blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
c75019f21661bc624e73bbe764e03525d3bc61b7 | C++ | dillonhuff/TinyCPU | /alu_main.cpp | UTF-8 | 1,512 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <ctime>
#include <cstdlib>
#include "Valu.h"
#include "verilated.h"
using namespace std;
void test_and_out(int argc, char** argv) {
Verilated::commandArgs(argc, argv);
Valu* top = new Valu;
top->eval();
top->op_select = 1;
top->in0 = 1;
top->in1 = 0;
top->eval();
assert(top->out == 0);
top->in1 = 1;
top->eval();
assert(top->out == 1);
top->final();
}
void test_or_out(int argc, char** argv) {
Verilated::commandArgs(argc, argv);
Valu* top = new Valu;
top->eval();
top->eval();
top->in0 = 1;
top->in1 = 0;
top->eval();
assert(top->out == 1);
top->in0 = 0;
top->in1 = 0;
top->eval();
assert(top->out == 0);
top->final();
}
void test_xor_out(int argc, char** argv) {
Verilated::commandArgs(argc, argv);
Valu* top = new Valu;
top->in0 = 1;
top->in1 = 0;
top->op_select = 2;
top->eval();
assert(top->out == 1);
top->in0 = 1;
top->in1 = 1;
top->eval();
assert(top->out == 0);
top->final();
}
void test_neq_out(int argc, char** argv) {
Verilated::commandArgs(argc, argv);
Valu* top = new Valu;
top->in0 = 1;
top->in1 = 0;
top->op_select = 6;
top->eval();
assert(top->out == 1);
top->in0 = 101;
top->in1 = 101;
top->eval();
assert(top->out == 0);
top->final();
}
int main(int argc, char** argv) {
test_and_out(argc, argv);
test_or_out(argc, argv);
test_xor_out(argc, argv);
test_neq_out(argc, argv);
cout << "$$$$ ALU tests pass" << endl;
}
| true |
12ddfcc73d1af683157c1128b01bcddef951bb36 | C++ | sravankr96/Authored-Problems | /surveyor/ipgen.cpp | UTF-8 | 299 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
ofstream ipfile;
int n = 0,t = 9;
char c[20];
while(t--)
{
n+=100;
cin>>c;
ipfile.open(c);
ipfile<<n<<endl;
for(int i=0;i<n;i++)
ipfile<<rand()%n<<endl;
ipfile.close();
}
return 0;
}
| true |
0c85264f222dd4faf2326abf0224d715070fba0e | C++ | Crust3d/C867-Class-Project | /softwareStudent.cpp | UTF-8 | 653 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include "softwareStudent.h"
#include "degree.h"
SoftwareStudent::SoftwareStudent() :Student()
{
major = Degree::SOFTWARE;
}
SoftwareStudent::SoftwareStudent(
string studentID,
string firstName,
string lastName,
string email,
int age,
double numDays[],
Degree degreeProgram) : Student(studentID, firstName, lastName, email, age, numDays)
{
major = SOFTWARE;
}
Degree SoftwareStudent::getDegreeProgram()
{
return SOFTWARE;
}
void SoftwareStudent::print()
{
this->Student::print();
std::cout << "SOFTWARE" << std::endl;
}
SoftwareStudent::~SoftwareStudent()
{
Student::~Student();
} | true |
339c4b3786baa141213f5486b8b24895360b0b56 | C++ | shivral/cf | /0600/60/667b.cpp | UTF-8 | 619 | 3.09375 | 3 | [
"Unlicense"
] | permissive | #include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
template <typename T>
std::istream& operator >>(std::istream& input, std::vector<T>& v)
{
for (T& a : v)
input >> a;
return input;
}
void answer(unsigned v)
{
std::cout << v << '\n';
}
void solve(std::vector<unsigned>& l)
{
const unsigned s = std::accumulate(l.cbegin(), l.cend(), 0);
const unsigned x = *std::max_element(l.cbegin(), l.cend());
answer(x - (s - x) + 1);
}
int main()
{
size_t n;
std::cin >> n;
std::vector<unsigned> l(n);
std::cin >> l;
solve(l);
return 0;
}
| true |
ecedc48e9fd74f2b1d7437813a65a872264bdcff | C++ | effekseer/Effekseer | /Dev/Cpp/Effekseer/Effekseer/Effekseer.Effect.h | UTF-8 | 24,259 | 2.640625 | 3 | [
"LicenseRef-scancode-nvidia-2002",
"BSD-3-Clause",
"GPL-3.0-only",
"GPL-3.0-or-later",
"Bison-exception-2.2",
"MIT",
"Apache-2.0",
"BSD-2-Clause",
"GD",
"MS-PL",
"OFL-1.1",
"LicenseRef-scancode-warranty-disclaimer",
"IJG",
"LicenseRef-scancode-khronos",
"Zlib"
] | permissive |
#ifndef __EFFEKSEER_EFFECT_H__
#define __EFFEKSEER_EFFECT_H__
//----------------------------------------------------------------------------------
// Include
//----------------------------------------------------------------------------------
#include "Effekseer.Base.h"
#include "Effekseer.File.h"
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
namespace Effekseer
{
class Effect;
using EffectRef = RefPtr<Effect>;
/**
@brief
\~English Terms where an effect exists
\~Japanese エフェクトが存在する期間
*/
struct EffectTerm
{
/**
@brief
\~English Minimum end time that the effect may exist
\~Japanese エフェクトが存在する可能性のある最小の終了時間
*/
int32_t TermMin;
/**
@brief
\~English Maximum end time that the effect may exist
\~Japanese エフェクトが存在する可能性のある最大の終了時間
*/
int32_t TermMax;
};
/**
@brief
\~English Terms where instances exists
\~Japanese インスタンスが存在する期間
*/
struct EffectInstanceTerm
{
/**
@brief
\~English Minimum start time that the first instance may exist
\~Japanese 最初のインスタンスが存在する可能性のある最小の開始時間
*/
int32_t FirstInstanceStartMin = 0;
/**
@brief
\~English Maximum start time that the first instance may exist
\~Japanese 最初のインスタンスが存在する可能性のある最大の開始時間
*/
int32_t FirstInstanceStartMax = 0;
/**
@brief
\~English Minimum end time that the first instance may exist
\~Japanese 最初のインスタンスが存在する可能性のある最小の終了時間
*/
int32_t FirstInstanceEndMin = INT_MAX;
/**
@brief
\~English Maximum end time that the first instance may exist
\~Japanese 最初のインスタンスが存在する可能性のある最大の終了時間
*/
int32_t FirstInstanceEndMax = INT_MAX;
/**
@brief
\~English Minimum start time that the last instance may exist
\~Japanese 最後のインスタンスが存在する可能性のある最小の開始時間
*/
int32_t LastInstanceStartMin = 0;
/**
@brief
\~English Maximum start time that the last instance may exist
\~Japanese 最後のインスタンスが存在する可能性のある最大の開始時間
*/
int32_t LastInstanceStartMax = 0;
/**
@brief
\~English Minimum end time that the last instance may exist
\~Japanese 最後のインスタンスが存在する可能性のある最小の終了時間
*/
int32_t LastInstanceEndMin = INT_MAX;
/**
@brief
\~English Maximum end time that the last instance may exist
\~Japanese 最後のインスタンスが存在する可能性のある最大の終了時間
*/
int32_t LastInstanceEndMax = INT_MAX;
};
/**
@brief
\~English A class to edit an instance of EffectParameter for supporting original format when a binary is loaded.
\~Japanese 独自フォーマットをサポートするための、バイナリが読み込まれた時にEffectParameterのインスタンスを編集するクラス
*/
class EffectFactory : public ReferenceObject
{
public:
EffectFactory();
virtual ~EffectFactory();
/**
@brief
\~English load body data(parameters of effect) from a binary
\~Japanese バイナリから本体(エフェクトのパラメーター)を読み込む。
*/
bool LoadBody(Effect* effect, const void* data, int32_t size, float magnification, const char16_t* materialPath);
/**
@brief
\~English set texture data into specified index
\~Japanese 指定されたインデックスにテクスチャを設定する。
*/
void SetTexture(Effect* effect, int32_t index, TextureType type, TextureRef data);
/**
@brief
\~English set sound data into specified index
\~Japanese 指定されたインデックスに音を設定する。
*/
void SetSound(Effect* effect, int32_t index, SoundDataRef data);
/**
@brief
\~English set model data into specified index
\~Japanese 指定されたインデックスにモデルを設定する。
*/
void SetModel(Effect* effect, int32_t index, ModelRef data);
/**
@brief
\~English set material data into specified index
\~Japanese 指定されたインデックスにマテリアルを設定する。
*/
void SetMaterial(Effect* effect, int32_t index, MaterialRef data);
/**
@brief
\~English set curve data into specified index
\~Japanese 指定されたインデックスにカーブを設定する。
*/
void SetCurve(Effect* effect, int32_t index, CurveRef data);
/**
@brief
\~English set model data into specified index
\~Japanese 指定されたインデックスにモデルを設定する。
*/
void SetProceduralModel(Effect* effect, int32_t index, ModelRef data);
/**
@brief
\~English set loading data
\~Japanese ロード用データを設定する。
*/
void SetLoadingParameter(Effect* effect, ReferenceObject* obj);
/**
@brief
\~English this method is called to check whether loaded binary are supported.
\~Japanese バイナリがサポートされているか確認するためにこのメソッドが呼ばれる。
*/
virtual bool OnCheckIsBinarySupported(const void* data, int32_t size);
/**
@brief
\~English this method is called to check whether reloading are supported.
\~Japanese リロードがサポートされているか確認するためにこのメソッドが呼ばれる。
*/
virtual bool OnCheckIsReloadSupported();
/**
@brief
\~English this method is called when load a effect from binary
\~Japanese バイナリからエフェクトを読み込む時に、このメソッドが呼ばれる。
*/
virtual bool OnLoading(Effect* effect, const void* data, int32_t size, float magnification, const char16_t* materialPath);
/**
@brief
\~English this method is called when load resources
\~Japanese リソースを読み込む時に、このメソッドが呼ばれる。
*/
virtual void OnLoadingResource(Effect* effect, const void* data, int32_t size, const char16_t* materialPath);
/**
@brief
\~English this method is called when unload resources
\~Japanese リソースを廃棄される時に、このメソッドが呼ばれる。
*/
virtual void OnUnloadingResource(Effect* effect);
/**
\~English get factory's name
\~Japanese ファクトリーの名称を取得する。
*/
virtual const char* GetName() const;
/**
\~English get whether resources are loaded automatically when a binary is loaded
\~Japanese バイナリを読み込んだときに自動的にリソースを読み込むか取得する。
*/
virtual bool GetIsResourcesLoadedAutomatically() const;
};
/**
@brief
\~English Effect parameters
\~Japanese エフェクトパラメータークラス
*/
class Effect : public IReference
{
protected:
Effect()
{
}
virtual ~Effect()
{
}
public:
/**
@brief エフェクトを生成する。
@param manager [in] 管理クラス
@param data [in] データ配列の先頭のポインタ
@param size [in] データ配列の長さ
@param magnification [in] 読み込み時の拡大率
@param materialPath [in] 素材ロード時の基準パス
@return エフェクト。失敗した場合はnullptrを返す。
*/
static EffectRef Create(const ManagerRef& manager, const void* data, int32_t size, float magnification = 1.0f, const char16_t* materialPath = nullptr);
/**
@brief エフェクトを生成する。
@param manager [in] 管理クラス
@param path [in] 読込元のパス
@param magnification [in] 読み込み時の拡大率
@param materialPath [in] 素材ロード時の基準パス
@return エフェクト。失敗した場合はnullptrを返す。
*/
static EffectRef Create(const ManagerRef& manager, const char16_t* path, float magnification = 1.0f, const char16_t* materialPath = nullptr);
/**
@brief エフェクトを生成する。
@param setting [in] 設定クラス
@param data [in] データ配列の先頭のポインタ
@param size [in] データ配列の長さ
@param magnification [in] 読み込み時の拡大率
@param materialPath [in] 素材ロード時の基準パス
@return エフェクト。失敗した場合はnullptrを返す。
*/
static EffectRef Create(const SettingRef& setting, const void* data, int32_t size, float magnification = 1.0f, const char16_t* materialPath = nullptr);
/**
@brief エフェクトを生成する。
@param setting [in] 設定クラス
@param path [in] 読込元のパス
@param magnification [in] 読み込み時の拡大率
@param materialPath [in] 素材ロード時の基準パス
@return エフェクト。失敗した場合はnullptrを返す。
*/
static EffectRef Create(const SettingRef& setting, const char16_t* path, float magnification = 1.0f, const char16_t* materialPath = nullptr);
/**
@brief 標準のエフェクト読込インスタンスを生成する。
*/
static ::Effekseer::EffectLoaderRef CreateEffectLoader(::Effekseer::FileInterfaceRef fileInterface = nullptr);
/**
@brief
\~English Get this effect's name. If this effect is loaded from file, default name is file name without extention.
\~Japanese エフェクトの名前を取得する。もしファイルからエフェクトを読み込んだ場合、名前は拡張子を除いたファイル名である。
*/
virtual const char16_t* GetName() const = 0;
/**
\~English Set this effect's name
\~Japanese エフェクトの名前を設定する。
*/
virtual void SetName(const char16_t* name) = 0;
/**
@brief 設定を取得する。
@return 設定
*/
virtual const SettingRef& GetSetting() const = 0;
/**
@brief \~English Get the magnification multiplied by the magnification at the time of loaded and exported.
\~Japanese 読み込み時と出力時の拡大率をかけた拡大率を取得する。
*/
virtual float GetMaginification() const = 0;
/**
@brief エフェクトデータのバージョン取得
*/
virtual int GetVersion() const = 0;
/**
@brief
\~English Get loading parameter supecfied by EffectFactory. This parameter is not used unless EffectFactory is used
\~Japanese
EffectFactoryによって指定されたロード用パラメーターを取得する。EffectFactoryを使用しない限り、子のパラメーターは使用しない。
*/
virtual ReferenceObject* GetLoadingParameter() const = 0;
/**
@brief 格納されている色画像のポインタを取得する。
@param n [in] 画像のインデックス
@return 画像のポインタ
*/
virtual TextureRef GetColorImage(int n) const = 0;
/**
@brief 格納されている画像のポインタの個数を取得する。
*/
virtual int32_t GetColorImageCount() const = 0;
/**
@brief \~English Get a color image's path
\~Japanese 色画像のパスを取得する。
*/
virtual const char16_t* GetColorImagePath(int n) const = 0;
/**
@brief 格納されている法線画像のポインタを取得する。
@param n [in] 画像のインデックス
@return 画像のポインタ
*/
virtual TextureRef GetNormalImage(int n) const = 0;
/**
@brief 格納されている法線画像のポインタの個数を取得する。
*/
virtual int32_t GetNormalImageCount() const = 0;
/**
@brief \~English Get a normal image's path
\~Japanese 法線画像のパスを取得する。
*/
virtual const char16_t* GetNormalImagePath(int n) const = 0;
/**
@brief 格納されている歪み画像のポインタを取得する。
@param n [in] 画像のインデックス
@return 画像のポインタ
*/
virtual TextureRef GetDistortionImage(int n) const = 0;
/**
@brief 格納されている歪み画像のポインタの個数を取得する。
*/
virtual int32_t GetDistortionImageCount() const = 0;
/**
@brief \~English Get a distortion image's path
\~Japanese 歪み画像のパスを取得する。
*/
virtual const char16_t* GetDistortionImagePath(int n) const = 0;
/**
@brief 格納されている音波形のポインタを取得する。
*/
virtual SoundDataRef GetWave(int n) const = 0;
/**
@brief 格納されている音波形のポインタの個数を取得する。
*/
virtual int32_t GetWaveCount() const = 0;
/**
@brief \~English Get a wave's path
\~Japanese 音波形のパスを取得する。
*/
virtual const char16_t* GetWavePath(int n) const = 0;
/**
@brief 格納されているモデルのポインタを取得する。
*/
virtual ModelRef GetModel(int n) const = 0;
/**
@brief 格納されているモデルのポインタの個数を取得する。
*/
virtual int32_t GetModelCount() const = 0;
/**
@brief \~English Get a model's path
\~Japanese モデルのパスを取得する。
*/
virtual const char16_t* GetModelPath(int n) const = 0;
/**
@brief \~English Get a material's pointer
\~Japanese 格納されているマテリアルのポインタを取得する。
*/
virtual MaterialRef GetMaterial(int n) const = 0;
/**
@brief \~English Get the number of stored material pointer
\~Japanese 格納されているマテリアルのポインタの個数を取得する。
*/
virtual int32_t GetMaterialCount() const = 0;
/**
@brief \~English Get a material's path
\~Japanese マテリアルのパスを取得する。
*/
virtual const char16_t* GetMaterialPath(int n) const = 0;
/**
@brief \~English Get a curve's pointer
\~Japanese 格納されているカーブのポインタを取得する。
*/
virtual CurveRef GetCurve(int n) const = 0;
/**
@brief \~English Get the number of stored curve pointer
\~Japanese 格納されているカーブのポインタの個数を取得する。
*/
virtual int32_t GetCurveCount() const = 0;
/**
@brief \~English Get a curve's path
\~Japanese カーブのパスを取得する。
*/
virtual const char16_t* GetCurvePath(int n) const = 0;
/**
@brief \~English Get a procedural model's pointer
\~Japanese 格納されているプロシージャルモデルのポインタを取得する。
*/
virtual ModelRef GetProceduralModel(int n) const = 0;
/**
@brief \~English Get the number of stored procedural model's pointer
\~Japanese 格納されているプロシージャルモデルのポインタの個数を取得する。
*/
virtual int32_t GetProceduralModelCount() const = 0;
/**
@brief \~English Get a procedural model's parameter
\~Japanese 格納されているプロシージャルモデルのパラメーターを取得する。
*/
virtual const ProceduralModelParameter* GetProceduralModelParameter(int n) const = 0;
/**
@brief
\~English set texture data into specified index
\~Japanese 指定されたインデックスにテクスチャを設定する。
*/
virtual void SetTexture(int32_t index, TextureType type, TextureRef data) = 0;
/**
@brief
\~English set sound data into specified index
\~Japanese 指定されたインデックスに音を設定する。
*/
virtual void SetSound(int32_t index, SoundDataRef data) = 0;
/**
@brief
\~English set model data into specified index
\~Japanese 指定されたインデックスにモデルを設定する。
*/
virtual void SetModel(int32_t index, ModelRef data) = 0;
/**
@brief
\~English set material data into specified index
\~Japanese 指定されたインデックスにマテリアルを設定する。
*/
virtual void SetMaterial(int32_t index, MaterialRef data) = 0;
/**
@brief
\~English set curve data into specified index
\~Japanese 指定されたインデックスにカーブを設定する。
*/
virtual void SetCurve(int32_t index, CurveRef data) = 0;
/**
@brief
\~English set a model data into specified index
\~Japanese 指定されたインデックスにカーブを設定する。
*/
virtual void SetProceduralModel(int32_t index, ModelRef data) = 0;
/**
@brief
\~English Reload this effect
\~Japanese エフェクトのリロードを行う。
@param managers
\~English An array of manager instances
\~Japanese マネージャーの配列
@param managersCount
\~English Length of array
\~Japanese マネージャーの個数
@param data
\~English An effect's data
\~Japanese エフェクトのデータ
@param size
\~English An effect's size
\~Japanese エフェクトのデータサイズ
@param materialPath
\~English A path where reaources are loaded
\~Japanese リソースの読み込み元
@param reloadingThreadType
\~English A thread where reload function is called
\~Japanese リロードの関数が呼ばれるスレッド
@return
\~English Result
\~Japanese 結果
@note
\~English
If an effect is generated with Setting, the effect in managers is reloaded with managers
If reloadingThreadType is RenderThread, new resources aren't loaded and old resources aren't disposed.
\~Japanese
Settingを用いてエフェクトを生成したときに、Managerを指定することで対象のManager内のエフェクトのリロードを行う。
もし、reloadingThreadType が RenderThreadの場合、新規のリソースは読み込まれず、古いリソースは破棄されない。
*/
virtual bool Reload(ManagerRef* managers,
int32_t managersCount,
const void* data,
int32_t size,
const char16_t* materialPath = nullptr,
ReloadingThreadType reloadingThreadType = ReloadingThreadType::Main) = 0;
/**
@brief
\~English Reload this effect
\~Japanese エフェクトのリロードを行う。
@param managers
\~English An array of manager instances
\~Japanese マネージャーの配列
@param managersCount
\~English Length of array
\~Japanese マネージャーの個数
@param path
\~English An effect's path
\~Japanese エフェクトのパス
@param materialPath
\~English A path where reaources are loaded
\~Japanese リソースの読み込み元
@param reloadingThreadType
\~English A thread where reload function is called
\~Japanese リロードの関数が呼ばれるスレッド
@return
\~English Result
\~Japanese 結果
@note
\~English
If an effect is generated with Setting, the effect in managers is reloaded with managers
If reloadingThreadType is RenderThread, new resources aren't loaded and old resources aren't disposed.
\~Japanese
Settingを用いてエフェクトを生成したときに、Managerを指定することで対象のManager内のエフェクトのリロードを行う。
もし、reloadingThreadType が RenderThreadの場合、新規のリソースは読み込まれず、古いリソースは破棄されない。
*/
virtual bool Reload(ManagerRef* managers,
int32_t managersCount,
const char16_t* path,
const char16_t* materialPath = nullptr,
ReloadingThreadType reloadingThreadType = ReloadingThreadType::Main) = 0;
/**
@brief 画像等リソースの再読み込みを行う。
*/
virtual void ReloadResources(const void* data = nullptr, int32_t size = 0, const char16_t* materialPath = nullptr) = 0;
/**
@brief 画像等リソースの破棄を行う。
*/
virtual void UnloadResources() = 0;
/**
@brief Rootを取得する。
*/
virtual EffectNode* GetRoot() const = 0;
/**
@brief
\~English Calculate a term of instances where the effect exists
\~Japanese エフェクトが存在する期間を計算する。
*/
virtual EffectTerm CalculateTerm() const = 0;
/**
@brief
\~English Get values of default dynamic inputs.
\~Japanese 動的パラメーターのデフォルトの値を取得する。
*/
virtual std::array<float, 4> GetDefaultDynamicInputs() const = 0;
virtual EffectImplemented* GetImplemented() = 0;
virtual const EffectImplemented* GetImplemented() const = 0;
};
/**
@brief
\~English Node rendering parameters
\~Japanese ノードの描画パラメーター
@note
\~English
The members of this struct are subject to significant change.
\~Japanese
この構造体は内容が大きく変更される可能性があります。
*/
struct EffectBasicRenderParameter
{
int32_t MaterialIndex = -1;
std::array<int32_t, TextureSlotMax> TextureIndexes;
std::array<TextureFilterType, TextureSlotMax> TextureFilters;
std::array<TextureWrapType, TextureSlotMax> TextureWraps;
NodeRendererFlipbookParameter FlipbookParams;
RendererMaterialType MaterialType;
float UVDistortionIntensity;
int32_t TextureBlendType;
float BlendUVDistortionIntensity;
bool EnableFalloff;
struct
{
int32_t ColorBlendType;
std::array<float, 4> BeginColor;
std::array<float, 4> EndColor;
float Pow = 1.0f;
} FalloffParam;
float EmissiveScaling;
struct
{
float Color[4];
float Threshold;
float ColorScaling;
} EdgeParam;
AlphaBlendType AlphaBlend;
bool ZWrite;
bool ZTest;
bool Distortion;
float DistortionIntensity;
float SoftParticleDistanceFar = 0.0f;
float SoftParticleDistanceNear = 0.0f;
float SoftParticleDistanceNearOffset = 0.0f;
};
/**
@brief
\~English Model parameter
\~Japanese モデルパラメーター
@note
\~English It may change greatly.
\~Japanese 大きく変更される可能性があります。
*/
struct EffectModelParameter
{
int32_t ModelIndex;
CullingType Culling;
};
/**
@brief ノードインスタンス生成クラス
@note
エフェクトのノードの実体を生成する。
*/
class EffectNode
{
public:
EffectNode()
{
}
virtual ~EffectNode()
{
}
/**
@brief ノードが所属しているエフェクトを取得する。
*/
virtual Effect* GetEffect() const = 0;
/**
@brief Get the type of this node
*/
virtual EffectNodeType GetType() const = 0;
/**
@brief
\~English Get a generation in the node tree. The generation increases by 1 as it moves a child node.
\~Japanese ノードツリーの世代を取得する。世代は子のノードになるにしたがって1増える。
*/
virtual int GetGeneration() const = 0;
/**
@brief 子のノードの数を取得する。
*/
virtual int GetChildrenCount() const = 0;
/**
@brief 子のノードを取得する。
*/
virtual EffectNode* GetChild(int index) const = 0;
/**
@brief 共通描画パラメーターを取得する。
*/
virtual EffectBasicRenderParameter GetBasicRenderParameter() const = 0;
/**
@brief 共通描画パラメーターを設定する。
*/
virtual void SetBasicRenderParameter(EffectBasicRenderParameter param) = 0;
/**
@brief
\~English Get a model parameter
\~Japanese モデルパラメーターを取得する。
*/
virtual EffectModelParameter GetEffectModelParameter() = 0;
/**
@brief
\~English Calculate a term of instances where instances exists
\~Japanese インスタンスが存在する期間を計算する。
*/
virtual EffectInstanceTerm CalculateInstanceTerm(EffectInstanceTerm& parentTerm) const = 0;
/**
@brief
\~English Get a user data for rendering in plugins.
\~Japanese プラグイン向けの描画拡張データを取得する。
@note
\~Japanese 詳細はSetterを参照。
*/
virtual RefPtr<RenderingUserData> GetRenderingUserData() = 0;
/**
@brief
\~English Specify a user data for rendering in plugins.
\~Japanese プラグイン向けの描画拡張データを設定する。
@note
\~English
This variable is passed to the Renderer at rendering time.
The variable is compared by the comparison function described by the inheritance of RenderingUserData, and if the values are different, DrawCall is issued.
\~Japanese
この変数は描画時にRendererに渡される。
変数は、RenderingUserDataの継承により記述される比較用の関数によって比較され、値が異なる場合、DrawCallを発行する。
*/
virtual void SetRenderingUserData(const RefPtr<RenderingUserData>& renderingUserData) = 0;
};
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
} // namespace Effekseer
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
#endif // __EFFEKSEER_EFFECT_H__
| true |
10434f81d7643a69598ad6974e5b7cf93496d665 | C++ | ermek-bdnf/c-cpp-sources | /19_accumulate.cpp | UTF-8 | 1,586 | 3.953125 | 4 | [] | no_license | //19 accumulate
#include<iostream>
#include<algorithm>
#include<vector>
#include<list>
#include<string>
#include<numeric> //accumulate
using namespace std;
//sum of even elements
//this algorithm can also work with strings
int main()
{
int m[] = {2,3,4};
string result = accumulate(next(begin(m)), end(m), to_string(m[0]),
[](string a, int b)
{
return a + "-" + to_string(b);
});
cout << result << endl;
//next(begin(m)) or next(m)
/*
auto result = accumulate(begin(m), end(m), 0,
[](int a, int b)
{
if(b % 2 == 0)
{
return a + b;
}
else
{
return a; //current state of data
}
});
cout << result << endl;
/*
int m[] = {2,3,4};
auto result = accumulate(begin(m), end(m), 1,
[](int a, int b)
{
return a * b;
});
// the third parameter of the function is accumulate.
cout << result << endl;
/*
int m[] = {2,3,4};
auto result = accumulate(begin(m), end(m), 0);
cout << "sum: " << result << endl;
/*
const int SIZE = 3;
int arr[SIZE] = {2, 4, 9};
auto result = accumulate(begin(arr), end(arr), 0);
cout << "sum: " << result << endl;
/*
vector<int> v = {2, 3, 4};
//list<int> lst = {4,7,77,-3,44,74};
//auto result = accumulate(lst.begin(), lst.end());
auto result = accumulate(v.begin(), v.end(), 0);
//0 is the reference point
//if zero, then 0 + the sum of all elements
cout << "sum: " << result << endl; //0 + sum of elements
auto result2 = accumulate(begin(v), v.end(), 10);
cout << "sum: " << result2 << endl; // 10 + sum of elements
*/
return 0;
}
| true |
1105d93f9b0e598a09aa25cc506bc4728cf576a5 | C++ | jonas2602/ParserGenerator | /ParserGenerator/src/ParserGenerator/Utils/StringUtils.cpp | UTF-8 | 1,218 | 3.65625 | 4 | [] | no_license | #include "StringUtils.h"
#include <algorithm>
std::string StringUtils::ToUpperCase(const std::string& InString)
{
std::string UpperCaseString = InString;
std::transform(UpperCaseString.begin(), UpperCaseString.end(), UpperCaseString.begin(), ::toupper);
return UpperCaseString;
}
std::string StringUtils::ToLowerCase(const std::string& InString)
{
std::string LowerCaseString = InString;
std::transform(LowerCaseString.begin(), LowerCaseString.end(), LowerCaseString.begin(), ::tolower);
return LowerCaseString;
}
std::string StringUtils::InterpretLiteral(const std::string& LiteralString)
{
std::string OutString = "";
for (int i = 0; i < LiteralString.size(); i++)
{
if (LiteralString[i] == '\\')
{
// Move to the symbol that should get escaped
i += 1;
OutString += StringUtils::EscapeCharacter(LiteralString[i]);
}
else
{
OutString += LiteralString[i];
}
}
return OutString;
}
char StringUtils::EscapeCharacter(const char& InCharacter)
{
switch (InCharacter)
{
case 'a': return '\a';
case 'b': return '\b';
case 'f': return '\f';
case 'n': return '\n';
case 'r': return '\r';
case 't': return '\t';
case 'v': return '\v';
default: return InCharacter;
}
}
| true |
5f07cb12c0267025e8ab1918e927f6f52248ebb2 | C++ | OmerCora/NetworkFinalProject | /Project3-Network/GraphicalClient2/cAreaInfo.cpp | UTF-8 | 557 | 2.734375 | 3 | [
"MIT"
] | permissive | #include "cAreaInfo.h"
//#include "GlobalStuff.h"
cAreaInfo::cAreaInfo()
{
//initialize the member variables with information from external file
this->Max.x = 25.0f;
this->Max.y = 10.0f;
this->Max.z = 25.0f;
this->Min.x = -25.0f;
this->Min.y = -10.0f;
this->Min.z = -25.0f;
}
cAreaInfo::~cAreaInfo()
{
}
float cAreaInfo::getLocationRange()
{
float widthOfOneSide = this->Max.x - this->Min.x;
int numOfLocsInOneSide = 13; // 9 locations + 2 coners(x2 width)
float locationRange = widthOfOneSide / numOfLocsInOneSide;
return locationRange;
}
| true |
c23f88bac6262b33b969bfb5840da4e572d9b65f | C++ | NightTerror1721/kpl | /[Distarted]/Krampus Language/src/instruction.cpp | UTF-8 | 1,140 | 2.6875 | 3 | [] | no_license | #include "instruction.h"
namespace kpl::inst
{
Instruction& Instruction::b(int value)
{
if (value >= 0)
_inst = (_inst & b_mask) | static_cast<Instruction>((value & 0xff) << 15);
else
{
_inst = (_inst & b_mask) | static_cast<Instruction>((-value & 0xff) << 15) | (0x1 << 14);
}
return *this;
}
Instruction& Instruction::c(int value)
{
if (value >= 0)
_inst = (_inst & c_mask) | static_cast<Instruction>((value & 0xff) << 24);
else
{
_inst = (_inst & c_mask) | static_cast<Instruction>((-value & 0xff) << 24) | (0x1 << 23);
}
return *this;
}
Instruction& Instruction::sbx(int value)
{
if (value >= 0)
_inst = (_inst & bx_mask) | static_cast<Instruction>((value & 0x1ffff) << 15);
else
{
_inst = (_inst & bx_mask) | static_cast<Instruction>((value & 0x1ffff) << 15) | (0x1 << 14);
}
return *this;
}
Instruction& Instruction::sax(int value)
{
if (value >= 0)
_inst = (_inst & ax_mask) | static_cast<Instruction>((value & 0x1ffffff) << 7);
else
{
_inst = (_inst & ax_mask) | static_cast<Instruction>((value & 0x1ffffff) << 7) | (0x1 << 6);
}
return *this;
}
}
| true |
25496d894aa7fe45d53d4e4a7ec5f06a7f50b21a | C++ | fdfragoso/GameEngines | /Random-Engine/src/AnimationCmp.cpp | UTF-8 | 2,120 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include "AnimationCmp.hpp"
#include "RandomEngine.hpp"
using namespace SRE;
Animation::Animation(std::vector<Sprite*> sprites, float durationMs)
: sprites(sprites), durationMs(durationMs)
{
minTime = durationMs / sprites.size();
}
AnimationCmp::AnimationCmp(GameObject *gameObject)
:Component(gameObject)
{
isPlaying = true;
resetAnim = false;
currentIndex = 0;
clockInit = 0;
}
AnimationCmp::~AnimationCmp() {
for (auto e : animations) {
//e.second->sprites.clear();
delete e.second;
}
animations.clear();
}
void AnimationCmp::createAnim(std::string name, Animation * anim) {
if (animations.find(name) == animations.end()) {
animations.emplace(name, anim);
}
}
void AnimationCmp::setAnim(std::string name) {
if (currentAnimName == name) {
return;
}
if (animations.find(name) != animations.end()) {
currentAnimName = name;
currentIndex = 0;
clockInit = 0;
}
}
void AnimationCmp::play() {
if (!isPlaying) {
if (resetAnim) {
currentIndex = 0;
}
clockInit = clock();
}
isPlaying = true;
resetAnim = false;
}
void AnimationCmp::stop() {
isPlaying = false;
resetAnim = true;
}
void AnimationCmp::pause() {
isPlaying = false;
resetAnim = false;
}
Sprite* AnimationCmp::getCurrentSprite() {
if (animations.find(currentAnimName) != animations.end()) {
if (clockInit == 0) {
clockInit = clock();
}
auto minTime = animations[currentAnimName]->minTime;
auto sprites = animations[currentAnimName]->sprites;
auto currentSprite = sprites[currentIndex];
if (isPlaying) {
auto diffTime = (clock() - clockInit) / CLOCKS_PER_MS;
if (diffTime >= minTime) {
currentIndex = (currentIndex + 1) % sprites.size();
clockInit = clock();
}
}
return currentSprite;
}
return nullptr;
}
void AnimationCmp::setCurrentAnimDuration(float duration) {
auto currentAnim = animations[currentAnimName];
currentAnim->durationMs = duration;
currentAnim->minTime = duration / currentAnim->sprites.size();
}
float AnimationCmp::getCurrentAnimDuration() {
auto currentAnim = animations[currentAnimName];
return currentAnim->durationMs;
} | true |
731eee3e0ae593cacc869a6fadfcabf9ae4d6260 | C++ | DualBrain/df_win | /src/EventView.cpp | UTF-8 | 973 | 3.03125 | 3 | [] | no_license | #include "EventView.h"
namespace df {
//Create view event with tag VIEW_EVENT, value 0 and delta false.
EventView::EventView() : m_tag(VIEW_EVENT), m_value(0), m_delta(false) {
setType(VIEW_EVENT);
}
//Create view event with tag, value and delta as indicated.
EventView::EventView(std::string new_tag, int new_value, bool new_delta) : m_tag(new_tag), m_value(new_value), m_delta(new_delta) {
setType(VIEW_EVENT);
}
//Set tag to new tag.
void EventView::setTag(std::string new_tag) {
m_tag = new_tag;
}
//Get tag
std::string EventView::getTag() const {
return m_tag;
}
//Set value to new value.
void EventView::setValue(int new_value) {
m_value = new_value;
}
//Get value
int EventView::getValue() const {
return m_value;
}
//Set delta to new delta.
void EventView::setDelta(bool new_delta) {
m_delta = new_delta;
}
//Get delta.
bool EventView::getDelta() const {
return m_delta;
}
} | true |
0f54002257d66268181292df2e2a257f5c3ebdcd | C++ | rnguyen18/CyclistAssist_Libraries | /LightController/LightController.h | UTF-8 | 522 | 2.71875 | 3 | [] | no_license | /*
LightController.h - Library for controlling lights.
*/
#ifndef LightController_h
#define LightController_h
#include "Arduino.h"
class LightController
{
public:
LightController(int headlightPin, int leftPin, int rightPin, int rearPin);
void Update();
void UpdateInput(char charIn);
bool CheckHeadlightStatus();
private:
int headlight_pin;
int left_pin;
int right_pin;
int rear_pin;
int blink_start;
char light;
bool blinkers;
bool headlight;
static const int BLINKER_TIMING = 1000;
};
#endif | true |
93f518a89c1d7b7b2b7d3534fc4aa1ae813962e4 | C++ | cmaughan/mgfx | /mcommon/file/mfilesystem.h | UTF-8 | 6,634 | 2.984375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <sys/stat.h>
#include <sys/types.h>
#include "string/stringutils.h"
#include "file/fileutils.h"
namespace mfilesystem
{
// NOTE:
// This is a very simple implementation of the <filesystem> functionality in CPP 14/17.
// It is not meant to be production code, but is enough to get this code working on a Mac, on which I can't get a
// working version of <filesystem>.
// I will remove this when I figure it out, or the compiler catches up ;)
// I'll also try to make this code more tested/functional until that time
class filesystem_error : public std::system_error
{
};
typedef std::chrono::system_clock::time_point file_time_type;
class path
{
public:
typedef std::vector<std::string>::const_iterator const_iterator;
path(const std::string& strPath = std::string())
: m_strPath(strPath)
{
}
path(const char* pszPath)
: m_strPath(pszPath)
{
}
bool empty() const
{
return m_strPath.empty();
}
path stem() const
{
std::string name, ext;
split(name, ext);
return name;
}
path filename() const
{
std::string name, ext;
split(name, ext);
return path(name + ext);
}
bool is_relative() const
{
return !is_absolute();
}
bool is_absolute() const
{
return false;
}
path extension() const
{
std::string name, ext;
split(name, ext);
return ext;
}
path parent_path() const
{
std::string strSplit;
size_t sep = m_strPath.find_last_of("\\/");
if (sep != std::string::npos)
{
return m_strPath.substr(0, sep);
}
return path("");
}
path& replace_extension(const std::string& extension)
{
size_t dot = m_strPath.find_last_of(".");
if (dot != std::string::npos)
{
m_strPath = m_strPath.substr(0, dot - 1) + extension;
}
else
{
m_strPath += extension;
}
return *this;
}
void split(std::string& name, std::string& extension) const
{
std::string strSplit;
size_t sep = m_strPath.find_last_of("\\/");
if (sep != std::string::npos)
{
strSplit = m_strPath.substr(sep + 1, m_strPath.size() - sep - 1);
}
size_t dot = strSplit.find_last_of(".");
if (dot != std::string::npos)
{
name = strSplit.substr(0, dot);
extension = strSplit.substr(dot, strSplit.size() - dot);
}
else
{
name = strSplit;
extension = "";
}
}
const char* c_str() const { return m_strPath.c_str(); }
std::string string() const { return m_strPath; }
bool operator == (const path& rhs) const { return m_strPath == rhs.string(); }
path operator / (const path& rhs) const
{
std::string temp = m_strPath;
StringUtils::RTrim(temp, "\\/");
return path(temp + "/" + rhs.string());
}
operator std::string() const { return m_strPath; }
bool operator < (const path& rhs) const
{
return m_strPath < rhs.string();
}
std::vector<std::string>::const_iterator begin()
{
std::string can = StringUtils::ReplaceString(m_strPath, "\\", "/");
m_components = StringUtils::Split(can, "/");
return m_components.begin();
}
std::vector<std::string>::const_iterator end()
{
return m_components.end();
}
private:
std::vector<std::string> m_components;
std::string m_strPath;
};
inline bool exists(const path& path)
{
struct stat buffer;
if (path.string().empty())
{
return false;
}
return stat(path.c_str(), &buffer) == 0;
}
inline path canonical(const path& input)
{
return path(StringUtils::ReplaceString(input.string(), "\\", "/"));
}
inline path absolute(const path& input)
{
// Read the comments at the top of this file; this is certainly incorrect, and doesn't handle ../
// It is sufficient for what we need though
auto p = canonical(input);
auto strAbs = StringUtils::ReplaceString(p.string(), "/.", "");
return path(strAbs);
}
inline std::ostream& operator << (std::ostream& rhs, const path& p)
{
rhs << p.string();
return rhs;
}
namespace copy_options
{
enum
{
overwrite_existing = 1
};
};
inline bool copy_file(const path& source, const path& dest, uint32_t options)
{
std::ifstream src(source.string(), std::ios::binary);
std::ofstream dst(dest.string(), std::ios::binary);
if (!src.is_open() || !dst.is_open())
{
return false;
}
dst << src.rdbuf();
return true;
}
inline bool isDirExist(const std::string& path)
{
#if defined(_WIN32)
struct _stat info;
if (_stat(path.c_str(), &info) != 0)
{
return false;
}
return (info.st_mode & _S_IFDIR) != 0;
#else
struct stat info;
if (stat(path.c_str(), &info) != 0)
{
return false;
}
return (info.st_mode & S_IFDIR) != 0;
#endif
}
inline bool makePath(const std::string& path)
{
#if defined(_WIN32)
int ret = _mkdir(path.c_str());
#else
mode_t mode = 0755;
int ret = mkdir(path.c_str(), mode);
#endif
if (ret == 0)
return true;
switch (errno)
{
case ENOENT:
// parent didn't exist, try to create it
{
auto pos = path.find_last_of('/');
if (pos == std::string::npos)
#if defined(_WIN32)
pos = path.find_last_of('\\');
if (pos == std::string::npos)
#endif
return false;
if (!makePath( path.substr(0, pos) ))
return false;
}
// now, try to create again
#if defined(_WIN32)
return 0 == _mkdir(path.c_str());
#else
return 0 == mkdir(path.c_str(), mode);
#endif
case EEXIST:
// done!
return isDirExist(path);
default:
return false;
}
}
inline bool create_directories(const path& source)
{
return makePath(source.string());
}
inline file_time_type last_write_time(const path& source)
{
struct stat attr;
std::string strSource = source.string();
stat(strSource.c_str(), &attr);
return std::chrono::system_clock::from_time_t(attr.st_mtime);
}
inline bool is_directory(const path& source)
{
struct stat s;
auto strPath = source.string();
if (stat(strPath.c_str(), &s) == 0)
{
if (s.st_mode & S_IFDIR)
{
//it's a directory
return true;
}
}
return false;
}
}
| true |
1825623f84a555ecdebbc4d75647cc196b079c95 | C++ | softerhardware/jam-stapl | /source/jamnote.c | UTF-8 | 8,162 | 2.625 | 3 | [] | no_license | /****************************************************************************/
/* */
/* Module: jamnote.c */
/* */
/* Copyright (C) Altera Corporation 1997 */
/* */
/* Description: Functions to extract NOTE fields from an JAM program */
/* */
/****************************************************************************/
#include "jamexprt.h"
#include "jamdefs.h"
#include "jamexec.h"
#include "jamutil.h"
/****************************************************************************/
/* */
BOOL jam_get_note_key
(
char *statement_buffer,
long *key_begin,
long *key_end
)
/* */
/* Description: This function finds the note key name in the statement */
/* buffer and returns the start and end offsets */
/* */
/* Returns: TRUE for success, FALSE if key not found */
/* */
/****************************************************************************/
{
int index = 0;
BOOL quoted_string = FALSE;
index = jam_skip_instruction_name(statement_buffer);
/*
* Check if key string has quotes
*/
if ((statement_buffer[index] == JAMC_QUOTE_CHAR) &&
(index < JAMC_MAX_STATEMENT_LENGTH))
{
quoted_string = TRUE;
++index;
}
/*
* Mark the beginning of the key string
*/
*key_begin = index;
/*
* Now find the end of the key string
*/
if (quoted_string)
{
/* look for matching quote */
while ((statement_buffer[index] != JAMC_NULL_CHAR) &&
(statement_buffer[index] != JAMC_QUOTE_CHAR) &&
(index < JAMC_MAX_STATEMENT_LENGTH))
{
++index;
}
if (statement_buffer[index] == JAMC_QUOTE_CHAR)
{
*key_end = index;
}
}
else
{
/* look for white space */
while ((statement_buffer[index] != JAMC_NULL_CHAR) &&
(!jam_isspace(statement_buffer[index])) &&
(index < JAMC_MAX_STATEMENT_LENGTH))
{
++index; /* skip over white space */
}
if (jam_isspace(statement_buffer[index]))
{
*key_end = index;
}
}
return ((*key_end > *key_begin) ? TRUE : FALSE);
}
/****************************************************************************/
/* */
BOOL jam_get_note_value
(
char *statement_buffer,
long *value_begin,
long *value_end
)
/* */
/* Description: Finds the value field of a NOTE. Could be enclosed in */
/* quotation marks, or could not be. Must be followed by */
/* a semicolon. */
/* */
/* Returns: TRUE for success, FALSE for failure */
/* */
/****************************************************************************/
{
int index = 0;
BOOL quoted_string = FALSE;
BOOL status = FALSE;
/* skip over white space */
while ((statement_buffer[index] != JAMC_NULL_CHAR) &&
(jam_isspace(statement_buffer[index])) &&
(index < JAMC_MAX_STATEMENT_LENGTH))
{
++index;
}
/*
* Check if value string has quotes
*/
if ((statement_buffer[index] == JAMC_QUOTE_CHAR) &&
(index < JAMC_MAX_STATEMENT_LENGTH))
{
quoted_string = TRUE;
++index;
}
/*
* Mark the beginning of the value string
*/
*value_begin = index;
/*
* Now find the end of the value string
*/
if (quoted_string)
{
/* look for matching quote */
while ((statement_buffer[index] != JAMC_NULL_CHAR) &&
(statement_buffer[index] != JAMC_QUOTE_CHAR) &&
(index < JAMC_MAX_STATEMENT_LENGTH))
{
++index;
}
if (statement_buffer[index] == JAMC_QUOTE_CHAR)
{
*value_end = index;
status = TRUE;
++index;
}
}
else
{
/* look for white space or semicolon */
while ((statement_buffer[index] != JAMC_NULL_CHAR) &&
(statement_buffer[index] != JAMC_SEMICOLON_CHAR) &&
(!jam_isspace(statement_buffer[index])) &&
(index < JAMC_MAX_STATEMENT_LENGTH))
{
++index; /* skip over non-white space */
}
if ((statement_buffer[index] == JAMC_SEMICOLON_CHAR) ||
(jam_isspace(statement_buffer[index])))
{
*value_end = index;
status = TRUE;
}
}
if (status)
{
while ((statement_buffer[index] != JAMC_NULL_CHAR) &&
(jam_isspace(statement_buffer[index])) &&
(index < JAMC_MAX_STATEMENT_LENGTH))
{
++index; /* skip over white space */
}
/*
* Next character must be semicolon
*/
if (statement_buffer[index] != JAMC_SEMICOLON_CHAR)
{
status = FALSE;
}
}
return (status);
}
/****************************************************************************/
/* */
JAM_RETURN_TYPE jam_get_note
(
char *program,
long program_size,
long *offset,
char *key,
char *value,
int length
)
/* */
/* Description: Gets key and value of NOTE fields in the JAM file. */
/* Can be called in two modes: if offset pointer is NULL, */
/* then the function searches for note fields which match */
/* the key string provided. If offset is not NULL, then */
/* the function finds the next note field of any key, */
/* starting at the offset specified by the offset pointer. */
/* */
/* Returns: JAMC_SUCCESS for success, else appropriate error code */
/* */
/****************************************************************************/
{
JAM_RETURN_TYPE status = JAMC_SUCCESS;
char *statement_buffer = NULL;
unsigned int statement_buffer_size = 0;
char label_buffer[JAMC_MAX_NAME_LENGTH + 1];
JAME_INSTRUCTION instruction = JAM_ILLEGAL_INSTR;
long key_begin = 0L;
long key_end = 0L;
long value_begin = 0L;
long value_end = 0L;
BOOL done = FALSE;
char *tmp_program = jam_program;
long tmp_program_size = jam_program_size;
long tmp_current_file_position = jam_current_file_position;
long tmp_current_statement_position = jam_current_statement_position;
long tmp_next_statement_position = jam_next_statement_position;
jam_program = program;
jam_program_size = program_size;
jam_current_statement_position = 0L;
jam_next_statement_position = 0L;
status = jam_init_statement_buffer(&statement_buffer, &statement_buffer_size);
if (status == JAMC_SUCCESS)
{
if (offset == NULL)
{
/*
* We will search for the first note with a specific key, and
* return only the value
*/
status = jam_seek(0L);
jam_current_file_position = 0L;
}
else
{
/*
* We will search for the next note, regardless of the key, and
* return both the value and the key
*/
status = jam_seek(*offset);
jam_current_file_position = *offset;
}
}
/*
* Get program statements and look for NOTE statements
*/
while ((!done) && (status == JAMC_SUCCESS))
{
status = jam_get_statement(statement_buffer, label_buffer);
if (status == JAMC_SUCCESS)
{
instruction = jam_get_instruction(statement_buffer);
if (instruction == JAM_NOTE_INSTR)
{
if (jam_get_note_key(statement_buffer, &key_begin, &key_end))
{
statement_buffer[key_end] = JAMC_NULL_CHAR;
if ((offset != NULL) || (jam_stricmp(
key, &statement_buffer[key_begin]) == 0))
{
if (jam_get_note_value(&statement_buffer[key_end + 1],
&value_begin, &value_end))
{
done = TRUE;
value_begin += (key_end + 1);
value_end += (key_end + 1);
statement_buffer[value_end] = JAMC_NULL_CHAR;
if (offset != NULL)
{
*offset = jam_current_file_position;
}
}
else
{
status = JAMC_SYNTAX_ERROR;
}
}
}
else
{
status = JAMC_SYNTAX_ERROR;
}
}
}
}
/*
* Copy the key and value strings into buffers provided
*/
if (done && (status == JAMC_SUCCESS))
{
if (offset != NULL)
{
/* only copy the key string if we were looking for all NOTEs */
jam_strncpy(
key, &statement_buffer[key_begin], JAMC_MAX_NAME_LENGTH);
}
jam_strncpy(value, &statement_buffer[value_begin], length);
}
jam_program = tmp_program;
jam_program_size = tmp_program_size;
jam_current_file_position = tmp_current_file_position;
jam_current_statement_position = tmp_current_statement_position;
jam_next_statement_position = tmp_next_statement_position;
jam_free_statement_buffer(&statement_buffer, &statement_buffer_size);
return (status);
}
| true |
199573e821ec5ed03f536b92e4006555942df4ec | C++ | wanggaoyang/code_skilss | /code/c++/练习/lintcode/倒数第n个结点.cpp | GB18030 | 430 | 3.609375 | 4 | [] | no_license | //еn ֻдʵַ
ListNode *nthToLast(ListNode *head, int n)
{
// write your code here
if(head==NULL)
return NULL;
ListNode *result=head;
int count=1;
while(head->next!=NULL)//¼һм
{
head=head->next;
count++;
}
for(int i=0;i<count-n;i++)
{
result=result->next;
}
return result;
}
| true |
16fa0393021ce818fc4409f26f07bff9873fdea7 | C++ | Miserlou/RJModules | /src/PitShift.cpp | UTF-8 | 2,198 | 2.640625 | 3 | [
"MIT"
] | permissive | /***************************************************/
/*! \class PitShift
\brief STK simple pitch shifter effect class.
This class implements a simple pitch shifter
using delay lines.
by Perry R. Cook and Gary P. Scavone, 1995--2019.
*/
/***************************************************/
#include "PitShift.h"
#include <cmath>
namespace stk {
PitShift :: PitShift( void )
{
delayLength_ = maxDelay - 24;
halfLength_ = delayLength_ / 2;
delay_[0] = 12;
delay_[1] = maxDelay / 2;
delayLine_[0].setMaximumDelay( maxDelay );
delayLine_[0].setDelay( delay_[0] );
delayLine_[1].setMaximumDelay( maxDelay );
delayLine_[1].setDelay( delay_[1] );
effectMix_ = 0.5;
rate_ = 1.0;
}
void PitShift :: clear()
{
delayLine_[0].clear();
delayLine_[1].clear();
lastFrame_[0] = 0.0;
}
void PitShift :: setShift( StkFloat shift )
{
if ( shift < 1.0 ) {
rate_ = 1.0 - shift;
}
else if ( shift > 1.0 ) {
rate_ = 1.0 - shift;
}
else {
rate_ = 0.0;
delay_[0] = halfLength_ + 12;
}
}
StkFrames& PitShift :: tick( StkFrames& frames, unsigned int channel )
{
#if defined(_STK_DEBUG_)
if ( channel >= frames.channels() ) {
oStream_ << "PitShift::tick(): channel and StkFrames arguments are incompatible!";
handleError( StkError::FUNCTION_ARGUMENT );
}
#endif
StkFloat *samples = &frames[channel];
unsigned int hop = frames.channels();
for ( unsigned int i=0; i<frames.frames(); i++, samples += hop )
*samples = tick( *samples );
return frames;
}
StkFrames& PitShift :: tick( StkFrames& iFrames, StkFrames& oFrames, unsigned int iChannel, unsigned int oChannel )
{
#if defined(_STK_DEBUG_)
if ( iChannel >= iFrames.channels() || oChannel >= oFrames.channels() ) {
oStream_ << "PitShift::tick(): channel and StkFrames arguments are incompatible!";
handleError( StkError::FUNCTION_ARGUMENT );
}
#endif
StkFloat *iSamples = &iFrames[iChannel];
StkFloat *oSamples = &oFrames[oChannel];
unsigned int iHop = iFrames.channels(), oHop = oFrames.channels();
for ( unsigned int i=0; i<iFrames.frames(); i++, iSamples += iHop, oSamples += oHop )
*oSamples = tick( *iSamples );
return iFrames;
}
} // stk namespace
| true |
1d0af2e9819f27282bc2a49c633b82d8829e8307 | C++ | Gratt-5r2/ZippedStream | /ZippedStream/Array/Array.h | UTF-8 | 9,122 | 2.546875 | 3 | [] | no_license | // Supported with union (c) 2018 Union team
#ifndef __UNION_ARRAY_H__
#define __UNION_ARRAY_H__
namespace Common {
template <class T>
class ArrayLocator {
T* Vector;
uint Count;
uint FullCount;
uint MemoryUsed;
uint MemoryAllocated;
uint AllocMultiplier;
uint refCrt;
protected:
void AllocArray( const uint& newCount );
void ReduceArray( const uint& newCount );
void InitArray();
public:
uint AddReference();
uint Release();
const uint GetRefCrf() const;
ArrayLocator();
T* AllocEnd( const uint& count = 1 );
T* AllocFront( const uint& count = 1 );
T* AllocAt( const uint& index, const uint& count = 1 );
void FreeEnd( const uint& count = 1 );
void FreeFront( const uint& count = 1 );
void FreeAt( const uint& index, const uint& count = 1 );
void FastFreeAt( const uint& index, const uint& count = 1 );
T& operator [] ( const uint& index );
const T& operator [] ( const uint& index ) const;
T* begin();
T* end();
const T* begin() const;
const T* end() const;
uint GetNum() const;
uint GetUsedMemory() const;
uint GetAllocatedMemory() const;
void SetLocatorMultiplier( const uint& rate );
void PrepareToReserveArray( const uint& count );
void ActivateAllocatedMemory();
void ShrinkToFit();
~ArrayLocator();
};
// A dynamic object constructor for arrays
template <class T>
struct TObjectLocator {
T refObject;
TObjectLocator() {}
TObjectLocator( const T& obj );
static void* operator new (size_t size, ArrayLocator<T>& allocator);
static void* operator new (size_t size, ArrayLocator<T>& allocator, const uint& index);
static void* operator new[]( size_t size, ArrayLocator<T>& allocator );
static void* operator new[]( size_t size, ArrayLocator<T>& allocator, const uint& index );
static void operator delete (void* mem);
static void operator delete (void* mem, ArrayLocator<T>& allocator);
static void operator delete (void* mem, ArrayLocator<T>& allocator, const uint& index);
static void operator delete[]( void* mem, ArrayLocator<T>& allocator );
static void operator delete[]( void* mem, ArrayLocator<T>& allocator, const uint& index );
};
#pragma warning(disable:4521)
// A dynamic array interface
template <class T>
class Array {
ArrayLocator<T>* Allocator;
ArrayLocator<T>& GetAllocator();
const ArrayLocator<T>& GetAllocator() const;
void* SortFunc;
public:
Array();
Array( T* copy, const uint& count = Invalid );
Array( Array& other ); // !!! Reference
Array( const Array& other ); // !!! Copy
T& Create();
T& InsertEnd( const T& obj );
T& Insert( const T& obj );
T& InsertAt( const T& obj, const uint& index );
T& InsertFront( const T& obj );
void Remove( const T& obj );
void RemoveAt( const uint& index );
void FastRemove( const T& obj );
void FastRemoveAt( const uint& index );
void RemoveAtBounds( const uint& index, const uint& count );
void Clear();
void Delete( const T& obj );
void DeleteAt( const uint& index );
void FastDelete( const T& obj );
void FastDeleteAt( const uint& index );
void DeleteAtBounds( const uint& index, const uint& count );
void DeleteData();
public:
void MergeArray( const Array& other );
void MergeArrayAt( const Array& other, const uint& index );
Array& operator += ( const T& obj );
Array& operator += ( const Array& other );
Array& operator |= ( const T& obj );
Array& operator |= ( const Array& other );
Array& operator -= ( const T& obj );
Array& operator -= ( const Array& other );
Array& operator ^= ( const T& obj );
Array& operator ^= ( const Array& other );
Array& operator = ( const Array& other );
bool operator == ( const Array& other ) const;
bool operator & ( const T& obj ) const;
bool CompareLinear( const Array& other ) const;
bool CompareInsorted( const Array& other ) const;
Array& Normalize();
void PrepareToReserveArray( const uint& count );
const T& operator[]( const uint& index ) const;
T& operator[]( const uint& index );
const T* GetSafe( const uint& index ) const;
T* GetSafe( const uint& index );
const T& GetFirst() const;
T& GetFirst();
const T& GetLast() const;
T& GetLast();
template<class O>
bool HasEqual( const O& obj ) const;
template<class O>
uint SearchEqual( const O& obj, const uint& begin = 0 ) const;
template<class O>
uint CountOfEqual( const O& obj ) const;
void ReleaseData();
T& InsertSorted( const T& obj );
void MergeArraySorted( const Array& other );
template<class O>
T& CreateSorted( const O& byObj );
template<class O>
bool HasEqualSorted( const O& obj ) const;
template<class O>
uint SearchEqualSorted( const O& obj ) const;
template<class O>
void RemoveSorted( const O& obj );
template<class O>
void DeleteSorted( const O& obj );
template<class O>
uint FindIndexForObject( const O& obj ) const;
protected:
void QuickSort( uint low, uint hight );
public:
Array& QuickSort();
void Copy( T** ppmem, const uint& index, const uint& count );
uint GetNum() const;
bool IsEmpty() const;
uint GetTypeSize() const;
void SetLocatorMultiplier( const uint& rate );
void ShrinkToFit();
T* begin();
T* end();
const T* begin() const;
const T* end() const;
const ArrayLocator<T>& GetArrayLocator() const;
virtual ~Array();
};
#pragma warning(default:4521)
#pragma warning(disable:4521)
template <class T, bool( __cdecl* FUNC )(const T&, const T&)>
class ArraySorted {
protected:
ArrayLocator<T>* Allocator;
ArrayLocator<T>& GetAllocator();
const ArrayLocator<T>& GetAllocator() const;
void* SortFunc;
public:
ArraySorted();
ArraySorted( T* copy, const uint& count = Invalid );
ArraySorted( ArraySorted& other ); // !!! Reference
ArraySorted( const ArraySorted& other ); // !!! Copy
ArraySorted( const Array<T>& other ); // !!! Copy
T& Insert( const T& obj );
template<void* LAMBDA, class O>
T& Create( const O& byObj );
template<void* LAMBDA, class O>
void Remove( const O& obj );
void Remove( const T& obj );
void RemoveAt( const uint& index );
void RemoveAtBounds( const uint& index, const uint& count );
void Clear();
template<void* LAMBDA, class O>
void Delete( const O& obj );
void Delete( const T& obj );
void DeleteAt( const uint& index );
void DeleteAtBounds( const uint& index, const uint& count );
void DeleteData();
void MergeArray( const ArraySorted& other );
void MergeArray( const Array<T>& other );
ArraySorted& operator += ( const T& obj );
ArraySorted& operator += ( const ArraySorted& other );
ArraySorted& operator |= ( const T& obj );
ArraySorted& operator |= ( const ArraySorted& other );
ArraySorted& operator -= ( const T& obj );
ArraySorted& operator -= ( const ArraySorted& other );
ArraySorted& operator ^= ( const T& obj );
ArraySorted& operator ^= ( const ArraySorted& other );
ArraySorted& operator = ( const ArraySorted& other );
ArraySorted& operator = ( const Array<T>& other );
bool operator == ( const ArraySorted& other ) const;
bool operator & ( const T& obj ) const;
bool Compare( const ArraySorted& other ) const;
ArraySorted& Normalize();
T& operator[]( const uint& index );
T* GetSafe( const uint& index );
T& GetFirst();
T& GetLast();
const T& operator[]( const uint& index ) const;
const T* GetSafe( const uint& index ) const;
const T& GetFirst() const;
const T& GetLast() const;
template<void* LAMBDA, class O>
bool HasEqual( const O& obj ) const;
bool HasEqual( const T& obj ) const;
template<void* LAMBDA, class O>
uint SearchEqual( const O& obj, const uint& begin = 0 ) const;
uint SearchEqual( const T& obj, const uint& begin = 0 ) const;
template<void* LAMBDA, class O>
uint CountOfEqual( const O& obj ) const;
uint CountOfEqual( const T& obj ) const;
void ReleaseData();
template<void* LAMBDA, class O>
uint FindIndexForObject( const O& obj ) const;
uint FindIndexForObject( const T& obj ) const;
protected:
void QuickSort( uint low, uint hight );
public:
ArraySorted& QuickSort();
void Copy( T** ppmem, const uint& index, const uint& count );
uint GetNum() const;
bool IsEmpty() const;
uint GetTypeSize() const;
void SetLocatorMultiplier( const uint& rate );
void ShrinkToFit();
T* begin();
T* end();
const T* begin() const;
const T* end() const;
const ArrayLocator<T>& GetArrayLocator() const;
virtual ~ArraySorted();
};
#pragma warning(default:4521)
}
#include "ArrayLocator.h"
#include "ObjectLocator.h"
#include "ArrayInterface.h"
#include "ArraySortedInterface.h"
#endif // __UNION_ARRAY_H__ | true |
f18c47e797ed1dc2f18a15e193ab996c9a5e8b25 | C++ | ramzimort/Pudge-Adventures | /Pudge Adventures/Component_Managers/CollisionManager.cpp | UTF-8 | 6,290 | 2.625 | 3 | [] | no_license | #include "CollisionManager.h"
#include "..\Components\GameObject.h"
#include "..\Components\Body.h"
#include "..\Components\Transform.h"
#include <glm/gtx/norm.hpp>
#include <algorithm>
#include <iostream>
Contact::Contact()
{
mBodies[0] = nullptr;
mBodies[1] = nullptr;
}
Contact::~Contact()
{
}
bool CheckCollisionCircleCircle(Shape* pShape1, Shape* pShape2, std::list<std::pair<Contact*, glm::vec2>> &Contacts);
bool CheckCollisionCircleAABB(Shape* pShape1, Shape* pShape2, std::list<std::pair<Contact*, glm::vec2>> &Contacts);
bool CheckCollisionAABBCircle(Shape* pShape1, Shape* pShape2, std::list<std::pair<Contact*, glm::vec2>> &Contacts);
bool CheckCollisionAABBAABB(Shape* pShape1, Shape* pShape2, std::list<std::pair<Contact*, glm::vec2>> &Contacts);
CollisionManager::CollisionManager()
{
CollisionFunctions[CIRCLE][CIRCLE] = CheckCollisionCircleCircle;
CollisionFunctions[CIRCLE][AABB] = CheckCollisionCircleAABB;
CollisionFunctions[AABB][CIRCLE] = CheckCollisionAABBCircle;
CollisionFunctions[AABB][AABB] = CheckCollisionAABBAABB;
}
CollisionManager::~CollisionManager()
{
for (auto c : mContacts)
delete c.first;
}
void CollisionManager::Reset()
{
for (auto c : mContacts)
delete c.first;
mContacts.clear();
}
bool CollisionManager::checkCollisionandGenerateContact(Shape * pShape1, Shape * pShape2, std::list<std::pair<Contact*, glm::vec2>>& Contacts)
{
return CollisionFunctions[pShape1->mType][pShape2->mType](pShape1, pShape2, mContacts);
}
bool CheckCollisionCircleCircle(
Shape* pShape1,
Shape* pShape2,
std::list<std::pair<Contact*, glm::vec2>> &Contacts)
{
ShapeCircle* C1 = static_cast<ShapeCircle*>(pShape1);
ShapeCircle* C2 = static_cast<ShapeCircle*>(pShape2);
glm::vec2
Center1 = C1->mpOwnerBody->mColliderCenter,
Center2 = C2->mpOwnerBody->mColliderCenter;
//Intersection!
if ((C1->mRadius + C2->mRadius)*(C1->mRadius + C2->mRadius) >= glm::distance2(Center1, Center2))
{
glm::vec2 deltaPos(0.f);
//Create a new contact and add it
Contact* pNewContact = new Contact();
pNewContact->mBodies[0] = pShape1->mpOwnerBody;
pNewContact->mBodies[1] = pShape2->mpOwnerBody;
Contacts.push_back(std::pair<Contact*,glm::vec2>(pNewContact, deltaPos));
return true;
}
return false;
}
bool CheckCollisionCircleAABB( Shape* pShape1,
Shape* pShape2,
std::list<std::pair<Contact*, glm::vec2>> &Contacts)
{
ShapeCircle* C1 = static_cast<ShapeCircle*>(pShape1);
ShapeAABB* S2 = static_cast<ShapeAABB*>(pShape2);
glm::vec2
Center1 = C1->mpOwnerBody->mColliderCenter,
Center2 = S2->mpOwnerBody->mColliderCenter;
float
L1 = Center1.x - C1->mRadius,
R1 = Center1.x + C1->mRadius,
U1 = Center1.y + C1->mRadius,
B1 = Center1.y - C1->mRadius,
L2 = Center2.x - S2->mWidth / 2.f,
R2 = Center2.x + S2->mWidth / 2.f,
U2 = Center2.y + S2->mHeight / 2.f,
B2 = Center2.y - S2->mHeight / 2.f;
// 8 different cases for CIRCLE location wrt AABB
// West
if (L1 > R2)
return false;
if (L2 > R1)
return false;
if (B1 > U2)
return false;
if (B2 > U1)
return false;
// NorthWest
if (Center1.x < L2 && Center1.y > U2)
if (glm::length2(Center1 - glm::vec2(L2, U2)) > C1->mRadius*C1->mRadius)
return false;
// Northeast
if (Center1.x > R2 && Center1.y > U2)
if (glm::length2(Center1 - glm::vec2(R2, U2)) > C1->mRadius*C1->mRadius)
return false;
// Southwest
if (Center1.x < L2 && Center1.y < B2)
if (glm::length2(Center1 - glm::vec2(L2, B2)) > C1->mRadius*C1->mRadius)
return false;
// Southeast
if (Center1.x > R2 && Center1.y < B2)
if (glm::length2(Center1 - glm::vec2(R2, B2)) > C1->mRadius*C1->mRadius)
return false;
glm::vec2 C2C1 = C1->mpOwnerBody->mPos - S2->mpOwnerBody->mPos;
float centerDistance = glm::length(C2C1);
glm::vec2 deltaPos = C2C1 / centerDistance;
deltaPos *= C1->mRadius + std::min(S2->mWidth, S2->mHeight) - centerDistance;
//Create a new contact and add itd
Contact* pNewContact = new Contact();
pNewContact->mBodies[0] = pShape1->mpOwnerBody;
pNewContact->mBodies[1] = pShape2->mpOwnerBody;
Contacts.push_back(std::pair<Contact*, glm::vec2>(pNewContact, deltaPos));
return true;
}
bool CheckCollisionAABBCircle(
Shape* pShape1,
Shape* pShape2,
std::list<std::pair<Contact*, glm::vec2>> &Contacts)
{
//Add code to invert last inserted deltaPos
return CheckCollisionCircleAABB(pShape2, pShape1, Contacts);
}
bool CheckCollisionAABBAABB(
Shape* pShape1,
Shape* pShape2,
std::list<std::pair<Contact*, glm::vec2>> &Contacts)
{
ShapeAABB* S1 = static_cast<ShapeAABB*>(pShape1);
ShapeAABB* S2 = static_cast<ShapeAABB*>(pShape2);
float L1 = S1->mpOwnerBody->mColliderCenter.x - S1->mWidth / 2.f,
R1 = S1->mpOwnerBody->mColliderCenter.x + S1->mWidth / 2.f,
U1 = S1->mpOwnerBody->mColliderCenter.y + S1->mHeight / 2.f,
B1 = S1->mpOwnerBody->mColliderCenter.y - S1->mHeight / 2.f,
L2 = S2->mpOwnerBody->mColliderCenter.x - S2->mWidth / 2.f,
R2 = S2->mpOwnerBody->mColliderCenter.x + S2->mWidth / 2.f,
U2 = S2->mpOwnerBody->mColliderCenter.y + S2->mHeight / 2.f,
B2 = S2->mpOwnerBody->mColliderCenter.y - S2->mHeight / 2.f;
if (L1 > R2)
return false;
if (L2 > R1)
return false;
if (B1 > U2)
return false;
if (B2 > U1)
return false;
glm::vec2 deltaPos(0.0f);
bool North = false,
East = false,
West = false,
South = false;
//Check Collision Directions:
if (B1 <= U2 && B2 <= U1 && B1 >= B2 && U1 >= U2)
North = true;
else if (B2 <= U1 && B1 <= U2 && B2 >= B1 && U2 >= U1)
South = true;
if (R1 >= L2 && R1 <= R2 && L1 <= L2 && L1 <= R2)
West = true;
else if (R2 >= L1 && R2 <= R1 && L2 <= L1 && L2 <= R1)
East = true;
// Modify offsets
if (North)
deltaPos.y += U2 - B1;
else if (South)
deltaPos.y -= U1 - B2;
if (West)
deltaPos.x -= R1 - L2;
else if (East)
deltaPos.x += R2 - L1;
if (North && West || North && East || South && West || South && East)
{
if (glm::abs(deltaPos.x) > glm::abs(deltaPos.y))
deltaPos.x = 0.f;
else
deltaPos.y = 0.f;
}
//Check y collision?
//Create a new contact and add itd
Contact* pNewContact = new Contact();
pNewContact->mBodies[0] = pShape1->mpOwnerBody;
pNewContact->mBodies[1] = pShape2->mpOwnerBody;
Contacts.push_back(std::pair<Contact*, glm::vec2>(pNewContact, deltaPos));
return true;
} | true |
6768bf38cfe37c099278f509cca4a5a0bb1c9032 | C++ | ricky-flyguy/RMZ_2014 | /Game2014/Classes/Player.cpp | UTF-8 | 1,105 | 2.828125 | 3 | [] | no_license |
#include "Player.h"
Player::Player(void)
{
screenSize = Director::getInstance()->getVisibleSize();
this->init();
}
bool Player::init()
{
this->velocity = new Point(2, 5);
//velocity->normalize();
return true;
}
Player* Player::create(const std::string &filename, Point* pos)
{
Player* p = new Player();
if (p && p->initWithFile(filename))
{
// Set auto release.
p->autorelease();
// Set Scale
p->setScale(0.25f);
// Set Position
p->setPosition(*pos);
return p;
}
CC_SAFE_DELETE(p);
return NULL;
}
void Player::update(float dt)
{
//this->setPosition(ccp(this->getPosition().x + velocity->x, this->getPosition().y + velocity->y));
clamp();
}
void Player::clamp()
{
if (this->getPosition().x - this->getBoundingBox().size.width/2 <= 0 || this->getPosition().x + this->getBoundingBox().size.width/2 >= screenSize.width)
velocity->x = -velocity->x;
if (this->getPosition().y - this->getBoundingBox().size.height/2 <= 0 || this->getPosition().y + this->getBoundingBox().size.height/2 >= screenSize.height)
velocity->y = -velocity->y;
}
Player::~Player(void)
{
}
| true |
721f148c37f01e30d091074055bd27937be45487 | C++ | chancelee/Safe | /safe/VirusManage.cpp | GB18030 | 2,542 | 2.734375 | 3 | [] | no_license | #include "stdafx.h"
#include "VirusManage.h"
CVirusManage::CVirusManage()
{
}
CVirusManage::~CVirusManage()
{
ClearVirusLibData();
ClearProcessLibData();
}
//ȡز
DWORD CVirusManage::LoadVirusLibData()
{
HANDLE pFile = nullptr;
pFile = CreateFile(GetProgramDir() + TEXT("VirusLib.dat"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (pFile == (HANDLE)-1)return 0;
DWORD nSize = GetFileSize((PHANDLE)pFile, 0);
DWORD nReadSize = 0;
m_dwVirusCount = nSize / sizeof(VIRUSINFO);
m_pVirusLib = new VIRUSINFO[m_dwVirusCount];
ReadFile(pFile, (LPVOID)m_pVirusLib, nSize, &nReadSize, NULL);
CloseHandle(pFile);
return m_dwVirusCount;
}
//ȡϢ
VOID CVirusManage::GetVirusLib(PVIRUSINFO &nVIRUSINFO)
{
memcpy_s(nVIRUSINFO, sizeof(VIRUSINFO)*m_dwVirusCount, m_pVirusLib, sizeof(VIRUSINFO)*m_dwVirusCount);
}
//д
VOID CVirusManage::SetVirusLib(PVIRUSINFO &nVIRUSINFO, DWORD nCount)
{
FILE *pFile = nullptr;
fopen_s(&pFile, GetProgramDir() + "VirusLib.dat", "wb");
m_dwVirusCount = fwrite(nVIRUSINFO, sizeof(VIRUSINFO), nCount, pFile);
fclose(pFile);
}
//رղ
VOID CVirusManage::ClearVirusLibData()
{
if (m_pVirusLib != nullptr)
{
delete[] m_pVirusLib;
}
m_pVirusLib = nullptr;
m_dwVirusCount = 0;
}
//ȡ
DWORD CVirusManage::LoadProcessLibData()
{
HANDLE pFile = nullptr;
pFile = CreateFile(GetProgramDir() + TEXT("ProcessLib.dat"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (pFile == (HANDLE)-1)return 0;
DWORD nSize = GetFileSize((PHANDLE)pFile, 0);
DWORD nReadSize = 0;
m_dwProcessCount = nSize / sizeof(VIRUSINFO);
m_pProcessLib = new VIRUSINFO[m_dwProcessCount];
ReadFile(pFile, (LPVOID)m_pProcessLib, nSize, &nReadSize, NULL);
CloseHandle(pFile);
return m_dwProcessCount;
}
//ȡϢ
VOID CVirusManage::GetProcessLib(PVIRUSINFO &nVIRUSINFO)
{
memcpy_s(nVIRUSINFO, sizeof(VIRUSINFO)*m_dwProcessCount, m_pProcessLib, sizeof(VIRUSINFO)*m_dwProcessCount);
}
//д
VOID CVirusManage::SetProcessLib(PVIRUSINFO &nVIRUSINFO, DWORD nCount)
{
FILE *pFile = nullptr;
fopen_s(&pFile, GetProgramDir() + "ProcessLib.dat", "wb");
m_dwProcessCount = fwrite(nVIRUSINFO, sizeof(VIRUSINFO), nCount, pFile);
fclose(pFile);
}
//رհ
VOID CVirusManage::ClearProcessLibData()
{
if (m_pProcessLib != nullptr)
{
delete[] m_pProcessLib;
}
m_pProcessLib = nullptr;
m_dwProcessCount = 0;
}
| true |
fe2f078e92fed89035af2f248b3120f1f358f0a6 | C++ | olicity-wong/Algorithm | /剑指offer/4_1.cpp | GB18030 | 679 | 3.359375 | 3 | [] | no_license | /*
ǴҵµʴϽ/½ǿʼ
ʣµľǴСжϣɾɾ
*/
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int num[100][100];
int n;
int result;
cin >> n;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++){
cin >> num[i][j];
}
cin >> result;
int row = 0;
int columns = n-1;
while(num[row][columns]!=result && row < n-1 && columns > 0){
if(num[row][columns] > result){
columns--;
}
if(num[row][columns] < result){
row++;
}
}
if(num[row][columns] == result){
cout << "true" << endl;
}
else{
cout << "false" << endl;
}
return 0;
}
| true |
b4c4eec0435ba03dbf1ae9c64bb6596425f9ca17 | C++ | greg2010/CC3K | /src/ConcreteVampire.cc | UTF-8 | 305 | 2.53125 | 3 | [] | no_license | #include "ConcreteVampire.h"
const int defaultHP = 50;
const int defaultAtk = 25;
const int defaultDef = 25;
ConcreteVampire::ConcreteVampire(std::pair<int,int> coords) : Enemy{defaultHP, defaultAtk, defaultDef, coords} { }
SubjectType ConcreteVampire::getType() {
return SubjectType::Vampire;
}
| true |
da5b1e11729169bb85da2b5835825c8cd7c15d55 | C++ | dfpreston/Clue-less-Colonel-Mustard-group- | /Clueless_cppDesignIdeas/Clueless/CardDeck.cpp | UTF-8 | 13,838 | 2.734375 | 3 | [] | no_license | ////////////////////////////////////////////////////////////////////////////////
///
/// Clue-Less
///
////////////////////////////////////////////////////////////////////////////////
///
/// \file CardDeck.cpp
/// \brief
///
/// \date 26 Feb 2019 1205
///
/// \note None
///
////////////////////////////////////////////////////////////////////////////////
#include "CardDeck.h"
#include "Card.h"
#include "Player.h"
#include "SolutionCardSet.h"
#include "CluelessEnums.h" //for PersonType, WeaponType, RoomType enum use
#include "mersenneTwister.h"
#include <math.h> //for std::floor use
#include <iostream> //for std::cout use
#include <stdexcept> //for std::logic_error use
//------------------------------------------------------------------------------
// Constructors / Destructor
//------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// \brief Default constructor
/// \param None
/// \return None
/// \throw None
/// \note None
////////////////////////////////////////////////////////////////////////////////
CardDeck::CardDeck()
: _caseFile( nullptr )
{
createPersonCards();
createWeaponCards();
createRoomCards();
chooseCaseFileSet();
} //end routine constructor
////////////////////////////////////////////////////////////////////////////////
/// \brief Destructor
/// \param None
/// \return None
/// \throw None
/// \note None
////////////////////////////////////////////////////////////////////////////////
CardDeck::~CardDeck()
{
//delete cards
std::set<Card*>::iterator pcard_iter( _personCards.begin() );
Card* curr_pcard( nullptr );
while( _personCards.end() != pcard_iter )
{
curr_pcard = *pcard_iter;
_personCards.erase( pcard_iter );
delete curr_pcard;
pcard_iter = _personCards.begin();
}
std::set<Card*>::iterator wcard_iter( _weaponCards.begin() );
Card* curr_wcard( nullptr );
while( _weaponCards.end() != wcard_iter )
{
curr_wcard = *wcard_iter;
_weaponCards.erase( wcard_iter );
delete curr_wcard;
wcard_iter = _weaponCards.begin();
}
std::set<Card*>::iterator rcard_iter( _roomCards.begin() );
Card* curr_rcard( nullptr );
while( _roomCards.end() != rcard_iter )
{
curr_rcard = *rcard_iter;
_roomCards.erase( rcard_iter );
delete curr_rcard;
rcard_iter = _roomCards.begin();
}
//case file
delete _caseFile;
_caseFile = nullptr;
} //end routine destructor
//------------------------------------------------------------------------------
// Game Setup Methods
//------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// \brief
/// \param None
/// \return None
/// \throw None
/// \note None
////////////////////////////////////////////////////////////////////////////////
void
CardDeck::createPersonCards()
{
using clueless::PersonType;
_personCards.insert( new PersonCard(PersonType::MISS_SCARLET) );
_personCards.insert( new PersonCard(PersonType::COLONEL_MUSTARD) );
_personCards.insert( new PersonCard(PersonType::MRS_WHITE) );
_personCards.insert( new PersonCard(PersonType::MR_GREEN) );
_personCards.insert( new PersonCard(PersonType::MRS_PEACOCK) );
_personCards.insert( new PersonCard(PersonType::PROFESSOR_PLUM) );
std::set<Card*>::iterator card_iter( _personCards.begin() );
while( _personCards.end() != card_iter )
{
//add reference to undealt card stack
_undealtCards.insert( *card_iter );
++card_iter;
} //end while (more room cards)
} //end routine createPersonCards()
////////////////////////////////////////////////////////////////////////////////
/// \brief
/// \param None
/// \return None
/// \throw None
/// \note None
////////////////////////////////////////////////////////////////////////////////
void
CardDeck::createWeaponCards()
{
using clueless::WeaponType;
_weaponCards.insert( new WeaponCard(WeaponType::LEAD_PIPE) );
_weaponCards.insert( new WeaponCard(WeaponType::KNIFE) );
_weaponCards.insert( new WeaponCard(WeaponType::ROPE) );
_weaponCards.insert( new WeaponCard(WeaponType::CANDLESTICK) );
_weaponCards.insert( new WeaponCard(WeaponType::REVOLVER) );
_weaponCards.insert( new WeaponCard(WeaponType::WRENCH) );
std::set<Card*>::iterator card_iter( _weaponCards.begin() );
while( _weaponCards.end() != card_iter )
{
//add reference to undealt card stack
_undealtCards.insert( *card_iter );
++card_iter;
} //end while (more room cards)
} //end routine createWeaponCards()
////////////////////////////////////////////////////////////////////////////////
/// \brief
/// \param None
/// \return None
/// \throw None
/// \note None
////////////////////////////////////////////////////////////////////////////////
void
CardDeck::createRoomCards()
{
using clueless::RoomType;
_roomCards.insert( new RoomCard(RoomType::STUDY) );
_roomCards.insert( new RoomCard(RoomType::HALL) );
_roomCards.insert( new RoomCard(RoomType::LOUNGE) );
_roomCards.insert( new RoomCard(RoomType::LIBRARY) );
_roomCards.insert( new RoomCard(RoomType::BILLIARD_ROOM) );
_roomCards.insert( new RoomCard(RoomType::DINING_ROOM) );
_roomCards.insert( new RoomCard(RoomType::CONSERVATORY) );
_roomCards.insert( new RoomCard(RoomType::BALLROOM) );
_roomCards.insert( new RoomCard(RoomType::KITCHEN) );
std::set<Card*>::iterator card_iter( _roomCards.begin() );
while( _roomCards.end() != card_iter )
{
//add reference to undealt card stack
_undealtCards.insert( *card_iter );
++card_iter;
} //end while (more room cards)
} //end routine createRoomCards()
////////////////////////////////////////////////////////////////////////////////
/// \brief
/// \param None
/// \return None
/// \throw None
/// \note None
////////////////////////////////////////////////////////////////////////////////
void
CardDeck::chooseCaseFileSet()
{
//choose one card from each category
PersonCard* person( (PersonCard*)chooseCard(&_personCards) );
WeaponCard* weapon( (WeaponCard*)chooseCard(&_weaponCards) );
RoomCard* room( (RoomCard*)chooseCard(&_roomCards) );
//copy into case file
_caseFile = new SolutionCardSet(*person, *weapon, *room);
std::cout << "Case File... " << _caseFile->report().str() << "\n\n";
//remove from undealt collection
removeCardFromUndealt( person );
removeCardFromUndealt( weapon );
removeCardFromUndealt( room );
} //end routine chooseCaseFileSet()
////////////////////////////////////////////////////////////////////////////////
/// \brief Chooses card from specified container with uniform random draw.
/// \param set<Card>: collection of cards
/// \return Card: choosen card
/// \throw
/// - INSUFFICIENT_DATA when empty collection of cards
/// \note None
////////////////////////////////////////////////////////////////////////////////
void
CardDeck::setup(
std::list<Player*>* players)
{
std::list<Player*>::const_iterator player_iter( (*players).begin() );
Card* chosen_card( nullptr );
while( areAnyCardsUndealt() )
{
//deal card from undealt to receiving player (incl remove card from undealt)
dealCard( *player_iter );
//cycle to next player
player_iter = determineNextPlayer(players, player_iter);
} //end while (undealt cards)
} //end routine setup()
////////////////////////////////////////////////////////////////////////////////
/// \brief Chooses card from specified container with uniform random draw.
/// \param set<Card>: collection of cards
/// \return Card: choosen card
/// \throw
/// - INSUFFICIENT_DATA when empty collection of cards
/// \note None
////////////////////////////////////////////////////////////////////////////////
Card*
CardDeck::chooseCard(
std::set<Card*>* cards) //i - cards to choose amongst
const
{
Card* choice( nullptr );
if( cards->empty() ) //no cards from which to choose
{
std::ostringstream msg;
msg << "CardDeck::chooseCard()\n"
<< " INSUFFICIENT_DATA\n"
<< " no cards from which to choose";
throw std::logic_error( msg.str() );
}
else if( 1 == cards->size() )
{
//only one choice
choice = *(cards->begin());
}
else //more than one card
{
//create position based on floor of random draw in [0, num cards)
size_t zero_based_pos( size_t(std::floor( MersenneTwister::drawReal2(0, (double)(cards->size())) )) );
std::set<Card*>::const_iterator card_iter( cards->begin() );
for(size_t pos_index(0);
pos_index < zero_based_pos;
++pos_index)
{
++card_iter;
}
choice = *card_iter;
}
return choice;
} //end routine chooseCard()
const Card*
CardDeck::chooseCard(
std::set<const Card*>* cards) //i - cards to choose amongst
const
{
const Card* choice( nullptr );
if( cards->empty() ) //no cards from which to choose
{
std::ostringstream msg;
msg << "CardDeck::chooseCard()\n"
<< " INSUFFICIENT_DATA\n"
<< " no cards from which to choose";
throw std::logic_error( msg.str() );
}
else if( 1 == cards->size() )
{
//only one choice
choice = *(cards->begin());
}
else //more than one card
{
//create position based on floor of random draw in [0, num cards)
size_t zero_based_pos( size_t(std::floor( MersenneTwister::drawReal2(0, (double)(cards->size())) )) );
std::set<const Card*>::const_iterator card_iter( cards->begin() );
for(size_t pos_index(0);
pos_index < zero_based_pos;
++pos_index)
{
++card_iter;
}
choice = *card_iter;
}
return choice;
} //end routine chooseCard()
////////////////////////////////////////////////////////////////////////////////
/// \brief Removes specified card from undealt cards collection.
/// \param Card: card to remove
/// \return None
/// \throw
/// - INCONSISTENT_DATA when specified card not found
/// \note None
////////////////////////////////////////////////////////////////////////////////
void
CardDeck::removeCardFromUndealt(
const Card* card) //i - card to remove
{
std::set<const Card*>::iterator card_iter( _undealtCards.find(card) );
if( _undealtCards.end() != card_iter ) //found card
{
_undealtCards.erase( card_iter );
}
else //card not found
{
std::ostringstream msg;
msg << "CardDeck::removeCardFromUndealt()\n"
<< " INSUFFICIENT_DATA\n"
<< " card \'" << card->getName() << "\' not found in undealt set";
throw std::logic_error( msg.str() );
}
} //end routine removeCardFromUndealt()
////////////////////////////////////////////////////////////////////////////////
/// \brief
/// \param None
/// \return None
/// \throw None
/// \note None
////////////////////////////////////////////////////////////////////////////////
const Card*
CardDeck::dealCard(
Player* player) //io- player to whom card will be dealt
{
const Card* card( nullptr );
if( 0 == _undealtCards.size() )
{
std::ostringstream msg;
msg << "CardDeck::dealCard()\n"
<< " INSUFFICIENT_DATA\n"
<< " no undealt cards in deck";
throw std::logic_error( msg.str() );
}
//uniform random draw of card
card = chooseCard( &_undealtCards );
player->addCardToHand( card );
//remove reference from undealt card collection
removeCardFromUndealt( card );
return card; //dealt
} //end routine dealCard()
////////////////////////////////////////////////////////////////////////////////
/// \brief Determines next player given collection of players and current player.
/// \param set<Player*>: all players
/// \param set<Player*>::iterator: current player
/// \return set<Player*>::iterator: next player
/// \throw None
/// \note None
////////////////////////////////////////////////////////////////////////////////
std::list<Player*>::const_iterator
CardDeck::determineNextPlayer(
const std::list<Player*>* const players, //i -
std::list<Player*>::const_iterator curr_player_iter)
{
std::list<Player*>::const_iterator next_player_iter( curr_player_iter );
//increment iterator
++next_player_iter;
//if iterator represents end of collection
if( (*players).end() == next_player_iter )
{
//cycle back to first player
next_player_iter = (*players).begin();
}
return next_player_iter;
} //end routine determineNextPlayer()
//------------------------------------------------------------------------------
// Accessors and Mutators
//------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// \brief Reports contents of Case File (solution).
/// \param None
/// \return ostringstream: text report
/// \throw None
/// \note None
////////////////////////////////////////////////////////////////////////////////
std::ostringstream
CardDeck::reportCaseFile()
const
{
return _caseFile->report();
} //end routine reportCaseFile()
//------------------------------------------------------------------------------
// Additional Member Functions
//------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// \brief
/// \param None
/// \return None
/// \throw None
/// \note None
////////////////////////////////////////////////////////////////////////////////
bool
CardDeck::doesAccusationMatchCaseFile(
const SolutionCardSet& accusation) //i - accusation to compare with case file
const
{
return( *_caseFile == accusation );
} //end routine doesAccusationMatchCaseFile()
| true |
9b6cfcc8f90734786fa35b3070f6126ab9aaa298 | C++ | AzJezebel/GameEngineJVK | /EngineEditor/sources/ECS/EntityManager.cpp | UTF-8 | 933 | 3.234375 | 3 | [] | no_license | #include "EntityManager.h"
#include <cassert>
EntityManager::EntityManager()
{
for (Entity entity = 0; entity < MAX_ENTITIES; ++entity)
{
m_availableEntities.push(entity);
}
}
Entity EntityManager::CreateEntity()
{
assert(m_livingEntityCount < MAX_ENTITIES && "Too many entities in existence.");
Entity id = m_availableEntities.front();
m_availableEntities.pop();
++m_livingEntityCount;
return id;
}
void EntityManager::DestroyEntity(Entity entity)
{
assert(entity < MAX_ENTITIES && "Entity out of range.");
m_signatures[entity].reset();
m_availableEntities.push(entity);
--m_livingEntityCount;
}
void EntityManager::SetSignature(Entity entity, Signature signature)
{
assert(entity < MAX_ENTITIES && "Entity out of range.");
m_signatures[entity] = signature;
}
Signature EntityManager::GetSignature(Entity entity)
{
assert(entity < MAX_ENTITIES && "Entity out of range.");
return m_signatures[entity];
}
| true |
8bdaa26ba92ee54e0ece41f0d465a50f6c543a3c | C++ | lorenzomoulin/Programacao-Competitiva | /URI/matematica/1307.cpp | UTF-8 | 647 | 2.765625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
ull gcd(ull a, ull b){ return (b == 0) ? a : gcd(b, a % b);}
int main(){
int t;
cin >> t;
int cases = 1;
while(t--){
string s;
cin >> s;
bitset<32> bs(s);
unsigned long long a = bs.to_ullong();
cin >> s;
bs = bitset<32>(s);
unsigned long long b = bs.to_ullong();
if(gcd(a, b) != 1ULL)
cout << "Pair #" << cases << ": All you need is love!\n";
else
cout << "Pair #" << cases << ": Love is not all you need!\n";
cases++;
}
return 0;
}
| true |
3425e85b059d2ea0ae018af52f5434074a4fde97 | C++ | Subhash703/CP_CipherSchools | /Assignment_1/Que3.cpp | UTF-8 | 2,403 | 4.09375 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
//Search in a row wise and column wise sorted matrix
/*
mat[4][4] = { {10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};
*/
int binarySearch(vector<int> v, int start, int end, int x) // Binary Search O(log(n))
{
while (start <= end)
{
int mid = start + (end - start) / 2;
if (v[mid] == x)
{
return mid;
}
else if (v[mid] < x)
{
start = mid + 1;
}
else
{
end = mid - 1;
}
}
return -1;
}
pair<int, int> findElementInSortedMatrix(vector<vector<int>> &vec, int ele)
{
// Bruteforce is to put 2 for loops and find the element in the matrix,
// It's not efficient to find that because it will take : O(N*M) space
//Because the array is sorted, we can take benefit of it and apply binary search on some places
pair<int, int> result;
for (int col = 0; col < vec.size(); col++)
{
if (vec[col][0] == ele)
{
result.first = col;
result.second = 0;
return result;
}
if (vec[col][0] > ele)
{
int index = binarySearch(vec[col - 1], 0, vec[0].size() - 1, ele);
if (index == -1)
{
result.first = -1;
result.second = -1;
return result;
}
else
{
result.first = col - 1;
result.second = index;
}
}
else if (col == vec.size() - 1)
{
int index = binarySearch(vec[col], 0, vec[0].size() - 1, ele);
if (index == -1)
{
result.first = -1;
result.second = -1;
return result;
}
else
{
result.first = col - 1;
result.second = index;
}
}
}
return result;
}
int main()
{
vector<vector<int>> arr = {{10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};
pair<int, int> res = findElementInSortedMatrix(arr, 50);
cout << "(" << res.first << "," << res.second << ")";
return 0;
} | true |
cbf5c13532584e74975dfce1adf9c49e1a1339d6 | C++ | MenglaiWang/Leetcode | /338. Counting Bits.cpp | UTF-8 | 513 | 3.0625 | 3 | [] | no_license | class Solution {
public:
int count(int n){
int count = 0;
while(n){
count++;
n = n&(n-1);
}
return count;
}
vector<int> countBits(int num) {
if(num < 0) return vector<int>();
std::vector<int> result(num+1,0);
for(int i = 1; i <= num; i++ ){
if(result[i] <=0){
result[i] = count(i);
int j = i<<1;
while(j <= num){
result[j]=result[i];
j= (j<<1);
}
}
}
return result;
}
}; | true |
0858b26f0b9e873442e1e57e3bc77bf6854e2498 | C++ | orsanawwad/APEX | /AP-MS2/POSIXSockets.h | UTF-8 | 1,937 | 3.015625 | 3 | [] | no_license | #ifndef AP_MS2_POSIXSOCKETS_H
#define AP_MS2_POSIXSOCKETS_H
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cerrno>
#include <iostream>
#include <string>
#include "string.h"
#include <system_error>
#include <stdexcept>
namespace posix_sockets
{
class timeout_exception : public std::runtime_error {
public:
timeout_exception(const char *msg);
timeout_exception(const std::string msg);
};
class illegal_state_exception : public std::logic_error {
public:
illegal_state_exception(const std::string msg);
};
// struct defining general socket, with general operations (open and close)
// opening is done in the constructor.
// the socket is not automatically closed in the destructor so that the object
// can be passed as a parameter (possibly to another thread)
struct TCPSocket {
int sock_fd;
TCPSocket();
TCPSocket(int open_sock_fd);
void close();
void setTimeout(int sec, int usec = 0);
};
class TCPClient {
TCPSocket sock;
public:
// It makes sense to creates another constructor that
// will create a client from scratch
TCPClient(const TCPSocket sock);
// you should definitely use your own logic here
// suggestions are - read_until (char), read_min(int)
// read_line, etc.
// you can obviously define a write (or send) method
std::string read(int n);
long readLine(std::string &bufferLine);
long sendMessage(std::string &message);
void setTimeout(int sec, int usec = 0);
void close();
};
class TCPServer {
TCPSocket sock;
public:
TCPServer(int port);
void listen(int maxAllowedListens);
void setTimeout(int sec, int usec = 0);
TCPClient accept();
void close();
};
}
#endif //AP_MS2_POSIXSOCKETS_H
| true |
8c8255ca4f430966e06f8d808756ae49321df52d | C++ | codacy-badger/mqtt_mosquitto | /mqtt.cpp | UTF-8 | 3,439 | 2.59375 | 3 | [] | no_license | #include "mqtt.h"
void MQTT_mosquitto::my_message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message)
{
puts("void my_message_callback()");
if(message->payloadlen){
printf("%s %s\n", message->topic, message->payload);
}else{
printf("%s (null)\n", message->topic);
}
fflush(stdout);
std::string rec = (char*)(message->payload);
if(rec == "EXIT")
{
puts("EXIT JEST");
mosquitto_disconnect(mosq);
}
}
void MQTT_mosquitto::my_connect_callback(struct mosquitto *mosq, void *userdata, int result)
{
puts("my_connect_callback()");
int i;
if(!result){
/* Subscribe to broker information topics on successful connect. */
mosquitto_subscribe(mosq, NULL, "iDom/#", 2);
}else{
fprintf(stderr, "Connect failed\n");
}
}
void MQTT_mosquitto::my_subscribe_callback(struct mosquitto *mosq, void *userdata, int mid, int qos_count, const int *granted_qos)
{
puts("my_subscribe_callback()");
int i;
printf("Subscribed (mid: %d): %d", mid, granted_qos[0]);
for(i=1; i<qos_count; i++){
printf(", %d", granted_qos[i]);
}
printf("\n");
}
void MQTT_mosquitto::my_log_callback(struct mosquitto *mosq, void *userdata, int level, const char *str)
{
puts("my_log_callback()");
/* Pring all log messages regardless of level. */
printf("%s\n", str);
}
MQTT_mosquitto::MQTT_mosquitto(const std::string& username,
const std::string& host,
int port,
int keepalive,
bool clean_session): _host(host),
_port(port),
_keepalive(keepalive),
_clean_session(clean_session)
{
puts("MQTT_mosquitto::MQTT_mosquitto() start");
mosquitto_lib_init();
_mosq = mosquitto_new(username.c_str(), clean_session, NULL);
if(!_mosq){
fprintf(stderr, "Error: Out of memory.\n");
throw "cannot create MQTT";
}
mosquitto_log_callback_set(_mosq, my_log_callback);
mosquitto_connect_callback_set(_mosq, my_connect_callback);
mosquitto_message_callback_set(_mosq, my_message_callback);
mosquitto_subscribe_callback_set(_mosq, my_subscribe_callback);
if(mosquitto_connect(_mosq, _host.c_str(), _port, _keepalive)){
fprintf(stderr, "Unable to connect.\n");
throw "cannot connect to MQTT broker";
}
puts("MQTT_mosquitto::MQTT_mosquitto() end");
}
MQTT_mosquitto::~MQTT_mosquitto()
{
puts("MQTT_mosquitto::~MQTT_mosquitto() start");
mosquitto_destroy(_mosq);
mosquitto_lib_cleanup();
puts("MQTT_mosquitto::~MQTT_mosquitto() end");
}
int MQTT_mosquitto::publish(const std::string &topic, const std::string &msg, int qos)
{
puts("MQTT_mosquitto::publish() start");
std::lock_guard <std::mutex> lock(_publish_mutex);
mosquitto_publish(_mosq, NULL, topic.c_str(), msg.size(), msg.c_str(), qos, false);
puts("MQTT_mosquitto::publish() end");
}
void MQTT_mosquitto::subscribe(const std::string &topic)
{
mosquitto_loop_forever(_mosq, -1, 1);
}
void MQTT_mosquitto::disconnect()
{
puts("MQTT_mosquitto::disconnect() start");
mosquitto_disconnect(_mosq);
puts("MQTT_mosquitto::disconnect() end");
}
| true |
2ee7ab519e8e546062bcc067067892c7ef924a1f | C++ | jackeylove20XX/Cstudy | /algorithm/cs.cpp | UTF-8 | 727 | 3.328125 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
void count_sort(vector<int>&v,int k)
{
int max_v = INT_MIN;
for (int i = 0; i < k; i++) //get max value
{
if (v[i] > max_v)
{
max_v = v[i];
}
}
vector<int>b(max_v+1,0);
for (int i = 0; i <k; i++) //count
{
b[v[i]]++;
}
/*for (int i=1;i<=max_v;i++)
{
b[i] += b[i - 1];
}*/
int l = 0,r=0;
while(l<=max_v)
{
if (b[l] != 0)
{
v[r] = l;
r++;
b[l]--;
}
else
{
l++;
}
}
}
int main()
{
vector<int> v = { 2,5,3,0,2,3,0,3 };
int n = v.size();
count_sort(v,n);
for (int i = 0; i < n; i++)
{
cout << v[i] ;
}
cout << endl;
system("pause");
} | true |
dd13966b6d48d0734650108c0185372537a02f74 | C++ | fast01/axon | /src/util/log.cpp | UTF-8 | 1,394 | 2.828125 | 3 | [] | no_license | #include "util/log.hpp"
#include <unistd.h>
#include <cstring>
#include <cstdarg>
using namespace axon::util;
Log& Log::get_instance() {
static Log instance;
return instance;
}
void Log::log(const char* fn, int ln, LogLevel level, const char* msg, ...) {
va_list args;
va_start(args, msg);
std::string log = make_string(fn, ln, level, msg, args);
va_end(args);
fprintf(stdout, "%s", log.c_str());
fflush(stdout);
}
std::string Log::make_string(const char* fn, int ln, LogLevel level, const char* msg, va_list args) {
const size_t MAX_BUFFER_SIZE = 10240;
const char* levelText[] = { "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "UNKNOWN" };
time_t t = time(NULL);
struct tm local_tm;
localtime_r(&t, &local_tm);
char timestr[30];
strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", &local_tm);
char buffer[MAX_BUFFER_SIZE];
size_t len = 0;
int sz = 0;
sz = snprintf(buffer, MAX_BUFFER_SIZE - len, "[%s %s] ", timestr, levelText[level]);
if (sz >= 0) len += sz;
sz = vsnprintf(buffer + len, MAX_BUFFER_SIZE - len, msg, args);
if (sz >= 0) len += sz;
const char* fnbase= strrchr(fn, '/');
if (fnbase != NULL)
fn = fnbase + 1;
sz = snprintf(buffer + len, MAX_BUFFER_SIZE - len, " [%s:%d @%d]\n", fn, ln, getpid());
if (sz >= 0) len += sz;
return std::string(buffer);
}
| true |
8ff709f6adf0382a9159ffbf6fead049f436c48c | C++ | lukasz-borowka/Saper-remake | /Saper remake/GFX/GFX.cpp | UTF-8 | 492 | 3.1875 | 3 | [] | no_license | #include "GFX.h"
int Window_Width = 0, Window_Height = 0;
/*
surface surface to draw the point on
int x x pos of the point
int y y pos of the point
Uint32 color color of the point
*/
void GFX(SDL_Surface * surface, int x, int y, Uint32 color)
{
if (x > -1 & y > -1 & x < Window_Width & y < Window_Height)
{
Uint32 * p = (Uint32 *)surface->pixels + y * surface->w + x;
*p = color;
}
}
//
//GFX SETUP:
void GFX_Setup(int w, int h)
{
Window_Width = w;
Window_Height = h;
} | true |
67f4457ebd157802006582390fc3065998de8b90 | C++ | amos42/AgeLib | /src/AGE_GRP/TILE.cpp | UTF-8 | 3,162 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | /*#################################################################
-------------------------------------------------------------------
AGE (Ver 1.0)
(* =================== *)
Amos Game Engine
Author : Chu, Kyong-min( Amos )
Date : 1997/02/08
C Compiler : WATCOM 11.0
Assembler : WASM 11.0
-------------------------------------------------------------------
###################################################################*/
#include <stdio.h>
#include <string.h>
#include "age_grp.h"
typedef struct {
CHAR Header[20];
LONG Ver;
LONG Count;
LONG Width, Height;
} TIL_HEADER;
/****************
TILE의 생성자
*****************/
TILE :: TILE( void )
{
Count = 0;
Width = Height = 0;
Bitmap = NULL;
}
/****************
TILE의 생성자
*****************/
TILE :: TILE( STRING FileName )
{
Count = 0;
Width = Height = 0;
Bitmap = NULL;
Load( FileName );
}
/****************
TILE의 소멸자
*****************/
TILE :: ~TILE()
{
Clear();
}
/****************
TILE을 지운다.
*****************/
void TILE :: Clear( void )
{
Count = 0;
Width = Height = 0;
if( Bitmap ) delete Bitmap;
Bitmap = 0;
}
BOOL TILE :: Load( STRING FileName )
{
Clear();
char *res;
if( !_Resource.Load( FileName, &res ) ) return( FALSE );
char *temp = res;
TIL_HEADER *th = (TIL_HEADER *)res;
res += sizeof(TIL_HEADER);
if( strcmp( th->Header, "Amos Tile File;" ) ) return( 2 );
Count = th->Count;
Width = th->Width;
Height = th->Height;
int TileSize = Count * Width * Height;
Bitmap = new CHAR[ TileSize ];
memcpy( Bitmap, res, TileSize );
free( temp );
return( TRUE );
}
void TILE :: Put( INT X, INT Y, INT Index )
{
if( Index >= Count ) return;
int width = Width;
int height = Height;
if( width == 0 || height == 0 ) return;
char *ImgPtr = Bitmap + width * height * Index;
if( Y > _Clip.EndY ) return;
if( Y < _Clip.StartY ){
height -= _Clip.StartY - Y;
ImgPtr += (_Clip.StartY - Y) * width;
Y = _Clip.StartY;
}
int t = Y + height - 1;
if( t < _Clip.StartY ) return;
if( t > _Clip.EndY ){
height -= t - _Clip.EndY;
}
int iskip = 0;
if( X > _Clip.EndX ) return;
if( X < _Clip.StartX ){
width -= _Clip.StartX - X;
ImgPtr += _Clip.StartX - X;
iskip += _Clip.StartX - X;
X = _Clip.StartX;
}
t = X + width - 1;
if( t < _Clip.StartX ) return;
if( t > _Clip.EndX ){
width -= t - _Clip.EndX;
iskip += t - _Clip.EndX;
}
char *ScrPtr = CALC_ADDR( X, Y );
int sskip = VMEM_WIDTH - width;
int w2 = width & 0x03;
width >>= 2;
for( int i = 0; i < height; i ++ ){
for( int j = 0; j < width; j ++ ){
*((long *)ScrPtr) = *((long *)ImgPtr);
ScrPtr += sizeof(long);
ImgPtr += sizeof(long);
}
for( j = 0; j < w2; j ++ )
*ScrPtr++ = *ImgPtr++;
ScrPtr += sskip;
ImgPtr += iskip;
}
}
| true |
9d8fea6a3b0a2fe8caa7384196432ca38ed30066 | C++ | palori/api_swarm_mobile_robot | /API_rpi/task_allocation/tasks.cpp | UTF-8 | 501 | 2.6875 | 3 | [] | no_license | #include "tasks.h"
Tasks::Tasks(){
init();
}
Tasks::~Tasks(){}
void Tasks::init(){
this->to_do.set_name("To do");
this->done.set_name("Done");
}
int Tasks::get_MAX_LEN(){return MAX_LEN;}
void Tasks::set_MAX_LEN(int i){
MAX_LEN = i;
to_do.set_MAX_LEN(i);
done.set_MAX_LEN(i);
}
//void print_info();
//Tasks & operator=(Tasks & rp);
bool Tasks::mask_as_done(string task){
bool is_done = false;
is_done = to_do.remove_item(task);
if (is_done) done.add_item(task);
return is_done;
}
| true |
5dcd043a1869e9844598dbc9ba766e65e884c5a4 | C++ | Liamq12/Misty-Joystick | /Misty_Joystick_MK3/Misty_Joystick_MK3.ino | UTF-8 | 3,893 | 2.71875 | 3 | [] | no_license | /*
Liam Homburger
This is the code for the Misty Joystick Project
https://github.com/Liamq12
*/
#include <WiFi.h>
#include <HTTPClient.h>
//Your Network Creds
const char* ssid = "";
const char* password = "";
//Misty IP (Can find on the misty app)
String MistyIP = "";
//X and Y Analog Pins
#define JoyX 39
#define JoyY 36
//Max Analog Reading (ESP32 is 4096, Some boards are 1024)
#define AnalogMax 4096
//Ignore readings within this threshold. Reccomended at 5% of AnalogMax. Set to -1 for an autogenerated deadzone
int DeadZone = -1;
//Prorgam Globals
int ShiftX = 0;
int ShiftY = 0;
int XAverage = 0;
int YAverage = 0;
void setup() {
Serial.begin(115200);
//Auto set DeadZone to 5% of AnalogMax if not set.
if (DeadZone == -1) {
DeadZone = AnalogMax * 0.05;
}
int CalibrationX[100];
int CalibrationY[100];
//Take 100 readings super fast to get the average resting values
for (int i = 0; i < 100; i++) {
CalibrationX[i] = analogRead(JoyX);
CalibrationY[i] = analogRead(JoyY);
delay(10);
}
int XSum = 0;
int YSum = 0;
//Average resting values
for (int i = 0; i < 100; i++) {
XSum += CalibrationX[i];
YSum += CalibrationY[i];
}
XAverage = XSum / 100;
YAverage = YSum / 100;
//Calculate shifts for each axis
ShiftX = (AnalogMax / 2) - XAverage;
ShiftY = (AnalogMax / 2) - YAverage;
//Set Averages to True average plus Shift (About AnalogMax/2
XAverage = XAverage + ShiftX;
YAverage = YAverage + ShiftY;
//Connect to Wifi
WiFi.begin(ssid, password);
Serial.println("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
}
void loop() {
//Get raw X and Y value and add shift
int XValue = analogRead(JoyX) + ShiftX;
int YValue = analogRead(JoyY) + ShiftY;
int LinearVelocity = 0;
int AngularVelocity = 0;
//Calculate Linear and Angular Velocity on gradient
if (YValue > (YAverage + DeadZone)) {
int Range = (AnalogMax + DeadZone) - (YAverage + DeadZone);
double Rate = (double) Range / 100;
LinearVelocity = (YValue - (YAverage + DeadZone)) / Rate;
}
if (YValue < (YAverage - DeadZone)) {
int Range = (AnalogMax + DeadZone) - (YAverage + DeadZone);
double Rate = (double) Range / 100;
LinearVelocity = (YValue - (YAverage + DeadZone)) / Rate;
}
if (XValue > (XAverage + DeadZone)) {
int Range = (AnalogMax + DeadZone) - (XAverage + DeadZone);
double Rate = (double) Range / 100;
AngularVelocity = (-1) * ((XValue - (XAverage + DeadZone)) / Rate);
}
if (XValue < (XAverage - DeadZone)) {
int Range = (AnalogMax + DeadZone) - (XAverage + DeadZone);
double Rate = (double) Range / 100;
AngularVelocity = (-1) * ((XValue - (XAverage + DeadZone)) / Rate);
}
//Send HTTP POST Request to Misty with Angular and Linear Velocity
String DriveURL = "http://" + MistyIP + "/api/drive?linearVelocity=" + (String) LinearVelocity + "&angularVelocity=" + (String) AngularVelocity;
String HTTPRequest = httpPOSTRequest((DriveURL));
delay(100);
}
String httpPOSTRequest(String serverName) {
HTTPClient http;
// IP Adress of server with endpoint
http.begin(serverName);
// Send HTTP POST request to server
int httpResponseCode = http.POST("");
// Use empty payload
String payload = "--";
//Report response and any error
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
return payload;
}
| true |
2d6e51b8ae0485bb4f161ca8630ff2e519947a51 | C++ | kudotuanminh/CaveStory | /src/sprite.cpp | UTF-8 | 5,497 | 2.953125 | 3 | [] | no_license | #include <sprite.h>
/* Sprite class
* Holds information for individual sprites
*/
Sprite::Sprite() {}
Sprite::Sprite(Graphics &graphics, const std::string &filePath, int sourceX,
int sourceY, int width, int height, float posX, float posY)
: _x(posX), _y(posY) {
this->_sourceRect.x = sourceX;
this->_sourceRect.y = sourceY;
this->_sourceRect.w = width;
this->_sourceRect.h = height;
this->_spriteSheet = SDL_CreateTextureFromSurface(
graphics.getRenderer(), graphics.loadImage(filePath));
if (this->_spriteSheet == NULL)
std::cerr << "\nError: Unable to load image\n";
this->_boundingBox =
Rectangle(this->_x, this->_y, global::SPRITE_SCALE * width,
global::SPRITE_SCALE * height);
}
Sprite::~Sprite() {}
const float Sprite::getX() const { return this->_x; }
const float Sprite::getY() const { return this->_y; }
const Rectangle Sprite::getBoundingBox() const { return this->_boundingBox; }
const sides::Side Sprite::getCollisionSide(Rectangle &other) const {
int amountRight = this->getBoundingBox().getRight() - other.getLeft(),
amountLeft = other.getRight() - this->getBoundingBox().getLeft(),
amountTop = other.getBottom() - this->getBoundingBox().getTop(),
amountBottom = this->getBoundingBox().getBottom() - other.getTop();
int vals[4] = {abs(amountRight), abs(amountLeft), abs(amountTop),
abs(amountBottom)};
int min = *std::min_element(vals, vals + 4);
if (min == abs(amountRight))
return sides::RIGHT;
else if (min == abs(amountLeft))
return sides::LEFT;
else if (min == abs(amountTop))
return sides::TOP;
else if (min == abs(amountBottom))
return sides::BOTTOM;
else
return sides::NONE;
}
void Sprite::setSourceRectX(int value) { this->_sourceRect.x = value; }
void Sprite::setSourceRectY(int value) { this->_sourceRect.y = value; }
void Sprite::setSourceRectW(int value) { this->_sourceRect.w = value; }
void Sprite::setSourceRectH(int value) { this->_sourceRect.h = value; }
void Sprite::update() {
this->_boundingBox = Rectangle(this->_x, this->_y,
global::SPRITE_SCALE * this->_sourceRect.w,
global::SPRITE_SCALE * this->_sourceRect.h);
}
void Sprite::draw(Graphics &graphics, int x, int y) {
SDL_Rect destinationRectangle = {
x, y, global::SPRITE_SCALE * this->_sourceRect.w,
global::SPRITE_SCALE * this->_sourceRect.h};
graphics.blitSurface(this->_spriteSheet, &this->_sourceRect,
&destinationRectangle);
}
/* AnimatedSprite class
* Holds logic for animating sprites
*/
AnimatedSprite::AnimatedSprite() {}
AnimatedSprite::AnimatedSprite(Graphics &graphics, const std::string &filePath,
int sourceX, int sourceY, int width, int height,
float posX, float posY, float timeToUpdate)
: Sprite(graphics, filePath, sourceX, sourceY, width, height, posX, posY),
_frameIndex(0),
_timeToUpdate(timeToUpdate),
_visible(true),
_currentAnimationOnce(false),
_currentAnimation("") {}
AnimatedSprite::~AnimatedSprite() {}
void AnimatedSprite::addAnimation(int frames, int x, int y, std::string name,
int width, int height, Vector2 offset) {
std::vector<SDL_Rect> rectangles;
for (int i = 0; i < frames; i++) {
SDL_Rect newRect = {(i + x) * width, y, width, height};
rectangles.push_back(newRect);
}
this->_animations.insert(
std::pair<std::string, std::vector<SDL_Rect>>(name, rectangles));
this->_offsets.insert(std::pair<std::string, Vector2>(name, offset));
}
void AnimatedSprite::resetAnimations() {
this->_animations.clear();
this->_offsets.clear();
}
void AnimatedSprite::stopAnimation() {
this->_frameIndex = 0;
this->animationDone(this->_currentAnimation);
}
void AnimatedSprite::setVisible(bool visible) { this->_visible = visible; }
void AnimatedSprite::playAnimation(std::string animation, bool once) {
this->_currentAnimationOnce = once;
if (this->_currentAnimation != animation) {
this->_currentAnimation = animation;
this->_frameIndex = 0;
}
}
void AnimatedSprite::update(int elapsedTime) {
Sprite::update();
this->_timeElapsed += elapsedTime;
if (this->_timeElapsed > this->_timeToUpdate) {
this->_timeElapsed -= this->_timeToUpdate;
if (this->_frameIndex <
this->_animations[this->_currentAnimation].size() - 1)
this->_frameIndex++;
else {
if (this->_currentAnimationOnce)
this->setVisible(false);
this->stopAnimation();
}
}
}
void AnimatedSprite::draw(Graphics &graphics, int x, int y) {
if (this->_visible) {
SDL_Rect destinationRectangle;
destinationRectangle.x = x + this->_offsets[this->_currentAnimation].x;
destinationRectangle.y = y + this->_offsets[this->_currentAnimation].y;
destinationRectangle.w = global::SPRITE_SCALE * this->_sourceRect.w;
destinationRectangle.h = global::SPRITE_SCALE * this->_sourceRect.h;
SDL_Rect sourceRect =
this->_animations[this->_currentAnimation][this->_frameIndex];
graphics.blitSurface(this->_spriteSheet, &sourceRect,
&destinationRectangle);
}
}
| true |
225a000cdc3d5aff423947f63744a5366eb48376 | C++ | swindonmakers/LogoBot | /software/firmware/LogoBotBasic/LogoBotBasic.ino | UTF-8 | 2,410 | 2.796875 | 3 | [
"MIT"
] | permissive | #include "Configuration.h"
#include <DifferentialStepper.h>
#include <Bot.h>
#include <Servo.h>
Bot bot(MOTOR_L_PIN_1, MOTOR_L_PIN_2, MOTOR_L_PIN_3, MOTOR_L_PIN_4, MOTOR_R_PIN_1, MOTOR_R_PIN_2, MOTOR_R_PIN_3, MOTOR_R_PIN_4);
String cmd; // cmd received over serial - builds up char at a time
void setup()
{
initLEDs();
setLEDColour(0,0,1); // Blue, as we get started
Serial.begin(9600);
Serial.println("Logobot");
bot.begin();
bot.enableLookAhead(true);
bot.initBumpers(SWITCH_FL_PIN, SWITCH_FR_PIN, SWITCH_BL_PIN, SWITCH_BR_PIN, handleCollision);
initBuzzer();
playStartupJingle();
}
void loop()
{
// keep the bot moving (this triggers the stepper motors to move, so needs to be called frequently, i.e. >1KHz)
bot.run();
if (!bot.isQFull()) { // fill up the move queue to get the speed up
setLEDColour(0,1,0); // Green, because we are happily doing something
// keep it moving, until it hits something
bot.drive(10);
}
}
static void handleCollision(byte collisionData)
{
if (collisionData != 0) {
// Just hit something, so stop, buzz and backoff
setLEDColour(1,0,0); // Red, because we hit something
Serial.println("Ouch!");
bot.emergencyStop();
bot.buzz(500);
bot.drive(-20);
playGrumpy();
}
// Insert some recovery based on which bumper was hit
// Queue the moves directly to bot, don't bother with Logo command queue
if (collisionData == 1) {
bot.turn(-30);
} else if (collisionData == 2) {
bot.turn(60);
} else if (collisionData != 0) {
bot.turn(-90);
}
}
static void initLEDs() {
// LED setup
pinMode(LED_RED_PIN, OUTPUT);
pinMode(LED_GREEN_PIN, OUTPUT);
pinMode(LED_BLUE_PIN, OUTPUT);
setLEDColour(0,0,0);
}
static void setLEDColour(byte r, byte g, byte b) {
digitalWrite(LED_RED_PIN, r);
digitalWrite(LED_GREEN_PIN, g);
digitalWrite(LED_BLUE_PIN, b);
}
static void initBuzzer() {
pinMode(BUZZER_PIN, OUTPUT);
}
static void playStartupJingle() {
for (byte i=0; i<3; i++) {
analogWrite(BUZZER_PIN, 100 + i*50);
delay(200 + i*50);
}
analogWrite(BUZZER_PIN, 0);
}
static void playGrumpy() {
for (byte i=0; i<2; i++) {
analogWrite(BUZZER_PIN, 250 - i*100);
delay(100 + i*100);
}
analogWrite(BUZZER_PIN, 0);
}
| true |
f42fe3a4e3ed81b522d6b696e7d2f8d709c516d6 | C++ | hitgavin/vehicle-mpc-controller | /src/unicycle_model.cpp | UTF-8 | 1,294 | 2.84375 | 3 | [
"MIT"
] | permissive | #include <unicycle_model.h>
UnicycleModel::UnicycleModel(const std::string& model_name)
: VehicleModel(model_name, 3, 2) {
dynamics_function_ = [this](const state_t& x, state_t& dxdt,
const input_t& u) {
dxdt[0] = u[0] * std::cos(x[2]);
dxdt[1] = u[0] * std::sin(x[2]);
dxdt[2] = u[1];
};
dynamics_function_sim_ = [this](const std::vector<double>& x,
std::vector<double>& dxdt, const input_t& u) {
dxdt[0] = u[0] * std::cos(x[2]);
dxdt[1] = u[0] * std::sin(x[2]);
dxdt[2] = u[1];
};
}
void UnicycleModel::getLinearizedDynamicsContinuous(Eigen::MatrixXd& F,
Eigen::MatrixXd& G,
const state_t& x,
const input_t& u) {
// Check for correct size of the matrices:
// State transition matrix (F)
F(0, 0) = 0;
F(0, 1) = 0;
F(0, 2) = u[0] * (-1) * std::sin(x[2]);
F(1, 0) = 0;
F(1, 1) = 0;
F(1, 2) = u[0] * std::cos(x[2]);
F(2, 0) = 0;
F(2, 1) = 0;
F(2, 2) = 0;
// Input to state mapping matrix (G)
G(0, 0) = std::cos(x[2]);
G(0, 1) = 0;
G(1, 0) = std::sin(x[2]);
G(1, 1) = 0;
G(2, 0) = 0;
G(2, 1) = 1;
}
| true |
a834875cbbaa8f89fe3f2640be98ca476c349a2e | C++ | Shahaf11111/WarGameAI | /vs2017test/HpKit.cpp | UTF-8 | 496 | 2.78125 | 3 | [] | no_license | #include "HpKit.h"
#include "glut.h"
HpKit::HpKit(int c, int r, int hp) : Node(c, r) {
this->hp = hp;
}
int HpKit::getHp()
{
return this->hp;
}
void HpKit::drawMe() {
double size = 0.01;
double* myCoors = this->cell2coor(this->getCol(), this->getRow());
double x = myCoors[0];
double y = myCoors[1];
glColor3d(0, 1, 0);
glBegin(GL_POLYGON);
glVertex2d(x - size, y - size);
glVertex2d(x - size, y + size);
glVertex2d(x + size, y + size);
glVertex2d(x + size, y - size);
glEnd();
}
| true |
8361920fb0a8fe861953a1a7269fbda83ef1ba8d | C++ | zhiyu123/practice_project | /Project6/watch.cpp | UTF-8 | 290 | 3.15625 | 3 | [] | no_license | #include"watch.h"
Watch::Watch(int hour, int minute, int second):m_time(hour, minute, second)
{
cout << "Watch()" << endl;
}
Watch::~Watch()
{
cout << "~Watch()" << endl;
}
void Watch::display(void)
{
cout << m_time.m_hour << ":" << m_time.m_minute << ":" << m_time.m_second << endl;
} | true |
d56d214595102cca62a22468dad0738a38853adb | C++ | CHP-EmAS/TWLA | /The worst Link Adventure/Logo_Screen.cpp | UTF-8 | 8,804 | 2.796875 | 3 | [] | no_license | #include "Screens.h"
#include "Graphic_Manager.h"
#include "Sound_Manager.h"
Logo_Screen::Logo_Screen(void) : Screen(Screen_Type::Logos)
{
initScreen();
}
void Logo_Screen::updateScreen()
{
switch(screenState)
{
case 0: //Show "CHP presents"
if(screenStateClock.getElapsedTime().asMilliseconds() > 1500)
{
screenState = 1;
Sound_Manager::getMe().playEffectSound(Sound_Manager::Bing,false,false);
screenStateClock.restart();
}
break;
case 1://Wait 2 Sec
if(screenStateClock.getElapsedTime().asMilliseconds() > 2000)
{
screenState = 2;
Sound_Manager::getMe().changeBackgroundMusic("Music/Theme.ogg");
screenStateClock.restart();
}
break;
case 2://Background fade in
if(background.getColor().a + 2 < 255)
background.setColor(sf::Color(255,255,255,background.getColor().a + 2));
else
{
background.setColor(sf::Color(255,255,255,255));
screenState = 3;
}
break;
case 3://"The worst" flys in
if(screenStateClock.getElapsedTime().asMilliseconds() > 10)
{
bool correct = true;
if(the_text.getPosition().x + 20 < WINDOW_SIZE_X/4)
{
the_text.move(20,0);
correct = false;
}
if(worst_text.getPosition().x - 20 > the_text.getPosition().x + the_text.getGlobalBounds().width + 20)
{
worst_text.move(-20,0);
correct = false;
}
if(correct)
{
the_text.setPosition(WINDOW_SIZE_X/4,WINDOW_SIZE_Y/4 - 10);
worst_text.setPosition(the_text.getPosition().x + the_text.getGlobalBounds().width + 20,the_text.getPosition().y+2);
screenState = 4;
}
screenStateClock.restart();
}
break;
case 4://Wait 0.5 Sec
if(screenStateClock.getElapsedTime().asMilliseconds() > 500)
{
screenState = 5;
screenStateClock.restart();
}
break;
case 5://Fade "Link" in
if(screenStateClock.getElapsedTime().asMilliseconds() > 10)
{
if(link_text.getFillColor().a + 10 < 255) link_text.setFillColor(sf::Color(0,200,0,link_text.getFillColor().a + 10));
else
{
link_text.setFillColor(sf::Color(0,200,0,255));
screenState = 6;
}
}
break;
case 6://Print "Adventure"
if(screenStateClock.getElapsedTime().asMilliseconds() > 100)
{
if(adventure_text.getString().getSize() < 9)
{
switch(adventure_text.getString().getSize())
{
case 0:
adventure_text.setString("A");
break;
case 1:
adventure_text.setString("Ad");
break;
case 2:
adventure_text.setString("Adv");
break;
case 3:
adventure_text.setString("Adve");
break;
case 4:
adventure_text.setString("Adven");
break;
case 5:
adventure_text.setString("Advent");
break;
case 6:
adventure_text.setString("Adventu");
break;
case 7:
adventure_text.setString("Adventur");
break;
case 8:
adventure_text.setString("Adventure");
break;
default:
adventure_text.setString("Adventure");
break;
}
}
else
{
screenState = 7;
}
screenStateClock.restart();
}
break;
case 7://Fade Sword Img and vorgottenText in
if(screenStateClock.getElapsedTime().asMilliseconds() > 10)
{
if(spr_sword.getColor().a + 2 < 255) spr_sword.setColor(sf::Color(255,255,255,spr_sword.getColor().a + 2));
else
{
spr_sword.setColor(sf::Color(255,255,255,255));
}
if(vorgottenWorld_text.getFillColor().a + 2 < 255) vorgottenWorld_text.setFillColor(sf::Color(0,255,255,vorgottenWorld_text.getFillColor().a + 2));
else
{
vorgottenWorld_text.setFillColor(sf::Color(0,255,255,255));
}
if(vorgottenWorld_text.getFillColor().a == 255 && spr_sword.getColor().a == 255) screenState = 8;
}
break;
case 8://Wait 3Sec
if(screenStateClock.getElapsedTime().asMilliseconds() > 3000)
{
screenState = 9;
screenStateClock.restart();
}
break;
case 9://Switch to 10
if(screenStateClock.getElapsedTime().asMilliseconds() > 750)
{
screenState = 10;
screenStateClock.restart();
}
break;
case 10://Switch to 9
if(screenStateClock.getElapsedTime().asMilliseconds() > 750)
{
screenState = 9;
screenStateClock.restart();
}
break;
}
}
void Logo_Screen::drawScreen(sf::RenderWindow &mainWindow)
{
if(screenState == 1)
{
mainWindow.draw(CHPText);
mainWindow.draw(presentsText);
}
if(screenState >= 2)
{
//mainWindow.draw(background);
}
if(screenState >= 7)
{
mainWindow.draw(spr_sword);
mainWindow.draw(vorgottenWorld_text);
}
if(screenState >= 3)
{
mainWindow.draw(the_text);
mainWindow.draw(worst_text);
}
if(screenState >= 5)
{
mainWindow.draw(link_text);
}
if(screenState >= 6)
{
mainWindow.draw(adventure_text);
}
if(screenState == 9)
{
mainWindow.draw(contiueText);
}
}
void Logo_Screen::checkEvents(sf::Event newEvent)
{
switch(newEvent.type)
{
case sf::Event::KeyPressed:
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
{
Screen_Manager::getMe().changeScreen(Screen::Main_Menue);
}
break;
}
}
void Logo_Screen::loadScreen()
{
screenState = 0;
the_text.setPosition(-the_text.getGlobalBounds().width-220,WINDOW_SIZE_Y/4-10);
worst_text.setPosition(WINDOW_SIZE_X + worst_text.getGlobalBounds().width,the_text.getPosition().y+2);
link_text.setFillColor(sf::Color(0,200,0,0));
adventure_text.setString("");
spr_sword.setColor(sf::Color(255,255,255,0));
vorgottenWorld_text.setFillColor(sf::Color(0,150,150,0));
screenStateClock.restart();
setLoaded(true);
}
void Logo_Screen::restartScreen()
{
closeScreen();
loadScreen();
}
void Logo_Screen::closeScreen()
{
setLoaded(false);
}
void Logo_Screen::initScreen()
{
CHPText = sf::Text("- CHP -",Graphic_Manager::getMe().getFont(Graphic_Manager::Pixel),26);
CHPText.setOrigin(CHPText.getGlobalBounds().width/2,CHPText.getGlobalBounds().height/2);
CHPText.setPosition(WINDOW_SIZE_X/2,WINDOW_SIZE_Y/2);
presentsText = sf::Text("presents",Graphic_Manager::getMe().getFont(Graphic_Manager::Pixel),16);
presentsText.setOrigin(presentsText.getGlobalBounds().width/2,presentsText.getGlobalBounds().height/2);
presentsText.setPosition(WINDOW_SIZE_X/2,CHPText.getPosition().y+25);
contiueText = sf::Text("press 'Space' to continue",Graphic_Manager::getMe().getFont(Graphic_Manager::Pixel),18);
contiueText.setOrigin(contiueText.getGlobalBounds().width/2,contiueText.getGlobalBounds().height/2);
contiueText.setPosition(WINDOW_SIZE_X/2,WINDOW_SIZE_Y-contiueText.getGlobalBounds().height - 25);
contiueText.setOutlineColor(sf::Color::Black);
contiueText.setOutlineThickness(2);
the_text = sf::Text("The",Graphic_Manager::getMe().getFont(Graphic_Manager::Pixel),30);
the_text.setPosition(WINDOW_SIZE_X/4,WINDOW_SIZE_Y/4 - 20);
the_text.setOutlineThickness(3);
the_text.setOutlineColor(sf::Color(100,100,100));
worst_text = sf::Text("worst",Graphic_Manager::getMe().getFont(Graphic_Manager::Arial),30);
worst_text.setPosition(the_text.getPosition().x + the_text.getGlobalBounds().width + 20,the_text.getPosition().y+2);
worst_text.setFillColor(sf::Color(200,0,0));
worst_text.setStyle(sf::Text::Style::Bold);
worst_text.setOutlineThickness(3);
worst_text.setOutlineColor(sf::Color(0,0,0));
link_text = sf::Text("Link",Graphic_Manager::getMe().getFont(Graphic_Manager::Pixel),100);
link_text.setPosition(the_text.getPosition().x,the_text.getPosition().y + the_text.getGlobalBounds().height);
link_text.setFillColor(sf::Color(0,200,0));
link_text.setOutlineThickness(6);
link_text.setOutlineColor(sf::Color(0,100,0));
adventure_text = sf::Text("Adventure",Graphic_Manager::getMe().getFont(Graphic_Manager::Arial),60);
adventure_text.setPosition(link_text.getPosition().x + 10,link_text.getPosition().y + link_text.getGlobalBounds().height + 25);
adventure_text.setFillColor(sf::Color(255,255,0));
adventure_text.setStyle(sf::Text::Style::Italic);
adventure_text.setOutlineThickness(3);
adventure_text.setOutlineColor(sf::Color(50,50,0));
vorgottenWorld_text = sf::Text("Die vergessene Welt",Graphic_Manager::getMe().getFont(Graphic_Manager::Pixel),30);
vorgottenWorld_text.setPosition(adventure_text.getPosition().x - 85,adventure_text.getPosition().y + adventure_text.getGlobalBounds().height + 100);
vorgottenWorld_text.setFillColor(sf::Color(0,100,100));
vorgottenWorld_text.setOutlineThickness(3);
vorgottenWorld_text.setOutlineColor(sf::Color(50,50,50));
tex_sword.loadFromFile("Img/ect/Master Schwert.png");
spr_sword.setTexture(tex_sword);
spr_sword.setOrigin(tex_sword.getSize().x/2,tex_sword.getSize().y/2);
spr_sword.setPosition(WINDOW_SIZE_X/2,WINDOW_SIZE_Y/3+50);
spr_sword.setScale(0.25,0.25);
backTexture.loadFromFile("Img/Backgrounds/Intro.png");
background.setTexture(backTexture);
background.setPosition(0,0);
background.setColor(sf::Color(255,255,255,0));
screenState = 0;
}
Logo_Screen::~Logo_Screen(void)
{
}
| true |
7df897237f61d515366af31c77352f8c3f2ea4bd | C++ | SwordRebellion/algorithm | /6.2 装配线问题.cpp | UTF-8 | 817 | 2.578125 | 3 | [] | no_license | #include<stdio.h>
int n,e1,e2,x1,x2,a[2][1000],t[2][1000],f[2][1000];
void input()
{
int i;
scanf("%d",&n);
scanf("%d%d%d%d",&e1,&e2,&x1,&x2);
for(i=0;i<n;i++)
scanf("%d",&a[0][i]);
for(i=0;i<n;i++)
scanf("%d",&a[1][i]);
for(i=0;i<n-1;i++)
scanf("%d",&t[0][i]);
for(i=0;i<n-1;i++)
scanf("%d",&t[1][i]);
}
int FastWay()
{
int i;
f[0][0]=e1+a[0][0],f[1][0]=e2+a[1][0];
for(i=1;i<n;i++)
{
if(f[0][i-1]<f[1][i-1]+t[1][i-1])
f[0][i]=f[0][i-1]+a[0][i];
else
f[0][i]=f[1][i-1]+t[1][i-1]+a[0][i];
if(f[1][i-1]<f[0][i-1]+t[0][i-1])
f[1][i]=f[1][i-1]+a[1][i];
else
f[1][i]=f[0][i-1]+t[0][i-1]+a[1][i];
}
i--;
if(f[0][i]+x1 < f[1][i]+x2)
return f[0][i]+x1;
else
return f[1][i]+x2;
}
int main()
{
int FastTime;
input();
FastTime=FastWay();
printf("%d\n",FastTime);
return 0;
} | true |
e3e57ee8f9ec6ca80e849c924c7b6d1275b68894 | C++ | gashe-soo/Algorithm | /hackerrank/SherlockAndAnagrams.cpp | UTF-8 | 943 | 3.21875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
// Complete the sherlockAndAnagrams function below.
int sherlockAndAnagrams(string s)
{
int len = s.size();
unordered_map<string, int> m;
for (int i = 1; i < len; i++) {
for (int j = 0; j <= len - i; j++) {
string sub = s.substr(j, i);
sort(sub.begin(), sub.end());
m[sub]++;
}
}
int answer = 0;
for (auto it = m.begin(); it != m.end(); it++) {
int val = it->second;
if (val >= 2)
answer += (val - 1) * val / 2;
}
return answer;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int q;
cin >> q;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int q_itr = 0; q_itr < q; q_itr++) {
string s;
getline(cin, s);
int result = sherlockAndAnagrams(s);
fout << result << "\n";
}
fout.close();
return 0;
}
| true |
d44b95a23d849377c4b82752adf0d95aabb05329 | C++ | NullException0/Win32-API-Sample-Code | /Win32 API CreateDirectory/Win32 API CreateDirectory/Win32 API CreateDirectory.cpp | UTF-8 | 1,646 | 2.859375 | 3 | [] | no_license | // Win32 API CreateDirectory.cpp : This file contains the 'main' function. Program execution begins and ends there.
// https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createdirectorya
/*
lpPathName = The path of the directory to be created.
lpSecurityAttributes = A pointer to a SECURITY_ATTRIBUTES structure
BOOL RemoveDirectoryA(LPCSTR lpPathName);
BOOL CreateDirectory(LPCSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes)
*/
#include <iostream>
#include <Windows.h>
using namespace std;
int main()
{
BOOL cDir;
//create directory
cDir = CreateDirectory(L"C:\\Users\\azizi\\Desktop\\test", NULL);
if (!cDir)
cout << "Create Directory Failed : " << GetLastError() << endl;
else
cout << "Create Directory success : " << endl;
//remove directory
cDir = RemoveDirectory(L"C:\\Users\\azizi\\Desktop\\test");
if (!cDir)
cout << "Remove Directory Failed : " << GetLastError() << endl;
else
cout << "Remove Directory success : " << endl;
return 0;
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| true |
9f17337a8cddbc824cd63b5f44ecea751ea29cdb | C++ | ryucak/modernCPP | /mcp6/mcp54/54.cpp | UTF-8 | 568 | 3.375 | 3 | [] | no_license | /*
* 54.cpp
*
* Created on: 2019/07/16
* Author: hhhhh
*/
#include <vector>
template<typename Input, typename Output>
void pairwise(Input begin, Input end, Output result) {
auto it = begin;
while (it != end) {
auto const v1 = *it++;
if (it == end)
break;
auto const v2 = *it++;
result++ = std::make_pair(v1, v2);
}
}
template<typename T>
std::vector<std::pair<T, T>> pairwise(std::vector<T> const & range) {
std::vector<std::pair<T, T>> result;
pairwise(std::cbegin(range), std::cend(range), std::back_inserter(result));
return result;
}
| true |
f92d5a0dd36dd3c3d61e807e659b15e0df94f918 | C++ | nonothing/Dyna-Blaster-cocos2dx | /Classes/Model/Data/PlayerData.h | UTF-8 | 1,036 | 2.5625 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef __PLAYER_DATA_H__
#define __PLAYER_DATA_H__
#include "cocos2d.h"
#include "enumerate/EEventType.h"
#include "enumerate/EPlayer.h"
struct PlayerData
{
public:
int _maxInterval;
int _interval;
cocos2d::Point _speed;
int _sizeBomb;
int _maxBomb;
int _countBomb;
int _speedCount;
int _life;
bool _isImmortal;
bool _isRemote;
bool _canCreateBomb;
bool _isMoveWall;
bool _isThroughBomb;
CustomEvent customEvent;
PlayerColor _colorID;
PlayerData(PlayerColor color)
{
_interval = 0;
_colorID = color;
_sizeBomb = 1;
_countBomb = 1;
_life = 3;
clearBonus();
}
PlayerData(){}
void clearBonus()
{
_speedCount = 0;
_maxInterval = 3;
_isImmortal = false;
_isRemote = false;
_canCreateBomb = true;
_isMoveWall = false;
_isThroughBomb = false;
updateSpeed();
}
void updateSpeed()
{
_speed = cocos2d::Point(6, 8) + cocos2d::Point(2, 2) * _speedCount;
}
void updateLife()
{
customEvent(UPDATE_LIFE, _colorID);
}
};
#endif // __PLAYER_DATA_H__
| true |
45c6b48853fd04db553abb414a7810e784fdd2f2 | C++ | DSobscure/Computer-Graphic-Assignments | /Assignment1_2/Texture.h | UTF-8 | 827 | 2.53125 | 3 | [] | no_license | #pragma once
#include "FreeImage.h"
#include "glew.h"
#include <string>
#include "glut.h"
using namespace std;
namespace DSOpenGL
{
enum TextureType
{
No_Texture,
Single_Texture,
Multi_Texture,
Cube_Map
};
class Texture
{
public:
virtual void Active(bool active) = 0;
protected:
GLuint* textures;
};
class SingleTexture : public Texture
{
public:
SingleTexture(string fileDirectory, string fileName);
~SingleTexture();
void Active(bool active);
};
class MultiTexture : public Texture
{
public:
MultiTexture(string fileDirectory, string* fileNames, int fileCount);
~MultiTexture();
void Active(bool active);
};
class CubeMapTexture : public Texture
{
public:
CubeMapTexture(string fileDirectory, string cubeFileNames[6]);
~CubeMapTexture();
void Active(bool active);
};
} | true |
11b76897972b5e86235e26fa921a4e64c0f855ce | C++ | ravi-dafauti/DataStructures | /Matrix/FloodFillApplication.cpp | WINDOWS-1252 | 2,459 | 3.734375 | 4 | [] | no_license | /*
Given a matrix where every element is either O or X, replace O with X if surrounded by X. A O (or a set of O) is considered to be by surrounded by X if there are X at locations just below, just above, just left and just right of it.
Examples:
Input: mat[M][N] = {{'X', 'O', 'X', 'X', 'X', 'X'},
{'X', 'O', 'X', 'X', 'O', 'X'},
{'X', 'X', 'X', 'O', 'O', 'X'},
{'O', 'X', 'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'O', 'X', 'O'},
{'O', 'O', 'X', 'O', 'O', 'O'},
};
Output: mat[M][N] = {{'X', 'O', 'X', 'X', 'X', 'X'},
{'X', 'O', 'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'X', 'X', 'X'},
{'O', 'X', 'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'O', 'X', 'O'},
{'O', 'O', 'X', 'O', 'O', 'O'},
};
*/
#include<iostream>
using namespace std;
#define M 6
#define N 6
void floodFill(char mat[][N], int x, int y, char prev, char newc)
{
if (x < 0 || x >= M || y < 0 || y >= N)
return;
if (mat[x][y] != prev)
return;
mat[x][y] = newc;
floodFill(mat, x + 1, y, prev, newc);
floodFill(mat, x, y + 1, prev, newc);
floodFill(mat, x - 1, y, prev, newc);
floodFill(mat, x, y - 1, prev, newc);
}
void replaceSurrounded(char mat[][N])
{
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
if (mat[i][j] == 'O')
mat[i][j] = '-';
}
}
for (int i = 0; i < N; i++)
{
if (mat[0][i] == '-')
floodFill(mat, 0, i, '-', 'O');
}
for (int i = 1; i < M; i++)
{
if (mat[i][N - 1] == '-')
floodFill(mat, i, N - 1, '-', 'O');
}
for (int i = N-1; i >= 0; i--)
{
if (mat[M-1][i] == '-')
floodFill(mat, M-1, i, '-', 'O');
}
for (int i = M-2; i >=0; i--)
{
if (mat[i][0] == '-')
floodFill(mat, i, 0, '-', 'O');
}
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
if (mat[i][j] == '-')
mat[i][j] = 'X';
}
}
}
int main()
{
char mat[][N] = { { 'X', 'O', 'X', 'O', 'X', 'X' },
{ 'X', 'O', 'X', 'X', 'O', 'X' },
{ 'X', 'X', 'X', 'O', 'X', 'X' },
{ 'O', 'X', 'X', 'X', 'X', 'X' },
{ 'X', 'X', 'X', 'O', 'X', 'O' },
{ 'O', 'O', 'X', 'O', 'O', 'O' },
};
cout << "before\n";
for (int i = 0; i<M; i++)
{
for (int j = 0; j<N; j++)
cout << mat[i][j] << " ";
cout << endl;
}
cout << "after\n";
replaceSurrounded(mat);
for (int i = 0; i<M; i++)
{
for (int j = 0; j<N; j++)
cout << mat[i][j] << " ";
cout << endl;
}
return 0;
}
| true |
21ef1b7a892392d1f81bed8e5c1b5ff76d0fa765 | C++ | NandeeshG/projectEuler | /problem3.cpp | UTF-8 | 477 | 3.40625 | 3 | [] | no_license | // largest prime factor of any given number
#include <iostream>
#include <cmath>
using ull = unsigned long long;
//using namespace std;
int main()
{
ull number;
int largest_factor = number;
std::cin>>number;
while(number % 2 == 0)
{
number /= 2;
largest_factor = 2;
}
for(int i=3; i <= number; i += 2)
{
while(number % i == 0 )
{
largest_factor = i;
number /= i;
}
}
std::cout<<largest_factor;
return 0;
}
| true |
0aff3f1a1d18af009d79441cfceee45c6282855b | C++ | lukeandshuo/video-classifier | /minerva/minerva/optimizer/interface/LineSearch.h | UTF-8 | 1,161 | 2.71875 | 3 | [] | no_license |
/*! \brief LineSearch.h
\date August 23, 2014
\author Gregory Diamos <solustultus@gmail.com>
\brief The header file for the LineSearch class.
*/
#pragma once
// Forward Declarations
namespace minerva { namespace matrix { class Matrix; } }
namespace minerva { namespace matrix { class BlockSparseMatrix; } }
namespace minerva { namespace matrix { class BlockSparseMatrixVector; } }
namespace minerva { namespace optimizer { class CostAndGradientFunction; } }
namespace minerva
{
namespace optimizer
{
/*! \brief A generic interface to a line search algorithm */
class LineSearch
{
public:
typedef matrix::BlockSparseMatrix BlockSparseMatrix;
typedef matrix::Matrix Matrix;
typedef matrix::BlockSparseMatrixVector BlockSparseMatrixVector;
public:
virtual ~LineSearch();
public:
virtual void search(
const CostAndGradientFunction& costFunction,
BlockSparseMatrixVector& inputs, float& cost,
BlockSparseMatrixVector& gradient,
const BlockSparseMatrixVector& direction,
float step, const BlockSparseMatrixVector& previousInputs,
const BlockSparseMatrixVector& previousGradients) = 0;
};
}
}
| true |
abf7789a7e654c9216de744e4c6af6cbbd315d5e | C++ | onaycan/trivial_sensor_model | /ObjEnvironment.cpp | UTF-8 | 693 | 2.765625 | 3 | [] | no_license | #include "ObjEnvironment.h"
Environment::Environment(string filename)
{
string line;
ifstream myfile(filename);
if (myfile.is_open())
{
while (getline(myfile, line))
{
stringstream stream(line);
vector<double> current_real_object_coordinates(3);
for (int i = 0; i < 3; i++) {
stream>>current_real_object_coordinates[i];
//cout << line[i]<<endl;
//cout << current_real_object_coordinates[i] << endl;
}
real_object_coordinates.push_back(current_real_object_coordinates);
int current_type;
stream >> current_type;
real_object_type.push_back(current_type);
}
myfile.close();
}
}
Environment::~Environment()
{
}
| true |
83d9c4ba03faaa4f592cefc462d720f3a7bb1ded | C++ | dwax1324/baekjoon | /code/1895 필터.cpp | UTF-8 | 959 | 2.75 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
// 구현
// 1018 체스판 다시 칠하기랑 비슷한문제
//https://www.acmicpc.net/problem/1018
int main() {
int n, m;
cin >> n >> m;
int arr[41][41];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> arr[i][j];
}
}
int t;
cin >> t;
int cnt = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (i + 3 > n) break;
if (j + 3 > m) break;
vector<int> temp;
for (int k = i; k < i + 3; k++) {
for (int z = j; z < j + 3; z++) {
temp.push_back(arr[k][z]);
}
}
sort(temp.begin(), temp.end());
// for (auto x : temp) {
// cout << x << " ";
// }
// cout << '\n';
if (temp[4] >= t) cnt++;
}
}
cout << cnt;
} | true |
b1c4a9e04c92f2e841db204071010acddf59a74c | C++ | fatemetkl/MicroController_course | /Assembly codes in Code Vision/ReverseWord.cpp | UTF-8 | 1,073 | 2.515625 | 3 | [] | no_license | #define USE_STRLEN 0 ; //Use strlen to find string length?
//#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
void reverse(string word) {
int n = word.length();
char *arr = new char[n];
for (int i = 0; i < n; i++) {
arr[i] = word[i];
}
__asm
{
mov ecx, n
mov eax, arr
mov esi, eax;
add eax, ecx
mov edi, eax
dec edi;
shr ecx, 1;
jz done; //len =0 or 1
Loopqh :
mov al, [esi]; load characters
mov bl, [edi]
mov[esi], bl;
mov[edi], al
inc esi;
dec edi
dec ecx;
jnz Loopqh
done:
}
string res;
for (int i = 0; i < n; i++) {
cout<< arr[i];
}
cout << " ";
}
int main() {
string line, mid;;
getline(cin, line);
vector <string> words;
stringstream stream(line);
while (getline(stream, mid, ' ')) {
words.push_back(mid);
}
for (int i = 0; i < words.size(); i++) {
reverse(words[i]);
}
system("pause");
return 0;
} | true |
2af29ba50d30338f169c65e81053b8bdd99be3df | C++ | Dharnisingh/Git_test | /CPP/OperatorOverloading/comparision_operator.cpp | UTF-8 | 595 | 3.734375 | 4 | [] | no_license | /*Program to implement comparision operator
*/
#include <iostream>
using namespace std;
class x
{
int i;
public:
x(int a):i(a)
{
}
// We should implement such operatro using friend fucntions
// as by mistake if we pass obj2>obj1 might give us incorrect result
// because it will be treated as obj2.operator(obj1)
bool operator < (const x& obj) const
{
return obj.i < i;
}
bool operator > (const x& obj) const
{
return obj.i > i;
}
};
int main()
{
x obj1(5);
x obj2(10);
if(obj1 > obj2)
{
cout << "Obj2 is greater\n";
}
else
{
cout << "obj1 is greater\n";
}
return 0;
}
| true |
033df9011934799c74150c2eb1d9e36d37bb2c85 | C++ | leandropaganotti/ChatApp | /ChatServer/utils.cpp | UTF-8 | 591 | 2.84375 | 3 | [] | no_license | #include "utils.h"
namespace utils {
std::string &trim(std::string &s)
{
const std::string delimeters = " \f\n\r\t\v";
size_t p = s.find_first_not_of(delimeters);
s.erase(0, p);
p = s.find_last_not_of(delimeters);
if (std::string::npos != p)
s.erase(p+1);
return s;
}
std::string timestamp2string(std::time_t timestamp)
{
struct tm t;
if ( gmtime_r( ×tamp, &t ) == nullptr )
{
timestamp = 0;
gmtime_r( ×tamp, &t );
}
char buffer[64] = { };
strftime( buffer, 64, "%FT%T", &t );
return buffer;
}
}
| true |
654c306955020ab2bd86826e6ddd55640a1741bd | C++ | ezEngine/ezEngine | /Code/Engine/Foundation/Types/UniquePtr.h | UTF-8 | 3,535 | 3.09375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <Foundation/Basics.h>
/// \brief A Unique ptr manages an object and destroys that object when it goes out of scope. It is ensure that only one unique ptr can
/// manage the same object.
template <typename T>
class ezUniquePtr
{
EZ_DISALLOW_COPY_AND_ASSIGN(ezUniquePtr);
public:
EZ_DECLARE_MEM_RELOCATABLE_TYPE();
/// \brief Creates an empty unique ptr.
ezUniquePtr();
/// \brief Creates a unique ptr from a freshly created instance through EZ_NEW or EZ_DEFAULT_NEW.
template <typename U>
ezUniquePtr(const ezInternal::NewInstance<U>& instance);
/// \brief Creates a unique ptr from a pointer and an allocator. The passed allocator will be used to destroy the instance when the unique
/// ptr goes out of scope.
template <typename U>
ezUniquePtr(U* pInstance, ezAllocatorBase* pAllocator);
/// \brief Move constructs a unique ptr from another. The other unique ptr will be empty afterwards to guarantee that there is only one
/// unique ptr managing the same object.
template <typename U>
ezUniquePtr(ezUniquePtr<U>&& other);
/// \brief Initialization with nullptr to be able to return nullptr in functions that return unique ptr.
ezUniquePtr(std::nullptr_t);
/// \brief Destroys the managed object using the stored allocator.
~ezUniquePtr();
/// \brief Sets the unique ptr from a freshly created instance through EZ_NEW or EZ_DEFAULT_NEW.
template <typename U>
ezUniquePtr<T>& operator=(const ezInternal::NewInstance<U>& instance);
/// \brief Move assigns a unique ptr from another. The other unique ptr will be empty afterwards to guarantee that there is only one
/// unique ptr managing the same object.
template <typename U>
ezUniquePtr<T>& operator=(ezUniquePtr<U>&& other);
/// \brief Same as calling 'Reset()'
ezUniquePtr<T>& operator=(std::nullptr_t);
/// \brief Releases the managed object without destroying it. The unique ptr will be empty afterwards.
T* Release();
/// \brief Releases the managed object without destroying it. The unique ptr will be empty afterwards. Also returns the allocator that
/// should be used to destroy the object.
T* Release(ezAllocatorBase*& out_pAllocator);
/// \brief Borrows the managed object. The unique ptr stays unmodified.
T* Borrow() const;
/// \brief Destroys the managed object and resets the unique ptr.
void Clear();
/// \brief Provides access to the managed object.
T& operator*() const;
/// \brief Provides access to the managed object.
T* operator->() const;
/// \brief Returns true if there is managed object and false if the unique ptr is empty.
explicit operator bool() const;
/// \brief Compares the unique ptr against another unique ptr.
bool operator==(const ezUniquePtr<T>& rhs) const;
bool operator!=(const ezUniquePtr<T>& rhs) const;
bool operator<(const ezUniquePtr<T>& rhs) const;
bool operator<=(const ezUniquePtr<T>& rhs) const;
bool operator>(const ezUniquePtr<T>& rhs) const;
bool operator>=(const ezUniquePtr<T>& rhs) const;
/// \brief Compares the unique ptr against nullptr.
bool operator==(std::nullptr_t) const;
bool operator!=(std::nullptr_t) const;
bool operator<(std::nullptr_t) const;
bool operator<=(std::nullptr_t) const;
bool operator>(std::nullptr_t) const;
bool operator>=(std::nullptr_t) const;
private:
template <typename U>
friend class ezUniquePtr;
T* m_pInstance = nullptr;
ezAllocatorBase* m_pAllocator = nullptr;
};
#include <Foundation/Types/Implementation/UniquePtr_inl.h>
| true |
72fd98fa5249a3c7a8f93c1e41ae09f6f4fe5ea0 | C++ | MrAndMrswang/SimpleNetBase | /SrcFile/Poller.h | UTF-8 | 823 | 2.765625 | 3 | [] | no_license | #ifndef MUDUO_NET_POLLER_H
#define MUDUO_NET_POLLER_H
#include <map>
#include <vector>
#include <boost/noncopyable.hpp>
#include "Timestamp.h"
#include "EventLoop.h"
class Channel;
class Poller : boost::noncopyable
{
public:
typedef std::vector<Channel*> ChannelList;
Poller(EventLoop* loop);
virtual ~Poller();
virtual Timestamp poll(int timeoutMs, ChannelList* activeChannels) = 0;
virtual void updateChannel(Channel* channel) = 0;
virtual void removeChannel(Channel* channel) = 0;
virtual bool hasChannel(Channel* channel) const;
static Poller* newDefaultPoller(EventLoop* loop);
void assertInLoopThread() const
{
ownerLoop_->assertInLoopThread();
}
protected:
typedef std::map<int, Channel*> ChannelMap;
ChannelMap channels_;
private:
EventLoop* ownerLoop_;
};
#endif // MUDUO_NET_POLLER_H
| true |
b49fa487db09e7ce213c24636d5b2fc344c90d71 | C++ | atubo/online-judge | /luogu/P4030.cpp | UTF-8 | 2,414 | 2.828125 | 3 | [] | no_license | // https://www.luogu.org/problemnew/show/P4030
// [Code+#2]可做题1
#include <bits/stdc++.h>
using namespace std;
// note row and col are 1-indexed here
class FenwickInFenwick {
public:
const int N, M;
int **root;
FenwickInFenwick(int N_, int M_): N(N_), M(M_) {
alloc();
}
~FenwickInFenwick() {
dealloc();
}
// add value t to (x, y)
void add(int x, int y, int t) {
for (int i = x; i <= N; i += lowbit(i)) {
addRow(i, y, t);
}
}
// weight sum in region (x1, y1) -> (x2, y2), inclusive
int query(int x1, int y1, int x2, int y2) {
if (x1 > x2 || y1 > y2) return 0;
return query(x2, y2) - query(x1-1, y2) - query(x2, y1-1) +
query(x1-1, y1-1);
}
private:
void alloc() {
root = new int*[N+1];
for (int i = 0; i <= N; i++) {
root[i] = new int[M+1]{};
}
}
void dealloc() {
for (int i = 0; i <= N; i++) {
delete[] root[i];
}
delete[] root;
}
int lowbit(int x) const {return x & -x;}
void addRow(int row, int y, int t) {
for (int i = y; i <= M; i += lowbit(i)) {
root[row][i] += t;
}
}
// query range (1, 1) -> (x, y) inclusive
int query(int x, int y) const {
if (x == 0) return 0;
int res = 0;
while (x) {
res += queryRow(x, y);
x -= lowbit(x);
}
return res;
}
int queryRow(int row, int y) const {
if (y == 0) return 0;
int res = 0;
while (y) {
res += root[row][y];
y -= lowbit(y);
}
return res;
}
};
const int MAXN = 510;
int N, M, T;
int A[MAXN][MAXN], B[MAXN][MAXN];
int main() {
scanf("%d%d%d", &N, &M, &T);
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
scanf("%d", &A[i][j]);
}
}
FenwickInFenwick ft(N, M);
for (int i = 1; i < N; i++) {
for (int j = 0; j < M; j++) {
B[i][j] = A[i][j] - A[i-1][j];
if (j > 0 && B[i][j] != B[i][j-1]) {
ft.add(i+1, j, 1);
}
}
}
for (int i = 0; i < T; i++) {
int x, y, k;
scanf("%d%d%d", &x, &y, &k);
int cnt = ft.query(x+1, y, x+k-1, y+k-2);
printf("%c\n", cnt == 0 ? 'Y' : 'N');
}
return 0;
}
| true |
1c9ae3120888120da00d756ac7932e7d1521c16f | C++ | cruzj6/Syntax-Analyzer | /ConsoleApplication8/SyntaxAnalyzer.cpp | UTF-8 | 5,568 | 3.234375 | 3 | [] | no_license | #include "SyntaxAnalyzer.h"
int main() {
SyntaxAnalyzer SyntaxAnalyzer;
}
SyntaxAnalyzer::SyntaxAnalyzer()
{
if (lexer.openFile()) {
lexer.getChar();
nextToken = lexer.lex();
cout << "Deriving how your class is going from code: \n";
//cout << "First token is: " << nextToken << "\n";
taking_a_class();
}
}
SyntaxAnalyzer::~SyntaxAnalyzer()
{
}
void SyntaxAnalyzer::taking_a_class() {
cout << "You are taking a class" << endl;
if (nextToken == I_need_a)
classwork();
if (nextToken == Homework_is_due)
homework();
}
void SyntaxAnalyzer::classwork()
{
cout << "You are doing classwork!" << endl;
solo_work();
participation_grade();
}
void SyntaxAnalyzer::school_thing()
{
if (nextToken == pencil || nextToken == pen || nextToken == ruler || nextToken == calculator
|| nextToken == notebook || nextToken == laptop || nextToken == professor || nextToken == book)
{
cout << "You are using "<< suppliesctr << " tool(s) for your schoolwork!" << endl;
suppliesctr++;
nextToken = lexer.lex();
}
else{
cout << "ERROR!!! : Expected a school_thing" << endl;
if (cin.get())
{
exit(0);
}
}
}
void SyntaxAnalyzer::grade()
{
if (nextToken == A || nextToken == B || nextToken == C || nextToken == D || nextToken == E || nextToken == F)
{
cout << "You gave a grade in your code!" << endl;
nextToken = lexer.lex();
}
else{
cout << "ERROR!!! : Expected a grade (A,B,C,D,E,F)" << endl;
if (cin.get())
{
exit(0);
}
}
}
void SyntaxAnalyzer::quality()
{
if (nextToken == great || nextToken == efficient || nextToken == useful || nextToken == reflective)
{
cout << "By your opinion of this it sounds like you do good work! Yay!" << endl;
nextToken = lexer.lex();
}
else if (nextToken == bad)
{
cout << "You expressed the quality of your work needs improvement! Yay for honesty!";
nextToken = lexer.lex();
}
else{
cout << "ERROR!!! : Expected <quality> identifier" << endl;
if (cin.get())
{
exit(0);
}
}
}
void SyntaxAnalyzer::solo_work()
{
if (nextToken == I_need_a)
{
cout << "You do some work in the classroom!, for this you use some tools:" << endl;
nextToken = lexer.lex();
school_thing();
if (nextToken == and)
{
while (nextToken == and)
{
nextToken = lexer.lex();
school_thing();
}
}
if (nextToken == for_my)
{
nextToken = lexer.lex();
solo_respons();
}
else{
cout << "ERROR!!! : Expected for_my" << endl;
if (cin.get())
{
exit(0);
}
}
}
else{
cout << "ERROR!!! : Expected I_need_a" << endl;
if (cin.get())
{
exit(0);
}
}
}
void SyntaxAnalyzer::solo_respons()
{
quality();
solo_class_actions();
}
void SyntaxAnalyzer::solo_class_actions()
{
if (nextToken = notes || nextToken == writing || nextToken == problems || nextToken == answers || nextToken == questions)
{
cout << "You did stuff in class!" << endl;
nextToken = lexer.lex();
}
}
void SyntaxAnalyzer::participation_grade()
{
if (nextToken == I_have_a)
{
cout << "You have a grade in participation!" << endl;
nextToken = lexer.lex();
grade();
}
else
{
cout << "ERROR!!! : Expected I_have_a" << endl;
if (cin.get())
{
exit(0);
}
}
if (nextToken == in_participation)
{
nextToken = lexer.lex();
if (nextToken == my_grade_is)
{
cout << "Youre going to tell us what you think of your grade!" << endl;
nextToken = lexer.lex();
quality();
}
}
else{
cout << "ERROR!!! : Expected in_participation" << endl;
if (cin.get())
{
exit(0);
}
}
}
void SyntaxAnalyzer::homework()
{
hw_properties();
if (nextToken == also)
{
nextToken = lexer.lex();
what_hw_is();
nextToken = lexer.lex();
}
else{
cout << "ERROR!!! : Expected also" << endl;
if (cin.get())
{
exit(0);
}
}
}
void SyntaxAnalyzer::hw_properties()
{
due();
if (nextToken == it_is)
{
nextToken = lexer.lex();
quality();
}
else{
cout << "ERROR!!! : Expected it_is" << endl;
if (cin.get())
{
exit(0);
}
}
}
void SyntaxAnalyzer::due()
{
if (nextToken == Homework_is_due)
{
nextToken = lexer.lex();
day();
if (nextToken == and)
{
while (nextToken == and)
{
nextToken = lexer.lex();
day();
}
}
if (nextToken == Turned_Homework_in)
{
cout << "Good you turned in your homework!" << endl;
nextToken = lexer.lex();
day();
}
}
else
{
cout << "ERROR!!! : Expected Homework_is_due" << endl;
if (cin.get())
{
exit(0);
}
}
}
void SyntaxAnalyzer::day()
{
if (nextToken == tomorrow || nextToken == Monday || nextToken == Tuesday|| nextToken == Wednesday || nextToken == Thursday || nextToken == Friday)
{
//cout << "cool day!" << endl;
nextToken = lexer.lex();
}
else{
cout << "ERROR!!! : Expected a day of the week after and" << endl;
if (cin.get())
{
exit(0);
}
}
}
void SyntaxAnalyzer::what_hw_is()
{
if (nextToken == It_is)
{
nextToken = lexer.lex();
hw_type();
if (nextToken == requiring)
{
nextToken = lexer.lex();
school_thing();
}
else{
cout << "ERROR!!! : Expected requiring" << endl;
if (cin.get())
{
exit(0);
}
}
}
else{
cout << "ERROR!!! : Expected It_is" << endl;
if (cin.get())
{
exit(0);
}
}
}
void SyntaxAnalyzer::hw_type()
{
if (nextToken == project || nextToken == paper || nextToken == exercises)
{
cout << "You have some type of homework!" << endl;
nextToken = lexer.lex();
}
else{
cout << "ERROR!!! : Expected a hw_type terminal" << endl;
if (cin.get())
{
exit(0);
}
}
} | true |
772501c2d8293af38b0a9c6987697367c7e96d5f | C++ | sttie/game_of_patterns | /include/model/field.h | UTF-8 | 2,667 | 2.578125 | 3 | [] | no_license | #pragma once
#include <cstdint>
#include <tuple>
#include <optional>
#include <vector>
#include <game_objects/npc.h>
#include <model/cell.h>
#include <game_objects/player.h>
#include <logging/notifier.h>
#include <common.h>
#include <snapshots/field_snapshot.h>
namespace Model {
class Field {
public:
enum class Move {
UP,
RIGHT,
DOWN,
LEFT
};
static Field& GetField(int rows_,
int columns_,
int cell_size_);
static Field& GetField();
static void ClearField();
Field(const Field& other_field) = delete;
Field& operator=(const Field& other_field) = delete;
Field(Field&& other_field) noexcept;
Field& operator=(Field&& other_field) noexcept;
std::vector<Cell>& operator[](int index);
const std::vector<Cell>& operator[](int index) const;
bool IsNPC(int x, int y) const;
bool IsEnter(int x, int y) const;
bool IsExit(int x, int y) const;
bool IsObstacle(int x, int y) const;
bool IsLivesUp(int x, int y) const;
bool IsScoresUp(int x, int y) const;
bool IsPortal(int x, int y) const;
bool IsEmpty(int x, int y) const;
int Rows() const;
int Columns() const;
int CellSize() const;
bool IsGameOver() const;
int PlayerX() const;
int PlayerY() const;
int PlayerLives() const;
int PlayerScores() const;
void MovePlayer(const Move& direction);
void AddListener(Logging::Notifier::ListenerPtr new_listener);
auto begin();
auto end();
const auto begin() const;
const auto end() const;
void AddNPC(std::shared_ptr<GameObject::NPC> npc);
void UpdateEnemies();
const Snapshots::FieldSnapshot& SaveField(std::string name, Common::Date creation_date);
void RestoreField(const Snapshots::FieldSnapshot& restore_snapshot) noexcept;
private:
Field() = default;
Field(int rows_,
int columns_,
int cell_size_);
void FillField();
static std::shared_ptr<Field> field;
std::vector<std::vector<Cell>> cells{};
std::vector<std::shared_ptr<GameObject::NPC>> npcs{};
int rows;
int columns;
int cell_size;
GameObject::Player player{0, 9};
Logging::Notifier notifier;
std::optional<Snapshots::FieldSnapshot> field_snapshot;
};
// Inline для external linkage
inline std::shared_ptr<Field> Field::field = nullptr;
} | true |
428e08b6568dca78556c9f3084f514ba4556a81d | C++ | klzwii/UDPSpeeder | /RS.cpp | UTF-8 | 4,298 | 2.578125 | 3 | [] | no_license | //
// Created by liuze on 2021/4/12.
//
#include "RS.h"
#include <cstdio>
#include <cstring>
void RS::encode(uint8_t **shards, unsigned ShardLength) {
for (int i = DataShards; i < DataShards + FECShards; i++) {
for (int j = 0; j < ShardLength; j++) {
for (int k = 0; k < DataShards; k++) {
shards[i][j] ^= galois::mul(encodeMatrix[i][k], shards[k][j]);
}
}
}
}
void RS::decode(uint8_t **shards, unsigned ShardLength, const bool validShards[]) {
galois::gf originMat[DataShards][DataShards];
galois::gf invMat[DataShards][DataShards];
memset(originMat, 0, sizeof(originMat));
memset(invMat, 0, sizeof(invMat));
int j = DataShards;
for (int i = 0; i < DataShards; i++) {
invMat[i][i] = 1;
if (!validShards[i]) {
bool valid = false;
for (; j < DataShards + FECShards; j++) {
if (validShards[j]) {
memcpy(shards[i], shards[j], ShardLength * sizeof(galois::gf));
memcpy(originMat[i], encodeMatrix[j], DataShards * sizeof(galois::gf));
valid = true;
j++;
break;
}
}
if (!valid) {
printf("don't have enough shards to recover data");
return;
}
} else {
originMat[i][i] = 1;
}
}
#ifdef debug
galois::gf originMatCopy[DataShards][DataShards];
memcpy(originMatCopy, originMat, sizeof(originMat));
#endif
// first step transform into upper triangle matrix
for (int i = 0; i < DataShards; i++) {
if (validShards[i]) {
continue;
}
for (j = 0; j < i; j++) {
if (originMat[i][j]) {
galois::gf factor = originMat[i][j];
for (int k = 0; k < DataShards; k++) {
originMat[i][k] ^= galois::mul(originMat[j][k], factor);
invMat[i][k] ^= galois::mul(invMat[j][k], factor);
}
}
}
galois::gf factor = originMat[i][i];
for (j = 0; j < DataShards; j++) {
originMat[i][j] = galois::div(originMat[i][j], factor);
invMat[i][j] = galois::div(invMat[i][j], factor);
}
}
for (int i = DataShards - 1; i >= 1; i--) {
for (j = i - 1; j >= 0; j--) {
if (validShards[j]) {
continue;
}
galois::gf factor = originMat[j][i];
for (int k = 0; k < DataShards; k++) {
originMat[j][k] ^= galois::mul(factor, originMat[i][k]);
invMat[j][k] ^= galois::mul(factor, invMat[i][k]);
}
}
}
int curFec = DataShards;
for (int i = 0; i < DataShards; i++) {
if (validShards[i]) {
continue;
}
memset(shards[curFec], 0, sizeof(galois::gf) * ShardLength);
for (j = 0; j < ShardLength; j++) {
for (int k = 0; k < DataShards; k++) {
shards[curFec][j] ^= galois::mul(invMat[i][k], shards[k][j]);
}
}
++curFec;
}
curFec = DataShards;
for (int i = 0; i < DataShards; i++) {
if (validShards[i]) {
continue;
}
memcpy(shards[i], shards[curFec], sizeof(galois::gf) * ShardLength);
++curFec;
}
#ifdef debug
for (int i = 0; i < DataShards; i ++) {
for (j = 0; j < DataShards; j ++) {
printf("%d ", (int)invMat[i][j]);
}
printf("\n");
}
for (int i = 0; i < DataShards; i ++) {
for (j = 0; j < DataShards; j ++) {
printf("%d ", (int)originMatCopy[i][j]);
}
printf("\n");
}
galois::gf testMat[DataShards][DataShards];
memset(testMat, 0, sizeof(testMat));
for (int i = 0; i < DataShards; i ++) {
for (j = 0; j < DataShards; j ++) {
for (int k = 0; k < DataShards; k++ ) {
testMat[i][j] ^= galois::mul(originMatCopy[i][k], invMat[k][j]);
}
}
}
for (int i = 0; i < DataShards; i ++) {
for (j = 0; j < DataShards; j ++) {
printf("%d ", (int)testMat[i][j]);
}
printf("\n");
}
#endif
}
| true |
aafe8c2e3870545553f19f95d534b16f1271c307 | C++ | NightCreature/SpaceSim | /SpaceSim/Input/InputState.cpp | UTF-8 | 2,424 | 2.84375 | 3 | [] | no_license | #include "Input/InputState.h"
#include "Math/MathUtilityFunctions.h"
#include "Input/InputSystem.h"
#ifdef _DEBUG
///-----------------------------------------------------------------------------
///! @brief TODO enter a description
///! @remark
///-----------------------------------------------------------------------------
void InputState::printState() const
{
MSG_TRACE_CHANNEL("Input State", "/**********************INPUT STATE DATA*********************************/");
for (auto inputAction : m_inputState)
{
MSG_TRACE_CHANNEL( "Input State", "Input state for action %s is value %f ", InputSystem::m_actionNames[inputAction.getAction()].c_str(), inputAction.getValue());
}
}
#endif
///-----------------------------------------------------------------------------
///! @brief TODO enter a description
///! @remark
///-----------------------------------------------------------------------------
void InputState::mergeInputState(const InputState& input)
{
#ifdef _DEBUG
static bool test = false;
if (test)
{
printState();
}
#endif
for (auto standardInputAction : input.m_inputState)
{
//Does this action exist in the current input state?
InputStateMap::iterator it = std::find_if(m_inputState.begin(), m_inputState.end(), [standardInputAction](const StandardInputAction& inputAction) { return inputAction.getAction().getType() == standardInputAction.getAction().getType(); });
if (it != m_inputState.end())
{
float currentValue = it->getValue();
float inputValue = standardInputAction.getValue();
//Different signs, take the difference, need to figure out which one is bigger or negative
currentValue = currentValue + inputValue;
currentValue = math::clamp(currentValue, 0.0f, 1.0f);
#ifdef _DEBUG
if (test)
{
MSG_TRACE_CHANNEL("Input State", "During merging %s value will change to %f", InputSystem::m_actionNames[standardInputAction.getAction()].c_str(), currentValue);
}
#endif
it->setValue(currentValue);
}
else
{
//Value is not found in the current input set so we should add it to it.
m_inputState.push_back(standardInputAction);
}
}
#ifdef _DEBUG
if (test)
{
printState();
input.printState();
}
#endif
}
| true |
2403ab95db95841a714cc0122c0e0c2c73fd96c7 | C++ | gammabray/Mario-Stuff | /mario cplus/Tile.hpp | UTF-8 | 906 | 2.8125 | 3 | [] | no_license | #pragma once
#ifndef TILE_HPP
#define TILE_HPP
#include <SFML\Graphics.hpp>
#include <memory>
#include "DisplayObject.hpp"
namespace Game {
enum tileID : char {
DIRT = '1',
SNOW, // 2
SAND, // 3
METAL,// 4
DLTOP,// 5
DRTOP,// 6
DLBOT,// 7
DRBOT,// 8
DLEDGE = 'G',
DREDGE, //H
DTEDGE, //I
DBEDGE, //J
DMIDDLE, //K
POWERUP = 'P',
CHECKPOLE = 'C',
CHECKFLAG = 'D',
FINISHFLAG = 'F',
};
class Tile : public DisplayObject
///<summary>
///Class : Tile
///
///A class for each tile (Each bit of the level). Solely used by
///the Level class to draw multiple tiles with one call of draw.
///</summary>
{
protected:
public:
tileID ID;
void Draw(sf::RenderTarget & target,const sf::RenderStates & states) const;
Tile(const sf::Vector2f & startPos, const sf::Vector2f & startSize, std::string location, int ID);
};
}
#endif | true |
cece1307937317875a56eca77429b87ae28bc2de | C++ | wfnuser/POJ | /1273.DrainageDitches/main.cpp | UTF-8 | 1,214 | 2.609375 | 3 | [] | no_license | #include<iostream>
#include<string.h>
#include<cstdio>
#include<queue>
using namespace std;
#define min(a,b) (a<b?a:b)
#define INF 1000000
const int MAX = 210;
struct Node
{
int c;
int f;
};
int sx,ex;
int pre[MAX];
Node map[MAX][MAX];
int n,m;
bool BFS()
{
memset(pre,0,sizeof(pre));
queue<int> Q;
Q.push(sx);
pre[sx] = 1;
while(!Q.empty()){
int d = Q.front();
Q.pop();
for(int i=1;i<=n;i++){
if(!pre[i]&&map[d][i].c-map[d][i].f){
pre[i] = pre[d] + 1;
Q.push(i);
}
}
}
return pre[ex]!=0;
}
int dinic(int pos, int flow)
{
int f = flow;
if(pos == ex)
return flow;
for(int i=1;i<=n;i++){
if(map[pos][i].c-map[pos][i].f && pre[pos]+1==pre[i]){
int a = map[pos][i].c - map[pos][i].f;
int t = dinic(i,min(a,flow));
map[pos][i].f+=t;
map[i][pos].f-=t;
flow-=t;
return t;
}
}
return f-flow;
}
int solve()
{
int sum=0;
cout<<"solve start"<<endl;
while(BFS()){
sum += dinic(sx,INF);
}
return sum;
}
int main()
{
int u,v,w;
while(cin>>m>>n){
sx = 1;
ex = n;
cout<<"start"<<endl;
memset(map,0,sizeof(map));
for(int i=1;i<=m;i++){
cin>>u>>v>>w;
map[u][v].c+=w;
}
cout<<"end"<<endl;
cout<<solve()<<endl;
}
return 0;
}
| true |
581371cc8a3c24b63b5521d2b212f60704f8ffa1 | C++ | a6461/Qt-PyQt | /C++/I/05-FORMS/4/form.cpp | UTF-8 | 1,152 | 2.578125 | 3 | [] | no_license | #include "form.h"
#include "ui_form.h"
Form::Form(QWidget *parent) :
QWidget(parent),
ui(new Ui::Form)
{
ui->setupUi(this);
setFixedSize(size());
form2->setWindowFlags(Qt::Dialog | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint);
form3->setWindowFlags(Qt::Dialog | Qt::WindowCloseButtonHint);
connect(form2, SIGNAL(visibleChanged(bool)), this, SLOT(setPushButtonText(bool)));
connect(form3, SIGNAL(windowTitlesChanged(QString,QString)), this, SLOT(setWindowTitles(QString,QString)));
}
Form::~Form()
{
delete ui;
}
void Form::on_pushButton_clicked()
{
form2->move(geometry().right() - 10, geometry().bottom() - 10);
if (form2->isVisible())
form2->close();
else
form2->show();
}
void Form::on_pushButton_2_clicked()
{
form3->show();
}
void Form::setPushButtonText(bool visible)
{
ui->pushButton->setText(visible ? "Открыть подчиненное окно" :
"Закрыть подчиненное окно");
}
void Form::setWindowTitles(const QString &title1, const QString &title2)
{
setWindowTitle(title1);
form2->setWindowTitle(title2);
}
| true |
7e294608da8b741d12fc5a97e2ecab8d5a39cd93 | C++ | raychaudhuri-amitava/prog | /c++/double_arithmetic/double_arithmetic.cc | UTF-8 | 1,844 | 3.171875 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<stdint.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <limits.h>
using namespace std;
template <class T>
std::ostream& safe_write(std::ostream& s, const T& val )
{
s.write( reinterpret_cast<const char *>(&val), sizeof(T) );
return s;
}
template<class T>
inline bool safe_read(int filefd, T &val) {
//Read one T at a time.
bool done = false;
uint32_t tries = 0; //Try max 10 times.
ssize_t b = read(filefd, reinterpret_cast<char*>(&val), sizeof(T));
return true;
}
int main(void){
double ubd = 768.0;
uint32_t ubu = 768;
double capd = ubd/0.77;
uint32_t capu = ubu/0.77;
cout<<"Double = "<<capd<<" Uint = "<<capu<<endl;
for(uint64_t x = 0; x < ULONG_MAX; x++) {
ofstream os("a.txt", ios::trunc);
uint32_t y = 63;
double xd = static_cast<double>(x);
double yd = static_cast<double>(y);
//cout<<"x = "<<xd<<" xu = "<<x<<" y = "<<yd<<" yu = "<<y<<endl;
safe_write(os,xd);
safe_write(os,yd);
os.close();
int fd = open("a.txt", O_RDONLY);
double xdd = 0.0;
double ydd = 0.0;
uint64_t xu = 0;
uint32_t yu = 0;
safe_read(fd, xdd);
safe_read(fd, ydd);
close(fd);
xu = static_cast<uint64_t>(xdd);
yu = static_cast<uint32_t>(ydd);
//cout<<"x = "<<xdd<<" xu = "<<xu<<" y = "<<ydd<<" yu = "<<yu<<endl;
xd = x;
//if(xd<xdd) cout<<"less than"<<endl;
//else cout<<"greater than or equal to"<<endl;
if(xd != xdd){
cout <<"no equal equal !!!"<<endl;
cout<<"x = "<<xdd<<" xu = "<<xu<<" y = "<<ydd<<" yu = "<<yu<<endl;
}
if(xd > xdd){
cout <<"Greater !!!"<<endl;
cout<<"x = "<<xdd<<" xu = "<<xu<<" y = "<<ydd<<" yu = "<<yu<<endl;
}
if(xd < xdd){
cout <<"Less !!!"<<endl;
cout<<"x = "<<xdd<<" xu = "<<xu<<" y = "<<ydd<<" yu = "<<yu<<endl;
}
}
return 0;
}
| true |
a7ca56d5fc3da36396fdd051e05781aca1285657 | C++ | anonymouss/cpp_notes | /head_first_design_patterns/10_State_Pattern/src/GumballMachine.cpp | UTF-8 | 5,449 | 2.703125 | 3 | [] | no_license | #include "GumballMachine.h"
#include <iostream>
constexpr int DEFAULT_COUNT = 5;
struct GumballMachine::BaseState : public IState {
explicit BaseState(GumballMachine *machine) : mMachine(machine) {}
virtual ~BaseState() = default;
virtual void insertQuarter() override{};
virtual void ejectQuarter() override{};
virtual void turnCrank() override{};
virtual void dispense() override{};
virtual std::string toString() const { return mName; }
std::string mName = "[BaseState]";
GumballMachine *mMachine;
};
struct GumballMachine::NoQuarterState : public GumballMachine::BaseState {
explicit NoQuarterState(GumballMachine *machine) : BaseState(machine) {}
virtual void insertQuarter() final {
std::cout << "[INFO] you inserted quarter" << std::endl;
mMachine->changeState(mMachine->mHasQuarterState);
}
virtual void ejectQuarter() final {
std::cout << "[ERROR] you have not insert quarter" << std::endl;
};
virtual void turnCrank() final {
std::cout << "[ERROR] you have not insert quarter" << std::endl;
};
virtual void dispense() final {
std::cout << "[ERROR] you have not insert quarter" << std::endl;
};
virtual std::string toString() const final { return mName; }
std::string mName = "[NoQuarterState]";
};
struct GumballMachine::HasQuarterState : public GumballMachine::BaseState {
explicit HasQuarterState(GumballMachine *machine) : BaseState(machine) {}
virtual void insertQuarter() final {
std::cout << "[ERROR] you have already insert quarter" << std::endl;
}
virtual void ejectQuarter() final {
std::cout << "[INFO] ok, give back quarter to you" << std::endl;
mMachine->changeState(mMachine->mNoQuarterState);
};
virtual void turnCrank() final {
std::cout << "[INFO] turning crank..." << std::endl;
mMachine->changeState(mMachine->mSoldState);
};
virtual void dispense() final { std::cout << "[ERROR] no gumball dispense" << std::endl; };
virtual std::string toString() const final { return mName; }
std::string mName = "[HasQuarterState]";
};
struct GumballMachine::SoldState : public GumballMachine::BaseState {
explicit SoldState(GumballMachine *machine) : BaseState(machine) {}
virtual void insertQuarter() final {
std::cout << "[ERROR] please wait, an order is handling" << std::endl;
}
virtual void ejectQuarter() final {
std::cout << "[ERROR] sorry, you have already turnned the crank" << std::endl;
};
virtual void turnCrank() final {
std::cout << "[ERROR] oh. you can't turn the crank twice" << std::endl;
};
virtual void dispense() final {
mMachine->releaseGumball();
if (mMachine->isEmpty()) {
mMachine->changeState(mMachine->mSoldOutState);
} else {
mMachine->changeState(mMachine->mNoQuarterState);
}
};
virtual std::string toString() const final { return mName; }
std::string mName = "[SoldState]";
};
struct GumballMachine::SoldOutState : public GumballMachine::BaseState {
explicit SoldOutState(GumballMachine *machine) : BaseState(machine) {}
virtual void insertQuarter() final {
std::cout << "[ERROR] gumball sold out... don't insert quater" << std::endl;
}
virtual void ejectQuarter() final { std::cout << "[ERROR] gumball sold out..." << std::endl; };
virtual void turnCrank() final { std::cout << "[ERROR] gumball sold out..." << std::endl; };
virtual void dispense() final { std::cout << "[ERROR] gumball sold out..." << std::endl; };
virtual std::string toString() const final { return mName; }
std::string mName = "[SoldOutState]";
};
GumballMachine::GumballMachine() {
mGumballCounts = DEFAULT_COUNT;
mNoQuarterState = std::make_shared<NoQuarterState>(this);
mHasQuarterState = std::make_shared<HasQuarterState>(this);
mSoldState = std::make_shared<SoldState>(this);
mSoldOutState = std::make_shared<SoldOutState>(this);
mState = std::make_shared<BaseState>(this);
if (mGumballCounts > 0) {
changeState(mNoQuarterState);
} else {
changeState(mSoldOutState);
}
}
void GumballMachine::setGumballCount(int count) {
if (mState == mNoQuarterState || mState == mSoldOutState) {
mGumballCounts = count;
} else {
std::cout << "[ERROR] transaction in progress, invalid state to set count" << std::endl;
return;
}
if (mGumballCounts > 0) {
changeState(mNoQuarterState);
} else {
changeState(mSoldOutState);
}
}
void GumballMachine::changeState(std::shared_ptr<GumballMachine::BaseState> state) {
if (mState == state) {
std::cout << "[WARNING] State Unchanged!" << std::endl;
return;
}
std::cout << "[INFO] " << mState->toString() << " -> " << state->toString() << std::endl;
mState = state;
}
void GumballMachine::releaseGumball() {
std::cout << "[INFO] a gumball comes rolling out the slot..." << std::endl;
--mGumballCounts;
}
bool GumballMachine::isEmpty() const { return mGumballCounts <= 0; }
void GumballMachine::insertQuarter() { mState->insertQuarter(); }
void GumballMachine::ejectQuarter() { mState->ejectQuarter(); }
void GumballMachine::turnCrank() {
mState->turnCrank();
dispense();
}
void GumballMachine::dispense() { mState->dispense(); } | true |
2f0251345449bd9073c7812e73278fb57c3ab6ec | C++ | leobang17/algorithms-assignment | /Algorithms02/Algorithms02_04.cpp | UTF-8 | 1,001 | 3.53125 | 4 | [] | no_license | #include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS
int binarySearch(int arr[], int target, int start, int end);
void arrayPrinter(int arr[], int arrayLen);
int main(void) {
int arr[9] = { 12, 34, 37, 45, 57, 82, 99, 120, 134 };
int target;
int start = 0;
int end = (sizeof(arr) / sizeof(int)) - 1;
arrayPrinter(arr, sizeof(arr) / sizeof(int));
printf("Target Integer : ");
scanf_s("%d", &target);
int k = binarySearch(arr, target, start, end);
printf("target found : %d", k);
}
int binarySearch(int arr[], int target, int start, int end) {
int centre = (end + start) / 2;
if (arr[centre] == target)
return arr[centre];
else if (arr[centre] < target) {
return binarySearch(arr, target, centre + 1, end);
}
else if (arr[centre] > target) {
return binarySearch(arr, target, start, centre - 1);
}
else;
}
void arrayPrinter(int arr[], int arrayLen) {
printf("Current Array : [ ");
for (int i = 0; i < arrayLen; i++) {
printf("%d ", *(arr + i));
}
printf("]\n\n");
} | true |
c68ba0daf6a3e188bc53e83003a07772b04cb7a2 | C++ | metodos-computacionales-1/ejercicio13-JFRodriguezH | /ejercicio_c_13.cpp | UTF-8 | 1,724 | 3.515625 | 4 | [] | no_license | #include <iostream>
int fill(int **m, int N);
int producto(int **m, int **n, int **mult, int N);
int main(){
std::cout.precision(16);
std::cout.setf(std::ios::scientific);
int N;
std::cout<<"Escriba el valor de N: "<<std::endl;
std::cin>> N;
std::cout<<std::endl;
int **m;
m = new int *[N];
for(int i = 0; i <N; i++)
m[i] = new int[N];
int **n;
n = new int *[N];
for(int i = 0; i <N; i++)
n[i] = new int[N];
int **mult;
mult = new int *[N];
for(int i = 0; i <N; i++)
mult[i] = new int[N];
for(int i=0; i<N; i++){
for(int j=0; j<N; j++){
mult[i][j]=0;
}
}
fill(m, N);
fill(n, N);
producto(m, n, mult, N);
for(int i=0; i<N; i++){
for(int j=0; j<N; j++){
std::cout<< mult[i][j] << " ";
}
std::cout<<std::endl;
}
return 0;
}
int fill(int **m, int N){
for(int i=0; i < N; i++){
for(int j=0; j < N; j++){
if(i==0){
m[i][j] = 2;
if(j==N-1){
m[i][j] = 1-N;
}
} else{
if((i-1)==j){
m[i][j]=N+2;
} else if(j==N-1){
m[i][j] = -N;
} else {
m[i][j] = 1;
}
}
}
}
return 0;
}
int producto(int **m, int **n, int **mult, int N){
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
int suma=0;
for(int k=0;k<N;k++){
suma += m[i][k] * n[k][j];
}
mult[i][j]=suma;
}
}
return 0;
}
| true |
962c2ac3a20b1ce1b852e37afae1420ff92752ca | C++ | gnuevo/median-data-structure | /tests.cpp | UTF-8 | 1,200 | 3.34375 | 3 | [] | no_license | #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch2/catch.hh"
#include "data_structure.hh"
#include <iostream>
using namespace std;
TEST_CASE( "Test the computing of the median", "[median]" ) {
int i;
DataStructure data;
SECTION( "Trying with 0..8 numbers (odd)" ) {
int n = 9;
int numbers[n] = {3, 5, 0, 8, 7, 6, 4, 2, 1};
for (i = 0; i < n; i++) {
data.add(numbers[i]);
}
REQUIRE( data.median() == 4.0 );
}
SECTION( "Trying with 0..7 numbers (even)" ) {
int n = 8;
int numbers[n] = {3, 5, 0, 7, 6, 4, 2, 1};
for (i = 0; i < n; i++) {
data.add(numbers[i]);
}
REQUIRE( data.median() == 3.5 );
}
SECTION( "Trying with -10.0..5.0 (decimals and negatives)" ) {
int n = 21;
float numbers[n] = {-4.75, -7.75, -7.0, 0.5, -2.5, -5.5, -9.25, 5.0, -0.25, -1.75, -10.0, 2.0, -4.0, -1.0, 3.5, -3.25, -8.5, 4.25, 2.75, 1.25, -6.25};
for (i = 0; i < n; i++) {
data.add(numbers[i]);
}
REQUIRE( data.median() == -2.5 );
}
}
| true |
2203edcc3243fd1d4fb06f1845fa45fe31ecbcf1 | C++ | TWLK139/Discrete-Prim | /Prim/Prim.cpp | GB18030 | 5,446 | 2.734375 | 3 | [] | no_license | #include<iostream>
#include <cstdlib>
#include <ctime>
#include<stdlib.h>
#define INF 65535 //
#define MaxVerNum 8 //
typedef int elementType; //ͼж
typedef float eInfotype; //eInfoͣȨֵ
typedef struct eNode //Ľṹ
{
int adjVer; //ڽӶϢ˴Ϊţ1ʼ
eInfotype eInfo; //бʾߵϢߵȨֵ
struct eNode* next; //ָеһ
} EdgeNode; //
typedef struct vNode //嶥Ľṹ
{
elementType data; //ͼжݽṹ
EdgeNode* firstEdge; //ָ˶ĵһߵָ룬ͷָ
} VerNode; //
typedef struct GraphAdjLinkList //ͼṹ
{
VerNode VerList[MaxVerNum]; //
int VerNum; //
int ArcNum; //
} Graph; //ͼ
typedef struct minEdgeType
{
int v; //ѡһζ˵Ķ
eInfotype eWeight; //ߵȨֵ
} MinEdgeType; //Ԫ
typedef struct result //洢Ľṹ
{
elementType begin[MaxVerNum - 1]; //ʼ
eInfotype weight[MaxVerNum - 1]; //Ȩֵ
elementType end[MaxVerNum - 1]; //
} resType;
bool visited[MaxVerNum] = { false };
bool HasEdge(Graph& G, int vBegin, int vEnd, eInfotype& eWeight);
void InitialTE(Graph& G, MinEdgeType TE[], int vID);
int GetMinEdge(Graph& G, MinEdgeType TE[]);
void UpdateTE(Graph& G, MinEdgeType TE[], int vID);
void Prim(Graph& G, int vID, resType &res);
using namespace std;
int main(void)
{
Graph oilPipeline;
EdgeNode * ep = nullptr, * newEp = nullptr;
eInfotype eInfo[MaxVerNum][MaxVerNum] = { {0,1.3,2.1,0.9,0.7,1.8,2.0,1.8},{1.3,0,0.9,1.8,1.2,2.8,2.3,1.1},{2.1,0.9,0,2.6,1.7,2.5,1.9,1.0},{0.9,1.8,2.6,0,0.7,1.6,1.5,0.9},{0.7,1.2,1.7,0.7,0,0.9,1.1,0.8},{1.8,2.8,2.5,1.6,0.9,0,0.6,1.0},{2.0,2.3,1.9,1.5,1.1,0.6,0,0.5},{1.8,1.1,1.0,0.9,0.8,1.0,0.5,0} };
resType minOilPipeline;
eInfotype allLength = 5;
oilPipeline.ArcNum = 0;
for (int i = 0; i < MaxVerNum; i++)
{
for (int j = 0; j < MaxVerNum; j++)
{
if (i == (MaxVerNum - 1 - j)) {
continue;
}
newEp = new EdgeNode;
newEp->next = ep;
newEp->adjVer = 8 - j;
newEp->eInfo = eInfo[i][MaxVerNum - 1 - j];
ep = newEp;
oilPipeline.ArcNum++;
}
oilPipeline.VerList[i].data = i + 1;
oilPipeline.VerList[i].firstEdge = ep;
}
oilPipeline.ArcNum /= 2;
oilPipeline.VerNum = MaxVerNum;
//ʹPrim㷨
Prim(oilPipeline, 1, minOilPipeline);
//ӡ
for (int j = 0; j < MaxVerNum - 1; j++)
{
allLength += minOilPipeline.weight[j];
cout << "ʼ" << minOilPipeline.begin[j] << "" << minOilPipeline.end[j] << endl;
}
cout << "裺" << allLength << "ǧס" << endl;
//ͷĿռ
for (int i = 0; i < MaxVerNum; i++)
{
for (int j = 0; j < MaxVerNum-1; j++)
{
newEp = oilPipeline.VerList[i].firstEdge;
oilPipeline.VerList[i].firstEdge = newEp->next;
free(newEp);
}
}
return 0;
}
//ܣж϶vBeginvEnde֮ǷбߣرߵȨֵ
//أtrueΪбߣfalseΪޱߣeWeightΪߵȨֵ
bool HasEdge(Graph& G, int vBegin, int vEnd, eInfotype& eWeight)
{
EdgeNode* p;
bool f = false;
eWeight = INF;
p = G.VerList[vBegin - 1].firstEdge;
while (p)
{
if (p->adjVer == vEnd)
{
f = true;
eWeight = p->eInfo;
break;
}
p = p->next;
}
return f;
}
//ܣʼTE
void InitialTE(Graph& G, MinEdgeType TE[], int vID)
{
int i;
eInfotype eWeight; //Ȩֵ
for (i = 1; i <= G.VerNum; i++)
{
//ʼTE[]
if (HasEdge(G, vID, i, eWeight))
{
TE[i - 1].v = vID; //ߣvIDi֮ı
TE[i - 1].eWeight = eWeight; //ߵȨֵ
}
else
{
TE[i - 1].eWeight = INF; //vIDi֮ûбߣȨֵΪ
}
}
}
//ܣӱTE[]лȡȨֵСĺѡ
//أѡһ˵Ķ
int GetMinEdge(Graph& G, MinEdgeType TE[])
{
eInfotype eMin = INF; //СȨֵʼΪ
int i, j = 0;
for (i = 1; i <= G.VerNum; i++)
{
if (visited[i - 1] == false && TE[i - 1].eWeight < eMin)
{
j = i;
eMin = TE[i - 1].eWeight;
}
}
return j; //ӦıߣTE[j-1].v, jΪѡеı
}
//ܣvIDѡбΪѡºѡ
void UpdateTE(Graph& G, MinEdgeType TE[], int vID)
{
int i, j;
eInfotype eWeight;
for (i = 1; i <= G.VerNum; i++)
{
if (visited[i - 1] == false)
{
if (HasEdge(G, vID, i, eWeight) && eWeight < TE[i - 1].eWeight)
{
TE[i - 1].v = vID;
TE[i - 1].eWeight = eWeight;
}
}
}
}
//Prim㷨
void Prim(Graph& G, int vID, resType& res)
{
MinEdgeType TE[MaxVerNum];
int i;
int curID;
InitialTE(G, TE, vID);
visited[vID - 1] = true;
for (i = 1; i < G.VerNum; i++)
{
curID = GetMinEdge(G, TE);
visited[curID - 1] = true;
UpdateTE(G, TE, curID);
res.begin[i - 1] = TE[curID - 1].v;
res.weight[i - 1] = TE[curID - 1].eWeight;
res.end[i - 1] = curID;
}
} | true |
c261beb4823e62930640122ca8bf6752e882da2e | C++ | BartoszSiemienczuk/GL_Cubes | /ConsoleApplication1/Camera.cpp | UTF-8 | 665 | 3.078125 | 3 | [] | no_license | #include "Camera.h"
void Camera::setLastPost(Vector3 lastPos)
{
this->lastPos = lastPos;
}
Vector3 Camera::getLastPost()
{
return this->lastPos;
}
void Camera::setVertAngle(float angle)
{
this->vertAngle = angle;
}
float Camera::getVertAngle()
{
return this->vertAngle;
}
void Camera::setAngle(float angle)
{
this->angle = angle;
}
float Camera::getAngle()
{
return this->angle;
}
void Camera::update()
{
glLoadIdentity();
//position is the eye position
//rotation here is really the point to look at
//third vector is "up"
gluLookAt(position.x, 1.0f, position.z,
position.x+rotation.x, rotation.y, position.z+rotation.z,
0.0f, 1.0f, 0.0f);
}
| true |
7ba0d552eeb8551030fe2059e7f0183cba4da327 | C++ | naseem366/Data-Structures-and-Algorithms-master | /Array Data Structures/noble.cpp | UTF-8 | 494 | 3.3125 | 3 | [] | no_license | #include<iostream>
#include<bits/stdc++.h>
using namespace std;
int noble(int arr[],int n)
{
sort(arr,arr+n);
for(int i=0;i<n-1;i++){
if(arr[i]==arr[i+1])
continue;
if(arr[i]==n-i-1){
return arr[i];
}
}
return 1;
}
int main()
{
int arr[] = {10, 3, 20, 40, 2};
int res = noble(arr, 5);
if (res != -1)
cout << "The noble integer is " << res;
else
cout << "No Noble Integer Found";
return 0;
}
| true |
db7eb8574aee0609d55d1e8fe918d0c0f7f173fe | C++ | alkaidlong/PaperDemo | /Dev/Common/MedusaCore/Core/String/BaseString.h | UTF-8 | 20,424 | 2.90625 | 3 | [] | no_license | #pragma once
#include "Core/String/TStringRef.h"
#include "Core/Assertion/CommonAssert.h"
#include "Core/Utility/HashUtility.h"
#include "Core/Memory/Memory.h"
#include "Core/String/StdString.h"
MEDUSA_BEGIN;
template<typename T>
class BaseString
{
public:
const static T LineSeparator=StdString::ConstValues<T>::LineSeparator;
public:
BaseString(T* inBuffer,size_t bufferSize,bool isInitNull=false)
{
mLength=0;
mBuffer=inBuffer;
mBufferSize=bufferSize;
if (mBuffer!=NULL)
{
if (isInitNull)
{
Memory::Set(mBuffer,(char)0,mBufferSize);
}
else
{
mBuffer[0]=0;
}
}
}
virtual ~BaseString(void)
{
}
/*operator const T*()const
{
return mBuffer;
}*/
operator TStringRef<T>()const
{
return TStringRef<T>(mBuffer,mLength);
}
protected:
/*BaseString()
{
}*/
public:
virtual void Clear()=0;
BaseString& operator=(const BaseString& inString)
{
size_t length=inString.Length();
if (length>=mBufferSize)
{
size_t size= Math::GetNewSizeSquare(mBufferSize,length+1);
bool isSuccess=ResizeHelper(size);
MEDUSA_ASSERT_TRUE(isSuccess,"");
UN_USED(isSuccess);
}
mLength=length;
StdString::CopyStringN( mBuffer,mBufferSize, inString.Buffer(), mLength );
mBuffer[mLength] = 0;
return *this;
}
BaseString& operator=(const TStringRef<T>& inString)
{
size_t length=inString.Length();
if (length>=mBufferSize)
{
size_t size= Math::GetNewSizeSquare(mBufferSize,length+1);
bool isSuccess=ResizeHelper(size);
MEDUSA_ASSERT_TRUE(isSuccess,"");
UN_USED(isSuccess);
}
mLength=length;
StdString::CopyStringN(mBuffer,mBufferSize, inString.Buffer(), mLength );
mBuffer[mLength] = 0;
return *this;
}
BaseString& operator+=(const BaseString& inString)
{
Append(inString);
return *this;
}
BaseString& operator+=(const T* inString)
{
Append(inString);
return *this;
}
BaseString& operator+=(TStringRef<T> inString)
{
Append(inString);
return *this;
}
BaseString& operator+=(T inChar)
{
Append(inChar);
return *this;
}
//to be more fast
bool operator==(const TStringRef<T>& inString)const
{
return ToString()==inString;
}
bool operator!=(const TStringRef<T>& inString)const
{
return ToString()!=inString;
}
bool operator>(const TStringRef<T>& inString)const
{
return ToString()>inString;
}
bool operator<(const TStringRef<T>& inString)const
{
return ToString()<inString;
}
bool operator>=(const TStringRef<T>& inString)const
{
return ToString()>=inString;
}
bool operator<=(const TStringRef<T>& inString)const
{
return ToString()<=inString;
}
bool operator==(const BaseString& inString)const
{
return ToString()==inString.ToString();
}
bool operator!=(const BaseString& inString)const
{
return ToString()!=inString.ToString();
}
bool operator>(const BaseString& inString)const
{
return ToString()>inString.ToString();
}
bool operator<(const BaseString& inString)const
{
return ToString()<inString.ToString();
}
bool operator>=(const BaseString& inString)const
{
return ToString()>=inString.ToString();
}
bool operator<=(const BaseString& inString)const
{
return ToString()<=inString.ToString();
}
T& operator[](size_t index)
{
return mBuffer[index];
}
T operator[](size_t index)const
{
return mBuffer[index];
}
bool IsNull()const
{
return mBufferSize==0||mBuffer==NULL;
}
bool IsEmpty()const
{
return mLength==0;
}
bool IsNullOrEmpty()const
{
return mLength==0||mBufferSize==0||mBuffer==NULL;
}
size_t Size()const
{
return mBufferSize;
}
T* c_str(){return mBuffer;}
T* Buffer(){return mBuffer;}
const T* c_str()const{return mBuffer;}
const T* Buffer()const{return mBuffer;}
TStringRef<T> ToString()const{return TStringRef<T>(mBuffer,mLength);}
size_t Length() const { return mLength; }
void ForceSetLength(size_t length) {mLength=length;mBuffer[mLength]=0;}
void ForceUpdateLength()
{
mLength=mBuffer!=NULL?StdString::GetLength(mBuffer):0;
}
intp GetHashCode()const
{
return HashUtility::HashString(mBuffer);
}
public:
int Compare(const TStringRef<T>& inString,bool isIgnoreCase=false)const
{
return ToString().Compare(inString,isIgnoreCase);
}
intp IndexOf(T inFindChar)const
{
RETURN_OBJECT_IF(IsNull(),-1);
return ToString().IndexOf(inFindChar);
}
intp IndexOf(const TStringRef<T>& inString)const
{
RETURN_OBJECT_IF(IsNull(),-1);
return ToString().IndexOf(inString);
}
intp IndexOfAny(const TStringRef<T>& inString)const
{
RETURN_OBJECT_IF(IsNull(),-1);
return ToString().IndexOfAny(inString);
}
intp LastIndexOf(T inFindChar)const
{
RETURN_OBJECT_IF(IsNull(),-1);
return ToString().LastIndexOf(inFindChar);
}
intp LastIndexOfAny(const TStringRef<T>& inString)const
{
RETURN_OBJECT_IF(IsNull(),-1);
return ToString().LastIndexOfAny(inString);
}
intp LastIndexOf(const TStringRef<T>& inString)const
{
RETURN_OBJECT_IF(IsNull(),-1);
return ToString().LastIndexOf(inString);
}
bool Contains(T inFindChar)const
{
RETURN_FALSE_IF(IsNull());
return ToString().Contains(inFindChar);
}
bool Contains(const TStringRef<T>& inString)const
{
RETURN_FALSE_IF(IsNull());
return ToString().Contains(inString);
}
bool ContainsAny(const TStringRef<T>& inString)const
{
RETURN_FALSE_IF(IsNull());
return ToString().ContainsAny(inString);
}
bool BeginWith(const TStringRef<T>& inString)const
{
RETURN_FALSE_IF(IsNull());
return ToString().BeginWith(inString);
}
bool EndWith(const TStringRef<T>& inString)const
{
RETURN_FALSE_IF(IsNull());
return ToString().EndWith(inString);
}
long ToInteger(int radix=10)const
{
RETURN_OBJECT_IF(IsNull(),-1);
return ToString().ToInteger(radix);
}
bool TryParseInteger(long& outResult,int radix=10)const
{
RETURN_FALSE_IF(IsNull());
return ToString().TryParseInteger(outResult,radix);
}
double ToDouble()const
{
return ToString().ToDouble();
}
bool TryParseDouble(double& outResult)const
{
RETURN_FALSE_IF(IsNull());
return ToString().TryParseDouble(outResult);
}
size_t Count(T inChar)const
{
RETURN_OBJECT_IF(IsNull(),-1);
return ToString().Count(inChar);
}
size_t Count(const TStringRef<T>& inString)const
{
RETURN_OBJECT_IF(IsNull(),-1);
return ToString().Count(inString);
}
void CopyTo(const BaseString& outString)
{
RETURN_IF(IsNull());
CopyTo(outString.Buffer(),outString.Size(),0,mLength);
}
void CopyTo(const BaseString& outString,size_t length)
{
RETURN_IF(IsNull());
CopyTo(outString.Buffer(),outString.Size(),0,length);
}
void CopyTo(const BaseString& outString,size_t beginIndex,size_t length)
{
RETURN_IF(IsNull());
CopyTo(outString.Buffer(),outString.Size());
}
void CopyTo(T* outBuffer,size_t outBufferSize)
{
RETURN_IF(IsNull());
CopyTo(outBuffer,outBufferSize,0,mLength);
}
void CopyTo(T* outBuffer,size_t outBufferSize,size_t length)
{
RETURN_IF(IsNull());
CopyTo(outBuffer,outBufferSize,0,length);
}
void CopyTo(T* outBuffer,size_t outBufferSize,size_t beginIndex,size_t length)
{
RETURN_IF(IsNull());
RETURN_IF(beginIndex+length>mLength);
RETURN_IF(length>outBufferSize);
Memory::SafeCopy(outBuffer,outBufferSize,mBuffer+beginIndex,length);
}
TStringRef<T> SubString(size_t index)const
{
if (IsNull())
{
return TStringRef<T>::Empty;
}
return TStringRef<T>(mBuffer+index,mLength-index);
}
public:
void ToCase(bool isLowCase)
{
RETURN_IF(IsNull());
if (isLowCase)
{
ToLower();
}
else
{
ToUpper();
}
}
void ToUpper()
{
RETURN_IF(IsNull());
StdString::ToUpper(mBuffer,mLength);
}
void ToLower()
{
RETURN_IF(IsNull());
StdString::ToLower(mBuffer,mLength);
}
void Reverse()
{
RETURN_IF(IsNull());
StdString::Reverse(mBuffer);
}
void ReplaceAllTo(T inChar)
{
RETURN_IF(IsNull());
StdString::ReplaceAllTo(mBuffer,mBufferSize,inChar);
}
void ReplacelTo(T inChar,size_t count)
{
RETURN_IF(IsNull());
StdString::ReplaceAllToN(mBuffer,mBufferSize,inChar,count);
}
void ReplaceAll(T oldChar,T newChar)
{
RETURN_IF(IsNull());
RETURN_IF(oldChar==newChar);
RETURN_IF(mLength==0);
for (size_t i=0;i<mLength;++i)
{
if (mBuffer[i]==oldChar)
{
mBuffer[i]=newChar;
}
}
}
void ReplaceFirst(T oldChar,T newChar)
{
RETURN_IF(IsNull());
RETURN_IF(oldChar==newChar);
RETURN_IF(mLength==0);
for (size_t i=0;i<mLength;++i)
{
if (mBuffer[i]==oldChar)
{
mBuffer[i]=newChar;
return;
}
}
}
void ReplaceLast(T oldChar,T newChar)
{
RETURN_IF(IsNull());
RETURN_IF(oldChar==newChar);
RETURN_IF(mLength==0);
for (intp i=(intp)mLength-1;i>=0;--i)
{
if (mBuffer[i]==oldChar)
{
mBuffer[i]=newChar;
return;
}
}
}
bool ReplaceAll(const TStringRef<T>& oldString,const TStringRef<T>& newString)
{
RETURN_FALSE_IF(IsNull());
size_t oldLength=oldString.Length();
size_t newLength=newString.Length();
if (oldLength==newLength)
{
T* index=(T*)StdString::FindString(mBuffer,oldString.Buffer());
while(index!=NULL)
{
Memory::SafeCopy(index,mBuffer+mBufferSize-index,newString.Buffer(),newLength);
index+=oldLength;
index=(T*)StdString::FindString(index,oldString.Buffer());
}
}
else if (oldLength>newLength)
{
T* index= (T*)StdString::FindString(mBuffer,oldString.Buffer());
while(index!=NULL)
{
Memory::SafeCopy(index,mBuffer+mBufferSize-index,newString.Buffer(),newLength);
index+=newLength;
Memory::SetZero(index,oldLength-newLength);
index+=oldLength-newLength;
index= (T*)StdString::FindString(index,oldString.Buffer());
}
//do a compress
T* w=mBuffer;
T* r=mBuffer;
T* oldEnd=mBuffer+mLength;
while(r!=oldEnd)
{
if (*r==0)
{
++r;
}
else
{
*w++=*r++;
}
}
*w=0;
mLength=w-mBuffer;
}
else
{
T* index= (T*)StdString::FindString(mBuffer,oldString.Buffer());
if (index==NULL)
{
return true;
}
size_t dis=newLength-oldLength;
while(index!=NULL)
{
if (mLength+dis>=mBufferSize)
{
size_t newSize=Math::GetNewSizeSquare(mBufferSize,mLength+dis+1);
RETURN_FALSE_IF_FALSE(ResizeHelper(newSize));
}
//copy last string
Memory::SafeCopy(index+newLength,mBufferSize+mBuffer-index-newLength,index+oldLength,mLength+mBuffer-index+oldLength);
//copy new string
Memory::SafeCopy(index,mBufferSize+mBuffer-index,newString.Buffer(),newLength);
mLength+=dis;
index= (T*)StdString::FindString(index,oldString.Buffer());
}
}
return true;
}
bool ReplaceFirst(const TStringRef<T>& oldString,const TStringRef<T>& newString)
{
RETURN_FALSE_IF(IsNull());
intp index= IndexOf(oldString);
if (index<0)
{
return false;
}
size_t oldLength=oldString.Length();
size_t newLength=newString.Length();
if (oldLength==newLength)
{
Memory::SafeCopy(mBuffer+index,mBufferSize-index,newString.Buffer(),oldLength);
}
else if(oldLength>newLength)
{
Memory::SafeCopy(mBuffer+index,mBufferSize-index,newString.Buffer(),newLength);
RemoveAt(index+newLength,oldLength-newLength);
}
else
{
size_t dis=newLength-oldLength;
if (mLength+dis>=mBufferSize)
{
size_t newSize=Math::GetNewSizeSquare(mBufferSize,mLength+dis+1);
RETURN_FALSE_IF_FALSE(ResizeHelper(newSize));
}
//copy last string
Memory::SafeCopy(mBuffer+index+newLength,mBufferSize+index-newLength,mBuffer+index+oldLength,mLength+index+oldLength);
//copy new string
Memory::SafeCopy(mBuffer+index,mBufferSize+index,newString.Buffer(),newLength);
mLength+=dis;
}
return true;
}
bool ReplaceLast(const TStringRef<T>& oldString,const TStringRef<T>& newString)
{
RETURN_FALSE_IF(IsNull());
T* w=mBuffer;
T* r=mBuffer;
const T* p=oldString.Buffer();
intp index= LastIndexOf(oldString);
if (index<0)
{
return false;
}
size_t oldLength=oldString.Length();
size_t newLength=newString.Length();
if (oldLength==newLength)
{
Memory::SafeCopy(mBuffer+index,mBufferSize-index,newString.Buffer(),oldLength);
}
else if(oldLength>newLength)
{
Memory::SafeCopy(mBuffer+index,mBufferSize-index,newString.Buffer(),newLength);
RemoveAt(index+newLength,oldLength-newLength);
}
else
{
size_t dis=newLength-oldLength;
if (mLength+dis>=mBufferSize)
{
size_t newSize=Math::GetNewSizeSquare(mBufferSize,mLength+dis+1);
RETURN_FALSE_IF_FALSE(ResizeHelper(newSize));
}
//copy last string
Memory::SafeCopy(mBuffer+index+newLength,mBufferSize+index-newLength,mBuffer+index+oldLength,mLength+index+oldLength);
//copy new string
Memory::SafeCopy(mBuffer+index,mBufferSize+index,newString.Buffer(),newLength);
mLength+=dis;
}
return true;
}
bool RemoveBeginAny(const TStringRef<T>& chars)
{
RETURN_FALSE_IF(IsNull());
T* p=mBuffer;
for (size_t i=0;i<mLength;++i)
{
if(chars.Contains(mBuffer[i]))
{
++p;
}
else
{
break;
}
}
return RemoveAt(0,p-mBuffer);
}
bool RemoveBeginAnyExclude(const TStringRef<T>& chars)
{
RETURN_FALSE_IF(IsNull());
T* p=mBuffer;
for (size_t i=0;i<mLength;++i)
{
if(!chars.Contains(mBuffer[i]))
{
++p;
}
else
{
break;
}
}
return RemoveAt(0,p-mBuffer);
}
bool RemoveBegin(T inChar)
{
RETURN_FALSE_IF(IsNull());
T* p=mBuffer;
for (size_t i=0;i<mLength;++i)
{
if (mBuffer[i]==inChar)
{
++p;
}
else
{
break;
}
}
return RemoveAt(0,p-mBuffer);
}
bool RemoveBeginExclude(T inChar)
{
RETURN_FALSE_IF(IsNull());
T* p=mBuffer;
for (size_t i=0;i<mLength;++i)
{
if (mBuffer[i]!=inChar)
{
++p;
}
else
{
break;
}
}
return RemoveAt(0,p-mBuffer);
}
bool RemoveEnd(T inChar)
{
RETURN_FALSE_IF(IsNull());
T* p=mBuffer+mLength-1;
for (intp i=mLength-1;i>=0;--i)
{
if (mBuffer[i]==inChar)
{
--p;
}
else
{
break;
}
}
return RemoveAt(p-mBuffer+1);
}
bool RemoveEndExclude(T inChar)
{
RETURN_FALSE_IF(IsNull());
T* p=mBuffer+mLength-1;
for (intp i=mLength-1;i>=0;--i)
{
if (mBuffer[i]!=inChar)
{
--p;
}
else
{
break;
}
}
return RemoveAt(p-mBuffer+1);
}
bool RemoveEndAny(const TStringRef<T>& chars)
{
RETURN_FALSE_IF(IsNull());
T* p=mBuffer+mLength-1;
for (intp i=mLength-1;i>=0;--i)
{
if(chars.Contains(mBuffer[i]))
{
--p;
}
else
{
break;
}
}
return RemoveAt(p-mBuffer+1);
}
bool RemoveEndAnyExclude(const TStringRef<T>& chars)
{
RETURN_FALSE_IF(IsNull());
T* p=mBuffer+mLength-1;
for (intp i=mLength-1;i>=0;--i)
{
if(!chars.Contains(mBuffer[i]))
{
--p;
}
else
{
break;
}
}
return RemoveAt(p-mBuffer+1);
}
bool Append(T inChar,size_t count=1)
{
return Insert(mLength,inChar,count);
}
bool Append(const TStringRef<T>& inString)
{
return Insert(mLength,inString);
}
bool Append(const T* buffer,size_t length)
{
return Insert(mLength,buffer,length);
}
bool AppendLine()
{
return Append(LineSeparator);
}
bool AppendLine(T inChar,size_t count=1)
{
if(Insert(mLength,inChar,count))
{
return Append(LineSeparator);
}
return false;
}
bool AppendLine(const TStringRef<T>& inString)
{
if(Insert(mLength,inString))
{
return Append(LineSeparator);
}
return false;
}
bool AppendLine(const T* buffer,size_t length)
{
if(Insert(mLength,buffer,length))
{
return Append(LineSeparator);
}
return false;
}
bool AppendFormat(const T* format,...)
{
RETURN_FALSE_IF_NULL(format);
va_list args;
va_start(args,format);
int length=StdString::GetFormatLength(format,args);
RETURN_FALSE_IF(length<=0);
if ((size_t)length>=mBufferSize)
{
size_t newSize=Math::GetNewSizeSquare(mBufferSize,length+1);
RETURN_FALSE_IF_FALSE(ResizeHelper(newSize));
}
T* temp=new T[length+1];
StdString::VSPrintf(temp,length+1,format,args);
va_end(args);
Append(TStringRef<T>(temp,length));
SAFE_DELETE_ARRAY(temp);
return true;
}
bool Push(T inChar,size_t count=1)
{
return Insert(0,inChar,count);
}
bool Push(const TStringRef<T>& inString)
{
return Insert(0,inString);
}
bool Insert(size_t index,T inChar,size_t count=1)
{
RETURN_FALSE_IF_ZERO(inChar);
RETURN_FALSE_IF_ZERO(count);
RETURN_FALSE_IF(index>mLength);
if (mLength+count>=mBufferSize)
{
size_t size= Math::GetNewSizeSquare(mBufferSize,mLength+count+1);
RETURN_FALSE_IF_FALSE(ResizeHelper(size));
}
Memory::SafeCopy(mBuffer+index+count,mBufferSize-index-count,mBuffer+index,mLength-index);
if (count==1)
{
mBuffer[index]=inChar;
}
else
{
Memory::Set(mBuffer+index,inChar,count);
}
mLength+=count;
mBuffer[mLength]=0;
return true;
}
bool Insert(size_t index,const TStringRef<T>& inString)
{
return Insert(index,inString.Buffer(),inString.Length());
}
bool Insert(size_t index,const T* buffer,size_t length)
{
RETURN_FALSE_IF_NULL(buffer);
RETURN_FALSE_IF_ZERO(length);
RETURN_FALSE_IF(index>mLength);
if (mLength+length>=mBufferSize)
{
size_t size= Math::GetNewSizeSquare(mBufferSize,mLength+length+1);
RETURN_FALSE_IF_FALSE(ResizeHelper(size));
}
RETURN_FALSE_IF(mLength+length>mBufferSize);
Memory::SafeCopy(mBuffer+index+length,mBufferSize-index-length,mBuffer+index,mLength-index+1); //+1 to copy '\0'
Memory::SafeCopy(mBuffer+index,mBufferSize-index,buffer,length);
mLength+=length;
mBuffer[mLength]=0;
return true;
}
bool RemoveAll(T inChar)
{
RETURN_FALSE_IF(IsNull());
T* p=mBuffer;
for (size_t i=0;i<mLength;++i)
{
if (mBuffer[i]!=inChar)
{
*p=mBuffer[i];
++p;
}
}
++p;
*p=0;
mLength=p-mBuffer;
return true;
}
bool RemoveFirst()
{
return RemoveAt(0);
}
bool RemoveFirst(T inChar)
{
RETURN_FALSE_IF(IsNull());
intp index= IndexOf(inChar);
if (index>=0)
{
return RemoveAt(index);
}
return false;
}
bool RemoveLast(T inChar)
{
RETURN_FALSE_IF(IsNull());
intp index= LastIndexOf(inChar);
if (index>=0)
{
return RemoveAt(index);
}
return false;
}
bool RemoveLast()
{
return RemoveAt(mLength-1);
}
bool RemoveAt(size_t index)
{
return RemoveAt(index,1);
}
bool RemoveAt(size_t index,size_t length)
{
RETURN_FALSE_IF(IsNull());
RETURN_FALSE_IF(index+length>mLength);
Memory::SafeCopy(mBuffer+index,mBufferSize-index,mBuffer+index+length,mLength-index-length+1); //+1 to copy '\0'
mLength-=length;
return true;
}
bool RemoveFrom(size_t index)
{
return RemoveAt(index,mLength-index);
}
bool RemoveAll(const TStringRef<T>& inString)
{
RETURN_FALSE_IF(IsNull());
T *w=mBuffer;
T* r=mBuffer;
const T *p=inString.Buffer();
while(*r!=0)
{
if(*p==0)
{
p=inString.Buffer();
}
if (*r!=*p)
{
*w++=*r++;
p=inString.Buffer();
}
else
{
++r;
++p;
}
}
if (*p!=0)
{
r-=p-inString.Buffer();
StdString::CopyString(w,mBufferSize+mBuffer-w,r);
mLength+=p-inString.Buffer();
}
else
{
*w=0;
mLength=w-mBuffer;
}
}
bool RemoveFirst(const TStringRef<T>& inString)
{
RETURN_FALSE_IF(IsNull());
intp index= IndexOf(inString);
if (index>=0)
{
return RemoveAt(index,inString.Length());
}
return false;
}
bool RemoveLast(const TStringRef<T>& inString)
{
RETURN_FALSE_IF(IsNull());
intp index= LastIndexOf(inString);
if (index>=0)
{
return RemoveAt(index,inString.Length());
}
return false;
}
void TrimAll()
{
TrimBegin();
TrimEnd();
}
void TrimBegin()
{
RemoveBeginAny(StdString::ConstValues<T>::TrimChars);
}
void TrimEnd()
{
RemoveEndAny(StdString::ConstValues<T>::TrimChars);
}
bool Format(const T* format,...)
{
RETURN_FALSE_IF_NULL(format);
va_list args;
va_start(args,format);
int length=StdString::GetFormatLength(format,args);
size_t size=length+1; //for 0
RETURN_FALSE_IF(size<=0);
if (size>=mBufferSize)
{
size_t newSize= Math::GetNewSizeSquare(mBufferSize,size);
RETURN_FALSE_IF_FALSE(ResizeHelper(newSize));
}
StdString::VSPrintf(mBuffer,size,format,args);
va_end(args);
mLength=length;
return true;
}
MemoryData<T> ToMemoryData()const{return MemoryData<T>(mBuffer,mLength);}
protected:
virtual bool ResizeHelper(size_t size)=0;
protected:
size_t mLength;
size_t mBufferSize;
T* mBuffer;
};
MEDUSA_END; | true |
46e656cc35db7331a32d5c0516e547f4758bb014 | C++ | 9-5-2-7/learning | /src/27_conpare_list<int>_vector<int>.cpp | UTF-8 | 635 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <list>
#include <vector>
bool compare(const std::list<int> &a, const std::vector<int> &b)
{
if(a.size() != b.size())
{
return false;
}
auto ablist = a.begin();
//auto aelist = a.end();
auto bb = b.begin();
while(ablist != a.end())
{
if(*ablist != *bb)////元素对比,解指针运算符不要忘了
{
return false;
}
++ablist;
++bb;
}
return true;
}
int main()
{
std::list<int> i = {1,6,7};
std::vector<int> j = {1,3,5,6,7};
std::cout << compare(i, j) << std::endl;
return 0;
| true |
5211357378f5976cee7ab103e38cd2bb6c7b4728 | C++ | rinconm/ENGR19C | /examples/CH4-A.CPP | UTF-8 | 1,069 | 3.21875 | 3 | [
"MIT"
] | permissive | /* Eddie Rangel */
/* COMS B35 OOP C++ */
/* CH4-A.CPP */
/* 2-13-03 */
/* Asks user for a double */
/* HEX value in each byte */
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
union uprgrm
{
double number;
unsigned char c[8];
};
main()
{
uprgrm byte;
clrscr();
cout << "Please enter a number: ";
cin >> byte.number;
cout << "This is your first byte: ";
cout << hex << setw(2) <<setfill('0') << (int)(byte.c[0]) << '\n';
cout << "This is your second byte: ";
cout << setw(2) << (int)(byte.c[1]) << '\n';
cout << "This is your third byte: ";
cout << setw(2) << (int)(byte.c[2]) << '\n';
cout << "This is your fourth byte: ";
cout << setw(2) << (int)(byte.c[3]) << '\n';
cout << "This is your fifth byte: ";
cout << setw(2) << (int)(byte.c[4]) << '\n';
cout << "This is your sixth byte: ";
cout << setw(2) << (int)(byte.c[5]) << '\n';
cout << "This is your seventh byte: ";
cout << setw(2) << (int)(byte.c[6]) << '\n';
cout << "This is your eighth byte: ";
cout << setw(2) << (int)(byte.c[7]) << '\n';
return 0;
}
| true |
88d444b021439685757063427ad07e30fdf41073 | C++ | ren-zhe/landlordD | /card.h | GB18030 | 938 | 3.1875 | 3 | [] | no_license | #include"cocos2d.h"
enum pukeType {
Heart,
Spade,
Diamond,
Club,
Joker
};
class Card : public cocos2d::Sprite
{
public :
Card(pukeType type, int num):puketype(type),number(num),select(false),moveState(false){}
virtual bool init(pukeType type, int number);
static Card* create(pukeType type, int number);
static bool cmp(const Card* lhs, const Card *rhs)
{
if (lhs->getNumber() > rhs->getNumber())
return true;
else
return false;
}
int getNumber()const {
return number;
}
pukeType getType()const
{
return puketype;
}
bool isSelect()
{
return select;
}
void setSelect(bool s)
{
select = s;
}
bool getMoveState()
{
return moveState;
}
void setMoveState(bool state)
{
moveState = state;
}
private:
pukeType puketype; //˿˻ɫ
int number;//˿
bool select;//Ƿѡ
bool moveState;//Ƿָѡ״̬
}; | true |
29469a1d0175194a3064d378a2061d443e2b63a6 | C++ | whoozle/toolkit | /src/toolkit/text/Formatters.cpp | UTF-8 | 697 | 2.90625 | 3 | [
"MIT"
] | permissive | #include <toolkit/text/Formatters.h>
namespace TOOLKIT_NS { namespace text
{
void HexDump::ToString(StringOutputStream & ss) const
{
if (!Name.empty())
ss << Name << ": ";
if (Buffer.empty())
{
ss << "[empty]";
return;
}
for(size_t base = 0, size = Buffer.size(); base < size; base += 16)
{
ss << '\n' << Hex(base, 8) << ": ";
size_t i;
size_t lineSize = std::min<size_t>(size - base, 16);
for(i = 0; i < lineSize; ++i)
{
ss << Hex(Buffer[base + i], 2) << ' ';
}
for(; i < 16; ++i)
ss << " ";
ss << "\t";
for(i = 0; i < lineSize; ++i)
{
char ch = Buffer[base + i];
ss << (ch >= 0x20 && ch < 0x7f? ch: '.');
}
}
}
}}
| true |
38c9fe043c8c4a583fbfb5761388f074e371fcd8 | C++ | mcszymist/homework | /HW5/build.cpp | UTF-8 | 2,502 | 3.453125 | 3 | [] | no_license | // build.cpp
// City to City Max Toll
// By Tyler J Roberts
// For CS411 HW5
#include "build.hpp"
#include <vector>
using std::vector;
#include <algorithm>
using std::sort;
//compare to sort bridges with west then sort same west bridges by east
const bool compare(const Bridge &a,const Bridge &b){
if(a[0] == b[0]){
return a[1] < b[1];
}
else {
return a[0] < b[0];
}
}
// remove duplicate bridges and replace with the better value
void removeDups(vector<Bridge> &bridges){
for(auto i = 1; i < bridges.size();i++){
if(bridges[i-1][0] == bridges[i][0] && bridges[i-1][1] == bridges[i][1]){
if(bridges[i-1][2] < bridges[i][2]){
bridges.erase(bridges.begin()+i-1);
}
else{
bridges.erase(bridges.begin()+i);
}
i--;
}
}
}
// pushing the position into the bridges for its location in the data vector
void engageDataLoc(vector<Bridge> &bridges){
for(size_t i = 0; i < bridges.size();i++){
bridges[i].push_back(i);
}
}
// returns the valid bridges for the selected bridge out of the list.
vector<Bridge> validBridges(const Bridge &selected,const vector<Bridge> &bridges){
vector<Bridge> valid{};
for(size_t ii = 0;ii< bridges.size();ii++){
if(!((selected[0] >= bridges[ii][0] && selected[1] <= bridges[ii][1]) || (selected[0] <= bridges[ii][0] && selected[1] >= bridges[ii][1]) || (selected[0] >= bridges[ii][0] && selected[1] >= bridges[ii][1]))){
valid.push_back(bridges[ii]);
}
}
return valid;
}
// recursive function to find the maximum tool
int recurse(const vector<Bridge> &bridges,vector<int> &data){
if(bridges.empty()){
return 0;
} else if(bridges.size()==1){
return bridges[0][2];
}
int max = 0;
int hold = 0;
for(auto &i : bridges){
if(data[i[3]] != -1){
hold = data[i[3]];
} else {
auto temp = validBridges(i, bridges);
hold = recurse(temp,data);
hold += i[2];
data[i[3]] = hold;
}
if(max < hold){
max = hold;
}
}
return max;
}
//setup to recurse
int build(int w, int e, const vector<Bridge> &bridges){
auto allBridges = bridges;
sort(allBridges.begin(),allBridges.end(),compare);
removeDups(allBridges);
engageDataLoc(allBridges);
vector<int> data(allBridges.size(),-1);
return recurse(allBridges,data);
};
| true |
5f0e9743f32f62fe9fb22af005778470ffbaefb3 | C++ | astone30/PopeyeEngine | /Popeye/src/Popeye/Resource/Mesh.cpp | UTF-8 | 1,215 | 2.75 | 3 | [] | no_license | #include "Mesh.h"
namespace Popeye
{
Mesh::Mesh(std::vector<float> _vertices, std::vector<unsigned int> _indices, BoundBox _boundbox)
{
vertices = _vertices;
indices = _indices;
boundbox = _boundbox;
SetMesh();
}
void Mesh::SetMesh()
{
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(float), &vertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (void*)(6 * sizeof(float)));
glBindVertexArray(0);
}
void Mesh::DrawMesh()
{
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, (void*)0);
glBindVertexArray(0);
}
} | true |
859850ad51c20cb6ec77a1647c085989d4573912 | C++ | ajtazer/cpp | /62.cpp | UTF-8 | 628 | 3.09375 | 3 | [] | no_license | #include<iostream>
#include<string.h>
using namespace std;
int main()
{
char string[3][30],ch;
int i,j,k,len;
cout<<"Enter your 3 string : \n";
for(i=0;i<3;i++)
cin.getline(string[i],30);
cout<<"Your entered string : \n";
for(i=0;i<3;i++)
cout<<string[i]<<"\n";
cout<<"Reversed string : \n";
for(i=0;i<3;i++)
{
len = strlen(string[i]);
for(j=0,k=len-1;j<len/2;j++,k--)
{
ch=string[i][j];
string[i][j]=string[i][k];
string[i][k]=ch;
}
}
for(i=0;i<3;i++)
cout<<string[i]<<"\n";
return 0;
}
| true |
04e5c3c3b0faded9c67de67760b4f7c0d7c6b2ea | C++ | alexandraback/datacollection | /solutions_2652486_0/C++/black3r/main.cpp | UTF-8 | 1,557 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
using namespace std;
vector<int> cards;
vector<int> input;
int R, N, M, K;
void gen_cards() {
cards.clear();
for (int i = 0; i < N; i++) {
int t = rand() % (M-2+1);
t += 2;
cards.push_back(t);
}
}
bool valid() {
set<int> products;
int a = cards[0];
int b = cards[1];
int c = cards[2];
products.insert(a);
products.insert(b);
products.insert(a*b);
products.insert(a*c);
products.insert(b*c);
products.insert(a*b*c);
products.insert(c);
products.insert(1);
bool cor = true;
for (int i = 0; i < input.size(); i++) {
if (products.find(input[i]) == products.end()) {
cor = false;
}
}
return cor;
}
int main()
{
cout << "Case #1:" << endl;
int x; cin >> x;
cin >> R >> N >> M >> K;
while (R--) {
input.clear();
for (int i = 0; i < K; i++) {
int t; cin >> t;
input.push_back(t);
}
bool solution = false;
int maxm = 10000;
int j = 0;
while (!solution) {
j++;
if (j > maxm) break;
gen_cards();
solution = valid();
}
for (int j = 0; j < cards.size(); j++) {
cout << cards[j];
}
cout << endl;
}
return 0;
}
| true |
a01a39f42c004e2f431b2f61a4a235e5ec6d55ea | C++ | supercomputra/comp6618036-tnca-week-4 | /Source/User.hpp | UTF-8 | 689 | 2.84375 | 3 | [
"MIT"
] | permissive | #ifndef USER_HPP
#define USER_HPP
#include "Foundation.hpp"
typedef UInt64 UserIdentifier;
struct Profile {
String name;
String address;
Profile() {
name = "";
address = "";
}
};
struct User {
public:
UserIdentifier id;
String email;
Profile profile;
Bool isPasswordMatched(String password) {
UInt64 hashValue = hashed(password);
return hashValue == hashedPassword;
}
User(String email = "", String password = "", UserIdentifier id = timestamp(), Profile profile = Profile()) {
this->id = id;
this->email = email;
this->profile = profile;
this->hashedPassword = hashed(password);
}
private:
Int64 hashedPassword;
};
#endif | true |
6ec22678039fe6c873ca1c9b64276db19edb43b6 | C++ | sam007961/toy-browser | /src/dom.hpp | UTF-8 | 1,796 | 3.046875 | 3 | [] | no_license | #pragma once
#include <memory>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <string>
class DomVisitor;
namespace dom {
struct Node;
typedef std::unique_ptr<Node> NodePtr;
// Node base class
struct Node {
// child nodes
std::vector<NodePtr> children;
Node();
Node(std::vector<NodePtr>&& children);
virtual void accept(DomVisitor& visitor) = 0;
virtual bool isEqual(const Node& other) const = 0;
bool operator==(const Node& other) const;
bool operator!=(const Node& other) const;
};
// Text node
struct TextNode : Node {
std::string text;
TextNode() {}
TextNode(const std::string& text,
std::vector<NodePtr>&& children = {});
virtual void accept(DomVisitor& visitor);
virtual bool isEqual(const Node& other) const;
};
// Attribute map
typedef std::unordered_map<std::string, std::string> AttrMap;
// Element data
struct ElementData {
std::string tag_name;
AttrMap attributes;
ElementData() {}
ElementData(const std::string& tag_name, const AttrMap& attributes);
bool operator==(const ElementData& other) const;
std::optional<std::string> id() const;
std::unordered_set<std::string> classes() const;
};
// Element node
struct ElementNode : Node {
ElementData data;
ElementNode() {}
ElementNode(const std::string& name, const AttrMap& attrs = {},
std::vector<NodePtr>&& children = {});
virtual void accept(DomVisitor& visitor);
virtual bool isEqual(const Node& other) const;
};
// compare two trees or sub-trees
bool compare(const Node& a, const Node& b);
} | true |
af5e90a85c4bc7799160cceb21f45b6a3d74b9de | C++ | ZMLight/DataStructureHomework | /dataStructureHomework/1316/1316.cpp | UTF-8 | 1,881 | 3.34375 | 3 | [] | no_license | #include <iostream>
using namespace std;
struct MilkProcessTime
{
int start, end;
MilkProcessTime *next;
MilkProcessTime(int s = 0, int e = 0, MilkProcessTime *t = NULL):start(s), end(e), next(t){}
};
int main()
{
int N, startT, endT, oneInterval, noInterval;
bool flag = false;
MilkProcessTime *head, *pres, *temp;
cin >> N;
head = new MilkProcessTime(0,0,NULL);
for(int i = 0; i < N; ++i)
{
cin >> startT >> endT;
pres = head;
while(pres->next != NULL && startT > pres->next->start)
pres = pres->next;
temp = new MilkProcessTime(startT,endT,pres->next);
pres->next = temp;
}
while(!flag)
{
flag = true;
pres = head->next;
while(pres->next != NULL)
{
if(pres->end >= pres->next->start)
{
if(pres->end < pres->next->end)
pres->end = pres->next->end;
flag = false;
temp = pres->next;
pres->next = temp->next;
delete temp;
}
else
pres = pres->next;
}
}
oneInterval = 0;
noInterval = 0;
pres = head->next;
while(pres->next != NULL)
{
if((pres->end - pres->start) > oneInterval)
oneInterval = pres->end - pres->start;
if((pres->next->start - pres->end) > noInterval)
noInterval = pres->next->start - pres->end;
pres = pres->next;
}
if((pres->end - pres->start) > oneInterval)
oneInterval = pres->end - pres->start;
cout << oneInterval << ' ' << noInterval;
pres = head;
while(pres != NULL)
{
temp = pres->next;
delete pres;
pres = temp;
}
return 0;
}
| true |
3072582177e918f40fe020b2508fd21d7269ec77 | C++ | alexxyjiang/photo-sign-freeimage | /src/hsvcolor.cpp | UTF-8 | 2,956 | 2.859375 | 3 | [
"MIT"
] | permissive | /** hsvcolor.cpp - Support RGB & HSV color convert
* @author: Alex.J. (alexxyjiang@gmail.com)
* @date: 2017-09-19
*/
#include "hsvcolor.h"
namespace PhotoMgr {
HSVACOLOR convert_rgba2hsva(const RGBQUAD rgba_color) {
double r = double(rgba_color.rgbRed / 255.0);
double g = double(rgba_color.rgbGreen / 255.0);
double b = double(rgba_color.rgbBlue / 255.0);
uint8_t a = uint8_t(rgba_color.rgbReserved);
double c_max = r>g ? r : g;
c_max = c_max>b ? c_max : b;
double c_min = r<g ? r : g;
c_min = c_min<b ? c_min : b;
double h;
if (c_max - c_min < 1e-6) {
h = 0;
} else if (c_max == r) {
if (g >= b) {
h = 60.0 * double(g - b) / double(c_max - c_min);
} else {
h = 60.0 * double(g - b) / double(c_max - c_min) + 360.0;
}
} else if (c_max == g) {
h = 60.0 * double(b - r) / double(c_max - c_min) + 120.0;
} else {
h = 60.0 * double(r - g) / double(c_max - c_min) + 240.0;
}
double s;
if (c_max < 1e-6) {
s = 0.0;
} else {
s = 1.0 - double(c_min) / double(c_max);
}
double v = c_max;
HSVACOLOR res;
res.h = h;
res.s = s;
res.v = v;
res.a = a;
return res;
}
RGBQUAD convert_hsva2rgba(const HSVACOLOR hsva_color) {
double h = hsva_color.h;
double s = hsva_color.s;
double v = hsva_color.v;
uint8_t a = hsva_color.a;
uint8_t group = uint8_t(h / 60.0) % 6;
double f = h / 60.0 - group;
double p = v * (1.0 - s);
double q = v * (1.0 - f * s);
double t = v * (1.0 - (1.0 - f) * s);
RGBQUAD res;
if (group == 0) {
res.rgbRed = BYTE(v * 255.0);
res.rgbGreen = BYTE(t * 255.0);
res.rgbBlue = BYTE(p * 255.0);
res.rgbReserved = BYTE(a);
} else if (group == 1) {
res.rgbRed = BYTE(q * 255.0);
res.rgbGreen = BYTE(v * 255.0);
res.rgbBlue = BYTE(p * 255.0);
res.rgbReserved = BYTE(a);
} else if (group == 2) {
res.rgbRed = BYTE(p * 255.0);
res.rgbGreen = BYTE(v * 255.0);
res.rgbBlue = BYTE(t * 255.0);
res.rgbReserved = BYTE(a);
} else if (group == 3) {
res.rgbRed = BYTE(p * 255.0);
res.rgbGreen = BYTE(q * 255.0);
res.rgbBlue = BYTE(v * 255.0);
res.rgbReserved = BYTE(a);
} else if (group == 4) {
res.rgbRed = BYTE(t * 255.0);
res.rgbGreen = BYTE(p * 255.0);
res.rgbBlue = BYTE(v * 255.0);
res.rgbReserved = BYTE(a);
} else {
res.rgbRed = BYTE(v * 255.0);
res.rgbGreen = BYTE(p * 255.0);
res.rgbBlue = BYTE(q * 255.0);
res.rgbReserved = BYTE(a);
}
return res;
}
HSVACOLOR reversed_hsva_color(const HSVACOLOR hsva_color) {
HSVACOLOR res = hsva_color;
res.h += 180.0;
if (res.h > 360.0) {
res.h -= 360.0;
}
res.v = 1.0 - res.v;
return res;
}
} // namespace PhotoMgr
| true |
8b6faba8dd0f8df87c522e869b8e5216e744f157 | C++ | dtraczewski/zpk2014 | /home/kgawron/projekt_zaliczeniowy_poprawiony/main.cpp | UTF-8 | 19,640 | 2.578125 | 3 | [] | no_license | /*
******************************
** 2048 game **
******************************
*/
#include <allegro5/allegro.h>
#include <allegro5/allegro_primitives.h>
#include "allegro5/allegro_image.h"
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
#include <iostream>
#include <sstream>
#include <string>
#include <cmath>
#include <cstdio>
using namespace std;
/*
**
** Game's configuration
**
*/
// Game's settings
int max_value = 11; // basically it's highest power of 2 = highest result
// Dimensions
int block_height = 106;
int block_width = 106;
int button_x = 361;
int button_y = 100;
int button_w = 129;
int button_h = 42;
int vertical_blocks = 4;
int horizontal_blocks = 4;
int gap_size = 15;
int top_offset = 186;
int display_width = block_width * horizontal_blocks + gap_size * ( horizontal_blocks + 1 );
int display_height = block_height * vertical_blocks + gap_size * ( vertical_blocks + 1 ) + top_offset;
// Blocks values
int values_number = vertical_blocks * horizontal_blocks;
int values[ 16 ];
// Allegro variables
ALLEGRO_DISPLAY *display = NULL;
ALLEGRO_EVENT_QUEUE *event_queue = NULL;
ALLEGRO_BITMAP* bitmap[ 12 ];
ALLEGRO_BITMAP* buttons[ 1 ];
ALLEGRO_BITMAP* items[ 3 ];
ALLEGRO_FONT * font20 = NULL;
ALLEGRO_MOUSE_STATE mice;
// Mechanics utils
int last_round[ 16 ];
int indexes[ 4 ][ 4 ];
int score;
int summed_blocks[ 3 ];
bool game_end;
const string button_files[ 1 ] =
{
"blocks/new.png"
};
const string items_files[ 3 ] =
{
"blocks/board.png",
"blocks/lost.png",
"blocks/won.png"
};
/*
**
** Initialization functions
**
*/
// load all graphics
bool prepare_bitmaps()
{
stringstream ss;
for( int i = 0; i <= max_value; ++i )
{
ss << "blocks/" << i << ".png";
bitmap[ i ] = al_load_bitmap( ss.str().c_str() );
if( !bitmap[ i ] )
{
cerr << "Prepare Bitmaps error." << endl;
cerr << "Could not load: " << ss.str() << endl;
return false;
}
ss.str( "" );
}
for( int i = 0; i < 1; ++i )
{
buttons[ i ] = al_load_bitmap( button_files[ i ].c_str() );
if( !buttons[ i ] )
{
cerr << "Prepare Bitmaps error." << endl;
cerr << "Could not load: " << button_files[ i ] << endl;
return false;
}
}
for( int i = 0; i < 3; ++i )
{
items[ i ] = al_load_bitmap( items_files[ i ].c_str() );
if( !items[ i ] )
{
cerr << "Prepare Bitmaps error." << endl;
cerr << "Could not load: " << items_files[ i ] << endl;
return false;
}
}
return true;
}
// clear game_board, empty all blocks
void prepare_values()
{
for( int i = 0; i < values_number; ++i )
{
values[ i ] = 0;
}
}
// initialize allegro
int init()
{
if( !al_init() )
{
cerr << "Al Init error." << endl;
return -1;
}
if( !al_init_primitives_addon() )
{
cerr << "Al Init Primitives Addon error." << endl;
return -1;
}
if( !al_init_image_addon() )
{
cerr << "Al Init Image Addon error." << endl;
return -1;
}
al_init_font_addon();
if( !al_init_ttf_addon() )
{
cerr << "Al Init TTF Addon error." << endl;
return -1;
}
font20 = al_load_ttf_font("blocks/courbd.ttf",20, 0);
if( !font20 )
{
cerr << "Al Create Font error." << endl;
return -1;
}
if( !al_install_keyboard() )
{
cerr << "Al Install Keyboard error." << endl;
return -1;
}
if( !al_install_mouse() )
{
cerr << "Al Install Mouse error." << endl;
return -1;
}
display = al_create_display( display_width, display_height );
if( !display )
{
cerr << "Al Create Display error." << endl;
return -1;
}
event_queue = al_create_event_queue();
if( !event_queue )
{
cerr << "Al Create Event Queue error." << endl;
al_destroy_display( display );
return -1;
}
al_register_event_source( event_queue, al_get_display_event_source( display ) );
al_register_event_source( event_queue, al_get_keyboard_event_source() );
al_register_event_source( event_queue, al_get_mouse_event_source());
al_clear_to_color( al_map_rgb( 0, 0, 0 ) );
al_flip_display();
return 0;
}
/*
**
** Game mechanics
**
*/
// moving directions
enum directions { dir_up = 1001, dir_down = 1002, dir_left = 1003, dir_right = 1004 };
// verbose boolean enum
enum tests { test = true, not_a_test = false };
// get horizontal distance for given column
int get_block_x( int column )
{
return block_width * column + gap_size * (column + 1);
}
// get vertical distance for given row
int get_block_y( int row )
{
return block_height * row + gap_size * (row + 1) + top_offset;
}
// draw current state of game board
void draw_game_board()
{
al_clear_to_color( al_map_rgb( 0, 0, 0 ) );
al_draw_bitmap( items[ 0 ], 0, 0, 0 );
al_draw_textf (font20,al_map_rgb(100,100,100),375,22,0, "%i" ,score );
al_draw_bitmap( buttons[ 0 ], 361, 100, 0 );
int value_index;
for( int i = 0; i < horizontal_blocks; ++i )
{
for( int j = 0; j < vertical_blocks ; ++j )
{
value_index = i * horizontal_blocks + j; //basically increase from 0 to 15
//{0, 1, 2, 3 }
//{4, 5, 6, 7 }
//{8, 9, 10, 11}
//{12, 13, 14, 15}
al_draw_bitmap( bitmap[ values[ value_index ] ],
get_block_x( j ),
get_block_y( i ),
0 );
// bitmap[0] - keeps empty image
// bitmap[1] - keeps image with number 2
// bitmap[2] - keeps image with number 4 and so on
// bitmap[ values[ value_index ] ] - keeps image with number for value_index block
}
}
}
// updates two dimensional array needed for moving
// every row keeps sorted blocks indexes
// in row: indexes from last to first - it is how blocks will be moved
void updateIndexes( directions direction )
{
//game board
//{0, 1, 2, 3 }
//{4, 5, 6, 7 }
//{8, 9, 10, 11}
//{12, 13, 14, 15}
switch( direction )
{
case dir_up:
//moving blocks up
indexes[0][0] = 0;indexes[0][1] = 4;indexes[0][2] = 8;indexes[0][3] = 12;// {0, 4, 8, 12}
//first we move block on index 4 -> 0, then 8 -> 4 -> 0, then 12 -> 8 -> 4 -> 0
indexes[1][0] = 1;indexes[1][1] = 5;indexes[1][2] = 9;indexes[1][3] = 13; // {1, 5, 9, 13}
//second we move 5 -> 1, then 9 -> 5 -> 1, then 13 -> 9 -> 5 -> 1, and so on
indexes[2][0] = 2;indexes[2][1] = 6;indexes[2][2] = 10;indexes[2][3] = 14;// {2, 6, 10, 14}
indexes[3][0] = 3;indexes[3][1] = 7;indexes[3][2] = 11;indexes[3][3] = 15;// {3, 7, 11, 15}
break;
case dir_down:
indexes[0][0] = 12;indexes[0][1] = 8;indexes[0][2] = 4;indexes[0][3] = 0;// {12, 8, 4, 0}
indexes[1][0] = 13;indexes[1][1] = 9;indexes[1][2] = 5;indexes[1][3] = 1; // {13, 9, 5, 1}
indexes[2][0] = 14;indexes[2][1] = 10;indexes[2][2] = 6;indexes[2][3] = 2;// {14, 10, 6, 2}
indexes[3][0] = 15;indexes[3][1] = 11;indexes[3][2] = 7;indexes[3][3] = 3;// {15, 11, 7, 3}
break;
case dir_left:
indexes[0][0] = 0;indexes[0][1] = 1;indexes[0][2] = 2;indexes[0][3] = 3;// {0, 1, 2, 3}
indexes[1][0] = 4;indexes[1][1] = 5;indexes[1][2] = 6;indexes[1][3] = 7; // {4, 5, 6, 7}
indexes[2][0] = 8;indexes[2][1] = 9;indexes[2][2] = 10;indexes[2][3] = 11;// {8, 9, 10, 11}
indexes[3][0] = 12;indexes[3][1] = 13;indexes[3][2] = 14;indexes[3][3] = 15;// {12, 13, 14, 15}
break;
case dir_right:
indexes[0][0] = 3;indexes[0][1] = 2;indexes[0][2] = 1;indexes[0][3] = 0;// {3, 2, 1, 0}
indexes[1][0] = 7;indexes[1][1] = 6;indexes[1][2] = 5;indexes[1][3] = 4; // {7, 6, 5, 4}
indexes[2][0] = 11;indexes[2][1] = 10;indexes[2][2] = 9;indexes[2][3] = 8;// {11, 10, 9, 8}
indexes[3][0] = 15;indexes[3][1] = 14;indexes[3][2] = 13;indexes[3][3] = 12;// {15, 14, 13, 12}
break;
}
}
void print_score()
{
cout << "Your score: " << score << endl;
}
void clear_summed_blocks()
{
summed_blocks[0] = -1;
summed_blocks[1] = -1;
summed_blocks[2] = -1;
}
void set_block_as_summed( int block_index )
{
for( int i = 0; i < 3; ++i )
{
if( -1 == summed_blocks[ i ] )
{
summed_blocks[ i ] = block_index;
break;
}
}
}
bool was_summed( int block_index )
{
for( int i = 0; i < 3; ++i )
{
if( block_index == summed_blocks[ i ] )
{
return true;
}
}
return false;
}
// moving blocks, or just testing if move possible
bool move_values( int current, int target, bool test )
{
if( values[ target ] == 0 )
{
//move possible
if( test )
{
return true;
}
//move to empty block
//move value and leave empty block behind
values[ target ] = values[ current ];
values[ current ] = 0;
}
else if( values[ target ] == values[ current ] && !was_summed(target) && !was_summed(current))
{
//move possible
if( test )
{
return true;
}
//move to block with same value if target block has not been summed yet
//change value on next block (increase power of 2)
//and leave empty block behind
values[ target ] = values[ target ] + 1;
score += pow(2, values[ target ]);
print_score();
values[ current ] = 0;
set_block_as_summed( target );
set_block_as_summed( current );
}
//if move to block with different value, do not do anything
return false;
}
// moving whole line (or just test if possible)
// if moving up/down it is column
// if moving right/left it is row
// function is using two dimensional array indexes to distinct between column/row
bool move_line( int i, bool test )
{
clear_summed_blocks();
//we are moving blocks 1 tile at a time
//starting at 2nd block closes to direction we moving (if moving up, we start moving with 2nd block from top)
//1st block obviously stays in place, but still can change value (if moving up, the top block does not move)
for( int start_at = 1; start_at < 4; ++start_at )
{
for( int current_block = start_at; current_block > 0; --current_block )
{
int target_block = current_block - 1;
// current block and target blocks will get following values:
// current -> target
// 1 -> 0
// 2 -> 1
// 1 -> 0
// 3 -> 2
// 2 -> 1
// 1 -> 0
// if we moving up - second (1) goes to the top block (0),
// then third (2) goes to second(1) and again to the top (0),
// then fourth (3, the one at the bottom) goes to third block (2) then to second (1) and then to the top one (0).
bool test_result = move_values(indexes[i][current_block], indexes[i][target_block], test);
// if just testing if move possible and test_result is true, return true = moving this line is possible
if(test && test_result)
{
return true;
}
}
}
return false;
}
// moving all line
// prepares two dimensional array indexes
// and invoke move_line for all (columns - up/down or rows - right/left).
void move_it( directions direction )
{
updateIndexes(direction);
for( int i = 0; i < 4; ++i )
{
move_line(i, not_a_test);
}
}
// testing moving all lines
// does same thing as move_it
// but does NOT change any value on game board
bool test_it( directions direction )
{
updateIndexes(direction);
for( int i = 0; i < 4; ++i )
{
bool test_result = move_line(i, test);
if( test_result )
{
return true;
}
}
return false;
}
// nice name for testing if moving up is possible
bool can_move_up()
{
return test_it(dir_up);
}
// nice name for moving up
void move_up()
{
move_it(dir_up);
}
// so forth
bool can_move_down()
{
return test_it(dir_down);
}
// and so on
void move_down()
{
move_it(dir_down);
}
bool can_move_left()
{
return test_it(dir_left);
}
void move_left()
{
move_it(dir_left);
}
bool can_move_right()
{
return test_it(dir_right);
}
void move_right()
{
move_it(dir_right);
}
// nice name for checking if move in any direction is possible
bool check_move_available()
{
return can_move_up() || can_move_down() || can_move_left() || can_move_right();
}
// checking if there is empty block on game board
// needed to place random number 2 at the begging of turn
bool can_add_one()
{
for( int i = 0; i < values_number; ++i )
{
if( values[ i ] == 0 )
{
return true;
}
}
return false;
}
// returns [from, to] - including both from and to
// not [from, to) as in basic rand
int getRandom( int from, int to )
{
int range = to - from + 1;
int randomed = rand() % range;
return from + randomed;
}
// adding number 2 or 4 on random empty block
void add_one_at_random()
{
int randomNumber;
do
{
randomNumber = rand() % values_number;
}
while( values[ randomNumber ] != 0 );
values[ randomNumber ] = getRandom(1, 2);
}
// starting game
void start_game()
{
cout << "New game. Good Luck!" << endl;
game_end = false;
// clear game board
prepare_values();
for( int i = 0; i < 16; ++i )
{
last_round[ i ] = 0;
}
// set players score to 0
score = 0;
// add random 2
add_one_at_random();
// add random 2
add_one_at_random();
// dram game board
draw_game_board();
// show newly drawn board
al_flip_display();
}
// checking if any block has maximum value (11 -> pow(2,11) = 2048)
bool check_if_won()
{
for( int i = 0; i < values_number; ++i )
{
if( values[ i ] == max_value )
{
return true;
}
}
return false;
}
bool check_if_button_hit(float x, float y)
{
if( (x > button_x) & (x<button_x + button_w))
{
if( (y > button_y) & (y<button_y + button_h))
{
return true;
}
}
return false;
}
// draws result on game board
void draw_result( string result )
{
if( result == "lost")
{
al_draw_bitmap(items[ 1 ], 0, 0, 0);
}
else
{
al_draw_bitmap(items[ 2 ], 0, 0, 0);
}
al_flip_display();
}
void win()
{
game_end = true;
draw_result( "won" );
cout << "You won" << endl;
cout << "If you want to play again click S" << endl;
cout << "To exit click ESC" << endl;
}
void lose()
{
game_end = true;
draw_result( "lost" );
cout << "You lost" << endl;
cout << "If you want to try again click S" << endl;
cout << "To exit click ESC" << endl;
}
bool moved_since_last_round()
{
for( int i = 0; i < 16; ++i )
{
/*cout << values[ i ] << " " << last_round[ i ];
if( (i + 1) % 4 == 0 )
{
cout << endl;
}*/
if(values[ i ] != last_round[ i ] )
{
return true;
}
}
return false;
}
void update_last_round()
{
for( int i = 0; i < 16; ++i )
{
last_round[ i ] = values[ i ];
}
}
/*
**
** Game itself
**
*/
int main( int argc, char ** argv )
{
// initialize random salt for whole game
srand( time( NULL ) );
// initialize allegro
if( init() != 0 )
{
cerr << "Init error." << endl;
return -1;
}
// load images
if( !prepare_bitmaps() )
{
return -1;
}
bool redraw = false;
bool exit = false;
bool print_menu = true;
// main loop
do
{
if( print_menu )
{
cout << "Welcome to 2048 game clone." << endl;
cout << "To start click S" << endl;
cout << "To leave (now or ever) press ESC" << endl;
cout << endl << "You can use arrows to navigate, everything else is straight forward." << endl;
cout << "Good luck at getting 2048!";
if( max_value != 11 )
{
cout << " Or " << pow( 2, max_value ) << " this time.";
}
cout << endl;
print_menu = false;
start_game();
}
ALLEGRO_EVENT ev;
al_get_mouse_state(&mice);
al_wait_for_event( event_queue, &ev );
// Player control - get clicked key
if( ev.type == ALLEGRO_EVENT_KEY_UP )
{
// ESC
if( ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE || ev.keyboard.keycode == ALLEGRO_KEY_Q )
{
//signal end of game
exit = true;
}
// S
if( ev.keyboard.keycode == ALLEGRO_KEY_S )
{
start_game();
}
// UP
if( ev.keyboard.keycode == ALLEGRO_KEY_UP )
{
// check if it is possible to move up
if( can_move_up() )
{
// move up - update values on game board (player can not see it yet - game board is not redrawn)
move_up();
// signal need for redrawing game board
redraw = true;
}
}
// DOWN
if( ev.keyboard.keycode == ALLEGRO_KEY_DOWN )
{
if( can_move_down() )
{
move_down();
redraw = true;
}
}
// LEFT
if( ev.keyboard.keycode == ALLEGRO_KEY_LEFT )
{
if( can_move_left() )
{
move_left();
redraw = true;
}
}
// RIGHT
if( ev.keyboard.keycode == ALLEGRO_KEY_RIGHT )
{
if( can_move_right() )
{
move_right();
redraw = true;
}
}
}
if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN)
{
if (check_if_button_hit(mice.x,mice.y))
{
start_game();
}
}
// Game board control
// player clicked up, down, left or right
if( redraw && al_is_event_queue_empty( event_queue ) )
{
// game board will be redrawn, wait for another signal
redraw = false;
if( check_if_won() )
{
win();
}
else if( !can_add_one() )
{
lose();
}
if( !game_end )
{
if( moved_since_last_round() )
{
// add number 2 or 4 at random empty block
add_one_at_random();
update_last_round();
}
draw_game_board();
al_flip_display();
if( !check_move_available() )
{
lose();
}
}
}
}
while( !exit );
return 0;
}
| true |
011a545499299853e99ee19d063782adc8058ba7 | C++ | jaye1944/lcpp | /cpp11/template.cpp | UTF-8 | 255 | 2.75 | 3 | [] | no_license | #include <iostream>
//g++ -std=c++11 <file.cpp>
int rValue(int k)
{
int kk = k*k;
return kk;
}
int main (int argc, char *argv[])
{
std::cout << "Hello World" << std::endl;
auto answ = rValue(3);
std::cout << answ << std::endl;
return 0;
}
| true |
64808e114a457eb5baf8610a0bc94ec8cc87d52e | C++ | klowell/COMP-2010-Summer-2018-Lab8 | /Lab8.cpp | UTF-8 | 1,319 | 3.921875 | 4 | [] | no_license | /*****************************************************************************************
Project Name: Lab 8
Name: Kristopher Lowell
Date Completed: 8/8/2018
Purpose: Using a class with overloaded operators, add, subtract, multiply, and divide
two rational numbers represented by two integers each.
*****************************************************************************************/
#include "Rational.h"
using namespace std;
int main(int argc, char *argv[])
{
Rational X, Y, Z;
int entry;
cout << "Enter the numerator and denominator of the first rational number (X): ";
cin >> X;
cout << "Enter the numerator and denominator of the second rational number (Y): ";
cin >> Y;
cout << "-X = " << X << endl;
cout << "-Y = " << Y << endl;
Z = X + Y;
cout << "X + Y = " << X << " + " << Y << " = " << Z << endl;
Z = X - Y;
cout << "X - Y = " << X << " - " << Y << " = " << Z << endl;
Z = X * Y;
cout << "X * Y = " << X << " * " << Y << " = " << Z << endl;
Z = X / Y;
cout << "X / Y = " << X << " / " << Y << " = " << Z << endl;
cout << "Is X < Y or Y < X? ";
if (X < Y)
cout << X << " < " << Y << endl;
else
cout << Y << " < " << X << endl;
cout << "Is Y > X or X > Y? ";
if (Y > X)
cout << Y << " > " << X << endl;
else
cout << X << " > " << Y << endl;
cin >> entry;
return 0;
} | true |
1adbd3648406ae49b885eca517b8e6991527a0b7 | C++ | maryllb/all_studey | /c++/day5/company/include/Employee.h | UTF-8 | 476 | 2.8125 | 3 | [] | no_license | #pragma once
#include<iostream>
#include<string>
using namespace std;
/*---抽象类----*/
class Employee
{
public:
Employee();
virtual ~Employee();
//人员初始化
virtual void init(string name) = 0;
//升级
virtual void uplevel(int level) = 0;
//获取薪资
virtual double getsalary() = 0;
//显示员工信息
void display();
protected:
string name;
int level;
double salary;
int id;
static int startNum;
};
| true |
e8cba4dde2ddf8364334e9b76a98b16bb2f17d3b | C++ | canon4444/AtCoder | /etc./colopl2018-final-open/A.cpp | UTF-8 | 1,372 | 2.90625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
long long int N;
string S;
cin >> N >> S;
int len = (int)S.length();
long long int ans = 0, k = 0;
if( S[0] == 'A' && S[len-1] == 'A' ){
long long int s = -1, e = -1;
for( int i = 0; i < len; ++i )
if( s == -1 && S[i] == 'B' ) s = i;
for( int i = len-1; -1 < i; --i )
if( e == -1 && S[i] == 'B' ) e = len - i - 1;
if( s == -1 && e == -1 ){
ans = (len*N*(1+len*N))/2;
cout << ans << endl;
return 0;
}
for( int i = s; i < len-e; ++i ){
if( S[i] == 'A' ){
++k;
ans += k;
} else if( S[i] == 'B' ){
k = 0;
}
}
ans *= N;
//cout << ans << " *" << endl;
ans += (s*(1+s))/2; // 1回目の最初
//cout << ans << " s" << endl;
ans += (N-1) * ((e+s)*(1+e+s))/2; // 2〜N-1回目の間
//cout << ans << " rep" << endl;
ans += (e*(1+e))/2; // N回目の最後
} else {
for( int i = 0; i < len; ++i ){
if( S[i] == 'A' ){
++k;
ans += k;
} else if( S[i] == 'B' ){
k = 0;
}
}
ans *= N;
}
cout << ans << endl;
return 0;
}
| true |
a955e63a83309e68f6ca8769e97b01fbbfd375e2 | C++ | syrota-roman/LeetCode | /findTheDifference.cpp | UTF-8 | 926 | 3.984375 | 4 | [] | no_license | /*
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
*/
#include <iostream>
#include <algorithm>
using namespace std;
class Solution {
public:
char findTheDifference(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
char res;
for ( int i = 0; i < t.length(); i++ ) {
if ( i == s.length() ) {
res = t[i];
break;
} else if ( s[i] != t[i] ) {
res = t[i];
break;
}
}
return res;
}
};
int main(int argc, char *argv[]) {
Solution sol;
string str = "a b c";
string str1 = "a b zc";
char x = sol.findTheDifference(str, str1);
cout << x << endl;
return 0;
}
| true |
e79ebaca70787b03167dc73cc4db2cfefc4c2cb5 | C++ | dhruvpatel348/C-Programming | /L-8.cpp | UTF-8 | 225 | 2.953125 | 3 | [] | no_license | #include<stdio.h>
int main()
{
int i,n,s=1;
printf("\nEnter n=>");
scanf("%d",&n);
for(i=n; i>=1; i--)
{
printf(" %d * ",i);
s=s*i;
}
printf("\n factorial is %d",s);
}
| true |
03c308519d612a7b441723375b1cd3eeeb978d5b | C++ | rohitbakoliya/algorithms | /Data Structures/Linked list/Singly_link_list.cpp | UTF-8 | 3,753 | 3.796875 | 4 | [] | no_license | #include<stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node* next;
};
void Finsert(struct node** pointerToHead , int x)
{
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));
temp->data= x;
//temp->next = NULL;
// if(head!=NULL)
temp->next = *pointerToHead;
*pointerToHead = temp;
}
void Rinsert(struct node** head , int x)
{
struct node* temp ;
temp = ( struct node* ) malloc ( sizeof ( struct node ) );
temp->data = x;
temp->next = NULL;
struct node* itr = *head;
if(*head==NULL)
{
*head=temp;
return;
}
while(itr->next!=NULL)
{
itr=itr->next;
}
itr->next=temp;
}
void Minsert(struct node** head , int x , int pos)
{
struct node* itr =*head;
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));
temp->next=NULL;
temp->data=x;
if(pos==1)
{
temp->next=*head;
*head=temp;
return;
}
for(int i=1 ; i<= (pos-2) ; i++)
{
itr=itr->next;
}
temp->next= itr->next;
itr->next=temp;
}
void Fdelete(struct node** head)
{
struct node* temp;
temp=*head;
*head=temp->next;
}
void Mdelete(struct node** head, int pos)
{
struct node* temp;
temp=*head;
if(pos==1)
{
*head=temp->next;
return;
}
for(int i=1 ;i <= pos-2;i++)
{
temp=temp->next;
}
temp->next=temp->next->next;
}
void Rdelete(struct node** head)
{
struct node* temp;
temp=*head;
if(temp->next==NULL)
{
*head=NULL;
return;
}
while(temp->next->next!=NULL)
{
temp=temp->next;
}
temp->next=NULL;
}
void Display(struct node** head)
{
struct node* temp = *head;
printf("List is : ");
while(temp!=NULL)
{
printf(" %d" , temp->data);
temp= temp->next;
}
printf("\n");
}
int main()
{
int n,i,x, choice , pos, del;
struct node* head=NULL; // list is empty
printf("How many number you want to insert? \n");
scanf("%d" , &n);
for (int i = 0; i <n ; ++i) {
choices:
printf("1. Front Insert 2. Middle Insert 3. Rear Insert\n4. Front Delete 5. Middle Delete 6. Rear Delete\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
{
printf("Enter number : \n");
scanf("%d", &x);
Finsert(&head,x);
Display(&head);
break;
}
case 2:
{
printf("Enter number : \n");
scanf("%d", &x);
printf("Enter position where you wanna insert : \n");
scanf("%d", &pos);
Minsert(&head , x, pos);
Display(&head);
break;
}
case 3:
{
printf("Enter number : \n");
scanf("%d", &x);
Rinsert(&head , x);
Display(&head);
break;
}
case 4:
{
Fdelete(&head);
Display(&head);
break;
}
case 5:
{
printf("Which position of element you want to delete\n");
scanf("%d",&del);
Mdelete(&head,del);
Display(&head);
break;
}
case 6:
{
Rdelete(&head);
Display(&head);
break;
}
default: printf("***Choose correct option***\n");
goto choices;
}
}
}
| true |
a8dfacf8510ee2340164edd0e4456b4bf6d086a3 | C++ | FcoCarlosMM/C2-5 | /src/move_turtlesim/src/test1.cpp | UTF-8 | 6,082 | 3.265625 | 3 | [] | no_license | // Code: Test1.
// Objective: Simulate the movement of a Turtlebot usin Turtlesim as basis for a further code using Turttlebot hardware.
// Mini project.
// Author: Team C2-05, Robot Programming, Robotics, AAU.
// December 2018.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Summary: The code shows two options to work. The first one generates random movements for the turtle and tracks the coordinates at every movement.
// An area is delimited and if the movement commanded to the turtle makes it go further than the dimensions established, the turtle will avoid the instruction and take the next one.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include<stdlib.h> //used to generate random numbers
#include<time.h> //used to generate random numbers
#include<math.h> //used to get sin and cos functions
using namespace std;
///////////////////////////////////////////////////////////////////////////////////////////////////////////
int randvel(){ // This function type integer is used to generate a random value for the linear displacement of the turtle between 5 and 1.
int vel=0;
vel=1+rand()%(6-1);
return vel;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
int randrot(){ // This function type integer is used to generate a random value for the angular displacement of the turtle between 3 and -3 radians.
int rot=0;
rot=1+rand()%(7)-3;//
return rot;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
void movefunc(){ // This function moves the turtlebot through random directions and tracks its position.
double angle=0; // This variable will be actualized for every movement.
double realangle=0; // This variable will keep track of the turtle's angle seen from the very initial position
double posx=0; // This variable will keep track of the displacement in X-axis at every movement.
double posy=0; // This variable will keep track of the displacement in Y-axis at every movement.
double ahead=0; // This variable will dictate the distance of each linear movement.
double realposx=0; // This variable will keep track of the displacement in X-axis seen from the origin.
double realposy=0; // This variable will keep track of the displacement in Y-axis seen from the origin.
int rep=0;
cout << "How many repetitions do you want?"<<endl; //The user is asked how many repetitions are required, 1 repetition include 1 rotation and one displacement.
cin>>rep;
ros::NodeHandle nh;
ros::Publisher cmd_vel_pub = nh.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel", 10); //It is advertisedd that the publisher will publish in the cmd_vel topic (the turtle simulator is subscribed to this topic)
for (int i=0;i<rep;i++){
ros::Duration(1.0).sleep();
geometry_msgs::Twist msg;
msg.linear.x = 0.0;
angle=randrot(); // The variable angle gets a value from the function randrot()
realangle=realangle+angle;// // The value of the angle seen from the origin is updated each cycle.
msg.angular.z = angle; // First a rotation is performed.
cmd_vel_pub.publish(msg); // The message is published to the topic.
ros::Duration(1.0).sleep();
ahead = randvel(); // Now the variable ahead gets a value from the fucntion randvel() to indicate a linear displacement.
posx=ahead*cos(realangle); // The X and Y components of every linear movement are calculated.
posy=ahead*sin(realangle);
if (realposx+posx<5&&realposx+posx>(-5)) { //This two conditions check if the next movement will keep the turtle inside the area indicated.
if (realposy+posy<5&&realposy+posy>(-5)) { // If the longitude of the next movement is enough to get the turtle out of the area, the instruction is avoided.
realposx=realposx+posx; // The components in X and Y axis are added every cycle.
realposy=realposy+posy;
msg.linear.x = ahead;
msg.angular.z = 0.0;
cout<<"position en X: "<<realposx<<endl;
cout<<"position en Y: "<<realposy<<endl;
cmd_vel_pub.publish(msg);
}
else {
cout<<"The position in Y would be: "<<realposy+posy<<", limit is -+5"<<endl;
}
}
else {
cout<<"The position in X would be: "<<realposx+posx<<", limit is -+5"<< endl;
}
}
}
///////////////////////////////////////////////////////////////////////
void rotatefunc(){ //This function is written in order to test only the rotatory movement of the simulation. No return value is required.
double value = 0.0;
cout<<"How many radians?"<<endl;
cin>>value;
ros::NodeHandle nh;
ros::Publisher cmd_vel_pub = nh.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel", 10);
ros::Duration(1.0).sleep();
geometry_msgs::Twist msg;
msg.linear.x = 0.0;
msg.angular.z = value;
cmd_vel_pub.publish(msg);
ros::Duration(1.0).sleep();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[]) { //Main function that contains only 2 cases to be selected. Every case calls a function.
int method=0;
srand(time(NULL));
ros::init(argc, argv, "move_turtlesim");
cout<<"Which working method do you prefer? 1. Move or 2. Rotate"<<endl;
cin>>method;
switch (method) {
case 1:
movefunc();
break;
case 2:
rotatefunc();
break;
}
ros::spin();
return 0;
}
| true |
d588765d5dc722b15ebc88b19ad59f28ead996be | C++ | snowynguyen/atcoder | /ARC113/d.cpp | UTF-8 | 850 | 2.828125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
const int mod = 998244353;
int pw(int a, int b)
{
if (b == 0)
return 1;
long long c = pw(a, b / 2);
c =c * c % mod;
if (b % 2 == 1)
c = c * a % mod;
return c;
}
int F(int n, int k)
{
return ((pw(k, n) - pw(k - 1, n)) % mod + mod) % mod;
}
int main()
{
int m, n, k;
cin >> n >> m >> k;
if (n == 1)
{
if (m == 1)
{
cout << k;
}
else
{
cout << pw(k, m);
}
return 0;
}
else if ( m == 1)
{
cout << pw(k, n);
return 0;
}
int r = 0;
for (int i=1; i<=k; ++i)
{
r = (r + (long long)(pw(i, n) - pw(i - 1, n) + mod) * pw(k - i + 1, m))% mod;
}
cout << r;
} | true |
5c05f71477bf51094e2236bf2cc6b608aa1e5796 | C++ | IdanTo1/spl-assignment1 | /src/PopularTag.cpp | UTF-8 | 1,080 | 3.171875 | 3 | [] | no_license | //
// Created by idanto on 20/11/2019.
//
#include "../include/Session.h"
PopularTag::PopularTag() : _name(""), _count(0) {}
PopularTag::PopularTag(std::string name) : _name(name), _count(1) {}
PopularTag::PopularTag(const PopularTag& other) : _name(other._name), _count(other._count) {}
PopularTag::~PopularTag() {}
const std::string& PopularTag::getName() const {
return _name;
}
int PopularTag::getCount() const {
return _count;
}
void PopularTag::increaseCount() {
_count++;
}
// overloaded < operator
bool PopularTag::operator<(const PopularTag& pt) {
// check if pt is more popular, has bigger count (meaning the user has more Watchables in his history
// containing this tag)
if (this->_count < pt._count) {
return true;
}
else if (this->_count > pt._count) {
return false;
}
// if both tags have same popularity, compare by the classic string opertor>
// that's because we want to sort count from large to small, but name from small to large
else {
return (this->_name > pt._name);
}
}
| true |
d2bf358810a21c1b60e79d9ff59236459b72698e | C++ | mahamedHassan/Dev-projects | /c++/pointer1/pointer1/main.cpp | UTF-8 | 833 | 3.859375 | 4 | [] | no_license | //
// main.cpp
// prints the values and addresses of values
//
// Created by Mahamed Hassan on 1/27/21.
//
#include <iostream>
using namespace std;
int var, *ptr; //Definition of variables var and ptr
int main() //outputs the values and addresses of the variables var and ptr.
{
var = 100;
ptr = &var;
cout<< " Value of var: "<< var
<< " Address of var: "<< &var
<<endl;
cout<< " Value of ptr: "<< ptr
<< " Address of ptr: "<< &ptr
<<endl;
return 0;
}
//Sample screen out put
//Value of var: 100 Address of var: 0x1000080a8
//Value of ptr: 0x1000080a8 Address of ptr: 0x1000080b0
//A pointer is an expression that represents the address and tyype of another //pbject. using the address operator, &, for given object creates a pointerto //that object.
| true |
563787c8a2f3d242c2f134a07fd186422b4923a6 | C++ | romanchom/WiFlyer | /main/MotorPWM.hpp | UTF-8 | 604 | 2.984375 | 3 | [] | no_license | #pragma once
#include "PWM.hpp"
struct MotorPWM : PWM
{
MotorPWM(PWMTimer * timer, gpio_num_t pin, float durationAtZeroPower = 0.001f, float durationAtFullPower = 0.002f) :
PWM(timer, pin),
mDurationAtZeroPower(durationAtZeroPower),
mDurationAtFullPower(durationAtFullPower)
{
thrust(0);
}
void thrust(float fraction)
{
float duration = mDurationAtZeroPower * (1 - fraction) + mDurationAtFullPower * fraction;
duty(duration * mTimer->frequency());
}
protected:
float mDurationAtZeroPower;
float mDurationAtFullPower;
};
| true |
74f90f740295a727373415b80a9f6969070cb1dc | C++ | nitinkumar2558/LAB-8 | /l2.cpp | UTF-8 | 2,037 | 3.921875 | 4 | [] | no_license | //Write a program to find the largest, smallest, mean, median, elements with highest frequency of the elements of all elements of an array. (Use functions for each of the task in the question)
#include<iostream>
using namespace std;
void foomean(int aarray[],int sizeofarray);
void foomedian(int aarray[],int sizeofarray);
void foolargest(int aarray[],int sizeofarray);
void foosmallest(int aarray[],int sizeofarray);
int main() {
int array[5]={2,55,4,99,44} ;
foolargest(array,5);
foosmallest(array,5);
foomean(array,5);
foomedian(array,5);
}
/*
void foolargest(int aarray[],int sizeofarray){
if (aarray[0]>aarray[1,2,3,4]) {cout<<aarray[0]<<"is largest"<<endl;} aarray[1,2,3,4] is reopresent the [4] value only and these all compare with 44 so 55 is maximum will be executed
else if (aarray[1]>aarray[0,2,3,4]) {cout<<aarray[1]<<"is largest"<<endl;}
else if (aarray[2]>aarray[0,1,3,4]) {cout<<aarray[2]<<"is largest"<<endl;}
else if (aarray[3]>aarray[0,2,1,4]) {cout<<aarray[3]<<"is largest"<<endl;}
else {cout<<aarray[4]<<"is largest"<<endl;}
}*/
void foolargest(int aarray[],int sizeofarray){
int max=aarray[0];
for (int i=1;i<5;i++)//after initialisation of max we compare max with aarray[1] to aarray[4]
{if (max<aarray[i]) {max=aarray[i];} }//reassign the value to max and compare new max with next one
cout <<max<< "is maximum"<<endl;}
void foosmallest(int aarray[],int sizeofarray){
int min=aarray[0];
for (int i=1;i<5;i++)//after initialisation of max we compare max with aarray[1] to aarray[4]
{if (min>aarray[i]) {min=aarray[i];} }//reassign the value to max and compare new max with next one
cout <<min<< "is minimum"<<endl;}
void foomean(int aarray[],int sizeofarray){
int sum=0,m;
for(int i=0;i<sizeofarray;i++){
sum=sum+aarray[i];}
m=sum/sizeofarray;
cout<<"mean in int datatype: "<<m<<endl;
}
void foomedian(int aarray[],int sizeofarray){
if (sizeofarray%2!=0){
int x=sizeofarray/2;
cout<<"meadian is: "<<aarray[x]<<endl;
}
else cout<<"print array of odd elements"<<endl;
}
| true |