blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9f4b0fd603bdfd61b7aa86a090dddca2c6ab040a | 292a513550f7c761f76453c7de760ea44e3b78bc | /src/particle_filter.h | e9fbe2a8f22c02a38a84df82651a8d1fff86cfad | [] | no_license | wfs/sdc-term2-p3-kidnapped-vehicle | a34befb7ef72999569be69a75e9586952255e95d | 1016f1b6dde66d676e8402590f007cdb0f6b3b7c | refs/heads/master | 2021-01-20T13:38:51.906152 | 2017-06-04T10:35:25 | 2017-06-04T10:35:25 | 90,510,163 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,799 | h | /*
* particle_filter.h
*
* 2D particle filter class.
* Created on: Dec 12, 2016
* Author: Tiffany Huang
*/
#ifndef PARTICLE_FILTER_H_
#define PARTICLE_FILTER_H_
#include "helper_functions.h"
struct Particle {
int id;
double x;
double y;
double theta;
double weight;
std::vector<int> associations;
std::vector<double> sense_x;
std::vector<double> sense_y;
};
class ParticleFilter {
// Number of particles to draw
int num_particles;
// Flag, if filter is initialized
bool is_initialized;
// Vector of weights of all particles
std::vector<double> weights;
public:
// Set of current particles
std::vector<Particle> particles;
// Constructor
// @param M Number of particles
ParticleFilter() : num_particles(0), is_initialized(false) {}
// Destructor
~ParticleFilter() {}
/**
* init Initializes particle filter by initializing particles to Gaussian
* distribution around first position and all the weights to 1.
* @param x Initial x position [m] (simulated estimate from GPS)
* @param y Initial y position [m]
* @param theta Initial orientation [rad]
* @param std[] Array of dimension 3 [standard deviation of x [m], standard deviation of y [m]
* standard deviation of yaw [rad]]
*/
void init(double x, double y, double theta, double std[]);
/**
* prediction Predicts the state for the next time step
* using the process model.
* @param delta_t Time between time step t and t+1 in measurements [s]
* @param std_pos[] Array of dimension 3 [standard deviation of x [m], standard deviation of y [m]
* standard deviation of yaw [rad]]
* @param velocity Velocity of car from t to t+1 [m/s]
* @param yaw_rate Yaw rate of car from t to t+1 [rad/s]
*/
void prediction(double delta_t, double std_pos[], double velocity, double yaw_rate);
/**
* dataAssociation Finds which observations correspond to which landmarks (likely by using
* a nearest-neighbors data association).
* @param predicted Vector of predicted landmark observations
* @param observations Vector of landmark observations
*/
void dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs> &observations);
/**
* updateWeights Updates the weights for each particle based on the likelihood of the
* observed measurements.
* @param sensor_range Range [m] of sensor
* @param std_landmark[] Array of dimension 2 [standard deviation of range [m],
* standard deviation of bearing [rad]]
* @param observations Vector of landmark observations
* @param map Map class containing map landmarks
*/
void updateWeights(double sensor_range, double std_landmark[], std::vector<LandmarkObs> observations,
Map map_landmarks);
/**
* resample Resamples from the updated set of particles to form
* the new set of particles.
*/
void resample();
/*
* Set a particles list of associations, along with the associations calculated world x,y coordinates
* This can be a very useful debugging tool to make sure transformations are correct and assocations correctly connected
*/
Particle SetAssociations(Particle particle, std::vector<int> associations, std::vector<double> sense_x,
std::vector<double> sense_y);
std::string getAssociations(Particle best);
std::string getSenseX(Particle best);
std::string getSenseY(Particle best);
/**
* initialized Returns whether particle filter is initialized yet or not.
*/
const bool initialized() const {
return is_initialized;
}
};
#endif /* PARTICLE_FILTER_H_ */
| [
"hullpod.central@gmail.com"
] | hullpod.central@gmail.com |
dccb060623c7e08adfc30364ba0459882b517f9a | 80f2fa4f1f4d56eef9471174f80b62838db9fc3b | /xdl/ps-plus/ps-plus/client/partitioner/merged_broadcast.h | 33ce832c8ec13a2a3e1caa327b044a5d3c68be61 | [
"Apache-2.0"
] | permissive | laozhuang727/x-deeplearning | a54f2fef1794274cbcd6fc55680ea19760d38f8a | 781545783a4e2bbbda48fc64318fb2c6d8bbb3cc | refs/heads/master | 2020-05-09T17:06:00.495080 | 2019-08-15T01:45:40 | 2019-08-15T01:45:40 | 181,295,053 | 1 | 0 | Apache-2.0 | 2019-08-15T01:45:41 | 2019-04-14T10:51:53 | PureBasic | UTF-8 | C++ | false | false | 1,061 | h | /* Copyright (C) 2016-2018 Alibaba Group Holding Limited
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 PS_PLUS_CLIENT_PARTITIONER_MERGED_BROADCAST_H_
#define PS_PLUS_CLIENT_PARTITIONER_MERGED_BROADCAST_H_
#include "ps-plus/client/merged_partitioner.h"
namespace ps {
namespace client {
namespace partitioner {
class MergedBroadcast : public MergedPartitioner {
public:
virtual Status Split(MergedPartitionerContext* ctx, Data* src, std::vector<Data*>* dst) override;
};
}
}
}
#endif
| [
"yue.song@alibaba-inc.com"
] | yue.song@alibaba-inc.com |
60fa836114a5362349571f6ec3d6f8120ffcfae6 | a6f5d608a22fb2e904c8e438d23694599d4cd8e1 | /apps-src/apps/librose/gui/widgets/tree_node.hpp | 962f278efcc1e38908e6ed0e0d8ce1d4072c55f4 | [
"BSD-2-Clause"
] | permissive | absir/Rose | ec18ad5c5a8c9d24cb4af281fbd00a2efa7285fa | 23a9f4307a27a3d4f2aceac30853d0ee69bc0f41 | refs/heads/main | 2023-02-24T20:00:47.442495 | 2021-01-31T08:03:05 | 2021-01-31T08:35:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,052 | hpp | /* $Id: tree_view_node.hpp 54007 2012-04-28 19:16:10Z mordante $ */
/*
Copyright (C) 2010 - 2012 by Mark de Wever <koraq@xs4all.nl>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
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.
See the COPYING file for more details.
*/
#ifndef GUI_WIDGETS_TREE_NODE_HPP_INCLUDED
#define GUI_WIDGETS_TREE_NODE_HPP_INCLUDED
#include "gui/auxiliary/window_builder/tree.hpp"
#include "gui/widgets/toggle_panel.hpp"
#include <boost/ptr_container/ptr_vector.hpp>
namespace gui2 {
class ttoggle_button;
class ttree;
class ttree_node: public ttoggle_panel
{
friend class ttree;
public:
typedef implementation::tbuilder_tree::tnode tnode_definition;
explicit ttree_node(const std::string& id
, const std::vector<tnode_definition>& node_definitions
, ttree_node* parent_node
, ttree& parent_tree_view
, const std::map<std::string, std::string>& data
, bool branch);
~ttree_node();
/**
* Adds a child item to the list of child nodes.
*
* @param id The id of the node definition to use for the
* new node.
* @param data The data to send to the set_members of the
* widgets. If the member id is not an empty
* string it is only send to the widget that has
* the wanted id (if any). If the member id is an
* empty string, it is send to all members.
* Having both empty and non-empty id's gives
* undefined behaviour.
* @param index The item before which to add the new item,
* 0 == begin, -1 == end.
*/
ttree_node& insert_node(const std::string& id, const std::map<std::string, std::string>& data, int at = nposm, const bool branch = false);
/**
* Removes all child items from the widget.
*/
void erase_children();
/**
* Is this node the root node?
*
* When the parent tree view is created it adds one special node, the root
* node. This node has no parent node and some other special features so
* several code paths need to check whether they are the parent node.
*/
bool is_root_node() const { return parent_node_ == NULL; }
/**
* The indention level of the node.
*
* The root node starts at level 0.
*/
unsigned get_indention_level() const;
/** Does the node have children? */
bool empty() const { return children_.empty(); }
size_t size() const { return children_.size(); }
ttree_node& child(int at) const;
/** Is the node folded? */
bool is_folded() const;
void set_widget_visible(const std::string& id, const bool visible);
void set_widget_label(const std::string& id, const std::string& label);
class tsort_func
{
public:
tsort_func(const boost::function<bool (const ttree_node&, const ttree_node&)>& did_compare)
: did_compare_(did_compare)
{}
bool operator()(ttree_node* a, ttree_node* b) const
{
return did_compare_(*a, *b);
}
private:
const boost::function<bool (const ttree_node&, const ttree_node&)>& did_compare_;
};
void sort_children(const boost::function<bool (const ttree_node&, const ttree_node&)>& did_compare);
void fold();
void unfold();
void fold_children();
void unfold_children();
bool is_child2(const ttree_node& target) const;
/**
* Returns the parent node.
*
* @pre is_root_node() == false.
*/
ttree_node& parent_node()
{
VALIDATE(parent_node_, null_str);
return *parent_node_;
}
const ttree_node& parent_node() const
{
VALIDATE(parent_node_, null_str);
return *parent_node_;
}
ttree& tree() { return tree_; }
const ttree& tree() const { return tree_; }
ttoggle_button* icon() const { return icon_; }
/** Inherited from twidget.*/
void dirty_under_rect(const SDL_Rect& clip) override;
twidget* find_at(const tpoint& coordinate, const bool must_be_active) override;
twidget* find(const std::string& id, const bool must_be_active) override;
const twidget* find(const std::string& id, const bool must_be_active) const override;
private:
void child_populate_dirty_list(twindow& caller, const std::vector<twidget*>& call_stack) override;
tpoint calculate_best_size() const override;
bool disable_click_dismiss() const override { return true; }
tpoint calculate_best_size(const int indention_level, const unsigned indention_step_size) const;
tpoint calculate_best_size_left_align(const int indention_level
, const unsigned indention_step_size) const;
void set_origin(const tpoint& origin) override;
void place(const tpoint& origin, const tpoint& size) override;
unsigned place_left_align(
const unsigned indention_step_size
, tpoint origin
, unsigned width);
void set_visible_area(const SDL_Rect& area) override;
void impl_draw_children(texture& frame_buffer, int x_offset, int y_offset) override;
void clear_texture() override;
void validate_children_continuous(int& next_shown_at, int& next_distance, const bool parent_has_folded) const;
void did_icon_state_changed(ttoggle_button& widget);
void post_fold_changed(const bool folded);
const ttree_node& gc_serie_first_shown() const;
ttree_node& gc_serie_first_shown();
// attention: before call is_front, this must not equal that.
bool is_front(const ttree_node& that) const;
ttree_node* gc_terminal_node(const int at) const;
void calculate_gc_insert_cache_vsize(const bool only_children, const bool must_include_children);
bool gc_is_shown() const;
private:
/**
* Our parent node.
*
* All nodes except the root node have a parent node.
*/
ttree_node* parent_node_;
/** The tree view that owns us. */
ttree& tree_;
/**
* Our children.
*
* We want the returned child nodes to remain stable so store pointers.
*/
std::vector<ttree_node*> children_;
/**
* The node definitions known to use.
*
* This list is needed to create new nodes.
*
* @todo Maybe store this list in the tree_view to avoid copying the
* reference.
*/
const std::vector<tnode_definition>& node_definitions_;
/** The icon to show the folded state. */
ttoggle_button* icon_;
bool branch_;
void signal_handler_mouse_enter(const event::tevent event, bool& handled) override;
void signal_handler_mouse_leave(const event::tevent event, bool& handled) override;
void signal_handler_left_button_click(const event::tevent event, bool& handled, bool& halt) override;
void signal_handler_left_button_double_click(const event::tevent event, bool& handled, bool& halt) override;
void signal_handler_right_button_up(bool& handled, bool& halt, const tpoint& coordinate) override;
};
} // namespace gui2
#endif
| [
"service@leagor.com"
] | service@leagor.com |
c85d206675c97df69179c68a6c2cc556812a395a | 1ea801dd4704e160c75bac3bc88b8df9c2f36368 | /translator/tests/pattern/vpxor/vpxor001.cpp | c6cbb26774e338385ca7aa6a48ad4a80827e4fbd | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | fcccode/xbyak_translator_aarch64 | e37e02038c9737564bff0319f7e1f514390c1452 | 11e976d859e519d94a62acb245902e57ba4f39c8 | refs/heads/main | 2023-04-22T02:12:28.889408 | 2021-05-14T11:16:17 | 2021-05-14T11:16:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,698 | cpp | /*******************************************************************************
* Copyright 2020 FUJITSU LIMITED
*
* 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 "test_generator2.h"
class TestPtnGenerator : public TestGenerator {
public:
void setInitialRegValue() {
/* Here modify arrays of inputGenReg, inputPredReg, inputZReg */
setInputZregAllRandomHex();
#if 0
for (int i = 0; i < 8; i++) {
inputZReg[0].ud_dt[i] = ~uint64_t(0);
inputZReg[3].ud_dt[i] = ~uint64_t(0);
inputZReg[6].ud_dt[i] = ~uint64_t(0);
}
for (int i = 0; i < 8; i++) {
inputZReg[1].ud_dt[i] = uint32_t(0xFF00FF00AA55AA55);
inputZReg[4].ud_dt[i] = uint32_t(0xFF00FF00AA55AA55);
inputZReg[7].ud_dt[i] = uint32_t(0xFF00FF00AA55AA55);
}
#endif
}
void setCheckRegFlagAll() {
/* Here modify arrays of checkGenRegMode, checkPredRegMode, checkZRegMode */
}
void genJitTestCode() {
/* Here write JIT code with x86_64 mnemonic function to be tested. */
vpxor(Ymm(0), Ymm(1), Ymm(2));
vpxor(Ymm(3), Ymm(3), Ymm(4));
vpxor(Ymm(5), Ymm(6), Ymm(5));
vpxor(Ymm(7), Ymm(8), Ymm(8));
vpxor(Ymm(9), Ymm(9), Ymm(9));
}
};
int main(int argc, char *argv[]) {
/* Initializing arrays of inputData, inputGenReg, inputPredReg, inputZReg,
* checkGenRegMode, checkPredRegMode,checkZRegMode */
TestPtnGenerator gen;
/* Set bool output_jit_on_, bool exec_jit_on_ = 0; */
gen.parseArgs(argc, argv);
/* Generate JIT code and get function pointer */
void (*f)();
if (gen.isOutputJitOn()) {
f = (void (*)())gen.gen();
}
/* Dump generated JIT code to a binary file */
gen.dumpJitCode();
/* 1:Execute JIT code, 2:dump all register values, 3:dump register values to
* be checked */
if (gen.isExecJitOn()) {
/* Before executing JIT code, dump inputData, inputGenReg, inputPredReg,
* inputZReg. */
gen.dumpInputReg();
f(); /* Execute JIT code */
gen.dumpOutputReg(); /* Dump all register values */
gen.dumpCheckReg(); /* Dump register values to be checked */
}
return 0;
}
| [
"kawakami.k@fujitsu.com"
] | kawakami.k@fujitsu.com |
06c38f76e729f3e0558b384d99c9e00bd8e804fa | 74eea6dc0c143961baf233b5ad85763e7d15c9c1 | /P190521/P190521/ptr01.cpp | ea6cc2119c110dcdf978244191d3254d72cf07bf | [] | no_license | devSOWON0628/Cplus2019 | c9101cee2ed552dbd8d9579c912c40d79e83624b | 2777d9bc65121125fe7380be77caffecd2925c48 | refs/heads/master | 2022-03-24T11:50:50.726328 | 2019-12-21T23:15:32 | 2019-12-21T23:15:32 | 180,942,078 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 626 | cpp | #include <iostream>
using namespace std;
class cat {
private:
int age;
const char * name;
public :
cat() {
age = 18;
name = "야옹이";
}
~cat() {}
int getAge() { return age; }
void setAge(int age) { this->age = age; }
char * getName() { return (char*)name; }
void setName(const char *name) { this->name = name; }
};
int main() {
cat* pcat = new cat;
cout << "고양이의 나이" << pcat->getAge() << "고양이 이름" << pcat->getName << endl;
pcat->setAge(20);
pcat->setName("방울이");
cout << "고양이의 나이" << pcat->getAge() << "고양이 이름" << pcat->getName << endl;
return 0;
} | [
"s2018s29@e-mirim.hs.kr"
] | s2018s29@e-mirim.hs.kr |
dc5a841936669c7dabac5d93a9cc79268975cdd0 | e6b668c5afc2a333a836bd8dc1dce6e04a5ef328 | /contest/1-7-2015/d.cpp | 359b374e73d41d6ae8233eca78d4a6ed4f518fdd | [] | no_license | mahim007/Online-Judge | 13b48cfe8fe1e8a723ea8e9e2ad40efec266e7ee | f703fe624035a86d7c6433c9111a3e3ee3e43a77 | refs/heads/master | 2020-03-11T21:02:04.724870 | 2018-04-20T11:28:42 | 2018-04-20T11:28:42 | 130,253,727 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 206 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long int
int main(){
ll n,b,a;
while(scanf("%lld %lld %lld",&n,&a,&b)==3){
printf("%lld\n",(ll)(2*n*a*b));
}
return 0;
}
| [
"ashrafulmahim@gmail.com"
] | ashrafulmahim@gmail.com |
09aea8d5e5e0cad9bec650c68ea98b93948f1816 | 7a615a4818cbad72fe6bc21d169200c8982d0cd1 | /src/libcode/vx_summary/summary_calc_sum.h | daec131260af92e9a48517f24efd301a21932ef4 | [
"Apache-2.0"
] | permissive | dtcenter/MET | 860f42331d22f6b616320bb4629aaecc8ac8db67 | 3f0411b65cef5719bf11b6fb75f7e8413fe633f0 | refs/heads/main_v11.1 | 2023-08-02T00:38:11.726674 | 2023-08-01T22:36:19 | 2023-08-01T22:36:19 | 184,336,905 | 46 | 21 | Apache-2.0 | 2023-09-14T18:50:21 | 2019-04-30T21:56:39 | C++ | UTF-8 | C++ | false | false | 1,166 | h | // *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
// ** Copyright UCAR (c) 1992 - 2023
// ** University Corporation for Atmospheric Research (UCAR)
// ** National Center for Atmospheric Research (NCAR)
// ** Research Applications Lab (RAL)
// ** P.O.Box 3000, Boulder, Colorado, 80307-3000, USA
// *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
////////////////////////////////////////////////////////////////////////
#ifndef __SUMMARYCALCSUM_H__
#define __SUMMARYCALCSUM_H__
////////////////////////////////////////////////////////////////////////
#include <iostream>
#include "summary_calc.h"
////////////////////////////////////////////////////////////////////////
class SummaryCalcSum : public SummaryCalc
{
public:
SummaryCalcSum();
virtual ~SummaryCalcSum();
virtual string getType() const
{
return "SUM";
}
virtual double calcSummary(const NumArray &num_array) const
{
return num_array.sum();
}
};
////////////////////////////////////////////////////////////////////////
#endif /* __SUMMARYCALCSUM_H__ */
////////////////////////////////////////////////////////////////////////
| [
"noreply@github.com"
] | dtcenter.noreply@github.com |
4017a3ab1c4c44f956c6ef8ff6fd05680857858c | d72b740992ce1876a504cbc0ee03de1ae667efcf | /samples/threat_level/src/PostRadial.inl | d05e7dc87371b2cd41413c07900b91f20a1593c1 | [
"Zlib"
] | permissive | fallahn/crogine | a5ba6d4c1a1ff6209d5a485f6033915a3a02bd03 | 9bf497fe599fe9aa24cf5eac301d209b5b065f6f | refs/heads/master | 2023-08-04T06:32:47.847808 | 2023-06-05T08:44:59 | 2023-06-05T08:44:59 | 101,754,475 | 62 | 9 | null | 2023-08-05T09:52:00 | 2017-08-29T11:38:17 | C++ | UTF-8 | C++ | false | false | 2,744 | inl | /*-----------------------------------------------------------------------
Matt Marchant 2017
http://trederia.blogspot.com
crogine test application - Zlib license.
This software is provided 'as-is', without any express or
implied warranty.In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions :
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
-----------------------------------------------------------------------*/
const std::string extractionFrag = R"(
uniform sampler2D u_texture;
VARYING_IN MED vec2 v_texCoord;
OUTPUT
const MED float threshold = 0.8;
const MED float factor = 4.0;
void main()
{
LOW vec4 colour = TEXTURE(u_texture, v_texCoord);
LOW float luminance = colour.r * 0.2126 + colour.b * 0.7152 + colour.g * 0.0722;
colour *= clamp(luminance - threshold, 0.0, 1.0) * factor;
FRAG_OUT = colour;
}
)";
//radial blur shader used in the radial blur post process
//https://www.shadertoy.com/view/MdG3RD
const std::string blueDream = R"(
#define SAMPLES 10
uniform sampler2D u_texture;
uniform sampler2D u_baseTexture;
VARYING_IN MED vec2 v_texCoord;
OUTPUT
const MED float decay = 0.96815;
const MED float exposure = 0.21;
const MED float density = 0.926;
const MED float weight = 0.58767;
void main()
{
MED vec2 deltaTexCoord = v_texCoord + vec2(-0.5);
deltaTexCoord *= 1.0 / float(SAMPLES) * density;
MED vec2 texCoord = v_texCoord;
LOW float illuminationDecay = 1.0;
LOW vec4 colour = TEXTURE(u_texture, texCoord) * 0.305104;
texCoord += deltaTexCoord * fract(sin(dot(v_texCoord, vec2(12.9898, 78.233))) * 43758.5453);
for(int i = 0; i < SAMPLES; ++i)
{
texCoord -= deltaTexCoord;
LOW vec4 deltaColour = TEXTURE(u_texture, texCoord) * 0.305104;
deltaColour *- illuminationDecay * weight;
colour += deltaColour;
illuminationDecay *= decay;
}
FRAG_OUT = (colour * exposure) + TEXTURE(u_baseTexture, v_texCoord);
}
)"; | [
"matty_styles@hotmail.com"
] | matty_styles@hotmail.com |
dfb7b8dde711b5a2a3649344d1e05d8b34ef5959 | 238eb3b8319f9f2de6b9ac16f1d885c4367c7832 | /p1089.cpp | f8dc8b07aa3fa8379980978e60d55ba2ca95ebd2 | [] | no_license | xjs-js/luogu | fac59d9dcdec3088cf66420d3c3867d1ee0cfc4a | f3dd66ebe60427fa25e564669152f9ac93d4fcf1 | refs/heads/master | 2020-05-18T01:07:33.068356 | 2019-05-08T14:37:18 | 2019-05-08T14:37:18 | 184,081,445 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 756 | cpp | // https://www.luogu.org/problemnew/show/P1089
// p1089.cpp
// luogu
//
// Created by js on 4/30/19.
// Copyright © 2019 js. All rights reserved.
//
#include <iostream>
using namespace std;
int main(int argc, const char *argv[])
{
// 读取12个输入
int own = 0, mom = 0;
for (int i = 1; i <= 12; ++i) {
int expense;
cin >> expense;
own = own + 300 - expense;
if (own < 0) {
cout << "-" << i << endl;
return 0;
} else {
if (own >= 100) {
mom += (own / 100) * 100;
own -= (own / 100) * 100;
}
}
}
double final_money = own + mom * 1.2;
cout << final_money << endl;
return 0;
}
| [
"xjs.js@outlook.com"
] | xjs.js@outlook.com |
b2adfb3e9e693d444bd66aeedfd05e28ad8fe792 | a43982de34f143432be37406e8cc1c03ed60880b | /Integer Data Swapper.cpp | f6ba408842a513dffd09ff662d1e24ea274a4e17 | [] | no_license | ShristDas/C- | 9675099096958c53e45f72cad1f4cf094077a22b | 6eb700da004ea15f4ea523bd7ee5b323161a95b3 | refs/heads/master | 2020-08-18T23:13:20.032940 | 2019-10-17T11:58:59 | 2019-10-17T11:58:59 | 215,846,191 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 949 | cpp | /*WAP to swap two integer data of different class using
friend function.*/
#include <iostream>
using namespace std;
class B;
class A
{
int x;
public:
A(int p)
{
x = p;
}
friend void swap(A *i, B *j);
void display()
{
cout << x;
}
};
class B
{
int y;
public:
B(int q)
{
y = q;
}
friend void swap(A *i, B *j);
void display()
{
cout << y;
}
};
void swap(A *i, B *j)
{
i->x = i->x + j->y;
j->y = i->x - j->y;
i->x = i->x - j->y;
}
int main()
{
int m, n;
cout << "Enter the value of the first integer- ";
cin >> m;
cout << "Enter the value of the second integer- ";
cin >> n;
A a(m);
B b(n);
cout << "\nThe initial values of the entered integers are:-";
cout << "\nx = "<<m;
cout << "\ny = "<<n;
swap(&a, &b);
cout << "\n\nThe final values of the integers after swapping are:-";
cout << "\nx = ";
a.display();
cout << "\ny = ";
b.display();
cout << endl;
return 0;
}
| [
"shristdas@gmail.com"
] | shristdas@gmail.com |
24d7ebd1178b23828b5fe6a7ff66e6df5981f6ff | 8b381f74097b486c85b86ce078bc5f69b72e8893 | /include/yangutil/buffer/YangAudioEncoderBuffer.h | f28846c80e858e8b564c491a664058a02af68c3b | [
"MIT"
] | permissive | docterling/yangrtc | e34e89e173bacf59018dffe69105c248c406e045 | e5dbb40aab826be3f2068c3b86bd54c4e3f0816b | refs/heads/main | 2023-07-15T11:19:46.635708 | 2021-09-04T12:14:23 | 2021-09-04T12:14:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 670 | h | #ifndef YangAudioEncoderBuffer_H
#define YangAudioEncoderBuffer_H
#include <yangutil/buffer/YangMediaBuffer.h>
struct YangAudioEBufferHeader {
int32_t length;
int32_t palyId;
};
class YangAudioEncoderBuffer: public YangMediaBuffer {
public:
YangAudioEncoderBuffer(int32_t paudioCacheNum);
~YangAudioEncoderBuffer(void);
void reset();
void putAudio(YangAudioFrame* audioFrame);
void getAudio(YangAudioFrame* audioFrame);
uint8_t* getAudioRef(int32_t *bufLen);
void putPlayAudio(YangAudioFrame* pframe);
void getPlayAudio(YangAudioFrame* audioFrame);
private:
int32_t m_headerLen, m_tid;
YangAudioEBufferHeader *m_in, *m_out;
void initHeader();
};
#endif
| [
"yangrtc@aliyun.com"
] | yangrtc@aliyun.com |
8458f9f0d1df8317fa53c0cf296ca8b05cbd845a | 2d361696ad060b82065ee116685aa4bb93d0b701 | /include/serial/objhook.hpp | 4468bae4442568f1524ea26f9fa054d412ba8c96 | [
"LicenseRef-scancode-public-domain"
] | permissive | AaronNGray/GenomeWorkbench | 5151714257ce73bdfb57aec47ea3c02f941602e0 | 7156b83ec589e0de8f7b0a85699d2a657f3e1c47 | refs/heads/master | 2022-11-16T12:45:40.377330 | 2020-07-10T00:54:19 | 2020-07-10T00:54:19 | 278,501,064 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 21,865 | hpp | #ifndef OBJHOOK__HPP
#define OBJHOOK__HPP
/* $Id: objhook.hpp 546693 2017-09-20 17:04:38Z gouriano $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Eugene Vasilchenko
*
* File Description:
* Read and write hooks
*/
#include <util/util_exception.hpp>
#include <serial/serialdef.hpp>
#include <serial/impl/objecttype.hpp>
#include <serial/impl/objstack.hpp>
#include <serial/objectiter.hpp>
/** @addtogroup ObjStreamSupport
*
* @{
*/
BEGIN_NCBI_SCOPE
class CObjectIStream;
class CObjectOStream;
class CObjectStreamCopier;
class CObjectInfo;
class CConstObjectInfo;
class CObjectTypeInfo;
/// Read hook for a standalone object
class NCBI_XSERIAL_EXPORT CReadObjectHook : public CObject
{
public:
virtual ~CReadObjectHook(void);
/// This method will be called at approriate time
/// when the object of requested type is to be read
virtual void ReadObject(CObjectIStream& in,
const CObjectInfo& object) = 0;
// Default actions
/// Default read
void DefaultRead(CObjectIStream& in,
const CObjectInfo& object);
/// Default skip
void DefaultSkip(CObjectIStream& in,
const CObjectTypeInfo& object);
};
/// Read hook for data member of a containing object (eg, SEQUENCE)
class NCBI_XSERIAL_EXPORT CReadClassMemberHook : public CObject
{
public:
virtual ~CReadClassMemberHook(void);
/// This method will be called at approriate time
/// when the object of requested type is to be read
virtual void ReadClassMember(CObjectIStream& in,
const CObjectInfoMI& member) = 0;
virtual void ReadMissingClassMember(CObjectIStream& in,
const CObjectInfoMI& member);
void DefaultRead(CObjectIStream& in,
const CObjectInfoMI& object);
void DefaultSkip(CObjectIStream& in,
const CObjectTypeInfoMI& object);
void ResetMember(const CObjectInfoMI& object,
CObjectInfoMI::EEraseFlag flag =
CObjectInfoMI::eErase_Optional);
};
/// Read hook for data member of a containing object (eg, SEQUENCE)
class NCBI_XSERIAL_EXPORT CPreReadClassMemberHook
: public CReadClassMemberHook
{
public:
virtual ~CPreReadClassMemberHook(void);
/// This method will be called at approriate time
/// when the object of requested type is to be read
virtual void ReadClassMember(CObjectIStream& in,
const CObjectInfoMI& member) override;
/// Return true to invoke default reading method afterwards.
/// Return false if no firther reading needs to be done.
virtual void PreReadClassMember(CObjectIStream& in,
const CObjectInfoMI& member) = 0;
};
/// Read hook for a choice variant (CHOICE)
class NCBI_XSERIAL_EXPORT CReadChoiceVariantHook : public CObject
{
public:
virtual ~CReadChoiceVariantHook(void);
/// This method will be called at approriate time
/// when the object of requested type is to be read
virtual void ReadChoiceVariant(CObjectIStream& in,
const CObjectInfoCV& variant) = 0;
void DefaultRead(CObjectIStream& in,
const CObjectInfoCV& object);
void DefaultSkip(CObjectIStream& in,
const CObjectTypeInfoCV& object);
};
/// Read hook for a choice variant (CHOICE)
class NCBI_XSERIAL_EXPORT CPreReadChoiceVariantHook
: public CReadChoiceVariantHook
{
public:
virtual ~CPreReadChoiceVariantHook(void);
/// This method will be called at approriate time
/// when the object of requested type is to be read
virtual void ReadChoiceVariant(CObjectIStream& in,
const CObjectInfoCV& variant) override;
/// Return true to invoke default reading method afterwards.
/// Return false if no firther reading needs to be done.
virtual void PreReadChoiceVariant(CObjectIStream& in,
const CObjectInfoCV& object) = 0;
};
/// Read hook for a container element (SEQUENCE OF)
class NCBI_XSERIAL_EXPORT CReadContainerElementHook : public CObject
{
public:
virtual ~CReadContainerElementHook(void);
virtual void ReadContainerElement(CObjectIStream& in,
const CObjectInfo& container) = 0;
};
/// Write hook for a standalone object
class NCBI_XSERIAL_EXPORT CWriteObjectHook : public CObject
{
public:
virtual ~CWriteObjectHook(void);
/// This method will be called at approriate time
/// when the object of requested type is to be written
virtual void WriteObject(CObjectOStream& out,
const CConstObjectInfo& object) = 0;
void DefaultWrite(CObjectOStream& out,
const CConstObjectInfo& object);
};
/// Write hook for data member of a containing object (eg, SEQUENCE)
class NCBI_XSERIAL_EXPORT CWriteClassMemberHook : public CObject
{
public:
virtual ~CWriteClassMemberHook(void);
virtual void WriteClassMember(CObjectOStream& out,
const CConstObjectInfoMI& member) = 0;
void DefaultWrite(CObjectOStream& out,
const CConstObjectInfoMI& member);
void CustomWrite(CObjectOStream& out,
const CConstObjectInfoMI& member,
const CConstObjectInfo& custom_object);
};
/// Write hook for a choice variant (CHOICE)
class NCBI_XSERIAL_EXPORT CWriteChoiceVariantHook : public CObject
{
public:
virtual ~CWriteChoiceVariantHook(void);
virtual void WriteChoiceVariant(CObjectOStream& out,
const CConstObjectInfoCV& variant) = 0;
void DefaultWrite(CObjectOStream& out,
const CConstObjectInfoCV& variant);
void CustomWrite(CObjectOStream& out,
const CConstObjectInfoCV& variant,
const CConstObjectInfo& custom_object);
};
/// Skip hook for a standalone object
class NCBI_XSERIAL_EXPORT CSkipObjectHook : public CObject
{
public:
virtual ~CSkipObjectHook(void);
virtual void SkipObject(CObjectIStream& stream,
const CObjectTypeInfo& type) = 0;
// Default actions
/// Default read
void DefaultRead(CObjectIStream& in,
const CObjectInfo& object);
/// Default skip
void DefaultSkip(CObjectIStream& in,
const CObjectTypeInfo& type);
};
/// Skip hook for data member of a containing object (eg, SEQUENCE)
class NCBI_XSERIAL_EXPORT CSkipClassMemberHook : public CObject
{
public:
virtual ~CSkipClassMemberHook(void);
virtual void SkipClassMember(CObjectIStream& stream,
const CObjectTypeInfoMI& member) = 0;
virtual void SkipMissingClassMember(CObjectIStream& stream,
const CObjectTypeInfoMI& member);
void DefaultRead(CObjectIStream& in,
const CObjectInfo& object);
void DefaultSkip(CObjectIStream& stream,
const CObjectTypeInfoMI& member);
};
/// Skip hook for a choice variant (CHOICE)
class NCBI_XSERIAL_EXPORT CSkipChoiceVariantHook : public CObject
{
public:
virtual ~CSkipChoiceVariantHook(void);
virtual void SkipChoiceVariant(CObjectIStream& stream,
const CObjectTypeInfoCV& variant) = 0;
void DefaultRead(CObjectIStream& in,
const CObjectInfo& object);
void DefaultSkip(CObjectIStream& stream,
const CObjectTypeInfoCV& variant);
};
/// Copy hook for a standalone object
class NCBI_XSERIAL_EXPORT CCopyObjectHook : public CObject
{
public:
virtual ~CCopyObjectHook(void);
virtual void CopyObject(CObjectStreamCopier& copier,
const CObjectTypeInfo& type) = 0;
void DefaultCopy(CObjectStreamCopier& copier,
const CObjectTypeInfo& type);
};
/// Copy hook for data member of a containing object (eg, SEQUENCE)
class NCBI_XSERIAL_EXPORT CCopyClassMemberHook : public CObject
{
public:
virtual ~CCopyClassMemberHook(void);
virtual void CopyClassMember(CObjectStreamCopier& copier,
const CObjectTypeInfoMI& member) = 0;
virtual void CopyMissingClassMember(CObjectStreamCopier& copier,
const CObjectTypeInfoMI& member);
void DefaultCopy(CObjectStreamCopier& copier,
const CObjectTypeInfoMI& member);
};
/// Copy hook for a choice variant (CHOICE)
class NCBI_XSERIAL_EXPORT CCopyChoiceVariantHook : public CObject
{
public:
virtual ~CCopyChoiceVariantHook(void);
virtual void CopyChoiceVariant(CObjectStreamCopier& copier,
const CObjectTypeInfoCV& variant) = 0;
void DefaultCopy(CObjectStreamCopier& copier,
const CObjectTypeInfoCV& variant);
};
enum EDefaultHookAction {
eDefault_Normal, // read or write data
eDefault_Skip // skip data
};
class NCBI_XSERIAL_EXPORT CObjectHookGuardBase
{
protected:
// object read hook
CObjectHookGuardBase(const CObjectTypeInfo& info,
CReadObjectHook& hook,
CObjectIStream* stream = 0);
// object write hook
CObjectHookGuardBase(const CObjectTypeInfo& info,
CWriteObjectHook& hook,
CObjectOStream* stream = 0);
// object skip hook
CObjectHookGuardBase(const CObjectTypeInfo& info,
CSkipObjectHook& hook,
CObjectIStream* stream = 0);
// object copy hook
CObjectHookGuardBase(const CObjectTypeInfo& info,
CCopyObjectHook& hook,
CObjectStreamCopier* stream = 0);
// member read hook
CObjectHookGuardBase(const CObjectTypeInfo& info,
const string& id,
CReadClassMemberHook& hook,
CObjectIStream* stream = 0);
// member write hook
CObjectHookGuardBase(const CObjectTypeInfo& info,
const string& id,
CWriteClassMemberHook& hook,
CObjectOStream* stream = 0);
// member skip hook
CObjectHookGuardBase(const CObjectTypeInfo& info,
const string& id,
CSkipClassMemberHook& hook,
CObjectIStream* stream = 0);
// member copy hook
CObjectHookGuardBase(const CObjectTypeInfo& info,
const string& id,
CCopyClassMemberHook& hook,
CObjectStreamCopier* stream = 0);
// choice variant read hook
CObjectHookGuardBase(const CObjectTypeInfo& info,
const string& id,
CReadChoiceVariantHook& hook,
CObjectIStream* stream = 0);
// choice variant write hook
CObjectHookGuardBase(const CObjectTypeInfo& info,
const string& id,
CWriteChoiceVariantHook& hook,
CObjectOStream* stream = 0);
// choice variant skip hook
CObjectHookGuardBase(const CObjectTypeInfo& info,
const string& id,
CSkipChoiceVariantHook& hook,
CObjectIStream* stream = 0);
// choice variant copy hook
CObjectHookGuardBase(const CObjectTypeInfo& info,
const string& id,
CCopyChoiceVariantHook& hook,
CObjectStreamCopier* stream = 0);
~CObjectHookGuardBase(void);
void ResetHook(const CObjectTypeInfo& info);
private:
CObjectHookGuardBase(const CObjectHookGuardBase&);
const CObjectHookGuardBase& operator=(const CObjectHookGuardBase&);
enum EHookMode {
eHook_None,
eHook_Read,
eHook_Write,
eHook_Skip,
eHook_Copy
};
enum EHookType {
eHook_Null, // object hook
eHook_Object, // object hook
eHook_Member, // class member hook
eHook_Variant, // choice variant hook
eHook_Element // container element hook
};
union {
CObjectIStream* m_IStream;
CObjectOStream* m_OStream;
CObjectStreamCopier* m_Copier;
} m_Stream;
CRef<CObject> m_Hook;
EHookMode m_HookMode;
EHookType m_HookType;
string m_Id; // member or variant id
};
/// Helper class: installs hooks in constructor, and uninstalls in destructor
template <class T>
class CObjectHookGuard : public CObjectHookGuardBase
{
typedef CObjectHookGuardBase CParent;
public:
/// Install object read hook
///
/// @param hook
/// Hook object
/// @param stream
/// Data stream: if 0, the global hook is installed,
/// otherwise - local one
CObjectHookGuard(CReadObjectHook& hook,
CObjectIStream* stream = 0)
: CParent(CType<T>(), hook, stream)
{
}
/// Install object write hook
///
/// @param hook
/// Hook object
/// @param stream
/// Data stream: if 0, the global hook is installed,
/// otherwise - local one
CObjectHookGuard(CWriteObjectHook& hook,
CObjectOStream* stream = 0)
: CParent(CType<T>(), hook, stream)
{
}
/// Install object skip hook
///
/// @param hook
/// Hook object
/// @param stream
/// Data stream: if 0, the global hook is installed,
/// otherwise - local one
CObjectHookGuard(CSkipObjectHook& hook,
CObjectIStream* stream = 0)
: CParent(CType<T>(), hook, stream)
{
}
/// Install object copy hook
///
/// @param hook
/// Hook object
/// @param stream
/// Data stream: if 0, the global hook is installed,
/// otherwise - local one
CObjectHookGuard(CCopyObjectHook& hook,
CObjectStreamCopier* stream = 0)
: CParent(CType<T>(), hook, stream)
{
}
/// Install member read hook
///
/// @param id
/// Member id
/// @param hook
/// Hook object
/// @param stream
/// Data stream: if 0, the global hook is installed,
/// otherwise - local one
CObjectHookGuard(const string& id,
CReadClassMemberHook& hook,
CObjectIStream* stream = 0)
: CParent(CType<T>(), id, hook, stream)
{
}
/// Install member write hook
///
/// @param id
/// Member id
/// @param hook
/// Hook object
/// @param stream
/// Data stream: if 0, the global hook is installed,
/// otherwise - local one
CObjectHookGuard(const string& id,
CWriteClassMemberHook& hook,
CObjectOStream* stream = 0)
: CParent(CType<T>(), id, hook, stream)
{
}
/// Install member skip hook
///
/// @param id
/// Member id
/// @param hook
/// Hook object
/// @param stream
/// Data stream: if 0, the global hook is installed,
/// otherwise - local one
CObjectHookGuard(const string& id,
CSkipClassMemberHook& hook,
CObjectIStream* stream = 0)
: CParent(CType<T>(), id, hook, stream)
{
}
/// Install member copy hook
///
/// @param id
/// Member id
/// @param hook
/// Hook object
/// @param stream
/// Data stream: if 0, the global hook is installed,
/// otherwise - local one
CObjectHookGuard(const string& id,
CCopyClassMemberHook& hook,
CObjectStreamCopier* stream = 0)
: CParent(CType<T>(), id, hook, stream)
{
}
/// Install choice variant read hook
///
/// @param id
/// Variant id
/// @param hook
/// Hook object
/// @param stream
/// Data stream: if 0, the global hook is installed,
/// otherwise - local one
CObjectHookGuard(const string& id,
CReadChoiceVariantHook& hook,
CObjectIStream* stream = 0)
: CParent(CType<T>(), id, hook, stream)
{
}
/// Install choice variant write hook
///
/// @param id
/// Variant id
/// @param hook
/// Hook object
/// @param stream
/// Data stream: if 0, the global hook is installed,
/// otherwise - local one
CObjectHookGuard(const string& id,
CWriteChoiceVariantHook& hook,
CObjectOStream* stream = 0)
: CParent(CType<T>(), id, hook, stream)
{
}
/// Install choice variant skip hook
///
/// @param id
/// Variant id
/// @param hook
/// Hook object
/// @param stream
/// Data stream: if 0, the global hook is installed,
/// otherwise - local one
CObjectHookGuard(const string& id,
CSkipChoiceVariantHook& hook,
CObjectIStream* stream = 0)
: CParent(CType<T>(), id, hook, stream)
{
}
/// Install choice variant copy hook
///
/// @param id
/// Variant id
/// @param hook
/// Hook object
/// @param stream
/// Data stream: if 0, the global hook is installed,
/// otherwise - local one
CObjectHookGuard(const string& id,
CCopyChoiceVariantHook& hook,
CObjectStreamCopier* stream = 0)
: CParent(CType<T>(), id, hook, stream)
{
}
~CObjectHookGuard(void)
{
CParent::ResetHook(CType<T>());
}
};
/// Helper hook for Serial_FilterObjects function template;
/// User hook class should be derived from this base class
template<typename TObject>
class CSerial_FilterObjectsHook : public CSkipObjectHook
{
public:
virtual void SkipObject(CObjectIStream& in, const CObjectTypeInfo& type) override
{
if (type.GetTypeInfo()->IsCObject()) {
TObjectPtr objectPtr = type.GetTypeInfo()->Create(/*in.GetMemoryPool()*/);
CRef<CObject> ref;
ref.Reset(static_cast<CObject*>(objectPtr));
type.GetTypeInfo()->DefaultReadData(in, objectPtr);
Process(*static_cast<TObject*>(objectPtr));
} else {
TObject obj;
type.GetTypeInfo()->DefaultReadData(in, &obj);
Process(obj);
}
}
/// This method will be called when the object of the
/// requested class is read
virtual void Process(const TObject& obj) = 0;
};
template<typename TObject>
class CSerial_FilterReadObjectsHook : public CReadObjectHook
{
public:
CSerial_FilterReadObjectsHook<TObject>(
CSerial_FilterObjectsHook<TObject>* processor)
: m_processor(processor)
{
}
virtual void ReadObject(CObjectIStream& in,const CObjectInfo& object) override
{
DefaultRead(in,object);
TObject* obj = (TObject*)(object.GetObjectPtr());
m_processor->Process(*obj);
}
private:
CSerial_FilterObjectsHook<TObject>* m_processor;
};
NCBI_XSERIAL_EXPORT
bool Serial_FilterSkip(CObjectIStream& in, const CObjectTypeInfo& ctype);
/// Scan input stream, finding objects of requested type (TObject) only
template<typename TRoot, typename TObject>
void Serial_FilterObjects(CObjectIStream& in, CSerial_FilterObjectsHook<TObject>* hook,
bool readall=true)
{
CObjectTypeInfo root = CType<TRoot>();
CObjectTypeInfo request = CType<TObject>();
request.SetLocalSkipHook(in, hook);
request.SetLocalReadHook(in, new CSerial_FilterReadObjectsHook<TObject>(hook));
while (Serial_FilterSkip(in,root) && readall)
;
}
/// Scan input stream, finding objects that are not derived from CSerialObject
template<typename TRoot, typename TObject>
void Serial_FilterStdObjects(CObjectIStream& in, CSerial_FilterObjectsHook<TObject>* hook,
bool readall=true)
{
CObjectTypeInfo root = CType<TRoot>();
CObjectTypeInfo request = CStdTypeInfo<TObject>::GetTypeInfo();
request.SetLocalSkipHook(in, hook);
while (Serial_FilterSkip(in,root) && readall)
;
}
/* @} */
END_NCBI_SCOPE
#endif /* OBJHOOK__HPP */
| [
"aaronngray@gmail.com"
] | aaronngray@gmail.com |
6163e5c8394de9d569209b0748e11bb06edd281f | 0f6a4e78200d59fa066355c91266cd9d6bbed330 | /mcp.cpp | e50d465599687681f9453bd917013c4da9a02bbc | [] | no_license | crw-xiix/TempSensor | 6e403fe10ca0703bc6774e1b28785ad88e540465 | 7ed2dea6779f3a63b43b023a999d7a20e404c278 | refs/heads/master | 2020-06-25T12:14:28.602346 | 2019-07-28T15:58:54 | 2019-07-28T15:58:54 | 199,304,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,810 | cpp | /**************************************************************************/
/*!
@file Adafruit_MCP9808.cpp
@author K.Townsend (Adafruit Industries)
@license BSD (see license.txt)
I2C Driver for Microchip's MCP9808 I2C Temp sensor
This is a library for the Adafruit MCP9808 breakout
----> http://www.adafruit.com/products/1782
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
@section HISTORY
v1.0 - First release
*/
/**************************************************************************/
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
// #ifdef __AVR_ATtiny85__
// #include "TinyWireM.h"
// #define Wire TinyWireM
//#else
#include <Wire.h>
// #endif
#include "mcp.h"
/**************************************************************************/
/*!
@brief Instantiates a new MCP9808 class
*/
/**************************************************************************/
MCP9808::MCP9808() {
}
/*
Public methods for the MCP9808 class.
*/
void MCP9808::readSensor(void) {
temperature_C = readTemperature();
}
float MCP9808::getTemperature_C(void) {
return temperature_C;
}
float MCP9808::getTemperature_F(void) {
temperature_F = temperature_C * 1.8 + 32;
return temperature_F;
}
void MCP9808::sensorPowerUp(void) {
shutdown_wake(0);
}
void MCP9808::sensorPowerDown(void) {
shutdown_wake(1);
}
/**************************************************************************/
/*!
@brief Setups the HW
*/
/**************************************************************************/
boolean MCP9808::begin(uint8_t addr) {
_i2caddr = addr;
Wire.begin();
if (read16(MCP9808_REG_MANUF_ID) != 0x0054) return false;
if (read16(MCP9808_REG_DEVICE_ID) != 0x0400) return false;
return true;
}
/**************************************************************************/
/*!
@brief Reads the 16-bit temperature register and returns the Centigrade
temperature as a float.
*/
/**************************************************************************/
float MCP9808::readTemperature( void )
{
uint16_t t = read16(MCP9808_REG_AMBIENT_TEMP);
float temp = t & 0x0FFF;
temp /= 16.0;
if (t & 0x1000) temp -= 256;
return temp;
}
//*************************************************************************
// Set Sensor to Shutdown-State or wake up (Conf_Register BIT8)
// 1= shutdown / 0= wake up
//*************************************************************************
int MCP9808::shutdown_wake( uint8_t sw_ID )
{
uint16_t conf_shutdown ;
uint16_t conf_register = read16(MCP9808_REG_CONFIG);
if (sw_ID == 1)
{
conf_shutdown = conf_register | MCP9808_REG_CONFIG_SHUTDOWN ;
write16(MCP9808_REG_CONFIG, conf_shutdown);
}
if (sw_ID == 0)
{
conf_shutdown = conf_register ^ MCP9808_REG_CONFIG_SHUTDOWN ;
write16(MCP9808_REG_CONFIG, conf_shutdown);
}
return 0;
}
/**************************************************************************/
/*!
@brief Low level 16 bit read and write procedures!
*/
/**************************************************************************/
void MCP9808::write16(uint8_t reg, uint16_t value) {
Wire.beginTransmission(_i2caddr);
Wire.write((uint8_t)reg);
Wire.write(value >> 8);
Wire.write(value & 0xFF);
Wire.endTransmission();
}
uint16_t MCP9808::read16(uint8_t reg) {
uint16_t val;
Wire.beginTransmission(_i2caddr);
Wire.write((uint8_t)reg);
Wire.endTransmission();
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2);
val = Wire.read();
val <<= 8;
val |= Wire.read();
return val;
}
| [
"charles@loneaspen.com"
] | charles@loneaspen.com |
3220c14e79fe936b602df3c6785f587d057a217c | 27ce4a10ba6fdc0273e86e402c2d8b49d4deeb50 | /HomeAutomation-Services/homeautomationservices.cpp | 42d6ef238d45d5a337e97c14fd264751651d5b7f | [] | no_license | manuel-du-bois/HomeAutomationServer | b549bc4582a6bfe329adfa050787f53995a85015 | 8658b62b233862f59580f09cde5cbfa214e94b4d | refs/heads/master | 2020-04-03T02:37:41.809323 | 2018-10-27T12:13:59 | 2018-10-27T12:13:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 199 | cpp | #include "homeautomationservices.h"
HomeAutomationServices::HomeAutomationServices(QObject *parent) : QObject(parent)
{
}
QString HomeAutomationServices::getString()
{
return "Hallo Welt";
}
| [
"mandubo@gmx.de"
] | mandubo@gmx.de |
a8d25b18fdd05800f2516d3cab6b0e99471bbbfd | f12849f2dbacb9cafe0c7127eec3f87a05a91d34 | /include/Physics.h | 012d0e214fcc046937ba4128782d663f613b9144 | [] | no_license | dominik-dopka/simple-billiard-game | 96fc74d387e1b4ba542be541efa024d37472e667 | 277f4ada1f41cdcbc35225fde391223b9645fc2f | refs/heads/master | 2020-04-18T21:15:16.445262 | 2019-01-30T11:26:13 | 2019-01-30T11:26:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 637 | h | #pragma once
#include "Game.h"
class Physics {
public:
struct Circle {
int x, y;
int r;
};
Physics();
static double estimateAngle(SDL_Point point, Circle circle);
static double estimateAngle(double angle);
static double estimateBounceAngle(SDL_Rect rect, Circle circle);
static double estimateVelocity (double strengh, Uint32 lastTime);
static double estimateStrengh(double strengh, Uint32 lastTime);
static double destTransform_x(int destRect_x, double velocity, int angle);
static double destTransform_y(int destRect_y, double velocity, int angle);
private:
static double Angle(int x1, int y1, int x2, int y2);
}; | [
"galyn43@gmail.com"
] | galyn43@gmail.com |
844acecaabedb1cfb932ef4092a77bc2c2c99dab | 759d2256468303ed4426fc7fad8d3f1d21cdac21 | /6-ZigZag-Conversion/solution.cpp | 4c220b3b62da0090bb1ad52a81144a4ed574d693 | [] | no_license | xuchaoUCAS/leetcode | 880949fa6c4d28696b29c1f5b03d1ee5c8ec9c5e | 434d75c2690d8d27d2ba63512b96809ee5afe72d | refs/heads/master | 2021-03-24T12:05:16.617105 | 2016-09-29T09:19:34 | 2016-09-29T09:19:34 | 44,957,962 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 569 | cpp | class Solution {
public:
string convert(string s, int numRows) {
if(numRows <= 1)
return s;
int len = s.length();
int row = 0,direc = 1;
string *result = new string[numRows];
for(int i = 0;i < len;++i){
result[row].push_back(s[i]);
if(row == 0)
direc = 1;
if(row == numRows - 1)
direc = -1;
row += direc;
}
s = "";
for(int i = 0;i < numRows;++i)
s += result[i];
return s;
}
}; | [
"xuchao0813@gmail.com"
] | xuchao0813@gmail.com |
9fa83256c604bf24bb5a46471c32f2c6d10ea978 | 46577aa5c596ea3f99aa55ee239a848621d04723 | /src/KyloSpace.cpp | 2bc333b85917286460fe194ee2cdb79a31a3ee34 | [
"MIT"
] | permissive | venGaza/starwars | b8a48ad271f0551ba3d3b024207fab6e0a155869 | 37f1281375241125081177482bd6caff02f80535 | refs/heads/master | 2020-04-13T04:10:20.711099 | 2019-01-23T17:38:13 | 2019-01-23T17:38:13 | 162,953,316 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,348 | cpp | /*
* Class: KyloSpace
* -------------------------
* This is the implementation file for the KyloSpace class. This class is a subclass of the superclass
* Space object and is one of the types of spaces within the game. The player will traverse the various
* types of spaces to collect items and reach the final boss.
*/
#include "KyloSpace.hpp"
#include "SnokeSpace.hpp"
#include "LaunchBay.hpp"
/*
* Function: KyloSpace::KyloSpace()
* Usage: KyloSpace()
* -------------------------
* This is the default constructor for the KyloSpace class. This function sets default values for the
* Space object.
*/
KyloSpace::KyloSpace() {
Space::roomName = "Command Center";
Space::roomDescription= "The Command Center where all the nefarious bad guys tend to hang out. Oh look, Kylo Ren is here and he does not look happy to see you!";
Space::top = nullptr;
Space::bottom = new SnokeSpace;
Space::bottom->setTop(this);
Space::left = new LaunchBay;
Space::left->setRight(this);
Space::right = new SnokeSpace;
Space::right->setLeft(this);
}
/*
* Function: KyloSpace::KyloSpace(space*, space*, space*, space*)
* Usage: KyloSpace(space, space, space, space)
* -------------------------
* This is the overloaded constructor for the KyloSpace class. This function sets default values for the
* Space object.
*/
KyloSpace::KyloSpace(Space* top, Space* bottom, Space* left, Space* right) {
this->Space::top = top;
this->Space::bottom = bottom;
this->Space::left = left;
this->Space::right = right;
}
/*
* Function: KyloSpace::~KyloSpace()
* Usage: ~KyloSpace()
* -------------------------
* This is the default destructor for the KyloSpace class.
*/
KyloSpace::~KyloSpace() {
delete Space::getBottom();
delete Space::getLeft();
delete Space::getRight();
}
/****************************************************************************************************
* ABSTRACT PUBLIC FUNCTIONS *
***************************************************************************************************/
/*
* Function: KyloSpace::printChoices()
* Usage: obj.printChoices()
* -------------------------
* This is a public member function for the KyloSpace class. This function prints out the menu choices
* for this space. This is an abstract function inherited from Space class.
*/
void KyloSpace::printChoices() {
cout << "1) North - Startanium Door" << endl
<< "2) East - Mysterious Room" << endl
<< "3) West - Launch Bay" << endl
<< "4) Item Inventory " << endl
<< "5) Look around" << endl << endl;
}
/*
* Function: KyloSpace::getChoice()
* Usage: obj.getChoice()
* -------------------------
* This is a public member function for the KyloSpace class. This function gets a choice from
* the user. This is an abstract function inherited from Space class.
*/
string KyloSpace::getChoice() {
cout << "Please select a choice (enter integer): ";
int choice = getInteger();
validate(choice, 1, 5);
cout << endl;
if (choice == 1) {
return "north";
} else if (choice == 2) {
return "east";
} else if (choice == 3) {
return "west";
} else if (choice == 4) {
return "items";
} else {
return "look";
}
}
| [
"gazaven@gmail.com"
] | gazaven@gmail.com |
da5648169d19fdecf0dcc0e6cdc0579be3dea2f8 | 201c337ade624418a077514ca4db608b3d800886 | /chrome/browser/ui/ash/launcher/arc_app_launcher_browsertest.cc | 6eab68153319daa4163611b055364eeefe54c3a2 | [
"BSD-3-Clause"
] | permissive | huningxin/chromium-src | 78282bff41a04ab0e76298e82a5d097f0d9f9dd2 | e7b9a67db6608d4358141193994194705dc95b0d | refs/heads/webml | 2023-05-26T21:09:02.471210 | 2019-09-04T06:56:33 | 2019-09-26T01:48:14 | 217,235,865 | 0 | 1 | BSD-3-Clause | 2019-11-11T05:11:12 | 2019-10-24T07:16:04 | null | UTF-8 | C++ | false | false | 21,549 | cc | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <string>
#include <tuple>
#include "ash/public/cpp/shelf_item_delegate.h"
#include "ash/public/cpp/shelf_model.h"
#include "ash/shelf/shelf.h"
#include "ash/shelf/shelf_app_button.h"
#include "ash/shelf/shelf_view_test_api.h"
#include "ash/shell.h"
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/chromeos/arc/arc_service_launcher.h"
#include "chrome/browser/chromeos/arc/arc_session_manager.h"
#include "chrome/browser/chromeos/arc/arc_util.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/ui/app_list/app_list_client_impl.h"
#include "chrome/browser/ui/app_list/app_list_controller_delegate.h"
#include "chrome/browser/ui/app_list/app_list_syncable_service.h"
#include "chrome/browser/ui/app_list/app_list_syncable_service_factory.h"
#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h"
#include "chrome/browser/ui/app_list/arc/arc_app_utils.h"
#include "chrome/browser/ui/ash/launcher/arc_app_window_launcher_controller.h"
#include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h"
#include "chrome/browser/ui/ash/launcher/chrome_launcher_controller_test_util.h"
#include "chrome/browser/ui/ash/launcher/shelf_spinner_controller.h"
#include "components/arc/arc_service_manager.h"
#include "components/arc/arc_util.h"
#include "components/arc/metrics/arc_metrics_constants.h"
#include "components/arc/session/arc_bridge_service.h"
#include "components/arc/test/fake_app_instance.h"
#include "content/public/test/browser_test_utils.h"
#include "ui/display/types/display_constants.h"
#include "ui/events/event_constants.h"
#include "ui/events/test/event_generator.h"
#include "ui/views/animation/ink_drop.h"
namespace mojo {
template <>
struct TypeConverter<arc::mojom::AppInfoPtr, arc::mojom::AppInfo> {
static arc::mojom::AppInfoPtr Convert(const arc::mojom::AppInfo& app_info) {
return app_info.Clone();
}
};
template <>
struct TypeConverter<arc::mojom::ArcPackageInfoPtr,
arc::mojom::ArcPackageInfo> {
static arc::mojom::ArcPackageInfoPtr Convert(
const arc::mojom::ArcPackageInfo& package_info) {
return package_info.Clone();
}
};
template <>
struct TypeConverter<arc::mojom::ShortcutInfoPtr, arc::mojom::ShortcutInfo> {
static arc::mojom::ShortcutInfoPtr Convert(
const arc::mojom::ShortcutInfo& shortcut_info) {
return shortcut_info.Clone();
}
};
} // namespace mojo
namespace {
constexpr char kTestAppName[] = "Test ARC App";
constexpr char kTestAppName2[] = "Test ARC App 2";
constexpr char kTestShortcutName[] = "Test Shortcut";
constexpr char kTestShortcutName2[] = "Test Shortcut 2";
constexpr char kTestAppPackage[] = "test.arc.app.package";
constexpr char kTestAppActivity[] = "test.arc.app.package.activity";
constexpr char kTestAppActivity2[] = "test.arc.gitapp.package.activity2";
constexpr char kTestShelfGroup[] = "shelf_group";
constexpr char kTestShelfGroup2[] = "shelf_group_2";
constexpr char kTestShelfGroup3[] = "shelf_group_3";
constexpr int kAppAnimatedThresholdMs = 100;
std::string GetTestApp1Id(const std::string& package_name) {
return ArcAppListPrefs::GetAppId(package_name, kTestAppActivity);
}
std::string GetTestApp2Id(const std::string& package_name) {
return ArcAppListPrefs::GetAppId(package_name, kTestAppActivity2);
}
std::vector<arc::mojom::AppInfoPtr> GetTestAppsList(
const std::string& package_name,
bool multi_app) {
std::vector<arc::mojom::AppInfoPtr> apps;
arc::mojom::AppInfoPtr app(arc::mojom::AppInfo::New());
app->name = kTestAppName;
app->package_name = package_name;
app->activity = kTestAppActivity;
app->sticky = false;
apps.push_back(std::move(app));
if (multi_app) {
app = arc::mojom::AppInfo::New();
app->name = kTestAppName2;
app->package_name = package_name;
app->activity = kTestAppActivity2;
app->sticky = false;
apps.push_back(std::move(app));
}
return apps;
}
class AppAnimatedWaiter {
public:
explicit AppAnimatedWaiter(const std::string& app_id) : app_id_(app_id) {}
void Wait() {
const base::TimeDelta threshold =
base::TimeDelta::FromMilliseconds(kAppAnimatedThresholdMs);
ShelfSpinnerController* controller =
ChromeLauncherController::instance()->GetShelfSpinnerController();
while (controller->GetActiveTime(app_id_) < threshold) {
base::RunLoop().RunUntilIdle();
}
}
private:
const std::string app_id_;
};
enum TestAction {
TEST_ACTION_START, // Start app on app appears.
TEST_ACTION_EXIT, // Exit Chrome during animation.
TEST_ACTION_CLOSE, // Close item during animation.
};
// Test parameters include TestAction and pin/unpin state.
typedef std::tuple<TestAction, bool> TestParameter;
TestParameter build_test_parameter[] = {
TestParameter(TEST_ACTION_START, false),
TestParameter(TEST_ACTION_EXIT, false),
TestParameter(TEST_ACTION_CLOSE, false),
TestParameter(TEST_ACTION_START, true),
};
std::string CreateIntentUriWithShelfGroup(const std::string& shelf_group_id) {
return base::StringPrintf("#Intent;S.org.chromium.arc.shelf_group_id=%s;end",
shelf_group_id.c_str());
}
} // namespace
class ArcAppLauncherBrowserTest : public extensions::ExtensionBrowserTest {
public:
ArcAppLauncherBrowserTest() {}
~ArcAppLauncherBrowserTest() override {}
protected:
// content::BrowserTestBase:
void SetUpCommandLine(base::CommandLine* command_line) override {
extensions::ExtensionBrowserTest::SetUpCommandLine(command_line);
arc::SetArcAvailableCommandLineForTesting(command_line);
}
void SetUpInProcessBrowserTestFixture() override {
extensions::ExtensionBrowserTest::SetUpInProcessBrowserTestFixture();
arc::ArcSessionManager::SetUiEnabledForTesting(false);
}
void SetUpOnMainThread() override {
arc::SetArcPlayStoreEnabledForProfile(profile(), true);
}
void InstallTestApps(const std::string& package_name, bool multi_app) {
app_host()->OnAppListRefreshed(GetTestAppsList(package_name, multi_app));
std::unique_ptr<ArcAppListPrefs::AppInfo> app_info =
app_prefs()->GetApp(GetTestApp1Id(package_name));
ASSERT_TRUE(app_info);
EXPECT_TRUE(app_info->ready);
if (multi_app) {
std::unique_ptr<ArcAppListPrefs::AppInfo> app_info2 =
app_prefs()->GetApp(GetTestApp2Id(package_name));
ASSERT_TRUE(app_info2);
EXPECT_TRUE(app_info2->ready);
}
}
std::string InstallShortcut(const std::string& name,
const std::string& shelf_group) {
arc::mojom::ShortcutInfo shortcut;
shortcut.name = name;
shortcut.package_name = kTestAppPackage;
shortcut.intent_uri = CreateIntentUriWithShelfGroup(shelf_group);
const std::string shortcut_id =
ArcAppListPrefs::GetAppId(shortcut.package_name, shortcut.intent_uri);
app_host()->OnInstallShortcut(arc::mojom::ShortcutInfo::From(shortcut));
base::RunLoop().RunUntilIdle();
std::unique_ptr<ArcAppListPrefs::AppInfo> shortcut_info =
app_prefs()->GetApp(shortcut_id);
CHECK(shortcut_info);
EXPECT_TRUE(shortcut_info->shortcut);
EXPECT_EQ(kTestAppPackage, shortcut_info->package_name);
EXPECT_EQ(shortcut.intent_uri, shortcut_info->intent_uri);
return shortcut_id;
}
void SendPackageAdded(const std::string& package_name, bool package_synced) {
arc::mojom::ArcPackageInfo package_info;
package_info.package_name = package_name;
package_info.package_version = 1;
package_info.last_backup_android_id = 1;
package_info.last_backup_time = 1;
package_info.sync = package_synced;
package_info.system = false;
app_host()->OnPackageAdded(arc::mojom::ArcPackageInfo::From(package_info));
base::RunLoop().RunUntilIdle();
}
void SendPackageUpdated(const std::string& package_name, bool multi_app) {
app_host()->OnPackageAppListRefreshed(
package_name, GetTestAppsList(package_name, multi_app));
// Ensure async callbacks from the resulting observer calls are run.
base::RunLoop().RunUntilIdle();
}
void SendPackageRemoved(const std::string& package_name) {
app_host()->OnPackageRemoved(package_name);
// Ensure async callbacks from the resulting observer calls are run.
base::RunLoop().RunUntilIdle();
}
void SendInstallationStarted(const std::string& package_name) {
app_host()->OnInstallationStarted(package_name);
base::RunLoop().RunUntilIdle();
}
void SendInstallationFinished(const std::string& package_name, bool success) {
arc::mojom::InstallationResult result;
result.package_name = package_name;
result.success = success;
app_host()->OnInstallationFinished(
arc::mojom::InstallationResultPtr(result.Clone()));
base::RunLoop().RunUntilIdle();
}
void StartInstance() {
if (!arc_session_manager()->profile()) {
// This situation happens when StartInstance() is called after
// StopInstance().
// TODO(hidehiko): The emulation is not implemented correctly. Fix it.
arc_session_manager()->SetProfile(profile());
arc::ArcServiceLauncher::Get()->OnPrimaryUserProfilePrepared(profile());
}
app_instance_ = std::make_unique<arc::FakeAppInstance>(app_host());
arc_brige_service()->app()->SetInstance(app_instance_.get());
}
void StopInstance() {
if (app_instance_)
arc_brige_service()->app()->CloseInstance(app_instance_.get());
arc_session_manager()->Shutdown();
}
ash::ShelfItemDelegate* GetShelfItemDelegate(const std::string& id) {
auto* model = ChromeLauncherController::instance()->shelf_model();
return model->GetShelfItemDelegate(ash::ShelfID(id));
}
ArcAppListPrefs* app_prefs() { return ArcAppListPrefs::Get(profile()); }
// Returns as AppHost interface in order to access to private implementation
// of the interface.
arc::mojom::AppHost* app_host() { return app_prefs(); }
// Returns as AppInstance observer interface in order to access to private
// implementation of the interface.
arc::ConnectionObserver<arc::mojom::AppInstance>* app_connection_observer() {
return app_prefs();
}
arc::ArcSessionManager* arc_session_manager() {
return arc::ArcSessionManager::Get();
}
arc::ArcBridgeService* arc_brige_service() {
return arc::ArcServiceManager::Get()->arc_bridge_service();
}
private:
std::unique_ptr<arc::FakeAppInstance> app_instance_;
DISALLOW_COPY_AND_ASSIGN(ArcAppLauncherBrowserTest);
};
class ArcAppDeferredLauncherBrowserTest : public ArcAppLauncherBrowserTest {
public:
ArcAppDeferredLauncherBrowserTest() = default;
~ArcAppDeferredLauncherBrowserTest() override = default;
private:
DISALLOW_COPY_AND_ASSIGN(ArcAppDeferredLauncherBrowserTest);
};
IN_PROC_BROWSER_TEST_F(ArcAppDeferredLauncherBrowserTest,
StartAppDeferredFromShelfButton) {
StartInstance();
InstallTestApps(kTestAppPackage, false);
SendPackageAdded(kTestAppPackage, false);
// Restart ARC and ARC apps are in disabled state.
StopInstance();
StartInstance();
ChromeLauncherController* const controller =
ChromeLauncherController::instance();
const std::string app_id = GetTestApp1Id(kTestAppPackage);
controller->PinAppWithID(app_id);
aura::Window* const root_window = ash::Shell::GetPrimaryRootWindow();
ash::ShelfViewTestAPI test_api(
ash::Shelf::ForWindow(root_window)->GetShelfViewForTesting());
const int item_index =
controller->shelf_model()->ItemIndexByID(ash::ShelfID(app_id));
ASSERT_GE(item_index, 0);
ash::ShelfAppButton* const button = test_api.GetButton(item_index);
ASSERT_TRUE(button);
views::InkDrop* const ink_drop = button->GetInkDropForTesting();
ASSERT_TRUE(ink_drop);
EXPECT_EQ(views::InkDropState::HIDDEN, ink_drop->GetTargetInkDropState());
ui::test::EventGenerator event_generator(root_window);
event_generator.MoveMouseTo(button->GetBoundsInScreen().CenterPoint());
base::RunLoop().RunUntilIdle();
event_generator.ClickLeftButton();
EXPECT_EQ(views::InkDropState::ACTION_TRIGGERED,
ink_drop->GetTargetInkDropState());
}
class ArcAppDeferredLauncherWithParamsBrowserTest
: public ArcAppDeferredLauncherBrowserTest,
public testing::WithParamInterface<TestParameter> {
public:
ArcAppDeferredLauncherWithParamsBrowserTest() = default;
~ArcAppDeferredLauncherWithParamsBrowserTest() override = default;
protected:
bool is_pinned() const { return std::get<1>(GetParam()); }
TestAction test_action() const { return std::get<0>(GetParam()); }
private:
DISALLOW_COPY_AND_ASSIGN(ArcAppDeferredLauncherWithParamsBrowserTest);
};
// This tests simulates normal workflow for starting ARC app in deferred mode.
IN_PROC_BROWSER_TEST_P(ArcAppDeferredLauncherWithParamsBrowserTest,
StartAppDeferred) {
// Install app to remember existing apps.
StartInstance();
InstallTestApps(kTestAppPackage, false);
SendPackageAdded(kTestAppPackage, false);
ChromeLauncherController* controller = ChromeLauncherController::instance();
const std::string app_id = GetTestApp1Id(kTestAppPackage);
const ash::ShelfID shelf_id(app_id);
if (is_pinned()) {
controller->PinAppWithID(app_id);
const ash::ShelfItem* item = controller->GetItem(shelf_id);
EXPECT_EQ(base::UTF8ToUTF16(kTestAppName), item->title);
} else {
EXPECT_FALSE(controller->GetItem(shelf_id));
}
StopInstance();
std::unique_ptr<ArcAppListPrefs::AppInfo> app_info =
app_prefs()->GetApp(app_id);
EXPECT_FALSE(app_info);
// Restart instance. App should be taken from prefs but its state is non-ready
// currently.
StartInstance();
app_info = app_prefs()->GetApp(app_id);
ASSERT_TRUE(app_info);
EXPECT_FALSE(app_info->ready);
EXPECT_EQ(is_pinned(), controller->GetItem(shelf_id) != nullptr);
// Launching non-ready ARC app creates item on shelf and spinning animation.
if (is_pinned()) {
EXPECT_EQ(ash::SHELF_ACTION_NEW_WINDOW_CREATED,
SelectShelfItem(shelf_id, ui::ET_MOUSE_PRESSED,
display::kInvalidDisplayId));
} else {
arc::LaunchApp(profile(), app_id, ui::EF_LEFT_MOUSE_BUTTON,
arc::UserInteractionType::NOT_USER_INITIATED);
}
const ash::ShelfItem* item = controller->GetItem(shelf_id);
EXPECT_EQ(base::UTF8ToUTF16(kTestAppName), item->title);
AppAnimatedWaiter(app_id).Wait();
switch (test_action()) {
case TEST_ACTION_START:
// Now simulates that ARC is started and app list is refreshed. This
// should stop animation and delete icon from the shelf.
InstallTestApps(kTestAppPackage, false);
SendPackageAdded(kTestAppPackage, false);
EXPECT_TRUE(controller->GetShelfSpinnerController()
->GetActiveTime(app_id)
.is_zero());
EXPECT_EQ(is_pinned(), controller->GetItem(shelf_id) != nullptr);
break;
case TEST_ACTION_EXIT:
// Just exit Chrome.
break;
case TEST_ACTION_CLOSE: {
// Close item during animation.
ash::ShelfItemDelegate* delegate = GetShelfItemDelegate(app_id);
ASSERT_TRUE(delegate);
delegate->Close();
EXPECT_TRUE(controller->GetShelfSpinnerController()
->GetActiveTime(app_id)
.is_zero());
EXPECT_EQ(is_pinned(), controller->GetItem(shelf_id) != nullptr);
break;
}
}
}
INSTANTIATE_TEST_SUITE_P(ArcAppDeferredLauncherWithParamsBrowserTestInstance,
ArcAppDeferredLauncherWithParamsBrowserTest,
::testing::ValuesIn(build_test_parameter));
// This tests validates pin state on package update and remove.
IN_PROC_BROWSER_TEST_F(ArcAppLauncherBrowserTest, PinOnPackageUpdateAndRemove) {
StartInstance();
// Make use app list sync service is started. Normally it is started when
// sycing is initialized.
app_list::AppListSyncableServiceFactory::GetForProfile(profile())
->GetModelUpdater();
InstallTestApps(kTestAppPackage, true);
SendPackageAdded(kTestAppPackage, false);
const ash::ShelfID shelf_id1(GetTestApp1Id(kTestAppPackage));
const ash::ShelfID shelf_id2(GetTestApp2Id(kTestAppPackage));
ChromeLauncherController* controller = ChromeLauncherController::instance();
controller->PinAppWithID(shelf_id1.app_id);
controller->PinAppWithID(shelf_id2.app_id);
EXPECT_TRUE(controller->GetItem(shelf_id1));
EXPECT_TRUE(controller->GetItem(shelf_id2));
// Package contains only one app. App list is not shown for updated package.
SendPackageUpdated(kTestAppPackage, false);
// Second pin should gone.
EXPECT_TRUE(controller->GetItem(shelf_id1));
EXPECT_FALSE(controller->GetItem(shelf_id2));
// Package contains two apps. App list is not shown for updated package.
SendPackageUpdated(kTestAppPackage, true);
// Second pin should not appear.
EXPECT_TRUE(controller->GetItem(shelf_id1));
EXPECT_FALSE(controller->GetItem(shelf_id2));
// Package removed.
SendPackageRemoved(kTestAppPackage);
// No pin is expected.
EXPECT_FALSE(controller->GetItem(shelf_id1));
EXPECT_FALSE(controller->GetItem(shelf_id2));
}
// Test AppListControllerDelegate::IsAppOpen for ARC apps.
IN_PROC_BROWSER_TEST_F(ArcAppLauncherBrowserTest, IsAppOpen) {
StartInstance();
InstallTestApps(kTestAppPackage, false);
SendPackageAdded(kTestAppPackage, true);
const std::string app_id = GetTestApp1Id(kTestAppPackage);
AppListClientImpl* client = AppListClientImpl::GetInstance();
AppListControllerDelegate* delegate = client;
EXPECT_FALSE(delegate->IsAppOpen(app_id));
arc::LaunchApp(profile(), app_id, ui::EF_LEFT_MOUSE_BUTTON,
arc::UserInteractionType::NOT_USER_INITIATED);
EXPECT_FALSE(delegate->IsAppOpen(app_id));
// Simulate task creation so the app is marked as running/open.
std::unique_ptr<ArcAppListPrefs::AppInfo> info = app_prefs()->GetApp(app_id);
app_host()->OnTaskCreated(0, info->package_name, info->activity, info->name,
info->intent_uri);
EXPECT_TRUE(delegate->IsAppOpen(app_id));
}
// Test Shelf Groups
IN_PROC_BROWSER_TEST_F(ArcAppLauncherBrowserTest, ShelfGroup) {
StartInstance();
InstallTestApps(kTestAppPackage, false);
SendPackageAdded(kTestAppPackage, true);
const std::string shorcut_id1 =
InstallShortcut(kTestShortcutName, kTestShelfGroup);
const std::string shorcut_id2 =
InstallShortcut(kTestShortcutName2, kTestShelfGroup2);
const std::string app_id = GetTestApp1Id(kTestAppPackage);
std::unique_ptr<ArcAppListPrefs::AppInfo> info = app_prefs()->GetApp(app_id);
ASSERT_TRUE(info);
const std::string shelf_id1 =
arc::ArcAppShelfId(kTestShelfGroup, app_id).ToString();
const std::string shelf_id2 =
arc::ArcAppShelfId(kTestShelfGroup2, app_id).ToString();
const std::string shelf_id3 =
arc::ArcAppShelfId(kTestShelfGroup3, app_id).ToString();
// 1 task for group 1
app_host()->OnTaskCreated(1, info->package_name, info->activity, info->name,
CreateIntentUriWithShelfGroup(kTestShelfGroup));
ash::ShelfItemDelegate* delegate1 = GetShelfItemDelegate(shelf_id1);
ASSERT_TRUE(delegate1);
// 2 tasks for group 2
app_host()->OnTaskCreated(2, info->package_name, info->activity, info->name,
CreateIntentUriWithShelfGroup(kTestShelfGroup2));
ash::ShelfItemDelegate* delegate2 = GetShelfItemDelegate(shelf_id2);
ASSERT_TRUE(delegate2);
ASSERT_NE(delegate1, delegate2);
app_host()->OnTaskCreated(3, info->package_name, info->activity, info->name,
CreateIntentUriWithShelfGroup(kTestShelfGroup2));
ASSERT_EQ(delegate2, GetShelfItemDelegate(shelf_id2));
// 2 tasks for group 3 which does not have shortcut.
app_host()->OnTaskCreated(4, info->package_name, info->activity, info->name,
CreateIntentUriWithShelfGroup(kTestShelfGroup3));
ash::ShelfItemDelegate* delegate3 = GetShelfItemDelegate(shelf_id3);
ASSERT_TRUE(delegate3);
ASSERT_NE(delegate1, delegate3);
ASSERT_NE(delegate2, delegate3);
app_host()->OnTaskCreated(5, info->package_name, info->activity, info->name,
CreateIntentUriWithShelfGroup(kTestShelfGroup3));
ASSERT_EQ(delegate3, GetShelfItemDelegate(shelf_id3));
ChromeLauncherController* controller = ChromeLauncherController::instance();
const ash::ShelfItem* item1 = controller->GetItem(ash::ShelfID(shelf_id1));
ASSERT_TRUE(item1);
// The shelf group item's title should be the title of the referenced ARC app.
EXPECT_EQ(base::UTF8ToUTF16(kTestAppName), item1->title);
// Destroy task #0, this kills shelf group 1
app_host()->OnTaskDestroyed(1);
EXPECT_FALSE(GetShelfItemDelegate(shelf_id1));
// Destroy task #1, shelf group 2 is still alive
app_host()->OnTaskDestroyed(2);
EXPECT_EQ(delegate2, GetShelfItemDelegate(shelf_id2));
// Destroy task #2, this kills shelf group 2
app_host()->OnTaskDestroyed(3);
EXPECT_FALSE(GetShelfItemDelegate(shelf_id2));
// Disable ARC, this removes app and as result kills shelf group 3.
arc::SetArcPlayStoreEnabledForProfile(profile(), false);
EXPECT_FALSE(GetShelfItemDelegate(shelf_id3));
}
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
65340a321c77005426b2e07c1f3874c0531769a8 | 6ee3292d2dc2bf4cb350f869294855606b6c04ef | /EchoServer_ver.2/src/DataReposit/DataReposit.cpp | 0756aa4a5fdf7c50ea3d514ed51611c5e01cbc78 | [] | no_license | leejinsoo92/EchoServer | 4f209e91a76bb4ba509d05e2e48f03f4557f230c | c8ee2194b3323c49de6c54e5b4f742dc0a69481c | refs/heads/master | 2020-07-26T15:21:25.895696 | 2019-10-10T10:37:48 | 2019-10-10T10:37:48 | 208,688,995 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,328 | cpp | /*
* DataReposit.cpp
*
* Created on: 2019. 10. 2.
* Author: leejinsoo
*/
#include "DataReposit.h"
#include <string.h>
#include <mutex>
pthread_mutex_t listlock;
CDataReposit::CDataReposit() {
// TODO Auto-generated constructor stub
}
CDataReposit::~CDataReposit() {
// TODO Auto-generated destructor stub
DeleteInstance();
m_listData.clear();
}
CDataReposit* CDataReposit::instance = nullptr;
CDataReposit* CDataReposit::getInstance()
{
if( nullptr == instance )
{
instance = new CDataReposit();
pthread_mutex_init(&listlock, NULL);
}
return instance;
}
void CDataReposit::DeleteInstance()
{
delete instance;
instance = nullptr;
}
bool CDataReposit::isEmpty()
{
return m_listData.empty();
}
bool CDataReposit::SaveData(char* _data)
{
pthread_mutex_lock(&listlock);
if(true == m_listData.empty())
{
m_listData.push_back(_data);
pthread_mutex_unlock(&listlock);
return true;
}
for(vector<string>::iterator iter = m_listData.begin(); iter != m_listData.end(); ++iter)
{
if( iter->compare(_data) == 0)
{
pthread_mutex_unlock(&listlock);
return false;
}
}
m_listData.push_back(_data);
pthread_mutex_unlock(&listlock);
return true;
}
bool CDataReposit::DeleteData(char* _data)
{
pthread_mutex_lock(&listlock);
if(true == m_listData.empty())
{
pthread_mutex_unlock(&listlock);
return false;
}
for(vector<string>::iterator iter = m_listData.begin(); iter != m_listData.end(); )
{
if( iter->compare(_data) == 0)
{
iter = m_listData.erase(iter);
pthread_mutex_unlock(&listlock);
return true;
}
else
++iter;
}
pthread_mutex_unlock(&listlock);
return false;
}
char* CDataReposit::PrintSendData(int num)
{
vector<string>::iterator iter_begin = m_listData.begin();
vector<string>::iterator iter_end = m_listData.end();
vector<string>::iterator iter = iter_begin + num;
if( iter != iter_end )
{
char* szRedata = new char[ (*iter).size() + 1];
std::copy((*iter).begin(), (*iter).end(), szRedata);
szRedata[(*iter).size()] = '\0';
return szRedata;
}
return nullptr;
}
char* CDataReposit::PrintSend()
{
vector<string>::iterator iter_begin = m_listData.begin();
vector<string>::iterator iter_end = m_listData.end();
vector<string>::iterator iter = iter_begin + m_iPrintCnt;
m_iCurrentCnt = 0;
while(1)
{
if( iter != iter_end )
{
if(MAX_PACKET_SIZE < m_iRear + (*iter).size() + 1)
{
m_iRear = 0;
m_isEnd = false;
break;
}
std::copy((*iter).begin(), (*iter).end(), m_szTempBuf + m_iRear);
m_szTempBuf[m_iRear + (*iter).size()] = '\0';
++m_iPrintCnt;
++m_iCurrentCnt;
m_iRear += (*iter).size() + 1;
}
else
{
m_iRear = 0;
m_isEnd = true;
break;
}
++iter;
}
memset(m_szPrintBuf, 0, sizeof(MAX_PACKET_SIZE)); // 보내는 버퍼 초기화
memcpy(m_szPrintBuf, m_szTempBuf, sizeof(m_szTempBuf)); // 임시 버퍼 -> 보내는 버퍼
memset(m_szTempBuf, 0, sizeof(MAX_PACKET_SIZE)); // 임시 버퍼 초기화
pthread_mutex_unlock(&listlock);
return m_szPrintBuf;
return nullptr;
}
void CDataReposit::PrintData()
{
cout << endl;
cout << "[DataReposit] Data list " << endl;
int iNum = 1;
for(vector<string>::iterator iter = m_listData.begin(); iter != m_listData.end(); ++iter)
{
cout << "[ " << iNum++ << " ] " << *iter << endl;
}
cout << endl;
}
| [
"wlstn4020@naver.com"
] | wlstn4020@naver.com |
7da80e37f3e4923362b48428c149c40208d92896 | 3a5033582f05639ce12ec61e77fad7428ef54993 | /Interface/showscore.h | 7320abcab3ed52f5f1c41adb7c8295ac964d1d9e | [] | no_license | fanxiang090909/Students-Scores-Analysis-version1 | 6872c3569a83395153439c0b84f68863349e7fb2 | 57a393795d51f47d327d082b4638ef1a597b0f9d | refs/heads/master | 2020-12-24T13:44:29.675142 | 2015-03-12T11:56:30 | 2015-03-12T11:56:30 | 32,062,515 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,110 | h | #ifndef SHOWSCORE_H
#define SHOWSCORE_H
#include "ui_showscore.h"
#include <QDialog>
#include <QSqlTableModel>
#include <QSqlRelationalTableModel>
#include <QDataWidgetMapper>
namespace Ui {
class showscore;
}
enum {
Course_No = 0,
Course_name = 1,
Course_Credits = 2
};
enum {
Score_studNo = 0,
Score_courseNo = 1,
Score_score = 2,
Score_examDate = 3,
Score_time = 4
};
class showscore : public QDialog
{
Q_OBJECT
public:
explicit showscore(QString studNo, QDialog *parent = 0);
void createScoreShow(QString studNo);
void updateG();
void updategmodel(QString studNo);
~showscore();
private slots:
void on_stunumEdit_textChanged(QString );
void checkFindEdit();
void addg();
void on_findButton_clicked();
void on_findEdit_textChanged(QString );
void on_findEdit_returnPressed();
private:
Ui::showscore *ui;
QWidget * widget;
QSqlRelationalTableModel *scoreModel;
QSqlRelationalTableModel *gModel;
QSqlRelationalTableModel *tableModel;
QDataWidgetMapper *mapper;
};
#endif // SHOWSCORE_H
| [
"fanxiang090909@126.com"
] | fanxiang090909@126.com |
c06991dfdf3c7ed4a8ddfe52f2b60494811fdd78 | edd1f52a6b8a4f81c63c8c804818bbe142c7a357 | /feet and inches to centi.cpp | 8b1d5c2b0847893d73e2518ed94ea26d8e3fa3b2 | [] | no_license | abdulkhan4ux/oop | 3302550231b52145c45735efd5214153a2d79991 | 3daa7336e5397b64144130720cd8206bcdcac2e5 | refs/heads/master | 2020-09-12T20:07:28.750909 | 2019-11-27T23:16:59 | 2019-11-27T23:16:59 | 222,538,156 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 420 | cpp | #include<iostream>;
using namespace std;
int main()
{
const double feet_to_inch = 12;
const double inch_to_centi = 2.54;
double feet;
cout << "Enter in feet " ;
cin >> feet ;
double inches;
cout << "Enter in inches " ;
cin >> inches ;
double total_inches = feet * feet_to_inch ;
double total_centi = total_inches * inch_to_centi ;
cout << "/n The Result is :" << total_centi;
return 0;
}
| [
"noreply@github.com"
] | abdulkhan4ux.noreply@github.com |
739ba6f183c66ab2f2e03b1295ff74ee9f621ecc | dca653bb975528bd1b8ab2547f6ef4f48e15b7b7 | /tags/wxPy-2.9.0.1/tests/benchmarks/tls.cpp | b187566c17d85184b72d7273bb76f012da37bf55 | [] | no_license | czxxjtu/wxPython-1 | 51ca2f62ff6c01722e50742d1813f4be378c0517 | 6a7473c258ea4105f44e31d140ea5c0ae6bc46d8 | refs/heads/master | 2021-01-15T12:09:59.328778 | 2015-01-05T20:55:10 | 2015-01-05T20:55:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,439 | cpp | /////////////////////////////////////////////////////////////////////////////
// Name: tests/benchmarks/strings.cpp
// Purpose: String-related benchmarks
// Author: Vadim Zeitlin
// Created: 2008-07-19
// RCS-ID: $Id$
// Copyright: (c) 2008 Vadim Zeitlin <vadim@wxwidgets.org>
// Licence: wxWindows license
/////////////////////////////////////////////////////////////////////////////
#include "bench.h"
#include "wx/tls.h"
#if defined(__UNIX__)
#define HAVE_PTHREAD
#include <pthread.h>
#elif defined(__WIN32__)
#define HAVE_WIN32_THREAD
#include "wx/msw/wrapwin.h"
#endif
#if wxCHECK_GCC_VERSION(3, 3)
#define HAVE_COMPILER_THREAD
#define wxTHREAD_SPECIFIC __thread
#elif wxCHECK_VISUALC_VERSION(7)
#define HAVE_COMPILER_THREAD
#define wxTHREAD_SPECIFIC __declspec(thread)
#endif
// uncomment this to also test Boost version (you will also need to link with
// libboost_threads)
//#define HAVE_BOOST_THREAD
#ifdef HAVE_BOOST_THREAD
#include <boost/thread/tss.hpp>
#endif
static const int NUM_ITER = 1000;
// this is just a baseline
BENCHMARK_FUNC(DummyTLS)
{
static int s_global = 0;
for ( int n = 0; n < NUM_ITER; n++ )
{
if ( n % 2 )
s_global = 0;
else
s_global = n;
}
return !s_global;
}
#ifdef HAVE_COMPILER_THREAD
BENCHMARK_FUNC(CompilerTLS)
{
static wxTHREAD_SPECIFIC int s_global = 0;
for ( int n = 0; n < NUM_ITER; n++ )
{
if ( n % 2 )
s_global = 0;
else
s_global = n;
}
return !s_global;
}
#endif // HAVE_COMPILER_THREAD
#ifdef HAVE_PTHREAD
class PthreadKey
{
public:
PthreadKey()
{
pthread_key_create(&m_key, NULL);
}
~PthreadKey()
{
pthread_key_delete(m_key);
}
operator pthread_key_t() const { return m_key; }
private:
pthread_key_t m_key;
DECLARE_NO_COPY_CLASS(PthreadKey)
};
BENCHMARK_FUNC(PosixTLS)
{
static PthreadKey s_key;
for ( int n = 0; n < NUM_ITER; n++ )
{
if ( n % 2 )
pthread_setspecific(s_key, 0);
else
pthread_setspecific(s_key, &n);
}
return !pthread_getspecific(s_key);
}
#endif // HAVE_PTHREAD
#ifdef HAVE_WIN32_THREAD
class TlsSlot
{
public:
TlsSlot()
{
m_slot = ::TlsAlloc();
}
~TlsSlot()
{
::TlsFree(m_slot);
}
operator DWORD() const { return m_slot; }
private:
DWORD m_slot;
DECLARE_NO_COPY_CLASS(TlsSlot)
};
BENCHMARK_FUNC(Win32TLS)
{
static TlsSlot s_slot;
for ( int n = 0; n < NUM_ITER; n++ )
{
if ( n % 2 )
::TlsSetValue(s_slot, 0);
else
::TlsSetValue(s_slot, &n);
}
return !::TlsGetValue(s_slot);
}
#endif // HAVE_WIN32_THREAD
#ifdef HAVE_BOOST_THREAD
BENCHMARK_FUNC(BoostTLS)
{
static boost::thread_specific_ptr<int> s_ptr;
if ( !s_ptr.get() )
s_ptr.reset(new int(0));
for ( int n = 0; n < NUM_ITER; n++ )
{
if ( n % 2 )
*s_ptr = 0;
else
*s_ptr = n;
}
return !*s_ptr;
}
#endif // HAVE_BOOST_THREAD
BENCHMARK_FUNC(wxTLS)
{
static wxTLS_TYPE(int) s_globalVar;
#define s_global wxTLS_VALUE(s_globalVar)
for ( int n = 0; n < NUM_ITER; n++ )
{
if ( n % 2 )
s_global = 0;
else
s_global = n;
}
return !s_global;
}
| [
"RD@c3d73ce0-8a6f-49c7-b76d-6d57e0e08775"
] | RD@c3d73ce0-8a6f-49c7-b76d-6d57e0e08775 |
9450ef2ec779b705576cb7e39fa195f5b9dc140d | 24e763341c2c143a88c59f893855bf50601447ab | /GuiView/ContactsGui/UClusterCreateSuccessedPage.h | 9085925e443f34666ce0094246176c5ff2776396 | [] | no_license | LinLinYi/kirogi | 63f8e67aa62e5d44f13aae8b46373a166f9597e5 | f171f7d9a53398d221e2330da98b6b4e9677609d | refs/heads/master | 2021-01-10T01:00:03.866064 | 2015-04-06T04:02:47 | 2015-04-06T04:02:47 | 33,439,487 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,125 | h | #ifndef UCLUSTERCREATESUCCESSEDPAGE_H
#define UCLUSTERCREATESUCCESSEDPAGE_H
class GroupButton;
class InputPacket;
class UClusterInfo;
class NavigationBar;
class QPushButton;
#include "BasePage.h"
class UClusterCreateSuccessedPage : public BasePage
{
Q_OBJECT
public:
explicit UClusterCreateSuccessedPage(QWidget* parent = 0, quint64 clusID = 0);
virtual ~UClusterCreateSuccessedPage();
public:
void fetchData(InputPacket& inpack);
private:
quint64 curClusterID;
NavigationBar* navigationBar; /*! 导航栏*/
GroupButton* btnTitleInfo; /*! 群标题信息*/
GroupButton* btnDescribe; /*! 群描述*/
QPushButton* btnComplete; /*! 完成群创建*/
UClusterInfo* curClusterInfo; /*! 群信息*/
private:
void initializeWidget();
void handleClusterInfo(InputPacket& inpack);
void setGroupButton(GroupButton* btn, QPixmap photo, QString title);
private slots:
void on_btnPerfactClusterInfo_clicked();
void on_btnInviationDevice_clicked();
void on_btnCompleted_clicked();
};
#endif // UCLUSTERCREATESUCCESSEDPAGE_H
| [
"yilinlin2014@gmail.com"
] | yilinlin2014@gmail.com |
2e3d6c0a4baf487969351db1aed595afdbcea77d | 5f7d56a80dc49f815733b2869e3870af027621cb | /src/qt/paymentserver.h | 32284a9d939818d8c7a7633367c6cf2524c94989 | [
"MIT"
] | permissive | axxd2001/cpc | 44f5a839b5c2b48d367572b2e2f77dddb3834a1a | 25214cddfb5115df521243a6249bfa2d0675db54 | refs/heads/master | 2020-05-25T23:26:05.176408 | 2016-07-29T03:19:24 | 2016-07-29T03:19:24 | 64,445,045 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,887 | h | #ifndef PAYMENTSERVER_H
#define PAYMENTSERVER_H
//
// This class handles payment requests from clicking on
// Chinesepaintingcoin: URIs
//
// This is somewhat tricky, because we have to deal with
// the situation where the user clicks on a link during
// startup/initialization, when the splash-screen is up
// but the main window (and the Send Coins tab) is not.
//
// So, the strategy is:
//
// Create the server, and register the event handler,
// when the application is created. Save any URIs
// received at or during startup in a list.
//
// When startup is finished and the main window is
// shown, a signal is sent to slot uiReady(), which
// emits a receivedURL() signal for any payment
// requests that happened during startup.
//
// After startup, receivedURL() happens as usual.
//
// This class has one more feature: a static
// method that finds URIs passed in the command line
// and, if a server is running in another process,
// sends them to the server.
//
#include <QObject>
#include <QString>
class OptionsModel;
class QApplication;
class QLocalServer;
class PaymentServer : public QObject
{
Q_OBJECT
private:
bool saveURIs;
QLocalServer* uriServer;
public:
// Returns true if there were URIs on the command line
// which were successfully sent to an already-running
// process.
static bool ipcSendCommandLine();
PaymentServer(QApplication* parent);
bool eventFilter(QObject *object, QEvent *event);
// OptionsModel is used for getting proxy settings and display unit
void setOptionsModel(OptionsModel *optionsModel);
signals:
void receivedURI(QString);
public slots:
// Signal this when the main window's UI is ready
// to display payment requests to the user
void uiReady();
private slots:
void handleURIConnection();
private:
OptionsModel *optionsModel;
};
#endif // PAYMENTSERVER_H
| [
"736686484@qq.com"
] | 736686484@qq.com |
e62929b332683b383a645fe7d74cf79206666144 | 2a2e99fa853241cea8960b54b419ee89f3cabe29 | /backend/screen_data.h | 5296de372b9aefec82e3c42dc4ed135ee51817b8 | [] | no_license | lbt/yat | 0ef3814edd4b576b50dab1c422ccc98ef653b70c | 47ec5d19a16c863b3a0d430dde6be67fd72780a2 | refs/heads/master | 2021-01-16T00:31:32.271987 | 2013-04-17T20:32:49 | 2013-04-17T20:32:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,492 | h | /**************************************************************************************************
* Copyright (c) 2012 Jørgen Lind
*
* 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.
*
***************************************************************************************************/
#ifndef SCREENDATA_H
#define SCREENDATA_H
#include <QtCore/QVector>
#include <QtCore/QPoint>
#include <QtGui/QClipboard>
class Line;
class Screen;
class ScreenData
{
public:
ScreenData(Screen *screen);
~ScreenData();
int width() const;
void setWidth(int width);
int height() const;
void setHeight(int height);
int scrollAreaStart() const;
int scrollAreaEnd() const;
Line *at(int index) const;
void clearToEndOfLine(int row, int from_char);
void clearToEndOfScreen(int row);
void clearToBeginningOfScreen(int row);
void clearLine(int index);
void clear();
void setScrollArea(int from, int to);
void moveLine(int from, int to);
void updateIndexes(int from = 0, int to = -1);
void sendSelectionToClipboard(const QPointF &start, const QPointF &end, QClipboard::Mode clipboard);
void getDoubleClickSelectionArea(const QPointF &cliked, int *start_ret, int *end_ret) const;
void dispatchLineEvents();
void printScreen() const;
private:
Screen *m_screen;
int m_width;
QVector<Line *> m_screen_lines;
int m_scroll_start;
int m_scroll_end;
bool m_scroll_area_set;
};
#endif // SCREENDATA_H
| [
"jorgen.lind@gmail.com"
] | jorgen.lind@gmail.com |
1f8a9ae12dca56fd1c12ca3b974bae042259992c | 5718748f4aebf7073499c6b0ddfe9e83d4adaa2a | /src/main.cpp | 48cf204ef2054e140997f81721c244e91805af45 | [] | no_license | pdpreez/bomberman | 53096da210f8c1a6716ebd2570b93ccc0f4af9bd | 906d3128d115b92c8c0bf6d96ab77a803b0399ec | refs/heads/master | 2020-07-02T06:08:52.829136 | 2019-08-20T14:20:30 | 2019-08-20T14:20:30 | 201,435,839 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 958 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ppreez <ppreez@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/08/11 11:03:07 by ppreez #+# #+# */
/* Updated: 2019/08/12 10:32:09 by ppreez ### ########.fr */
/* */
/* ************************************************************************** */
#include "Game.hpp"
int main()
{
Game game;
game.run();
} | [
"ppreez@c4r12s9.wethinkcode.co.za"
] | ppreez@c4r12s9.wethinkcode.co.za |
3cc9d22fd1b4cfc7d09dd6567919f4ec7d5d8ce2 | 3a278d9204a8c9353b665f81297fd79b132e87e9 | /ModelGL/rendering.cpp | 632d136ee19e907ecaac475baefdb206b4c53ec7 | [
"MIT"
] | permissive | gabrielferrazduque/OpenModelGL | f8c0bdd68fe6256638aa868903066ca32bd2e8bf | c7e85501afc05300aea43ebe2130a87553d1c7b7 | refs/heads/main | 2023-06-02T02:50:02.708977 | 2021-06-20T00:26:31 | 2021-06-20T00:26:31 | 375,177,356 | 9 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,032 | cpp | rendering
of your modelview matrix project
matModel.rotateZ(modelAngle[2]);
matModel.rotateY(modelAngle[1]);
matModel.rotateX(modelAngle[0]);
matModel.translate(modelPosition[0], modelPosition[1], modelPosition[2]);
matModelView = matView * matModel;
glLoadMatrixf(matModelView.get());
if i change it to
matModel.rotateZ(modelAngle[2]);
matModel.rotateY(modelAngle[1]);
matModel.rotateX(modelAngle[0]);
matModelView = matView * matModel;
matModelView.translate(modelPosition[0], modelPosition[1], modelPosition[2]);
glLoadMatrixf(matModelView.get());
nothing happens, but if i make opengl do the translation part like this
matModel.rotateZ(modelAngle[2]);
matModel.rotateY(modelAngle[1]);
matModel.rotateX(modelAngle[0]);
matModelView = matView * matModel;
glLoadMatrixf(matModelView.get());
glTranslatef(modelPosition[0], modelPosition[1], modelPosition[2])/* v' = Mt · Mr · v */
glTranslatef(...);
glRotatef(...);
glVertex3f(...);
matModelView ();
/ This creates a symmetric frustum.
// It converts to 6 params (l, r, b, t, n, f) for glFrustum()
// from given 4 params (fovy, aspect, near, far)
void makeFrustum(double fovY, double aspectRatio, double front, double back)
{
const double DEG2RAD = 3.14159265 / 180;
double tangent = tan(fovY/2 * DEG2RAD); // tangent of half fovY
double height = front * tangent; // half height of near plane
double width = height * aspectRatio; // half width of near plane
// params: left, right, bottom, top, near, far
glFrustum(-width, width, -height, height, front, back);
}// Note that the object will be translated first then rotated
glRotatef(angle, 1, 0, 0); // rotate object angle degree around X-axis
glTranslatef(x, y, z); // move object to (x, y, z)
drawObject();
gluLookAt()glTranslatef()
/ This creates a symmetric frustum.
// It converts to 6 params (l, r, b, t, n, f) for glFrustum()
// from given 4 params (fovy, aspect, near, far)
void makeFrustum(double fovY, double aspectRatio, double front, double back)
{
const double DEG2RAD = 3.14159265 / 180;
double tangent = tan(fovY/2 * DEG2RAD); // tangent of half fovY
double height = front * tangent; // half height of near plane
double width = height * aspectRatio; // half width of near plane
// params: left, right, bottom, top, near, far
glFrustum(-width, width, -height, height, front, back);
}
// rotate texture around X-axis
glMatrixMode(GL_TEXTURE);
glRotatef(angle, 1, 0, 0);
...glRotatef(), glTranslatef(), glScalef().
glPushMatrix();glRotatef(), glTranslatef(), glScalef().
// set view matrix for camera transform
glLoadMatrixf(matrixView.get());
// draw the grid at origin before model transform
drawGrid();
// set modelview matrix for both model and view transform
// It transforms from object space to eye space.
glLoadMatrixf(matrixModelView.get());
// draw a teapot after both view and model transforms
drawTeapot();
glPopMatrix();
... glPushMatrix
...height()
glPushMatrix();
// initialze ModelView matrix
glLoadIdentity();
// First, transform the camera (viewing matrix) from world space to eye space
// Notice translation and heading values are negated,
// because we move the whole scene with the inverse of camera transform
// ORDER: translation -> roll -> heading -> pitch
glRotatef(cameraAngle[2], 0, 0, 1); // roll
glRotatef(-cameraAngle[1], 0, 1, 0); // heading
glRotatef(cameraAngle[0], 1, 0, 0); // pitch
glTranslatef(-cameraPosition[0], -cameraPosition[1], -cameraPosition[2]);
// draw the grid at origin before model transform
drawGrid();
// transform the object (model matrix)
// The result of GL_MODELVIEW matrix will be:
// ModelView_M = View_M * Model_M
// ORDER: rotZ -> rotY -> rotX -> translation
glTranslatef(modelPosition[0], modelPosition[1], modelPosition[2]);
glRotatef(modelAngle[0], 1, 0, 0);
glRotatef(modelAngle[1], 0, 1, 0);
glRotatef(modelAngle[2], 0, 0, 1);
// draw a teapot with model and view transform together
drawTeapot();
glPopMatrix();
...
///////////////////////////////////////////////////////////////////////////////
// return a perspective frustum with 6 params similar to glFrustum()
// (left, right, bottom, top, near, far)
///////////////////////////////////////////////////////////////////////////////
Matrix4 ModelGL::setFrustum(float l, float r, float b, float t, float n, float f)
{
Matrix4 matrix;
matrix[0] = 2 * n / (r - l);
matrix[5] = 2 * n / (t - b);
matrix[8] = (r + l) / (r - l);
matrix[9] = (t + b) / (t - b);
matrix[10] = -(f + n) / (f - n);
matrix[11] = -1;
matrix[14] = -(2 * f * n) / (f - n);
matrix[15] = 0;
return matrix;
}
///////////////////////////////////////////////////////////////////////////////
// return a symmetric perspective frustum with 4 params similar to
// gluPerspective() (vertical field of view, aspect ratio, near, far)
///////////////////////////////////////////////////////////////////////////////
Matrix4 ModelGL::setFrustum(float fovY, float aspectRatio, float front, float back)
{
float tangent = tanf(fovY/2 * DEG2RAD); // tangent of half fovY
float height = front * tangent; // half height of near plane
float width = height * aspectRatio; // half width of near plane
// params: left, right, bottom, top, near, far
return setFrustum(-width, width, -height, height, front, back);
}glRotatef()
glTranslatef() glScalef()
///////////////////////////////////////////////////////////////////////////////
// set a orthographic frustum with 6 params similar to glOrtho()
// (left, right, bottom, top, near, far)
///////////////////////////////////////////////////////////////////////////////
Matrix4 ModelGL::setOrthoFrustum(float l, float r, float b, float t, float n, float f)
{ (m0, m1, m2), (m4, m5, m6) and (m8, m9, m10)(m12, m13, m14)
Matrix4 matrix;
matrix[0] = 2 / (r - l);
matrix[5] = 2 / (t - b);
matrix[10] = -2 / (f - n);
matrix[12] = -(r + l) / (r - l);
matrix[13] = -(t + b) / (t - b);
matrix[14] = -(f + n) / (f - n);
return matrix;
}
... P1=(3,4) à P2=(20,18)
Xmin = 5, Xmax = 10, Ymin = 7, Ymax = 13,
Xmin = 2, Xmax = 10, Ymin = 10, Ymax = 17,
Xmin = 2, Xmax = 10, Ymin = 10, YmaxP1=(3,4) à P2=(20,18) = 17,
P1=(3,4) à P2=(20,18) P1=(15,11) à P2=(1,3)
// how to pass projection matrx to OpenGL
Matrix4 projectionMatrix = setFrustum(l, r, b, t, n, f);
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(matrixProjection.get());
(m0, m1, m2) : +X axis, left vector, (1, 0, 0) by default
(m4, m5, m6) : +Y axis, up vector, (0, 1, 0) by default
(m8, m9, m10) : +Z axis, forward vector, (0, 0, 1) by default
...
function rotacionar(x, y, radianos) {
var graus = radianos * Math.PI / 180;
var seno = Math.sin(graus);
var coseno = Math.cos(graus);
x += 98;
return {
x: parseInt(x * coseno + y * seno),
y: parseInt(y * coseno - x * seno),
}export default class App extends Component {
state = { retorno: false }
async function req(){
//requisicao feita aqui com retorno
//.then seta retorno = true
}
render() {
if(!this.state.retorno){
//se o retorno for false ele retorna qualquer coisa que você queira
return({/* qualquer coisa aqui */});
}
//se for true ele vai retornar o render normal
return();
}
}
export default class App extends Component {
state = { requisicao: null }
funcaoDeRequisicao = async () => {
//aqui faz a requisicao e seta o estado
}
return requisicao && <Text>TESTE</Text>
}
return
export default class App extends Component {
state = { retorno: false }
async function req(){
//requisicao feita aqui com retorno
//.then seta retorno = true
}
render() {
if(!this.state.retorno){
//se o retorno for false ele retorna qualquer coisa que você queira
return(){/* qualquer coisa aqui */};
}
//se for true ele vai retornar o render normal
return();
}
}
| [
"noreply@github.com"
] | gabrielferrazduque.noreply@github.com |
bb01a83759a5d995a22540a0f4b5198f0254d95a | 3e3975ad03027b88f0dd9e263f3cb20db645683f | /source/StackDefinition.h | 3af002547ab1d3418417f42fbaf2a0b0eef3da7e | [] | no_license | srgn08/Prefix-Postfix-Infix | 928127c4b9fdab87966bc0b86f4138a74b75acce | f62bfcb936f667ea810cbee61ae35216d9fdff32 | refs/heads/master | 2020-03-21T13:03:42.256369 | 2018-06-25T11:29:11 | 2018-06-25T11:29:11 | 138,585,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 373 | h | #ifndef UNTITLED3_STACKDEFINITION_H
#define UNTITLED3_STACKDEFINITION_H
#include <iostream>
#include <string.h>
#include <fstream>
#include <string>
using namespace std;
class StackDefinition {
public:
string stack[100];
int top;
StackDefinition();
void push_element(string element);
string pop_element();
};
#endif //UNTITLED3_STACKDEFINITION_H
| [
"sergentopcu08@gmail.com"
] | sergentopcu08@gmail.com |
b06410bc117d18b01e8df9dd70f9f52e74ef19e8 | 0cb37a1b2b2d61e7eddaa9957d5509dc00d9e920 | /src/CQIllustratorShapeGaussianFilter.h | 0d05b426b7a77f81df92015e336d878f7bc32e3d | [
"MIT"
] | permissive | QtWorks/CQIllustrator | f30ad9e15defab24c2778e59a2fb41c8604e2722 | da34c5f487bd629d82786e908c45b3b273a585bc | refs/heads/master | 2020-05-03T23:33:08.894874 | 2019-03-09T12:51:00 | 2019-03-09T12:51:00 | 178,867,703 | 1 | 0 | null | 2019-04-01T13:19:42 | 2019-04-01T13:19:42 | null | UTF-8 | C++ | false | false | 343 | h | #ifndef CQIllustratorShapeGaussianFilter_H
#define CQIllustratorShapeGaussianFilter_H
#include <CQIllustratorShapeFilter.h>
class CQIllustratorShapeGaussianFilter : public CQIllustratorShapeFilter {
public:
CQIllustratorShapeGaussianFilter(double std_dev=1.0) :
std_dev_(std_dev) {
}
private:
double std_dev_ { 1.0 };
};
#endif
| [
"colinw@nc.rr.com"
] | colinw@nc.rr.com |
3263bef40569eef85e37ff34e666800f379e58d0 | 708282478011bd60c9734362f6db52f6a0344c5b | /Lab9/l9_qns5alt.cpp | ee8d7b3235213659fb48538e167b54f860cf455a | [] | no_license | Binamra7/LabAssignment | a1226cafa1f7ac1dc5141c6a352ac0e61131e968 | e8ba8a179bcbb625f6cdb6c61de88ca8d569597f | refs/heads/main | 2023-08-15T04:09:50.757475 | 2021-10-03T15:18:37 | 2021-10-03T15:18:37 | 375,080,710 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 292 | cpp | #include<conio.h>
#include<stdio.h>
int digitSum(int n)
{
int sum=0;
while(n)
{
sum+=n%10;
n/=10;
}
return sum;
}
int main()
{
int a,sum=0;
printf("Enter a number:");
scanf("%d",&a);
printf("The sum is:%d",digitSum(a));
return 0;
}
| [
"binamra7khadka6@gmail.com"
] | binamra7khadka6@gmail.com |
6feab6665da5aaa780f3b4590c119902f2e212fd | 69c0c4044aadbf6b66e79ad433dd11cd213e298e | /cooking/examples/LoRaWAN/LoRaWAN_01a_configure_module_868.cpp | 9f228c0dac27a8da9f507bc463a1e79fb542e71b | [] | no_license | lancezhangsf/LorawanSensorGateway | c185f024aee6eadfb9ccc00ac1cc4d2302aa2208 | 593805b9bea725d08f7c2e6a6bb4a43b4d984932 | refs/heads/master | 2021-01-11T05:48:20.558078 | 2016-07-26T14:37:49 | 2016-07-26T14:37:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,937 | cpp | /*
* ------ LoRaWAN Code Example --------
*
* Explanation: This example shows how to configure the module
* and all general settings related to back-end registration
* process.
*
* Copyright (C) 2015 Libelium Comunicaciones Distribuidas S.L.
* http://www.libelium.com
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*
* Version: 0.4
* Design: David Gascon
* Implementation: Luismi Marti, Ruben Martin
*/
#include "arduPiLoRaWAN.h"
//////////////////////////////////////////////
uint8_t sock = SOCKET0;
//////////////////////////////////////////////
// Device parameters for Back-End registration
////////////////////////////////////////////////////////////
char DEVICE_EUI[] = "0102030405060708";
char DEVICE_ADDR[] = "05060708";
char NWK_SESSION_KEY[] = "01020304050607080910111213141516";
char APP_SESSION_KEY[] = "000102030405060708090A0B0C0D0E0F";
char APP_KEY[] = "000102030405060708090A0B0C0D0E0F";
////////////////////////////////////////////////////////////
// variable
uint8_t error;
void setup()
{
printf("LoRaWAN example - Module configuration\n");
//////////////////////////////////////////////
// 1. switch on
//////////////////////////////////////////////
error = LoRaWAN.ON(sock);
// Check status
if( error == 0 )
{
printf("1. Switch ON OK\n");
}
else
{
printf("1. Switch ON error = %d\n", error);
}
//////////////////////////////////////////////
// 2. Reset to factory default values
//////////////////////////////////////////////
error = LoRaWAN.factoryReset();
// Check status
if( error == 0 )
{
printf("2. Reset to factory default values OK\n");
}
else
{
printf("2. Reset to factory error = %d\n", error);
}
//////////////////////////////////////////////
// 3. Set/Get Device EUI
//////////////////////////////////////////////
// Set Device EUI
error = LoRaWAN.setDeviceEUI(DEVICE_EUI);
// Check status
if( error == 0 )
{
printf("3.1. Set Device EUI OK\n");
}
else
{
printf("3.1. Set Device EUI error = %d\n", error);
}
// Get Device EUI
error = LoRaWAN.getDeviceEUI();
// Check status
if( error == 0 )
{
printf("3.2. Get Device EUI OK. ");
printf("Device EUI: %s\n",LoRaWAN._devEUI);
}
else
{
printf("3.2. Get Device EUI error = %d\n", error);
}
//////////////////////////////////////////////
// 4. Set/Get Device Address
//////////////////////////////////////////////
// Set Device Address
error = LoRaWAN.setDeviceAddr(DEVICE_ADDR);
// Check status
if( error == 0 )
{
printf("4.1. Set Device address OK\n");
}
else
{
printf("4.1. Set Device address error = %d\n", error);
}
// Get Device Address
error = LoRaWAN.getDeviceAddr();
// Check status
if( error == 0 )
{
printf("4.2. Get Device address OK. ");
printf("Device address: %s\n", LoRaWAN._devAddr);
}
else
{
printf("4.2. Get Device address error = %d\n", error);
}
//////////////////////////////////////////////
// 5. Set Network Session Key
//////////////////////////////////////////////
error = LoRaWAN.setNwkSessionKey(NWK_SESSION_KEY);
// Check status
if( error == 0 )
{
printf("5. Set Network Session Key OK\n");
}
else
{
printf("5. Set Network Session Key error = %d\n", error);
}
//////////////////////////////////////////////
// 6. Set Application Session Key
//////////////////////////////////////////////
error = LoRaWAN.setAppSessionKey(APP_SESSION_KEY);
// Check status
if( error == 0 )
{
printf("6. Set Application Session Key OK\n");
}
else
{
printf("6. Set Application Session Key error = %d\n", error);
}
//////////////////////////////////////////////
// 7. Set retransmissions for uplink confirmed packet
//////////////////////////////////////////////
// set retries
error = LoRaWAN.setRetries(7);
// Check status
if( error == 0 )
{
printf("7.1. Set Retransmissions for uplink confirmed packet OK\n");
}
else
{
printf("7.1. Set Retransmissions for uplink confirmed packet error = %d\n", error);
}
// Get retries
error = LoRaWAN.getRetries();
// Check status
if( error == 0 )
{
printf("7.2. Get Retransmissions for uplink confirmed packet OK. \n");
printf("TX retries: %d\n", LoRaWAN._retries);
}
else
{
printf("7.2. Get Retransmissions for uplink confirmed packet error = %d\n", error);
}
//////////////////////////////////////////////
// 8. Set application key
//////////////////////////////////////////////
error = LoRaWAN.setAppKey(APP_KEY);
// Check status
if( error == 0 )
{
printf("8. Application key set OK\n");
}
else
{
printf("8. Application key set error = %d\n", error);
}
//////////////////////////////////////////////
// 9. Channel configuration. (Recomemnded)
// Consult your Network Operator and Backend Provider
//////////////////////////////////////////////
// Set channel 3 -> 867.1 MHz
// Set channel 4 -> 867.3 MHz
// Set channel 5 -> 867.5 MHz
// Set channel 6 -> 867.7 MHz
// Set channel 7 -> 867.9 MHz
uint32_t freq = 867100000;
for (int ch = 3; ch <= 7; ch++)
{
error = LoRaWAN.setChannelFreq(ch, freq);
freq += 200000;
// Check status
if( error == 0 )
{
printf("9. Application key set ch=%d - freq=%d OK\n",ch ,freq);
}
else
{
printf("9. Application key set error = %d\n", error);
}
}
//////////////////////////////////////////////
// 10. Set Duty Cycle for specific channel. (Recomemnded)
// Consult your Network Operator and Backend Provider
//////////////////////////////////////////////
for (uint8_t ch = 0; ch <= 2; ch++)
{
error = LoRaWAN.setChannelDutyCycle(ch, 33333);
// Check status
if( error == 0 )
{
printf("10. Duty cycle channel %d set OK\n", ch);
}
else
{
printf("10. Duty cycle channel %d set error = %d\n", ch, error);
}
}
for (uint8_t ch = 3; ch <= 7; ch++)
{
error = LoRaWAN.setChannelDutyCycle(ch, 40000);
// Check status
if( error == 0 )
{
printf("10. Duty cycle channel %d set OK\n", ch);
}
else
{
printf("10. Duty cycle channel %d set error = %d\n", ch, error);
}
}
//////////////////////////////////////////////
// 11. Set Data Range for specific channel. (Recomemnded)
// Consult your Network Operator and Backend Provider
//////////////////////////////////////////////
for (int ch = 0; ch <= 7; ch++)
{
error = LoRaWAN.setChannelDRRange(ch, 0, 5);
// Check status
if( error == 0 )
{
printf("11. Data rate range channel %d set OK\n", ch);
}
else
{
printf("11. Data rate range channel %d set error = %d\n", ch, error);
}
}
//////////////////////////////////////////////
// 12. Set Data rate range for specific channel. (Recomemnded)
// Consult your Network Operator and Backend Provider
//////////////////////////////////////////////
for (int ch = 0; ch <= 7; ch++)
{
error = LoRaWAN.setChannelStatus(ch, (char*)"on");
// Check status
if( error == 0 )
{
printf("12. Channel %d status set OK\n", ch);
}
else
{
printf("12. Channel %d status set error = %d\n", ch, error);
}
}
//////////////////////////////////////////////
// 13. Save configuration
//////////////////////////////////////////////
error = LoRaWAN.saveConfig();
// Check status
if( error == 0 )
{
printf("13. Save configuration OK\n");
}
else
{
printf("13. Save configuration error = %d\n", error);
}
printf("------------------------------------\n");
printf("Now the LoRaWAN module is ready for\n");
printf("joining networks and send messages.\n");
printf("Please check the next examples...\n");
printf("------------------------------------\n");
}
void loop()
{
// do nothing
}
//////////////////////////////////////////////
// Main loop setup() and loop() declarations
//////////////////////////////////////////////
int main (){
setup();
while(1){
loop();
}
return (0);
}
//////////////////////////////////////////////
| [
"m.talhabuyukakkaslar@Ms-MacBook-Pro.local"
] | m.talhabuyukakkaslar@Ms-MacBook-Pro.local |
ab61d93baea2fc12727ede44b5f4f943a2a7121c | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/0d/99b9f5a58705e8/main.cpp | bb42b7bc428b25b853655474fe5fc84cfaf39aa3 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,613 | cpp | #include <tuple>
#include <array>
#include <utility>
#include <type_traits>
double f1(double x)
{
return x * 2;
}
double f2(const std::tuple<double>& x)
{
return std::get<0>(x) * 2;
}
template<std::size_t N>
struct apply_impl {
template<class F, class Tuple, class... TParams>
static auto apply(F&& fn, Tuple&& t, TParams&&... args)
-> decltype(
apply_impl<N - 1>::apply(
std::forward<F>(fn), std::forward<Tuple>(t),
std::get<N - 1>(std::forward<Tuple>(t)),
std::forward<TParams>(args)...
))
{
return apply_impl<N - 1>::apply(
std::forward<F>(fn), std::forward<Tuple>(t),
std::get<N - 1>(std::forward<Tuple>(t)),
std::forward<TParams>(args)...
);
}
};
template<>
struct apply_impl<0> {
template<class F, class Tuple, class... TParams>
static auto apply(F&& fn, Tuple&&, TParams&&... args)
-> decltype(std::forward<F>(fn)(std::forward<TParams>(args)...))
{
return std::forward<F>(fn)(std::forward<TParams>(args)...);
}
};
template<class F, class Tuple>
auto apply(F&& fn, Tuple&& t)
-> decltype(apply_impl<
std::tuple_size<typename std::decay<Tuple>::type>::value
>::apply(std::forward<F>(fn), std::forward<Tuple>(t)))
{
return apply_impl<
std::tuple_size<typename std::decay<Tuple>::type>::value
>::apply(std::forward<F>(fn), std::forward<Tuple>(t));
}
template<class Fn, class TupleArr,
class = decltype(std::declval<Fn>()(
std::declval<typename TupleArr::value_type>()))>
void tuple_array_map(Fn f, const TupleArr& arr)
{
for (auto i = 0; i < arr.size(); ++i)
static_cast<void>(f(arr[i]));
}
template<class Fn, class TupleArr,
class = decltype(apply(std::declval<Fn>(),
std::declval<typename TupleArr::value_type>())),
class = void>
void tuple_array_map(Fn f, const TupleArr& arr)
{
tuple_array_map([&](const typename TupleArr::value_type& t) {
return apply(f, t);
}, arr);
}
int main()
{
std::array<std::tuple<double>, 5> tuples = {
std::make_tuple(1),
std::make_tuple(2),
std::make_tuple(3),
std::make_tuple(4),
std::make_tuple(5)
};
// "apply" unpacks a tuple into arguments to a function
apply(f1, tuples[0]);
// this call produces an ambiguity one level down under clang
tuple_array_map(f1, tuples);
// this call directly produces an ambiguity under clang
tuple_array_map(f2, tuples);
}
| [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
fa6f33da5065d8ad4d6164185854a6c80ee11dae | 710ac369ce06c8648ab7b8de905ca68b6fcb30da | /CPP/Finished/Problem140_WordBreakII.cpp | 2c473511f2a3378e0a7c8690363d3836216d894e | [] | no_license | XuanShawnLi/LeetCode | d268b1623ab311ae75d0896b71176a484e1f99f7 | a7ff2c37de71ef1f82f78f31d862738820630730 | refs/heads/master | 2021-01-01T06:38:36.274615 | 2015-04-27T21:52:19 | 2015-04-27T21:52:19 | 31,913,092 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,873 | cpp | /*
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].
A solution is ["cats and dog", "cat sand dog"].
*/
#include<iostream>
#include<tr1/unordered_set>
#include<vector>
using namespace std;
using namespace std::tr1;
class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
vector<string> result;
int n=s.length();
if(n==0){return result;}
vector< vector<int> > dp;
for(int i=0;i<=n;i++){vector<int> tmp; dp.push_back(tmp);}
dp[n].push_back(-1);//tail element must be non empty
for(int i=n-1;i>=0;i--){
for(int l=n-i;l>=1;l--){
if(not(dp[i+l].empty()) and dict.count(s.substr(i,l))==1){
dp[i].push_back(l);
}
}
}
if(dp[0].empty()){return result;}
ComposeString(s,dp,result);
return result;
}
void ComposeString(string s,vector< vector<int> >& dp, vector<string> &result){
int n=dp[0].size();
for(int i=0;i<n;i++){
int l=dp[0][i];
ComposeString_sub(s,dp,s.substr(0,l),l,result);
}
}
void ComposeString_sub(string s,vector< vector<int> > &dp, string previous, int start, vector<string> &result){
if(start==s.length()){result.push_back(previous);return;}
int n=dp[start].size();
for(int i=0;i<n;i++){
int l=dp[start][i];
ComposeString_sub(s,dp,previous+" "+s.substr(start,l),start+l,result);
}
}
};
int main(){
Solution s;
string word="catsanddog";
unordered_set<string> dict;
dict.insert("cat");dict.insert("cats"),dict.insert("and");
dict.insert("sand");dict.insert("dog");
vector<string> result=s.wordBreak(word,dict);
for(int i=0;i<result.size();i++){
cout<<"|"<<result[i]<<"|"<<endl;
}
}
| [
"xuanli1981@gmail.com"
] | xuanli1981@gmail.com |
b1a0c5c0df1561aa78a4f6c06560ad9be23fe1cd | 3ca6b3b6155f791abc816e0376a688bc63a1f656 | /testtree/tree.cc | 2f81b265a3f46bb056e4a9a2a479d1bb74465656 | [] | no_license | stellawroblewski/Homework5-Trees | 1e432546e0db08928091bd57c8d2e7928bd49c68 | 5a32046e5fabaa8acd402fb796f849b367c31cea | refs/heads/master | 2020-04-03T12:49:06.072169 | 2018-10-29T21:41:13 | 2018-10-29T21:41:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,005 | cc | #include "tree.hh"
#define DEBUG
#include <cassert>
//////////////////////////////////////////////////////////////////////////////
// create_tree allocates space for a new tree node and fills it with the given
// data parameters. By default, the tree is a leaf, so its children point to
// nullptr, but you may override with actual pointers to other nodes.
tree_ptr_t create_tree(const key_t& key,
const value_t& value,
tree_ptr_t left,
tree_ptr_t right){
tree_ptr_t t = new Tree({key, value, left, right}); //allocate space in heap for a new tree struct, t
return t;
}
//////////////////////////////////////////////////////////////////////////////
// Deallocate all space consumed by this tree and its children.
void destroy_tree(tree_ptr_t tree)
{
if (tree == nullptr){ //recursively move through and delete all trees
return;}
destroy_tree(tree->left_);
destroy_tree(tree->right_);
delete tree;
tree = nullptr;
}
//////////////////////////////////////////////////////////////////////////////
// path_to: return a string representing the path taken from a given tree root
// to a given key in the tree. For each left child taken along the path, the
// string contains an 'L' character, and 'R' for a right child, in order.
// So for example for the following tree (only keys depicted, values omitted):
/*
126
/ \
/ \
-5 12
/ \ /
12 6 3
/
9
*/
// path_to(tree, 9) will return "LRL", path_to(tree, 3) will return "RL", and
// path_to(126) will return "".
// If the key isn't found in the tree, path_to may abort the program using an
// assert() or exit() call.
//
// If multiple matches to key exist in the tree, return the path to the
// leftmost match. For the tree above, path_to(tree, 12) returns "LL".
bool is_key_in_tree(tree_ptr_t tree, key_t k){
if ((tree->left_ != nullptr) && is_key_in_tree(tree->left_, k) == true){
return true; //to find leftmost;
}
else{
if (tree->key_ == k){ //check if root
return true;
}
else if ((tree->right_ != nullptr) && is_key_in_tree(tree->right_, k) == true){
return true; //traverse right
}
else{
return false; //return false if not in tree;
}
}
}
std::string path_to(tree_ptr_t t, key_t key){
std::string string_path = "";
bool is_key = is_key_in_tree(t, key);
assert(is_key == true);
if (t->left_ != nullptr && (is_key_in_tree(t->left_, key) == true)){
string_path += 'L' + path_to(t->left_, key);
}
else if (t->key_ == key){
return string_path;
}
else if(t->right_ != nullptr && (is_key_in_tree(t->right_, key) == true)){
string_path += 'R' + path_to(t->right_, key);
}
return string_path;
}
//////////////////////////////////////////////////////////////////////////////
// node_at: Follow a path from a given root node and return the node that is
// at the end of the path. For example, for the root of the tree above,
// node_at("LR") will return a pointer to the node whose key is 6.
// If the path leads to an invalid or empty child, or contains any character
// other than 'L' or 'R', return nullptr (don't crash)
tree_ptr_t node_at(tree_ptr_t tree, std::string path){
tree_ptr_t location = tree;
if (path == ""){
return location; //return root ptr
}
else{
for (char & c : path){ //for all characters in the given path
if (location == nullptr){//check for nullptr
location = nullptr;
break;
}
else if (c == 'L'){ //if char is L the location now points from its current to the left of current
location = location->left_;
}
else if (c == 'R'){//if char is R the location now points from its current to the right of he current
location = location->right_;
}
}
}
return location;
}
| [
"noreply@github.com"
] | stellawroblewski.noreply@github.com |
99893b37937b8cb9811cf777b3b5f9f9eb5cd549 | 4d6bf26f4d9a43082f87e177c1a2ac6c9662c288 | /Chapter 15/Programming Challenges/13/circle.h | e397d2e1be1d3f4bd2c230b8f1be24589fecc3b1 | [] | no_license | Miao4382/Starting-Out-with-Cplusplus | 08d13d75fdb741be59a398b76275c5ee394840ca | dd3a1eadcf403ae57a68183987fc24fbfac0517f | refs/heads/master | 2020-05-24T23:22:49.978761 | 2019-05-20T18:40:01 | 2019-05-20T18:40:01 | 187,513,299 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 482 | h | #ifndef CIRCLE_H
#define CIRCLE_H
#include "basic_shape.h"
class Circle : public BasicShape
{
private:
int center_x_;
int center_y_;
double radius_;
public:
/* Constructor */
// initialize x, y and radius of the circle, will also call CalcArea() to set area_
Circle(int x, int y, int r);
/* Accessor */
int GetCenterX() const
{ return center_x_; }
int GetCenterY() const
{ return center_y_; }
/* Function */
virtual void CalcArea();
};
#endif | [
"33183267+Miao4382@users.noreply.github.com"
] | 33183267+Miao4382@users.noreply.github.com |
953191fb28516df3ec2b2e08e06772eb1552c73f | 1f5b52bc0f7744abe32ab1c65ceec29e5dacb9bb | /testjmp.cpp | d8fedfc1e0aef232c287b61802670eb593a04667 | [] | no_license | szqh97/apue | daff2551c24b91a02cf2ffe19fb286f4eb83a9f4 | 54385696fe1b6d356dd160026806012e82b98874 | refs/heads/master | 2016-09-06T15:18:26.933268 | 2012-06-16T01:57:01 | 2012-06-16T01:57:01 | 4,681,699 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,736 | cpp | /*
* =======================================================================
* Filename: testjmp.cpp
* Description:
* Version: 1.0
* Created: 2012年04月26日 22时18分29秒
* Revision: none
* Compiler: gcc
* Author: szqh97 (), szqh97@163.com
* Company: szqh97
* =======================================================================
*/
#include <iostream>
#include <setjmp.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
jmp_buf jmpbuffer;
void g()
{
cout << "in g()" << endl;
longjmp(jmpbuffer, 2);
}
void f()
{
cout << "in f() " << endl;
g();
cout << "leave f()" << endl;
}
int globval;
int main ( int argc, char *argv[] )
{
int autoval;
register int regival;
volatile int volaval;
static int statval;
cout << "begin" << endl;
globval = 90;
autoval = 91;
regival = 92;
volaval = 93;
statval = 94;
int i = setjmp(jmpbuffer);
cout << "setjmpbuffer return code: " << i << endl;
if (i == 2)
{
cout << "error code: " << 1 << endl;
cout << "globval = " << globval << ";";
cout << "autoval = " << autoval << ";";
cout << "regival = " << regival << ";";
cout << "volaval = " << volaval << ";";
cout << "statval = " << statval << ";"<< endl;
return 0;
}
globval = 0;
autoval = 1;
regival = 2;
volaval = 3;
statval = 4;
cout << "globval = " << globval << ";";
cout << "autoval = " << autoval << ";";
cout << "regival = " << regival << ";";
cout << "volaval = " << volaval << ";";
cout << "statval = " << statval << ";"<< endl;
f();
return 0;
} /* ---------- end of function main ---------- */
| [
"szqh97@163.com"
] | szqh97@163.com |
ac269066c384edd45110c90fe16ac7ce568e87f3 | edba049dd6d7bde0af33988791be9e46f8143b8e | /dp_game.cpp | b0ff98ff917ca8a2b3a078d2c49318cdc2f083ab | [] | no_license | shuvokhalid173/algorithm-implementation | f5c552618f70ff44aa6b823f0ec18e69dc86e704 | 43b7468fc453b79e68f52586bb1b0b07afcabb6b | refs/heads/master | 2020-06-20T04:25:20.108859 | 2016-12-10T13:26:04 | 2016-12-10T13:26:04 | 74,883,965 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 630 | cpp | #include <bits/stdc++.h>
using namespace std;
const int N = 12345;
int dp[N];
void game () {
dp[0] = 0;
dp[1] = dp[2] = 1;
for (int i = 3; i < N; i++) {
if (!dp[i - 2] || !dp[i - 1])
dp[i] = 1;
else dp[i] = 0;
}
}
int dpp[1234];
set < int > st;
set < int > :: iterator it;
void grundy_number () {
dpp[0] = 0;
dpp[1] = 1;
for (int i = 2; i < 1234; i++) {
int x = dpp[i - 1];
int y = dpp[i - 2];
for (int ii = 0; ii <= N; ii++) {
if (ii != x && ii != y) {
dpp[i] = ii;
break;
}
}
}
}
int main () {
int n;
grundy_number ();
while (cin >> n) {
cout << dpp[n] << endl;
}
}
| [
"shuvokhalid173@gmail.com"
] | shuvokhalid173@gmail.com |
5cb51df1eb6fcdd0345e2c84c9c55bc02fef57b4 | e82e6b81a044c6db6bf2df44868cb1d35d865f65 | /Source Code for Experiments/Dijkstra/Single-GPU/Dijkstra_Basic/dijkstra-classic-v2.h | 63c847d1a3da1b9978434da3b0705ebb2a9727aa | [
"MIT"
] | permissive | kf4ayt/MTSU_Thesis | 66babd4a62e6148dd55e85b7b9f02df93d08f178 | de3abbe714eeabb722be843d29ab4177a476c276 | refs/heads/main | 2023-08-20T11:28:13.629128 | 2021-10-18T17:50:28 | 2021-10-18T17:50:28 | 358,495,885 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,221 | h |
/**********************************************************************************
Copyright 2021 Charles W. Johnson
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.
**********************************************************************************/
//
// Filename: dijkstra-classic-v2.h
// Author: Charles W Johnson
// Description: Header file for C / C++ program for Dijkstra's shortest path
// algorithm using a CSR representation of the graph
//
#ifndef DIJKSTRA_CLASSIC_V2_H_
#define DIJKSTRA_CLASSIC_V2_H_
#include <chrono>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include "Dijkstra_custom_data_structures.h"
#define INF 255
using namespace std;
/* ---- Function Declarations ---- */
// Name: dijkstra_classic_cpu
//
// Description: Runs the Dijkstra algorithm on the given graph
//
//
int dijkstra_classic_cpu(int* V, int* E, short int* W, distPred* dp, int num_vertices, int num_edges, int source);
// Name: getMinVertex
//
// Description: Returns the position in Q that contains the vertex with the min distance
//
//
int getMinVertex(vector<int>& Q, distPred* dp);
#endif /* DIJKSTRA_CLASSIC_V2_H_ */
| [
"noreply@github.com"
] | kf4ayt.noreply@github.com |
84558db4359d3b64b05f5de130b66763643dbaff | 3883f40753e36d3d91a1f9a4417f76ffcb11266a | /PIMC++/src/Actions/ST2WaterClass.h | 28a3143cccdebaef197cdb94bf5123fcde98c0d1 | [] | no_license | meng-cheng/pimcplusplus | 23ea9d318b6be23950e6955eb59abae55f8cb019 | 1ab955c6c4e0bd2f553f228b1e66b1606989e832 | refs/heads/master | 2021-05-28T20:57:03.713359 | 2012-06-07T17:32:53 | 2012-06-07T17:32:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,675 | h | /////////////////////////////////////////////////////////////
// Copyright (C) 2003-2006 Bryan Clark and Kenneth Esler //
// //
// 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. //
// For more information, please see the PIMC++ Home Page: //
// http://pathintegrals.info //
/////////////////////////////////////////////////////////////
#ifndef ST2WATER_CLASS_H
#define ST2WATER_CLASS_H
#include "ActionBase.h"
/// The KineticClass calculates the kinetic part of the action. This
/// is the "spring term", of the form
/// \f$ K \equiv \left(4\pi\lambda\tau\right)^{-\frac{ND}{2}}
/// \exp\left[-\frac{(R-R')^2}{4\lambda\tau}\right] \f$
class ST2WaterClass : public ActionBaseClass
{
public:
void Read (IOSectionClass &in);
double Action (int startSlice, int endSlice, const Array<int,1> &activeParticles, int level);
double SingleAction (int slice1, int slice2,
const Array<int,1> &activeParticles, int level);
double d_dBeta (int slice1, int slice2, int level);
string GetName();
double EField (Array<int,1> &activeMol, int startSlice, int endSlice, int level);
void EFieldVec (int molIndex, dVec &Efield, double &Emag, int slice, int level);
void BackSub(Array<double,2> &A,Array<double,1> &X,int N, int C);
void RowScale(Array<double,2> &A,int n,double scale,int C);
void Diff(Array<double,2> &A,int n,int m, double s, int C);
double OOSeparation (int slice,int ptcl1,int ptcl2);
double S(double r);
double RotationalKinetic(int startSlice, int endSlice, const Array<int,1> &activeParticles,int level);
double RotationalEnergy(int startSlice, int endSlice, int level);
void GetAngles(dVec disp, double &theta, double &phi);
double CalcEnergy(double reftheta,double dtheta, double dphi);
double SineOfPolar(dVec coords);
dVec COMVelocity (int slice1,int slice2,int ptcl);
dVec COMCoords (int slice, int ptcl);
dVec Displacement(int slice1, int slice2, int ptcl1, int ptcl2);
int FindCOM(int ptcl);
double ProtonKineticAction (int slice1, int slice2, const Array<int,1> &changedParticles, int level);
double ProtonKineticEnergy (int slice1, int slice2, int level);
double SecondProtonKineticAction(int startSlice, int endSlice, const Array<int,1> &activeParticles,int level);
double SecondProtonKineticEnergy(int startSlice, int endSlice, int level);
double dotprod(dVec vec1, dVec vec2, double mag);
int FindOtherProton(int ptcl);
double NewRotKinAction(int startSlice, int endSlice, const Array<int,1> &activeParticles, int level);
double NewRotKinEnergy(int startSlice, int endSlice, int level);
double FixedAxisAction(int startSlice, int endSlice, const Array<int,1> &activeParticles, int level);
double FixedAxisEnergy(int startSlice, int endSlice, int level);
dVec CrossProd(dVec v1, dVec v2);
double Mag(dVec v);
double GetAngle(dVec v1, dVec v2);
dVec Normalize(dVec v);
dVec Scale(dVec v, double scale);
dVec GetBisector(dVec v1, dVec v2);
double CalcPsi(double theta);
ST2WaterClass (PathDataClass &pathData);
};
const double RL = 2.0160;
const double RU = 3.1287;
#endif
| [
"ethan.w.brown@gmail.com"
] | ethan.w.brown@gmail.com |
fc2cbfd71d58e0f1ffe4300409dec6be26a0c125 | adf038a3037f4be1ea1f3b67121a6f64a6025a85 | /cache.cpp | 91b443401895f1c1f9ac7ac837f7b47e97e9876f | [] | no_license | Guid75/showdevant | 1a0ed8113fb33eed8cfadf56a2280646b84de601 | 4fad7642c971b130449491f2e823ff4468b7f48d | refs/heads/master | 2016-09-05T15:41:59.185437 | 2013-08-04T21:20:49 | 2013-08-04T21:20:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,946 | cpp | // Copyright 2013 Guillaume Denry (guillaume.denry@gmail.com)
// This file is part of ShowDevant.
//
// ShowDevant is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ShowDevant 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 ShowDevant. If not, see <http://www.gnu.org/licenses/>.
#include <QStringList>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDateTime>
#include <QVariant>
#include <QDebug>
#include <QMetaType>
#include <QSqlError>
#include <QThread>
#include "commandmanager.h"
#include "command.h"
#include "cache.h"
//#define OFFLINE 1
Cache *Cache::_instance = 0;
Cache &Cache::instance()
{
if (!_instance)
_instance = new Cache();
return *_instance;
}
void Cache::start()
{
thread->start();
}
Cache::Cache() :
QObject()
{
qRegisterMetaType<CacheDataType>("CacheDataType");
connect(&commandMapper, SIGNAL(mapped(QObject *)),
this, SLOT(commandFinished(QObject *)));
thread = new QThread;
this->moveToThread(thread);
}
Cache::~Cache()
{
thread->exit();
delete thread;
}
Cache::SynchronizeAction *Cache::getAction(CacheDataType dataType, const QVariantMap &id) const
{
foreach (SynchronizeAction *action, currentActions) {
if (action->dataType == dataType &&
action->id == id) {
return action;
}
}
return 0;
}
Cache::SynchronizeAction *Cache::getAction(Command *command) const
{
foreach (SynchronizeAction *action, currentActions) {
if (action->commands.indexOf(command) >= 0)
return action;
}
return 0;
}
void Cache::commandFinished(QObject *commandObj)
{
Command *command = qobject_cast<Command*>(commandObj);
Q_ASSERT(command != 0);
SynchronizeAction *action = getAction(command);
Q_ASSERT(action != 0); // an action MUST exists for the command
if (command->httpError())
emit synchronizeFailed(action->dataType, action->id);
else
QMetaObject::invokeMethod(this, action->callbackMethodName.toLocal8Bit(),
Qt::DirectConnection, Q_ARG(QVariantMap, action->id), Q_ARG(JsonParser, command->jsonParser()));
currentActions.removeOne(action);
command->deleteLater();
}
void Cache::parseEpisodes(const QString &showId, int season, const QJsonObject &root, bool detailMode)
{
QJsonObject episodesJson = root.value("episodes").toObject();
foreach (const QString &key, episodesJson.keys()) {
QJsonObject episodeJson = episodesJson.value(key).toObject();
if (episodeJson.isEmpty())
continue;
int episode = episodeJson.value("episode").toString().toInt();
QString title = episodeJson.value("title").toString();
QString description = episodeJson.value("description").toString();
QString number = episodeJson.value("number").toString();
int global = episodeJson.value("global").toString().toInt();
int date = episodeJson.value("date").toDouble();
bool seen = episodeJson.value("has_seen").toString() == "1"; // only valid when are logged
int comments = episodeJson.value("comments").toString().toInt();
QSqlQuery query;
query.prepare("INSERT INTO episode (show_id, season, episode, title, description, number, global, "
"date, seen, comments) "
"VALUES (:show_id, :season, :episode, :title, :description, :number, :global, "
":date, :seen, :comments)");
query.bindValue(":show_id", showId);
query.bindValue(":season", season);
query.bindValue(":episode", episode);
query.bindValue(":title", title);
query.bindValue(":description", description);
query.bindValue(":number", number);
query.bindValue(":global", global);
query.bindValue(":date", date);
query.bindValue(":seen", seen);
query.bindValue(":comments", comments);
if (query.exec())
continue;
// insert failed => it seems the episode already exists so let's just update it
query.prepare("UPDATE episode SET title=:title, description=:description, number=:number, global=:global, "
"date=:date, seen=:seen, comments=:comments WHERE show_id=:show_id AND season=:season AND episode=:episode");
query.bindValue(":show_id", showId);
query.bindValue(":season", season);
query.bindValue(":episode", episode);
query.bindValue(":title", title);
query.bindValue(":description", description);
query.bindValue(":number", number);
query.bindValue(":global", global);
query.bindValue(":date", date);
query.bindValue(":seen", seen);
query.bindValue(":comments", comments);
query.exec();
if (detailMode) {
query.prepare("UPDATE episode SET last_sync_detail=:epoch WHERE show_id=:show_id AND season=:season AND episode=:episode");
query.bindValue(":show_id", showId);
query.bindValue(":season", season);
query.bindValue(":episode", episode);
query.bindValue(":epoch", QDateTime::currentMSecsSinceEpoch() / 1000);
query.exec();
}
}
}
void Cache::tagSeen(const QString &showId, int maxSeason, int maxEpisode)
{
if (!QSqlDatabase::database().transaction()) {
qCritical("Error while beginning a transaction for SQL insertion");
return;
}
QSqlQuery query;
// command successful, we must tag all previous episodes
query.prepare("UPDATE episode SET seen=1 WHERE show_id=:showid AND (season < :season OR (season = :season AND episode <= :episode))");
query.bindValue(":showid", showId);
query.bindValue(":season", maxSeason);
query.bindValue(":episode", maxEpisode);
query.exec();
QSqlDatabase::database().commit();
}
void Cache::parseSeasons(const QString &showId, const JsonParser &json, bool allEpisodes)
{
QJsonObject seasonsJson = json.root().value("seasons").toObject();
if (!QSqlDatabase::database().transaction()) {
qCritical("Error while beginning a transaction for SQL insertion");
return;
}
foreach (const QString &key, seasonsJson.keys()) {
QJsonObject seasonJson = seasonsJson.value(key).toObject();
if (seasonJson.isEmpty())
continue;
int number = seasonJson.value("number").toString().toInt();
parseEpisodes(showId, number, seasonJson, !allEpisodes);
if (allEpisodes) {
// if we refresh all episodes, we can record the current date
QSqlQuery query;
query.prepare("UPDATE season SET last_sync_episode_list=:epoch WHERE show_id=:showid AND number=:number");
query.bindValue(":epoch", QDateTime::currentMSecsSinceEpoch() / 1000);
query.bindValue(":showid", showId);
query.bindValue(":number", number);
query.exec();
}
}
// update the episodes last check date of the show
QSqlDatabase::database().commit();
}
void Cache::parseShowInfos(const QString &showId, const JsonParser &json)
{
QJsonObject showJson = json.root().value("show").toObject();
if (!QSqlDatabase::database().transaction()) {
qCritical("Error while beginning a transaction for SQL insertion");
return;
}
// update the show details
QSqlQuery query;
query.prepare("INSERT OR REPLACE INTO show (show_id, title, description, network, duration, last_sync) "
"VALUES (:show_id, :title, :description, :network, :duration, :last_sync)");
query.bindValue(":show_id", showId);
query.bindValue(":title", showJson.value("title").toString());
query.bindValue(":description", showJson.value("description").toString());
query.bindValue(":network", showJson.value("network").toString());
query.bindValue(":duration", showJson.value("duration").toString().toInt());
query.bindValue(":last_sync", QDateTime::currentMSecsSinceEpoch() / 1000);
query.exec();
// init the "to delete" list
QList<int> toDelete;
query.prepare("SELECT number FROM season WHERE show_id=:show_id");
query.bindValue(":show_id", showId);
query.exec();
while (query.next())
toDelete << query.value("number").toInt();
// make the replace/insertion operations and reduct the "to delete" list
QJsonObject seasonsJson = showJson.value("seasons").toObject();
foreach (const QString &key, seasonsJson.keys()) {
QJsonObject seasonJson = seasonsJson.value(key).toObject();
int number = seasonJson.value("number").toString().toInt();
toDelete.removeOne(number);
query.prepare("REPLACE INTO season (show_id, number, episode_count) "
"VALUES (:show_id, :number, :episode_count)");
query.bindValue(":show_id", showId);
query.bindValue(":number", number);
query.bindValue(":episode_count", seasonJson.value("episodes").toDouble());
query.exec();
}
// delete all seasons that have not been found in the JSON return
foreach (int season, toDelete) {
query.prepare("DELETE FROM season WHERE show_id=:show_id AND season=:season");
query.bindValue(":show_id", showId);
query.bindValue(":season", season);
query.exec();
}
QSqlDatabase::database().commit();
}
void Cache::parseMemberInfos(const JsonParser &json)
{
if (!QSqlDatabase::database().transaction()) {
qCritical("Error while beginning a transaction for SQL insertion");
return;
}
QJsonObject memberJson = json.root().value("member").toObject();
// TODO parse member inner infos
// init the "to delete" list
QStringList toDelete;
QSqlQuery query;
query.prepare("SELECT show_id FROM myshows");
query.exec();
while (query.next())
toDelete << query.value("show_id").toString();
// parse shows
QJsonObject showsJson = memberJson.value("shows").toObject();
for (QJsonObject::const_iterator iter = showsJson.constBegin(); iter != showsJson.constEnd(); iter++) {
QJsonObject showJson = (*iter).toObject();
query.prepare("REPLACE INTO myshows (show_id, title, archive) "
"VALUES (:show_id, :title, :archive)");
query.bindValue(":show_id", showJson.value("url").toString());
query.bindValue(":title", showJson.value("title").toString());
query.bindValue(":archive", showJson.value("archive").toString().toInt());
query.exec();
toDelete.removeOne(showJson.value("url").toString());
}
// delete all shows that have not been found in the JSON return
foreach (const QString &showId, toDelete) {
query.prepare("DELETE FROM myshows WHERE show_id=:show_id");
query.bindValue(":show_id", showId);
query.exec();
}
QSqlDatabase::database().commit();
}
bool Cache::parseAddShow(const QString &showId, const QString &title, const JsonParser &json)
{
if (json.code() == 0) {
// TODO manage error code
return false;
}
if (!QSqlDatabase::database().transaction()) {
qCritical("Error while beginning a transaction for SQL insertion");
return false;
}
QSqlQuery query;
query.prepare("INSERT INTO myshows (show_id, title, archive) "
"VALUES (:show_id, :title, :archive)");
query.bindValue(":show_id", showId);
query.bindValue(":title", title);
query.bindValue(":archive", 0);
query.exec();
QSqlDatabase::database().commit();
return true;
}
bool Cache::parseRemoveShow(const QString &showId, const JsonParser &json)
{
if (json.code() == 0) {
// TODO manage error code
return false;
}
if (!QSqlDatabase::database().transaction()) {
qCritical("Error while beginning a transaction for SQL insertion");
return false;
}
QSqlQuery query;
query.prepare("DELETE FROM myshows WHERE show_id=:show_id");
query.bindValue(":show_id", showId);
query.exec();
QSqlDatabase::database().commit();
return true;
}
void Cache::parseSubtitles(const QString &show, int season, int episode, const JsonParser &json)
{
QJsonObject subtitlesJson = json.root().value("subtitles").toObject();
if (!QSqlDatabase::database().transaction()) {
qCritical("Error while beginning a transaction for SQL insertion");
return;
}
// remove all subtitles for an episode
QSqlQuery query;
query.prepare("DELETE FROM subtitle WHERE show_id=:show_id AND season=:season AND episode=:episode");
query.bindValue(":show_id", show);
query.bindValue(":season", season);
query.bindValue(":episode", episode);
query.exec();
foreach (const QString &key, subtitlesJson.keys()) {
QJsonObject subtitleJson = subtitlesJson.value(key).toObject();
if (subtitleJson.isEmpty())
continue;
QString language = subtitleJson.value("language").toString();
QString source = subtitleJson.value("source").toString();
QString file = subtitleJson.value("file").toString();
QString url = subtitleJson.value("url").toString();
int quality = subtitleJson.value("quality").toDouble();
// TODO smash data if already exists
query.prepare("INSERT INTO subtitle (show_id, season, episode, language, "
"source, file, url, quality) "
"VALUES (:show_id, :season, :episode, "
":language, :source, :file, :url, :quality)");
query.bindValue(":show_id", show);
query.bindValue(":season", season);
query.bindValue(":episode", episode);
query.bindValue(":language", language);
query.bindValue(":source", source);
query.bindValue(":file", file);
query.bindValue(":url", url);
query.bindValue(":quality", quality);
if (!query.exec()) {
qCritical("Insertion failed, the subtitle parsing is stopped");
break;
}
// content?
int subtitleId = query.lastInsertId().toInt();
QJsonObject contentJson = subtitleJson.value("content").toObject();
if (!contentJson.isEmpty()) {
// use a QMap to keep all strings ordered as sent by the webserver
QMap<int,QString> files;
foreach (const QString &key, contentJson.keys()) {
QString v = contentJson.value(key).toString();
if (!v.isEmpty())
files.insert(key.toInt(), v);
}
QMapIterator<int,QString> i(files);
while (i.hasNext()) {
i.next();
query.prepare("INSERT INTO subtitle_content (subtitle_id, file) "
"VALUES (:subtitle_id, :file)");
query.bindValue(":subtitle_id", subtitleId);
query.bindValue(":file", i.value());
query.exec();
}
}
}
// update the episodes last check date of the subtitles
query.prepare("UPDATE episode SET subtitles_last_check_date=:date WHERE show_id=:show_id AND season=:season AND episode=:episode");
query.bindValue(":date", QDateTime::currentMSecsSinceEpoch() / 1000);
query.bindValue(":show_id", show);
query.bindValue(":season", season);
query.bindValue(":episode", episode);
query.exec();
QSqlDatabase::database().commit();
}
void Cache::showInfosCallback(const QVariantMap &id, const JsonParser &json)
{
QString showId = id["showId"].toString();
// TODO: parseShowInfos must return a boolean for potential errors
parseShowInfos(showId, json);
emit synchronized(Data_ShowInfos, id);
}
void Cache::episodesCallback(const QVariantMap &id, const JsonParser &json)
{
QString showId = id["showId"].toString();
parseSeasons(showId, json, id["episode"].isNull());
emit synchronized(Data_Episodes, id);
}
void Cache::memberInfosCallback(const QVariantMap &id, const JsonParser &json)
{
parseMemberInfos(json);
emit synchronized(Data_MemberInfos, id);
}
void Cache::addShowCallback(const QVariantMap &id, const JsonParser &json)
{
if (parseAddShow(id["showId"].toString(), id["title"].toString(), json))
emit showAdded(id["title"].toString());
emit synchronized(Data_AddShow, id);
}
void Cache::removeShowCallback(const QVariantMap &id, const JsonParser &json)
{
// get the title into the database
QSqlQuery query;
query.prepare("SELECT title FROM myshows WHERE show_id=:show_id");
query.bindValue(":show_id", id["showId"]);
query.exec();
QString title;
if (query.next())
title = query.value("title").toString();
if (parseRemoveShow(id["showId"].toString(), json))
emit showRemoved(title);
emit synchronized(Data_RemoveShow, id);
}
void Cache::archiveShowCallback(const QVariantMap &id, const JsonParser &json)
{
// TODO
emit synchronized(Data_ArchiveShow, id);
}
void Cache::watchShowCallback(const QVariantMap &id, const JsonParser &json)
{
if (json.code() == 0) {
// TODO treat errors
emit synchronized(Data_WatchShow, id);
return;
}
tagSeen(id["showId"].toString(), id["season"].toInt(), id["episode"].toInt());
emit synchronized(Data_WatchShow, id);
}
void Cache::subtitlesCallback(const QVariantMap &id, const JsonParser &json)
{
parseSubtitles(id["showId"].toString(), id["season"].toInt(), id["episode"].toInt(), json);
emit synchronized(Data_Subtitles, id);
}
int Cache::synchronizeShowInfos(const QString &showId)
{
qint64 last_sync_epoch = 0;
qint64 expiration = 24 * 60 * 60 * 1000; // one day => TODO customizable
QVariantMap id;
id.insert("showId", showId);
// have we the season in database?
// take the expiration date in account
QSqlQuery query;
query.exec(QString("SELECT last_sync FROM show WHERE show_id='%1'").arg(showId));
if (query.next() && !query.value(0).isNull()) {
last_sync_epoch = query.value(0).toLongLong() * 1000;
}
#ifdef OFFLINE
emit synchronized(Data_ShowInfos, id);
return 0;
#endif
if (QDateTime::currentDateTime().toMSecsSinceEpoch() - last_sync_epoch <= expiration) {
// data are already synchronized, we can use them
emit synchronized(Data_ShowInfos, id);
return 0;
}
// expired data, we need to launch the request if not already done
emit synchronizing(Data_ShowInfos, id);
// is there a current action about it?
SynchronizeAction *action = getAction(Data_ShowInfos, id);
if (action) {
// just wait for the end of it
return 1;
}
// store the synchronize action
action = new SynchronizeAction;
action->dataType = Data_ShowInfos;
action->id = id;
action->callbackMethodName = "showInfosCallback";
Command *command = CommandManager::instance().showsDisplay(showId);
action->commands << command;
currentActions << action;
commandMapper.setMapping(command, command);
connect(command, SIGNAL(finished()), &commandMapper, SLOT(map()));
return 1;
}
int Cache::synchronizeEpisodes(const QString &showId, int season, int episode, bool fullInfo)
{
qint64 last_sync_epoch = 0;
qint64 expiration = 24 * 60 * 60 * 1000; // one day => TODO customizable
QVariantMap id;
id.insert("showId", showId);
id.insert("season", season);
if (episode >= 0)
id.insert("episode", episode);
// have we the season in database?
// take the expiration date in account
QSqlQuery query;
if (episode == -1)
query.prepare("SELECT last_sync_episode_list FROM season WHERE show_id=:show_id AND number=:season");
else
query.prepare("SELECT last_sync_detail FROM episode WHERE show_id=:show_id AND season=:season AND episode=:episode");
query.bindValue(":show_id", showId);
query.bindValue(":season", season);
if (episode >= 0)
query.bindValue(":episode", episode);
query.exec();
if (query.next() && !query.value(0).isNull())
last_sync_epoch = query.value(0).toLongLong() * 1000;
#ifdef OFFLINE
emit synchronized(Data_Episodes, id);
return 0;
#endif
if (QDateTime::currentDateTime().toMSecsSinceEpoch() - last_sync_epoch <= expiration) {
// data are already synchronized, we can use them
emit synchronized(Data_Episodes, id);
return 0;
}
// expired data, we need to launch the request if not already done
emit synchronizing(Data_Episodes, id);
// is there a current action about it?
SynchronizeAction *action = getAction(Data_Episodes, id);
if (action) {
// just wait for the end of it
return 1;
}
// store the synchronize action
action = new SynchronizeAction;
action->dataType = Data_Episodes;
action->id = id;
action->callbackMethodName = "episodesCallback";
Command *command = CommandManager::instance().showsEpisodes(showId, season, episode, !fullInfo, !fullInfo);
action->commands << command;
currentActions << action;
commandMapper.setMapping(command, command);
connect(command, SIGNAL(finished()), &commandMapper, SLOT(map()));
return 1;
}
int Cache::synchronizeMemberInfos()
{
QVariantMap id;
// expired data, we need to launch the request if not already done
emit synchronizing(Data_MemberInfos, id);
// is there a current action about it?
SynchronizeAction *action = getAction(Data_MemberInfos, id);
if (action) {
// just wait for the end of it
return 1;
}
// store the synchronize action
action = new SynchronizeAction;
action->dataType = Data_MemberInfos;
action->id = id;
action->callbackMethodName = "memberInfosCallback";
Command *command = CommandManager::instance().membersInfos();
action->commands << command;
currentActions << action;
commandMapper.setMapping(command, command);
connect(command, SIGNAL(finished()), &commandMapper, SLOT(map()));
return 1;
}
int Cache::addShow(const QString &showId, const QString &title)
{
QVariantMap id;
id.insert("showId", showId);
id.insert("title", title);
// expired data, we need to launch the request if not already done
emit synchronizing(Data_AddShow, id);
// store the synchronize action
SynchronizeAction *action = new SynchronizeAction;
action->dataType = Data_AddShow;
action->id = id;
action->callbackMethodName = "addShowCallback";
Command *command = CommandManager::instance().showsAdd(showId);
action->commands << command;
currentActions << action;
commandMapper.setMapping(command, command);
connect(command, SIGNAL(finished()), &commandMapper, SLOT(map()));
return 1;
}
int Cache::removeShow(const QString &showId)
{
QVariantMap id;
id.insert("showId", showId);
// expired data, we need to launch the request if not already done
emit synchronizing(Data_RemoveShow, id);
// store the synchronize action
SynchronizeAction *action = new SynchronizeAction;
action->dataType = Data_RemoveShow;
action->id = id;
action->callbackMethodName = "removeShowCallback";
Command *command = CommandManager::instance().showsRemove(showId);
action->commands << command;
currentActions << action;
commandMapper.setMapping(command, command);
connect(command, SIGNAL(finished()), &commandMapper, SLOT(map()));
return 1;
}
int Cache::archiveShow(const QString &showId)
{
QVariantMap id;
id.insert("showId", showId);
// expired data, we need to launch the request if not already done
emit synchronizing(Data_ArchiveShow, id);
// store the synchronize action
SynchronizeAction *action = new SynchronizeAction;
action->dataType = Data_ArchiveShow;
action->id = id;
action->callbackMethodName = "archiveShowCallback";
Command *command = CommandManager::instance().showsArchive(showId);
action->commands << command;
currentActions << action;
commandMapper.setMapping(command, command);
connect(command, SIGNAL(finished()), &commandMapper, SLOT(map()));
return 1;
}
int Cache::watchShow(const QString &showId, int season, int episode)
{
QVariantMap id;
id.insert("showId", showId);
id.insert("season", season);
id.insert("episode", episode);
// expired data, we need to launch the request if not already done
emit synchronizing(Data_WatchShow, id);
// store the synchronize action
SynchronizeAction *action = new SynchronizeAction;
action->dataType = Data_WatchShow;
action->id = id;
action->callbackMethodName = "watchShowCallback";
Command *command = CommandManager::instance().membersWatched(showId, season, episode);
action->commands << command;
currentActions << action;
commandMapper.setMapping(command, command);
connect(command, SIGNAL(finished()), &commandMapper, SLOT(map()));
return 1;
}
int Cache::synchronizeSubtitles(const QString &showId, int season, int episode, const QString &language)
{
qint64 last_sync_epoch = 0;
qint64 expiration = 24 * 60 * 60 * 1000; // one day => TODO customizable
QVariantMap id;
id.insert("showId", showId);
id.insert("season", season);
id.insert("episode", episode);
// have we the season in database?
// take the expiration date in account
QSqlQuery query;
query.prepare("SELECT subtitles_last_check_date FROM episode WHERE show_id=:show_id AND season=:season AND episode=:episode");
query.bindValue(":show_id", showId);
query.bindValue(":season", season);
query.bindValue(":episode", episode);
query.exec();
if (query.next() && !query.value(0).isNull())
last_sync_epoch = query.value(0).toLongLong() * 1000;
#ifdef OFFLINE
emit synchronized(Data_Subtitles, id);
return 0;
#endif
if (QDateTime::currentDateTime().toMSecsSinceEpoch() - last_sync_epoch <= expiration) {
// data are already synchronized, we can use them
emit synchronized(Data_Subtitles, id);
return 0;
}
// expired data, we need to launch the request if not already done
emit synchronizing(Data_Subtitles, id);
// is there a current action about it?
SynchronizeAction *action = getAction(Data_Subtitles, id);
if (action) {
// just wait for the end of it
return 1;
}
// store the synchronize action
action = new SynchronizeAction;
action->dataType = Data_Subtitles;
action->id = id;
action->callbackMethodName = "subtitlesCallback";
Command *command = CommandManager::instance().subtitlesShow(showId, season, episode);
action->commands << command;
currentActions << action;
commandMapper.setMapping(command, command);
connect(command, SIGNAL(finished()), &commandMapper, SLOT(map()));
return 1;
}
| [
"guillaume.denry@gmail.com"
] | guillaume.denry@gmail.com |
db3c3c2552d03c1a159843363af695310ec87add | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5631572862566400_0/C++/Janice/3.cpp | 84ea51ba50c9479ab4bb02c61dc92a714c509248 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,902 | cpp | #include <iostream>
#include <unordered_map>
#include <fstream>
using namespace std;
void quickSort(int array[], int start, int end);
int main() {
ifstream testCase ("./C-small-attempt0.in");
ofstream testCaseAns ("./output.txt");
int T = 0;
testCase >> T;
for (int i = 0; i < T; i++) {
int N = 0;
testCase >> N;
int bff[1005];
for (int j = 0; j < N; j++) {
testCase >> bff[j + 1];
}
int ans = 0;
for (int j = 1; j <= N; j++) {
int add[1005] = {0};
int index = j;
int count = 0;
int prev = j;
while (add[index] != 1) {
// printf("%d ", index);
add[index] = 1;
count++;
prev = index;
index = bff[index];
}
// printf("\nindex = %d prev = %d", index, prev);
if (bff[index] == prev) {
// printf("type2 ");
int end = 0;
while (!end) {
end = 1;
for (int k = 1; k <= N; k++) {
if (add[k] == 0 && bff[k] == prev) {
// printf("%d ", k);
add[k] = 1;
count++;
prev = k;
end = 0;
break;
}
}
}
if (ans < count) {
ans = count;
}
}
else if (index == j && ans < count) {
// printf("type1");
ans = count;
}
// printf("\n");
}
// printf("\n");
testCaseAns << "Case #" << i + 1 << ": " << ans << "\n";
}
testCase.close();
testCaseAns.close();
return 0;
}
| [
"alexandra1.back@gmail.com"
] | alexandra1.back@gmail.com |
6504893b419a771a16b9586a711a7c33c97e26e4 | 72b451bad6e2972ade5f06f83ad0623dbf28ce22 | /kernel/include/net/udp_layer.hpp | c769a56f4759c8ce71228026b2d23bf9f803f9a3 | [
"MIT"
] | permissive | cekkr/thor-os | b7d31901959d8c4c2686e8af1dfcf156fbef477a | 841b088eddc378ef38c98878a51958479dce4a31 | refs/heads/develop | 2021-03-30T23:26:56.990768 | 2018-03-31T16:53:16 | 2018-03-31T16:53:16 | 124,933,350 | 0 | 0 | MIT | 2018-03-31T16:53:17 | 2018-03-12T18:28:19 | C++ | UTF-8 | C++ | false | false | 8,349 | hpp | //=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://www.opensource.org/licenses/MIT)
//=======================================================================
#ifndef NET_UDP_LAYER_H
#define NET_UDP_LAYER_H
#include <types.hpp>
#include <atomic.hpp>
#include "tlib/net_constants.hpp"
#include "net/interface.hpp"
#include "net/packet.hpp"
#include "net/connection_handler.hpp"
#include "net/socket.hpp"
namespace network {
namespace ip {
struct layer;
}
namespace dns {
struct layer;
}
namespace dhcp {
struct layer;
}
namespace udp {
/*!
* \brief Header of an UDP packet
*/
struct header {
uint16_t source_port; ///< The source port
uint16_t target_port; ///< The target port
uint16_t length; ///< The length of the UDP payload
uint16_t checksum; ///< The UDP checksum
} __attribute__((packed));
/*!
* \brief A descriptor for a packet from the kernel
*/
struct kernel_packet_descriptor {
size_t payload_size; ///< The size of the payload
size_t source_port; ///< The source port
size_t target_port; ///< The target port
network::ip::address target_ip; ///< The target IP
};
/*!
* \brief An UDP connection
*/
struct udp_connection {
size_t local_port; ///< The local source port
size_t server_port; ///< The server port
network::ip::address server_address; ///< The server address
bool connected = false; ///< Indicates if the connection is connnected
bool server = false; ///< Indicates if the connection is in server mode
network::socket* socket = nullptr; ///< Pointer to the user socket
};
/*!
* \brief The UDP layer implementation
*/
struct layer {
/*!
* \brief Constructs the layer
* \param parent The parent layer
*/
layer(network::ip::layer* parent);
/*!
* \brief Decode a network packet.
*
* This must only be called from the IP layer.
*
* \param interface The interface on which the packet was received
* \param packet The packet to decode
*/
void decode(network::interface_descriptor& interface, network::packet_p& packet);
/*!
* \brief Prepare a packet for the kernel
* \param interface The interface on which to prepare the packet for
* \param descriptor The packet descriptor
* \return the prepared packet or an error
*/
std::expected<network::packet_p> kernel_prepare_packet(network::interface_descriptor& interface, const kernel_packet_descriptor& descriptor);
/*!
* \brief Prepare a packet for the user
* \param buffer The buffer to write the packet to
* \param interface The interface on which to prepare the packet for
* \param descriptor The packet descriptor
* \return the prepared packet or an error
*/
std::expected<network::packet_p> user_prepare_packet(char* buffer, network::socket& sock, const packet_descriptor* descriptor);
/*!
* \brief Prepare a packet for the user
* \param buffer The buffer to write the packet to
* \param sock The user socket
* \param descriptor The packet descriptor
* \param address The address to send to
* \return the prepared packet or an error
*/
std::expected<network::packet_p> user_prepare_packet(char* buffer, network::socket& sock, const network::udp::packet_descriptor* descriptor, network::inet_address* address);
/*!
* \brief Finalize a prepared packet
* \param interface The interface on which to finalize the packet
* \param p The packet to finalize
* \return nothing or an error
*/
std::expected<void> finalize_packet(network::interface_descriptor& interface, network::packet_p& p);
/*!
* \brief Finalize a prepared packet
* \param interface The interface on which to finalize the packet
* \param p The packet to finalize
* \return nothing or an error
*/
std::expected<void> finalize_packet(network::interface_descriptor& interface, network::socket& sock, network::packet_p& p);
/*!
* \brief Bind to the socket as a client
* \param socket the User socket
* \param server_port The server port
* \param server The address of the server
* \return The allocated local port or an error
*/
std::expected<size_t> client_bind(network::socket& socket, size_t server_port, network::ip::address server);
/*!
* \brief Unbind from the socket as a client
* \param socket the User socket
* \return Nothing or an error
*/
std::expected<void> client_unbind(network::socket& socket);
/*!
* \brief Bind to the socket as a server
* \param socket the User socket
* \param server_port The server port
* \param server The address of the server
* \return Nothing or an error
*/
std::expected<void> server_bind(network::socket& socket, size_t server_port, network::ip::address server);
/*!
* \brief Receive a message directly
* \þaram buffer The buffer in which to store the message
* \param socket The user socket
* \param n The maximum message size
* \return The number of bytes read or an error
*/
std::expected<size_t> receive(char* buffer, network::socket& socket, size_t n);
/*!
* \brief Receive a message directly
* \þaram buffer The buffer in which to store the message
* \param socket The user socket
* \param n The maximum message size
* \param ms The maximum amout of milliseconds to wait
* \return The number of bytes read or an error
*/
std::expected<size_t> receive(char* buffer, network::socket& socket, size_t n, size_t ms);
/*!
* \brief Receive a message directly and stores the address of the sender
* \þaram buffer The buffer in which to store the message
* \param socket The user socket
* \param n The maximum message size
* \param address Pointer to the address to write
* \return The number of bytes read or an error
*/
std::expected<size_t> receive_from(char* buffer, network::socket& socket, size_t n, void* address);
/*!
* \brief Receive a message directly and stores the address of the sender
* \þaram buffer The buffer in which to store the message
* \param socket The user socket
* \param n The maximum message size
* \param address Pointer to the address to write
* \param ms The maximum amout of milliseconds to wait
* \return The number of bytes read or an error
*/
std::expected<size_t> receive_from(char* buffer, network::socket& socket, size_t n, size_t ms, void* address);
/*!
* \brief Send a message directly
* \param target_buffer The buffer in which to write the packet
* \þaram socket The user socket
* \param buffer The source message
* \param n The size of the source message
* \return Nothing or an error
*/
std::expected<void> send(char* target_buffer, network::socket& socket, const char* buffer, size_t n);
/*!
* \brief Send a message directly to the given address
* \param target_buffer The buffer in which to write the packet
* \þaram socket The user socket
* \param buffer The source message
* \param n The size of the source message
* \param address The address descriptor pointer
* \return Nothing or an error
*/
std::expected<void> send_to(char* target_buffer, network::socket& socket, const char* buffer, size_t n, void* address);
/*!
* \brief Register the DNS layer
* \param layer The DNS layer
*/
void register_dns_layer(network::dns::layer* layer);
/*!
* \brief Register the DHCP layer
* \param layer The DHCP layer
*/
void register_dhcp_layer(network::dhcp::layer* layer);
private:
network::ip::layer* parent; ///< The parent layer
network::dns::layer* dns_layer; ///< The DNS layer
network::dhcp::layer* dhcp_layer; ///< The DHCP layer
std::atomic<size_t> local_port; ///< The local port allocator
network::connection_handler<udp_connection> connections; ///< The UDP connections
};
} // end of upd namespace
} // end of network namespace
#endif
| [
"baptiste.wicht@gmail.com"
] | baptiste.wicht@gmail.com |
c8b0b41b48b68d1e1119ac38ec8ae2cfba63a1fb | 3fa445267cadf3263bd52de4c9c71ac8f2108ada | /Problemes/Tema_0/Ex13/Ex13/Ex13/ParitatParell.cpp | 106bff821ae260c3ae93e3de9c4260d4da796f75 | [] | no_license | UAB-DCC/sessio1-evalveny | daf913d416361b7f8caba51f2da3dd7d6801f051 | 634e069f191e9cc67eb7d4a15faa70db3a50047e | refs/heads/master | 2021-01-01T21:49:06.428746 | 2018-06-01T14:03:33 | 2018-06-01T14:03:33 | 121,395,356 | 0 | 0 | null | null | null | null | ISO-8859-10 | C++ | false | false | 337 | cpp | //
// ParitatParell.cpp
// funcions de repās
//
#include "ParitatParell.h"
#include <iostream>
using namespace std;
/*
* exercici 1
*/
bool bitParitatParell (int* trama)
{
int compteUns = 0;
for (int i = 0; i <= 7; i++)
{
if (trama[i] == 1) {
compteUns++;
}
}
return (compteUns % 2 == 0);
}
| [
"ernest@cvc.uab.es"
] | ernest@cvc.uab.es |
60cfc0a7236f67e13e23aa5e26f6fef730ffb4ce | 326a439b950e2cc868b5ded0d2d7982e2437db58 | /src/datamatrix.h | 2bc5157d7b6183f87f60deca7ea625479d1f6ff1 | [] | no_license | lineCode/dmCreator | 74b9b495cda77d6176b0b090ef8d0aa08e4d19c6 | 1c1c252bcae4302e67be675c87e83965808079e5 | refs/heads/master | 2020-03-20T17:50:27.565834 | 2017-12-13T20:08:46 | 2017-12-13T20:08:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 615 | h | #include <string>
#include <vector>
struct dm_data {
int width;
int height;
int channels;
std::vector<unsigned char> pixels;
};
struct dm_image {
int cols;
int rows;
int channels;
unsigned char *data;
};
class DataMatrix {
public:
DataMatrix();
~DataMatrix();
void setData(const std::string &data);
bool generate(const std::string &text, dm_data &result);
bool decode(const dm_image &image, unsigned int timeout, std::string &decodedText);
std::string pathToFile() const;
private:
std::string m_path; // output path
std::string m_filename;
};
| [
"guillaume.zufferey@gmail.com"
] | guillaume.zufferey@gmail.com |
27bea4ca58e94b4345a9a04d72255b7681e7fc59 | 003663f0b4dd8b2f7d239138ae446065dd4f9d15 | /CollidersContainer.h | 89b6828a8e0ca5cccfb06c02a6656d6b541f65e6 | [] | no_license | Arkowski24/ParticlesCollisions | 53720cd809be02f20cf38f480e92bcf780efe97a | a742bdd133930367dd76391b57cd9a137f079f46 | refs/heads/master | 2021-01-01T19:24:52.578387 | 2015-07-10T19:39:56 | 2015-07-10T19:39:56 | 38,394,198 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,850 | h | #pragma once
#include <vector>
#include <cmath>
#include <utility>
#include <algorithm>
#include "Particle.h"
#include <SFML/Graphics.hpp>
#include <iterator>
#define PI 3.14159265
class CollidersContainer
{
public:
CollidersContainer();
~CollidersContainer();
void CreateParticle(Particle& NewParticle);
void DeleteParticle(const unsigned int& ParticleNumber);
unsigned int ParticlesQuantity();
void SetParticle(const Particle& NewParticle, const unsigned int& ParticleNumber);
Particle GetParticle(const unsigned int& ParticleNumber);
void SetParticleMass(const double& NewMass, const unsigned int& ParticleNumber);
double GetParticleMass(const unsigned int& ParticleNumber);
void SetParticleRadius(const double& NewRadius, const unsigned int& ParticleNumber);
double GetParticleRadius(const unsigned int& ParticleNumber);
void SetParticlePosition(const double& NewPositionX, const double& NewPositionY, const unsigned int& ParticleNumber);
double GetParticlePositionX(const unsigned int& ParticleNumber);
double GetParticlePositionY(const unsigned int& ParticleNumber);
void SetParticleVelocity(const double& NewVelocityX, const double& NewVelocityY, const unsigned int& ParticleNumber);
double GetParticleVelocity(const unsigned int& ParticleNumber);
double GetParticleVelocityX(const unsigned int& ParticleNumber);
double GetParticleVelocityY(const unsigned int& ParticleNumber);
void SetParticleActingForce(const double& NewActingForceX, const double& NewActingForceY, const unsigned int& ParticleNumber);
double GetParticleActingForce(const unsigned int& ParticleNumber);
double GetParticleActingForceX(const unsigned int& ParticleNumber);
double GetParticleActingForceY(const unsigned int& ParticleNumber);
void SetCollisionPrecision(const double& NewCollisionPrecision);
double GetCollisionPrecision();
void SetSearchPrecision(const double& NewSearchingPrecision);
double GetSearchPrecision();
void MoveParticles(const double& DeltaTime);
void SimulateCollisions();
void CalculateCollisions(const unsigned int& ParticleNumberA, const unsigned int& ParticleNumberB);
void DeflectParticlesOutOfBorder();
void SortParticlesByX();
std::vector <std::pair<double, unsigned int> >::iterator LowerBound(std::vector <std::pair<double, unsigned int> >::iterator First,
std::vector <std::pair<double, unsigned int> >::iterator Last, const double& Value);
std::vector <std::pair<double, unsigned int> >::iterator UpperBound(std::vector <std::pair<double, unsigned int> >::iterator First,
std::vector <std::pair<double, unsigned int> >::iterator Last, const double& Value);
private:
std::vector <Particle> ParticlesContainer;
std::vector <std::pair<double, unsigned int> > ParticlesByX;
double CollisionPrecision;
double SearchPrecision;
unsigned int WindowWidth;
unsigned int WindowHeight;
};
| [
"arkadiusz.placha@lo5.bielsko.pl"
] | arkadiusz.placha@lo5.bielsko.pl |
f6fe65acb469a780c5d3810c2104f59b1183139c | d53f3d899f08e2328a765bb699db4498a9acc8df | /Samples/bk_src/logl/src/1.getting_started/4.5.textures_exercise4/textures_exercise4.cpp | 6c24f4a5039932ff528070b4b93ae01835599ee5 | [
"MIT"
] | permissive | KangWeon/Glitter | b9c4172de0d71ebf02bfff1df01d845d91539ba3 | 4a94913691582dd3b966a1b91842fb1793ac6096 | refs/heads/master | 2021-02-10T00:52:31.149295 | 2020-10-05T19:19:04 | 2020-10-05T19:19:04 | 299,637,650 | 0 | 1 | null | 2020-09-29T14:10:32 | 2020-09-29T14:10:31 | null | UTF-8 | C++ | false | false | 8,930 | cpp | #include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <stb_image.h>
#include <learnopengl/filesystem.h>
#include <learnopengl/shader_s.h>
#include <iostream>
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
// stores how much we're seeing of either texture
float mixValue = 0.2f;
int main()
{
// glfw: initialize and configure
// ------------------------------
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X
#endif
// glfw window creation
// --------------------
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// glad: load all OpenGL function pointers
// ---------------------------------------
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
// build and compile our shader zprogram
// ------------------------------------
Shader ourShader("4.5.texture.vs", "4.5.texture.fs");
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
float vertices[] = {
// positions // colors // texture coords
0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top right
0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom right
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom left
-0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // top left
};
unsigned int indices[] = {
0, 1, 3, // first triangle
1, 2, 3 // second triangle
};
unsigned int VBO, VAO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// color attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
// texture coord attribute
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2);
// load and create a texture
// -------------------------
unsigned int texture1, texture2;
// texture 1
// ---------
glGenTextures(1, &texture1);
glBindTexture(GL_TEXTURE_2D, texture1);
// set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// load image, create texture and generate mipmaps
int width, height, nrChannels;
stbi_set_flip_vertically_on_load(true); // tell stb_image.h to flip loaded texture's on the y-axis.
// The FileSystem::getPath(...) is part of the GitHub repository so we can find files on any IDE/platform; replace it with your own image path.
unsigned char *data = stbi_load(FileSystem::getPath("resources/textures/container.jpg").c_str(), &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
std::cout << "Failed to load texture" << std::endl;
}
stbi_image_free(data);
// texture 2
// ---------
glGenTextures(1, &texture2);
glBindTexture(GL_TEXTURE_2D, texture2);
// set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// load image, create texture and generate mipmaps
data = stbi_load(FileSystem::getPath("resources/textures/awesomeface.png").c_str(), &width, &height, &nrChannels, 0);
if (data)
{
// note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
std::cout << "Failed to load texture" << std::endl;
}
stbi_image_free(data);
// tell opengl for each sampler to which texture unit it belongs to (only has to be done once)
// -------------------------------------------------------------------------------------------
ourShader.use(); // don't forget to activate/use the shader before setting uniforms!
// either set it manually like so:
glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), 0);
// or set it via the texture class
ourShader.setInt("texture2", 1);
// render loop
// -----------
while (!glfwWindowShouldClose(window))
{
// input
// -----
processInput(window);
// render
// ------
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// bind textures on corresponding texture units
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2);
// set the texture mix value in the shader
ourShader.setFloat("mixValue", mixValue);
// render container
ourShader.use();
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents();
}
// optional: de-allocate all resources once they've outlived their purpose:
// ------------------------------------------------------------------------
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &EBO);
// glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
glfwTerminate();
return 0;
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS)
{
mixValue += 0.001f; // change this value accordingly (might be too slow or too fast based on system hardware)
if(mixValue >= 1.0f)
mixValue = 1.0f;
}
if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS)
{
mixValue -= 0.001f; // change this value accordingly (might be too slow or too fast based on system hardware)
if (mixValue <= 0.0f)
mixValue = 0.0f;
}
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
} | [
"kangweon.jeong@gmail.com"
] | kangweon.jeong@gmail.com |
4ccc9ae7612c505ba9f7381919dd6d7a74b56f7b | 367b8a9c33357ae73fcf6b313995070d9cefacd6 | /Source/HeroShooter/HeroPlayerController.h | cdd314dfb6dca2e2ca61131eb4f02033d1241564 | [] | no_license | Krasi2405/EndOfYearProject | 96a046d9005b3d6c52670276de21e0633f2d4f50 | 9db5a463f69afb82a238399b5b2c8015e15d09a7 | refs/heads/master | 2022-10-21T00:32:04.087630 | 2020-06-09T04:12:11 | 2020-06-09T04:12:11 | 236,856,246 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,640 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "HeroPlayerController.generated.h"
class UIngameMenu;
class UChatBox;
class UHeroPickerMenu;
class UGameModeInfoWidget;
class AHeroSpawner;
class ABaseCharacter;
class AHeroSpawner;
/**
*
*/
UCLASS()
class HEROSHOOTER_API AHeroPlayerController : public APlayerController
{
GENERATED_BODY()
public:
AHeroPlayerController();
UFUNCTION(Server, Reliable)
void ServerSendMessageRequest(const FString& Message);
UFUNCTION(Client, Reliable)
void ClientReceiveMessage(APlayerState* SendingPlayer, const FString& Message);
void TeleportSpectatorToHeroPicker();
// Called after team index is changed on client and right away on server.
void TeamSetup();
void SetTeamIndex(int NewTeamIndex);
AHeroSpawner* GetAssociatedHeroSpawner();
protected:
virtual void BeginPlay() override;
// Team Index may be updated before or after begin play.
// If updated after begin play the responsibility is given to begin play for calling TeamSetup function.
bool bBeginPlayExecuted = false;
// Only called on client
virtual void AcknowledgePossession(class APawn* Pawn) override;
// Only called on server.
virtual void OnPossess(class APawn* Pawn) override;
virtual void SetupInputComponent() override;
UFUNCTION()
void ServerHandleDeath();
UFUNCTION()
void ClientHandleDeath();
UPROPERTY(EditDefaultsOnly)
int RespawnDelay = 5;
FTimerHandle RespawnTimerHandle;
void Respawn();
UPROPERTY()
AHeroSpawner* TeamSpawner;
UFUNCTION()
void ChooseHero(TSubclassOf<ABaseCharacter> Hero);
UFUNCTION(Server, Reliable)
void ServerSpawnHero(TSubclassOf<ABaseCharacter> Hero);
void ServerSpawnHero_Implementation(TSubclassOf<ABaseCharacter> Hero);
void ActivateHeroPicker();
void DeactivateHeroPicker();
void ToggleChat();
bool bChatOpen = false;
void ServerSendMessageRequest_Implementation(const FString& Message);
void ClientReceiveMessage_Implementation(APlayerState* SendingPlayer, const FString& Message);
void ToggleIngameMenu();
bool bIngameMenuActive = false;
int TeamIndex = -1;
int LastTeamSetupIndex = -1;
UFUNCTION()
void HandleWinCondition(int WinningTeamIndex);
UFUNCTION()
void OnEnterSpawnArea();
UFUNCTION()
void OnExitSpawnArea();
bool bCanSwitchHero = false;
void SwitchHero();
UFUNCTION()
void ShowStats();
UFUNCTION()
void HideStats();
UFUNCTION()
void OnTeamChange(class AHeroPlayerState* HeroPlayerState);
UFUNCTION()
void ChangeWeapon(class AWeapon* Weapon);
}; | [
"krasi2405@gmail.com"
] | krasi2405@gmail.com |
53fd63d7e81f5fb7410d9f0f4dca8ed69828a3bb | 7d31b44aa304c4b08601e5f7ee24fa66d0a6b27b | /LMP3D/Graphics/Quaternion.h | d395212c72aeb6d73ee279c19b88ca9b93d367af | [] | no_license | CyberSys/Fury-Fighting | ca1eebb31eb3ab2f922b5293500502b72ef28bfe | 486f84e742b660a0ea44fe7949d47c3fe96c9d0d | refs/heads/master | 2020-08-14T03:52:15.706027 | 2016-08-07T20:38:42 | 2016-08-07T20:38:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,376 | h | #ifndef ___LMP3D_GRAPHICS_QUATERNION_H___
#define ___LMP3D_GRAPHICS_QUATERNION_H___
#include "Vector.h"
namespace LMP3D
{
namespace Graphics
{
/**
@brief
Normalises a quaternion.
@param[in,out] quat
The quaternion to normalise.
*/
inline void normalise( Quaternion & quat );
/**
@brief
Quaternion class.
*/
class Quaternion
{
public:
/**
@brief
Default constructor.
*/
inline Quaternion()
: x( 0.0f )
, y( 0.0f )
, z( 0.0f )
, w( 1.0f )
{
}
/**
@brief
Constructor from specified values.
@param[in] x,y,z,w
The values.
*/
inline Quaternion( float x, float y, float z, float w )
: x( x )
, y( y )
, z( z )
, w( w )
{
normalise( *this );
}
/**
@brief
Constructor from axis and angle.
@param[in] axis
The axis.
@param[in] angle
The angle.
*/
inline Quaternion( Vector3 const & axis, float angle )
{
fromAxisAngle( axis, angle );
}
/**
@brief
Constructor from axis and angle.
@param[in] axis
The axis.
@param[in] angle
The angle.
*/
inline Quaternion( float pitch, float yaw, float roll )
{
fromEulerAngles( pitch, yaw, roll );
}
/**
@brief
Sets this quaternion from axis and angle.
@param[in] axis
The axis.
@param[in] angle
The angle.
*/
inline void fromAxisAngle( Vector3 const & axis, float angle )
{
float const h = angle * 0.5f;
float const s = sin( h );
w = cos( h );
x = axis.x * s;
y = axis.y * s;
z = axis.z * s;
normalise( *this );
}
/**
@brief
Retrieves axis and angle from this quaternion.
@param[out] axis
The axis.
@param[out] angle
The angle.
*/
inline void toAxisAngle( Vector3 & vector, float & angle )const
{
angle = 2.0f * acos( w );
float tmp = 1.0f - w * w;
if ( tmp <= 0.0f )
{
vector.x = 0;
vector.y = 0;
vector.z = 1;
}
else
{
tmp = 1.0f / sqrt( tmp );
vector.x = x * tmp;
vector.y = y * tmp;
vector.z = z * tmp;
}
}
/**
@brief
Sets this quaternion from Euler angles.
@param[in] pitch, yaw, roll
The angles.
*/
inline void fromEulerAngles( float pitch, float yaw, float roll )
{
pitch *= 0.5f;
yaw *= 0.5f;
roll *= 0.5f;
float const cp = cos( pitch );
float const cy = cos( yaw );
float const cr = cos( roll );
float const sp = sin( pitch );
float const sy = sin( yaw );
float const sr = sin( roll );
w = cp * cy * cr + sp * sy * sr;
x = sp * cy * cr - cp * sy * sr;
y = cp * sy * cr + sp * cy * sr;
z = cp * cy * sr - sp * sy * cr;
//w = ( cy * cr * cp ) - ( sy * sr * sp );
//x = ( sy * sr * cp ) + ( cy * cr * sp );
//y = ( sy * cr * cp ) + ( cy * sr * sp );
//z = ( cy * sr * cp ) - ( sy * cr * sp );
}
/**
@brief
Retrieves Euler angles from this quaternion.
@param[out] pitch, yaw, roll
Receive the angles.
*/
inline void toEulerAngles( float & pitch, float & yaw, float & roll )const
{
roll = float( atan2( 2.0f * ( x * y + w * z ), w * w + x * x - y * y - z * z ) );
pitch = float( atan2( 2.0f * ( y * z + w * x ), w * w - x * x - y * y + z * z ) );
yaw = asin( -2.0f * ( x * z - w * y ) );
}
/**
@brief
Retrieves the coordinate system described by this quaternion.
@param[out] p_x, p_y, p_z
Receive the coordinate system.
*/
inline void toAxes( Vector3 & p_x, Vector3 & p_y, Vector3 & p_z )const
{
p_x = Vector3( 1, 0, 0 );
p_y = Vector3( 0, 1, 0 );
p_z = Vector3( 0, 0, 1 );
transform( p_x, p_x );
transform( p_y, p_y );
transform( p_z, p_z );
}
/**
@brief
Transforms a vector and gives the result
@param[in] vector
The vector to transform
@param[out] result
Receives the result
@return
A reference to result
*/
inline Vector3 & transform( Vector3 const & vector, Vector3 & result )const
{
Vector3 u( x, y, z );
Vector3 uv( cross( u, vector ) );
Vector3 uuv( cross( u, uv ) );
uv *= 2 * w;
uuv *= 2;
result = vector + uv + uuv;
return result;
}
/**
@brief
Addition assignment operator.
@param[in] rhs
The other element.
@return
A reference to this object.
*/
inline Quaternion & operator+=( Quaternion const & rhs )
{
x += rhs.x;
y += rhs.y;
z += rhs.z;
w += rhs.w;
normalise( *this );
return *this;
}
/**
@brief
Subtraction assignment operator.
@param[in] rhs
The other element.
@return
A reference to this object.
*/
inline Quaternion & operator-=( Quaternion const & rhs )
{
x -= rhs.x;
y -= rhs.y;
z -= rhs.z;
w -= rhs.w;
normalise( *this );
return *this;
}
/**
@brief
Multiplication assignment operator.
@param[in] rhs
The other element.
@return
A reference to this object.
*/
inline Quaternion & operator*=( Quaternion const & rhs )
{
float const tmpx = x;
float const tmpy = y;
float const tmpz = z;
float const tmpw = w;
x = tmpw * rhs.x + tmpx * rhs.w + tmpy * rhs.z - tmpz * rhs.y;
y = tmpw * rhs.y + tmpy * rhs.w + tmpz * rhs.x - tmpx * rhs.z;
z = tmpw * rhs.z + tmpz * rhs.w + tmpx * rhs.y - tmpy * rhs.x;
w = tmpw * rhs.w - tmpx * rhs.x - tmpy * rhs.y - tmpz * rhs.z;
normalise( *this );
return *this;
}
/**
@brief
Multiplication assignment operator.
@param[in] rhs
The scalar.
@return
A reference to this object.
*/
inline Quaternion & operator*=( float p_rhs )
{
x *= p_rhs;
y *= p_rhs;
z *= p_rhs;
w *= p_rhs;
normalise( *this );
return *this;
}
/**
@brief
Division assignment operator.
@param[in] rhs
The scalar.
@return
A reference to this object.
*/
inline Quaternion & operator/=( float p_rhs )
{
x /= p_rhs;
y /= p_rhs;
z /= p_rhs;
w /= p_rhs;
normalise( *this );
return *this;
}
public:
float x;
float y;
float z;
float w;
};
/**
@brief
Addition operator.
@param[in] lhs, rhs
The operands.
*/
inline Quaternion operator+( Quaternion const & lhs, Quaternion const & rhs )
{
Quaternion l_return( lhs );
l_return += rhs;
return l_return;
}
/**
@brief
Subtraction operator.
@param[in] lhs, rhs
The operands.
*/
inline Quaternion operator-( Quaternion const & lhs, Quaternion const & rhs )
{
Quaternion l_return( lhs );
l_return -= rhs;
return l_return;
}
/**
@brief
Multiplication operator.
@param[in] lhs, rhs
The operands.
*/
inline Quaternion operator*( Quaternion const & lhs, Quaternion const & rhs )
{
Quaternion l_return( lhs );
l_return *= rhs;
return l_return;
}
/**
@brief
Multiplication operator.
@param[in] lhs, rhs
The operands.
*/
inline Quaternion operator*( Quaternion const & lhs, float rhs )
{
Quaternion l_return( lhs );
l_return *= rhs;
return l_return;
}
/**
@brief
Multiplication operator.
@param[in] lhs, rhs
The operands.
*/
inline Quaternion operator*( float lhs, Quaternion const & rhs )
{
Quaternion l_return( rhs );
l_return *= lhs;
return l_return;
}
/**
@brief
Division operator.
@param[in] lhs, rhs
The operands.
*/
inline Quaternion operator/( Quaternion const & lhs, float rhs )
{
Quaternion l_return( lhs );
l_return /= rhs;
return l_return;
}
/**
@brief
Negation operator.
@param[in] q
The operand.
*/
inline Quaternion operator-( Quaternion const & q )
{
Quaternion l_return( q );
l_return.w = -l_return.w;
return l_return;
}
/**
@brief
Computes the dot product of two quaternions.
@return
The dot product.
*/
inline float dot( Quaternion const & lhs, Quaternion const & rhs )
{
return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z + lhs.w * rhs.w;
}
/**
@brief
Computes the cross product of two quaternions.
@param[in] lhs, rhs
The operands.
@return
The cross product.
*/
inline Quaternion cross( Quaternion const & lhs, Quaternion const & rhs )
{
return Quaternion(
( lhs.w * rhs.x ) + ( lhs.x * rhs.w ) + ( lhs.y * rhs.z ) - ( lhs.z * rhs.y ),
( lhs.w * rhs.y ) + ( lhs.y * rhs.w ) + ( lhs.z * rhs.x ) - ( lhs.x * rhs.z ),
( lhs.w * rhs.z ) + ( lhs.z * rhs.w ) + ( lhs.x * rhs.y ) - ( lhs.y * rhs.x ),
( lhs.w * rhs.w ) - ( lhs.x * rhs.x ) - ( lhs.y * rhs.y ) - ( lhs.z * rhs.z )
);
}
/**
@brief
Computes the magnitude (norm) of the quaternion.
@return
The magnitude.
*/
inline float length( Quaternion const & quat )
{
return sqrt( dot( quat, quat ) );
}
/**
@brief
Normalises a quaternion.
@param[in,out] quat
The quaternion to normalise.
*/
inline void normalise( Quaternion & quat )
{
float norm = length( quat );
if ( norm != 0 )
{
quat.x /= norm;
quat.y /= norm;
quat.z /= norm;
quat.w /= norm;
}
}
/**
@brief
Converts degrees to radians.
@param[in] degrees
The angle in degrees.
*/
inline float radians( float degrees )
{
static double const pi = 3.1415926535897932384626433832795028841968;
return float( degrees * pi / 180.0 );
}
}
}
#endif
| [
"dragonjoker59@hotmail.com"
] | dragonjoker59@hotmail.com |
3556d15c65b4a052127819d9911cd3cc5daad6ad | d9c8c917a6a266061d5707a578dc678a11c79bee | /SchroedingerEquation/main.cpp | 3f7c0b893fd2f901a222bc44c626c76b67aeaf4d | [] | no_license | Philxy/Computational-Physics-Stuff | 0b80440e1e6a0288dbc531a4ce57233cf926a528 | 682c5e6e26c88ac52af462c7e80d88c41be4f200 | refs/heads/main | 2023-07-17T14:10:32.883215 | 2021-08-30T14:36:42 | 2021-08-30T14:36:42 | 400,626,844 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,826 | cpp | #include <iostream>
#include <cmath>
#include <math.h>
#include <fstream>
#include <limits>
using namespace std;
double H = 0.001;
double XMAX = 20;
double F(double r) {
return 0;
return -r * exp(-r);
}
double V(double x) {
if (x >= 0) {
return x;
} else {
return std::numeric_limits<double>::infinity();
}
}
double X(double r) {
return 0;
return (1 - (1 + r / 2) * exp(-r));
}
double k2(double E, double x) {
double m = 1;
double h_quer = 1;
return m * (E - V(x)) / (h_quer * h_quer);
}
double numerowIn(double E) {
std::ofstream resultKorrigiert;
std::ofstream ideal;
std::ofstream resultUnKorrigiert;
resultUnKorrigiert.open("numerovUn.txt");
resultKorrigiert.open("numerovKor.txt");
ideal.open("ideal.txt");
double x0 = 20;
double f_n1;
double f_n3 = 2;
double f_n2 = 2;
for (double x = x0 - 2 * H; x > 0.001; x -= H) {
f_n1 = ((-f_n3 * (1. + H * H / 12. * k2(E, x + H)))
+ (H * H / 12. * (F(x + H) + 10. * F(x) + F(x - H)))
+ f_n2 * (2. - 5. / 6. * H * H * k2(E, x))) / (1. + H * H / 12. * k2(E, x - H));
f_n3 = f_n2;
f_n2 = f_n1;
ideal << x << " " << X(x) / x << endl;
resultKorrigiert << x << " " << f_n1 / (2 * x) << endl;
resultUnKorrigiert << x << " " << f_n1 / (x) << endl;
}
}
double xEnd = 20;
double numerowIn2(double E) {
double f_n1;
double f_n3 = 0;
double f_n2 = f_n3 + H * H * (V(xEnd - H) - E);
for (double x = xEnd; x > 0; x -= H) {
f_n1 = ((-f_n3 * (1. + H * H / 12. * k2(E, x + H)))
+ (H * H / 12. * (F(x + H) + 10. * F(x) + F(x - H)))
+ f_n2 * (2. - 5. / 6. * H * H * k2(E, x))) / (1. + H * H / 12. * k2(E, x - H));
f_n3 = f_n2;
f_n2 = f_n1;
}
return f_n3;
}
double numerowIn2Print(double E) {
std::ofstream result2;
result2.open("result2.txt");
double f_n1;
double f_n3 = 0;
double f_n2 = f_n3 + H * H * (V(xEnd - H) - E);
int i = 0;
for (double x = xEnd; x > 0; x -= H) {
f_n1 = ((-f_n3 * (1. + H * H / 12. * k2(E, x + H)))
+ (H * H / 12. * (F(x + H) + 10. * F(x) + F(x - H)))
+ f_n2 * (2. - 5. / 6. * H * H * k2(E, x))) / (1. + H * H / 12. * k2(E, x - H));
f_n3 = f_n2;
f_n2 = f_n1;
result2 << f_n1 << endl;
}
return f_n3;
}
double numerowIn2Sum(double E) {
double f_n1;
double f_n3 = 0;
double f_n2 = f_n3 + H * H * (V(xEnd - H) - E);
int i = 0;
double sum;
for (double x = xEnd; x > 0; x -= H) {
f_n1 = ((-f_n3 * (1. + H * H / 12. * k2(E, x + H)))
+ (H * H / 12. * (F(x + H) + 10. * F(x) + F(x - H)))
+ f_n2 * (2. - 5. / 6. * H * H * k2(E, x))) / (1. + H * H / 12. * k2(E, x - H));
f_n3 = f_n2;
f_n2 = f_n1;
sum += H * f_n1;
i++;
}
return sum;
}
int main() {
double E = 7.94514;
numerowIn2Print(E);
/*
* for (double E = 7.92; E < 8; E += 0.00001) {
double n = numerowIn2(E);
if (abs(n / numerowIn2Sum(E)) < 0.00001) {
cout << E << endl;
}
}
*/
// plot "E1norm.txt", "E2norm.txt", "E3norm.txt", "E4norm.txt", "E5norm.txt"
// 2.33912 E1
// 4.08895 E2
// 5.52157 E3
// 6.78771 E4
// 7.94514 E5
/*
* double E0 = 1, E1 = 5, E, f0, f1;
do {
f1 = numerowIn2(E1);
f0 = numerowIn2(E0);
E = (f1 * E0 - f0 * E1) / (f1 - f0);
//E = E1 - (E1-E0)*f1/(f1-f0);
E0 = E1;
E1 = E;
cout << " E " << E << endl;
cout << " f0 " << f0 << endl;
} while (fabs(E1 - E0) > 1 / 10000000);
cout << " E " << E << endl;
*/
return 0;
}
| [
"philxyphilxy@gmail.com"
] | philxyphilxy@gmail.com |
8453443cca2583cc3baefb5295b037f5d536b189 | d52fd6a8c0bdbcab9459d9577dcf38484084767e | /hacker-rank/101hack38/easy-gcd-1.cpp | 81b5b2cdde111d408fc583bdc77eb7e12bffdf95 | [] | no_license | ex-surreal/contest-programming | af7f557b1bb28c9dbe8d75d8937f0cf3b5d7c2a9 | 10fce86777e6277283e1ea690749ab2b1e96eedf | refs/heads/master | 2020-04-12T03:53:45.785311 | 2019-01-05T14:05:12 | 2019-01-05T14:05:12 | 64,762,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,044 | cpp | #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <cmath>
#include <set>
#include <queue>
#include <stack>
#include <cstring>
#include <ctime>
#include <cstdlib>
#include <cassert>
using namespace std;
#define mem(a, v) memset(a, v, sizeof (a))
#define x first
#define y second
#define all(a) (a).begin(), (a).end()
#define mp make_pair
#define pb push_back
#define sz(x) int((x).size())
#define rep(i, n) for (int i = 0; i < int(n); i ++)
#define repi(i, a, n) for (int i = (a); i < int(n); i ++)
#define repe(x, v) for (auto x: (v))
int main () {
std::ios_base::sync_with_stdio(false);
int n, k, g;
cin >> n >> k >> g;
rep(i, n-1) {
int x;
cin >> x;
g = __gcd(g, x);
}
int ans = 0;
for (int i = 1; i*i <= g; i ++) {
if (g%i == 0) {
int q = g/i;
if (i != 1) {
ans = max(ans, k/i*i);
}
ans = max(ans, k/q*q);
}
}
cout << ans << "\n";
return 0;
}
| [
"mamumit07@gmail.com"
] | mamumit07@gmail.com |
d63ee772d7073a168ed5eb61f3f7e3f34bac47d2 | dfbe0a1723f7145fe11336ccc3e962a0e3b6dbcb | /game/logic/sim/io/events.h | fcf4d6a723dcbf7afc3bc513dcd0319b21a45310 | [] | no_license | grandseiken/iispace | 67d18d72ab62da1fbc4859394e0da14402feeaec | 88f57cbd7c0f2aa2996adc50a0c35b411bd1835d | refs/heads/master | 2023-07-05T21:55:59.023645 | 2023-07-02T14:37:40 | 2023-07-02T14:41:17 | 19,438,190 | 0 | 0 | null | 2022-08-28T20:06:04 | 2014-05-04T23:05:08 | C++ | UTF-8 | C++ | false | false | 578 | h | #ifndef II_GAME_LOGIC_SIM_IO_EVENTS_H
#define II_GAME_LOGIC_SIM_IO_EVENTS_H
#include "game/common/enum.h"
#include <cstdint>
#include <optional>
namespace ii {
enum class boss_flag : std::uint32_t {
kBoss1A = 1,
kBoss1B = 2,
kBoss1C = 4,
kBoss2A = 8,
kBoss2B = 16,
kBoss2C = 32,
kBoss3A = 64,
};
template <>
struct bitmask_enum<boss_flag> : std::true_type {};
struct run_event {
std::optional<boss_flag> boss_kill;
static run_event boss_kill_event(boss_flag boss) {
run_event e;
e.boss_kill = boss;
return e;
}
};
} // namespace ii
#endif
| [
"s+github@stu.scot"
] | s+github@stu.scot |
a7bbd9ea56a374478fffedd2548a24a910fb3c11 | 1d7f3fd33d01fed90fb48a1824134214adaf69a9 | /thread_test_impl.h | abd30ef8e0da40e06862350825be883eac462ff6 | [] | no_license | adrianyang/thread-time-control | 1a57883e16f99f5e20d948ff279a8be8192e275a | fd3176a288d3ccdec18eee49f80b54a513086b55 | refs/heads/master | 2021-03-27T14:26:14.236496 | 2014-06-25T13:31:19 | 2014-06-25T13:31:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,985 | h | #ifndef __THREAD_TEST_IMPL_H__
#define __THREAD_TEST_IMPL_H__
#include <stdio.h>
#include "thread_def_common.h"
// Useful implicit definitions are done here.
#define DEFINE_CLASS_THREAD_TEST(thread_test_group, thread_test_case) \
class thread_test_group ## thread_test_case : public ThreadTest { \
public: \
thread_test_group ## thread_test_case () { } \
virtual ~ thread_test_group ## thread_test_case () { } \
\
virtual int Run(); \
\
static int reg; \
}
#define MAKE_OBJECT(str) new str()
#define GET_OBJECT(str) ((dynamic_cast<str*>(ThreadTestContainer::GetInstance()->GetTest(#str))) ? \
(dynamic_cast<str*>(ThreadTestContainer::GetInstance()->GetTest(#str))) : MAKE_OBJECT(str))
#define MAKE_STRING(str) #str
#define REGISTER_GROUP_AND_CASE(thread_test_group, thread_test_case) \
int thread_test_group ## thread_test_case :: reg = \
RegisterGroupAndCase(MAKE_STRING(thread_test_group), \
GET_OBJECT(thread_test_group), \
MAKE_STRING(thread_test_group ## thread_test_case), \
MAKE_OBJECT(thread_test_group ## thread_test_case));
#if 0
#define REGISTER_GROUP_CASE(thread_test_group, thread_test_case)
#define REGISTER_GROUP(thread_test_group) \
ThreadTestContainer* container = ThreadTestContainer::GetInstance(); \
ThreadTestGroup* group = new thread_test_group (); \
container->AddTest(#thread_test_group, group)
#define ADD_THREAD_TEST_CASE(test_name, test_case) \
group->AddTest(#test_name, test_case)
#define REGISTER_CASE_REAL(thread_test_group, thread_test_case) \
ThreadTest* test_case = \
new thread_test_group ## thread_test_case (); \
ADD_THREAD_TEST_CASE(thread_test_group ## thread_test_case, test_case)
#define REGISTER_CASE(thread_test_group, thread_test_case) \
REGISTER_CASE_REAL(thread_test_group, thread_test_case)
#endif
// an extra "{" is added in the end, so that
// the macro of "BEGIN_THREAD_TEST" must be called.
#define DEFINE_RUN_FUNC(thread_test_group, thread_test_case) \
int thread_test_group ## thread_test_case :: Run() { \
ThreadActionSetterPtr thread_action_setter_ptr;
#define INIT_ENV(argc, argv) \
ThreadTestContainer::GetInstance()->InitEnv(argc, argv);
#define SET_DEFAULT_TEST_ACTION this->SetDefaultTestAction();
#define SET_DEFAULT_TEST_ATTR this->SetDefaultTestAttribute();
#define FORK this->ForkAndRunParentProcess();
// collect logs (TestLog) and test results (ThreadTestResult)
#define COLLECT_TEST_RESULTS this->GenerateLogs(); \
ThreadTestContainer::GetInstance()->CollectResults(this)
class ThreadTest;
enum TestLogInsertRet {
RET_NORMAL,
RET_ASSERT_FAILED,
};
// internal helper class:
class TestLog {
public:
struct LogItem {
enum MessageType {
LIB_FUNC_BEGIN,
LIB_FUNC_END,
USER_FUNC,
};
LogItem() :
thread_id(-1),
action_type(INVALID_THREAD_ACTION),
order(THREAD_ACTION_ORDER_SIZE),
ret_val(0),
ret(0),
index(-1),
message_type(USER_FUNC) { }
LogItem(int tid,
ThreadActionNestedIn action,
ThreadActionOrder od,
int r_v,
int r,
int idx,
MessageType m_t) :
thread_id(tid),
action_type(action),
order(od),
ret_val(r_v),
ret(r),
index(idx),
message_type(m_t) { }
LogItem(const LogItem& item) :
thread_id(item.thread_id),
action_type(item.action_type),
order(item.order),
ret_val(item.ret_val),
ret(item.ret),
index(item.index),
message_type(item.message_type) { }
bool IsInLockState() const;
// note that this is not the real process id form linux kernel
// we use an integer pre-set by users, because we presume that
// users care more about the value set by themselves.
int thread_id;
ThreadActionNestedIn action_type;
ThreadActionOrder order;
int ret_val;
int ret;
int index;
MessageType message_type;
};
TestLog();
~TestLog();
void Init();
TestLogInsertRet InsertLog(uint64_t timestamp, LogItem item);
bool IsRunNormally() {
return run_state_ == RUNNING_NORMALLY;
}
bool IsDeadLocked() {
return run_state_ == DEAD_LOCKING;
}
void SetDeadLock() {
run_state_ = DEAD_LOCKING;
}
// TODO: access log:
bool IsAllInLockState();
bool IsInSuspendState();
private:
friend class ThreadTestResult;
// note that there should never be an item of "CRASHED/ABORTED" here,
// because once crashed, no info could be captured into the log.
enum ProcessState {
RUNNING_NORMALLY,
DEAD_LOCKING,
};
// map timestamp to log:
std::map< uint64_t, std::vector<LogItem> > time_log_;
uint64_t latest_log_time_;
uint64_t last_checked_time_;
std::map<int, LogItem> latest_log_;
pthread_mutex_t mutex_;
ProcessState run_state_;
};
class ThreadTestResult {
public:
enum ThreadTestResultLogType {
LIB_FUNC_LOG = 0,
USER_EXPECT_LOG,
USER_ASSERT_LOG,
THREAD_TEST_RESULT_LOG_SIZE,
};
enum ThreadTestResultEndState {
SUC = 0,
FAILED,
THREAD_TEST_RESULT_END_STATE_SIZE,
};
enum ErrType {
EXPECT_FAILED,
ASSERT_FAILED,
};
struct ErrInfo {
ErrInfo(ErrType type,
std::string stat,
std::string file,
std::string line,
int id) :
err_type(type),
expect_statement(stat),
src_file(file),
line_no(line) {
char tmp[80];
snprintf(tmp, 80, "%d", id);
tid = tmp;
}
ErrType err_type;
// the statement of "EXPECT_THAT/ASSERT_THAT"
std::string expect_statement;
std::string src_file;
std::string line_no;
// thread id set by users:
std::string tid;
};
enum FailureReason {
FAILEURE_NONE = 0,
EXPECT_FAILURE = 1,
ASSERT_FAILURE = (EXPECT_FAILED << 1),
DEAD_LOCK = (ASSERT_FAILED << 1),
CRASHED = (DEAD_LOCK << 1),
};
ThreadTestResult();
~ThreadTestResult();
bool IsTestSuc() const {
return is_all_suc_;
}
void SetTestCrashed();
void SetTestDeadlock();
void SetExpectAssertErr(const ErrInfo& err_info);
// TODO: discard this function
std::string GetFailureReason(const ErrInfo& err_info);
void GenerateLogs(ThreadTest* test);
void DisplayGeneralResult(FILE* log_file) {
if (is_all_suc_) {
fprintf(log_file, "Succeeded.\n");
} else {
fprintf(log_file, "Failed: %s\n", failed_reason_str_.c_str());
}
}
void DisplaySuccessLogs(FILE* log_file) {
for (size_t i = LIB_FUNC_LOG; i < THREAD_TEST_RESULT_LOG_SIZE; ++i) {
for (size_t j = 0; j < logs_[i][SUC].size(); ++j) {
fprintf(log_file, "%s\n", logs_[i][SUC][j].c_str());
}
}
}
void DisplayFailureLogs(FILE* log_file) {
for (size_t i = LIB_FUNC_LOG; i < THREAD_TEST_RESULT_LOG_SIZE; ++i) {
for (size_t j = 0; j < logs_[i][FAILED].size(); ++j) {
fprintf(log_file, "%s\n", logs_[i][FAILED][j].c_str());
}
}
}
private:
bool is_all_suc_;
// crashed? / deadlocked?
int failure_reason_;
std::string failed_reason_str_;
std::vector<ErrInfo> all_errs_;
// 1st dim: ThreadTestResultLogType;
// 2nd dim: success / failure;
// 3rd dim: each log takes an element
std::vector< std::vector< std::vector<std::string> > > logs_;
pthread_mutex_t mutex_;
};
//class ThreadActionSetterPtr;
class ThreadActionSetter {
public:
ThreadActionSetter();
~ThreadActionSetter();
private:
friend class ThreadActionSetterPtr;
Func func_;
void* arg_;
ThreadActionType func_type_;
int tid_;
ThreadResource resource_;
ThreadActionOrder order_;
ThreadActionNestedIn pthread_func_;
ThreadActionFreq freq_;
int freq_num_;
std::string file_;
std::string line_;
};
class ThreadActionSetterPtr {
public:
ThreadActionSetterPtr();
~ThreadActionSetterPtr();
ThreadActionSetterPtr& operator=(ThreadActionSetter* setter);
void Clear();
ThreadActionSetterPtr& SetFunc(Func func,
std::string resource_name,
ThreadTest* test,
ThreadActionType func_type,
std::string file,
int line);
ThreadActionSetterPtr& SetArg(void* arg,
std::string resource_name,
ThreadTest* test);
ThreadActionSetterPtr& SetThreadId(int tid);
ThreadActionSetterPtr& SetAtMutex(pthread_mutex_t* mutex,
std::string resource_name,
ThreadTest* test);
ThreadActionSetterPtr& SetAtConditionVariable(pthread_cond_t* cond,
std::string resource_name,
ThreadTest* test);
ThreadActionSetterPtr& SetActionBeforeAfter(ThreadActionOrder order);
ThreadActionSetterPtr& SetActionName(ThreadActionNestedIn name);
ThreadActionSetterPtr& SetActionFreq(ThreadActionFreq freq);
private:
ThreadActionSetter* ptr_;
};
//const int CHECK_THIS_SYNC_POINT_ALWAYS = -1;
//const int STOP_CHECKING_THIS_SYNC_POINT = 0;
//const int CHECK_THIS_SYNC_POINT_AT_ALL_THREADS = ALL_THREADS;
enum OrderListType {
SINGLE_LIST,
CIRCULAR_LIST,
};
class SyncPointHelper {
struct SyncPoint {
SyncPoint() : is_done(false),
remained_check_num(1),
hit_num(0),
thread_num(ALL_THREADS) {
}
bool is_done;
int remained_check_num;
int hit_num;
int thread_num;
};
struct SyncPointOrderList {
SyncPointOrderList(OrderListType t) : type(t),
is_done(false),
sync_point_v() {
}
OrderListType type;
// used for SINGLE_LIST:
bool is_done;
std::vector<SyncPoint> sync_point_v;
};
struct SyncPointOrderIndex {
SyncPointOrderIndex(int list_n, int element_n) :
list_num(list_n) {
element_num.push_back(element_n);
}
int list_num;
std::vector<int> element_num;
};
typedef std::vector<SyncPointOrderIndex> SyncPointOrderListIndex;
public:
SyncPointHelper();
~SyncPointHelper();
SyncPointHelper& SetFileName(const char* filename);
SyncPointHelper& SetLineNumber(const char* linenum);
int SetSyncPointName(const char* sync_point_name);
SyncPointHelper& CreateList(OrderListType type);
SyncPointHelper& AddListNode(const char* sync_point_name);
SyncPointHelper& SetThreadId(int tid);
SyncPointHelper& SetTimes(int must_run_times);
void PreprocessLists();
void Update(int bk, int tid);
bool Check(int bk, int tid);
private:
std::string tmp_file_name_;
std::string tmp_line_num_;
std::map<int, std::string> gdb_bk_2_sync_name_;
std::map<std::string, int> sync_name_2_gdb_bk_;
std::map<int, SyncPointOrderListIndex> sync_point_index_list_;
std::vector<SyncPointOrderList> sync_point_order_list_;
bool is_skip_;
int curr_sync_point_order_list_;
int curr_sync_point_index_;
};
class ThreadTestFilter {
public:
private:
};
#endif
| [
"adrian.y.dm@gmail.com"
] | adrian.y.dm@gmail.com |
60474b79a5efc2eea460f5e0181a34d7958c0341 | 4726929e9ddcbaea59df5f0493dd11d1adf222e3 | /tutorials-src/graphics/intro-to-graphics/skybox/RenderManager.cpp | 79b901fd565d5adb8cd0eeb52498edf18cb20fe1 | [] | no_license | liam-middlebrook/graphics-tutorials | aeb48ce4fdec2accdfb582da65de5bad1a22ca55 | d3cd2c218c760236abaffaf3dc11e794b39300bd | refs/heads/master | 2021-01-10T08:43:34.198902 | 2015-11-24T21:27:57 | 2015-11-24T21:27:57 | 43,909,988 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,239 | cpp | #include "RenderManager.h"
#include "ResourceManager.h"
#include "RenderObject.h"
#include "CameraManager.h"
std::vector<RenderObject*> RenderManager::_displayList;
unsigned int RenderManager::_displayListLength;
void RenderManager::Init(unsigned int numRenderObjects)
{
_displayListLength = numRenderObjects;
_displayList = std::vector<RenderObject*>();
_displayList.reserve(numRenderObjects);
}
RenderObject* RenderManager::InitRenderObject(Mesh* mesh, GLint shader, GLenum mode, GLuint layer)
{
RenderObject* retObj = new RenderObject(mesh, shader, mode, layer);
_displayList.push_back(retObj);
return retObj;
}
void RenderManager::Update(float dt)
{
unsigned int size = _displayList.size();
for (unsigned int i = 0; i < size; ++i)
{
_displayList[i]->Update(dt);
}
}
void RenderManager::Draw(GLuint mask)
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
unsigned int size = _displayList.size();
for (unsigned int i = 0; i < size; ++i)
{
if (mask & _displayList[i]->layer())
_displayList[i]->Draw();
}
}
void RenderManager::DumpData()
{
unsigned int size = _displayList.size();
for (unsigned int i = 0; i < size; ++i)
{
delete _displayList[i];
}
}
| [
"liammiddlebrook@gmail.com"
] | liammiddlebrook@gmail.com |
095912430426e7469db05bd368007100284fa39c | b9bb2153e5bcabf7ebc3f753120703d169e81bd5 | /stats.h | ae7933f8a9b1c2e41065b99b2f4ac2437c1fe028 | [] | no_license | ucsb-cs24-w18/pa01_Roy766 | c5027e7aea49d962971f47111f7cce600f9386ff | 3650644dfb4465b8f819da97ecf8d9aeb304ac70 | refs/heads/master | 2021-05-02T07:38:04.990327 | 2018-02-09T01:27:43 | 2018-02-09T01:27:43 | 120,834,127 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,944 | h | // Aidan Babb, 9AM
// FILE: stats.h
// Written by: Michael Main (main@colorado.edu)
// CLASS PROVIDED: statistician
// (a class to keep track of statistics on a sequence of real numbers)
// This class is part of the namespace main_savitch_2C.
//
// CONSTRUCTOR for the statistician class:
// statistician( );
// Postcondition: The object has been initialized, and is ready to accept
// a sequence of numbers. Various statistics will be calculated about the
// sequence.
//
// PUBLIC MODIFICATION member functions for the statistician class:
// void next(double r)
// The number r has been given to the statistician as the next number in
// its sequence of numbers.
// void reset( );
// Postcondition: The statistician has been cleared, as if no numbers had
// yet been given to it.
//
// PUBLIC CONSTANT member functions for the statistician class:
// int length( ) const
// Postcondition: The return value is the length of the sequence that has
// been given to the statistician (i.e., the number of times that the
// next(r) function has been activated).
// double sum( ) const
// Postcondition: The return value is the sum of all the numbers in the
// statistician's sequence.
// double mean( ) const
// Precondition: length( ) > 0
// Postcondition: The return value is the arithmetic mean (i.e., the
// average of all the numbers in the statistician's sequence).
// double minimum( ) const
// Precondition: length( ) > 0
// Postcondition: The return value is the tiniest number in the
// statistician's sequence.
// double maximum( ) const
// Precondition: length( ) > 0
// Postcondition: The return value is the largest number in the
// statistician's sequence.
//
// NON-MEMBER functions for the statistician class:
// statistician operator +(const statistician& s1, const statistician& s2)
// Postcondition: The statistician that is returned contains all the
// numbers of the sequences of s1 and s2.
// statistician operator *(double scale, const statistician& s)
// Postcondition: The statistician that is returned contains the same
// numbers that s does, but each number has been multiplied by the
// scale number.
// bool operator ==(const statistician& s1, const statistician& s2)
// Postcondition: The return value is true if s1 and s2 have the zero
// length. Also, if the length is greater than zero, then s1 and s2 must
// have the same length, the same mean, the same minimum,
// the same maximum, and the same sum.
//
// VALUE SEMANTICS for the statistician class:
// Assignments and the copy constructor may be used with statistician objects.
#ifndef STATS_H // Prevent duplicate definition
#define STATS_H
namespace main_savitch_2C
{
class statistician
{
public:
// CONSTRUCTOR
statistician( );
// MODIFICATION MEMBER FUNCTIONS
void next(double r);
void reset( );
// CONSTANT MEMBER FUNCTIONS
int length( ) const { return count; }
double sum( ) const { return total; }
double mean( ) const;
double minimum( ) const;
double maximum( ) const;
// FRIEND FUNCTIONS
friend statistician operator +
(const statistician& s1, const statistician& s2);
friend statistician operator *
(double scale, const statistician& s);
private:
int count; // How many numbers in the sequence
double total; // The sum of all the numbers in the sequence
double tiniest; // The smallest number in the sequence
double largest; // The largest number in the sequence
};
// NON-MEMBER functions for the statistician class
bool operator ==(const statistician& s1, const statistician& s2);
}
#endif
| [
"noreply@github.com"
] | ucsb-cs24-w18.noreply@github.com |
60e0c87a2fdff84bf60f4091a70124bad6b649ad | ae73fd7cb1b075566c98187f509679a54a386855 | /LeetCode/zigzag-conversion.cpp | 4170d5ce1efaca32d38c36e14da8956b0f32d4e4 | [] | no_license | yaolili/cracking-the-coding-interview | f5b84cdea420a2d2516d0fd5054203b6ba23a830 | 7cd628f008613a24b8faf51b363bb300bf10b2f6 | refs/heads/master | 2020-12-28T19:47:40.800342 | 2014-09-24T06:28:07 | 2014-09-24T06:28:07 | 26,939,570 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 965 | cpp | class Solution {
public:
string convert(string s, int nRows) {
if (nRows <= 1) return s;
vector<vector<char> > v(nRows);
bool zig=true;
auto it = s.begin();
int zigRow = 0;
while (it != s.end()) {
if (zig) {
for (int r = 0; r < nRows; ++r) {
if (it == s.end()) break;
v[r].push_back(*it);
++it;
}
zigRow = nRows-2;
if (zigRow != 0) zig = false;
} else {
v[zigRow].push_back(*it);
++it;
--zigRow;
if (zigRow == 0) zig = true;
}
}
string res;
for (const auto &x: v)
for (const auto &y: x)
res += y;
return res;
}
};
| [
"qiangrw@gmail.com"
] | qiangrw@gmail.com |
15b06182d069aa88788b30ba569e97243b94de5e | f906af552bf1ef05dd53e80634ff85edebfef6e1 | /ITK/vvITKThresholdImageToPaintbrush.cxx | 26e93a2b9731289cbe85766fe0a6db8dc4a34d6e | [] | no_license | eglrp/VolViewPlugins | a82d06223d22f2990d97e043edcfb492786b7f3d | 2e77a64c71af72d89dff5c4c364c04156feab4e9 | refs/heads/master | 2020-04-02T04:02:48.892187 | 2017-04-02T10:12:26 | 2017-04-02T10:12:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,935 | cxx | /*=========================================================================
Copyright (c) Kitware, Inc.
All rights reserved.
See Copyright.txt or http://www.kitware.com/VolViewCopyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vvITKPaintbrushRunnerBase.h"
// =======================================================================
// The main class definition
// =======================================================================
template <class PixelType, class LabelPixelType >
class ThresholdImageToPaintbrushRunner :
public PaintbrushRunnerBase< PixelType, LabelPixelType >
{
public:
// define our typedefs
typedef PaintbrushRunnerBase< PixelType, LabelPixelType > Superclass;
typedef typename Superclass::ImageConstIteratorType ImageConstIteratorType;
typedef typename Superclass::LabelIteratorType LabelIteratorType;
ThresholdImageToPaintbrushRunner() {};
// Description:
// The actual execute method
virtual int Execute( vtkVVPluginInfo *info, vtkVVProcessDataStruct *pds );
};
// =======================================================================
// Main execute method
template <class PixelType, class LabelPixelType>
int ThresholdImageToPaintbrushRunner<PixelType,LabelPixelType>::
Execute( vtkVVPluginInfo *info, vtkVVProcessDataStruct *pds )
{
this->Superclass::Execute(info, pds);
const float lowerThreshold = atof( info->GetGUIProperty(info, 0, VVP_GUI_VALUE ));
const float upperThreshold = atof( info->GetGUIProperty(info, 1, VVP_GUI_VALUE ));
const unsigned int labelValue = atoi( info->GetGUIProperty(info, 2, VVP_GUI_VALUE ));
const bool replace = atoi( info->GetGUIProperty(info, 3, VVP_GUI_VALUE)) ? true : false;
ImageConstIteratorType iit( this->m_ImportFilter->GetOutput(),
this->m_ImportFilter->GetOutput()->GetBufferedRegion());
LabelIteratorType lit( this->m_LabelImportFilter->GetOutput(),
this->m_LabelImportFilter->GetOutput()->GetBufferedRegion());
info->UpdateProgress(info,0.1,"Beginning thresholding..");
unsigned long nPixelsThresholded = 0;
PixelType pixel;
for (iit.GoToBegin(), lit.GoToBegin(); !iit.IsAtEnd(); ++iit, ++lit)
{
pixel = iit.Get();
if (pixel >= lowerThreshold && pixel <= upperThreshold)
{
lit.Set(labelValue);
++nPixelsThresholded;
}
else if (replace)
{
lit.Set(0);
}
}
info->UpdateProgress(info,1.0,"Done thresholding.");
char results[1024];
sprintf(results,"Number of Pixels thresholded: %lu", nPixelsThresholded);
info->SetProperty(info, VVP_REPORT_TEXT, results);
return 0;
}
// =======================================================================
static int ProcessData(void *inf, vtkVVProcessDataStruct *pds)
{
vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf;
// do some error checking
if (!pds->inLabelData)
{
info->SetProperty(
info, VVP_ERROR, "Create a label map with the paintbrush first.");
return 1;
}
if (info->InputVolumeNumberOfComponents != 1)
{
info->SetProperty(
info, VVP_ERROR, "The input volume must be single component.");
return 1;
}
// Execute
vvITKPaintbrushRunnerExecuteTemplateMacro(
ThresholdImageToPaintbrushRunner, info, pds );
}
// =======================================================================
static int UpdateGUI(void *inf)
{
char tmp[1024], lower[256], upper[256];
vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf;
/* set the range of the sliders */
double stepSize = 1.0;
if (info->InputVolumeScalarType == VTK_FLOAT ||
info->InputVolumeScalarType == VTK_DOUBLE)
{
/* for float and double use a step size of 1/200 th the range */
stepSize = info->InputVolumeScalarRange[1]*0.005 -
info->InputVolumeScalarRange[0]*0.005;
}
sprintf(tmp,"%g %g %g",
info->InputVolumeScalarRange[0],
info->InputVolumeScalarRange[1],
stepSize);
sprintf(lower,"%g", info->InputVolumeScalarRange[0]);
sprintf(upper,"%g", info->InputVolumeScalarRange[1]);
info->SetGUIProperty(info, 0, VVP_GUI_LABEL, "Lower Threshold");
info->SetGUIProperty(info, 0, VVP_GUI_TYPE, VVP_GUI_SCALE);
info->SetGUIProperty(info, 0, VVP_GUI_DEFAULT, lower);
info->SetGUIProperty(info, 0, VVP_GUI_HELP, "Lower value for the range");
info->SetGUIProperty(info, 0, VVP_GUI_HINTS , tmp);
info->SetGUIProperty(info, 1, VVP_GUI_LABEL, "Upper Threshold");
info->SetGUIProperty(info, 1, VVP_GUI_TYPE, VVP_GUI_SCALE);
info->SetGUIProperty(info, 1, VVP_GUI_DEFAULT, upper);
info->SetGUIProperty(info, 1, VVP_GUI_HELP, "Upper value for the range");
info->SetGUIProperty(info, 1, VVP_GUI_HINTS , tmp);
info->SetGUIProperty(info, 2, VVP_GUI_LABEL, "Paintbrush Label");
info->SetGUIProperty(info, 2, VVP_GUI_TYPE, VVP_GUI_SCALE);
info->SetGUIProperty(info, 2, VVP_GUI_DEFAULT, "1");
info->SetGUIProperty(info, 2, VVP_GUI_HELP, "Paintbrush label value to fill. Voxels within the supplied threshold range will be accumulated into the label value for the selected paintbrush.");
info->SetGUIProperty(info, 2, VVP_GUI_HINTS , "1 255 1");
info->SetGUIProperty(info, 3, VVP_GUI_LABEL, "Replace ?");
info->SetGUIProperty(info, 3, VVP_GUI_TYPE, VVP_GUI_CHECKBOX);
info->SetGUIProperty(info, 3, VVP_GUI_DEFAULT, "1");
info->SetGUIProperty(info, 3, VVP_GUI_HELP, "The thresholding can replace the existing paintbrush label values or augment to the existing paintbrush label values.");
info->OutputVolumeScalarType = info->InputVolumeScalarType;
info->OutputVolumeNumberOfComponents = info->InputVolumeNumberOfComponents;
memcpy(info->OutputVolumeDimensions,info->InputVolumeDimensions,3*sizeof(int));
memcpy(info->OutputVolumeSpacing,info->InputVolumeSpacing,3*sizeof(float));
memcpy(info->OutputVolumeOrigin,info->InputVolumeOrigin,3*sizeof(float));
// really the memory consumption is one copy of the input + the size of the
// label pixel
sprintf(tmp,"%f", (double)(info->InputVolumeScalarSize + 1));
info->SetProperty(info, VVP_PER_VOXEL_MEMORY_REQUIRED, tmp);
return 1;
}
// =======================================================================
extern "C" {
void VV_PLUGIN_EXPORT vvITKThresholdImageToPaintbrushInit(vtkVVPluginInfo *info)
{
vvPluginVersionCheck();
// setup information that never changes
info->ProcessData = ProcessData;
info->UpdateGUI = UpdateGUI;
info->SetProperty(info, VVP_NAME, "Threshold to Paintbrush");
info->SetProperty(info, VVP_GROUP, "NIRFast Modules");
info->SetProperty(info, VVP_TERSE_DOCUMENTATION,
"Threshold to a Paintbrush label map.");
info->SetProperty(info, VVP_FULL_DOCUMENTATION,
"This plugin takes an image and appends a paintbrush label map for voxels that lie within the supplied thresholds. Both threshold values are inclusive. The label value indicates the sketch that is appended into the paintbrush.");
info->SetProperty(info, VVP_SUPPORTS_IN_PLACE_PROCESSING, "1");
info->SetProperty(info, VVP_REQUIRES_LABEL_INPUT, "1");
info->SetProperty(info, VVP_NUMBER_OF_GUI_ITEMS, "4");
info->SetProperty(info, VVP_SUPPORTS_PROCESSING_PIECES, "0");
info->SetProperty(info, VVP_REQUIRED_Z_OVERLAP, "0");
info->SetProperty(info, VVP_PER_VOXEL_MEMORY_REQUIRED, "0");
info->SetProperty(info, VVP_REQUIRES_SECOND_INPUT, "0");
info->SetProperty(info, VVP_REQUIRES_SERIES_INPUT, "0");
info->SetProperty(info, VVP_SUPPORTS_PROCESSING_SERIES_BY_VOLUMES, "0");
info->SetProperty(info, VVP_PRODUCES_OUTPUT_SERIES, "0");
info->SetProperty(info, VVP_PRODUCES_PLOTTING_OUTPUT, "0");
}
}
| [
"lzf@mail.bnu.edu.cn"
] | lzf@mail.bnu.edu.cn |
60c868d6ec01b1ad8573a36dcebfc476bb726efc | e3170964ef1007e68ae6598885720eaef5b4360c | /c++/problem11/main.cpp | e2239933caba9ffd6fe07f1553ebb183c44f0b4a | [] | no_license | SunnyQjm/leecode | 66a0426249971c850c0977502730d462b9db7e0f | eceb63b0d374f0783d19dc9c5dd776adbf82af85 | refs/heads/master | 2020-12-21T10:39:32.717955 | 2020-02-10T03:15:42 | 2020-02-10T03:15:42 | 236,405,770 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 343 | cpp | #include <iostream>
#include <gtest/gtest.h>
#include "solution.cpp"
using namespace std;
Solution solution;
TEST(Leetcode11_maxArea, test0) {
vector<int> v = {1, 8, 6, 2, 5, 4, 8, 3, 7};
EXPECT_EQ(solution.maxArea(v), 49);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| [
"qjm253@pku.edu.cn"
] | qjm253@pku.edu.cn |
580fa0452846f0f3762e97a53f26d569f72351d7 | 3b9b4049a8e7d38b49e07bb752780b2f1d792851 | /src/native_client/toolchain/linux_x86/pnacl_newlib/include/llvm/IR/GlobalVariable.h | 9f57705dae72e5dba7c145ab189823a2bc5802f3 | [
"BSD-3-Clause",
"Apache-2.0",
"Zlib",
"Classpath-exception-2.0",
"BSD-Source-Code",
"LZMA-exception",
"LicenseRef-scancode-unicode",
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"LicenseRef-scancode-philippe-de-muyter",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-intel-osl-1993",
... | permissive | webosce/chromium53 | f8e745e91363586aee9620c609aacf15b3261540 | 9171447efcf0bb393d41d1dc877c7c13c46d8e38 | refs/heads/webosce | 2020-03-26T23:08:14.416858 | 2018-08-23T08:35:17 | 2018-09-20T14:25:18 | 145,513,343 | 0 | 2 | Apache-2.0 | 2019-08-21T22:44:55 | 2018-08-21T05:52:31 | null | UTF-8 | C++ | false | false | 7,572 | h | //===-- llvm/GlobalVariable.h - GlobalVariable class ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the GlobalVariable class, which
// represents a single global variable (or constant) in the VM.
//
// Global variables are constant pointers that refer to hunks of space that are
// allocated by either the VM, or by the linker in a static compiler. A global
// variable may have an initial value, which is copied into the executables .data
// area. Global Constants are required to have initializers.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_GLOBALVARIABLE_H
#define LLVM_IR_GLOBALVARIABLE_H
#include "llvm/ADT/Twine.h"
#include "llvm/ADT/ilist_node.h"
#include "llvm/IR/GlobalObject.h"
#include "llvm/IR/OperandTraits.h"
namespace llvm {
class Module;
class Constant;
template<typename ValueSubClass, typename ItemParentClass>
class SymbolTableListTraits;
class GlobalVariable : public GlobalObject, public ilist_node<GlobalVariable> {
friend class SymbolTableListTraits<GlobalVariable, Module>;
void *operator new(size_t, unsigned) = delete;
void operator=(const GlobalVariable &) = delete;
GlobalVariable(const GlobalVariable &) = delete;
void setParent(Module *parent);
bool isConstantGlobal : 1; // Is this a global constant?
bool isExternallyInitializedConstant : 1; // Is this a global whose value
// can change from its initial
// value before global
// initializers are run?
public:
// allocate space for exactly one operand
void *operator new(size_t s) {
return User::operator new(s, 1);
}
/// GlobalVariable ctor - If a parent module is specified, the global is
/// automatically inserted into the end of the specified modules global list.
GlobalVariable(Type *Ty, bool isConstant, LinkageTypes Linkage,
Constant *Initializer = nullptr, const Twine &Name = "",
ThreadLocalMode = NotThreadLocal, unsigned AddressSpace = 0,
bool isExternallyInitialized = false);
/// GlobalVariable ctor - This creates a global and inserts it before the
/// specified other global.
GlobalVariable(Module &M, Type *Ty, bool isConstant,
LinkageTypes Linkage, Constant *Initializer,
const Twine &Name = "", GlobalVariable *InsertBefore = nullptr,
ThreadLocalMode = NotThreadLocal, unsigned AddressSpace = 0,
bool isExternallyInitialized = false);
~GlobalVariable() override {
NumOperands = 1; // FIXME: needed by operator delete
}
/// Provide fast operand accessors
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
/// Definitions have initializers, declarations don't.
///
inline bool hasInitializer() const { return !isDeclaration(); }
/// hasDefinitiveInitializer - Whether the global variable has an initializer,
/// and any other instances of the global (this can happen due to weak
/// linkage) are guaranteed to have the same initializer.
///
/// Note that if you want to transform a global, you must use
/// hasUniqueInitializer() instead, because of the *_odr linkage type.
///
/// Example:
///
/// @a = global SomeType* null - Initializer is both definitive and unique.
///
/// @b = global weak SomeType* null - Initializer is neither definitive nor
/// unique.
///
/// @c = global weak_odr SomeType* null - Initializer is definitive, but not
/// unique.
inline bool hasDefinitiveInitializer() const {
return hasInitializer() &&
// The initializer of a global variable with weak linkage may change at
// link time.
!mayBeOverridden() &&
// The initializer of a global variable with the externally_initialized
// marker may change at runtime before C++ initializers are evaluated.
!isExternallyInitialized();
}
/// hasUniqueInitializer - Whether the global variable has an initializer, and
/// any changes made to the initializer will turn up in the final executable.
inline bool hasUniqueInitializer() const {
return hasInitializer() &&
// It's not safe to modify initializers of global variables with weak
// linkage, because the linker might choose to discard the initializer and
// use the initializer from another instance of the global variable
// instead. It is wrong to modify the initializer of a global variable
// with *_odr linkage because then different instances of the global may
// have different initializers, breaking the One Definition Rule.
!isWeakForLinker() &&
// It is not safe to modify initializers of global variables with the
// external_initializer marker since the value may be changed at runtime
// before C++ initializers are evaluated.
!isExternallyInitialized();
}
/// getInitializer - Return the initializer for this global variable. It is
/// illegal to call this method if the global is external, because we cannot
/// tell what the value is initialized to!
///
inline const Constant *getInitializer() const {
assert(hasInitializer() && "GV doesn't have initializer!");
return static_cast<Constant*>(Op<0>().get());
}
inline Constant *getInitializer() {
assert(hasInitializer() && "GV doesn't have initializer!");
return static_cast<Constant*>(Op<0>().get());
}
/// setInitializer - Sets the initializer for this global variable, removing
/// any existing initializer if InitVal==NULL. If this GV has type T*, the
/// initializer must have type T.
void setInitializer(Constant *InitVal);
/// If the value is a global constant, its value is immutable throughout the
/// runtime execution of the program. Assigning a value into the constant
/// leads to undefined behavior.
///
bool isConstant() const { return isConstantGlobal; }
void setConstant(bool Val) { isConstantGlobal = Val; }
bool isExternallyInitialized() const {
return isExternallyInitializedConstant;
}
void setExternallyInitialized(bool Val) {
isExternallyInitializedConstant = Val;
}
/// copyAttributesFrom - copy all additional attributes (those not needed to
/// create a GlobalVariable) from the GlobalVariable Src to this one.
void copyAttributesFrom(const GlobalValue *Src) override;
/// removeFromParent - This method unlinks 'this' from the containing module,
/// but does not delete it.
///
void removeFromParent() override;
/// eraseFromParent - This method unlinks 'this' from the containing module
/// and deletes it.
///
void eraseFromParent() override;
/// Override Constant's implementation of this method so we can
/// replace constant initializers.
void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) override;
// Methods for support type inquiry through isa, cast, and dyn_cast:
static inline bool classof(const Value *V) {
return V->getValueID() == Value::GlobalVariableVal;
}
};
template <>
struct OperandTraits<GlobalVariable> :
public OptionalOperandTraits<GlobalVariable> {
};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GlobalVariable, Value)
} // End llvm namespace
#endif
| [
"changhyeok.bae@lge.com"
] | changhyeok.bae@lge.com |
5bbe671d91f306adc7bceed5753d5ed893cae93a | 435c58b836d00db4aaaf4e19dab820a935bbf323 | /examples/Games/Dices/Dices.ino | 9f65c2c9d1f96a4b352a4dce58d94e99ea09ef47 | [] | no_license | aenertia/M5StickC | b82a01776e68d15b5343e36b7862b49320d1a272 | 781128641206017e99f211ee7bb14fce98428259 | refs/heads/master | 2020-05-30T14:29:01.310338 | 2019-05-22T08:26:52 | 2019-05-22T08:26:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,443 | ino | /*
A couple of dices on a tiny 80x160px TFT display
Author: Alfonso de Cala <alfonso@el-magnifico.org>
*/
#include <M5StickC.h>
#define DOT_SIZE 6
int dot[6][6][2] {
{{35,35}},
{{15,15},{55,55}},
{{15,15},{35,35},{55,55}},
{{15,15},{15,55},{55,15},{55,55}},
{{15,15},{15,55},{35,35},{55,15},{55,55}},
{{15,15},{15,35},{15,55},{55,15},{55,35},{55,55}},
};
int16_t accX = 0;
int16_t accY = 0;
int16_t accZ = 0;
void setup(void) {
M5.begin();
M5.IMU.Init();
M5.Lcd.setRotation(1);
M5.Lcd.fillScreen(TFT_GREEN);
M5.Lcd.setTextColor(TFT_BLACK); // Adding a background colour erases previous text automatically
M5.Lcd.setCursor(10, 30);
M5.Lcd.setTextSize(3);
M5.Lcd.print("SHAKE ME");
delay(1000);
}
void loop() {
while(1) {
M5.IMU.getAccelData(&accX,&accY,&accZ);
if (((float) accX) * M5.IMU.aRes > 1 || ((float) accY) * M5.IMU.aRes > 1 ) {
break;
}
}
M5.Lcd.fillScreen(TFT_GREEN);
// Draw first dice
delay(1000); // A little delay to increase suspense :-D
int number = random(0, 6);
draw_dice(5,5,number);
// Draw second dice
delay(1000);
number = random(0, 6);
draw_dice(85,5,number);
}
void draw_dice(int16_t x, int16_t y, int n) {
M5.Lcd.fillRect(x, y, 70, 70, WHITE);
for(int d = 0; d < 7; d++) {
if (dot[n][d][0] > 0) {
M5.Lcd.fillCircle(x+dot[n][d][0], y+dot[n][d][1], DOT_SIZE, TFT_BLACK);
}
}
}
| [
"44561832+zhouyangyale@users.noreply.github.com"
] | 44561832+zhouyangyale@users.noreply.github.com |
6543e8d6fd3ce452bcabc2e234e6f35ed65a9e66 | d15d4c2932159033e7563fe0889a2874b4822ce2 | /Codeforces/Archives/April Fools 2017/E.cpp | a8b95545ca5955a098ea93a2c802af7d64e68b75 | [
"MIT"
] | permissive | lxdlam/CP-Answers | fd0ee514d87856423cb31d28298c75647f163067 | cde519ef9732ff9e4e9e3f53c00fb30d07bdb306 | refs/heads/master | 2021-03-17T04:50:44.772167 | 2020-05-04T09:24:32 | 2020-05-04T09:24:32 | 86,518,969 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 270 | cpp | #include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int a, b, c, d;
cin >> a >> b >> c >> d;
int e = a ^ b, f = c | d, g = b & c, h = a ^ d;
int aa = e & f, bb = g | h;
cout << (aa ^ bb) << endl;
return 0;
} | [
"lxdlam@gmail.com"
] | lxdlam@gmail.com |
fd9ef84aff0dbc8cbfb513e6996a339d8c35ecfd | 0d8616b10c58006187911f930c002213275229e4 | /src/policy/feerate.cpp | 617d2cf8d4d56a8f4868439a3c8b319a0a1db84c | [
"MIT"
] | permissive | biocarecoin/biocarecoin | 1345c5d88ccabdf4d767e4f389169c90ed25b314 | acaf0cf114eb4e14af20e6ab4cd34050fe851a3f | refs/heads/master | 2023-05-01T03:44:45.448477 | 2021-05-17T05:35:09 | 2021-05-17T05:35:09 | 368,057,950 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,149 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <policy/feerate.h>
#include <tinyformat.h>
const std::string CURRENCY_UNIT = "BCR";
CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nBytes_)
{
assert(nBytes_ <= uint64_t(std::numeric_limits<int64_t>::max()));
int64_t nSize = int64_t(nBytes_);
if (nSize > 0)
nSatoshisPerK = nFeePaid * 1000 / nSize;
else
nSatoshisPerK = 0;
}
CAmount CFeeRate::GetFee(size_t nBytes_) const
{
assert(nBytes_ <= uint64_t(std::numeric_limits<int64_t>::max()));
int64_t nSize = int64_t(nBytes_);
CAmount nFee = nSatoshisPerK * nSize / 1000;
if (nFee == 0 && nSize != 0) {
if (nSatoshisPerK > 0)
nFee = CAmount(1);
if (nSatoshisPerK < 0)
nFee = CAmount(-1);
}
return nFee;
}
std::string CFeeRate::ToString() const
{
return strprintf("%d.%08d %s/kB", nSatoshisPerK / COIN, nSatoshisPerK % COIN, CURRENCY_UNIT);
}
| [
"adamantcoders@gmail.com"
] | adamantcoders@gmail.com |
f7ef372868e063db284d488a6a9b2ff2a06e9e04 | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /c++/JUCE/2015/8/OpenGLDemo.cpp | cb36c8eeb529d66c6f3175d5a849521a702a7265 | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | C++ | false | false | 46,320 | cpp | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2015 - ROLI Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#include "../JuceDemoHeader.h"
#if JUCE_OPENGL
#include "WavefrontObjParser.h"
//==============================================================================
struct OpenGLDemoClasses
{
/** Vertex data to be passed to the shaders.
For the purposes of this demo, each vertex will have a 3D position, a colour and a
2D texture co-ordinate. Of course you can ignore these or manipulate them in the
shader programs but are some useful defaults to work from.
*/
struct Vertex
{
float position[3];
float normal[3];
float colour[4];
float texCoord[2];
};
//==============================================================================
// This class just manages the attributes that the demo shaders use.
struct Attributes
{
Attributes (OpenGLContext& openGLContext, OpenGLShaderProgram& shader)
{
position = createAttribute (openGLContext, shader, "position");
normal = createAttribute (openGLContext, shader, "normal");
sourceColour = createAttribute (openGLContext, shader, "sourceColour");
texureCoordIn = createAttribute (openGLContext, shader, "texureCoordIn");
}
void enable (OpenGLContext& openGLContext)
{
if (position != nullptr)
{
openGLContext.extensions.glVertexAttribPointer (position->attributeID, 3, GL_FLOAT, GL_FALSE, sizeof (Vertex), 0);
openGLContext.extensions.glEnableVertexAttribArray (position->attributeID);
}
if (normal != nullptr)
{
openGLContext.extensions.glVertexAttribPointer (normal->attributeID, 3, GL_FLOAT, GL_FALSE, sizeof (Vertex), (GLvoid*) (sizeof (float) * 3));
openGLContext.extensions.glEnableVertexAttribArray (normal->attributeID);
}
if (sourceColour != nullptr)
{
openGLContext.extensions.glVertexAttribPointer (sourceColour->attributeID, 4, GL_FLOAT, GL_FALSE, sizeof (Vertex), (GLvoid*) (sizeof (float) * 6));
openGLContext.extensions.glEnableVertexAttribArray (sourceColour->attributeID);
}
if (texureCoordIn != nullptr)
{
openGLContext.extensions.glVertexAttribPointer (texureCoordIn->attributeID, 2, GL_FLOAT, GL_FALSE, sizeof (Vertex), (GLvoid*) (sizeof (float) * 10));
openGLContext.extensions.glEnableVertexAttribArray (texureCoordIn->attributeID);
}
}
void disable (OpenGLContext& openGLContext)
{
if (position != nullptr) openGLContext.extensions.glDisableVertexAttribArray (position->attributeID);
if (normal != nullptr) openGLContext.extensions.glDisableVertexAttribArray (normal->attributeID);
if (sourceColour != nullptr) openGLContext.extensions.glDisableVertexAttribArray (sourceColour->attributeID);
if (texureCoordIn != nullptr) openGLContext.extensions.glDisableVertexAttribArray (texureCoordIn->attributeID);
}
ScopedPointer<OpenGLShaderProgram::Attribute> position, normal, sourceColour, texureCoordIn;
private:
static OpenGLShaderProgram::Attribute* createAttribute (OpenGLContext& openGLContext,
OpenGLShaderProgram& shader,
const char* attributeName)
{
if (openGLContext.extensions.glGetAttribLocation (shader.getProgramID(), attributeName) < 0)
return nullptr;
return new OpenGLShaderProgram::Attribute (shader, attributeName);
}
};
//==============================================================================
// This class just manages the uniform values that the demo shaders use.
struct Uniforms
{
Uniforms (OpenGLContext& openGLContext, OpenGLShaderProgram& shader)
{
projectionMatrix = createUniform (openGLContext, shader, "projectionMatrix");
viewMatrix = createUniform (openGLContext, shader, "viewMatrix");
texture = createUniform (openGLContext, shader, "demoTexture");
lightPosition = createUniform (openGLContext, shader, "lightPosition");
bouncingNumber = createUniform (openGLContext, shader, "bouncingNumber");
}
ScopedPointer<OpenGLShaderProgram::Uniform> projectionMatrix, viewMatrix, texture, lightPosition, bouncingNumber;
private:
static OpenGLShaderProgram::Uniform* createUniform (OpenGLContext& openGLContext,
OpenGLShaderProgram& shader,
const char* uniformName)
{
if (openGLContext.extensions.glGetUniformLocation (shader.getProgramID(), uniformName) < 0)
return nullptr;
return new OpenGLShaderProgram::Uniform (shader, uniformName);
}
};
//==============================================================================
/** This loads a 3D model from an OBJ file and converts it into some vertex buffers
that we can draw.
*/
struct Shape
{
Shape (OpenGLContext& openGLContext)
{
if (shapeFile.load (BinaryData::teapot_obj).wasOk())
for (int i = 0; i < shapeFile.shapes.size(); ++i)
vertexBuffers.add (new VertexBuffer (openGLContext, *shapeFile.shapes.getUnchecked(i)));
}
void draw (OpenGLContext& openGLContext, Attributes& attributes)
{
for (int i = 0; i < vertexBuffers.size(); ++i)
{
VertexBuffer& vertexBuffer = *vertexBuffers.getUnchecked (i);
vertexBuffer.bind();
attributes.enable (openGLContext);
glDrawElements (GL_TRIANGLES, vertexBuffer.numIndices, GL_UNSIGNED_INT, 0);
attributes.disable (openGLContext);
}
}
private:
struct VertexBuffer
{
VertexBuffer (OpenGLContext& context, WavefrontObjFile::Shape& shape) : openGLContext (context)
{
numIndices = shape.mesh.indices.size();
openGLContext.extensions.glGenBuffers (1, &vertexBuffer);
openGLContext.extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer);
Array<Vertex> vertices;
createVertexListFromMesh (shape.mesh, vertices, Colours::green);
openGLContext.extensions.glBufferData (GL_ARRAY_BUFFER, vertices.size() * (int) sizeof (Vertex),
vertices.getRawDataPointer(), GL_STATIC_DRAW);
openGLContext.extensions.glGenBuffers (1, &indexBuffer);
openGLContext.extensions.glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
openGLContext.extensions.glBufferData (GL_ELEMENT_ARRAY_BUFFER, numIndices * (int) sizeof (juce::uint32),
shape.mesh.indices.getRawDataPointer(), GL_STATIC_DRAW);
}
~VertexBuffer()
{
openGLContext.extensions.glDeleteBuffers (1, &vertexBuffer);
openGLContext.extensions.glDeleteBuffers (1, &indexBuffer);
}
void bind()
{
openGLContext.extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer);
openGLContext.extensions.glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
}
GLuint vertexBuffer, indexBuffer;
int numIndices;
OpenGLContext& openGLContext;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VertexBuffer)
};
WavefrontObjFile shapeFile;
OwnedArray<VertexBuffer> vertexBuffers;
static void createVertexListFromMesh (const WavefrontObjFile::Mesh& mesh, Array<Vertex>& list, Colour colour)
{
const float scale = 0.2f;
WavefrontObjFile::TextureCoord defaultTexCoord = { 0.5f, 0.5f };
WavefrontObjFile::Vertex defaultNormal = { 0.5f, 0.5f, 0.5f };
for (int i = 0; i < mesh.vertices.size(); ++i)
{
const WavefrontObjFile::Vertex& v = mesh.vertices.getReference (i);
const WavefrontObjFile::Vertex& n
= i < mesh.normals.size() ? mesh.normals.getReference (i) : defaultNormal;
const WavefrontObjFile::TextureCoord& tc
= i < mesh.textureCoords.size() ? mesh.textureCoords.getReference (i) : defaultTexCoord;
Vertex vert =
{
{ scale * v.x, scale * v.y, scale * v.z, },
{ scale * n.x, scale * n.y, scale * n.z, },
{ colour.getFloatRed(), colour.getFloatGreen(), colour.getFloatBlue(), colour.getFloatAlpha() },
{ tc.x, tc.y }
};
list.add (vert);
}
}
};
//==============================================================================
// These classes are used to load textures from the various sources that the demo uses..
struct DemoTexture
{
virtual ~DemoTexture() {}
virtual bool applyTo (OpenGLTexture&) = 0;
String name;
};
struct DynamicTexture : public DemoTexture
{
DynamicTexture() { name = "Dynamically-generated texture"; }
Image image;
BouncingNumber x, y;
bool applyTo (OpenGLTexture& texture) override
{
const int size = 128;
if (! image.isValid())
image = Image (Image::ARGB, size, size, true);
{
Graphics g (image);
g.fillAll (Colours::lightcyan);
g.setColour (Colours::darkred);
g.drawRect (0, 0, size, size, 2);
g.setColour (Colours::green);
g.fillEllipse (x.getValue() * size * 0.9f, y.getValue() * size * 0.9f, size * 0.1f, size * 0.1f);
g.setColour (Colours::black);
g.setFont (40);
g.drawFittedText (String (Time::getCurrentTime().getMilliseconds()), image.getBounds(), Justification::centred, 1);
}
texture.loadImage (image);
return true;
}
};
struct BuiltInTexture : public DemoTexture
{
BuiltInTexture (const char* nm, const void* imageData, size_t imageSize)
: image (resizeImageToPowerOfTwo (ImageFileFormat::loadFrom (imageData, imageSize)))
{
name = nm;
}
Image image;
bool applyTo (OpenGLTexture& texture) override
{
texture.loadImage (image);
return false;
}
};
struct TextureFromFile : public DemoTexture
{
TextureFromFile (const File& file)
{
name = file.getFileName();
image = resizeImageToPowerOfTwo (ImageFileFormat::loadFrom (file));
}
Image image;
bool applyTo (OpenGLTexture& texture) override
{
texture.loadImage (image);
return false;
}
};
static Image resizeImageToPowerOfTwo (Image image)
{
if (! (isPowerOfTwo (image.getWidth()) && isPowerOfTwo (image.getHeight())))
return image.rescaled (jmin (1024, nextPowerOfTwo (image.getWidth())),
jmin (1024, nextPowerOfTwo (image.getHeight())));
return image;
}
class OpenGLDemo;
//==============================================================================
/**
This component sits on top of the main GL demo, and contains all the sliders
and widgets that control things.
*/
class DemoControlsOverlay : public Component,
private CodeDocument::Listener,
private ComboBox::Listener,
private Slider::Listener,
private Button::Listener,
private Timer
{
public:
DemoControlsOverlay (OpenGLDemo& d)
: demo (d),
vertexEditorComp (vertexDocument, nullptr),
fragmentEditorComp (fragmentDocument, nullptr),
tabbedComp (TabbedButtonBar::TabsAtLeft),
showBackgroundToggle ("Draw 2D graphics in background")
{
addAndMakeVisible (statusLabel);
statusLabel.setJustificationType (Justification::topLeft);
statusLabel.setColour (Label::textColourId, Colours::black);
statusLabel.setFont (Font (14.0f));
addAndMakeVisible (sizeSlider);
sizeSlider.setRange (0.0, 1.0, 0.001);
sizeSlider.addListener (this);
addAndMakeVisible (zoomLabel);
zoomLabel.setText ("Zoom:", dontSendNotification);
zoomLabel.attachToComponent (&sizeSlider, true);
addAndMakeVisible (speedSlider);
speedSlider.setRange (0.0, 0.5, 0.001);
speedSlider.addListener (this);
speedSlider.setSkewFactor (0.5f);
addAndMakeVisible (speedLabel);
speedLabel.setText ("Speed:", dontSendNotification);
speedLabel.attachToComponent (&speedSlider, true);
addAndMakeVisible (showBackgroundToggle);
showBackgroundToggle.addListener (this);
Colour editorBackground (Colours::white.withAlpha (0.6f));
addAndMakeVisible (tabbedComp);
tabbedComp.setTabBarDepth (25);
tabbedComp.setColour (TabbedButtonBar::tabTextColourId, Colours::grey);
tabbedComp.addTab ("Vertex", editorBackground, &vertexEditorComp, false);
tabbedComp.addTab ("Fragment", editorBackground, &fragmentEditorComp, false);
vertexEditorComp.setColour (CodeEditorComponent::backgroundColourId, editorBackground);
fragmentEditorComp.setColour (CodeEditorComponent::backgroundColourId, editorBackground);
vertexDocument.addListener (this);
fragmentDocument.addListener (this);
textures.add (new BuiltInTexture ("Portmeirion", BinaryData::portmeirion_jpg, BinaryData::portmeirion_jpgSize));
textures.add (new BuiltInTexture ("Tiled Background", BinaryData::tile_background_png, BinaryData::tile_background_pngSize));
textures.add (new BuiltInTexture ("JUCE logo", BinaryData::juce_icon_png, BinaryData::juce_icon_pngSize));
textures.add (new DynamicTexture());
addAndMakeVisible (textureBox);
textureBox.addListener (this);
updateTexturesList();
addAndMakeVisible (presetBox);
presetBox.addListener (this);
Array<ShaderPreset> presets (getPresets());
StringArray presetNames;
for (int i = 0; i < presets.size(); ++i)
presetBox.addItem (presets[i].name, i + 1);
addAndMakeVisible (presetLabel);
presetLabel.setText ("Shader Preset:", dontSendNotification);
presetLabel.attachToComponent (&presetBox, true);
addAndMakeVisible (textureLabel);
textureLabel.setText ("Texture:", dontSendNotification);
textureLabel.attachToComponent (&textureBox, true);
}
void initialise()
{
showBackgroundToggle.setToggleState (false, sendNotification);
textureBox.setSelectedItemIndex (0);
presetBox.setSelectedItemIndex (0);
speedSlider.setValue (0.01);
sizeSlider.setValue (0.5);
}
void resized() override
{
Rectangle<int> area (getLocalBounds().reduced (4));
Rectangle<int> top (area.removeFromTop (75));
Rectangle<int> sliders (top.removeFromRight (area.getWidth() / 2));
showBackgroundToggle.setBounds (sliders.removeFromBottom (25));
speedSlider.setBounds (sliders.removeFromBottom (25));
sizeSlider.setBounds (sliders.removeFromBottom (25));
top.removeFromRight (70);
statusLabel.setBounds (top);
Rectangle<int> shaderArea (area.removeFromBottom (area.getHeight() / 2));
Rectangle<int> presets (shaderArea.removeFromTop (25));
presets.removeFromLeft (100);
presetBox.setBounds (presets.removeFromLeft (150));
presets.removeFromLeft (100);
textureBox.setBounds (presets);
shaderArea.removeFromTop (4);
tabbedComp.setBounds (shaderArea);
}
void mouseDown (const MouseEvent& e) override
{
demo.draggableOrientation.mouseDown (e.getPosition());
}
void mouseDrag (const MouseEvent& e) override
{
demo.draggableOrientation.mouseDrag (e.getPosition());
}
void mouseWheelMove (const MouseEvent&, const MouseWheelDetails& d) override
{
sizeSlider.setValue (sizeSlider.getValue() + d.deltaY);
}
void mouseMagnify (const MouseEvent&, float magnifyAmmount) override
{
sizeSlider.setValue (sizeSlider.getValue() + magnifyAmmount - 1.0f);
}
void selectPreset (int preset)
{
const ShaderPreset& p = getPresets()[preset];
vertexDocument.replaceAllContent (p.vertexShader);
fragmentDocument.replaceAllContent (p.fragmentShader);
startTimer (1);
}
void selectTexture (int itemID)
{
#if JUCE_MODAL_LOOPS_PERMITTED
if (itemID == 1000)
{
static File lastLocation = File::getSpecialLocation (File::userPicturesDirectory);
FileChooser fc ("Choose an image to open...", lastLocation, "*.jpg;*.jpeg;*.png;*.gif");
if (fc.browseForFileToOpen())
{
lastLocation = fc.getResult();
textures.add (new TextureFromFile (fc.getResult()));
updateTexturesList();
textureBox.setSelectedId (textures.size());
}
}
else
#endif
{
if (DemoTexture* t = textures [itemID - 1])
demo.setTexture (t);
}
}
void updateTexturesList()
{
textureBox.clear();
for (int i = 0; i < textures.size(); ++i)
textureBox.addItem (textures.getUnchecked(i)->name, i + 1);
#if JUCE_MODAL_LOOPS_PERMITTED
textureBox.addSeparator();
textureBox.addItem ("Load from a file...", 1000);
#endif
}
Label statusLabel;
private:
void sliderValueChanged (Slider*) override
{
demo.scale = (float) sizeSlider.getValue();
demo.rotationSpeed = (float) speedSlider.getValue();
}
void buttonClicked (Button*) override
{
demo.doBackgroundDrawing = showBackgroundToggle.getToggleState();
}
enum { shaderLinkDelay = 500 };
void codeDocumentTextInserted (const String& /*newText*/, int /*insertIndex*/) override
{
startTimer (shaderLinkDelay);
}
void codeDocumentTextDeleted (int /*startIndex*/, int /*endIndex*/) override
{
startTimer (shaderLinkDelay);
}
void timerCallback() override
{
stopTimer();
demo.setShaderProgram (vertexDocument.getAllContent(),
fragmentDocument.getAllContent());
}
void comboBoxChanged (ComboBox* box) override
{
if (box == &presetBox)
selectPreset (presetBox.getSelectedItemIndex());
else if (box == &textureBox)
selectTexture (textureBox.getSelectedId());
}
OpenGLDemo& demo;
Label speedLabel, zoomLabel;
CodeDocument vertexDocument, fragmentDocument;
CodeEditorComponent vertexEditorComp, fragmentEditorComp;
TabbedComponent tabbedComp;
ComboBox presetBox, textureBox;
Label presetLabel, textureLabel;
Slider speedSlider, sizeSlider;
ToggleButton showBackgroundToggle;
OwnedArray<DemoTexture> textures;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DemoControlsOverlay)
};
//==============================================================================
/** This is the main demo component - the GL context gets attached to it, and
it implements the OpenGLRenderer callback so that it can do real GL work.
*/
class OpenGLDemo : public Component,
private OpenGLRenderer
{
public:
OpenGLDemo()
: doBackgroundDrawing (false),
scale (0.5f), rotationSpeed (0.0f), rotation (0.0f),
textureToUse (nullptr)
{
MainAppWindow::getMainAppWindow()->setRenderingEngine (0);
setOpaque (true);
addAndMakeVisible (controlsOverlay = new DemoControlsOverlay (*this));
openGLContext.setRenderer (this);
openGLContext.attachTo (*this);
openGLContext.setContinuousRepainting (true);
controlsOverlay->initialise();
}
~OpenGLDemo()
{
openGLContext.detach();
}
void newOpenGLContextCreated() override
{
// nothing to do in this case - we'll initialise our shaders + textures
// on demand, during the render callback.
freeAllContextObjects();
}
void openGLContextClosing() override
{
// When the context is about to close, you must use this callback to delete
// any GPU resources while the context is still current.
freeAllContextObjects();
}
void freeAllContextObjects()
{
shape = nullptr;
shader = nullptr;
attributes = nullptr;
uniforms = nullptr;
texture.release();
}
// This is a virtual method in OpenGLRenderer, and is called when it's time
// to do your GL rendering.
void renderOpenGL() override
{
jassert (OpenGLHelpers::isContextActive());
const float desktopScale = (float) openGLContext.getRenderingScale();
OpenGLHelpers::clear (Colours::lightblue);
if (textureToUse != nullptr)
if (! textureToUse->applyTo (texture))
textureToUse = nullptr;
// First draw our background graphics to demonstrate the OpenGLGraphicsContext class
if (doBackgroundDrawing)
drawBackground2DStuff (desktopScale);
updateShader(); // Check whether we need to compile a new shader
if (shader == nullptr)
return;
// Having used the juce 2D renderer, it will have messed-up a whole load of GL state, so
// we need to initialise some important settings before doing our normal GL 3D drawing..
glEnable (GL_DEPTH_TEST);
glDepthFunc (GL_LESS);
glEnable (GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
openGLContext.extensions.glActiveTexture (GL_TEXTURE0);
glEnable (GL_TEXTURE_2D);
glViewport (0, 0, roundToInt (desktopScale * getWidth()), roundToInt (desktopScale * getHeight()));
texture.bind();
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
shader->use();
if (uniforms->projectionMatrix != nullptr)
uniforms->projectionMatrix->setMatrix4 (getProjectionMatrix().mat, 1, false);
if (uniforms->viewMatrix != nullptr)
uniforms->viewMatrix->setMatrix4 (getViewMatrix().mat, 1, false);
if (uniforms->texture != nullptr)
uniforms->texture->set ((GLint) 0);
if (uniforms->lightPosition != nullptr)
uniforms->lightPosition->set (-15.0f, 10.0f, 15.0f, 0.0f);
if (uniforms->bouncingNumber != nullptr)
uniforms->bouncingNumber->set (bouncingNumber.getValue());
shape->draw (openGLContext, *attributes);
// Reset the element buffers so child Components draw correctly
openGLContext.extensions.glBindBuffer (GL_ARRAY_BUFFER, 0);
openGLContext.extensions.glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, 0);
if (! controlsOverlay->isMouseButtonDown())
rotation += (float) rotationSpeed;
}
Matrix3D<float> getProjectionMatrix() const
{
float w = 1.0f / (scale + 0.1f);
float h = w * getLocalBounds().toFloat().getAspectRatio (false);
return Matrix3D<float>::fromFrustum (-w, w, -h, h, 4.0f, 30.0f);
}
Matrix3D<float> getViewMatrix() const
{
Matrix3D<float> viewMatrix = draggableOrientation.getRotationMatrix()
* Vector3D<float> (0.0f, 1.0f, -10.0f);
Matrix3D<float> rotationMatrix = viewMatrix.rotated (Vector3D<float> (rotation, rotation, -0.3f));
return rotationMatrix * viewMatrix;
}
void setTexture (DemoTexture* t)
{
textureToUse = t;
}
void setShaderProgram (const String& vertexShader, const String& fragmentShader)
{
newVertexShader = vertexShader;
newFragmentShader = fragmentShader;
}
void paint (Graphics&) override {}
void resized() override
{
controlsOverlay->setBounds (getLocalBounds());
draggableOrientation.setViewport (getLocalBounds());
}
Draggable3DOrientation draggableOrientation;
bool doBackgroundDrawing;
float scale, rotationSpeed;
BouncingNumber bouncingNumber;
private:
void drawBackground2DStuff (float desktopScale)
{
// Create an OpenGLGraphicsContext that will draw into this GL window..
ScopedPointer<LowLevelGraphicsContext> glRenderer (createOpenGLGraphicsContext (openGLContext,
roundToInt (desktopScale * getWidth()),
roundToInt (desktopScale * getHeight())));
if (glRenderer != nullptr)
{
Graphics g (*glRenderer);
g.addTransform (AffineTransform::scale (desktopScale));
for (int i = 0; i < numElementsInArray (stars); ++i)
{
float size = 0.25f;
// This stuff just creates a spinning star shape and fills it..
Path p;
p.addStar (Point<float> (getWidth() * stars[i].x.getValue(),
getHeight() * stars[i].y.getValue()), 7,
getHeight() * size * 0.5f,
getHeight() * size,
stars[i].angle.getValue());
float hue = stars[i].hue.getValue();
g.setGradientFill (ColourGradient (Colours::green.withRotatedHue (hue).withAlpha (0.8f),
0, 0,
Colours::red.withRotatedHue (hue).withAlpha (0.5f),
0, (float) getHeight(), false));
g.fillPath (p);
}
}
}
OpenGLContext openGLContext;
ScopedPointer<DemoControlsOverlay> controlsOverlay;
float rotation;
ScopedPointer<OpenGLShaderProgram> shader;
ScopedPointer<Shape> shape;
ScopedPointer<Attributes> attributes;
ScopedPointer<Uniforms> uniforms;
OpenGLTexture texture;
DemoTexture* textureToUse;
String newVertexShader, newFragmentShader;
struct BackgroundStar
{
SlowerBouncingNumber x, y, hue, angle;
};
BackgroundStar stars[3];
//==============================================================================
void updateShader()
{
if (newVertexShader.isNotEmpty() || newFragmentShader.isNotEmpty())
{
ScopedPointer<OpenGLShaderProgram> newShader (new OpenGLShaderProgram (openGLContext));
String statusText;
if (newShader->addVertexShader (OpenGLHelpers::translateVertexShaderToV3 (newVertexShader))
&& newShader->addFragmentShader (OpenGLHelpers::translateFragmentShaderToV3 (newFragmentShader))
&& newShader->link())
{
shape = nullptr;
attributes = nullptr;
uniforms = nullptr;
shader = newShader;
shader->use();
shape = new Shape (openGLContext);
attributes = new Attributes (openGLContext, *shader);
uniforms = new Uniforms (openGLContext, *shader);
statusText = "GLSL: v" + String (OpenGLShaderProgram::getLanguageVersion(), 2);
}
else
{
statusText = newShader->getLastError();
}
controlsOverlay->statusLabel.setText (statusText, dontSendNotification);
newVertexShader = String::empty;
newFragmentShader = String::empty;
}
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLDemo)
};
//==============================================================================
struct ShaderPreset
{
const char* name;
const char* vertexShader;
const char* fragmentShader;
};
static Array<ShaderPreset> getPresets()
{
#define SHADER_DEMO_HEADER \
"/* This is a live OpenGL Shader demo.\n" \
" Edit the shader program below and it will be \n" \
" compiled and applied to the model above!\n" \
"*/\n\n"
ShaderPreset presets[] =
{
{
"Texture + Lighting",
SHADER_DEMO_HEADER
"attribute vec4 position;\n"
"attribute vec4 normal;\n"
"attribute vec4 sourceColour;\n"
"attribute vec2 texureCoordIn;\n"
"\n"
"uniform mat4 projectionMatrix;\n"
"uniform mat4 viewMatrix;\n"
"uniform vec4 lightPosition;\n"
"\n"
"varying vec4 destinationColour;\n"
"varying vec2 textureCoordOut;\n"
"varying float lightIntensity;\n"
"\n"
"void main()\n"
"{\n"
" destinationColour = sourceColour;\n"
" textureCoordOut = texureCoordIn;\n"
"\n"
" vec4 light = viewMatrix * lightPosition;\n"
" lightIntensity = dot (light, normal);\n"
"\n"
" gl_Position = projectionMatrix * viewMatrix * position;\n"
"}\n",
SHADER_DEMO_HEADER
#if JUCE_OPENGL_ES
"varying lowp vec4 destinationColour;\n"
"varying lowp vec2 textureCoordOut;\n"
"varying highp float lightIntensity;\n"
#else
"varying vec4 destinationColour;\n"
"varying vec2 textureCoordOut;\n"
"varying float lightIntensity;\n"
#endif
"\n"
"uniform sampler2D demoTexture;\n"
"\n"
"void main()\n"
"{\n"
#if JUCE_OPENGL_ES
" highp float l = max (0.3, lightIntensity * 0.3);\n"
" highp vec4 colour = vec4 (l, l, l, 1.0);\n"
#else
" float l = max (0.3, lightIntensity * 0.3);\n"
" vec4 colour = vec4 (l, l, l, 1.0);\n"
#endif
" gl_FragColor = colour * texture2D (demoTexture, textureCoordOut);\n"
"}\n"
},
{
"Textured",
SHADER_DEMO_HEADER
"attribute vec4 position;\n"
"attribute vec4 sourceColour;\n"
"attribute vec2 texureCoordIn;\n"
"\n"
"uniform mat4 projectionMatrix;\n"
"uniform mat4 viewMatrix;\n"
"\n"
"varying vec4 destinationColour;\n"
"varying vec2 textureCoordOut;\n"
"\n"
"void main()\n"
"{\n"
" destinationColour = sourceColour;\n"
" textureCoordOut = texureCoordIn;\n"
" gl_Position = projectionMatrix * viewMatrix * position;\n"
"}\n",
SHADER_DEMO_HEADER
#if JUCE_OPENGL_ES
"varying lowp vec4 destinationColour;\n"
"varying lowp vec2 textureCoordOut;\n"
#else
"varying vec4 destinationColour;\n"
"varying vec2 textureCoordOut;\n"
#endif
"\n"
"uniform sampler2D demoTexture;\n"
"\n"
"void main()\n"
"{\n"
" gl_FragColor = texture2D (demoTexture, textureCoordOut);\n"
"}\n"
},
{
"Flat Colour",
SHADER_DEMO_HEADER
"attribute vec4 position;\n"
"attribute vec4 sourceColour;\n"
"attribute vec2 texureCoordIn;\n"
"\n"
"uniform mat4 projectionMatrix;\n"
"uniform mat4 viewMatrix;\n"
"\n"
"varying vec4 destinationColour;\n"
"varying vec2 textureCoordOut;\n"
"\n"
"void main()\n"
"{\n"
" destinationColour = sourceColour;\n"
" textureCoordOut = texureCoordIn;\n"
" gl_Position = projectionMatrix * viewMatrix * position;\n"
"}\n",
SHADER_DEMO_HEADER
#if JUCE_OPENGL_ES
"varying lowp vec4 destinationColour;\n"
"varying lowp vec2 textureCoordOut;\n"
#else
"varying vec4 destinationColour;\n"
"varying vec2 textureCoordOut;\n"
#endif
"\n"
"void main()\n"
"{\n"
" gl_FragColor = destinationColour;\n"
"}\n"
},
{
"Rainbow",
SHADER_DEMO_HEADER
"attribute vec4 position;\n"
"attribute vec4 sourceColour;\n"
"attribute vec2 texureCoordIn;\n"
"\n"
"uniform mat4 projectionMatrix;\n"
"uniform mat4 viewMatrix;\n"
"\n"
"varying vec4 destinationColour;\n"
"varying vec2 textureCoordOut;\n"
"\n"
"varying float xPos;\n"
"varying float yPos;\n"
"varying float zPos;\n"
"\n"
"void main()\n"
"{\n"
" vec4 v = vec4 (position);\n"
" xPos = clamp (v.x, 0.0, 1.0);\n"
" yPos = clamp (v.y, 0.0, 1.0);\n"
" zPos = clamp (v.z, 0.0, 1.0);\n"
" gl_Position = projectionMatrix * viewMatrix * position;\n"
"}",
SHADER_DEMO_HEADER
#if JUCE_OPENGL_ES
"varying lowp vec4 destinationColour;\n"
"varying lowp vec2 textureCoordOut;\n"
"varying lowp float xPos;\n"
"varying lowp float yPos;\n"
"varying lowp float zPos;\n"
#else
"varying vec4 destinationColour;\n"
"varying vec2 textureCoordOut;\n"
"varying float xPos;\n"
"varying float yPos;\n"
"varying float zPos;\n"
#endif
"\n"
"void main()\n"
"{\n"
" gl_FragColor = vec4 (xPos, yPos, zPos, 1.0);\n"
"}"
},
{
"Changing Colour",
SHADER_DEMO_HEADER
"attribute vec4 position;\n"
"attribute vec2 texureCoordIn;\n"
"\n"
"uniform mat4 projectionMatrix;\n"
"uniform mat4 viewMatrix;\n"
"\n"
"varying vec2 textureCoordOut;\n"
"\n"
"void main()\n"
"{\n"
" textureCoordOut = texureCoordIn;\n"
" gl_Position = projectionMatrix * viewMatrix * position;\n"
"}\n",
SHADER_DEMO_HEADER
"#define PI 3.1415926535897932384626433832795\n"
"\n"
#if JUCE_OPENGL_ES
"precision mediump float;\n"
"varying lowp vec2 textureCoordOut;\n"
#else
"varying vec2 textureCoordOut;\n"
#endif
"uniform float bouncingNumber;\n"
"\n"
"void main()\n"
"{\n"
" float b = bouncingNumber;\n"
" float n = b * PI * 2.0;\n"
" float sn = (sin (n * textureCoordOut.x) * 0.5) + 0.5;\n"
" float cn = (sin (n * textureCoordOut.y) * 0.5) + 0.5;\n"
"\n"
" vec4 col = vec4 (b, sn, cn, 1.0);\n"
" gl_FragColor = col;\n"
"}\n"
},
{
"Simple Light",
SHADER_DEMO_HEADER
"attribute vec4 position;\n"
"attribute vec4 normal;\n"
"\n"
"uniform mat4 projectionMatrix;\n"
"uniform mat4 viewMatrix;\n"
"uniform vec4 lightPosition;\n"
"\n"
"varying float lightIntensity;\n"
"\n"
"void main()\n"
"{\n"
" vec4 light = viewMatrix * lightPosition;\n"
" lightIntensity = dot (light, normal);\n"
"\n"
" gl_Position = projectionMatrix * viewMatrix * position;\n"
"}\n",
SHADER_DEMO_HEADER
#if JUCE_OPENGL_ES
"varying highp float lightIntensity;\n"
#else
"varying float lightIntensity;\n"
#endif
"\n"
"void main()\n"
"{\n"
#if JUCE_OPENGL_ES
" highp float l = lightIntensity * 0.25;\n"
" highp vec4 colour = vec4 (l, l, l, 1.0);\n"
#else
" float l = lightIntensity * 0.25;\n"
" vec4 colour = vec4 (l, l, l, 1.0);\n"
#endif
"\n"
" gl_FragColor = colour;\n"
"}\n"
},
{
"Flattened",
SHADER_DEMO_HEADER
"attribute vec4 position;\n"
"attribute vec4 normal;\n"
"\n"
"uniform mat4 projectionMatrix;\n"
"uniform mat4 viewMatrix;\n"
"uniform vec4 lightPosition;\n"
"\n"
"varying float lightIntensity;\n"
"\n"
"void main()\n"
"{\n"
" vec4 light = viewMatrix * lightPosition;\n"
" lightIntensity = dot (light, normal);\n"
"\n"
" vec4 v = vec4 (position);\n"
" v.z = v.z * 0.1;\n"
"\n"
" gl_Position = projectionMatrix * viewMatrix * v;\n"
"}\n",
SHADER_DEMO_HEADER
#if JUCE_OPENGL_ES
"varying highp float lightIntensity;\n"
#else
"varying float lightIntensity;\n"
#endif
"\n"
"void main()\n"
"{\n"
#if JUCE_OPENGL_ES
" highp float l = lightIntensity * 0.25;\n"
" highp vec4 colour = vec4 (l, l, l, 1.0);\n"
#else
" float l = lightIntensity * 0.25;\n"
" vec4 colour = vec4 (l, l, l, 1.0);\n"
#endif
"\n"
" gl_FragColor = colour;\n"
"}\n"
},
{
"Toon Shader",
SHADER_DEMO_HEADER
"attribute vec4 position;\n"
"attribute vec4 normal;\n"
"\n"
"uniform mat4 projectionMatrix;\n"
"uniform mat4 viewMatrix;\n"
"uniform vec4 lightPosition;\n"
"\n"
"varying float lightIntensity;\n"
"\n"
"void main()\n"
"{\n"
" vec4 light = viewMatrix * lightPosition;\n"
" lightIntensity = dot (light, normal);\n"
"\n"
" gl_Position = projectionMatrix * viewMatrix * position;\n"
"}\n",
SHADER_DEMO_HEADER
#if JUCE_OPENGL_ES
"varying highp float lightIntensity;\n"
#else
"varying float lightIntensity;\n"
#endif
"\n"
"void main()\n"
"{\n"
#if JUCE_OPENGL_ES
" highp float intensity = lightIntensity * 0.5;\n"
" highp vec4 colour;\n"
#else
" float intensity = lightIntensity * 0.5;\n"
" vec4 colour;\n"
#endif
"\n"
" if (intensity > 0.95)\n"
" colour = vec4 (1.0, 0.5, 0.5, 1.0);\n"
" else if (intensity > 0.5)\n"
" colour = vec4 (0.6, 0.3, 0.3, 1.0);\n"
" else if (intensity > 0.25)\n"
" colour = vec4 (0.4, 0.2, 0.2, 1.0);\n"
" else\n"
" colour = vec4 (0.2, 0.1, 0.1, 1.0);\n"
"\n"
" gl_FragColor = colour;\n"
"}\n"
}
};
return Array<ShaderPreset> (presets, numElementsInArray (presets));
}
};
// This static object will register this demo type in a global list of demos..
static JuceDemoType<OpenGLDemoClasses::OpenGLDemo> demo ("20 Graphics: OpenGL");
#endif
| [
"rodrigosoaresilva@gmail.com"
] | rodrigosoaresilva@gmail.com |
e06d596681c9d181f2acf691c8863bc5e700e67c | 5f9aa7846462f286ecff94d55fd26a736ac21238 | /source/math/warp/sampleWarp.cpp | 6648ac39a199ad1191f9418bd761c59a034d40a0 | [
"MIT"
] | permissive | xh5a5n6k6/cadise | bba37903facf98b7640571ec3f910a8ec0f070e1 | 797b116b96d7d3989b58454422501f6ace04c4b8 | refs/heads/master | 2023-06-01T08:17:39.848765 | 2021-02-04T13:17:06 | 2021-02-04T13:17:06 | 179,852,908 | 35 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 400 | cpp | #include "math/warp/sampleWarp.h"
#include "fundamental/assertion.h"
#include "math/tVector.h"
#include <cmath>
namespace cadise {
void SampleWarp::uniformTriangleUv(
const Vector2R& sample,
Vector2R* const out_uv) {
CADISE_ASSERT(out_uv);
const real sqrtSeedA = std::sqrt(sample.x());
*out_uv = Vector2R(1.0_r - sqrtSeedA, sqrtSeedA * sample.y());
}
} // namespace cadise | [
"xh5a5n6k6@gmail.com"
] | xh5a5n6k6@gmail.com |
93c161d93ba750579aa720d9ecfea21a321b8f91 | 155eef23b0a9dad13d50d50a9639f3b7637986fa | /tugastp_2/list.cpp | 228cd702094fcd9b216bb64f8410b7a2d3e7d297 | [] | no_license | ridhodori/tugas-praktikum | 2f23094aabe62265abe40e566a3f8567b327c00e | de9c55b52110aae3e2f156d34b8aca31b3734c02 | refs/heads/master | 2021-01-05T07:07:54.279225 | 2020-02-17T08:59:08 | 2020-02-17T08:59:08 | 240,926,061 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,390 | cpp | /*_.cpp
Moh Naufal Mizan Saputro
IF-43-12 / 1301190015
*/
#include <iostream>
#include "list.h"
using namespace std;
void createList(List &L){
first(L) = NULL;
}
address allocate(infotype x){
address p = new elmlist;
info(p) = x;
next(p) = NULL;
return p;
}
void insertFirst(List &L, address P){
next(P) = first(L);
first(L) = P;
}
void printinfo(List L){
address p = first(L);
while(p != NULL){
cout << info(p);
p = next(p);
}
cout << endl;
}
void deleteFirst(List &L, address &P){
if (first(L) != NULL){
P = first(L);
first(L) = next(P);
next(P) = NULL;
}
}
void insertLast(List &L, address &P){
if (first(L) == NULL){
first(L) = P;
}else{
address R = first(L);
while (next(R) != NULL){
R = next(R);
}
next(R) = P;
}
}
void insertAfter(List &L, infotype X, address &J){
address R = first(L);
while (info(next(R)) != X){
R = next(R);
}
next(J) = next(R);
next(R) = J;
}
void deleteLast(List &L, address &P){
address Q = first(L);
while (next(Q) != NULL) {
P = Q;
Q = next(Q);
}
next(P) = NULL;
}
void deleteAfter(List &L,address &P){
address R = first(L);
while (next(R) != P) {
R = next(R);
}
next(R) = next(P);
next(P) = NULL;
}
| [
"ridhodori48@gmail.com"
] | ridhodori48@gmail.com |
5b95187d0a3e45b3c014b47fb637665fd70cdbff | d4de46101e889c24522cc71c405f73ea9de02e6f | /SDK/SCUM_Event_Wooden_ArrowFeathers_classes.hpp | d1c90d3bf82409c74feb60b35544b4659297518e | [] | no_license | GoodstudyChina/SCUM_SDK | da6556d22744e4369931c3970d6e69f01b2882d0 | 0bf1c2ee4bc06eb4fc382914d9db2f5fcbd0de7e | refs/heads/master | 2020-08-29T23:48:19.574846 | 2019-10-14T13:34:20 | 2019-10-14T13:34:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 686 | hpp | #pragma once
// SCUM (Dumped by Hinnie) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Event_Wooden_ArrowFeathers.Event_Wooden_ArrowFeathers_C
// 0x0000 (0x0850 - 0x0850)
class AEvent_Wooden_ArrowFeathers_C : public AAmmunitionArrow
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass Event_Wooden_ArrowFeathers.Event_Wooden_ArrowFeathers_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"hsibma02@gmail.com"
] | hsibma02@gmail.com |
570cd92a2c31ba1c1c4c906a887da465706338b9 | 7b9407ebcb241200b05f2054f3a484b21e36c53a | /Computer Science II/TicTacToeProject/TTT1.cpp | fd2d6f15e8eeaa235f5597570148a69cdace462b | [] | no_license | obilano/CSFiles | 9ad2ebc05b0d86ac8ec3514fa322a1db3591d26b | 58a3098cc3bcff76c653f51c8342f1486b2858e4 | refs/heads/master | 2022-05-29T11:50:44.124636 | 2020-05-01T01:57:47 | 2020-05-01T01:57:47 | 260,356,784 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,304 | cpp | /*********************************************************************
Programmer: Oberon Ilano
Author(s): Dr. Janet Jenkins, Oberon Ilano
Project: 2 - Tic Tac Toe
Description: This program wil allow users to play
a Tic Tac Toe game. This program will also
allow user to keep, show, and save to file
the score of the game
Due Date: November 1, 2018
Course: CS255 - Computer Science II
**********************************************************************/
#include "TTT1.h" //include TTT header for function declarations
//***************************************************************
//class definition/ implementation
//***************************************************************
//*********************************************************************
//Constructors| iniatilized board wiht number 1 - 9, and user turn to 1
//*********************************************************************
TTT::TTT(): board{'1','2','3','4','5','6','7','8','9'}, turn(1){}
/*************************************************
#Function Definition#
Name: ClearBoard
Purpose: Reintialize the board for new game,
output matrix of 2D array 3x3 (char)
and reset users turn
Incoming: None
Outgoing: Tic Tac Toe Board (char)
Return: None
***************************************************/
void TTT::ClearBoard()
{
// reinitialize board
char newBoard[3][3] = {'1','2','3','4','5','6','7','8','9'};
for (int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
board[i][j] = newBoard[i][j];
//reset turn
turn = 1;
}
/*********************************************************
#Function Definition#
Name: CheckBoard
Purpose: To validate if any user win the game,
the board is full, or if the game is draw.
Incoming: none
Outgoing: none
Return: return winner number
**********************************************************/
short TTT::CheckBoard()const
{
// decide if game is over, return winner number; X, O, Cat, or noone (game isn't over)
// checking for horizontal win for user X (1
for (int i = 0; i < 3; i++)
if (((board[i][0] == 'X' && board[i][1] == 'X' && board[i][2] == 'X'))
// checking for vertical win for user X (1)
|| ((board[0][i] == 'X' && board[1][i] == 'X' && board[2][i] == 'X'))
//checking for diagonal win for user X (1)
|| ((board[0][0] == 'X' && board[1][1]== 'X' && board[2][2] == 'X') ||
(board[0][2] == 'X' && board[1][1] == 'X' && board[2][0] == 'X')))
return 1;
// checking for horizontal win for user O (-1)
for (int i = 0; i < 3; i++)
if (((board[i][0] == 'O' && board[i][1] == 'O' && board[i][2] == 'O'))
// checking for vertical win for user O (-1)
|| ((board[0][i] == 'O' && board[1][i] == 'O' && board[2][i] == 'O'))
//checking for diagonal win for user O (-1)
|| ((board[0][0] == 'O' && board[1][1]== 'O' && board[2][2] == 'O') ||
(board[0][2] == 'O' && board[1][1] == 'O' && board[2][0] == 'O')))
return -1;
//if grid is not full
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
if (board[i][j] != 'X' && board[i][j] != 'O')
return 0; //if not 0, 1, -1 then it is draw/cat win
}
/***************************************************
#Function Definition#
Name: MakeMove
Purpose: To validate if move is available,
board is all filled, and toggle
player bewtween X and O
Incoming: User's choice 1-9 (char)
Outgoing: User's move choice X or O (char)
Return: move (true)
*****************************************************/
bool TTT::MakeMove(char player, int r, int c)
{
bool move = false;
char choice;
// user switch turn
if (turn == 1)
cout << "User 1 (X) move: ";
if (turn == -1)
cout << "User 2 (O) move: ";
cin >> choice;
//validate which position/move does user wants to take
switch(choice)
{
case '1': //if user wants to take 1 for the move
r = 0; c = 0;
break;
case '2': //if user wants to take 2 for the move
r = 0; c = 1;
break;
case '3': //if user wants to take 3 for the move
r = 0; c = 2;
break;
case '4': //if user wants to take 4 for the move
r = 1; c = 0;
break;
case '5': //if user wants to take 5 for the move
r = 1; c = 1;
break;
case '6': //if user wants to take 6 for the move
r = 1; c = 2;
break;
case '7': //if user wants to take 7 for the move
r = 2; c = 0;
break;
case '8': //if user wants to take 8 for the move
r = 2; c = 1;
break;
case '9': //if user wants to take 9 for the move
r = 2; c = 2;
break;
default:
cout << "Please select a valid choice. " << endl;
return move;
}
//validate if choice is not already filled
if (turn == 1 && board[r][c] != 'X' && board[r][c] != 'O')
{
board[r][c] = 'X'; //fill the number of choice with X
turn = -1; //User O (-1) takes the turn
}
else if (turn == -1 && board[r][c] != 'X' && board[r][c] != 'O')
{
board[r][c] = 'O'; //fill the number of choice with O
turn = 1; //User X (1) takes the turn
}
else
{ // if move is already filled then output comment
cout << "Choice already filled. Please try another move! " << endl;
MakeMove(player, r, c); // ask the user again for valid choice
}
move = true;
return move;
}
/******************************************************
#Function Definition#
Name: PrintBoard
Purpose: Set up board for tic tac toe game, and
output matrix of 2D array 3x3 (char)
Incoming: None
Outgoing: Tic Tac Toe Board (char)
Return: None
*****************************************************/
void TTT::PrintBoard()const
{
// print board in TTT format
cout << "\t TIC TAC TOE " << endl
<< "\t ___ ___ ___ " << endl
<< "\t | | " << endl // display first row
<< "\t " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << endl
<< "\t ___|___|___ " << endl
<< "\t | | " << endl // display second row
<< "\t " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << endl
<< "\t ___|___|___ " << endl
<< "\t | | " << endl // display third row
<< "\t " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << endl
<< "\t ___|___|___ " << endl << endl;
//display users
cout << "\tUser X (1)" << endl
<< "\tUser O (-1)" << endl << endl;
}
| [
"obi.2010@live.com"
] | obi.2010@live.com |
91c31b31f944211a5c2e110287954e7bded07e69 | 435658d99db9b06d092c973602c9c3db3743ef04 | /include/SoT_OnlineSubsystem_structs.hpp | 64b94e0c2b62abd645b64e3e57c71fbeb400064c | [] | no_license | igromanru/SoT-SDK-compilable | ffaed840da65f76cde8d9391ea708b73ee37515c | 252aaaa3435ea75b33de5f941440fea650df28d2 | refs/heads/master | 2022-01-22T02:14:17.326666 | 2021-12-30T15:55:13 | 2021-12-30T15:55:13 | 176,750,213 | 5 | 15 | null | 2020-01-20T02:09:42 | 2019-03-20T14:20:38 | C++ | UTF-8 | C++ | false | false | 6,975 | hpp | #pragma once
// Sea of Thieves (2) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_Basic.hpp"
#include "SoT_OnlineSubsystem_enums.hpp"
#include "SoT_CoreUObject_classes.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Script Structs
//---------------------------------------------------------------------------
// ScriptStruct OnlineSubsystem.NamedInterface
// 0x0010
struct FNamedInterface
{
struct FName InterfaceName; // 0x0000(0x0008) (ZeroConstructor, IsPlainOldData)
class UObject* InterfaceObject; // 0x0008(0x0008) (ZeroConstructor, IsPlainOldData)
};
// ScriptStruct OnlineSubsystem.NamedInterfaceDef
// 0x0018
struct FNamedInterfaceDef
{
struct FName InterfaceName; // 0x0000(0x0008) (ZeroConstructor, IsPlainOldData)
class FString InterfaceClassName; // 0x0008(0x0010) (ZeroConstructor)
};
// ScriptStruct OnlineSubsystem.InAppPurchaseProductInfo
// 0x00A0
struct FInAppPurchaseProductInfo
{
class FString Identifier; // 0x0000(0x0010) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor)
class FString TransactionIdentifier; // 0x0010(0x0010) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor)
class FString DisplayName; // 0x0020(0x0010) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor)
class FString DisplayDescription; // 0x0030(0x0010) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor)
class FString DisplayPrice; // 0x0040(0x0010) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor)
class FString CurrencyCode; // 0x0050(0x0010) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor)
class FString CurrencySymbol; // 0x0060(0x0010) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor)
class FString DecimalSeparator; // 0x0070(0x0010) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor)
class FString GroupingSeparator; // 0x0080(0x0010) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor)
class FString ReceiptData; // 0x0090(0x0010) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor)
};
// ScriptStruct OnlineSubsystem.InAppPurchaseRestoreInfo
// 0x0020
struct FInAppPurchaseRestoreInfo
{
class FString Identifier; // 0x0000(0x0010) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor)
class FString ReceiptData; // 0x0010(0x0010) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor)
};
// ScriptStruct OnlineSubsystem.AchievementUpdatedEvent
// 0x0038
struct FAchievementUpdatedEvent
{
class FString AchievementId; // 0x0000(0x0010) (ZeroConstructor)
uint32_t Progress; // 0x0010(0x0004) (ZeroConstructor, IsPlainOldData)
bool Successful; // 0x0014(0x0001) (ZeroConstructor, IsPlainOldData)
unsigned char UnknownData00[0x3]; // 0x0015(0x0003) MISSED OFFSET
class FString Reason; // 0x0018(0x0010) (ZeroConstructor)
class FString Platform; // 0x0028(0x0010) (ZeroConstructor)
};
// ScriptStruct OnlineSubsystem.OnlineStoreCatalogItem
// 0x0090
struct FOnlineStoreCatalogItem
{
class FString ProductId; // 0x0000(0x0010) (ZeroConstructor)
class FString Title; // 0x0010(0x0010) (ZeroConstructor)
class FString Description; // 0x0020(0x0010) (ZeroConstructor)
class FString FormattedPrice; // 0x0030(0x0010) (ZeroConstructor)
class FString FormattedBasePrice; // 0x0040(0x0010) (ZeroConstructor)
bool IsOnSale; // 0x0050(0x0001) (ZeroConstructor, IsPlainOldData)
unsigned char UnknownData00[0x7]; // 0x0051(0x0007) MISSED OFFSET
struct FDateTime SaleEndDate; // 0x0058(0x0008) (ZeroConstructor)
class FString ImageUri; // 0x0060(0x0010) (ZeroConstructor)
class FString CurrencyCode; // 0x0070(0x0010) (ZeroConstructor)
TArray<class FString> MetaTags; // 0x0080(0x0010) (ZeroConstructor)
};
// ScriptStruct OnlineSubsystem.InAppPurchaseProductRequest
// 0x0018
struct FInAppPurchaseProductRequest
{
class FString ProductIdentifier; // 0x0000(0x0010) (BlueprintVisible, ZeroConstructor)
bool bIsConsumable; // 0x0010(0x0001) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
unsigned char UnknownData00[0x7]; // 0x0011(0x0007) MISSED OFFSET
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"igromanru@yahoo.de"
] | igromanru@yahoo.de |
8f441252f4382227e3d21e7093ed9692daca8fd1 | a2808ac35b2a639e34d740cde5440511408560f5 | /common/configdb.cpp | ececb2d3ff57ffb59c7c7a9380b74de8230454ef | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | cisco-aarhodes/sonic-swss-common | a172404ca8e689de006ad22523e15628267bb0b7 | c396ff7b9ecf6a0fe6ae53e84a3f3539dfc9a9a3 | refs/heads/master | 2023-05-26T16:25:26.437472 | 2023-05-17T07:58:41 | 2023-05-17T07:58:41 | 178,019,413 | 0 | 1 | NOASSERTION | 2019-03-27T15:09:34 | 2019-03-27T15:09:34 | null | UTF-8 | C++ | false | false | 15,628 | cpp | #include <boost/algorithm/string.hpp>
#include <map>
#include <vector>
#include "configdb.h"
#include "pubsub.h"
#include "converter.h"
using namespace std;
using namespace swss;
ConfigDBConnector_Native::ConfigDBConnector_Native(bool use_unix_socket_path, const char *netns)
: SonicV2Connector_Native(use_unix_socket_path, netns)
, m_table_name_separator("|")
, m_key_separator("|")
{
}
void ConfigDBConnector_Native::db_connect(string db_name, bool wait_for_init, bool retry_on)
{
m_db_name = db_name;
m_key_separator = m_table_name_separator = get_db_separator(db_name);
SonicV2Connector_Native::connect(m_db_name, retry_on);
if (wait_for_init)
{
auto& client = get_redis_client(m_db_name);
auto pubsub = make_shared<PubSub>(&client);
auto initialized = client.get(INIT_INDICATOR);
if (!initialized || initialized->empty())
{
string pattern = "__keyspace@" + to_string(get_dbid(m_db_name)) + "__:" + INIT_INDICATOR;
pubsub->psubscribe(pattern);
for (;;)
{
auto item = pubsub->listen_message();
if (item["type"] == "pmessage")
{
string channel = item["channel"];
size_t pos = channel.find(':');
string key;
if (pos != string::npos)
{
key = channel.substr(pos + 1);
}
if (key == INIT_INDICATOR)
{
initialized = client.get(INIT_INDICATOR);
if (initialized && !initialized->empty())
{
break;
}
}
}
}
pubsub->punsubscribe(pattern);
}
}
}
void ConfigDBConnector_Native::connect(bool wait_for_init, bool retry_on)
{
db_connect("CONFIG_DB", wait_for_init, retry_on);
}
// Write a table entry to config db.
// Remove extra fields in the db which are not in the data.
// Args:
// table: Table name.
// key: Key of table entry, or a tuple of keys if it is a multi-key table.
// data: Table row data in a form of dictionary {'column_key': 'value', ...}.
// Pass {} as data will delete the entry.
void ConfigDBConnector_Native::set_entry(string table, string key, const map<string, string>& data)
{
auto& client = get_redis_client(m_db_name);
string _hash = to_upper(table) + m_table_name_separator + key;
if (data.empty())
{
client.del(_hash);
}
else
{
auto original = get_entry(table, key);
client.hmset(_hash, data.begin(), data.end());
for (auto& it: original)
{
auto& k = it.first;
bool found = data.find(k) != data.end();
if (!found)
{
client.hdel(_hash, k);
}
}
}
}
// Modify a table entry to config db.
// Args:
// table: Table name.
// key: Key of table entry, or a tuple of keys if it is a multi-key table.
// data: Table row data in a form of dictionary {'column_key': 'value', ...}.
// Pass {} as data will create an entry with no column if not already existed.
// Pass None as data will delete the entry.
void ConfigDBConnector_Native::mod_entry(string table, string key, const map<string, string>& data)
{
auto& client = get_redis_client(m_db_name);
string _hash = to_upper(table) + m_table_name_separator + key;
if (data.empty())
{
client.del(_hash);
}
else
{
client.hmset(_hash, data.begin(), data.end());
}
}
// Read a table entry from config db.
// Args:
// table: Table name.
// key: Key of table entry, or a tuple of keys if it is a multi-key table.
// Returns:
// Table row data in a form of dictionary {'column_key': 'value', ...}
// Empty dictionary if table does not exist or entry does not exist.
map<string, string> ConfigDBConnector_Native::get_entry(string table, string key)
{
auto& client = get_redis_client(m_db_name);
string _hash = to_upper(table) + m_table_name_separator + key;
return client.hgetall<map<string, string>>(_hash);
}
// Read all keys of a table from config db.
// Args:
// table: Table name.
// split: split the first part and return second.
// Useful for keys with two parts <tablename>:<key>
// Returns:
// List of keys.
vector<string> ConfigDBConnector_Native::get_keys(string table, bool split)
{
auto& client = get_redis_client(m_db_name);
string pattern = to_upper(table) + m_table_name_separator + "*";
const auto& keys = client.keys(pattern);
vector<string> data;
for (auto& key: keys)
{
if (split)
{
size_t pos = key.find(m_table_name_separator);
string row;
if (pos != string::npos)
{
row = key.substr(pos + 1);
}
data.push_back(row);
}
else
{
data.push_back(key);
}
}
return data;
}
// Read an entire table from config db.
// Args:
// table: Table name.
// Returns:
// Table data in a dictionary form of
// { 'row_key': {'column_key': value, ...}, ...}
// or { ('l1_key', 'l2_key', ...): {'column_key': value, ...}, ...} for a multi-key table.
// Empty dictionary if table does not exist.
map<string, map<string, string>> ConfigDBConnector_Native::get_table(string table)
{
auto& client = get_redis_client(m_db_name);
string pattern = to_upper(table) + m_table_name_separator + "*";
const auto& keys = client.keys(pattern);
map<string, map<string, string>> data;
for (auto& key: keys)
{
auto const& entry = client.hgetall<map<string, string>>(key);
size_t pos = key.find(m_table_name_separator);
string row;
if (pos == string::npos)
{
continue;
}
row = key.substr(pos + 1);
data[row] = entry;
}
return data;
}
// Delete an entire table from config db.
// Args:
// table: Table name.
void ConfigDBConnector_Native::delete_table(string table)
{
auto& client = get_redis_client(m_db_name);
string pattern = to_upper(table) + m_table_name_separator + "*";
const auto& keys = client.keys(pattern);
for (auto& key: keys)
{
client.del(key);
}
}
// Write multiple tables into config db.
// Extra entries/fields in the db which are not in the data are kept.
// Args:
// data: config data in a dictionary form
// {
// 'TABLE_NAME': { 'row_key': {'column_key': 'value', ...}, ...},
// 'MULTI_KEY_TABLE_NAME': { ('l1_key', 'l2_key', ...) : {'column_key': 'value', ...}, ...},
// ...
// }
void ConfigDBConnector_Native::mod_config(const map<string, map<string, map<string, string>>>& data)
{
for (auto const& it: data)
{
string table_name = it.first;
auto const& table_data = it.second;
if (table_data.empty())
{
delete_table(table_name);
continue;
}
for (auto const& ie: table_data)
{
string key = ie.first;
auto const& fvs = ie.second;
mod_entry(table_name, key, fvs);
}
}
}
// Read all config data.
// Returns:
// Config data in a dictionary form of
// {
// 'TABLE_NAME': { 'row_key': {'column_key': 'value', ...}, ...},
// 'MULTI_KEY_TABLE_NAME': { ('l1_key', 'l2_key', ...) : {'column_key': 'value', ...}, ...},
// ...
// }
map<string, map<string, map<string, string>>> ConfigDBConnector_Native::get_config()
{
auto& client = get_redis_client(m_db_name);
return client.getall();
}
std::string ConfigDBConnector_Native::getKeySeparator() const
{
return m_key_separator;
}
std::string ConfigDBConnector_Native::getTableNameSeparator() const
{
return m_table_name_separator;
}
std::string ConfigDBConnector_Native::getDbName() const
{
return m_db_name;
}
ConfigDBPipeConnector_Native::ConfigDBPipeConnector_Native(bool use_unix_socket_path, const char *netns)
: ConfigDBConnector_Native(use_unix_socket_path, netns)
{
}
// Helper method to delete table entries from config db using Redis pipeline
// with batch size of REDIS_SCAN_BATCH_SIZE.
// The caller should call pipeline execute once ready
// Args:
// client: Redis client
// pipe: Redis DB pipe
// pattern: key pattern
// cursor: position to start scanning from
//
// Returns:
// cur: poition of next item to scan
int ConfigDBPipeConnector_Native::_delete_entries(DBConnector& client, RedisTransactioner& pipe, const char *pattern, int cursor)
{
const auto& rc = client.scan(cursor, pattern, REDIS_SCAN_BATCH_SIZE);
auto cur = rc.first;
auto& keys = rc.second;
for (auto const& key: keys)
{
RedisCommand sdel;
sdel.format("DEL %s", key.c_str());
pipe.enqueue(sdel, REDIS_REPLY_INTEGER);
}
return cur;
}
// Helper method to delete table entries from config db using Redis pipeline.
// The caller should call pipeline execute once ready
// Args:
// client: Redis client
// pipe: Redis DB pipe
// table: Table name.
void ConfigDBPipeConnector_Native::_delete_table(DBConnector& client, RedisTransactioner& pipe, string table)
{
string pattern = to_upper(table) + m_table_name_separator + "*";
auto cur = _delete_entries(client, pipe, pattern.c_str(), 0);
while (cur != 0)
{
cur = _delete_entries(client, pipe, pattern.c_str(), cur);
}
}
// Write a table entry to config db
// Remove extra fields in the db which are not in the data
// Args:
// table: Table name
// key: Key of table entry, or a tuple of keys if it is a multi-key table
// data: Table row data in a form of dictionary {'column_key': 'value', ...}
// Pass {} as data will delete the entry
void ConfigDBPipeConnector_Native::set_entry(string table, string key, const map<string, string>& data)
{
auto& client = get_redis_client(m_db_name);
DBConnector clientPipe(client);
RedisTransactioner pipe(&clientPipe);
pipe.multi();
_set_entry(pipe, table, key, data);
pipe.exec();
}
// Write a table entry to config db
// Remove extra fields in the db which are not in the data
// Args:
// pipe: Redis DB pipe
// table: Table name
// key: Key of table entry, or a tuple of keys if it is a multi-key table
// data: Table row data in a form of dictionary {'column_key': 'value', ...}
// Pass {} as data will delete the entry
void ConfigDBPipeConnector_Native::_set_entry(RedisTransactioner& pipe, std::string table, std::string key, const std::map<std::string, std::string>& data)
{
string _hash = to_upper(table) + m_table_name_separator + key;
if (data.empty())
{
RedisCommand sdel;
sdel.format("DEL %s", _hash.c_str());
pipe.enqueue(sdel, REDIS_REPLY_INTEGER);
}
else
{
auto original = get_entry(table, key);
RedisCommand shset;
shset.formatHSET(_hash, data.begin(), data.end());
pipe.enqueue(shset, REDIS_REPLY_INTEGER);
for (auto& it: original)
{
auto& k = it.first;
bool found = data.find(k) != data.end();
if (!found)
{
RedisCommand shdel;
shdel.formatHDEL(_hash, k);
pipe.enqueue(shdel, REDIS_REPLY_INTEGER);
}
}
}
}
// Modify a table entry to config db.
// Args:
// table: Table name.
// pipe: Redis DB pipe
// table: Table name.
// key: Key of table entry, or a tuple of keys if it is a multi-key table.
// data: Table row data in a form of dictionary {'column_key': 'value', ...}.
// Pass {} as data will create an entry with no column if not already existed.
// Pass None as data will delete the entry.
void ConfigDBPipeConnector_Native::_mod_entry(RedisTransactioner& pipe, string table, string key, const map<string, string>& data)
{
string _hash = to_upper(table) + m_table_name_separator + key;
if (data.empty())
{
RedisCommand sdel;
sdel.format("DEL %s", _hash.c_str());
pipe.enqueue(sdel, REDIS_REPLY_INTEGER);
}
else
{
RedisCommand shset;
shset.formatHSET(_hash, data.begin(), data.end());
pipe.enqueue(shset, REDIS_REPLY_INTEGER);
}
}
// Write multiple tables into config db.
// Extra entries/fields in the db which are not in the data are kept.
// Args:
// data: config data in a dictionary form
// {
// 'TABLE_NAME': { 'row_key': {'column_key': 'value', ...}, ...},
// 'MULTI_KEY_TABLE_NAME': { ('l1_key', 'l2_key', ...) : {'column_key': 'value', ...}, ...},
// ...
// }
void ConfigDBPipeConnector_Native::mod_config(const map<string, map<string, map<string, string>>>& data)
{
auto& client = get_redis_client(m_db_name);
DBConnector clientPipe(client);
RedisTransactioner pipe(&clientPipe);
pipe.multi();
for (auto const& id: data)
{
auto& table_name = id.first;
auto& table_data = id.second;
if (table_data.empty())
{
_delete_table(client, pipe, table_name);
continue;
}
for (auto const& it: table_data)
{
auto& key = it.first;
_mod_entry(pipe, table_name, key, it.second);
}
}
pipe.exec();
}
// Read config data in batches of size REDIS_SCAN_BATCH_SIZE using Redis pipelines
// Args:
// client: Redis client
// pipe: Redis DB pipe
// data: config dictionary
// cursor: position to start scanning from
//
// Returns:
// cur: position of next item to scan
int ConfigDBPipeConnector_Native::_get_config(DBConnector& client, RedisTransactioner& pipe, map<string, map<string, map<string, string>>>& data, int cursor)
{
auto const& rc = client.scan(cursor, "*", REDIS_SCAN_BATCH_SIZE);
auto cur = rc.first;
auto const& keys = rc.second;
pipe.multi();
for (auto const& key: keys)
{
size_t pos = key.find(m_table_name_separator);
if (pos == string::npos)
{
continue;
}
RedisCommand shgetall;
shgetall.format("HGETALL %s", key.c_str());
pipe.enqueue(shgetall, REDIS_REPLY_ARRAY);
}
pipe.exec();
for (auto const& key: keys)
{
size_t pos = key.find(m_table_name_separator);
string table_name = key.substr(0, pos);
string row;
if (pos == string::npos)
{
continue;
}
row = key.substr(pos + 1);
auto reply = pipe.dequeueReply();
RedisReply r(reply);
auto& dataentry = data[table_name][row];
for (unsigned int i = 0; i < r.getChildCount(); i += 2)
{
string field = r.getChild(i)->str;
string value = r.getChild(i+1)->str;
dataentry.emplace(field, value);
}
}
return cur;
}
map<string, map<string, map<string, string>>> ConfigDBPipeConnector_Native::get_config()
{
auto& client = get_redis_client(m_db_name);
DBConnector clientPipe(client);
RedisTransactioner pipe(&clientPipe);
map<string, map<string, map<string, string>>> data;
auto cur = _get_config(client, pipe, data, 0);
while (cur != 0)
{
cur = _get_config(client, pipe, data, cur);
}
return data;
}
| [
"noreply@github.com"
] | cisco-aarhodes.noreply@github.com |
5411f7faef60f51bc7bac733308568127e68aff6 | d6b357680ef235122078bf07d56541f5c74df763 | /ass2_1.cpp | 67d075cada2953c83d694453f40a10bf2783d0f0 | [] | no_license | HarizAzrir/mars-rover-game | 1c1eb1a617884d998aa5cf19680453002393cd94 | 986d62de79bb8f98b63d3f5369289f9b443cd405 | refs/heads/main | 2023-03-23T04:36:26.480758 | 2021-03-14T08:59:04 | 2021-03-14T08:59:04 | 347,414,370 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,035 | cpp | /********************************************
Course : TCP1101 Programming Fundamentals
Session: Trimester 2, 2020/21
Assignment: 2
Lecture Section : TC1V
Tutorial Section : TT1L
Name of Student #1 : AHMAD HARIZ IMRAN BIN AHMAD AZRIR
ID of Student #1 : 1191102257
Email of Student #1 : 1191102257@student.mmu.edu.my
Phone of Student #1 : 01139408962
Name of Student #2 : MOHD NAUFAL BIN MOHD ZAMRI
ID of Student #2 : 1191102248
Email of Student #2 : 1191102248@student.mmu.edu.my
Phone of Student #2 : 0102102967
********************************************/
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>
#include <vector>
#include <ctime>
#include <windows.h>
#include <fstream>
using namespace std;
class Mars
{
private:
vector < vector<char> > map;
int dimX, dimY;
int numOfGold;
vector < vector<char> > mapSecret; //the map that will be displayed in the game
int dimSecX,dimSecY;
public:
Mars(){
init();
}
void init();
void initSec(); //hidden map
void display();
void displaySecret(); //hidden map
int getDimX()const;
int getDimY()const;
int getNumOfGold()const;
char getObject(int,int); //allocating what character is inside the coordinate
void setObject( int, int, char); //adding object into map
void setObjectSec(int,int,char); //adding object into hiden map
bool isInsideMap(int,int);
bool isEmpty(int,int);//checking if the coordinate is empty
bool isWall(int,int);
void addGold();
bool victory(int);//checking if number of golds collected
};
void Mars::init()
{
system("pause");
system("cls");
char objects[] = {' ', ' ', '*',' ', 'O', '#', '*',' ',' ','#'};//character available in the game
int noOfObjects = 10;
cout << "Let's explore Mars..." << endl;
cout << "Mars dimension X => ";
while (!(cin >> dimX)) //making sure user inputs only an integer value
{
cout << "Error! Please enter a number! => ";
cin.clear();
cin.ignore(100, '\n');
}
cout << "Mars dimension Y => ";
while (!(cin >> dimY))
{
cout << "Error! Please enter a number! => ";
cin.clear();
cin.ignore(100, '\n');
}
cout << "No of Golds => ";
while (!(cin >> numOfGold))
{
cout << "Error! Please enter a number! => ";
cin.clear();
cin.ignore(100, '\n');
}
dimSecX = dimX;
dimSecY = dimY;
map.resize(dimY); //create rows, redefine the structure as dimY dimX
for (int i=0; i<dimY; ++i){
map[i].resize(dimX);
}
//DESIGNING THE MAP
//put random chars into the vector array
for (int i=0; i<dimY; ++i)
{
for (int j=0; j<dimX; ++j)
{
int objNo = rand() % noOfObjects;
map[i][j] = objects[ objNo ];//storing the random objects one by one into the matrix
}
}
initSec();
}
void Mars::initSec()
{
system("cls");
char secret = '?';
mapSecret.resize(dimSecY);
for (int i=0; i<dimSecY; ++i){
mapSecret[i].resize(dimSecX);
}
for (int i=0; i<dimSecY; ++i)
{
for (int j=0; j<dimSecX; ++j)
{
mapSecret[i][j] = secret;
}
}
}
void Mars::display()
{
system("cls");
cout << endl;
for (int i=0; i<dimY; ++i)
{
cout << " ";
for (int j=0; j<dimX; ++j){
if (j==0)
cout << " ";
cout << "+-";
}
cout << "+" << endl;
cout << setw(2) << (dimY-i);
for (int j=0; j<dimX; ++j){
cout << "|" << map[i][j];
}
cout << "|" << endl;
}
cout << " ";
for (int j=0; j<dimX; ++j){
if (j==0)
cout << " ";
cout << "+-";
}
cout << "+" << endl;
cout << " ";
for (int j=0; j<dimX; ++j)
{
int digit = (j+1)/10;
cout << " ";
if (digit==0)
cout << " ";
else
cout << digit;
}
cout << endl;
cout << " ";
for (int j=0; j<dimX; ++j){
cout << " " << (j+1)%10;
}
cout << endl << endl;
}
void Mars::displaySecret()
{
system("cls");
cout << "--__--__ Mars Rover Mapper__--__--" << endl;
for (int i=0; i<dimSecY; ++i)
{
cout << " ";
for (int j=0; j<dimSecX; ++j){
if (j==0)
cout << " ";
cout << "+-";
}
cout << "+" << endl;
cout << setw(2) << (dimSecY-i);
for (int j=0; j<dimSecX; ++j)
{
cout << "|" << mapSecret[i][j];
}
cout << "|" << endl;
}
cout << " ";
for (int j=0; j<dimSecX; ++j)
{
if (j==0)
cout << " ";
cout << "+-";
}
cout << "+" << endl;
cout << " ";
for (int j=0; j<dimSecX; ++j)
{
int digit = (j+1)/10;
cout << " ";
if (digit==0)
cout << " ";
else
cout << digit;
}
cout << endl;
cout << " ";
for (int j=0; j<dimSecX; ++j){
cout << " " << (j+1)%10;
}
cout << endl << endl;
}
int Mars::getDimX()const
{
return dimX;
}
int Mars::getDimY()const
{
return dimY;
}
int Mars :: getNumOfGold()const
{
return numOfGold;
}
char Mars::getObject(int x, int y)
{
return map[dimY-y][x-1];
}
void Mars::setObject( int x, int y, char ch)
{
map[dimY-y][x-1] = ch;
}
void Mars::setObjectSec( int x, int y, char ch)
{
mapSecret[dimSecY-y][x-1] = ch;
}
bool Mars :: isInsideMap(int x, int y)
{
if((x>0 && x <= dimX) && (y> 0 && y <= dimY))
return true;
else
return false;
}
bool Mars::isEmpty(int x,int y)
{
if (map[dimY-y][x-1] == ' ')
return true;
else
return false;
}
bool Mars :: isWall(int x, int y)
{
if (map[dimY-y][x-1] == '#')
return true;
else
return false;
}
void Mars :: addGold()
{
int x,y;
for (int j=0; j<numOfGold; ++j)
{
x = rand() % dimX+1;
y = rand() % dimY+1;
if(getObject(x,y)!= '$') //making sure everything is $
setObject(x,y,'$');
else
j=j-1;
setObject(x,y,'$');//its always 1 less gold than numOfGold so we added another one
}
}
bool Mars :: victory(int points) //checking to see if user has collected all the golds
{
if(points == numOfGold)
return true;
else
return false;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
class Rover //user controls the rover
{
private:
int x,y; //rover's coordinate
char heading;
int points = 0;
int bullets = 2;
bool status = false; //true when user either collects all the golds or user encounters a trap
bool quitStatus = false; //true if user quits
bool execute = true; //if the command is able to execute
public:
Rover() //rover is using mars
{
}
void land(Mars& mars);
int getroverX();
int getroverY();
int getPoint(Mars& mars);
int getBullet();
void turnLeft(Mars& mars);
void shoot(Mars& mars);
void turnRight(Mars& mars);
void move(Mars& mars);
char temporary(Mars& mars,int,int); //storing previous content of the location before rover moves there
void appear(Mars& mars); //showing the actual content of the map
void instruction(Mars& mars);
void Quit(Mars&mars);
bool quitFailure(Mars &mars);
bool failure(Mars &mars);
bool executable(Mars &mars);
};
void Rover::land(Mars& mars)//initialise where your rover should start at the middle of the map
{
char possibleHeading[] = {'^', '>', '<', 'v'};
int size = 4;
heading = possibleHeading[rand()% size];
if (mars.getDimX() % 2 == 0)
{
x = mars.getDimX() /2;
y = mars.getDimY() /2;
}
else
{
x = (mars.getDimX() + 1)/2;
y = (mars.getDimY() + 1)/2;
}
mars.setObject(x,y,heading);
mars.setObjectSec(x,y,heading);
}
int Rover :: getroverX()
{
return x;
}
int Rover :: getroverY()
{
return y;
}
int Rover:: getPoint(Mars &mars)
{
return points;
}
int Rover :: getBullet()
{
return bullets;
}
void Rover::turnLeft(Mars& mars)
{
if (heading == '^')
heading = '<';
else if (heading == '>')
heading = '^';
else if (heading == 'v')
heading = '>';
else if (heading == '<')
heading = 'v';
mars.setObject(x,y,heading);
mars.setObjectSec(x,y,heading);
}
void Rover:: shoot(Mars& mars)
{
execute = true;
if (bullets>0)
{
if (heading == '^')
{
if (mars.isInsideMap(x,y+1) == true)
{
if (mars.isWall(x,y+1) == true)
{
mars.setObject(x,y+1,' ');
mars.setObjectSec(x,y+1,' ');
bullets = bullets-1;
}
else
execute = false;
}
else
execute = false;
}
else if (heading == '>')
{
if (mars.isInsideMap(x+1,y) == true)
{
if (mars.isWall(x+1,y) == true)
{
mars.setObject(x+1,y,' ');
mars.setObjectSec(x+1,y,' ');
bullets = bullets-1;
}
else
execute = false;
}
else
execute = false;
}
else if (heading == 'v')
{
if (mars.isInsideMap(x,y-1) == true)
{
if (mars.isWall(x,y-1) == true)
{
mars.setObject(x,y-1,' ');
mars.setObjectSec(x,y-1,' ');
bullets = bullets-1;
}
else
execute = false;
}
else
execute = false;
}
else if (heading == '<')
{
if (mars.isInsideMap(x-1,y) == true)
{
if (mars.isWall(x-1,y) == true)
{
mars.setObject(x-1,y,' ');
mars.setObjectSec(x-1,y,' ');
bullets = bullets-1;
}
else
execute = false;
}
else
execute = false;
}
}
else
execute = false;
}
void Rover::turnRight(Mars& mars)
{
if (heading == '^')
heading = '>';
else if (heading == '>')
heading = 'v';
else if (heading == 'v')
heading = '<';
else if (heading == '<')
heading = '^';
mars.setObject(x,y,heading);
mars.setObjectSec(x,y,heading);
}
void Rover:: move(Mars& mars)
{
char store;
if (heading == '^')
{
if (mars.isInsideMap(x,y+1) == true)
{
if (mars.isWall(x,y+1) == false)
{
store = temporary(mars,x,y+1);
mars.setObject(x,y,' ');
mars.setObject(x,y+1,heading);
mars.setObjectSec(x,y,' ');
mars.setObjectSec(x,y+1,heading);
y=y+1;
if(store == '*')
{
status = true;
}
else if(store == '$')
{
points = points+1;
}
else if(store == 'O')
{
bullets = bullets+1;
}
}
else
{
execute = false;
}
}
else
execute = false;
}
else if (heading == '>')
{
if (mars.isInsideMap(x+1,y) == true)
{
if (mars.isWall(x+1,y) == false)
{
store = temporary(mars,x+1,y);
mars.setObject(x,y,' ');
mars.setObject(x+1,y,heading);
mars.setObjectSec(x,y,' ');
mars.setObjectSec(x+1,y,heading);
x=x+1;
if(store == '*')
{
status = true;
}
else if(store == '$')
{
points = points+1;
}
else if(store == 'O')
{
bullets = bullets+1;
}
}
else
{
execute = false;
}
}
else
execute = false;
}
else if (heading == 'v')
{
if (mars.isInsideMap(x,y-1) == true)
{
if (mars.isWall(x,y-1) == false)
{
store = temporary(mars,x,y-1);
mars.setObject(x,y,' ');
mars.setObject(x,y-1,heading);
mars.setObjectSec(x,y,' ');
mars.setObjectSec(x,y-1,heading);
y=y-1;
if(store == '*')
{
status = true;
}
else if(store == '$')
{
points = points+1;
}
else if(store == 'O')
{
bullets = bullets+1;
}
}
else
{
execute = false;
}
}
else
execute = false;
}
else if (heading == '<')
{
if (mars.isInsideMap(x-1,y) == true)
{
if (mars.isWall(x-1,y) == false)
{
store = temporary(mars,x-1,y);
mars.setObject(x,y,' ');
mars.setObject(x-1,y,heading);
mars.setObjectSec(x,y,' ');
mars.setObjectSec(x-1,y,heading);
x=x-1;
if(store == '*')
{
status = true;
}
else if(store == '$')
{
points = points+1;
}
else if(store == 'O')
{
bullets = bullets+1;
}
}
else
{
execute = false;
}
}
else
execute = false;
}
}
char Rover :: temporary(Mars& mars,int j ,int k)
{
char temporary = mars.getObject(j,k);
return temporary;
}
void Rover :: appear(Mars& mars) //DISPLAYING BACK OBJECTS FROM HIDDEN MAP
{
char object;
if (heading == '^')
{
if (mars.isInsideMap(x,y+1) == true) //top middle
{
object = mars.getObject(x,y+1);
mars.setObjectSec(x,y+1,object);
}
if (mars.isInsideMap(x+1,y+1) == true) //top right
{
object = mars.getObject(x+1,y+1);
mars.setObjectSec(x+1,y+1,object);
}
if (mars.isInsideMap(x-1,y+1) == true) //top left
{
object = mars.getObject(x-1,y+1);
mars.setObjectSec(x-1,y+1,object);
}
}
else if (heading == '>')
{
if (mars.isInsideMap(x+1,y) == true) //right middle
{
object = mars.getObject(x+1,y);
mars.setObjectSec(x+1,y,object);
}
if (mars.isInsideMap(x+1,y+1) == true) //right top
{
object = mars.getObject(x+1,y+1);
mars.setObjectSec(x+1,y+1,object);
}
if (mars.isInsideMap(x+1,y-1) == true) //right bottom
{
object = mars.getObject(x+1,y-1);
mars.setObjectSec(x+1,y-1,object);
}
}
else if (heading == 'v')
{
if (mars.isInsideMap(x,y-1) == true) //bottom middle
{
object = mars.getObject(x,y-1);
mars.setObjectSec(x,y-1,object);
}
if (mars.isInsideMap(x+1,y-1) == true) //bottom right
{
object = mars.getObject(x+1,y-1);
mars.setObjectSec(x+1,y-1,object);
}
if (mars.isInsideMap(x-1,y-1) == true) //bottom left
{
object = mars.getObject(x-1,y-1);
mars.setObjectSec(x-1,y-1,object);
}
}
else if (heading == '<')
{
if (mars.isInsideMap(x-1,y) == true) //left middle
{
object = mars.getObject(x-1,y);
mars.setObjectSec(x-1,y,object);
}
if (mars.isInsideMap(x-1,y+1) == true) //left top
{
object = mars.getObject(x-1,y+1);
mars.setObjectSec(x-1,y+1,object);
}
if (mars.isInsideMap(x-1,y-1) == true) //left bottom
{
object = mars.getObject(x-1,y-1);
mars.setObjectSec(x-1,y-1,object);
}
}
}
void Rover :: instruction(Mars& mars)
{
cout << "Mission: Get all the golds!!, Do not get trapped!!"<< endl;
cout << "L = Turn Left, R = Turn Right, M = Move, S = Shoot Wall, Q = Quit "<< endl;
cout << "# = Hill, * = Trap , $= Gold, O = Bullets" << endl;
cout << "Rover is at " << getroverX() << ", " << getroverY() << endl; //additional feature : locate rover
}
void Rover :: Quit(Mars&mars)
{
quitStatus = true;
}
bool Rover :: quitFailure(Mars &mars)
{
return quitStatus;
}
bool Rover :: failure(Mars &mars)
{
return status;
}
bool Rover :: executable(Mars &mars)
{
return execute;
}
/////////////////////////////TEXT FILE FOR HIGH SCORE///////////////////////////////////////////////////
int createFile()
{
ofstream marsFile;
marsFile.open("text.txt");
if (!marsFile) //file not created
{
cout << "error opening file \n";
return -1;
}
marsFile<< "0" << endl; //THIS WILL only be created if file hasnt
//been created yet
marsFile.close();
return 0;
}
int readFile(int &highScore) //storing the value of highscore
{
ifstream ifile;
ifile.open("text.txt");
if(!ifile)
{
cout << "no file to read" << endl;
createFile();
return -1;
}
else
{
while(ifile >> highScore)
{
ifile>>highScore;
}
}
return 0;
}
int appendFile(int &highScore) //editing file/changing highscore
{
fstream file;
file.open("text.txt");
if(!file)
{
cout << "no file to read" << endl;
return -1;
}
else
file << highScore << endl;
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
void printMenu(int &finalScore,int &comSequence,int &command,int &bullets,int &point,int &totalGold,int &highScore,string &userCommand)
{
finalScore = (point * 50) - (comSequence * 5) - (command * 1);
cout << endl;
cout << "Total Command Sequence = " << comSequence << " [S]" << endl;
cout << "Total Commands = " << command << " [C]" << endl;
cout << "Total Bullets = " << bullets << endl;
cout << "Total Golds = " << point << " [G] out of " << totalGold << endl;
cout << "Total Score = [G] X 50 - [S] X 5 - [C] X 1 = " << finalScore << endl;
cout << "High Score = " << highScore << endl;
cout << endl;
cout << "Example Sequence: MMLMMMRMMRMRMLLL" << endl;
cout << "Enter command sequence => ";
cin >> userCommand;
}
void execute()
{
vector<char> input;
string userCommand;
char ch; // (Yes/No)
int highScore;
readFile(highScore); //getting the value of high score
do
{
system("cls");
Mars mars;
Rover curiosity;
int command=0,comSequence = 0,point,finalScore;
int bullets;
int totalGold = mars.getNumOfGold();
curiosity.land(mars);
mars.addGold();
do
{
system("cls");
mars.display();
curiosity.appear(mars);
mars.displaySecret();
curiosity.instruction(mars);
point = curiosity.getPoint(mars);
bullets = curiosity.getBullet();
printMenu(finalScore,comSequence,command,bullets,point,totalGold,highScore,userCommand);
for (int i=0; i<userCommand.size();i++)
{
input.push_back(userCommand[i]);
}
system("pause");
comSequence = comSequence +1;
command = input.size();
for (auto i = input.begin(); i != input.end(); ++i)
{
system("cls");
if (*i == 'L'|| *i == 'l')
{
mars.display();
mars.displaySecret();
cout << "Command = L ..." << endl;
system("pause");
system("cls");
curiosity.turnLeft(mars);
curiosity.appear(mars);
mars.display();
mars.displaySecret();
cout << "Command = L [executed] " << endl;
system("pause");
}
else if (*i == 'R'|| *i == 'r')
{
mars.display();
mars.displaySecret();
cout << "Command = R ..." << endl;
system("pause");
system("cls");
curiosity.turnRight(mars);
curiosity.appear(mars);
mars.display();
mars.displaySecret();
cout << "Command = R [executed] " << endl;
system("pause");
}
else if (*i == 'M'|| *i == 'm')
{
mars.display();
mars.displaySecret();
cout << "Command = M ..." << endl;
system("pause");
system("cls");
curiosity.move(mars);
curiosity.appear(mars);
mars.display();
mars.displaySecret();
if (curiosity.executable(mars)==false)
cout << "Command = M [failed to execute] " << endl;
else
cout << "Command = M [executed] " << endl;
system("pause");
}
else if (*i == 'S'|| *i == 's')
{
mars.display();
mars.displaySecret();
cout << "Command = S ..." << endl;
system("pause");
system("cls");
curiosity.shoot(mars);
curiosity.appear(mars);
mars.display();
mars.displaySecret();
cout << "Command = S ..." << endl;
if (curiosity.executable(mars)==false)
cout << "Command = S [out of bullet OR location is not a wall] " << endl;
else
cout << "Command = S[executed] " << endl;
system("pause");
}
else if (*i == 'Q'|| *i == 'q')
{
curiosity.appear(mars);
mars.display();
mars.displaySecret();
curiosity.Quit(mars);
}
else
{
curiosity.appear(mars);
mars.display();
mars.displaySecret();
cout << "Command " << *i << " = [failed to executed] " << endl;
system("pause");
}
if(curiosity.failure(mars) == true)
break;
}
point = curiosity.getPoint(mars);
input.clear();
system("cls");
} while ((mars.victory(point) == false) && (curiosity.failure(mars) == false) && (curiosity.quitFailure(mars)== false));
if(finalScore > highScore){
highScore = finalScore;
appendFile(highScore);
}
if(curiosity.failure(mars) == false && curiosity.quitFailure(mars) == false)
cout << " Congratz, Mission ACCOMPLISHED!!" << endl;
else if (curiosity.failure(mars) == true && curiosity.quitFailure(mars) == false)
cout << "TRAPPED!! Mission FAILED!!" << endl;
else if (curiosity.quitFailure(mars) == true)
cout << "QUITTED!! Mission FAILED!!" << endl;
do{
cout <<" Do you want to see the map of Mars? => ";
cin >> ch;
} while(ch != 'y'&& ch != 'Y' && ch!= 'n' && ch!= 'N');
if(ch == 'y'||ch == 'Y')
mars.display();
do{
cout << "Do you want to explore Mars again? => ";
cin >> ch;
} while(ch != 'y'&& ch != 'Y' && ch!= 'n' && ch!= 'N'); //to make sure user only input y/n
}while((ch == 'y'||ch == 'Y') && (ch!= 'n' || ch!= 'N'));
cout << "Good Bye from Mars!" << endl;
}
int main()
{
execute();
return 0;
}
| [
"noreply@github.com"
] | HarizAzrir.noreply@github.com |
53b971507233f005b3e50288199ec6b97569e474 | e8ff84ea02e29295499f3c229353906300fa6c40 | /CodeFuture/1-Test/QT/testBaseMuti/basechild.h | a2dad56f57638640a58ca8d8dec449469b519357 | [] | no_license | dayunxiang/gitDocTrack | 541adccfff04834cb699298f67079d76fb86347e | 837ce6d833665f11ac60e47d07bfb6056200f8c4 | refs/heads/master | 2021-01-06T23:20:15.924779 | 2018-08-28T01:42:14 | 2018-08-28T01:42:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 312 | h | #ifndef BASECHILD_H
#define BASECHILD_H
#include <QObject>
#include "base.h"
class BaseChild : public Base
{
public:
BaseChild();
int hideFun();
virtual int v_fun();
int customFun();
private:
int pFun();
virtual int v_pFun();
};
#endif // BASECHILD_H
| [
"pengwei940613@163.com"
] | pengwei940613@163.com |
5527af563b2722d985cd7f626fc4e3782c5ee226 | 5c93333a71b27cfd5e5a017f29f74b25e3dd17fd | /UVa/10129 - Play on Words.cpp | ed9614b3d82945bf232062d0c429041d18db1a8e | [] | no_license | sktheboss/ProblemSolving | 7bcd7e8c2de1f4b1d251093c88754e2b1015684b | 5aff87cc10036a0e6ff255ae47e68a5d71cb7e9d | refs/heads/master | 2021-05-29T03:29:28.980054 | 2015-03-11T10:06:00 | 2015-03-11T10:06:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,231 | cpp | #include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string.h>
#include <list>
#include <hash_map>
#define rep(i,n) for(int i=0; i<n; i++)
#define reps(i,m,n) for(int i=m; i<n; i++)
#define repe(i,m,n) for(int i=m; i<=n; i++)
#define repi(it,stl) for(typeof((stl).begin()) it = (stl).begin(); (it)!=stl.end(); ++(it))
#define sz(a) ((int)(a).size())
#define mem(a,n) memset((a), (n), sizeof(a))
#define all(n) (n).begin(),(n).end()
#define rall(n) (n).rbegin(),(n).rend()
#define allarr(n) (n), (n)+( (sizeof (n)) / (sizeof (*n)) )
#define mp(a,b) make_pair((a),(b))
#define pii pair<int,int>
#define pib pair<int,bool>,&n
#define vi vector<int>
#define vs vector<string>
#define sstr stringstream
#define vit list<pair<int, pii> >::iterator
typedef long long ll;
using namespace std;
using namespace __gnu_cxx;
int n;
int graph[30][30];
int in[30], out[30];
int diff[30];
bool vis[30][30];
void DFS(int idx) {
rep(i,26)
if (graph[idx][i] && !vis[idx][i]) {
vis[idx][i] = 1;
DFS(i);
}
}
int main() {
int tst;
scanf("%d", &tst);
while (tst--) {
mem(graph,0);
mem(in,0), mem(out,0), mem(diff,0);
mem(vis,0);
scanf("%d", &n);
char str[1003];
rep(i,n) {
scanf("%s", str);
int l = strlen(str);
graph[str[0] - 'a'][str[l - 1] - 'a']++;
++out[str[0] - 'a'], ++in[str[l - 1] - 'a'];
}
bool valid = 1;
int pos1 = 0, neg1 = 0;
int start = 0;
rep(i,26) {
diff[i] = out[i] - in[i];
if (diff[i] > 1 || diff[i] < -1) {
valid = 0;
break;
}
if (diff[i] == 1)
++pos1, start = i;
else if (diff[i] == -1)
++neg1;
}
if (!valid || pos1 ^ neg1 || pos1 > 1) {
printf("The door cannot be opened.\n");
continue;
}
DFS(start);
valid = 1;
rep(i,26)
rep(j,26)
if (graph[i][j] && !vis[i][j]) {
valid = 0;
break;
}
if (!valid)
printf("The door cannot be opened.\n");
else
printf("Ordering is possible.\n");
}
return 0;
}
| [
"fci.islam@gmail.com"
] | fci.islam@gmail.com |
b71b96b22c32de9b32c93c512eb4e73d3b7eebaf | f00c7e2b2025a2795279676de527572588c17be7 | /Altis_Life_Heavy_Company_3.1.4.8.Altis/dialog/vehicleShop_old.h | 295865035ad8b8a4179e7a218578dade96befad3 | [] | no_license | DrCramer/Altis_Life_Heavy_Company | 82e09c6d63810241d70aa4f4788e0595ae765ee8 | 064512da1e51f2b38f093cfa85008bad75fdd04e | refs/heads/master | 2020-12-24T13:35:25.800751 | 2014-12-10T22:46:05 | 2014-12-10T22:46:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,436 | h | class Life_Vehicle_Shop_v2
{
idd = 2300;
name="life_vehicle_shop";
movingEnabled = 0;
enableSimulation = 1;
onLoad = "ctrlShow [2330,false];";
class controlsBackground
{
class Life_RscTitleBackground : Life_RscText
{
colorBackground[] = {0.039, 0.196, 0.51, 0.7};
idc = -1;
x = 0.1;
y = 0.2;
w = 0.8;
h = (1 / 25);
};
class MainBackground : Life_RscText
{
colorBackground[] = {0,0,0,0.7};
idc = -1;
x = 0.1;
y = 0.2 + (11 / 250);
w = 0.8;
h = 0.7 - (22 / 250);
};
class Title : Life_RscTitle
{
idc = 2301;
text = "";
x = 0.1;
y = 0.2;
w = 0.8;
h = (1 / 25);
};
class VehicleTitleBox : Life_RscText
{
idc = -1;
text = "$STR_GUI_ShopStock";
colorBackground[] = {0.039, 0.196, 0.51, 0.7};
x = 0.11; y = 0.26;
w = 0.3;
h = (1 / 25);
};
class VehicleInfoHeader : Life_RscText
{
idc = 2330;
text = "$STR_GUI_VehInfo";
colorBackground[] = {0.039, 0.196, 0.51, 0.7};
x = 0.42; y = 0.26;
w = 0.46;
h = (1 / 25);
};
class CloseBtn : Life_RscButtonMenu
{
idc = -1;
text = "$STR_Global_Close";
onButtonClick = "closeDialog 0;";
x = -0.06 + (6.25 / 40) + (1 / 250 / (safezoneW / safezoneH));
y = 0.9 - (1 / 25);
w = (6.25 / 40);
h = (1 / 25);
};
class RentCar : Life_RscButtonMenu
{
idc = -1;
text = "$STR_Global_RentVeh";
onButtonClick = "[false] spawn life_fnc_vehicleShopBuy;";
x = 0.1 + (6.25 / 40) + (1 / 250 / (safezoneW / safezoneH));
y = 0.9 - (1 / 25);
w = (6.25 / 40);
h = (1 / 25);
};
class BuyCar : life_RscButtonMenu
{
idc = 2309;
text = "$STR_Global_Buy";
onButtonClick = "[true] spawn life_fnc_vehicleShopBuy;";
x = 0.26 + (6.25 / 40) + (1 / 250 / (safezoneW / safezoneH));
y = 0.9 - (1 / 25);
w = (6.25 / 40);
h = (1 / 25);
};
};
class controls
{
class VehicleList : Life_RscListBox
{
idc = 2302;
text = "";
sizeEx = 0.04;
colorBackground[] = {0.1,0.1,0.1,0.9};
onLBSelChanged = "_this call life_fnc_vehicleShopLBChange";
//Position & height
x = 0.11; y = 0.302;
w = 0.303; h = 0.49;
};
class ColorList : Life_RscCombo
{
idc = 2304;
x = 0.11; y = 0.8;
w = 0.303; h = 0.03;
};
class vehicleInfomationList : Life_RscStructuredText
{
idc = 2303;
text = "";
sizeEx = 0.035;
x = 0.41; y = 0.3;
w = 0.5; h = 0.5;
};
};
}; | [
"cramerstation@gmail.com"
] | cramerstation@gmail.com |
701962aa8a6ba6f5a6a5631948f09a7ad296934a | 6da5140e9595582c2ab10f3a7def25115912973c | /5/02.mdi/Demo.07/MAINFRM.H | 3ed14c9d882b51ea27d25935b57bda798016c273 | [] | no_license | s1040486/xiaohui | 6df6064bb0d1e858429375b45418e4f2d234d1a3 | 233b6dfbda130d021b8d91ae6a3736ecc0f9f936 | refs/heads/master | 2022-01-12T07:10:57.181009 | 2019-06-01T04:02:16 | 2019-06-01T04:02:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,529 | h | // MainFrm.h : interface of the CMainFrame class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_MAINFRM_H__F9BB0CC8_3D20_11D2_BC46_0060970A2B51__INCLUDED_)
#define AFX_MAINFRM_H__F9BB0CC8_3D20_11D2_BC46_0060970A2B51__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
class CMainFrame : public CFrameWnd
{
protected: // create from serialization only
CMainFrame();
DECLARE_DYNCREATE(CMainFrame)
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMainFrame)
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected: // control bar embedded members
CStatusBar m_wndStatusBar;
CToolBar m_wndToolBar;
// Generated message map functions
protected:
//{{AFX_MSG(CMainFrame)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_MAINFRM_H__F9BB0CC8_3D20_11D2_BC46_0060970A2B51__INCLUDED_)
| [
"haihai107@126.com"
] | haihai107@126.com |
54bca5b80647ae292aa183e318db6f55e5ce7003 | b6ff5e342f3675087d2704199bb5a46362b5fc20 | /1GI/S2/Méthodes de résolution/Souhail/jeuMoulin++/table.cpp | 74908e26ae5e7b52e3685489f73ae158a3ebe0fd | [] | no_license | Ssouh/EHTP | 75f5071282a1b0ed500d5c27e73b514fefe7af61 | 96558e59e398f652ae2e8a560b9dcd4ee3e8c6a8 | refs/heads/main | 2023-03-14T11:56:46.424726 | 2021-03-04T09:49:05 | 2021-03-04T09:49:05 | 330,687,825 | 0 | 0 | null | 2021-01-24T18:02:23 | 2021-01-18T14:15:22 | null | UTF-8 | C++ | false | false | 15,157 | cpp | #include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <string.h>
#include <conio.h>
#include <vector> /// include vector https://www.geeksforgeeks.org/vector-in-cpp-stl/
using namespace std;
#include "Fonction.h"
int EI[7][7]= {{ -1, 10, 10, -1, 10, 10, -1},
{ 10, -1, 10, -1, 10, -1, 10},
{ 10, 10, -1, -1, -1, 10, 10},
{ -1, -1, -1, 10, -1, -1, -1},
{ 10, 10, -1, -1, -1, 10, 10},
{ 10, -1, 10, -1, 10, -1, 10},
{ -1, 10, 10, -1, 10, 10, -1}};
noeud Etat_initial(EI);
int compteur;/// pair le joueur, impair la machine
int JCaisse;
int MCaisse;
void fullscreen() ///function definition for fullscreen source: https://www.dreamincode.net/forums/topic/59497-run-a-c-program-in-full-screen/
{ keybd_event(VK_MENU,
0x38,
0,
0);
keybd_event(VK_RETURN,
0x1c,
0,
0);
keybd_event(VK_RETURN,
0x1c,
KEYEVENTF_KEYUP,
0);
keybd_event(VK_MENU,
0x38,
KEYEVENTF_KEYUP,
0);
}
void color(int t,int f) /// http://www.cplusplus.com/forum/beginner/54360/
{
HANDLE H=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(H,f*16+t);
}
void Choisi(int k)
{
if (k==-1)
{printf("+");
}
else if (k==0)
{
color(0,0);
printf(" ");
color(15,3);/// 0 ==> NOIR
}
else if (k==1)
{
color(0,15);
printf(" ");
color(15,3);/// 1 ==> BLANC
}}
void table(noeud N)
{
color(3,15);
int A[7][7];
for (int i=0;i<7;i++)
for (int j=0;j<7;j++)
A[i][j]=N.E[i][j];
system("cls");
cout<< "\n\n\n\t\t\t\t\t";color(15,3);cout<<" 1 2 3 4 5 6 7";color(3,15);cout<<"\n";
cout<< "\t\t\t\t\t";color(15,3);cout<<"1 ";Choisi(A[0][0]);cout<<"---------------------------";Choisi(A[0][3]);cout<<"---------------------------";Choisi(A[0][6]);color(3,15);color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<" | | |";color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<" | | |";color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<" | | |";color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<"2 | ";Choisi(A[1][1]);cout<<"------------------";Choisi(A[1][3]);cout<<"------------------";Choisi(A[1][5]);cout<<" |";color(3,15);color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<" | | | | |";color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<" | | | | |";color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<" | | | | |";color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<"3 | | ";Choisi(A[2][2]);cout<<"---------";Choisi(A[2][3]);cout<<"---------";Choisi(A[2][4]);cout<<" | |";color(3,15);color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<" | | | | | |";color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<" | | | | | |";color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<" | | | | | |";color(3,15);cout<<"\n"
"\t";Caisse(0);cout<<"\t\t";color(15,3);cout<<"4 ";Choisi(A[3][0]);cout<<"--------";Choisi(A[3][1]);cout<<"--------";Choisi(A[3][2]);cout<<" ";Choisi(A[3][4]);cout<<"--------";Choisi(A[3][5]);cout<<"--------";Choisi(A[3][6]);color(3,15);cout<<"\t";Caisse(1);cout<<"\t\t\n"
"\t";Caisse(2);cout<<"\t\t";color(15,3);cout<<" | | | | | |";color(3,15);cout<<"\t";Caisse(3);cout<<"\t\t\n"
"\t\t\t\t\t";color(15,3);cout<<" | | | | | |";color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<" | | | | | |";color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<"5 | | ";Choisi(A[4][2]);cout<<"---------";Choisi(A[4][3]);cout<<"---------";Choisi(A[4][4]);cout<<" | |";color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<" | | | | |";color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<" | | | | |";color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<" | | | | |";color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<"6 | ";Choisi(A[5][1]);cout<<"------------------";Choisi(A[5][3]);cout<<"------------------";Choisi(A[5][5]);cout<<" |";color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<" | | |";color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<" | | |";color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<" | | |";color(3,15);cout<<"\n"
"\t\t\t\t\t";color(15,3);cout<<"7 ";Choisi(A[6][0]);cout<<"---------------------------";Choisi(A[6][3]);cout<<"---------------------------";Choisi(A[6][6]);color(3,15);cout<<"\n";
;color(15,3);cout<<"\n\t\t\t\t\t\t\tPour QUITTER entrez -1 -1\n";
Fin(N);
if (compteur<18)
table(Saisie(A));/// si compteur < 18
else table(Deplacement(A));/// si compteur > 18
}
void Caisse(int k)/// les stocks des pierres des joueurs a cote de la table
{
if (k==0){
cout << "Joueur Capture="<<JCaisse;
}
else if (k==1)
{
cout << "Machine Capture="<<MCaisse;
}else if (k==2 && compteur<18)
{
cout << "Pions Restants="<<(int)(18-compteur)/2;
}else if (k==2)
{
cout << "Pions Restants=0";
}else if (k==3 && compteur<18)
{
cout << "Pions Restants="<<(int)(18-compteur)/2;
}else if (k==3)
{
cout << "Pions Restants=0";
}
}
noeud Saisie(int A[7][7])
{
noeud R(A);
if (compteur<18)
{ int i,j;
if (compteur % 2 == 0)
{ L:
cout<< "\n\t\t\t\t\t\t CHOISIR LA LIGNE PUIS COLONNE ^-^ : ";
cin>> i; cin>>j;
if (i==-1 && j==-1) main();
if (!Tester(i,j,A)) {cout<< "\n\t\t\t\t\t\t ERREUR"; goto L;}
A[i-1][j-1]=0;
R=Capture(i,j,A);
}
else
{
noeud N(A);
noeud M;vector<int> CR;
M=AttaqueDefense(N,1);
A=M.E;
CR=N.Remove(M);///case moved
R=Capture(CR[0]+1,CR[1]+1,A);
}
compteur++;
}
return R;
}
bool Tester(int i, int j,int A[7][7])/// return bool en accord avec la validite de l'emplacement
{
if (A[i-1][j-1]!=-1) return false;
if (i==1 && j==2 ) return false;
if (i==1 && j==3 ) return false;
if (i==1 && j==5 ) return false;
if (i==1 && j==6 ) return false;
if (i==2 && j==1 ) return false;
if (i==2 && j==3 ) return false;
if (i==2 && j==5 ) return false;
if (i==2 && j==7 ) return false;
if (i==3 && j==1 ) return false;
if (i==3 && j==2 ) return false;
if (i==3 && j==6 ) return false;
if (i==3 && j==7 ) return false;
if (i==4 && j==4 ) return false;
if (i==5 && j==1 ) return false;
if (i==5 && j==2 ) return false;
if (i==5 && j==6 ) return false;
if (i==5 && j==7 ) return false;
if (i==6 && j==1 ) return false;
if (i==6 && j==3 ) return false;
if (i==6 && j==5 ) return false;
if (i==6 && j==7 ) return false;
if (i==7 && j==2 ) return false;
if (i==7 && j==3 ) return false;
if (i==7 && j==5 ) return false;
if (i==7 && j==6 ) return false;
return true;
}
noeud Deplacement(int A[7][7])
{
noeud R(A);
if (compteur>=18)
{
int i1,j1,i2,j2;
if (compteur% 2 == 0)
{ L:
cout<< "\n\t\t\t\t\t CHOISIR LA LIGNE PUIS COLONNE DU PIONS A DEPLACER ^_^ : ";
cin>> i1;cin>>j1;
if (i1==-1 && j1==-1) main();
if (!valide(i1,j1,A,1)) {cout<< "\n\t\t\t\t\t\t\t ERREUR"; goto L;}
cout<< "\n\t\t\t\t\t\t CHOISIR LA LIGNE PUIS COLONNE ^_^ : ";
cin>> i2;cin>>j2;
if (!Tester(i2,j2,A)) {cout<< "\n\t\t\t\t\t\t\t ERREUR"; goto L;}
A[i1-1][j1-1]=-1;A[i2-1][j2-1]=0;
Choisi(A[i2-1][j2-1]);
R=Capture(i2,j2,A);
}
else
{
noeud N(A);
noeud M;vector<int> CR;
M=AttaqueDefense(N,1);
A=M.E;
CR=M.Remove(N);///case moved
R=Capture(CR[0]+1,CR[1]+1,A);
}
compteur++;
}
return R;
}
bool valide(int i, int j,int A[7][7],int caseOP)/// return bool en accord avec la validite de la cas a deplacer
{
if (A[i-1][j-1]==-1) return false;
if (A[i-1][j-1]==caseOP) return false;
if (i==1 && j==2 ) return false;
if (i==1 && j==3 ) return false;
if (i==1 && j==5 ) return false;
if (i==1 && j==6 ) return false;
if (i==2 && j==1 ) return false;
if (i==2 && j==3 ) return false;
if (i==2 && j==5 ) return false;
if (i==2 && j==7 ) return false;
if (i==3 && j==1 ) return false;
if (i==3 && j==2 ) return false;
if (i==3 && j==6 ) return false;
if (i==3 && j==7 ) return false;
if (i==4 && j==4 ) return false;
if (i==5 && j==1 ) return false;
if (i==5 && j==2 ) return false;
if (i==5 && j==6 ) return false;
if (i==5 && j==7 ) return false;
if (i==6 && j==1 ) return false;
if (i==6 && j==3 ) return false;
if (i==6 && j==5 ) return false;
if (i==6 && j==7 ) return false;
if (i==7 && j==2 ) return false;
if (i==7 && j==3 ) return false;
if (i==7 && j==5 ) return false;
if (i==7 && j==6 ) return false;
return true;
}
noeud Retirer(int A[7][7])
{
int i,j;
if (compteur% 2 ==0)
{ R:
printf("\n\t\t\t\t\t\t CHOISIR LA LIGNE PUIS COLONNE A RETIRER ^_^ : ");
cin>> i;cin>>j;
if (valide(i,j,A,0)) A[i-1][j-1]=-1;
else {cout<< "\n\t\t\t\t\t\t\t ERREUR"; goto R;}
JCaisse++;
}
else
{
noeud N(A);
noeud M;vector<int> CR;
M=AttaqueDefense(N,0);
CR=M.Remove(N);///Noeud Remove
A[CR[0]][CR[1]]=-1;
MCaisse++;
}
noeud H(A);
H.afficheToi();
getch();
return H;
}
bool MurLigne(int i,int j,int A[7][7])
{
int ite=0;
if (i!=4){
for (int r=0;r<7;r++)
if (A[i-1][r]==A[i-1][j-1]) ite++;
if (ite==3) return true;}
else{
for (int r=0;r<3;r++)
if (A[i-1][r]==A[i-1][j-1]) ite++;
if (ite==3) return true;
ite=0;
for (int r=4;r<7;r++)
if (A[i-1][r]==A[i-1][j-1]) ite++;
if (ite==3) return true;}
return false;
}
bool MurColonne(int i,int j,int A[7][7])
{
int ite=0;
if (j!=4){
for (int r=0;r<7;r++)
if (A[r][j-1]==A[i-1][j-1]) ite++;
if (ite==3) return true;}
else{
for (int r=0;r<3;r++)
if (A[r][j-1]==A[i-1][j-1]) ite++;
if (ite==3) return true;
ite=0;
for (int r=4;r<7;r++)
if (A[r][j-1]==A[i-1][j-1]) ite++;
if (ite==3) return true;}
return false;
}
noeud Capture(int i,int j,int A[7][7])///Mur + retirer
{
noeud R(A);
if(MurLigne(i,j,A)) R=Retirer(A);
if(MurColonne(i,j,A)) R=Retirer(A);
return R;
}
void Fin(noeud N)
{
if (N.Etat_Final())
{
system("cls");
cout<<"\n"
"\n"
"\t\t\t\t\t @@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@ @ @@@@@@@\n"
"\t\t\t\t\t @ @ @ @ @ @ @ @ @\n"
"\t\t\t\t\t @@@@@@@ @ @ @@@@@@@ @ @ @\n"
"\t\t\t\t\t @ @@@@@@@ @ @ @ @ @@@@@@@\n"
"\t\t\t\t\t @ @ @ @ @ @ @ @\n"
"\t\t\t\t\t @ @ @ @ @ @ @ @\n"
"\t\t\t\t\t @ @ @ @ @ @ @ @@@@@@@ \n\n\n"
"\t\t\t\t\t @@@@@@@ @ @ @ @ @@@@@@@\n"
"\t\t\t\t\t @ @ @@ @ @ @\n"
"\t\t\t\t\t @ @ @ @ @ @ @\n"
"\t\t\t\t\t @@@@@@@ @ @ @ @ @ @@@@@@@\n"
"\t\t\t\t\t @ @ @ @ @ @ @\n"
"\t\t\t\t\t @ @ @ @@ @ @\n"
"\t\t\t\t\t @ @ @ @ @ @@@@@@@ \n";
getch();
main();
}
}
/*
void selectionJVM()
{ int i,k=0,j,x,y;
if (((compteur+1)/2. - (compteur+1)/2)==0)
{printf("\n\t\t\t\t\t\t\t\t CHOISIR LA LIGNE PUIS COLONNE ^_^ : ");
cin>> i,j;
if ( i>8 || j>8) {printf("\t\t\t\t\t\t\t CASE INCORRECTE '~' "); selectionJVM();}
if (H[i][j]==0 || H[i][j]==1) {printf("\t\t\t\t\t\t\t CASE PLEINE '-' "); selectionJVM();}
else {
//Coup_interdit(i+1,j+1);Coup_interdit_grp(i+1,j+1);
A[i][j]=1;}}
else{
srand(time(NULL) );
do {x=rand()%9;
y=rand()%9;k=1;
} while ( H[x][y]!= -1 || k==0);
A[x][y]=1;}
compteur++;
system("cls");
table();
}
void selectionJVJ()
{ int i,j;
if (((compteur+1)/2. - (compteur+1)/2)==0)
{ color(15,3);
printf("\n\t\t\t\t\t JOUEUR EN ");
color(0,0);
printf(" ");
color(15,3);
printf(" ");
color(3,15);
printf(" CHOISIT TA LIGNE PUIS COLONNE ^_^ : ");
}
else {color(15,3);
printf("\n\t\t\t\t\t JOUEUR EN ");
color(0,15);
printf(" ");
color(15,3);
printf(" ");
color(3,15);
printf(" CHOISIT TA LIGNE PUIS COLONNE ^_^ : ");}
cin>> i>>j;
//vector<int> V; V.push_back();
///if (H[i-1][j-1]==0 || H[i-1][j-1]==1) {printf("\t\t\t\t CASE PLEINE '-' "); selectionJVJ();}
/// vecteur is needed in this area .
///if(std::find(v.begin(), v.end(), x) != v.end()) {
/// v contains x
/// } else {
/// v does not contain x
if ( i>7 || j>7) {printf("\t\t\t\t CASE INCORRECTE '~' "); selectionJVJ();}
else {
compteur++;
A[i-1][j-1]=1;
system("cls");
table();
}
}
*/
| [
"safi-bigg@live.fr"
] | safi-bigg@live.fr |
f687130ec37b8bb0728fb538ac3b42c940fa8cda | 344db7c30f7bf34d8ae20d5ed040280a8c038f9c | /PAT_Code-master/B1005.cpp | 5abcc0fa14ec48ec2fec6149a13c2ba35b4aa5c4 | [] | no_license | CoderDXQ/Brush-Algorithm-problem | 75d5a700eae5df8be600fea3a5427c94a9f941b9 | 78cf6a79c7c0fe1a9fc659101ba5ba9196912df5 | refs/heads/master | 2023-06-19T14:20:01.117764 | 2021-07-18T04:59:19 | 2021-07-18T04:59:19 | 253,854,814 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 807 | cpp | #include <cstdio>
#include <algorithm>
using namespace std;
bool cmp(int a, int b) {
return a > b;
}
int main() {
int n, m, a[110];
scanf("%d", &n);
bool HashTable[1000] = {0}; //1000不行就开10000,必过
for(int i = 0; i < n; i++) {
scanf("%d", &a[i]);
m = a[i];
while(m != 1) {
if(m % 2 == 1) m = (3 * m + 1) / 2;
else m = m / 2;
HashTable[m] = true;
}
}
int count = 0;
for(int i = 0; i < n; i++) {
if(HashTable[a[i]] == false) {
count++;
}
}
sort(a, a + n, cmp);
for(int i = 0; i < n; i++) {
if(HashTable[a[i]] == false) {
printf("%d", a[i]);
count--;
if(count > 0) printf(" ");
}
}
return 0;
}
| [
"794055465@qq.com"
] | 794055465@qq.com |
fa8378bb308600ef0263729b919cc8783016acf3 | 06bed8ad5fd60e5bba6297e9870a264bfa91a71d | /libPr3/qtsoundaudiofactory.cpp | 8a2c67c51b011830a4e87eeb02e71a8dde7e3d0c | [] | no_license | allenck/DecoderPro_app | 43aeb9561fe3fe9753684f7d6d76146097d78e88 | 226c7f245aeb6951528d970f773776d50ae2c1dc | refs/heads/master | 2023-05-12T07:36:18.153909 | 2023-05-10T21:17:40 | 2023-05-10T21:17:40 | 61,044,197 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 6,799 | cpp | #include "qtsoundaudiofactory.h"
#include "audiomanager.h"
#include "instancemanager.h"
#include "audio.h"
#include "qtsoundaudiobuffer.h"
#include "qtsoundaudiosource.h"
#include "qtsoundaudiolistener.h"
#include <QAudioDeviceInfo>
#include "mixer.h"
/*private*/ /*volatile*/ /*static*/ Mixer* QtSoundAudioFactory::_mixer = NULL;
/*private*/ /*static*/ bool QtSoundAudioFactory::_initialised = false;
QtSoundAudioFactory::QtSoundAudioFactory(QObject *parent) :
AbstractAudioFactory(parent)
{
log = new Logger("QtSoundAudioFactory");
_activeAudioListener = NULL;
}
#if 1
/**
* This is the JavaSound audio system specific AudioFactory.
* <p>
* The JavaSound sound system supports, where available, 2-channel stereo.
* <p>
* The implemented Audio objects provide an approximation of a 3D positionable
* audio model through the use of calculated panning and gain based on the 3D
* position of the individual sound sources.
* <p>
* This factory initialises JavaSound, provides new JavaSound-specific Audio
* objects and deals with clean-up operations.
* <p>
* For more information about the JavaSound API, visit
* <a href="http://java.sun.com/products/java-media/sound/">http://java.sun.com/products/java-media/sound/</a>
*
* <hr>
* This file is part of JMRI.
* <p>
* JMRI is free software; you can redistribute it and/or modify it under the
* terms of version 2 of the GNU General Public License as published by the Free
* Software Foundation. See the "COPYING" file for a copy of this license.
* <p>
* JMRI 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.
* <p>
*
* @author Matthew Harris copyright (c) 2009
* @version $Revision: 28746 $
*/
///*public*/ class JavaSoundAudioFactory extends AbstractAudioFactory {
//@Override
/*public*/ bool QtSoundAudioFactory::init()
{
if (_initialised)
{
return true;
}
#if 0
// Initialise JavaSound
if (_mixer == NULL)
{
// Iterate through possible mixers until we find the one we require
foreach (Mixer::Info mixerInfo, QAudioSystem::getMixerInfo()) {
if (mixerInfo.getName().equals("Java Sound Audio Engine")) {
_mixer = AudioSystem.getMixer(mixerInfo);
break;
}
}
}
// Check to see if a suitable mixer has been found
if (_mixer == NULL)
{
if (log->isDebugEnabled())
{
log->debug("No JavaSound audio system found.");
}
return false;
}
else
{
if (log->isInfoEnabled())
{
log->info("Initialised JavaSound:"
+ " vendor - " + _mixer.getMixerInfo().getVendor()
+ " version - " + _mixer.getMixerInfo().getVersion());
}
}
#else
// Initialize QtSound.
// QList<QAudioDeviceInfo> list = QAudioDeviceInfo::availableDevices(QAudio::AudioOutput);
// log->info("Available Audio output devices:");
// foreach (QAudioDeviceInfo info , list)
// {
// log->info(" Name"+ info.deviceName());
// if(QAudioDeviceInfo::defaultOutputDevice().deviceName() == info.deviceName())
// {
// log->info(" Is default!");
// }
// QAudioFormat format = info.preferredFormat();
// log->info(QString(" %1Hz %2 %3 bit %4 endian").arg(format.sampleRate()).arg(format.channelCount()> 1?"stereo":"mono").arg(format.sampleSize()).arg(format.BigEndian?"big":"little"));
// }
// QAudioDeviceInfo info = QAudioDeviceInfo::defaultOutputDevice();
// QAudioFormat format = info.preferredFormat();
// log->info(QString(" %1Hz %2 %3 bit %4 endian").arg(format.sampleRate()).arg(format.channelCount()> 1?"stereo":"mono").arg(format.sampleSize()).arg(format.BigEndian?"big":"little"));
#endif
AbstractAudioFactory::init();
_initialised = true;
return true;
}
//@Override
/*public*/ QString QtSoundAudioFactory::toString()
{
#if 0
return "QtSoundAudioFactory:"
+ " vendor - " + _mixer.getMixerInfo().getVendor()
+ " version - " + _mixer.getMixerInfo().getVersion();
#else
return "QtSoundAudioFactory: " + _mixer->deviceInfo()->deviceName();
#endif
}
//@Override
//@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
// OK to write to static variable _mixer as we are cleaning up
/*public*/ void QtSoundAudioFactory::cleanup()
{
// Stop the command thread
AbstractAudioFactory::cleanup();
// Get the active AudioManager
AudioManager* am = (AudioManager*)InstanceManager::getDefault("AudioManager");
// Retrieve list of Audio Objects and remove the sources
QStringList audios = am->getSystemNameList();
foreach (QString audioName, audios)
{
Audio* audio = am->getAudio(audioName);
if (audio->getSubType() == Audio::SOURCE)
{
if (log->isDebugEnabled())
{
log->debug("Removing JavaSoundAudioSource: " + audioName);
}
// Cast to JavaSoundAudioSource and cleanup
((QtSoundAudioSource*) audio)->cleanUp();
}
}
// Now, re-retrieve list of Audio objects and remove the buffers
audios = am->getSystemNameList();
foreach (QString audioName, audios)
{
Audio* audio = am->getAudio(audioName);
if (audio->getSubType() == Audio::BUFFER)
{
if (log->isDebugEnabled()) {
log->debug("Removing JavaSoundAudioBuffer: " + audioName);
}
// Cast to JavaSoundAudioBuffer and cleanup
((QtSoundAudioBuffer*) audio)->cleanUp();
}
}
// Lastly, re-retrieve list and remove listener.
audios = am->getSystemNameList();
foreach (QString audioName, audios)
{
Audio* audio = am->getAudio(audioName);
if (audio->getSubType() == Audio::LISTENER)
{
if (log->isDebugEnabled()) {
log->debug("Removing JavaSoundAudioListener: " + audioName);
}
// Cast to JavaSoundAudioListener and cleanup
((QtSoundAudioListener*) audio)->cleanUp();
}
}
// Finally, shutdown JavaSound and close the output device
log->debug("Shutting down JavaSound");
_mixer = NULL;
}
//@Override
/*public*/ AudioBuffer* QtSoundAudioFactory::createNewBuffer(QString systemName, QString userName)
{
return new QtSoundAudioBuffer(systemName, userName);
}
//@Override
/*public*/ AudioListener* QtSoundAudioFactory::createNewListener(QString systemName, QString userName)
{
_activeAudioListener = new QtSoundAudioListener(systemName, userName);
return _activeAudioListener;
}
//@Override
/*public*/ AudioListener* QtSoundAudioFactory::getActiveAudioListener() {
return _activeAudioListener;
}
//@Override
/*public*/ AudioSource* QtSoundAudioFactory::createNewSource(QString systemName, QString userName)
{
return new QtSoundAudioSource(systemName, userName);
}
#endif
/**
* Return reference to the current JavaSound mixer object
*
* @return current JavaSound mixer
*/
/*public*/ /*static*/ /*synchronized*/ Mixer* QtSoundAudioFactory::getMixer()
{
return _mixer;
}
| [
"allenck@windstream.net"
] | allenck@windstream.net |
8f92cfe7e3ad9e70b66c05c882d33c552e72a78f | 2ef43ed8cd2670d100cdec1c74b72dc400abd9fd | /src/objects.h | 0a1cf55fcafbb883704caed76d9a1889fb377a69 | [] | no_license | lawu103/tiny_raytracer | aedd43ec8e998e579d4fd0a948cc0055ac08fbd4 | 9d5a2e105d9db1619a8fb8498eec3ba10f4e03e3 | refs/heads/master | 2023-06-07T23:31:31.830568 | 2021-06-19T14:52:10 | 2021-06-19T14:52:10 | 303,430,453 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,390 | h | /*
* objects.h
*
* Created on: Sep. 28, 2020
* Author: lawu103
*/
#ifndef OBJECTS_H_
#define OBJECTS_H_
#include "geometry.h"
class Sphere {
private:
Vec3f center;
float radius;
Vec3f color;
float specular;
float reflective;
public:
Sphere(): center(0, 0, 0), radius(0), color(255, 0, 0), specular(0), reflective(0) {}
Sphere(Vec3f C, float Rd, Vec3f Color, float S, float Rf): center(C), radius(Rd), color(Color),
specular(S), reflective(Rf) {}
~Sphere() {}
Vec3f get_center() const {return center; }
Vec3f get_color() const { return color; }
float get_specular() const { return specular; }
float get_reflective() const { return reflective; }
float ray_intersection(const Vec3f& origin, const Vec3f& dir) const;
};
class Light {
protected:
float intensity;
public:
Light(): intensity(0) {}
Light(float i): intensity(i) {}
~Light() {}
float get_intensity() const { return intensity; }
};
class DirectedLight : public Light {
private:
bool isPoint; // true if point light, false if directional light
Vec3f v; // for point lights, the position. For directional lights, the direction.
public:
DirectedLight(): Light(0), isPoint(true), v(0, 0, 0) {}
DirectedLight(float I, bool T, Vec3f V): Light(I), isPoint(T), v(V) {}
~DirectedLight() {}
bool is_point() const { return isPoint; }
Vec3f get_v() const { return v; }
};
#endif /* OBJECTS_H_ */
| [
"l58wu@uwaterloo.ca"
] | l58wu@uwaterloo.ca |
ae3c0b991bec1c8d1db3198b8472776d201d9405 | 7f69e98afe43db75c3d33f7e99dbba702a37a0a7 | /src/plugins/thirdParty/LLVM/include/llvm/Support/raw_ostream.h | b0e3796cb4cd4681516204aceae46cf0ba4a3ee6 | [
"Apache-2.0"
] | permissive | hsorby/opencor | ce1125ba6a6cd86a811d13d4b54fb12a53a3cc7c | 4ce3332fed67069bd093a6215aeaf81be81c9933 | refs/heads/master | 2021-01-19T07:23:07.743445 | 2015-11-08T13:17:29 | 2015-11-08T13:17:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,946 | h | //===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the raw_ostream class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_SUPPORT_RAW_OSTREAM_H
#define LLVM_SUPPORT_RAW_OSTREAM_H
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/DataTypes.h"
#include <system_error>
//---OPENCOR--- BEGIN
#include "llvmglobal.h"
//---OPENCOR--- END
namespace llvm {
class format_object_base;
class FormattedString;
class FormattedNumber;
template <typename T> class SmallVectorImpl;
namespace sys {
namespace fs {
enum OpenFlags : unsigned;
}
}
/// This class implements an extremely fast bulk output stream that can *only*
/// output to a stream. It does not support seeking, reopening, rewinding, line
/// buffered disciplines etc. It is a simple buffer that outputs
/// a chunk at a time.
class raw_ostream {
private:
void operator=(const raw_ostream &) = delete;
raw_ostream(const raw_ostream &) = delete;
/// The buffer is handled in such a way that the buffer is
/// uninitialized, unbuffered, or out of space when OutBufCur >=
/// OutBufEnd. Thus a single comparison suffices to determine if we
/// need to take the slow path to write a single character.
///
/// The buffer is in one of three states:
/// 1. Unbuffered (BufferMode == Unbuffered)
/// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
/// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
/// OutBufEnd - OutBufStart >= 1).
///
/// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
/// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
/// managed by the subclass.
///
/// If a subclass installs an external buffer using SetBuffer then it can wait
/// for a \see write_impl() call to handle the data which has been put into
/// this buffer.
char *OutBufStart, *OutBufEnd, *OutBufCur;
enum BufferKind {
Unbuffered = 0,
InternalBuffer,
ExternalBuffer
} BufferMode;
public:
// color order matches ANSI escape sequence, don't change
enum Colors {
BLACK=0,
RED,
GREEN,
YELLOW,
BLUE,
MAGENTA,
CYAN,
WHITE,
SAVEDCOLOR
};
explicit raw_ostream(bool unbuffered = false)
: BufferMode(unbuffered ? Unbuffered : InternalBuffer) {
// Start out ready to flush.
OutBufStart = OutBufEnd = OutBufCur = nullptr;
}
virtual ~raw_ostream();
/// tell - Return the current offset with the file.
uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
//===--------------------------------------------------------------------===//
// Configuration Interface
//===--------------------------------------------------------------------===//
/// Set the stream to be buffered, with an automatically determined buffer
/// size.
void SetBuffered();
/// Set the stream to be buffered, using the specified buffer size.
void SetBufferSize(size_t Size) {
flush();
SetBufferAndMode(new char[Size], Size, InternalBuffer);
}
size_t GetBufferSize() const {
// If we're supposed to be buffered but haven't actually gotten around
// to allocating the buffer yet, return the value that would be used.
if (BufferMode != Unbuffered && OutBufStart == nullptr)
return preferred_buffer_size();
// Otherwise just return the size of the allocated buffer.
return OutBufEnd - OutBufStart;
}
/// Set the stream to be unbuffered. When unbuffered, the stream will flush
/// after every write. This routine will also flush the buffer immediately
/// when the stream is being set to unbuffered.
void SetUnbuffered() {
flush();
SetBufferAndMode(nullptr, 0, Unbuffered);
}
size_t GetNumBytesInBuffer() const {
return OutBufCur - OutBufStart;
}
//===--------------------------------------------------------------------===//
// Data Output Interface
//===--------------------------------------------------------------------===//
void flush() {
if (OutBufCur != OutBufStart)
flush_nonempty();
}
raw_ostream &operator<<(char C) {
if (OutBufCur >= OutBufEnd)
return write(C);
*OutBufCur++ = C;
return *this;
}
raw_ostream &operator<<(unsigned char C) {
if (OutBufCur >= OutBufEnd)
return write(C);
*OutBufCur++ = C;
return *this;
}
raw_ostream &operator<<(signed char C) {
if (OutBufCur >= OutBufEnd)
return write(C);
*OutBufCur++ = C;
return *this;
}
raw_ostream &operator<<(StringRef Str) {
// Inline fast path, particularly for strings with a known length.
size_t Size = Str.size();
// Make sure we can use the fast path.
if (Size > (size_t)(OutBufEnd - OutBufCur))
return write(Str.data(), Size);
if (Size) {
memcpy(OutBufCur, Str.data(), Size);
OutBufCur += Size;
}
return *this;
}
raw_ostream &operator<<(const char *Str) {
// Inline fast path, particularly for constant strings where a sufficiently
// smart compiler will simplify strlen.
return this->operator<<(StringRef(Str));
}
raw_ostream &operator<<(const std::string &Str) {
// Avoid the fast path, it would only increase code size for a marginal win.
return write(Str.data(), Str.length());
}
raw_ostream &operator<<(const llvm::SmallVectorImpl<char> &Str) {
return write(Str.data(), Str.size());
}
raw_ostream &operator<<(unsigned long N);
raw_ostream &operator<<(long N);
raw_ostream &operator<<(unsigned long long N);
raw_ostream &operator<<(long long N);
raw_ostream &operator<<(const void *P);
raw_ostream &operator<<(unsigned int N) {
return this->operator<<(static_cast<unsigned long>(N));
}
raw_ostream &operator<<(int N) {
return this->operator<<(static_cast<long>(N));
}
raw_ostream &operator<<(double N);
/// Output \p N in hexadecimal, without any prefix or padding.
raw_ostream &write_hex(unsigned long long N);
/// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
/// satisfy std::isprint into an escape sequence.
raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
raw_ostream &write(unsigned char C);
raw_ostream &write(const char *Ptr, size_t Size);
// Formatted output, see the format() function in Support/Format.h.
raw_ostream &operator<<(const format_object_base &Fmt);
// Formatted output, see the leftJustify() function in Support/Format.h.
raw_ostream &operator<<(const FormattedString &);
// Formatted output, see the formatHex() function in Support/Format.h.
raw_ostream &operator<<(const FormattedNumber &);
/// indent - Insert 'NumSpaces' spaces.
raw_ostream &indent(unsigned NumSpaces);
/// Changes the foreground color of text that will be output from this point
/// forward.
/// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
/// change only the bold attribute, and keep colors untouched
/// @param Bold bold/brighter text, default false
/// @param BG if true change the background, default: change foreground
/// @returns itself so it can be used within << invocations
virtual raw_ostream &changeColor(enum Colors Color,
bool Bold = false,
bool BG = false) {
(void)Color;
(void)Bold;
(void)BG;
return *this;
}
/// Resets the colors to terminal defaults. Call this when you are done
/// outputting colored text, or before program exit.
virtual raw_ostream &resetColor() { return *this; }
/// Reverses the forground and background colors.
virtual raw_ostream &reverseColor() { return *this; }
/// This function determines if this stream is connected to a "tty" or
/// "console" window. That is, the output would be displayed to the user
/// rather than being put on a pipe or stored in a file.
virtual bool is_displayed() const { return false; }
/// This function determines if this stream is displayed and supports colors.
virtual bool has_colors() const { return is_displayed(); }
//===--------------------------------------------------------------------===//
// Subclass Interface
//===--------------------------------------------------------------------===//
private:
/// The is the piece of the class that is implemented by subclasses. This
/// writes the \p Size bytes starting at
/// \p Ptr to the underlying stream.
///
/// This function is guaranteed to only be called at a point at which it is
/// safe for the subclass to install a new buffer via SetBuffer.
///
/// \param Ptr The start of the data to be written. For buffered streams this
/// is guaranteed to be the start of the buffer.
///
/// \param Size The number of bytes to be written.
///
/// \invariant { Size > 0 }
virtual void write_impl(const char *Ptr, size_t Size) = 0;
// An out of line virtual method to provide a home for the class vtable.
virtual void handle();
/// Return the current position within the stream, not counting the bytes
/// currently in the buffer.
virtual uint64_t current_pos() const = 0;
protected:
/// Use the provided buffer as the raw_ostream buffer. This is intended for
/// use only by subclasses which can arrange for the output to go directly
/// into the desired output buffer, instead of being copied on each flush.
void SetBuffer(char *BufferStart, size_t Size) {
SetBufferAndMode(BufferStart, Size, ExternalBuffer);
}
/// Return an efficient buffer size for the underlying output mechanism.
virtual size_t preferred_buffer_size() const;
/// Return the beginning of the current stream buffer, or 0 if the stream is
/// unbuffered.
const char *getBufferStart() const { return OutBufStart; }
//===--------------------------------------------------------------------===//
// Private Interface
//===--------------------------------------------------------------------===//
private:
/// Install the given buffer and mode.
void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
/// Flush the current buffer, which is known to be non-empty. This outputs the
/// currently buffered data and resets the buffer to empty.
void flush_nonempty();
/// Copy data into the buffer. Size must not be greater than the number of
/// unused bytes in the buffer.
void copy_to_buffer(const char *Ptr, size_t Size);
};
/// An abstract base class for streams implementations that also support a
/// pwrite operation. This is usefull for code that can mostly stream out data,
/// but needs to patch in a header that needs to know the output size.
class raw_pwrite_stream : public raw_ostream {
virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
public:
explicit raw_pwrite_stream(bool Unbuffered = false)
: raw_ostream(Unbuffered) {}
void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
#ifndef NDBEBUG
uint64_t Pos = tell();
// /dev/null always reports a pos of 0, so we cannot perform this check
// in that case.
if (Pos)
assert(Size + Offset <= Pos && "We don't support extending the stream");
#endif
pwrite_impl(Ptr, Size, Offset);
}
};
//===----------------------------------------------------------------------===//
// File Output Streams
//===----------------------------------------------------------------------===//
/// A raw_ostream that writes to a file descriptor.
///
class raw_fd_ostream : public raw_pwrite_stream {
int FD;
bool ShouldClose;
/// Error This flag is true if an error of any kind has been detected.
///
bool Error;
/// Controls whether the stream should attempt to use atomic writes, when
/// possible.
bool UseAtomicWrites;
uint64_t pos;
bool SupportsSeeking;
/// See raw_ostream::write_impl.
void write_impl(const char *Ptr, size_t Size) override;
void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
/// Return the current position within the stream, not counting the bytes
/// currently in the buffer.
uint64_t current_pos() const override { return pos; }
/// Determine an efficient buffer size.
size_t preferred_buffer_size() const override;
/// Set the flag indicating that an output error has been encountered.
void error_detected() { Error = true; }
public:
/// Open the specified file for writing. If an error occurs, information
/// about the error is put into EC, and the stream should be immediately
/// destroyed;
/// \p Flags allows optional flags to control how the file will be opened.
///
/// As a special case, if Filename is "-", then the stream will use
/// STDOUT_FILENO instead of opening a file. Note that it will still consider
/// itself to own the file descriptor. In particular, it will close the
/// file descriptor when it is done (this is necessary to detect
/// output errors).
raw_fd_ostream(StringRef Filename, std::error_code &EC,
sys::fs::OpenFlags Flags);
/// FD is the file descriptor that this writes to. If ShouldClose is true,
/// this closes the file when the stream is destroyed.
raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
~raw_fd_ostream() override;
/// Manually flush the stream and close the file. Note that this does not call
/// fsync.
void close();
bool supportsSeeking() { return SupportsSeeking; }
/// Flushes the stream and repositions the underlying file descriptor position
/// to the offset specified from the beginning of the file.
uint64_t seek(uint64_t off);
/// Set the stream to attempt to use atomic writes for individual output
/// routines where possible.
///
/// Note that because raw_ostream's are typically buffered, this flag is only
/// sensible when used on unbuffered streams which will flush their output
/// immediately.
void SetUseAtomicWrites(bool Value) {
UseAtomicWrites = Value;
}
raw_ostream &changeColor(enum Colors colors, bool bold=false,
bool bg=false) override;
raw_ostream &resetColor() override;
raw_ostream &reverseColor() override;
bool is_displayed() const override;
bool has_colors() const override;
/// Return the value of the flag in this raw_fd_ostream indicating whether an
/// output error has been encountered.
/// This doesn't implicitly flush any pending output. Also, it doesn't
/// guarantee to detect all errors unless the stream has been closed.
bool has_error() const {
return Error;
}
/// Set the flag read by has_error() to false. If the error flag is set at the
/// time when this raw_ostream's destructor is called, report_fatal_error is
/// called to report the error. Use clear_error() after handling the error to
/// avoid this behavior.
///
/// "Errors should never pass silently.
/// Unless explicitly silenced."
/// - from The Zen of Python, by Tim Peters
///
void clear_error() {
Error = false;
}
};
/// This returns a reference to a raw_ostream for standard output. Use it like:
/// outs() << "foo" << "bar";
/*---OPENCOR---
raw_ostream &outs();
*/
//---OPENCOR--- BEGIN
raw_ostream LLVM_EXPORT &outs();
//---OPENCOR--- END
/// This returns a reference to a raw_ostream for standard error. Use it like:
/// errs() << "foo" << "bar";
raw_ostream &errs();
/// This returns a reference to a raw_ostream which simply discards output.
/*---OPENCOR---
raw_ostream &nulls();
*/
//---OPENCOR--- BEGIN
raw_ostream LLVM_EXPORT &nulls();
//---OPENCOR--- END
//===----------------------------------------------------------------------===//
// Output Stream Adaptors
//===----------------------------------------------------------------------===//
/// A raw_ostream that writes to an std::string. This is a simple adaptor
/// class. This class does not encounter output errors.
class raw_string_ostream : public raw_ostream {
std::string &OS;
/// See raw_ostream::write_impl.
void write_impl(const char *Ptr, size_t Size) override;
/// Return the current position within the stream, not counting the bytes
/// currently in the buffer.
uint64_t current_pos() const override { return OS.size(); }
public:
explicit raw_string_ostream(std::string &O) : OS(O) {}
~raw_string_ostream() override;
/// Flushes the stream contents to the target string and returns the string's
/// reference.
std::string& str() {
flush();
return OS;
}
};
/// A raw_ostream that writes to an SmallVector or SmallString. This is a
/// simple adaptor class. This class does not encounter output errors.
class raw_svector_ostream : public raw_pwrite_stream {
SmallVectorImpl<char> &OS;
/// See raw_ostream::write_impl.
void write_impl(const char *Ptr, size_t Size) override;
void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
/// Return the current position within the stream, not counting the bytes
/// currently in the buffer.
uint64_t current_pos() const override;
protected:
// Like the regular constructor, but doesn't call init.
explicit raw_svector_ostream(SmallVectorImpl<char> &O, unsigned);
void init();
public:
/// Construct a new raw_svector_ostream.
///
/// \param O The vector to write to; this should generally have at least 128
/// bytes free to avoid any extraneous memory overhead.
explicit raw_svector_ostream(SmallVectorImpl<char> &O);
~raw_svector_ostream() override;
/// This is called when the SmallVector we're appending to is changed outside
/// of the raw_svector_ostream's control. It is only safe to do this if the
/// raw_svector_ostream has previously been flushed.
void resync();
/// Flushes the stream contents to the target vector and return a StringRef
/// for the vector contents.
StringRef str();
};
/// A raw_ostream that discards all output.
class raw_null_ostream : public raw_pwrite_stream {
/// See raw_ostream::write_impl.
void write_impl(const char *Ptr, size_t size) override;
void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
/// Return the current position within the stream, not counting the bytes
/// currently in the buffer.
uint64_t current_pos() const override;
public:
explicit raw_null_ostream() {}
~raw_null_ostream() override;
};
class buffer_ostream : public raw_svector_ostream {
raw_ostream &OS;
SmallVector<char, 0> Buffer;
public:
buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer, 0), OS(OS) {
init();
}
~buffer_ostream() { OS << str(); }
};
} // end llvm namespace
#endif
| [
"agarny@hellix.com"
] | agarny@hellix.com |
a434132ec730ff643d5c7821172262422d5a3e10 | fe0072fb695126aa5a4d6efd08828975d04cfb80 | /set、multiset/set、multiset/源.cpp | 065ff1d20c5dc4e5310941e99b73ee72bf660643 | [] | no_license | smx7/CPlusPlus | 6ef1bd6aab9ddea51962e508511db8abc71bc77e | 7c4cd6522e5132e598d1ed129569643a23cf54a1 | refs/heads/master | 2020-04-15T00:03:26.172291 | 2019-02-26T11:40:08 | 2019-02-26T11:40:08 | 164,226,880 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,217 | cpp | #include<iostream>
#include<set>
using namespace std;
template<class T>
void print(set<T>& s)
{
set<T>::iterator it = s.begin();
while (it != s.end())
{
cout << *it << " ";
it++;
}
cout << endl;
}
void testset1()
{
set<int> s1;
set<int> s2{
{ 2 }, { 4 }, { 1 }, { 1 },{ 6 }
, { 3 }, { 5 }, { 4 }
};
set<int> s3(s2);
set<int> s4(s2.begin(), s2.end());
s1 = s3;
print(s1);
print(s2);
print(s3);
print(s4);
}
void testset2()
{
set<int> s1;
pair<set<int>::iterator, bool> ret;
int arr[] = { 5, 2, 5, 1, 4, 3 };
ret = s1.insert(3);
s1.insert(s1.find(2), 6);
s1.insert(arr, arr + 6);
print(s1);
cout << *(ret.first) << " " << ret.second << endl;
set<int> s2(s1);
s1.erase(s1.find(3));
s1.erase(5);
print(s1);
s1.swap(s2);
print(s1);
print(s2);
s1.clear();
print(s1);
cout << s2.count(2) << endl;
}
void testmultiset()
{
multiset<int> s
{ { 3 }, { 4 }, { 2 }, { 2 },
{ 1 }, { 6 }, { 3 }, { 5 } };
multiset<int>::iterator it = s.begin();
while (it != s.end())
{
cout << *it << " ";
it++;
}
cout << endl;
}
int main()
{
//testset2();
testmultiset();
system("pause");
return 0;
} | [
"noreply@github.com"
] | smx7.noreply@github.com |
f523cb5fc8d274ab9d60a952a8f4556a491816c6 | 35635422101e1c0e4142ca1e176c5d976a6a6ff2 | /deps/glm.9.9.5/glm_inn/detail/type_mat4x4.hpp | e67f4ea3f90f3f21bb9253a10503849ac282bf77 | [
"BSD-3-Clause"
] | permissive | wanghaoxin1991/tprPix | e9ac6078dcf104b89e7db8bc6e973b47d4a46bfc | 877d2f3bcd2028b28f575deebf37bf7d19d1da52 | refs/heads/master | 2021-05-25T17:27:13.564129 | 2020-04-08T22:08:00 | 2020-04-08T22:08:00 | 253,843,248 | 0 | 0 | null | 2020-04-07T15:58:08 | 2020-04-07T15:58:08 | null | UTF-8 | C++ | false | false | 13,738 | hpp | <<<<<<< HEAD
/// @ref core
/// @file glm/detail/type_mat4x4.hpp
#pragma once
#include "type_vec4.hpp"
#include <limits>
#include <cstddef>
namespace glm
{
template<typename T, qualifier Q>
struct mat<4, 4, T, Q>
{
typedef vec<4, T, Q> col_type;
typedef vec<4, T, Q> row_type;
typedef mat<4, 4, T, Q> type;
typedef mat<4, 4, T, Q> transpose_type;
typedef T value_type;
private:
col_type value[4];
public:
// -- Accesses --
typedef length_t length_type;
GLM_FUNC_DECL static GLM_CONSTEXPR length_type length(){return 4;}
GLM_FUNC_DECL col_type & operator[](length_type i);
GLM_FUNC_DECL GLM_CONSTEXPR col_type const& operator[](length_type i) const;
// -- Constructors --
GLM_FUNC_DECL GLM_CONSTEXPR mat() GLM_DEFAULT;
template<qualifier P>
GLM_FUNC_DECL GLM_CONSTEXPR mat(mat<4, 4, T, P> const& m);
GLM_FUNC_DECL explicit GLM_CONSTEXPR mat(T const& x);
GLM_FUNC_DECL GLM_CONSTEXPR mat(
T const& x0, T const& y0, T const& z0, T const& w0,
T const& x1, T const& y1, T const& z1, T const& w1,
T const& x2, T const& y2, T const& z2, T const& w2,
T const& x3, T const& y3, T const& z3, T const& w3);
GLM_FUNC_DECL GLM_CONSTEXPR mat(
col_type const& v0,
col_type const& v1,
col_type const& v2,
col_type const& v3);
// -- Conversions --
template<
typename X1, typename Y1, typename Z1, typename W1,
typename X2, typename Y2, typename Z2, typename W2,
typename X3, typename Y3, typename Z3, typename W3,
typename X4, typename Y4, typename Z4, typename W4>
GLM_FUNC_DECL GLM_CONSTEXPR mat(
X1 const& x1, Y1 const& y1, Z1 const& z1, W1 const& w1,
X2 const& x2, Y2 const& y2, Z2 const& z2, W2 const& w2,
X3 const& x3, Y3 const& y3, Z3 const& z3, W3 const& w3,
X4 const& x4, Y4 const& y4, Z4 const& z4, W4 const& w4);
template<typename V1, typename V2, typename V3, typename V4>
GLM_FUNC_DECL GLM_CONSTEXPR mat(
vec<4, V1, Q> const& v1,
vec<4, V2, Q> const& v2,
vec<4, V3, Q> const& v3,
vec<4, V4, Q> const& v4);
// -- Matrix conversions --
template<typename U, qualifier P>
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<4, 4, U, P> const& m);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<2, 2, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<3, 3, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<2, 3, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<3, 2, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<2, 4, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<4, 2, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<3, 4, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<4, 3, T, Q> const& x);
// -- Unary arithmetic operators --
template<typename U>
GLM_FUNC_DECL mat<4, 4, T, Q> & operator=(mat<4, 4, U, Q> const& m);
template<typename U>
GLM_FUNC_DECL mat<4, 4, T, Q> & operator+=(U s);
template<typename U>
GLM_FUNC_DECL mat<4, 4, T, Q> & operator+=(mat<4, 4, U, Q> const& m);
template<typename U>
GLM_FUNC_DECL mat<4, 4, T, Q> & operator-=(U s);
template<typename U>
GLM_FUNC_DECL mat<4, 4, T, Q> & operator-=(mat<4, 4, U, Q> const& m);
template<typename U>
GLM_FUNC_DECL mat<4, 4, T, Q> & operator*=(U s);
template<typename U>
GLM_FUNC_DECL mat<4, 4, T, Q> & operator*=(mat<4, 4, U, Q> const& m);
template<typename U>
GLM_FUNC_DECL mat<4, 4, T, Q> & operator/=(U s);
template<typename U>
GLM_FUNC_DECL mat<4, 4, T, Q> & operator/=(mat<4, 4, U, Q> const& m);
// -- Increment and decrement operators --
GLM_FUNC_DECL mat<4, 4, T, Q> & operator++();
GLM_FUNC_DECL mat<4, 4, T, Q> & operator--();
GLM_FUNC_DECL mat<4, 4, T, Q> operator++(int);
GLM_FUNC_DECL mat<4, 4, T, Q> operator--(int);
};
// -- Unary operators --
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator+(mat<4, 4, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator-(mat<4, 4, T, Q> const& m);
// -- Binary operators --
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator+(mat<4, 4, T, Q> const& m, T const& s);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator+(T const& s, mat<4, 4, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator+(mat<4, 4, T, Q> const& m1, mat<4, 4, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator-(mat<4, 4, T, Q> const& m, T const& s);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator-(T const& s, mat<4, 4, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator-(mat<4, 4, T, Q> const& m1, mat<4, 4, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator*(mat<4, 4, T, Q> const& m, T const& s);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator*(T const& s, mat<4, 4, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL typename mat<4, 4, T, Q>::col_type operator*(mat<4, 4, T, Q> const& m, typename mat<4, 4, T, Q>::row_type const& v);
template<typename T, qualifier Q>
GLM_FUNC_DECL typename mat<4, 4, T, Q>::row_type operator*(typename mat<4, 4, T, Q>::col_type const& v, mat<4, 4, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<2, 4, T, Q> operator*(mat<4, 4, T, Q> const& m1, mat<2, 4, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<3, 4, T, Q> operator*(mat<4, 4, T, Q> const& m1, mat<3, 4, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator*(mat<4, 4, T, Q> const& m1, mat<4, 4, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator/(mat<4, 4, T, Q> const& m, T const& s);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator/(T const& s, mat<4, 4, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL typename mat<4, 4, T, Q>::col_type operator/(mat<4, 4, T, Q> const& m, typename mat<4, 4, T, Q>::row_type const& v);
template<typename T, qualifier Q>
GLM_FUNC_DECL typename mat<4, 4, T, Q>::row_type operator/(typename mat<4, 4, T, Q>::col_type const& v, mat<4, 4, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator/(mat<4, 4, T, Q> const& m1, mat<4, 4, T, Q> const& m2);
// -- Boolean operators --
template<typename T, qualifier Q>
GLM_FUNC_DECL bool operator==(mat<4, 4, T, Q> const& m1, mat<4, 4, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL bool operator!=(mat<4, 4, T, Q> const& m1, mat<4, 4, T, Q> const& m2);
}//namespace glm
#ifndef GLM_EXTERNAL_TEMPLATE
#include "type_mat4x4.inl"
#endif//GLM_EXTERNAL_TEMPLATE
=======
/// @ref core
/// @file glm/detail/type_mat4x4.hpp
#pragma once
#include "type_vec4.hpp"
#include <limits>
#include <cstddef>
namespace glm
{
template<typename T, qualifier Q>
struct mat<4, 4, T, Q>
{
typedef vec<4, T, Q> col_type;
typedef vec<4, T, Q> row_type;
typedef mat<4, 4, T, Q> type;
typedef mat<4, 4, T, Q> transpose_type;
typedef T value_type;
private:
col_type value[4];
public:
// -- Accesses --
typedef length_t length_type;
GLM_FUNC_DECL static GLM_CONSTEXPR length_type length(){return 4;}
GLM_FUNC_DECL col_type & operator[](length_type i);
GLM_FUNC_DECL GLM_CONSTEXPR col_type const& operator[](length_type i) const;
// -- Constructors --
GLM_FUNC_DECL GLM_CONSTEXPR mat() GLM_DEFAULT;
template<qualifier P>
GLM_FUNC_DECL GLM_CONSTEXPR mat(mat<4, 4, T, P> const& m);
GLM_FUNC_DECL explicit GLM_CONSTEXPR mat(T const& x);
GLM_FUNC_DECL GLM_CONSTEXPR mat(
T const& x0, T const& y0, T const& z0, T const& w0,
T const& x1, T const& y1, T const& z1, T const& w1,
T const& x2, T const& y2, T const& z2, T const& w2,
T const& x3, T const& y3, T const& z3, T const& w3);
GLM_FUNC_DECL GLM_CONSTEXPR mat(
col_type const& v0,
col_type const& v1,
col_type const& v2,
col_type const& v3);
// -- Conversions --
template<
typename X1, typename Y1, typename Z1, typename W1,
typename X2, typename Y2, typename Z2, typename W2,
typename X3, typename Y3, typename Z3, typename W3,
typename X4, typename Y4, typename Z4, typename W4>
GLM_FUNC_DECL GLM_CONSTEXPR mat(
X1 const& x1, Y1 const& y1, Z1 const& z1, W1 const& w1,
X2 const& x2, Y2 const& y2, Z2 const& z2, W2 const& w2,
X3 const& x3, Y3 const& y3, Z3 const& z3, W3 const& w3,
X4 const& x4, Y4 const& y4, Z4 const& z4, W4 const& w4);
template<typename V1, typename V2, typename V3, typename V4>
GLM_FUNC_DECL GLM_CONSTEXPR mat(
vec<4, V1, Q> const& v1,
vec<4, V2, Q> const& v2,
vec<4, V3, Q> const& v3,
vec<4, V4, Q> const& v4);
// -- Matrix conversions --
template<typename U, qualifier P>
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<4, 4, U, P> const& m);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<2, 2, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<3, 3, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<2, 3, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<3, 2, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<2, 4, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<4, 2, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<3, 4, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<4, 3, T, Q> const& x);
// -- Unary arithmetic operators --
template<typename U>
GLM_FUNC_DECL mat<4, 4, T, Q> & operator=(mat<4, 4, U, Q> const& m);
template<typename U>
GLM_FUNC_DECL mat<4, 4, T, Q> & operator+=(U s);
template<typename U>
GLM_FUNC_DECL mat<4, 4, T, Q> & operator+=(mat<4, 4, U, Q> const& m);
template<typename U>
GLM_FUNC_DECL mat<4, 4, T, Q> & operator-=(U s);
template<typename U>
GLM_FUNC_DECL mat<4, 4, T, Q> & operator-=(mat<4, 4, U, Q> const& m);
template<typename U>
GLM_FUNC_DECL mat<4, 4, T, Q> & operator*=(U s);
template<typename U>
GLM_FUNC_DECL mat<4, 4, T, Q> & operator*=(mat<4, 4, U, Q> const& m);
template<typename U>
GLM_FUNC_DECL mat<4, 4, T, Q> & operator/=(U s);
template<typename U>
GLM_FUNC_DECL mat<4, 4, T, Q> & operator/=(mat<4, 4, U, Q> const& m);
// -- Increment and decrement operators --
GLM_FUNC_DECL mat<4, 4, T, Q> & operator++();
GLM_FUNC_DECL mat<4, 4, T, Q> & operator--();
GLM_FUNC_DECL mat<4, 4, T, Q> operator++(int);
GLM_FUNC_DECL mat<4, 4, T, Q> operator--(int);
};
// -- Unary operators --
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator+(mat<4, 4, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator-(mat<4, 4, T, Q> const& m);
// -- Binary operators --
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator+(mat<4, 4, T, Q> const& m, T const& s);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator+(T const& s, mat<4, 4, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator+(mat<4, 4, T, Q> const& m1, mat<4, 4, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator-(mat<4, 4, T, Q> const& m, T const& s);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator-(T const& s, mat<4, 4, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator-(mat<4, 4, T, Q> const& m1, mat<4, 4, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator*(mat<4, 4, T, Q> const& m, T const& s);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator*(T const& s, mat<4, 4, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL typename mat<4, 4, T, Q>::col_type operator*(mat<4, 4, T, Q> const& m, typename mat<4, 4, T, Q>::row_type const& v);
template<typename T, qualifier Q>
GLM_FUNC_DECL typename mat<4, 4, T, Q>::row_type operator*(typename mat<4, 4, T, Q>::col_type const& v, mat<4, 4, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<2, 4, T, Q> operator*(mat<4, 4, T, Q> const& m1, mat<2, 4, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<3, 4, T, Q> operator*(mat<4, 4, T, Q> const& m1, mat<3, 4, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator*(mat<4, 4, T, Q> const& m1, mat<4, 4, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator/(mat<4, 4, T, Q> const& m, T const& s);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator/(T const& s, mat<4, 4, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL typename mat<4, 4, T, Q>::col_type operator/(mat<4, 4, T, Q> const& m, typename mat<4, 4, T, Q>::row_type const& v);
template<typename T, qualifier Q>
GLM_FUNC_DECL typename mat<4, 4, T, Q>::row_type operator/(typename mat<4, 4, T, Q>::col_type const& v, mat<4, 4, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 4, T, Q> operator/(mat<4, 4, T, Q> const& m1, mat<4, 4, T, Q> const& m2);
// -- Boolean operators --
template<typename T, qualifier Q>
GLM_FUNC_DECL bool operator==(mat<4, 4, T, Q> const& m1, mat<4, 4, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL bool operator!=(mat<4, 4, T, Q> const& m1, mat<4, 4, T, Q> const& m2);
}//namespace glm
#ifndef GLM_EXTERNAL_TEMPLATE
#include "type_mat4x4.inl"
#endif//GLM_EXTERNAL_TEMPLATE
>>>>>>> f8aea6f7d63dae77b8d83ba771701e3561278dc4
| [
"wanghaoxin8@163.com"
] | wanghaoxin8@163.com |
b8b5f52794142b4817bcb0d99093910650dd2c3a | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/DiskGroup/UNIX_DiskGroup_HPUX.hxx | 637dd8dc98abe1f638b1ca475fe32f94d59e030b | [
"MIT"
] | permissive | brunolauze/openpegasus-providers | 3244b76d075bc66a77e4ed135893437a66dd769f | f24c56acab2c4c210a8d165bb499cd1b3a12f222 | refs/heads/master | 2020-04-17T04:27:14.970917 | 2015-01-04T22:08:09 | 2015-01-04T22:08:09 | 19,707,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,802 | hxx | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#ifdef PEGASUS_OS_HPUX
#ifndef __UNIX_DISKGROUP_PRIVATE_H
#define __UNIX_DISKGROUP_PRIVATE_H
#endif
#endif
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
f93bc4944b9969a7bf74ef06b5e459998403df17 | 8a5138bab0e35eb33c5dd141a0e7ec784285cb53 | /Problem 18.cpp | 44ac1020b701d2de882efa8e92738c7de28fa674 | [] | no_license | prabodhw96/ProjectEuler | a0d387ed1225bbfe0e7703643b6f3c2495e2e82d | 6e69fe30714ed48026fa6a16b16596ddc6e36bb2 | refs/heads/master | 2020-04-24T20:25:50.251661 | 2019-03-02T10:05:44 | 2019-03-02T10:05:44 | 172,243,223 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,154 | cpp | #include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int tri_num[15][15] = {
{75, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{95, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{17, 47, 82, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{18, 35, 87, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{20, 4, 82, 47, 65, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{19, 1, 23, 75, 3, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{88, 2, 77, 73, 7, 63, 67, 0, 0, 0, 0, 0, 0, 0, 0},
{99, 65, 4, 28, 6, 16, 70, 92, 0, 0, 0, 0, 0, 0, 0},
{41, 41, 26, 56, 83, 40, 80, 70, 33, 0, 0, 0, 0, 0, 0},
{41, 48, 72, 33, 47, 32, 37, 16, 94, 29, 0, 0, 0, 0, 0},
{53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14, 0, 0, 0, 0},
{70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57, 0, 0, 0},
{91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48, 0, 0},
{63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31, 0},
{4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23}
};
for(int i=13; i>=0; i--)
for(int j=0; j<=i; j++)
tri_num[i][j] += max(tri_num[i+1][j], tri_num[i+1][j+1]);
cout<<tri_num[0][0];
return 0;
} | [
"prabodhwankhede1996@gmail.com"
] | prabodhwankhede1996@gmail.com |
6025d90b65ffb63d16e1bc0775f22f3e67ae04d2 | 61b7f668639498fd1301b8973fe4146de4b71211 | /Code/HomingEnemy.cpp | 8ce6d9870b2d85ffd48982e8731ff31f173faea5 | [] | no_license | BenDB925/Bullet-Crush | 476e0c07f5f8ea91d3bacbbb254d86b5466eaa7f | 7507810a6ec7d4fe27d0e92ad4e793ac4d6e8575 | refs/heads/master | 2016-09-01T07:40:56.401898 | 2015-12-14T13:10:50 | 2015-12-14T13:10:50 | 45,038,905 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,314 | cpp | #include "stdafx.h"
#include "HomingEnemy.h"
const float HomingEnemy::m_ACCEL = 0.00001;
const float HomingEnemy::m_MAX_SPEED = 0.0005;
const float HomingEnemy::m_COLLISIONBOXSIZE = 50;
float myDistFormula(sf::Vector2f x, sf::Vector2f y)
{
float distance, tempx, tempy;
tempx = (x.x - y.x);
tempx = pow(tempx, 2.0f);
tempy = (x.y - y.y);
tempy = pow(tempy, 2.0f);
distance = tempx + tempy;
distance = sqrt(distance);
return distance;
}
sf::Vector2f Normalise(sf::Vector2f p_vec)
{
float dist = myDistFormula(sf::Vector2f(0, 0), p_vec);
p_vec /= dist;
return p_vec;
}
HomingEnemy::HomingEnemy(sf::Vector2f p_position, sf::Texture * p_tex, sf::IntRect p_texRect)
{
m_sprite = sf::Sprite(*p_tex);
m_sprite.setTextureRect(p_texRect);
m_position = p_position;
m_sprite.setPosition(m_position);
m_health = 2;
}
HomingEnemy::~HomingEnemy()
{
}
void HomingEnemy::Init()
{
}
void HomingEnemy::Update(sf::Vector2f p_playerPos, float p_dt)
{
sf::Vector2f vecBetweenPlEnem = p_playerPos - m_position;
vecBetweenPlEnem = Normalise(vecBetweenPlEnem);
if (m_velocity.x < m_MAX_SPEED && m_velocity.y < m_MAX_SPEED)
m_velocity += vecBetweenPlEnem * m_ACCEL;
m_position += m_velocity * p_dt;
m_sprite.setPosition(m_position);
m_collisionBox = sf::IntRect(m_position.x + 24, m_position.y, 58, 50);
}
| [
"bendb923@gmail.com"
] | bendb923@gmail.com |
e04dedc26d79393dc6432a7967e04a534be688bf | d1cee40adee73afdbce5b3582bbe4761b595c4e1 | /back/RtmpLivePushSDK/boost/boost/ratio/ratio_static_string.hpp | 4b7e66db12a6f8ead9a09635a383d41037ac9904 | [
"BSL-1.0"
] | permissive | RickyJun/live_plugin | de6fb4fa8ef9f76fffd51e2e51262fb63cea44cb | e4472570eac0d9f388ccac6ee513935488d9577e | refs/heads/master | 2023-05-08T01:49:52.951207 | 2021-05-30T14:09:38 | 2021-05-30T14:09:38 | 345,919,594 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,951 | hpp | // ratio_io
//
// (C) Copyright 2010 Vicente J. Botet Escriba
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
//
// This code was adapted by Vicente from Howard Hinnant's experimental work
// on chrono i/o under lvm/libc++ to Boost
#ifndef BOOST_RATIO_RATIO_STATIC_STRING_HPP
#define BOOST_RATIO_RATIO_STATIC_STRING_HPP
/*
ratio_static_string synopsis
#include <ratio>
#include <string>
namespace boost
{
template <class Ratio, class CharT>
struct ratio_static_string
{
typedef basic_str<CharT, ...> short_name;
typedef basic_str<CharT, ...> long_name;
};
} // boost
*/
#include "config.hpp"
#include "ratio.hpp"
#include "basic_str.hpp"
//#include <sstream>
#if defined(BOOST_NO_UNICODE_LITERALS) || defined(BOOST_NO_CHAR16_T) || defined(BOOST_NO_CHAR32_T)
//~ #define BOOST_RATIO_HAS_UNICODE_SUPPORT
#else
#define BOOST_RATIO_HAS_UNICODE_SUPPORT 1
#endif
namespace boost {
template <class Ratio, class CharT>
struct ratio_static_string;
// atto
template <>
struct ratio_static_string<atto, char>
{
typedef static_string::str_1<'a'>::type short_name;
typedef static_string::str_4<'a','t','t','o'>::type long_name;
};
#ifdef BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_static_string<atto, char16_t>
{
typedef static_string::u16str_1<u'a'>::type short_name;
typedef static_string::u16str_4<u'a',u't',u't',u'o'>::type long_name;
};
template <>
struct ratio_static_string<atto, char32_t>
{
typedef static_string::u32str_1<U'a'>::type short_name;
typedef static_string::u32str_4<U'a',U't',U't',U'o'>::type long_name;
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_static_string<atto, wchar_t>
{
typedef static_string::wstr_1<L'a'>::type short_name;
typedef static_string::wstr_4<L'a',L't',L't',L'o'>::type long_name;
};
#endif
// femto
template <>
struct ratio_static_string<femto, char>
{
typedef static_string::str_1<'f'>::type short_name;
typedef static_string::str_5<'f','e','m','t','o'>::type long_name;
};
#ifdef BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_static_string<femto, char16_t>
{
typedef static_string::u16str_1<u'f'>::type short_name;
typedef static_string::u16str_5<u'f',u'e',u'm',u't',u'o'>::type long_name;
};
template <>
struct ratio_static_string<femto, char32_t>
{
typedef static_string::u32str_1<U'f'>::type short_name;
typedef static_string::u32str_5<U'f',U'e',U'm',U't',U'o'>::type long_name;
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_static_string<femto, wchar_t>
{
typedef static_string::wstr_1<L'f'>::type short_name;
typedef static_string::wstr_5<L'f',L'e',L'm',L't',L'o'>::type long_name;
};
#endif
// pico
template <>
struct ratio_static_string<pico, char>
{
typedef static_string::str_1<'p'>::type short_name;
typedef static_string::str_4<'p','i','c','o'>::type long_name;
};
#ifdef BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_static_string<pico, char16_t>
{
typedef static_string::u16str_1<u'p'>::type short_name;
typedef static_string::u16str_4<u'p',u'i',u'c',u'o'>::type long_name;
};
template <>
struct ratio_static_string<pico, char32_t>
{
typedef static_string::u32str_1<U'p'>::type short_name;
typedef static_string::u32str_4<U'p',U'i',U'c',U'o'>::type long_name;
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_static_string<pico, wchar_t>
{
typedef static_string::wstr_1<L'p'>::type short_name;
typedef static_string::wstr_4<L'p',L'i',L'c',L'o'>::type long_name;
};
#endif
// nano
template <>
struct ratio_static_string<nano, char>
{
typedef static_string::str_1<'n'>::type short_name;
typedef static_string::str_4<'n','a','n','o'>::type long_name;
};
#ifdef BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_static_string<nano, char16_t>
{
typedef static_string::u16str_1<u'n'>::type short_name;
typedef static_string::u16str_4<u'n',u'a',u'n',u'o'>::type long_name;
};
template <>
struct ratio_static_string<nano, char32_t>
{
typedef static_string::u32str_1<U'n'>::type short_name;
typedef static_string::u32str_4<U'n',U'a',U'n',U'o'>::type long_name;
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_static_string<nano, wchar_t>
{
typedef static_string::wstr_1<L'n'>::type short_name;
typedef static_string::wstr_4<L'n',L'a',L'n',L'o'>::type long_name;
};
#endif
// micro
template <>
struct ratio_static_string<micro, char>
{
typedef static_string::str_2<'\xC2','\xB5'>::type short_name;
typedef static_string::str_5<'m','i','c','r','o'>::type long_name;
};
#ifdef BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_static_string<micro, char16_t>
{
typedef static_string::u16str_1<u'\xB5'>::type short_name;
typedef static_string::u16str_5<u'm',u'i',u'c',u'r',u'o'>::type long_name;
};
template <>
struct ratio_static_string<micro, char32_t>
{
typedef static_string::u32str_1<U'\xB5'>::type short_name;
typedef static_string::u32str_5<U'm',U'i',U'c',U'r',U'o'>::type long_name;
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_static_string<micro, wchar_t>
{
typedef static_string::wstr_1<L'\xB5'>::type short_name;
typedef static_string::wstr_5<L'm',L'i',L'c',L'r',L'o'>::type long_name;
};
#endif
// milli
template <>
struct ratio_static_string<milli, char>
{
typedef static_string::str_1<'m'>::type short_name;
typedef static_string::str_5<'m','i','l','l','i'>::type long_name;
};
#ifdef BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_static_string<milli, char16_t>
{
typedef static_string::u16str_1<u'm'>::type short_name;
typedef static_string::u16str_5<u'm',u'i',u'l',u'l',u'i'>::type long_name;
};
template <>
struct ratio_static_string<milli, char32_t>
{
typedef static_string::u32str_1<U'm'>::type short_name;
typedef static_string::u32str_5<U'm',U'i',U'l',U'l',U'i'>::type long_name;
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_static_string<milli, wchar_t>
{
typedef static_string::wstr_1<L'm'>::type short_name;
typedef static_string::wstr_5<L'm',L'i',L'l',L'l',L'i'>::type long_name;
};
#endif
// centi
template <>
struct ratio_static_string<centi, char>
{
typedef static_string::str_1<'c'>::type short_name;
typedef static_string::str_5<'c','e','n','t','i'>::type long_name;
};
#ifdef BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_static_string<centi, char16_t>
{
typedef static_string::u16str_1<u'c'>::type short_name;
typedef static_string::u16str_5<u'c',u'e',u'n',u't',u'i'>::type long_name;
};
template <>
struct ratio_static_string<centi, char32_t>
{
typedef static_string::u32str_1<U'c'>::type short_name;
typedef static_string::u32str_5<U'c',U'e',U'n',U't',U'i'>::type long_name;
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_static_string<centi, wchar_t>
{
typedef static_string::wstr_1<L'c'>::type short_name;
typedef static_string::wstr_5<L'c',L'e',L'n',L't',L'i'>::type long_name;
};
#endif
// deci
template <>
struct ratio_static_string<deci, char>
{
typedef static_string::str_1<'d'>::type short_name;
typedef static_string::str_4<'d','e','c','i'>::type long_name;
};
#ifdef BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_static_string<deci, char16_t>
{
typedef static_string::u16str_1<u'd'>::type short_name;
typedef static_string::u16str_4<u'd',u'e',u'c',u'i'>::type long_name;
};
template <>
struct ratio_static_string<deci, char32_t>
{
typedef static_string::u32str_1<U'd'>::type short_name;
typedef static_string::u32str_4<U'd',U'e',U'c',U'i'>::type long_name;
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_static_string<deci, wchar_t>
{
typedef static_string::wstr_1<L'd'>::type short_name;
typedef static_string::wstr_4<L'd',L'e',L'c',L'i'>::type long_name;
};
#endif
// deca
template <>
struct ratio_static_string<deca, char>
{
typedef static_string::str_2<'d','a'>::type short_name;
typedef static_string::str_4<'d','e','c','a'>::type long_name;
};
#ifdef BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_static_string<deca, char16_t>
{
typedef static_string::u16str_2<u'd',u'a'>::type short_name;
typedef static_string::u16str_4<u'd',u'e',u'c',u'a'>::type long_name;
};
template <>
struct ratio_static_string<deca, char32_t>
{
typedef static_string::u32str_2<U'd',U'a'>::type short_name;
typedef static_string::u32str_4<U'd',U'e',U'c',U'a'>::type long_name;
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_static_string<deca, wchar_t>
{
typedef static_string::wstr_2<L'd',L'a'>::type short_name;
typedef static_string::wstr_4<L'd',L'e',L'c',L'a'>::type long_name;
};
#endif
// hecto
template <>
struct ratio_static_string<hecto, char>
{
typedef static_string::str_1<'h'>::type short_name;
typedef static_string::str_5<'h','e','c','t','o'>::type long_name;
};
#ifdef BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_static_string<hecto, char16_t>
{
typedef static_string::u16str_1<u'h'>::type short_name;
typedef static_string::u16str_5<u'h',u'e',u'c',u't',u'o'>::type long_name;
};
template <>
struct ratio_static_string<hecto, char32_t>
{
typedef static_string::u32str_1<U'h'>::type short_name;
typedef static_string::u32str_5<U'h',U'e',U'c',U't',U'o'>::type long_name;
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_static_string<hecto, wchar_t>
{
typedef static_string::wstr_1<L'h'>::type short_name;
typedef static_string::wstr_5<L'h',L'e',L'c',L't',L'o'>::type long_name;
};
#endif
// kilo
template <>
struct ratio_static_string<kilo, char>
{
typedef static_string::str_1<'k'>::type short_name;
typedef static_string::str_4<'k','i','l','o'>::type long_name;
};
#ifdef BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_static_string<kilo, char16_t>
{
typedef static_string::u16str_1<u'k'>::type short_name;
typedef static_string::u16str_4<u'k',u'i',u'l',u'o'>::type long_name;
};
template <>
struct ratio_static_string<kilo, char32_t>
{
typedef static_string::u32str_1<U'k'>::type short_name;
typedef static_string::u32str_4<U'k',U'i',U'l',U'o'>::type long_name;
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_static_string<kilo, wchar_t>
{
typedef static_string::wstr_1<L'k'>::type short_name;
typedef static_string::wstr_4<L'k',L'i',L'l',L'o'>::type long_name;
};
#endif
// mega
template <>
struct ratio_static_string<mega, char>
{
typedef static_string::str_1<'M'>::type short_name;
typedef static_string::str_4<'m','e','g','a'>::type long_name;
};
#ifdef BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_static_string<mega, char16_t>
{
typedef static_string::u16str_1<u'M'>::type short_name;
typedef static_string::u16str_4<u'm',u'e',u'g',u'a'>::type long_name;
};
template <>
struct ratio_static_string<mega, char32_t>
{
typedef static_string::u32str_1<U'M'>::type short_name;
typedef static_string::u32str_4<U'm',U'e',U'g',U'a'>::type long_name;
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_static_string<mega, wchar_t>
{
typedef static_string::wstr_1<L'M'>::type short_name;
typedef static_string::wstr_4<L'm',L'e',L'g',L'a'>::type long_name;
};
#endif
// giga
template <>
struct ratio_static_string<giga, char>
{
typedef static_string::str_1<'G'>::type short_name;
typedef static_string::str_4<'g','i','g','a'>::type long_name;
};
#ifdef BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_static_string<giga, char16_t>
{
typedef static_string::u16str_1<u'G'>::type short_name;
typedef static_string::u16str_4<u'g',u'i',u'g',u'a'>::type long_name;
};
template <>
struct ratio_static_string<giga, char32_t>
{
typedef static_string::u32str_1<U'G'>::type short_name;
typedef static_string::u32str_4<U'g',U'i',U'g',U'a'>::type long_name;
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_static_string<giga, wchar_t>
{
typedef static_string::wstr_1<L'G'>::type short_name;
typedef static_string::wstr_4<L'g',L'i',L'g',L'a'>::type long_name;
};
#endif
// tera
template <>
struct ratio_static_string<tera, char>
{
typedef static_string::str_1<'T'>::type short_name;
typedef static_string::str_4<'t','e','r','a'>::type long_name;
};
#ifdef BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_static_string<tera, char16_t>
{
typedef static_string::u16str_1<u'T'>::type short_name;
typedef static_string::u16str_4<u't',u'e',u'r',u'a'>::type long_name;
};
template <>
struct ratio_static_string<tera, char32_t>
{
typedef static_string::u32str_1<U'T'>::type short_name;
typedef static_string::u32str_4<U't',U'e',U'r',U'a'>::type long_name;
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_static_string<tera, wchar_t>
{
typedef static_string::wstr_1<L'T'>::type short_name;
typedef static_string::wstr_4<L'r',L'e',L'r',L'a'>::type long_name;
};
#endif
// peta
template <>
struct ratio_static_string<peta, char>
{
typedef static_string::str_1<'P'>::type short_name;
typedef static_string::str_4<'p','e','t','a'>::type long_name;
};
#ifdef BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_static_string<peta, char16_t>
{
typedef static_string::u16str_1<u'P'>::type short_name;
typedef static_string::u16str_4<u'p',u'e',u't',u'a'>::type long_name;
};
template <>
struct ratio_static_string<peta, char32_t>
{
typedef static_string::u32str_1<U'P'>::type short_name;
typedef static_string::u32str_4<U'p',U'e',U't',U'a'>::type long_name;
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_static_string<peta, wchar_t>
{
typedef static_string::wstr_1<L'P'>::type short_name;
typedef static_string::wstr_4<L'p',L'e',L't',L'a'>::type long_name;
};
#endif
// exa
template <>
struct ratio_static_string<exa, char>
{
typedef static_string::str_1<'E'>::type short_name;
typedef static_string::str_3<'e','x','a'>::type long_name;
};
#ifdef BOOST_RATIO_HAS_UNICODE_SUPPORT
template <>
struct ratio_static_string<exa, char16_t>
{
typedef static_string::u16str_1<u'E'>::type short_name;
typedef static_string::u16str_3<u'e',u'x',u'a'>::type long_name;
};
template <>
struct ratio_static_string<exa, char32_t>
{
typedef static_string::u32str_1<U'E'>::type short_name;
typedef static_string::u32str_3<U'e',U'x',U'a'>::type long_name;
};
#endif
#ifndef BOOST_NO_STD_WSTRING
template <>
struct ratio_static_string<exa, wchar_t>
{
typedef static_string::wstr_1<L'E'>::type short_name;
typedef static_string::wstr_3<L'e',L'x',L'a'>::type long_name;
};
#endif
}
#endif // BOOST_RATIO_RATIO_STATIC_STRING_HPP
| [
"wenwenjun@weeget.cn"
] | wenwenjun@weeget.cn |
cfb98aea49cb86ac17f3de55b8a83c16f5c57c5d | 5390eac0ac54d2c3c1c664ae525881fa988e2cf9 | /include/Pothos/serialization/impl/mpl/sort.hpp | bdac8ad0e791545d0ac96a80b2a077b26f2d1213 | [
"BSL-1.0"
] | permissive | pothosware/pothos-serialization | 2935b8ab1fe51299a6beba2a3e11611928186849 | c59130f916a3e5b833a32ba415063f9cb306a8dd | refs/heads/master | 2021-08-16T15:22:12.642058 | 2015-12-10T03:32:04 | 2015-12-10T03:32:04 | 19,961,886 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 761 | hpp |
#ifndef POTHOS_MPL_SORT_HPP_INCLUDED
#define POTHOS_MPL_SORT_HPP_INCLUDED
// Copyright Eric Friedman 2002-2003
// Copyright Aleksey Gurtovoy 2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: sort.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-10 23:19:02 -0700 (Fri, 10 Oct 2008) $
// $Revision: 49267 $
#include <Pothos/serialization/impl/mpl/aux_/sort_impl.hpp>
#include <Pothos/serialization/impl/mpl/aux_/inserter_algorithm.hpp>
namespace Pothos { namespace mpl {
POTHOS_MPL_AUX_INSERTER_ALGORITHM_DEF(3, sort)
}}
#endif // BOOST_MPL_SORT_HPP_INCLUDED
| [
"josh@joshknows.com"
] | josh@joshknows.com |
fb299b68dfc9309bc3d47e3656859a60dac94e63 | a1620e869cd9542a334d2e118d2ea7ceb7c1a535 | /OpenGLTheCherno/src/Shader.h | e32d300f560f5f213d35c5b29101cbc9b4ab96a5 | [] | no_license | Xertor/OpenGLTheCherno | a83010bea5eaf3c8c8b83bd1752bd17ddf97af81 | f0c811b5de0be050138a31b6f2a7d626aab9968a | refs/heads/master | 2022-11-07T22:34:56.350890 | 2020-06-22T00:42:42 | 2020-06-22T00:42:42 | 255,145,807 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,017 | h | #pragma once
#include <string>
#include <unordered_map>
#include "glm/glm.hpp"
struct ShaderProgramSource
{
std::string VertexSource;
std::string FragmentSource;
};
class Shader
{
private:
std::string m_Filepath;
unsigned int m_RenderID;
// caching for uniforms
std::unordered_map<std::string, int> m_UniformLocationCache;
public:
Shader(const std::string& filepath);
~Shader();
void Bind() const;
void Unbind() const;
// Set uniforms
void SetUniform1i(const std::string& name, int value);
void SetUniform1f(const std::string& name, float value);
void SetUniform4f(const std::string& name, float v0, float v1, float v2, float f3);
void SetUniformMat4f(const std::string& name, const glm::mat4& proj);
private:
ShaderProgramSource ParseShader(const std::string& filepath);
unsigned int CreateShader(const std::string& vertexShader, const std::string& fragmentShader);
unsigned int CompileShader(unsigned int type, const std::string& source);
int GetUniformLocation(const std::string& name);
}; | [
"marsp@abv.bg"
] | marsp@abv.bg |
a25ee5e43899b03b21c864897b0da53566d42721 | ceb4e487773685b116127dc2e2bcfc047cfc52fc | /cpp/gtest_all.cpp | 7585e43872bb90c998bd5582dd0fab057c356334 | [
"MIT"
] | permissive | emilybache/Tennis-Refactoring-Kata | 182642b952fca63ca9782bce2aeb9df0e682ad52 | f196fb3dbb94848ffd0d69bc2b952df744c99bf1 | refs/heads/main | 2023-08-26T09:35:36.716013 | 2023-08-14T07:12:28 | 2023-08-14T07:12:39 | 10,599,822 | 608 | 1,108 | MIT | 2023-09-05T12:10:58 | 2013-06-10T12:36:08 | TypeScript | UTF-8 | C++ | false | false | 3,077 | cpp | //
// Created by Anders Arnholm on 2020-12-04.
//
#include <string>
#include <gtest/gtest.h>
const std::string tennis_score(int p1Score, int p2Score);
TEST(TennisTest, LoveAll_0_0) {
EXPECT_EQ("Love-All", tennis_score(0, 0));
}
TEST(TennisTest, FifteenAll_1_1) {
EXPECT_EQ("Fifteen-All", tennis_score(1, 1));
}
TEST(TennisTest, ThirtyAll_2_2) {
EXPECT_EQ("Thirty-All", tennis_score(2, 2));
}
TEST(TennisTest, Deuce_3_3) {
EXPECT_EQ("Deuce", tennis_score(3, 3));
}
TEST(TennisTest, Deuce_4_4) {
EXPECT_EQ("Deuce", tennis_score(4, 4));
}
TEST(TennisTest, FifteenLove_1_0) {
EXPECT_EQ("Fifteen-Love", tennis_score(1, 0));
}
TEST(TennisTest, LoveFifteen_0_1) {
EXPECT_EQ("Love-Fifteen", tennis_score(0, 1));
}
TEST(TennisTest, ThirtyLove_2_0) {
EXPECT_EQ("Thirty-Love", tennis_score(2, 0));
}
TEST(TennisTest, LoveThirty_0_2) {
EXPECT_EQ("Love-Thirty", tennis_score(0, 2));
}
TEST(TennisTest, FortyLove_3_0) {
EXPECT_EQ("Forty-Love", tennis_score(3, 0));
}
TEST(TennisTest, LoveForty_0_3) {
EXPECT_EQ("Love-Forty", tennis_score(0, 3));
}
TEST(TennisTest, Winforplayer1_4_0) {
EXPECT_EQ("Win for player1", tennis_score(4, 0));
}
TEST(TennisTest, Winforplayer2_0_4) {
EXPECT_EQ("Win for player2", tennis_score(0, 4));
}
TEST(TennisTest, ThirtyFifteen_2_1) {
EXPECT_EQ("Thirty-Fifteen", tennis_score(2, 1));
}
TEST(TennisTest, FifteenThirty_1_2) {
EXPECT_EQ("Fifteen-Thirty", tennis_score(1, 2));
}
TEST(TennisTest, FortyFifteen_3_1) {
EXPECT_EQ("Forty-Fifteen", tennis_score(3, 1));
}
TEST(TennisTest, FifteenForty_1_3) {
EXPECT_EQ("Fifteen-Forty", tennis_score(1, 3));
}
TEST(TennisTest, Winforplayer1_4_1) {
EXPECT_EQ("Win for player1", tennis_score(4, 1));
}
TEST(TennisTest, Winforplayer2_1_4) {
EXPECT_EQ("Win for player2", tennis_score(1, 4));
}
TEST(TennisTest, FortyThirty_3_2) {
EXPECT_EQ("Forty-Thirty", tennis_score(3, 2));
}
TEST(TennisTest, ThirtyForty_2_3) {
EXPECT_EQ("Thirty-Forty", tennis_score(2, 3));
}
TEST(TennisTest, Winforplayer1_4_2) {
EXPECT_EQ("Win for player1", tennis_score(4, 2));
}
TEST(TennisTest, Winforplayer2_2_4) {
EXPECT_EQ("Win for player2", tennis_score(2, 4));
}
TEST(TennisTest, Advantageplayer1_4_3) {
EXPECT_EQ("Advantage player1", tennis_score(4, 3));
}
TEST(TennisTest, Advantageplayer2_3_4) {
EXPECT_EQ("Advantage player2", tennis_score(3, 4));
}
TEST(TennisTest, Advantageplayer1_5_4) {
EXPECT_EQ("Advantage player1", tennis_score(5, 4));
}
TEST(TennisTest, Advantageplayer2_4_5) {
EXPECT_EQ("Advantage player2", tennis_score(4, 5));
}
TEST(TennisTest, Advantageplayer1_15_14) {
EXPECT_EQ("Advantage player1", tennis_score(15, 14));
}
TEST(TennisTest, Advantageplayer2_14_15) {
EXPECT_EQ("Advantage player2", tennis_score(14, 15));
}
TEST(TennisTest, Winforplayer1_6_4) {
EXPECT_EQ("Win for player1", tennis_score(6, 4));
}
TEST(TennisTest, Winforplayer2_4_6) {
EXPECT_EQ("Win for player2", tennis_score(4, 6));
}
TEST(TennisTest, Winforplayer1_16_14) {
EXPECT_EQ("Win for player1", tennis_score(16, 14));
}
TEST(TennisTest, Winforplayer2_14_16) {
EXPECT_EQ("Win for player2", tennis_score(14, 16));
}
| [
"anders.arnholm@hiq.se"
] | anders.arnholm@hiq.se |
5648e41dd396f64200800205f031b642448d8db8 | d939ea588d1b215261b92013e050993b21651f9a | /lighthouse/src/v20200324/model/Bundle.cpp | 6319162ddb579d195462dcf181b8d4d723fc47b3 | [
"Apache-2.0"
] | permissive | chenxx98/tencentcloud-sdk-cpp | 374e6d1349f8992893ded7aa08f911dd281f1bda | a9e75d321d96504bc3437300d26e371f5f4580a0 | refs/heads/master | 2023-03-27T05:35:50.158432 | 2021-03-26T05:18:10 | 2021-03-26T05:18:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,297 | cpp | /*
* 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.
*/
#include <tencentcloud/lighthouse/v20200324/model/Bundle.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Lighthouse::V20200324::Model;
using namespace rapidjson;
using namespace std;
Bundle::Bundle() :
m_bundleIdHasBeenSet(false),
m_memoryHasBeenSet(false),
m_systemDiskTypeHasBeenSet(false),
m_systemDiskSizeHasBeenSet(false),
m_monthlyTrafficHasBeenSet(false),
m_supportLinuxUnixPlatformHasBeenSet(false),
m_supportWindowsPlatformHasBeenSet(false),
m_priceHasBeenSet(false),
m_cPUHasBeenSet(false),
m_internetMaxBandwidthOutHasBeenSet(false),
m_internetChargeTypeHasBeenSet(false),
m_bundleSalesStateHasBeenSet(false),
m_bundleTypeHasBeenSet(false),
m_bundleDisplayLabelHasBeenSet(false)
{
}
CoreInternalOutcome Bundle::Deserialize(const Value &value)
{
string requestId = "";
if (value.HasMember("BundleId") && !value["BundleId"].IsNull())
{
if (!value["BundleId"].IsString())
{
return CoreInternalOutcome(Error("response `Bundle.BundleId` IsString=false incorrectly").SetRequestId(requestId));
}
m_bundleId = string(value["BundleId"].GetString());
m_bundleIdHasBeenSet = true;
}
if (value.HasMember("Memory") && !value["Memory"].IsNull())
{
if (!value["Memory"].IsInt64())
{
return CoreInternalOutcome(Error("response `Bundle.Memory` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_memory = value["Memory"].GetInt64();
m_memoryHasBeenSet = true;
}
if (value.HasMember("SystemDiskType") && !value["SystemDiskType"].IsNull())
{
if (!value["SystemDiskType"].IsString())
{
return CoreInternalOutcome(Error("response `Bundle.SystemDiskType` IsString=false incorrectly").SetRequestId(requestId));
}
m_systemDiskType = string(value["SystemDiskType"].GetString());
m_systemDiskTypeHasBeenSet = true;
}
if (value.HasMember("SystemDiskSize") && !value["SystemDiskSize"].IsNull())
{
if (!value["SystemDiskSize"].IsInt64())
{
return CoreInternalOutcome(Error("response `Bundle.SystemDiskSize` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_systemDiskSize = value["SystemDiskSize"].GetInt64();
m_systemDiskSizeHasBeenSet = true;
}
if (value.HasMember("MonthlyTraffic") && !value["MonthlyTraffic"].IsNull())
{
if (!value["MonthlyTraffic"].IsInt64())
{
return CoreInternalOutcome(Error("response `Bundle.MonthlyTraffic` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_monthlyTraffic = value["MonthlyTraffic"].GetInt64();
m_monthlyTrafficHasBeenSet = true;
}
if (value.HasMember("SupportLinuxUnixPlatform") && !value["SupportLinuxUnixPlatform"].IsNull())
{
if (!value["SupportLinuxUnixPlatform"].IsBool())
{
return CoreInternalOutcome(Error("response `Bundle.SupportLinuxUnixPlatform` IsBool=false incorrectly").SetRequestId(requestId));
}
m_supportLinuxUnixPlatform = value["SupportLinuxUnixPlatform"].GetBool();
m_supportLinuxUnixPlatformHasBeenSet = true;
}
if (value.HasMember("SupportWindowsPlatform") && !value["SupportWindowsPlatform"].IsNull())
{
if (!value["SupportWindowsPlatform"].IsBool())
{
return CoreInternalOutcome(Error("response `Bundle.SupportWindowsPlatform` IsBool=false incorrectly").SetRequestId(requestId));
}
m_supportWindowsPlatform = value["SupportWindowsPlatform"].GetBool();
m_supportWindowsPlatformHasBeenSet = true;
}
if (value.HasMember("Price") && !value["Price"].IsNull())
{
if (!value["Price"].IsObject())
{
return CoreInternalOutcome(Error("response `Bundle.Price` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_price.Deserialize(value["Price"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_priceHasBeenSet = true;
}
if (value.HasMember("CPU") && !value["CPU"].IsNull())
{
if (!value["CPU"].IsInt64())
{
return CoreInternalOutcome(Error("response `Bundle.CPU` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_cPU = value["CPU"].GetInt64();
m_cPUHasBeenSet = true;
}
if (value.HasMember("InternetMaxBandwidthOut") && !value["InternetMaxBandwidthOut"].IsNull())
{
if (!value["InternetMaxBandwidthOut"].IsUint64())
{
return CoreInternalOutcome(Error("response `Bundle.InternetMaxBandwidthOut` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_internetMaxBandwidthOut = value["InternetMaxBandwidthOut"].GetUint64();
m_internetMaxBandwidthOutHasBeenSet = true;
}
if (value.HasMember("InternetChargeType") && !value["InternetChargeType"].IsNull())
{
if (!value["InternetChargeType"].IsString())
{
return CoreInternalOutcome(Error("response `Bundle.InternetChargeType` IsString=false incorrectly").SetRequestId(requestId));
}
m_internetChargeType = string(value["InternetChargeType"].GetString());
m_internetChargeTypeHasBeenSet = true;
}
if (value.HasMember("BundleSalesState") && !value["BundleSalesState"].IsNull())
{
if (!value["BundleSalesState"].IsString())
{
return CoreInternalOutcome(Error("response `Bundle.BundleSalesState` IsString=false incorrectly").SetRequestId(requestId));
}
m_bundleSalesState = string(value["BundleSalesState"].GetString());
m_bundleSalesStateHasBeenSet = true;
}
if (value.HasMember("BundleType") && !value["BundleType"].IsNull())
{
if (!value["BundleType"].IsString())
{
return CoreInternalOutcome(Error("response `Bundle.BundleType` IsString=false incorrectly").SetRequestId(requestId));
}
m_bundleType = string(value["BundleType"].GetString());
m_bundleTypeHasBeenSet = true;
}
if (value.HasMember("BundleDisplayLabel") && !value["BundleDisplayLabel"].IsNull())
{
if (!value["BundleDisplayLabel"].IsString())
{
return CoreInternalOutcome(Error("response `Bundle.BundleDisplayLabel` IsString=false incorrectly").SetRequestId(requestId));
}
m_bundleDisplayLabel = string(value["BundleDisplayLabel"].GetString());
m_bundleDisplayLabelHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void Bundle::ToJsonObject(Value &value, Document::AllocatorType& allocator) const
{
if (m_bundleIdHasBeenSet)
{
Value iKey(kStringType);
string key = "BundleId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_bundleId.c_str(), allocator).Move(), allocator);
}
if (m_memoryHasBeenSet)
{
Value iKey(kStringType);
string key = "Memory";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_memory, allocator);
}
if (m_systemDiskTypeHasBeenSet)
{
Value iKey(kStringType);
string key = "SystemDiskType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_systemDiskType.c_str(), allocator).Move(), allocator);
}
if (m_systemDiskSizeHasBeenSet)
{
Value iKey(kStringType);
string key = "SystemDiskSize";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_systemDiskSize, allocator);
}
if (m_monthlyTrafficHasBeenSet)
{
Value iKey(kStringType);
string key = "MonthlyTraffic";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_monthlyTraffic, allocator);
}
if (m_supportLinuxUnixPlatformHasBeenSet)
{
Value iKey(kStringType);
string key = "SupportLinuxUnixPlatform";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_supportLinuxUnixPlatform, allocator);
}
if (m_supportWindowsPlatformHasBeenSet)
{
Value iKey(kStringType);
string key = "SupportWindowsPlatform";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_supportWindowsPlatform, allocator);
}
if (m_priceHasBeenSet)
{
Value iKey(kStringType);
string key = "Price";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(kObjectType).Move(), allocator);
m_price.ToJsonObject(value[key.c_str()], allocator);
}
if (m_cPUHasBeenSet)
{
Value iKey(kStringType);
string key = "CPU";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_cPU, allocator);
}
if (m_internetMaxBandwidthOutHasBeenSet)
{
Value iKey(kStringType);
string key = "InternetMaxBandwidthOut";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_internetMaxBandwidthOut, allocator);
}
if (m_internetChargeTypeHasBeenSet)
{
Value iKey(kStringType);
string key = "InternetChargeType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_internetChargeType.c_str(), allocator).Move(), allocator);
}
if (m_bundleSalesStateHasBeenSet)
{
Value iKey(kStringType);
string key = "BundleSalesState";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_bundleSalesState.c_str(), allocator).Move(), allocator);
}
if (m_bundleTypeHasBeenSet)
{
Value iKey(kStringType);
string key = "BundleType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_bundleType.c_str(), allocator).Move(), allocator);
}
if (m_bundleDisplayLabelHasBeenSet)
{
Value iKey(kStringType);
string key = "BundleDisplayLabel";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_bundleDisplayLabel.c_str(), allocator).Move(), allocator);
}
}
string Bundle::GetBundleId() const
{
return m_bundleId;
}
void Bundle::SetBundleId(const string& _bundleId)
{
m_bundleId = _bundleId;
m_bundleIdHasBeenSet = true;
}
bool Bundle::BundleIdHasBeenSet() const
{
return m_bundleIdHasBeenSet;
}
int64_t Bundle::GetMemory() const
{
return m_memory;
}
void Bundle::SetMemory(const int64_t& _memory)
{
m_memory = _memory;
m_memoryHasBeenSet = true;
}
bool Bundle::MemoryHasBeenSet() const
{
return m_memoryHasBeenSet;
}
string Bundle::GetSystemDiskType() const
{
return m_systemDiskType;
}
void Bundle::SetSystemDiskType(const string& _systemDiskType)
{
m_systemDiskType = _systemDiskType;
m_systemDiskTypeHasBeenSet = true;
}
bool Bundle::SystemDiskTypeHasBeenSet() const
{
return m_systemDiskTypeHasBeenSet;
}
int64_t Bundle::GetSystemDiskSize() const
{
return m_systemDiskSize;
}
void Bundle::SetSystemDiskSize(const int64_t& _systemDiskSize)
{
m_systemDiskSize = _systemDiskSize;
m_systemDiskSizeHasBeenSet = true;
}
bool Bundle::SystemDiskSizeHasBeenSet() const
{
return m_systemDiskSizeHasBeenSet;
}
int64_t Bundle::GetMonthlyTraffic() const
{
return m_monthlyTraffic;
}
void Bundle::SetMonthlyTraffic(const int64_t& _monthlyTraffic)
{
m_monthlyTraffic = _monthlyTraffic;
m_monthlyTrafficHasBeenSet = true;
}
bool Bundle::MonthlyTrafficHasBeenSet() const
{
return m_monthlyTrafficHasBeenSet;
}
bool Bundle::GetSupportLinuxUnixPlatform() const
{
return m_supportLinuxUnixPlatform;
}
void Bundle::SetSupportLinuxUnixPlatform(const bool& _supportLinuxUnixPlatform)
{
m_supportLinuxUnixPlatform = _supportLinuxUnixPlatform;
m_supportLinuxUnixPlatformHasBeenSet = true;
}
bool Bundle::SupportLinuxUnixPlatformHasBeenSet() const
{
return m_supportLinuxUnixPlatformHasBeenSet;
}
bool Bundle::GetSupportWindowsPlatform() const
{
return m_supportWindowsPlatform;
}
void Bundle::SetSupportWindowsPlatform(const bool& _supportWindowsPlatform)
{
m_supportWindowsPlatform = _supportWindowsPlatform;
m_supportWindowsPlatformHasBeenSet = true;
}
bool Bundle::SupportWindowsPlatformHasBeenSet() const
{
return m_supportWindowsPlatformHasBeenSet;
}
Price Bundle::GetPrice() const
{
return m_price;
}
void Bundle::SetPrice(const Price& _price)
{
m_price = _price;
m_priceHasBeenSet = true;
}
bool Bundle::PriceHasBeenSet() const
{
return m_priceHasBeenSet;
}
int64_t Bundle::GetCPU() const
{
return m_cPU;
}
void Bundle::SetCPU(const int64_t& _cPU)
{
m_cPU = _cPU;
m_cPUHasBeenSet = true;
}
bool Bundle::CPUHasBeenSet() const
{
return m_cPUHasBeenSet;
}
uint64_t Bundle::GetInternetMaxBandwidthOut() const
{
return m_internetMaxBandwidthOut;
}
void Bundle::SetInternetMaxBandwidthOut(const uint64_t& _internetMaxBandwidthOut)
{
m_internetMaxBandwidthOut = _internetMaxBandwidthOut;
m_internetMaxBandwidthOutHasBeenSet = true;
}
bool Bundle::InternetMaxBandwidthOutHasBeenSet() const
{
return m_internetMaxBandwidthOutHasBeenSet;
}
string Bundle::GetInternetChargeType() const
{
return m_internetChargeType;
}
void Bundle::SetInternetChargeType(const string& _internetChargeType)
{
m_internetChargeType = _internetChargeType;
m_internetChargeTypeHasBeenSet = true;
}
bool Bundle::InternetChargeTypeHasBeenSet() const
{
return m_internetChargeTypeHasBeenSet;
}
string Bundle::GetBundleSalesState() const
{
return m_bundleSalesState;
}
void Bundle::SetBundleSalesState(const string& _bundleSalesState)
{
m_bundleSalesState = _bundleSalesState;
m_bundleSalesStateHasBeenSet = true;
}
bool Bundle::BundleSalesStateHasBeenSet() const
{
return m_bundleSalesStateHasBeenSet;
}
string Bundle::GetBundleType() const
{
return m_bundleType;
}
void Bundle::SetBundleType(const string& _bundleType)
{
m_bundleType = _bundleType;
m_bundleTypeHasBeenSet = true;
}
bool Bundle::BundleTypeHasBeenSet() const
{
return m_bundleTypeHasBeenSet;
}
string Bundle::GetBundleDisplayLabel() const
{
return m_bundleDisplayLabel;
}
void Bundle::SetBundleDisplayLabel(const string& _bundleDisplayLabel)
{
m_bundleDisplayLabel = _bundleDisplayLabel;
m_bundleDisplayLabelHasBeenSet = true;
}
bool Bundle::BundleDisplayLabelHasBeenSet() const
{
return m_bundleDisplayLabelHasBeenSet;
}
| [
"tencentcloudapi@tenent.com"
] | tencentcloudapi@tenent.com |
d854844c5ed286065e0bfdf381b468d16b2ff3a6 | cbd2a87e64c0338e5c0a0ef4f98dccfb8452c687 | /src/marnav/nmea/dbk.cpp | d041d5e8b6e2ac99cddc31e81004b12979b0b56f | [
"BSD-3-Clause",
"BSD-4-Clause"
] | permissive | mb12/marnav | 194c87279e8aa329d530ee9b7125b7fdc64bf4f2 | 4eb797488c734c183c2a4e4c22158891cd80d2e8 | refs/heads/master | 2021-01-24T23:34:31.791011 | 2016-01-11T10:52:25 | 2016-01-11T10:52:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,401 | cpp | #include "dbk.hpp"
#include <marnav/nmea/io.hpp>
#include <marnav/utils/unique.hpp>
namespace marnav
{
namespace nmea
{
constexpr const char * dbk::TAG;
dbk::dbk()
: sentence(ID, TAG, talker_id::integrated_instrumentation)
{
}
void dbk::set_depth_feet(double t) noexcept
{
depth_feet = t;
depth_feet_unit = unit::distance::feet;
}
void dbk::set_depth_meter(double t) noexcept
{
depth_meter = t;
depth_meter_unit = unit::distance::meter;
}
void dbk::set_depth_fathom(double t) noexcept
{
depth_fathom = t;
depth_fathom_unit = unit::distance::fathom;
}
std::unique_ptr<sentence> dbk::parse(
const std::string & talker, const std::vector<std::string> & fields)
{
if (fields.size() != 6)
throw std::invalid_argument{"invalid number of fields in dbk::parse"};
std::unique_ptr<sentence> result = utils::make_unique<dbk>();
result->set_talker(talker);
dbk & detail = static_cast<dbk &>(*result);
read(fields[0], detail.depth_feet);
read(fields[1], detail.depth_feet_unit);
read(fields[2], detail.depth_meter);
read(fields[3], detail.depth_meter_unit);
read(fields[4], detail.depth_fathom);
read(fields[5], detail.depth_fathom_unit);
return result;
}
std::vector<std::string> dbk::get_data() const
{
return {to_string(depth_feet), to_string(depth_feet_unit), to_string(depth_meter),
to_string(depth_meter_unit), to_string(depth_fathom), to_string(depth_fathom_unit)};
}
}
}
| [
"mario.konrad@gmx.net"
] | mario.konrad@gmx.net |
c6be8641e4c16986a539123e925f1af4d6ef6b92 | c5cb356ccd642e707ba30148bee1590601f407d9 | /SINGLE_SOURCE_SHORTEST_PATH_DIJKSTRA_ALGO_WITH_ADJACENCY_LIST.cpp | cb3a3fa254f3b1a348c4f0194501ff9171b08f77 | [] | no_license | chaudhary19/CP-Algorithms-in-C_plus-plus | 90b4ae97752bc77f2df92d8c796c86c28b67532d | 0a4f7b5f6bf96bd7f92f81ce9d7b17ba27a29720 | refs/heads/master | 2023-08-29T21:04:06.424132 | 2021-10-22T06:33:58 | 2021-10-22T06:33:58 | 300,290,438 | 0 | 0 | null | 2020-10-01T13:31:57 | 2020-10-01T13:31:57 | null | UTF-8 | C++ | false | false | 4,409 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
// Given a weighted graph, can be directed or undirected but has to be strongly connected graph
// We have to find SINGLE SOURCE SHORTEST PATH
// That means, from one source node, we have to find shortest path to reach all other nodes
// We will use DIJKSTRA ALGORITHM to solve this
//
// Consider the following graph for this problem
//
// 5 3
// (1)-------(3)-------------(5)
// / /| |
// 4/ / | |
// / / | |
// / / | |
// (0) 5/ |4 |8
// \ / | |
// \ / | |
// 8\ / | |
// \ / 9 | 1 |
// (2)--------(4)-------------(6)
//
// We have taken 0 as our source node
// Try choosing different source nodes with same code
//
void traverse(vector <vector <pair <ll,ll>>> &v1)
{
cout<<"Adjacency Linked List Traversal with weights in square brackets []\n";
cout<<"Index Connections\n";
for(int i=0;i<v1.size();i++)
{
cout<<" ("<<i<<") -> ";
for(int j=0;j<v1[i].size();j++)
{
cout<<v1[i][j].first<<" ["<<v1[i][j].second<<"] ";
}
cout<<"\n";
}
}
void traverse(vector <pair <bool,ll>> &visited_array,ll source)
{
cout<<"From source node ["<<source<<"] to nodes\n";
for(int i=0;i<visited_array.size();i++)
{
cout<<"["<<i<<"] minimum cost is = "<<visited_array[i].second<<"\n";
}
}
void initialize(vector <pair <bool,ll>> &visited_array)
{
for(int i=0;i<visited_array.size();i++)
{
visited_array[i].first=false;
visited_array[i].second=INT_MAX;
}
}
ll find_smallest_node(vector <pair <bool,ll>> &visited_array)
{
ll cost=INT_MAX;
ll node=-1;
for(int i=0;i<visited_array.size();i++)
{
if(visited_array[i].first==false && visited_array[i].second <cost )
{
cost=visited_array[i].second;
node=i;
}
}
return node;
}
void dijkstra_algorithm(ll source,vector <vector <pair <ll,ll>>> &graph, vector <pair <bool,ll>> &visited_array)
{
visited_array[source].second=0;
for(int i=0;i<graph.size();i++)
{
ll smallest_node=find_smallest_node(visited_array);
visited_array[smallest_node].first=true;
ll cost=visited_array[smallest_node].second;
for(int j=0;j<graph[smallest_node].size();j++)
{
visited_array[graph[smallest_node][j].first].second=min(visited_array[graph[smallest_node][j].first].second ,( cost + graph[smallest_node][j].second) );
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
ll n,e;
n=7; // n are the nodes in graph
e=9; // e are the edges in graph
vector <vector <pair <ll,ll>>> graph(n);
// use the below code for providing your own input
//cin>>n>>e;
/*while(e--)
{
ll node1,node2,weight;
cin>>node1>>node2>>weight;
graph[node1].push_back(make_pair(node2,weight));
}
*/
graph[0].push_back(make_pair(1,4)); graph[1].push_back(make_pair(0,4));
graph[0].push_back(make_pair(2,8)); graph[2].push_back(make_pair(0,8));
graph[1].push_back(make_pair(3,5)); graph[3].push_back(make_pair(1,5));
graph[2].push_back(make_pair(3,5)); graph[3].push_back(make_pair(2,5));
graph[2].push_back(make_pair(4,9)); graph[4].push_back(make_pair(2,9));
graph[3].push_back(make_pair(4,4)); graph[4].push_back(make_pair(3,4));
graph[3].push_back(make_pair(5,3)); graph[5].push_back(make_pair(3,3));
graph[4].push_back(make_pair(6,1)); graph[6].push_back(make_pair(4,1));
graph[5].push_back(make_pair(6,8)); graph[6].push_back(make_pair(5,8));
traverse(graph);cout<<"\n\n";
ll source;
//cin>>source;
source=0;
vector <pair <bool,ll>> visited_array(n);
initialize(visited_array);
dijkstra_algorithm(source,graph,visited_array);
traverse(visited_array,source);
cout<<"\n\n";
return 0;
}
// code contributed by LAKSHYA SAXENA
| [
"noreply@github.com"
] | chaudhary19.noreply@github.com |
694c5831e299ef953015fbd3ccd0a1c618ea2d4b | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /tcm/src/v20210413/model/DescribeMeshListResponse.cpp | 0a4b30487da457b58d31547b00885f81ce875f74 | [
"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 | 5,290 | cpp | /*
* 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.
*/
#include <tencentcloud/tcm/v20210413/model/DescribeMeshListResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Tcm::V20210413::Model;
using namespace std;
DescribeMeshListResponse::DescribeMeshListResponse() :
m_meshListHasBeenSet(false),
m_totalHasBeenSet(false)
{
}
CoreInternalOutcome DescribeMeshListResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Core::Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("MeshList") && !rsp["MeshList"].IsNull())
{
if (!rsp["MeshList"].IsArray())
return CoreInternalOutcome(Core::Error("response `MeshList` is not array type"));
const rapidjson::Value &tmpValue = rsp["MeshList"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
Mesh item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_meshList.push_back(item);
}
m_meshListHasBeenSet = true;
}
if (rsp.HasMember("Total") && !rsp["Total"].IsNull())
{
if (!rsp["Total"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `Total` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_total = rsp["Total"].GetInt64();
m_totalHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
string DescribeMeshListResponse::ToJsonString() const
{
rapidjson::Document value;
value.SetObject();
rapidjson::Document::AllocatorType& allocator = value.GetAllocator();
if (m_meshListHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "MeshList";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_meshList.begin(); itr != m_meshList.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
if (m_totalHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Total";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_total, allocator);
}
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
value.Accept(writer);
return buffer.GetString();
}
vector<Mesh> DescribeMeshListResponse::GetMeshList() const
{
return m_meshList;
}
bool DescribeMeshListResponse::MeshListHasBeenSet() const
{
return m_meshListHasBeenSet;
}
int64_t DescribeMeshListResponse::GetTotal() const
{
return m_total;
}
bool DescribeMeshListResponse::TotalHasBeenSet() const
{
return m_totalHasBeenSet;
}
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
6016b92ee913279597800ffc95da274aedf112cf | 80553401d0d0b3db79be2f8db23f62c6cda7ffbd | /src/h/Plate.h | dea36e699faaaa4afdf545fdbe294e6b3ac4d300 | [] | no_license | fem-team/stappp | b3dc45adfde8ac6e89231e1a834e984a67ef7b14 | 974c37641b645bd982023c5b6b4e5aec6bc98391 | refs/heads/master | 2020-04-27T08:20:53.167506 | 2019-05-15T07:04:48 | 2019-05-15T07:04:48 | 174,167,671 | 0 | 1 | null | 2019-03-06T15:10:44 | 2019-03-06T15:10:44 | null | GB18030 | C++ | false | false | 1,742 | h | /*****************************************************************************/
/* STAP++ : A C++ FEM code sharing the same input data file with STAP90 */
/* Jinliang Kang promoted */
/* School of Aerospace Engineering, Tsinghua University */
/* */
/* Release 1.11, November 22, 2017 */
/* */
/* http://www.comdyn.cn/ */
/*****************************************************************************/
#pragma once
#include "Element.h"
using namespace std;
//! Plate element class
class CPlate : public CElement
{
public:
//! Constructor
CPlate();
//! Desconstructor
~CPlate();
//! Read element data from stream Input
virtual bool Read(ifstream& Input, unsigned int Ele, CMaterial* MaterialSets, CNode* NodeList);
//! Write element data to stream
virtual void Write(COutputter& output, unsigned int Ele);
//! Generate location matrix: the global equation number that corresponding to each DOF of the element!
// Caution: Equation number is numbered from 1 !
virtual void GenerateLocationMatrix();
//! Calculate element stiffness matrix
virtual void ElementStiffness(double* Matrix);
//! Calculate element stress
virtual void ElementStress(double* stress, double* Displacement, double* position);
//! Return the size of the element stiffness matrix (stored as an array column by column)
virtual unsigned int SizeOfStiffnessMatrix();
//Gravity 不用时定义成0
virtual double Gravity();
};
| [
"kang-jl16@mails.tsinghua.edu.cn"
] | kang-jl16@mails.tsinghua.edu.cn |
40965db993666ac69209bcad772054da1e49a31b | 49fa495d4ae473539b8326d2ae7b1d70d213c863 | /ComputerGraphics/curve.h | f1bdff634fe33286e16730e3b2a5cf8845eb3b4f | [] | no_license | akuxcw/ComputerGraphic | 70786a4fcc27c3d86a2225dc72dec57687aa1d27 | fde64f15360e075a64d8d2bbc9dcaadbf45102bc | refs/heads/master | 2020-12-02T22:46:46.302428 | 2017-07-04T06:14:13 | 2017-07-04T06:14:13 | 96,181,244 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,426 | h | #ifndef __CURVE_H_
#define __CURVE_H_
#include "graph.h"
#define NODENUM 20
class Curve : public Graph{
private:
public:
Curve(Point p) {
this->vertex.push_back(p);
type = TYPECURVE;
}
Curve() {
type = TYPECURVE;
}
void DrawP(int px, int py, int cx, int cy) {
DrawPoint(px, py);
if (px >= cx - 5 && px <= cx + 7 && py >= cy - 5 && py <= cy + 7) {
SetChoose(this);
}
}
void DrawControlP(int px, int py, int cx, int cy) {
if (px >= cx - 5 && px <= cx + 7 && py >= cy - 5 && py <= cy + 7) {
SetChoose(this);
}
if (ischosen) {
if (py > 500) return;
glColor3f(front.x, front.y, front.z);//画笔颜色
glPointSize(POINTSIZE-1);//画笔粗细
glBegin(GL_POINTS);
glVertex2i(px, py);//画点
glEnd();
}
}
void MovePoint(Point p) {
vertex.back() = p;
}
void AddPoint(Point p) {
vertex.push_back(p);
}
void Drawline(Point p1, Point p2, int cx, int cy) {
int x0 = p1.x, y0 = p1.y, x1 = p2.x, y1 = p2.y;
if (x0 == x1&&y0 == y1) {
DrawP(x0, y0, cx, cy);
}
int dx, dy, h, a, b, x, y, flag, t;
dx = abs(x1 - x0); dy = abs(y1 - y0);
if (x1 > x0) a = 1; else a = -1;
if (y1 > y0) b = 1; else b = -1;
x = x0; y = y0;
if (dx >= dy) {
flag = 0;
}
else {
t = dx;
dx = dy;
dy = t;
flag = 1;
}
h = 2 * dy - dx;
for (int i = 1; i <= dx; ++i) {
DrawP(x, y, cx, cy);
if (h >= 0) {
if (flag == 0) y = y + b;
else x = x + a;
h = h - 2 * dx;
}
if (flag == 0) x = x + a;
else y = y + b;
h = h + 2 * dy;
}
}
void DrawControlline(Point p1, Point p2, int cx, int cy) {
int x0 = p1.x, y0 = p1.y, x1 = p2.x, y1 = p2.y;
if (x0 == x1&&y0 == y1) {
DrawControlP(x0, y0, cx, cy);
}
int dx, dy, h, a, b, x, y, flag, t;
dx = abs(x1 - x0); dy = abs(y1 - y0);
if (x1 > x0) a = 1; else a = -1;
if (y1 > y0) b = 1; else b = -1;
x = x0; y = y0;
if (dx >= dy) {
flag = 0;
}
else {
t = dx;
dx = dy;
dy = t;
flag = 1;
}
h = 2 * dy - dx;
for (int i = 1; i <= dx; ++i) {
DrawControlP(x, y, cx, cy);
if (h >= 0) {
if (flag == 0) y = y + b;
else x = x + a;
h = h - 2 * dx;
}
if (flag == 0) x = x + a;
else y = y + b;
h = h + 2 * dy;
}
}
//画曲线
void Drawcurve(int cx, int cy) {
if (vertex.size() < 4) return;
float f1, f2, f3, f4;
float deltaT = 1.0 / NODENUM;
float T;
vector<Point> astring;
for (int num = 0; num < (int)vertex.size() - 3; num++) {
for (int i = 0; i <= NODENUM; i++) {
T = i * deltaT;
//四个基函数的值
f1 = (-T*T*T + 3 * T*T - 3 * T + 1) / 6.0;
f2 = (3 * T*T*T - 6 * T*T + 4) / 6.0;
f3 = (-3 * T*T*T + 3 * T*T + 3 * T + 1) / 6.0;
f4 = (T*T*T) / 6.0;
Point p(f1*vertex[num].x + f2*vertex[num + 1].x + f3*vertex[num + 2].x + f4*vertex[num + 3].x,
f1*vertex[num].y + f2*vertex[num + 1].y + f3*vertex[num + 2].y + f4*vertex[num + 3].y);
astring.push_back(p);
}
}
for (int i = 0; i < (int)astring.size() - 1; i++) {
Drawline(astring[i], astring[i + 1], cx, cy);
}
}
void DrawControlPolygon(int cx, int cy) {
glColor3f(1.0, 1.0, 1.0);//画笔颜色
glPointSize(1.0f);//画笔粗细
for (int i = 0; i < vertex.size() - 1; i++) {
DrawControlline(vertex[i], vertex[i + 1], cx, cy);
}
}
void Draw(int cx, int cy) {
if (vertex.size() == 0) return;
Drawcurve(cx, cy);
DrawControlPolygon(cx, cy);
AfterDraw();
glFlush();
}
};
#endif // !__CURVE_H_ | [
"陈鹏光"
] | 陈鹏光 |
09386e714c4702b134dfd17e1357f3aab2c958a9 | def01884ab644c607ae948f7323afe2bea15bff2 | /AUI.Core/src/AUI/Util/LZ.cpp | 87e9418784f92002a4d003b2fd788f5c60bfcd5a | [
"MIT"
] | permissive | lineCode/aui-1 | be2654156d6d36e4a31618b212d6f845c557c9ea | c2d82f8a040e3028adb2d63fd6b62ea1662413e7 | refs/heads/master | 2023-05-12T16:26:00.221734 | 2021-06-01T21:37:41 | 2021-06-01T21:37:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,617 | cpp | /**
* =====================================================================================================================
* Copyright (c) 2021 Alex2772
*
* 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.
* Original code located at https://github.com/Alex2772/aui
* =====================================================================================================================
*/
#include "LZ.h"
#include <stdexcept>
#include <string>
#include "AUI/Common/AByteBuffer.h"
#include <zlib.h>
void LZ::compress(const AByteBuffer& b, AByteBuffer& dst)
{
dst.reserve(dst.getSize() + b.getAvailable() + 0xff);
uLong len = b.getAvailable() + 0xff;
int r = compress2(reinterpret_cast<Bytef*>(const_cast<char*>(dst.getCurrentPosAddress())), &len,
reinterpret_cast<Bytef*>(const_cast<char*>(b.getCurrentPosAddress())), b.getAvailable(), Z_BEST_COMPRESSION);
if (r != Z_OK)
{
throw std::runtime_error(std::string("zlib compress error ") + std::to_string(r));
}
dst.setSize(dst.getSize() + len);
dst.setCurrentPos(dst.getSize());
}
void LZ::decompress(const AByteBuffer& b, AByteBuffer& dst)
{
for (size_t i = 4;; i++) {
dst.reserve(b.getAvailable() * i);
uLong len = dst.getReserved();
int r = uncompress(reinterpret_cast<Bytef*>(const_cast<char*>(dst.getCurrentPosAddress())), &len,
reinterpret_cast<Bytef*>(const_cast<char*>(b.getCurrentPosAddress())), b.getAvailable());
switch (r) {
case Z_BUF_ERROR:
continue;
case Z_OK:
dst.setSize(dst.getSize() + len);
return;
default:
throw AZLibException("zlib decompress error " + AString::number(r));
}
}
} | [
"alex2772sc@gmail.com"
] | alex2772sc@gmail.com |
375fd5f4b4f1733d083061ca5c5276864b252c4a | bf46ead26b9550c92c1f4cb81ff0bb553471ce8f | /src/hash.h | 014232b32d3572277d04a3e3fbadc4aeb9db74f9 | [
"MIT"
] | permissive | HondaisCoin/hondaiscoinmn | afeadfa0a34c6b5aafb2f5f89f7d1b36a77a2ee3 | 5b159940ee12ff8886ef21498dfddffb4ac76b1a | refs/heads/master | 2020-08-29T03:44:24.444315 | 2019-10-27T20:59:52 | 2019-10-27T20:59:52 | 217,913,441 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 14,611 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_HASH_H
#define BITCOIN_HASH_H
#include "crypto/ripemd160.h"
#include "crypto/sha256.h"
#include "prevector.h"
#include "serialize.h"
#include "uint256.h"
#include "version.h"
#include "crypto/sph_blake.h"
#include "crypto/sph_bmw.h"
#include "crypto/sph_groestl.h"
#include "crypto/sph_jh.h"
#include "crypto/sph_keccak.h"
#include "crypto/sph_skein.h"
#include "crypto/sph_luffa.h"
#include "crypto/sph_cubehash.h"
#include "crypto/sph_shavite.h"
#include "crypto/sph_simd.h"
#include "crypto/sph_echo.h"
#include <vector>
typedef uint256 ChainCode;
#ifdef GLOBALDEFINED
#define GLOBAL
#else
#define GLOBAL extern
#endif
GLOBAL sph_blake512_context z_blake;
GLOBAL sph_bmw512_context z_bmw;
GLOBAL sph_groestl512_context z_groestl;
GLOBAL sph_jh512_context z_jh;
GLOBAL sph_keccak512_context z_keccak;
GLOBAL sph_skein512_context z_skein;
GLOBAL sph_luffa512_context z_luffa;
GLOBAL sph_cubehash512_context z_cubehash;
GLOBAL sph_shavite512_context z_shavite;
GLOBAL sph_simd512_context z_simd;
GLOBAL sph_echo512_context z_echo;
#define fillz() do { \
sph_blake512_init(&z_blake); \
sph_bmw512_init(&z_bmw); \
sph_groestl512_init(&z_groestl); \
sph_jh512_init(&z_jh); \
sph_keccak512_init(&z_keccak); \
sph_skein512_init(&z_skein); \
sph_luffa512_init(&z_luffa); \
sph_cubehash512_init(&z_cubehash); \
sph_shavite512_init(&z_shavite); \
sph_simd512_init(&z_simd); \
sph_echo512_init(&z_echo); \
} while (0)
#define ZBLAKE (memcpy(&ctx_blake, &z_blake, sizeof(z_blake)))
#define ZBMW (memcpy(&ctx_bmw, &z_bmw, sizeof(z_bmw)))
#define ZGROESTL (memcpy(&ctx_groestl, &z_groestl, sizeof(z_groestl)))
#define ZJH (memcpy(&ctx_jh, &z_jh, sizeof(z_jh)))
#define ZKECCAK (memcpy(&ctx_keccak, &z_keccak, sizeof(z_keccak)))
#define ZSKEIN (memcpy(&ctx_skein, &z_skein, sizeof(z_skein)))
/* ----------- Bitcoin Hash ------------------------------------------------- */
/** A hasher class for Bitcoin's 256-bit hash (double SHA-256). */
class CHash256 {
private:
CSHA256 sha;
public:
static const size_t OUTPUT_SIZE = CSHA256::OUTPUT_SIZE;
void Finalize(unsigned char hash[OUTPUT_SIZE]) {
unsigned char buf[sha.OUTPUT_SIZE];
sha.Finalize(buf);
sha.Reset().Write(buf, sha.OUTPUT_SIZE).Finalize(hash);
}
CHash256& Write(const unsigned char *data, size_t len) {
sha.Write(data, len);
return *this;
}
CHash256& Reset() {
sha.Reset();
return *this;
}
};
/** A hasher class for Bitcoin's 160-bit hash (SHA-256 + RIPEMD-160). */
class CHash160 {
private:
CSHA256 sha;
public:
static const size_t OUTPUT_SIZE = CRIPEMD160::OUTPUT_SIZE;
void Finalize(unsigned char hash[OUTPUT_SIZE]) {
unsigned char buf[sha.OUTPUT_SIZE];
sha.Finalize(buf);
CRIPEMD160().Write(buf, sha.OUTPUT_SIZE).Finalize(hash);
}
CHash160& Write(const unsigned char *data, size_t len) {
sha.Write(data, len);
return *this;
}
CHash160& Reset() {
sha.Reset();
return *this;
}
};
/** Compute the 256-bit hash of an object. */
template<typename T1>
inline uint256 Hash(const T1 pbegin, const T1 pend)
{
static const unsigned char pblank[1] = {};
uint256 result;
CHash256().Write(pbegin == pend ? pblank : (const unsigned char*)&pbegin[0], (pend - pbegin) * sizeof(pbegin[0]))
.Finalize((unsigned char*)&result);
return result;
}
/** Compute the 256-bit hash of the concatenation of two objects. */
template<typename T1, typename T2>
inline uint256 Hash(const T1 p1begin, const T1 p1end,
const T2 p2begin, const T2 p2end) {
static const unsigned char pblank[1] = {};
uint256 result;
CHash256().Write(p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0]))
.Write(p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0]))
.Finalize((unsigned char*)&result);
return result;
}
/** Compute the 256-bit hash of the concatenation of three objects. */
template<typename T1, typename T2, typename T3>
inline uint256 Hash(const T1 p1begin, const T1 p1end,
const T2 p2begin, const T2 p2end,
const T3 p3begin, const T3 p3end) {
static const unsigned char pblank[1] = {};
uint256 result;
CHash256().Write(p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0]))
.Write(p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0]))
.Write(p3begin == p3end ? pblank : (const unsigned char*)&p3begin[0], (p3end - p3begin) * sizeof(p3begin[0]))
.Finalize((unsigned char*)&result);
return result;
}
/** Compute the 256-bit hash of the concatenation of three objects. */
template<typename T1, typename T2, typename T3, typename T4>
inline uint256 Hash(const T1 p1begin, const T1 p1end,
const T2 p2begin, const T2 p2end,
const T3 p3begin, const T3 p3end,
const T4 p4begin, const T4 p4end) {
static const unsigned char pblank[1] = {};
uint256 result;
CHash256().Write(p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0]))
.Write(p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0]))
.Write(p3begin == p3end ? pblank : (const unsigned char*)&p3begin[0], (p3end - p3begin) * sizeof(p3begin[0]))
.Write(p4begin == p4end ? pblank : (const unsigned char*)&p4begin[0], (p4end - p4begin) * sizeof(p4begin[0]))
.Finalize((unsigned char*)&result);
return result;
}
/** Compute the 256-bit hash of the concatenation of three objects. */
template<typename T1, typename T2, typename T3, typename T4, typename T5>
inline uint256 Hash(const T1 p1begin, const T1 p1end,
const T2 p2begin, const T2 p2end,
const T3 p3begin, const T3 p3end,
const T4 p4begin, const T4 p4end,
const T5 p5begin, const T5 p5end) {
static const unsigned char pblank[1] = {};
uint256 result;
CHash256().Write(p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0]))
.Write(p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0]))
.Write(p3begin == p3end ? pblank : (const unsigned char*)&p3begin[0], (p3end - p3begin) * sizeof(p3begin[0]))
.Write(p4begin == p4end ? pblank : (const unsigned char*)&p4begin[0], (p4end - p4begin) * sizeof(p4begin[0]))
.Write(p5begin == p5end ? pblank : (const unsigned char*)&p5begin[0], (p5end - p5begin) * sizeof(p5begin[0]))
.Finalize((unsigned char*)&result);
return result;
}
/** Compute the 256-bit hash of the concatenation of three objects. */
template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
inline uint256 Hash(const T1 p1begin, const T1 p1end,
const T2 p2begin, const T2 p2end,
const T3 p3begin, const T3 p3end,
const T4 p4begin, const T4 p4end,
const T5 p5begin, const T5 p5end,
const T6 p6begin, const T6 p6end) {
static const unsigned char pblank[1] = {};
uint256 result;
CHash256().Write(p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0]))
.Write(p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0]))
.Write(p3begin == p3end ? pblank : (const unsigned char*)&p3begin[0], (p3end - p3begin) * sizeof(p3begin[0]))
.Write(p4begin == p4end ? pblank : (const unsigned char*)&p4begin[0], (p4end - p4begin) * sizeof(p4begin[0]))
.Write(p5begin == p5end ? pblank : (const unsigned char*)&p5begin[0], (p5end - p5begin) * sizeof(p5begin[0]))
.Write(p6begin == p6end ? pblank : (const unsigned char*)&p6begin[0], (p6end - p6begin) * sizeof(p6begin[0]))
.Finalize((unsigned char*)&result);
return result;
}
/** Compute the 160-bit hash an object. */
template<typename T1>
inline uint160 Hash160(const T1 pbegin, const T1 pend)
{
static unsigned char pblank[1] = {};
uint160 result;
CHash160().Write(pbegin == pend ? pblank : (const unsigned char*)&pbegin[0], (pend - pbegin) * sizeof(pbegin[0]))
.Finalize((unsigned char*)&result);
return result;
}
/** Compute the 160-bit hash of a vector. */
inline uint160 Hash160(const std::vector<unsigned char>& vch)
{
return Hash160(vch.begin(), vch.end());
}
/** Compute the 160-bit hash of a vector. */
template<unsigned int N>
inline uint160 Hash160(const prevector<N, unsigned char>& vch)
{
return Hash160(vch.begin(), vch.end());
}
/** A writer stream (for serialization) that computes a 256-bit hash. */
class CHashWriter
{
private:
CHash256 ctx;
public:
int nType;
int nVersion;
CHashWriter(int nTypeIn, int nVersionIn) : nType(nTypeIn), nVersion(nVersionIn) {}
CHashWriter& write(const char *pch, size_t size) {
ctx.Write((const unsigned char*)pch, size);
return (*this);
}
// invalidates the object
uint256 GetHash() {
uint256 result;
ctx.Finalize((unsigned char*)&result);
return result;
}
template<typename T>
CHashWriter& operator<<(const T& obj) {
// Serialize to this stream
::Serialize(*this, obj, nType, nVersion);
return (*this);
}
};
/** Reads data from an underlying stream, while hashing the read data. */
template<typename Source>
class CHashVerifier : public CHashWriter
{
private:
Source* source;
public:
CHashVerifier(Source* source_) : CHashWriter(source_->GetType(), source_->GetVersion()), source(source_) {}
void read(char* pch, size_t nSize)
{
source->read(pch, nSize);
this->write(pch, nSize);
}
void ignore(size_t nSize)
{
char data[1024];
while (nSize > 0) {
size_t now = std::min<size_t>(nSize, 1024);
read(data, now);
nSize -= now;
}
}
template<typename T>
CHashVerifier<Source>& operator>>(T& obj)
{
// Unserialize from this stream
::Unserialize(*this, obj, nType, nVersion);
return (*this);
}
};
/** Compute the 256-bit hash of an object's serialization. */
template<typename T>
uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
{
CHashWriter ss(nType, nVersion);
ss << obj;
return ss.GetHash();
}
unsigned int MurmurHash3(unsigned int nHashSeed, const std::vector<unsigned char>& vDataToHash);
void BIP32Hash(const ChainCode &chainCode, unsigned int nChild, unsigned char header, const unsigned char data[32], unsigned char output[64]);
/** SipHash-2-4, using a uint64_t-based (rather than byte-based) interface */
class CSipHasher
{
private:
uint64_t v[4];
int count;
public:
CSipHasher(uint64_t k0, uint64_t k1);
CSipHasher& Write(uint64_t data);
uint64_t Finalize() const;
};
uint64_t SipHashUint256(uint64_t k0, uint64_t k1, const uint256& val);
uint64_t SipHashUint256Extra(uint64_t k0, uint64_t k1, const uint256& val, uint32_t extra);
/* ----------- HondaisCoinMN Hash ------------------------------------------------ */
template<typename T1>
inline uint256 HashX11(const T1 pbegin, const T1 pend)
{
sph_blake512_context ctx_blake;
sph_bmw512_context ctx_bmw;
sph_groestl512_context ctx_groestl;
sph_jh512_context ctx_jh;
sph_keccak512_context ctx_keccak;
sph_skein512_context ctx_skein;
sph_luffa512_context ctx_luffa;
sph_cubehash512_context ctx_cubehash;
sph_shavite512_context ctx_shavite;
sph_simd512_context ctx_simd;
sph_echo512_context ctx_echo;
static unsigned char pblank[1];
uint512 hash[11];
sph_blake512_init(&ctx_blake);
sph_blake512 (&ctx_blake, (pbegin == pend ? pblank : static_cast<const void*>(&pbegin[0])), (pend - pbegin) * sizeof(pbegin[0]));
sph_blake512_close(&ctx_blake, static_cast<void*>(&hash[0]));
sph_bmw512_init(&ctx_bmw);
sph_bmw512 (&ctx_bmw, static_cast<const void*>(&hash[0]), 64);
sph_bmw512_close(&ctx_bmw, static_cast<void*>(&hash[1]));
sph_groestl512_init(&ctx_groestl);
sph_groestl512 (&ctx_groestl, static_cast<const void*>(&hash[1]), 64);
sph_groestl512_close(&ctx_groestl, static_cast<void*>(&hash[2]));
sph_skein512_init(&ctx_skein);
sph_skein512 (&ctx_skein, static_cast<const void*>(&hash[2]), 64);
sph_skein512_close(&ctx_skein, static_cast<void*>(&hash[3]));
sph_jh512_init(&ctx_jh);
sph_jh512 (&ctx_jh, static_cast<const void*>(&hash[3]), 64);
sph_jh512_close(&ctx_jh, static_cast<void*>(&hash[4]));
sph_keccak512_init(&ctx_keccak);
sph_keccak512 (&ctx_keccak, static_cast<const void*>(&hash[4]), 64);
sph_keccak512_close(&ctx_keccak, static_cast<void*>(&hash[5]));
sph_luffa512_init(&ctx_luffa);
sph_luffa512 (&ctx_luffa, static_cast<void*>(&hash[5]), 64);
sph_luffa512_close(&ctx_luffa, static_cast<void*>(&hash[6]));
sph_cubehash512_init(&ctx_cubehash);
sph_cubehash512 (&ctx_cubehash, static_cast<const void*>(&hash[6]), 64);
sph_cubehash512_close(&ctx_cubehash, static_cast<void*>(&hash[7]));
sph_shavite512_init(&ctx_shavite);
sph_shavite512(&ctx_shavite, static_cast<const void*>(&hash[7]), 64);
sph_shavite512_close(&ctx_shavite, static_cast<void*>(&hash[8]));
sph_simd512_init(&ctx_simd);
sph_simd512 (&ctx_simd, static_cast<const void*>(&hash[8]), 64);
sph_simd512_close(&ctx_simd, static_cast<void*>(&hash[9]));
sph_echo512_init(&ctx_echo);
sph_echo512 (&ctx_echo, static_cast<const void*>(&hash[9]), 64);
sph_echo512_close(&ctx_echo, static_cast<void*>(&hash[10]));
return hash[10].trim256();
}
#endif // BITCOIN_HASH_H
| [
"you@example.com"
] | you@example.com |
071a3f98d5100ffca8f6ccc4f18457a167620066 | d32a86b54095bbf7886350932d5173493a1c8dd3 | /DegreeRadianJ_Branson.cpp | a1324ca6a0ce28422c3d1e4572f8085926f76699 | [] | no_license | Jbranson85/Cplusplus-ERG-126 | 01ba685dd35683f35816d88a7b7ba097ed6f8f67 | 254da0479516726bebddbf9dcdc8fa00a3ef4f3f | refs/heads/master | 2020-03-15T22:22:34.580121 | 2018-05-06T20:13:22 | 2018-05-06T20:13:22 | 132,371,969 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 320 | cpp | #include <iostream>
//Jonathan Branson
using namespace std;
int main()
{
cout << "Degrees Radians\n"
<< "0 0.0000\n"
<< "90 1.5708\n"
<< "180 3.1416\n"
<< "270 4.7124\n"
<< "360 6.2832\n";
return 0;
}
| [
"noreply@github.com"
] | Jbranson85.noreply@github.com |
e908a0183bdd999a36d3ab41e052eb1efb2ebf2c | 634120df190b6262fccf699ac02538360fd9012d | /Develop/Game/XCursorSmartReleaser.cpp | 266cfef6fdda54686f6b4aa984f95444f13d18da | [] | no_license | ktj007/Raiderz_Public | c906830cca5c644be384e68da205ee8abeb31369 | a71421614ef5711740d154c961cbb3ba2a03f266 | refs/heads/master | 2021-06-08T03:37:10.065320 | 2016-11-28T07:50:57 | 2016-11-28T07:50:57 | 74,959,309 | 6 | 4 | null | 2016-11-28T09:53:49 | 2016-11-28T09:53:49 | null | UHC | C++ | false | false | 2,211 | cpp | #include "stdafx.h"
#include "XCursorSmartReleaser.h"
#include "XUISystem.h"
#include "XController.h"
#include "XMyPlayer.h"
void XCursorSmartReleaser::Update( float fDelta, XCursor* pCursor, XUISystem* pUISystem, XController* pController )
{
if (IsUpdateEnabled(pCursor, pUISystem, pController) == false)
{
m_fElapsedTime = 0.0f;
return;
}
m_fElapsedTime += fDelta;
if (m_fElapsedTime >= CURSOR_SMART_RELEASE_TIME)
{
DoIt(pCursor, pUISystem);
m_fElapsedTime = 0.0f;
}
}
bool XCursorSmartReleaser::IsUpdateEnabled(XCursor* pCursor, XUISystem* pUISystem, XController* pController)
{
if (pCursor->IsVisible() == false) return false;
/*if (pUISystem->IsFocusMainInput() == false) return false;*/
// ui 창이 있으면 발동하지 않는다.
//if (pUISystem->GetWindowShowManager())
//{
// if (pUISystem->GetWindowShowManager()->IsAllHided() == false) return false;
//}
// 채팅창 활성화 체크
if (pUISystem->IsChattingBoxFocused() == true)
{
return false;
}
// 콘솔창 활성화 체크
if (pUISystem->IsConsoleVisible() == true)
{
return false;
}
// 마우스 커서 토글 키 누르고 있는지 체크
if (pUISystem->IsMouseCursorToggleKeyDown() == true)
{
return false;
}
if (gvar.Game.pMyPlayer)
{
if (gvar.Game.pMyPlayer->IsDead()) return false;
}
// 이동 키 체크
if (pController == NULL) return false;
bool bMovingKeyPressed = false;
if (pController->IsVirtualKeyPressed(VKEY_FORWARD)) bMovingKeyPressed = true;
else if (pController->IsVirtualKeyPressed(VKEY_BACKWARD)) bMovingKeyPressed = true;
else if (pController->IsVirtualKeyPressed(VKEY_LEFT)) bMovingKeyPressed = true;
else if (pController->IsVirtualKeyPressed(VKEY_RIGHT)) bMovingKeyPressed = true;
if (bMovingKeyPressed == false) return false;
return true;
}
void XCursorSmartReleaser::DoIt(XCursor* pCursor, XUISystem* pUISystem)
{
if ( global.script) global.script->GetGlueGameEvent().OnGameEvent( "UI", "HIDE_ALL_WINDOW");
/*
if (pUISystem->GetWindowShowManager())
{
if (pUISystem->GetWindowShowManager()->IsAllHided() == false)
{
pUISystem->GetWindowShowManager()->HideAll();
}
}
*/
pCursor->Show(false);
// pUISystem->SetFocusMainInput();
} | [
"espause0703@gmail.com"
] | espause0703@gmail.com |
9422920e66af19312822bdfa978972d1fe9dd083 | 4d2be893f0f347af1d42bb2e9e5d13a3bceff5ca | /Febuary Leetcode challenge/Week 1/Week 2/Number of Steps to Reduce a Number to Zero.cpp | dff1b6d99947cff32e2284de25d22792bb95a5cb | [] | no_license | Ishankochar99/Leetcode | 66019b30f499c5d9bd84edf27870c3fa332cd39b | cb33c4dde3f3091e3d9917cc37fc9a25d20b6a0a | refs/heads/master | 2023-05-12T00:14:51.882383 | 2021-06-03T08:12:21 | 2021-06-03T08:12:21 | 292,915,801 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 315 | cpp | class Solution {
public:
int numberOfSteps (int num) {
int sum=0;
while(num!=0){
if(num%2==0){
num=num/2;
sum++;
}else{
num=num-1;
sum++;
}
}
return sum;
}
};
| [
"noreply@github.com"
] | Ishankochar99.noreply@github.com |
ae99285a168603f7c095e3eaa64a5558e431cc02 | 57b4fe01eb4d7a8fb40c476a82ef5980a0f6690d | /20_point.cpp | 423b4bad72fdd118e411c9b3e672914c48a70f2e | [] | no_license | RazielSun/glut-tutorials | f82bf211d0d19bcd148d38db29ec95ebc47645e7 | 93ce2c7c964d51f5f58c6896cee46fcf2a135a67 | refs/heads/master | 2020-02-26T15:22:11.948768 | 2017-01-09T19:41:30 | 2017-01-09T19:41:30 | 70,258,209 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,542 | cpp |
#include <assert.h>
#include <math.h>
#include "utils/util_3d.h"
#include "utils/util_camera.h"
#include "utils/util_pipeline.h"
#include "utils/util_texture.h"
#include "utils/util_light.h"
#include <iostream>
#include <GL/glew.h>
#include <SDL2/SDL.h>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#define WINDOW_WIDTH 1024
#define WINDOW_HEIGHT 768
#define PLANE_WIDTH 5.0f
#define PLANE_HEIGHT 5.0f
#define MAX_POINT_LIGHTS 2
const char* WINDOW_NAME = "Tutorial 20";
GLuint ibo;
GLuint vbo;
DirectionLight directionLight;
PointLight pointLights[MAX_POINT_LIGHTS];
Camera *camera = NULL;
Texture *texture = NULL;
LightProgram *program = NULL;
static std::string vertex_shader = ""
"attribute vec3 position;"
"attribute vec2 texCoord;"
"attribute vec3 normal;"
"uniform mat4 WVP;"
"uniform mat4 world;"
"varying vec2 uvCoord;"
"varying vec3 normal0;"
"varying vec3 worldPos0;"
"void main()"
"{"
" gl_Position = WVP * vec4(position, 1.0);"
" uvCoord = texCoord;"
" normal0 = (world * vec4(normal, 0.0)).xyz;"
" worldPos0 = (world * vec4(position, 1.0)).xyz;"
"}";
static std::string fragment_shader = ""
"const int MAX_POINT_LIGHTS = 2;"
"struct BaseLight"
"{"
" vec3 Color;"
" float AmbientIntensity;"
" float DiffuseIntensity;"
"};"
"struct DirectionalLight"
"{"
" BaseLight Base;"
" vec3 Direction;"
"};"
"struct Attenuation"
"{"
" float Constant;"
" float Linear;"
" float Exp;"
"};"
"struct PointLight"
"{"
" BaseLight Base;"
" vec3 Position;"
" Attenuation Atten;"
"};"
"uniform DirectionalLight directionLight;"
"uniform PointLight pointLight[MAX_POINT_LIGHTS];"
"uniform int numPointLights;"
"uniform sampler2D sampler;"
"varying vec2 uvCoord;"
"varying vec3 normal0;"
"varying vec3 worldPos0;"
"vec4 CalcLightInternal(BaseLight Light, vec3 LightDirection, vec3 Normal)"
"{"
" vec4 AmbientColor = vec4(Light.Color * Light.AmbientIntensity, 1.0);"
" float DiffuseFactor = dot(Normal, -LightDirection);"
" vec4 DiffuseColor = vec4(0, 0, 0, 0);"
" if (DiffuseFactor > 0.0) {"
" DiffuseColor = vec4(Light.Color * Light.DiffuseIntensity * DiffuseFactor, 1.0);"
" }"
" return (AmbientColor + DiffuseColor);"
"}"
"vec4 CalcDirectionalLight(vec3 Normal)"
"{"
" return CalcLightInternal(directionLight.Base, directionLight.Direction, Normal);"
"}"
"vec4 CalcPointLight(int Index, vec3 Normal)"
"{"
" vec3 LightDirection = worldPos0 - pointLight[Index].Position;"
" float Distance = length(LightDirection);"
" LightDirection = normalize(LightDirection);"
" vec4 Color = CalcLightInternal(pointLight[Index].Base, LightDirection, Normal);"
" float Atn = pointLight[Index].Atten.Constant + pointLight[Index].Atten.Linear * Distance + pointLight[Index].Atten.Exp * Distance * Distance;"
" return Color / Atn;"
"}"
"void main()"
"{"
" vec3 Normal = normalize(normal0);"
" vec4 TotalLight = CalcDirectionalLight(Normal);"
" for (int i = 0; i < numPointLights; i++) {"
" TotalLight += CalcPointLight(i, Normal);"
" }"
" gl_FragColor = texture2D(sampler, uvCoord) * TotalLight;"
"}";
void render ()
{
camera->OnRender();
glClear(GL_COLOR_BUFFER_BIT);
static float scale = 0.0f;
scale += 0.01f;
Pipeline p;
float Z = 3.0f;
pointLights[0].Position = Vector3f(2.0f*sinf(scale), 1.0f, Z+2.0f*cosf(scale));
pointLights[1].Position = Vector3f(-2.0f*sinf(scale), 1.0f, Z+2.0f*cosf(scale));
p.Pos(0.0f, 0.0f, Z);
p.SetPerspectiveProj(60.0f, WINDOW_WIDTH, WINDOW_HEIGHT, 1.0f, 100.0f);
p.SetCamera(*camera);
program->SetWVP(p.GetTrans());
program->SetWorld(p.GetWorldTrans());
program->SetDirectionLight(directionLight);
program->SetPointLights(2, pointLights);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)12);
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)20);
glEnableVertexAttribArray(2);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
texture->Bind(GL_TEXTURE0);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
}
void createContext ()
{
unsigned int indices[] = { 0, 1, 2,
0, 2, 3 };
unsigned int indexCount = ARRAY_SIZE_IN_ELEMENTS(indices);
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
Vector3f Normal(0.0f, 1.0f, 0.0f);
Vertex vertices[4] = { Vertex(Vector3f(-PLANE_WIDTH, 0.0f, -PLANE_HEIGHT), Vector2f(0.0f, 0.0f), Normal),
Vertex(Vector3f(-PLANE_WIDTH, 0.0f, PLANE_HEIGHT), Vector2f(0.0f, 1.0f), Normal),
Vertex(Vector3f(PLANE_WIDTH, 0.0f, PLANE_HEIGHT), Vector2f(1.0f, 1.0f), Normal),
Vertex(Vector3f(PLANE_WIDTH, 0.0f, -PLANE_HEIGHT), Vector2f(1.0f, 0.0f), Normal) };
unsigned int vertexCount = ARRAY_SIZE_IN_ELEMENTS(vertices);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
}
void createShaderProgram ()
{
program = new LightProgram();
if (!program->Init()) {
exit(1);
}
program->AddShader(GL_VERTEX_SHADER, vertex_shader.c_str());
program->AddShader(GL_FRAGMENT_SHADER, fragment_shader.c_str());
program->Compile();
program->Link();
glUniform1i(program->GetUniformLocation("sampler"), 0);
}
SDL_Window *window;
void init()
{
if ( SDL_Init(SDL_INIT_VIDEO) < 0 )
{
fprintf(stderr, "Unable to init SDL, error: '%s'\n", SDL_GetError());
exit(1);
}
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
window = SDL_CreateWindow(WINDOW_NAME, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
SDL_GLContext glcontext = SDL_GL_CreateContext(window);
if (window == NULL)
{
fprintf(stderr, "Unable to create SDL Context");
exit(1);
}
glewExperimental = GL_TRUE;
GLenum res = glewInit();
if (res != GLEW_OK)
{
fprintf(stderr, "Error: '%s'\n", glewGetErrorString(res));
exit(1);
}
}
void addPointIntensity(float delta)
{
for (int i = 0; i < MAX_POINT_LIGHTS; i++)
{
pointLights[i].AmbientIntensity += delta;
pointLights[i].DiffuseIntensity += delta;
}
}
int main (int argc, char *argv[])
{
init();
camera = new Camera(WINDOW_WIDTH, WINDOW_HEIGHT);
camera->SetPos(0.0f, -2.0f, 2.0f);
camera->LookAt(0.0f, 0.0f, 3.0f);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glFrontFace(GL_CW);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
directionLight.Color = Vector3f(1.0f, 1.0f, 1.0f);
directionLight.AmbientIntensity = 0.1f;
directionLight.DiffuseIntensity = 0.1f;
directionLight.Direction = Vector3f(1.0f, -1.0f, 0.0f);
pointLights[0].Color = Vector3f(1.0f, 0.5f, 0.0f);
pointLights[0].AmbientIntensity = 0.1f;
pointLights[0].DiffuseIntensity = 0.1f;
pointLights[0].Position = Vector3f(3.0f, 1.0f, 3.0f);
pointLights[0].Attenuation.Linear = 0.1f;
pointLights[1].Color = Vector3f(0.0f, 0.5f, 1.0f);
pointLights[1].AmbientIntensity = 0.1f;
pointLights[1].DiffuseIntensity = 0.1f;
pointLights[1].Position = Vector3f(-3.0f, 1.0f, 3.0f);
pointLights[1].Attenuation.Linear = 0.1f;
createContext();
createShaderProgram();
texture = new Texture(GL_TEXTURE_2D, "content/uvLayoutGrid.jpg");
if (!texture->Load()) {
return 1;
}
bool running = true;
while(running)
{
SDL_Event event;
while ( SDL_PollEvent(&event) )
{
switch(event.type)
{
case SDL_QUIT:
running = false;
break;
case SDL_MOUSEMOTION:
camera->OnMouse(event.motion.x, event.motion.y);
break;
case SDL_KEYDOWN:
{
camera->OnKeyboard(event.key.keysym.sym);
switch(event.key.keysym.sym)
{
case SDLK_q:
directionLight.AmbientIntensity += 0.1f;
break;
case SDLK_w:
directionLight.AmbientIntensity -= 0.1f;
break;
case SDLK_a:
addPointIntensity(0.1f);
break;
case SDLK_s:
addPointIntensity(-0.1f);
break;
case SDLK_ESCAPE:
running = false;
break;
}
}
break;
}
}
render();
SDL_GL_SwapWindow(window);
}
SDL_Quit();
return 0;
}
| [
"razielsun@gmail.com"
] | razielsun@gmail.com |
d0176ba96f6b7a70a7a427f3d3a1fd48f17cf219 | 57fa84e55f5944a435ec2510bfc9a64532ab9d92 | /src/qt/optionsdialog.h | fedfe5baf179b7e4507be9b654ef741dbb6a6896 | [
"MIT"
] | permissive | barrystyle/deftchain-0.17 | 133d3bffec152738166a01bd14d6d2a26962432a | d93b9307d8919117b10129a2828cb98833a1c9a1 | refs/heads/master | 2020-04-17T01:26:28.232962 | 2018-09-30T12:18:20 | 2018-09-30T12:20:27 | 166,091,970 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,798 | h | // Copyright (c) 2011-2018 The Bitcoin Core developers
// Copyright (c) 2018 The Deftchain developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DEFTCHAIN_QT_OPTIONSDIALOG_H
#define DEFTCHAIN_QT_OPTIONSDIALOG_H
#include <QDialog>
#include <QValidator>
class OptionsModel;
class QValidatedLineEdit;
QT_BEGIN_NAMESPACE
class QDataWidgetMapper;
QT_END_NAMESPACE
namespace Ui {
class OptionsDialog;
}
/** Proxy address widget validator, checks for a valid proxy address.
*/
class ProxyAddressValidator : public QValidator
{
Q_OBJECT
public:
explicit ProxyAddressValidator(QObject *parent);
State validate(QString &input, int &pos) const;
};
/** Preferences dialog. */
class OptionsDialog : public QDialog
{
Q_OBJECT
public:
explicit OptionsDialog(QWidget *parent, bool enableWallet);
~OptionsDialog();
void setModel(OptionsModel *model);
void setMapper();
private Q_SLOTS:
/* set OK button state (enabled / disabled) */
void setOkButtonState(bool fState);
void on_resetButton_clicked();
void on_openBitcoinConfButton_clicked();
void on_okButton_clicked();
void on_cancelButton_clicked();
void on_hideTrayIcon_stateChanged(int fState);
void togglePruneWarning(bool enabled);
void showRestartWarning(bool fPersistent = false);
void clearStatusLabel();
void updateProxyValidationState();
/* query the networks, for which the default proxy is used */
void updateDefaultProxyNets();
Q_SIGNALS:
void proxyIpChecks(QValidatedLineEdit *pUiProxyIp, int nProxyPort);
private:
Ui::OptionsDialog *ui;
OptionsModel *model;
QDataWidgetMapper *mapper;
};
#endif // DEFTCHAIN_QT_OPTIONSDIALOG_H
| [
"barrystyle@westnet.com.au"
] | barrystyle@westnet.com.au |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.