blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aebd669bc00ebeff1dc71122b6456cb016696a2f | c0fbb8d47bcc752fddb7004962ac21ced60a005e | /单链表找环(声)/单链表找环(声)/源.cpp | e8bc745656c62ff1c9b7d48777df75d9d2da8d1e | [] | no_license | yaogit666/yaogit666 | 8724738093e9edfbf9d37fa6881f5c863523c464 | 6d11fd7fae5bbd7f2291e7ba69480f0d163af860 | refs/heads/master | 2021-07-20T00:32:48.295459 | 2020-10-18T13:53:13 | 2020-10-18T13:53:13 | 223,742,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 454 | cpp | #include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v;
vector<int> table(1000, 0);
int n;
bool b = true;
while (cin >> n)
{
v.push_back(n);
if (cin.get() == '\n')
{
break;
}
}
for (int i = 0; i < v.size(); i++)
{
table[v[i]] ++;
}
for (int i = 0; i < 1000; i++)
{
if (table[i] > 1)
b = false;
}
if (!b)
cout << "true" << endl;
else
cout << "false" << endl;
system("pause");
return 0;
} | [
"1397847010@qq.com"
] | 1397847010@qq.com |
0bb171094e35ab8c6f5bb0d36bc13206e99c075d | a8ccdf4e5b2d4b7314fd98e4962bc7381104e89b | /touchgfx/framework/include/touchgfx/mixins/PreRenderable.hpp | 598197b3ef85daa0723795bab8cffa950a3b67af | [] | no_license | misstek/SmartHomePanel | d6e9948ec97655cff072bffcb13fc9b11b7bdd93 | 72a6498e9850533206a229407217dea05e641c12 | refs/heads/master | 2021-05-01T19:17:09.823698 | 2018-02-10T14:18:40 | 2018-02-10T14:18:40 | 121,018,424 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,754 | hpp | /******************************************************************************
* This file is part of the TouchGFX 4.9.2 distribution.
* Copyright (C) 2017 Draupner Graphics A/S <http://www.touchgfx.com>.
******************************************************************************
* This is licensed software. Any use hereof is restricted by and subject to
* the applicable license terms. For further information see "About/Legal
* Notice" in TouchGFX Designer or in your TouchGFX installation directory.
*****************************************************************************/
#ifndef PRERENDERABLE_HPP
#define PRERENDERABLE_HPP
#include <touchgfx/Drawable.hpp>
#include <touchgfx/hal/HAL.hpp>
namespace touchgfx
{
/**
* @class PreRenderable PreRenderable.hpp touchgfx/mixins/PreRenderable.hpp
*
* @brief This mixin can be used on any Drawable.
*
* This mixin can be used on any Drawable. It provides a preRender function, which will
* cache the current visual appearance of the Drawable to be cache in a memory region.
* Subsequent calls to draw() on this Drawable will result in a simple memcpy of the
* cached memory instead of the normal draw operation. This mixin can therefore be used
* on Drawables whose visual appearance is static and the normal draw operation takes a
* long time to compute.
*
* @note The actual uses of this mixin are rare, and the class is mainly provided for example
* purposes.
*
* @tparam T The type of Drawable to add this functionality to.
*/
template <class T>
class PreRenderable : public T
{
public:
/**
* @fn PreRenderable::PreRenderable()
*
* @brief Default constructor.
*
* Default constructor. Initializes the PreRenderable.
*/
PreRenderable() : preRenderedAddress(0) { }
/**
* @fn void PreRenderable::draw(const Rect& invalidatedArea) const
*
* @brief Overrides the draw function.
*
* Overrides the draw function. If preRender has been called, perform a memcpy of
* the cached version. If not, just call the base class version of draw.
*
* @param invalidatedArea The subregion of this Drawable which needs to be redrawn.
*/
void draw(const Rect& invalidatedArea) const
{
if (isPreRendered())
{
Rect dirty = invalidatedArea;
Rect meAbs = T::getRect();
uint16_t width = T::rect.width;
int cols = dirty.width;
int rows = dirty.height;
int offsetPos = dirty.x + width * dirty.y;
uint16_t* src = (uint16_t*)preRenderedAddress;
HAL::getInstance()->blitCopy(src + offsetPos, meAbs.x + dirty.x, meAbs.y + dirty.y, cols, rows, width, 255, false);
}
else
{
T::draw(invalidatedArea);
}
}
/**
* @fn virtual void PreRenderable::setupDrawChain(const Rect& invalidatedArea, Drawable** nextPreviousElement)
*
* @brief Add to draw chain.
*
* @note For TouchGFX internal use only.
*
* @param invalidatedArea Include drawables that intersect with this area only.
* @param [in,out] nextPreviousElement Modifiable element in linked list.
*/
virtual void setupDrawChain(const Rect& invalidatedArea, Drawable** nextPreviousElement)
{
T::resetDrawChainCache();
if (isPreRendered())
{
if (!T::isVisible())
{
return;
}
T::nextDrawChainElement = *nextPreviousElement;
*nextPreviousElement = this;
}
else
{
T::setupDrawChain(invalidatedArea, nextPreviousElement);
}
}
/**
* @fn bool PreRenderable::isPreRendered() const
*
* @brief Whether or not the snapshot of the widget been taken.
*
* @return Is the widget rendered.
*/
bool isPreRendered() const
{
return preRenderedAddress != 0;
}
/**
* @fn void PreRenderable::preRender()
*
* @brief Takes a snapshot of the current visual appearance of this widget.
*
* Takes a snapshot of the current visual appearance of this widget. All subsequent
* calls to draw on this mixin will result in the snapshot being draw.
*/
void preRender()
{
if (HAL::getInstance()->getBlitCaps() & BLIT_OP_COPY)
{
Rect meAbs = T::getRect();
T::translateRectToAbsolute(meAbs);
preRenderedAddress = HAL::getInstance()->copyFBRegionToMemory(meAbs);
}
}
private:
uint16_t* preRenderedAddress;
};
} // namespace touchgfx
#endif // PRERENDERABLE_HPP
| [
"ming123zhen456@gmail.com"
] | ming123zhen456@gmail.com |
492207df9b45c995f7c43883831557c8447398a1 | 5230acc704b8120c7628f98597780412bf5bf606 | /libs/ofxSoundPlayer/OpenAL/SoundStream.h | 9aece1e3d3ca114aded6657a340bb53e3b8b9dbf | [] | no_license | gaborpapp/smileomaton | 3fa691947df692aad2afb94cc7d8962309a95259 | 6c49e0cb30570ad7a45894738221419135e36df6 | refs/heads/master | 2021-01-10T20:19:06.024471 | 2010-05-29T16:06:38 | 2010-05-29T16:06:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,287 | h | ////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef OFX_SOUNDPLAYER_SOUNDSTREAM_H
#define OFX_SOUNDPLAYER_SOUNDSTREAM_H
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "Sound.h"
#include "ofxThread.h"
#include <cstdlib>
namespace ofxOpenALPlayer
{
////////////////////////////////////////////////////////////
/// SoundStream is a streamed sound, ie samples are acquired
/// while the sound is playing. Use it for big sounds that would
/// require hundreds of MB in memory (see Music),
/// or for streaming sound from the network
////////////////////////////////////////////////////////////
class SoundStream : private ofxThread, private Sound
{
public :
using Sound::SoundStatus;
using Sound::Stopped;
using Sound::Paused;
using Sound::Playing;
using Sound::Pause;
using Sound::SetPitch;
using Sound::SetVolume;
using Sound::SetPosition;
using Sound::SetRelativeToListener;
using Sound::SetMinDistance;
using Sound::SetAttenuation;
using Sound::GetPitch;
using Sound::GetVolume;
using Sound::GetPosition;
using Sound::IsRelativeToListener;
using Sound::GetMinDistance;
using Sound::GetAttenuation;
////////////////////////////////////////////////////////////
/// Structure defining a chunk of audio data to stream
////////////////////////////////////////////////////////////
struct Chunk
{
const Int16* Samples; ///< Pointer to the audio samples
std::size_t NbSamples; ///< Number of samples pointed by Samples
};
////////////////////////////////////////////////////////////
/// Virtual destructor
///
////////////////////////////////////////////////////////////
virtual ~SoundStream();
////////////////////////////////////////////////////////////
/// Start playing the audio stream
///
////////////////////////////////////////////////////////////
void Play();
////////////////////////////////////////////////////////////
/// Stop playing the audio stream
///
////////////////////////////////////////////////////////////
void Stop();
////////////////////////////////////////////////////////////
/// Return the number of channels (1 = mono, 2 = stereo)
///
/// \return Number of channels
///
////////////////////////////////////////////////////////////
unsigned int GetChannelsCount() const;
////////////////////////////////////////////////////////////
/// Get the stream sample rate
///
/// \return Stream frequency (number of samples per second)
///
////////////////////////////////////////////////////////////
unsigned int GetSampleRate() const;
////////////////////////////////////////////////////////////
/// Get the status of the stream (stopped, paused, playing)
///
/// \return Current status of the sound
///
////////////////////////////////////////////////////////////
SoundStatus GetStatus() const;
////////////////////////////////////////////////////////////
/// Get the current playing position of the stream
///
/// \return Current playing position, expressed in seconds
///
////////////////////////////////////////////////////////////
float GetPlayingOffset() const;
////////////////////////////////////////////////////////////
/// Set the stream loop state.
/// This parameter is disabled by default
///
/// \param Loop : True to play in loop, false to play once
///
////////////////////////////////////////////////////////////
void SetLoop(bool Loop);
////////////////////////////////////////////////////////////
/// Tell whether or not the stream is looping
///
/// \return True if the music is looping, false otherwise
///
////////////////////////////////////////////////////////////
bool GetLoop() const;
protected :
////////////////////////////////////////////////////////////
/// Default constructor
///
////////////////////////////////////////////////////////////
SoundStream();
////////////////////////////////////////////////////////////
/// Set the audio stream parameters, you must call it before Play()
///
/// \param ChannelsCount : Number of channels
/// \param SampleRate : Sample rate
///
////////////////////////////////////////////////////////////
void Initialize(unsigned int ChannelsCount, unsigned int SampleRate);
private :
////////////////////////////////////////////////////////////
/// /see Thread::Run
///
////////////////////////////////////////////////////////////
virtual void threadedFunction();
////////////////////////////////////////////////////////////
/// Called when the sound restarts
///
/// \return If false is returned, the playback is aborted
///
////////////////////////////////////////////////////////////
virtual bool OnStart();
////////////////////////////////////////////////////////////
/// Called each time new audio data is needed to feed the stream
///
/// \param Data : New chunk of data to stream
///
/// \return True to continue playback, false to stop
///
////////////////////////////////////////////////////////////
virtual bool OnGetData(Chunk& Data) = 0;
////////////////////////////////////////////////////////////
/// Fill a new buffer with audio data, and push it to the
/// playing queue
///
/// \param Buffer : Buffer to fill
///
/// \return True if the derived class has requested to stop
///
////////////////////////////////////////////////////////////
bool FillAndPushBuffer(unsigned int Buffer);
////////////////////////////////////////////////////////////
/// Fill the buffers queue with all available buffers
///
/// \return True if the derived class has requested to stop
///
////////////////////////////////////////////////////////////
bool FillQueue();
////////////////////////////////////////////////////////////
/// Clear the queue of any remaining buffers
///
////////////////////////////////////////////////////////////
void ClearQueue();
enum {BuffersCount = 3};
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
bool myIsStreaming; ///< Streaming state (true = playing, false = stopped)
unsigned int myBuffers[BuffersCount]; ///< Sound buffers used to store temporary audio data
unsigned int myChannelsCount; ///< Number of channels (1 = mono, 2 = stereo, ...)
unsigned int mySampleRate; ///< Frequency (samples / second)
unsigned long myFormat; ///< Format of the internal sound buffers
bool myLoop; ///< Loop flag (true to loop, false to play once)
unsigned int mySamplesProcessed; ///< Number of buffers processed since beginning of the stream
};
} // namespace ofxOpenALPlayer
#endif // OFX_SOUNDPLAYER_SOUNDSTREAM_H
| [
"gabor.papp@gmail.com"
] | gabor.papp@gmail.com |
52cc9161bec18e6dd3d406b549ebd16e2fa2ea73 | c776476e9d06b3779d744641e758ac3a2c15cddc | /examples/litmus/c/run-scripts/tmp_1/LB+dataonceonce+dataonceonce-rfionceonce-frionceonce.c.cbmc_out.cpp | 2995233757bdf5f69dafeba0619fce308cb2fb94 | [] | no_license | ashutosh0gupta/llvm_bmc | aaac7961c723ba6f7ffd77a39559e0e52432eade | 0287c4fb180244e6b3c599a9902507f05c8a7234 | refs/heads/master | 2023-08-02T17:14:06.178723 | 2023-07-31T10:46:53 | 2023-07-31T10:46:53 | 143,100,825 | 3 | 4 | null | 2023-05-25T05:50:55 | 2018-08-01T03:47:00 | C++ | UTF-8 | C++ | false | false | 37,656 | cpp | // 4:atom_1_X4_1:1
// 0:vars:2
// 2:atom_0_X0_2:1
// 3:atom_1_X0_1:1
// 5:thr0:1
// 6:thr1:1
#define ADDRSIZE 7
#define NPROC 3
#define NCONTEXT 1
#define ASSUME(stmt) __CPROVER_assume(stmt)
#define ASSERT(stmt) __CPROVER_assert(stmt, "error")
#define max(a,b) (a>b?a:b)
char __get_rng();
char get_rng( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
char get_rng_th( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
int main(int argc, char **argv) {
// declare arrays for intial value version in contexts
int meminit_[ADDRSIZE*NCONTEXT];
#define meminit(x,k) meminit_[(x)*NCONTEXT+k]
int coinit_[ADDRSIZE*NCONTEXT];
#define coinit(x,k) coinit_[(x)*NCONTEXT+k]
int deltainit_[ADDRSIZE*NCONTEXT];
#define deltainit(x,k) deltainit_[(x)*NCONTEXT+k]
// declare arrays for running value version in contexts
int mem_[ADDRSIZE*NCONTEXT];
#define mem(x,k) mem_[(x)*NCONTEXT+k]
int co_[ADDRSIZE*NCONTEXT];
#define co(x,k) co_[(x)*NCONTEXT+k]
int delta_[ADDRSIZE*NCONTEXT];
#define delta(x,k) delta_[(x)*NCONTEXT+k]
// declare arrays for local buffer and observed writes
int buff_[NPROC*ADDRSIZE];
#define buff(x,k) buff_[(x)*ADDRSIZE+k]
int pw_[NPROC*ADDRSIZE];
#define pw(x,k) pw_[(x)*ADDRSIZE+k]
// declare arrays for context stamps
char cr_[NPROC*ADDRSIZE];
#define cr(x,k) cr_[(x)*ADDRSIZE+k]
char iw_[NPROC*ADDRSIZE];
#define iw(x,k) iw_[(x)*ADDRSIZE+k]
char cw_[NPROC*ADDRSIZE];
#define cw(x,k) cw_[(x)*ADDRSIZE+k]
char cx_[NPROC*ADDRSIZE];
#define cx(x,k) cx_[(x)*ADDRSIZE+k]
char is_[NPROC*ADDRSIZE];
#define is(x,k) is_[(x)*ADDRSIZE+k]
char cs_[NPROC*ADDRSIZE];
#define cs(x,k) cs_[(x)*ADDRSIZE+k]
char crmax_[NPROC*ADDRSIZE];
#define crmax(x,k) crmax_[(x)*ADDRSIZE+k]
char sforbid_[ADDRSIZE*NCONTEXT];
#define sforbid(x,k) sforbid_[(x)*NCONTEXT+k]
// declare arrays for synchronizations
int cl[NPROC];
int cdy[NPROC];
int cds[NPROC];
int cdl[NPROC];
int cisb[NPROC];
int caddr[NPROC];
int cctrl[NPROC];
int cstart[NPROC];
int creturn[NPROC];
// declare arrays for contexts activity
int active[NCONTEXT];
int ctx_used[NCONTEXT];
int r0= 0;
char creg_r0;
int r1= 0;
char creg_r1;
int r2= 0;
char creg_r2;
int r3= 0;
char creg_r3;
int r4= 0;
char creg_r4;
int r5= 0;
char creg_r5;
int r6= 0;
char creg_r6;
int r7= 0;
char creg_r7;
int r8= 0;
char creg_r8;
int r9= 0;
char creg_r9;
int r10= 0;
char creg_r10;
int r11= 0;
char creg_r11;
int r12= 0;
char creg_r12;
int r13= 0;
char creg_r13;
int r14= 0;
char creg_r14;
int r15= 0;
char creg_r15;
int r16= 0;
char creg_r16;
int r17= 0;
char creg_r17;
char old_cctrl= 0;
char old_cr= 0;
char old_cdy= 0;
char old_cw= 0;
char new_creg= 0;
buff(0,0) = 0;
pw(0,0) = 0;
cr(0,0) = 0;
iw(0,0) = 0;
cw(0,0) = 0;
cx(0,0) = 0;
is(0,0) = 0;
cs(0,0) = 0;
crmax(0,0) = 0;
buff(0,1) = 0;
pw(0,1) = 0;
cr(0,1) = 0;
iw(0,1) = 0;
cw(0,1) = 0;
cx(0,1) = 0;
is(0,1) = 0;
cs(0,1) = 0;
crmax(0,1) = 0;
buff(0,2) = 0;
pw(0,2) = 0;
cr(0,2) = 0;
iw(0,2) = 0;
cw(0,2) = 0;
cx(0,2) = 0;
is(0,2) = 0;
cs(0,2) = 0;
crmax(0,2) = 0;
buff(0,3) = 0;
pw(0,3) = 0;
cr(0,3) = 0;
iw(0,3) = 0;
cw(0,3) = 0;
cx(0,3) = 0;
is(0,3) = 0;
cs(0,3) = 0;
crmax(0,3) = 0;
buff(0,4) = 0;
pw(0,4) = 0;
cr(0,4) = 0;
iw(0,4) = 0;
cw(0,4) = 0;
cx(0,4) = 0;
is(0,4) = 0;
cs(0,4) = 0;
crmax(0,4) = 0;
buff(0,5) = 0;
pw(0,5) = 0;
cr(0,5) = 0;
iw(0,5) = 0;
cw(0,5) = 0;
cx(0,5) = 0;
is(0,5) = 0;
cs(0,5) = 0;
crmax(0,5) = 0;
buff(0,6) = 0;
pw(0,6) = 0;
cr(0,6) = 0;
iw(0,6) = 0;
cw(0,6) = 0;
cx(0,6) = 0;
is(0,6) = 0;
cs(0,6) = 0;
crmax(0,6) = 0;
cl[0] = 0;
cdy[0] = 0;
cds[0] = 0;
cdl[0] = 0;
cisb[0] = 0;
caddr[0] = 0;
cctrl[0] = 0;
cstart[0] = get_rng(0,NCONTEXT-1);
creturn[0] = get_rng(0,NCONTEXT-1);
buff(1,0) = 0;
pw(1,0) = 0;
cr(1,0) = 0;
iw(1,0) = 0;
cw(1,0) = 0;
cx(1,0) = 0;
is(1,0) = 0;
cs(1,0) = 0;
crmax(1,0) = 0;
buff(1,1) = 0;
pw(1,1) = 0;
cr(1,1) = 0;
iw(1,1) = 0;
cw(1,1) = 0;
cx(1,1) = 0;
is(1,1) = 0;
cs(1,1) = 0;
crmax(1,1) = 0;
buff(1,2) = 0;
pw(1,2) = 0;
cr(1,2) = 0;
iw(1,2) = 0;
cw(1,2) = 0;
cx(1,2) = 0;
is(1,2) = 0;
cs(1,2) = 0;
crmax(1,2) = 0;
buff(1,3) = 0;
pw(1,3) = 0;
cr(1,3) = 0;
iw(1,3) = 0;
cw(1,3) = 0;
cx(1,3) = 0;
is(1,3) = 0;
cs(1,3) = 0;
crmax(1,3) = 0;
buff(1,4) = 0;
pw(1,4) = 0;
cr(1,4) = 0;
iw(1,4) = 0;
cw(1,4) = 0;
cx(1,4) = 0;
is(1,4) = 0;
cs(1,4) = 0;
crmax(1,4) = 0;
buff(1,5) = 0;
pw(1,5) = 0;
cr(1,5) = 0;
iw(1,5) = 0;
cw(1,5) = 0;
cx(1,5) = 0;
is(1,5) = 0;
cs(1,5) = 0;
crmax(1,5) = 0;
buff(1,6) = 0;
pw(1,6) = 0;
cr(1,6) = 0;
iw(1,6) = 0;
cw(1,6) = 0;
cx(1,6) = 0;
is(1,6) = 0;
cs(1,6) = 0;
crmax(1,6) = 0;
cl[1] = 0;
cdy[1] = 0;
cds[1] = 0;
cdl[1] = 0;
cisb[1] = 0;
caddr[1] = 0;
cctrl[1] = 0;
cstart[1] = get_rng(0,NCONTEXT-1);
creturn[1] = get_rng(0,NCONTEXT-1);
buff(2,0) = 0;
pw(2,0) = 0;
cr(2,0) = 0;
iw(2,0) = 0;
cw(2,0) = 0;
cx(2,0) = 0;
is(2,0) = 0;
cs(2,0) = 0;
crmax(2,0) = 0;
buff(2,1) = 0;
pw(2,1) = 0;
cr(2,1) = 0;
iw(2,1) = 0;
cw(2,1) = 0;
cx(2,1) = 0;
is(2,1) = 0;
cs(2,1) = 0;
crmax(2,1) = 0;
buff(2,2) = 0;
pw(2,2) = 0;
cr(2,2) = 0;
iw(2,2) = 0;
cw(2,2) = 0;
cx(2,2) = 0;
is(2,2) = 0;
cs(2,2) = 0;
crmax(2,2) = 0;
buff(2,3) = 0;
pw(2,3) = 0;
cr(2,3) = 0;
iw(2,3) = 0;
cw(2,3) = 0;
cx(2,3) = 0;
is(2,3) = 0;
cs(2,3) = 0;
crmax(2,3) = 0;
buff(2,4) = 0;
pw(2,4) = 0;
cr(2,4) = 0;
iw(2,4) = 0;
cw(2,4) = 0;
cx(2,4) = 0;
is(2,4) = 0;
cs(2,4) = 0;
crmax(2,4) = 0;
buff(2,5) = 0;
pw(2,5) = 0;
cr(2,5) = 0;
iw(2,5) = 0;
cw(2,5) = 0;
cx(2,5) = 0;
is(2,5) = 0;
cs(2,5) = 0;
crmax(2,5) = 0;
buff(2,6) = 0;
pw(2,6) = 0;
cr(2,6) = 0;
iw(2,6) = 0;
cw(2,6) = 0;
cx(2,6) = 0;
is(2,6) = 0;
cs(2,6) = 0;
crmax(2,6) = 0;
cl[2] = 0;
cdy[2] = 0;
cds[2] = 0;
cdl[2] = 0;
cisb[2] = 0;
caddr[2] = 0;
cctrl[2] = 0;
cstart[2] = get_rng(0,NCONTEXT-1);
creturn[2] = get_rng(0,NCONTEXT-1);
// Dumping initializations
mem(4+0,0) = 0;
mem(0+0,0) = 0;
mem(0+1,0) = 0;
mem(2+0,0) = 0;
mem(3+0,0) = 0;
mem(5+0,0) = 0;
mem(6+0,0) = 0;
// Dumping context matching equalities
co(0,0) = 0;
delta(0,0) = -1;
co(1,0) = 0;
delta(1,0) = -1;
co(2,0) = 0;
delta(2,0) = -1;
co(3,0) = 0;
delta(3,0) = -1;
co(4,0) = 0;
delta(4,0) = -1;
co(5,0) = 0;
delta(5,0) = -1;
co(6,0) = 0;
delta(6,0) = -1;
// Dumping thread 1
int ret_thread_1 = 0;
cdy[1] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[1] >= cstart[1]);
T1BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !37, metadata !DIExpression()), !dbg !54
// br label %label_1, !dbg !55
goto T1BLOCK1;
T1BLOCK1:
// call void @llvm.dbg.label(metadata !53), !dbg !56
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !40, metadata !DIExpression()), !dbg !57
// %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !58
// LD: Guess
old_cr = cr(1,0+1*1);
cr(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN LDCOM
// Check
ASSUME(active[cr(1,0+1*1)] == 1);
ASSUME(cr(1,0+1*1) >= iw(1,0+1*1));
ASSUME(cr(1,0+1*1) >= 0);
ASSUME(cr(1,0+1*1) >= cdy[1]);
ASSUME(cr(1,0+1*1) >= cisb[1]);
ASSUME(cr(1,0+1*1) >= cdl[1]);
ASSUME(cr(1,0+1*1) >= cl[1]);
// Update
creg_r0 = cr(1,0+1*1);
crmax(1,0+1*1) = max(crmax(1,0+1*1),cr(1,0+1*1));
caddr[1] = max(caddr[1],0);
if(cr(1,0+1*1) < cw(1,0+1*1)) {
r0 = buff(1,0+1*1);
} else {
if(pw(1,0+1*1) != co(0+1*1,cr(1,0+1*1))) {
ASSUME(cr(1,0+1*1) >= old_cr);
}
pw(1,0+1*1) = co(0+1*1,cr(1,0+1*1));
r0 = mem(0+1*1,cr(1,0+1*1));
}
ASSUME(creturn[1] >= cr(1,0+1*1));
// call void @llvm.dbg.value(metadata i64 %0, metadata !43, metadata !DIExpression()), !dbg !57
// %conv = trunc i64 %0 to i32, !dbg !59
// call void @llvm.dbg.value(metadata i32 %conv, metadata !38, metadata !DIExpression()), !dbg !54
// %xor = xor i32 %conv, %conv, !dbg !60
creg_r1 = max(creg_r0,creg_r0);
ASSUME(active[creg_r1] == 1);
r1 = r0 ^ r0;
// call void @llvm.dbg.value(metadata i32 %xor, metadata !44, metadata !DIExpression()), !dbg !54
// %add = add nsw i32 %xor, 1, !dbg !61
creg_r2 = max(creg_r1,0);
ASSUME(active[creg_r2] == 1);
r2 = r1 + 1;
// call void @llvm.dbg.value(metadata i32 %add, metadata !45, metadata !DIExpression()), !dbg !54
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !46, metadata !DIExpression()), !dbg !62
// %conv1 = sext i32 %add to i64, !dbg !63
// call void @llvm.dbg.value(metadata i64 %conv1, metadata !48, metadata !DIExpression()), !dbg !62
// store atomic i64 %conv1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !63
// ST: Guess
iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0);
cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0)] == 1);
ASSUME(active[cw(1,0)] == 1);
ASSUME(sforbid(0,cw(1,0))== 0);
ASSUME(iw(1,0) >= creg_r2);
ASSUME(iw(1,0) >= 0);
ASSUME(cw(1,0) >= iw(1,0));
ASSUME(cw(1,0) >= old_cw);
ASSUME(cw(1,0) >= cr(1,0));
ASSUME(cw(1,0) >= cl[1]);
ASSUME(cw(1,0) >= cisb[1]);
ASSUME(cw(1,0) >= cdy[1]);
ASSUME(cw(1,0) >= cdl[1]);
ASSUME(cw(1,0) >= cds[1]);
ASSUME(cw(1,0) >= cctrl[1]);
ASSUME(cw(1,0) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0) = r2;
mem(0,cw(1,0)) = r2;
co(0,cw(1,0))+=1;
delta(0,cw(1,0)) = -1;
ASSUME(creturn[1] >= cw(1,0));
// %cmp = icmp eq i32 %conv, 2, !dbg !64
// %conv2 = zext i1 %cmp to i32, !dbg !64
// call void @llvm.dbg.value(metadata i32 %conv2, metadata !49, metadata !DIExpression()), !dbg !54
// call void @llvm.dbg.value(metadata i64* @atom_0_X0_2, metadata !50, metadata !DIExpression()), !dbg !65
// %1 = zext i32 %conv2 to i64
// call void @llvm.dbg.value(metadata i64 %1, metadata !52, metadata !DIExpression()), !dbg !65
// store atomic i64 %1, i64* @atom_0_X0_2 seq_cst, align 8, !dbg !66
// ST: Guess
iw(1,2) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,2);
cw(1,2) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,2)] == 1);
ASSUME(active[cw(1,2)] == 1);
ASSUME(sforbid(2,cw(1,2))== 0);
ASSUME(iw(1,2) >= max(creg_r0,0));
ASSUME(iw(1,2) >= 0);
ASSUME(cw(1,2) >= iw(1,2));
ASSUME(cw(1,2) >= old_cw);
ASSUME(cw(1,2) >= cr(1,2));
ASSUME(cw(1,2) >= cl[1]);
ASSUME(cw(1,2) >= cisb[1]);
ASSUME(cw(1,2) >= cdy[1]);
ASSUME(cw(1,2) >= cdl[1]);
ASSUME(cw(1,2) >= cds[1]);
ASSUME(cw(1,2) >= cctrl[1]);
ASSUME(cw(1,2) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,2) = (r0==2);
mem(2,cw(1,2)) = (r0==2);
co(2,cw(1,2))+=1;
delta(2,cw(1,2)) = -1;
ASSUME(creturn[1] >= cw(1,2));
// ret i8* null, !dbg !67
ret_thread_1 = (- 1);
// Dumping thread 2
int ret_thread_2 = 0;
cdy[2] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[2] >= cstart[2]);
T2BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !70, metadata !DIExpression()), !dbg !96
// br label %label_2, !dbg !66
goto T2BLOCK1;
T2BLOCK1:
// call void @llvm.dbg.label(metadata !95), !dbg !98
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !72, metadata !DIExpression()), !dbg !99
// %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !69
// LD: Guess
old_cr = cr(2,0);
cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0)] == 2);
ASSUME(cr(2,0) >= iw(2,0));
ASSUME(cr(2,0) >= 0);
ASSUME(cr(2,0) >= cdy[2]);
ASSUME(cr(2,0) >= cisb[2]);
ASSUME(cr(2,0) >= cdl[2]);
ASSUME(cr(2,0) >= cl[2]);
// Update
creg_r3 = cr(2,0);
crmax(2,0) = max(crmax(2,0),cr(2,0));
caddr[2] = max(caddr[2],0);
if(cr(2,0) < cw(2,0)) {
r3 = buff(2,0);
} else {
if(pw(2,0) != co(0,cr(2,0))) {
ASSUME(cr(2,0) >= old_cr);
}
pw(2,0) = co(0,cr(2,0));
r3 = mem(0,cr(2,0));
}
ASSUME(creturn[2] >= cr(2,0));
// call void @llvm.dbg.value(metadata i64 %0, metadata !74, metadata !DIExpression()), !dbg !99
// %conv = trunc i64 %0 to i32, !dbg !70
// call void @llvm.dbg.value(metadata i32 %conv, metadata !71, metadata !DIExpression()), !dbg !96
// %xor = xor i32 %conv, %conv, !dbg !71
creg_r4 = max(creg_r3,creg_r3);
ASSUME(active[creg_r4] == 2);
r4 = r3 ^ r3;
// call void @llvm.dbg.value(metadata i32 %xor, metadata !75, metadata !DIExpression()), !dbg !96
// %add = add nsw i32 %xor, 1, !dbg !72
creg_r5 = max(creg_r4,0);
ASSUME(active[creg_r5] == 2);
r5 = r4 + 1;
// call void @llvm.dbg.value(metadata i32 %add, metadata !76, metadata !DIExpression()), !dbg !96
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !77, metadata !DIExpression()), !dbg !104
// %conv1 = sext i32 %add to i64, !dbg !74
// call void @llvm.dbg.value(metadata i64 %conv1, metadata !79, metadata !DIExpression()), !dbg !104
// store atomic i64 %conv1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !74
// ST: Guess
iw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,0+1*1);
cw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,0+1*1)] == 2);
ASSUME(active[cw(2,0+1*1)] == 2);
ASSUME(sforbid(0+1*1,cw(2,0+1*1))== 0);
ASSUME(iw(2,0+1*1) >= creg_r5);
ASSUME(iw(2,0+1*1) >= 0);
ASSUME(cw(2,0+1*1) >= iw(2,0+1*1));
ASSUME(cw(2,0+1*1) >= old_cw);
ASSUME(cw(2,0+1*1) >= cr(2,0+1*1));
ASSUME(cw(2,0+1*1) >= cl[2]);
ASSUME(cw(2,0+1*1) >= cisb[2]);
ASSUME(cw(2,0+1*1) >= cdy[2]);
ASSUME(cw(2,0+1*1) >= cdl[2]);
ASSUME(cw(2,0+1*1) >= cds[2]);
ASSUME(cw(2,0+1*1) >= cctrl[2]);
ASSUME(cw(2,0+1*1) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,0+1*1) = r5;
mem(0+1*1,cw(2,0+1*1)) = r5;
co(0+1*1,cw(2,0+1*1))+=1;
delta(0+1*1,cw(2,0+1*1)) = -1;
ASSUME(creturn[2] >= cw(2,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !81, metadata !DIExpression()), !dbg !106
// %1 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !76
// LD: Guess
old_cr = cr(2,0+1*1);
cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0+1*1)] == 2);
ASSUME(cr(2,0+1*1) >= iw(2,0+1*1));
ASSUME(cr(2,0+1*1) >= 0);
ASSUME(cr(2,0+1*1) >= cdy[2]);
ASSUME(cr(2,0+1*1) >= cisb[2]);
ASSUME(cr(2,0+1*1) >= cdl[2]);
ASSUME(cr(2,0+1*1) >= cl[2]);
// Update
creg_r6 = cr(2,0+1*1);
crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1));
caddr[2] = max(caddr[2],0);
if(cr(2,0+1*1) < cw(2,0+1*1)) {
r6 = buff(2,0+1*1);
} else {
if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) {
ASSUME(cr(2,0+1*1) >= old_cr);
}
pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1));
r6 = mem(0+1*1,cr(2,0+1*1));
}
ASSUME(creturn[2] >= cr(2,0+1*1));
// call void @llvm.dbg.value(metadata i64 %1, metadata !83, metadata !DIExpression()), !dbg !106
// %conv5 = trunc i64 %1 to i32, !dbg !77
// call void @llvm.dbg.value(metadata i32 %conv5, metadata !80, metadata !DIExpression()), !dbg !96
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !84, metadata !DIExpression()), !dbg !109
// call void @llvm.dbg.value(metadata i64 2, metadata !86, metadata !DIExpression()), !dbg !109
// store atomic i64 2, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !79
// ST: Guess
iw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,0+1*1);
cw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,0+1*1)] == 2);
ASSUME(active[cw(2,0+1*1)] == 2);
ASSUME(sforbid(0+1*1,cw(2,0+1*1))== 0);
ASSUME(iw(2,0+1*1) >= 0);
ASSUME(iw(2,0+1*1) >= 0);
ASSUME(cw(2,0+1*1) >= iw(2,0+1*1));
ASSUME(cw(2,0+1*1) >= old_cw);
ASSUME(cw(2,0+1*1) >= cr(2,0+1*1));
ASSUME(cw(2,0+1*1) >= cl[2]);
ASSUME(cw(2,0+1*1) >= cisb[2]);
ASSUME(cw(2,0+1*1) >= cdy[2]);
ASSUME(cw(2,0+1*1) >= cdl[2]);
ASSUME(cw(2,0+1*1) >= cds[2]);
ASSUME(cw(2,0+1*1) >= cctrl[2]);
ASSUME(cw(2,0+1*1) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,0+1*1) = 2;
mem(0+1*1,cw(2,0+1*1)) = 2;
co(0+1*1,cw(2,0+1*1))+=1;
delta(0+1*1,cw(2,0+1*1)) = -1;
ASSUME(creturn[2] >= cw(2,0+1*1));
// %cmp = icmp eq i32 %conv, 1, !dbg !80
// %conv8 = zext i1 %cmp to i32, !dbg !80
// call void @llvm.dbg.value(metadata i32 %conv8, metadata !87, metadata !DIExpression()), !dbg !96
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !88, metadata !DIExpression()), !dbg !112
// %2 = zext i32 %conv8 to i64
// call void @llvm.dbg.value(metadata i64 %2, metadata !90, metadata !DIExpression()), !dbg !112
// store atomic i64 %2, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !82
// ST: Guess
iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,3);
cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,3)] == 2);
ASSUME(active[cw(2,3)] == 2);
ASSUME(sforbid(3,cw(2,3))== 0);
ASSUME(iw(2,3) >= max(creg_r3,0));
ASSUME(iw(2,3) >= 0);
ASSUME(cw(2,3) >= iw(2,3));
ASSUME(cw(2,3) >= old_cw);
ASSUME(cw(2,3) >= cr(2,3));
ASSUME(cw(2,3) >= cl[2]);
ASSUME(cw(2,3) >= cisb[2]);
ASSUME(cw(2,3) >= cdy[2]);
ASSUME(cw(2,3) >= cdl[2]);
ASSUME(cw(2,3) >= cds[2]);
ASSUME(cw(2,3) >= cctrl[2]);
ASSUME(cw(2,3) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,3) = (r3==1);
mem(3,cw(2,3)) = (r3==1);
co(3,cw(2,3))+=1;
delta(3,cw(2,3)) = -1;
ASSUME(creturn[2] >= cw(2,3));
// %cmp12 = icmp eq i32 %conv5, 1, !dbg !83
// %conv13 = zext i1 %cmp12 to i32, !dbg !83
// call void @llvm.dbg.value(metadata i32 %conv13, metadata !91, metadata !DIExpression()), !dbg !96
// call void @llvm.dbg.value(metadata i64* @atom_1_X4_1, metadata !92, metadata !DIExpression()), !dbg !115
// %3 = zext i32 %conv13 to i64
// call void @llvm.dbg.value(metadata i64 %3, metadata !94, metadata !DIExpression()), !dbg !115
// store atomic i64 %3, i64* @atom_1_X4_1 seq_cst, align 8, !dbg !85
// ST: Guess
iw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,4);
cw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,4)] == 2);
ASSUME(active[cw(2,4)] == 2);
ASSUME(sforbid(4,cw(2,4))== 0);
ASSUME(iw(2,4) >= max(creg_r6,0));
ASSUME(iw(2,4) >= 0);
ASSUME(cw(2,4) >= iw(2,4));
ASSUME(cw(2,4) >= old_cw);
ASSUME(cw(2,4) >= cr(2,4));
ASSUME(cw(2,4) >= cl[2]);
ASSUME(cw(2,4) >= cisb[2]);
ASSUME(cw(2,4) >= cdy[2]);
ASSUME(cw(2,4) >= cdl[2]);
ASSUME(cw(2,4) >= cds[2]);
ASSUME(cw(2,4) >= cctrl[2]);
ASSUME(cw(2,4) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,4) = (r6==1);
mem(4,cw(2,4)) = (r6==1);
co(4,cw(2,4))+=1;
delta(4,cw(2,4)) = -1;
ASSUME(creturn[2] >= cw(2,4));
// ret i8* null, !dbg !86
ret_thread_2 = (- 1);
// Dumping thread 0
int ret_thread_0 = 0;
cdy[0] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[0] >= cstart[0]);
T0BLOCK0:
// %thr0 = alloca i64, align 8
// %thr1 = alloca i64, align 8
// call void @llvm.dbg.value(metadata i32 %argc, metadata !125, metadata !DIExpression()), !dbg !167
// call void @llvm.dbg.value(metadata i8** %argv, metadata !126, metadata !DIExpression()), !dbg !167
// %0 = bitcast i64* %thr0 to i8*, !dbg !85
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !85
// call void @llvm.dbg.declare(metadata i64* %thr0, metadata !127, metadata !DIExpression()), !dbg !169
// %1 = bitcast i64* %thr1 to i8*, !dbg !87
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !87
// call void @llvm.dbg.declare(metadata i64* %thr1, metadata !131, metadata !DIExpression()), !dbg !171
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !132, metadata !DIExpression()), !dbg !172
// call void @llvm.dbg.value(metadata i64 0, metadata !134, metadata !DIExpression()), !dbg !172
// store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !90
// ST: Guess
iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+1*1);
cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+1*1)] == 0);
ASSUME(active[cw(0,0+1*1)] == 0);
ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(cw(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cw(0,0+1*1) >= old_cw);
ASSUME(cw(0,0+1*1) >= cr(0,0+1*1));
ASSUME(cw(0,0+1*1) >= cl[0]);
ASSUME(cw(0,0+1*1) >= cisb[0]);
ASSUME(cw(0,0+1*1) >= cdy[0]);
ASSUME(cw(0,0+1*1) >= cdl[0]);
ASSUME(cw(0,0+1*1) >= cds[0]);
ASSUME(cw(0,0+1*1) >= cctrl[0]);
ASSUME(cw(0,0+1*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+1*1) = 0;
mem(0+1*1,cw(0,0+1*1)) = 0;
co(0+1*1,cw(0,0+1*1))+=1;
delta(0+1*1,cw(0,0+1*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !135, metadata !DIExpression()), !dbg !174
// call void @llvm.dbg.value(metadata i64 0, metadata !137, metadata !DIExpression()), !dbg !174
// store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !92
// ST: Guess
iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0);
cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0)] == 0);
ASSUME(active[cw(0,0)] == 0);
ASSUME(sforbid(0,cw(0,0))== 0);
ASSUME(iw(0,0) >= 0);
ASSUME(iw(0,0) >= 0);
ASSUME(cw(0,0) >= iw(0,0));
ASSUME(cw(0,0) >= old_cw);
ASSUME(cw(0,0) >= cr(0,0));
ASSUME(cw(0,0) >= cl[0]);
ASSUME(cw(0,0) >= cisb[0]);
ASSUME(cw(0,0) >= cdy[0]);
ASSUME(cw(0,0) >= cdl[0]);
ASSUME(cw(0,0) >= cds[0]);
ASSUME(cw(0,0) >= cctrl[0]);
ASSUME(cw(0,0) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0) = 0;
mem(0,cw(0,0)) = 0;
co(0,cw(0,0))+=1;
delta(0,cw(0,0)) = -1;
ASSUME(creturn[0] >= cw(0,0));
// call void @llvm.dbg.value(metadata i64* @atom_0_X0_2, metadata !138, metadata !DIExpression()), !dbg !176
// call void @llvm.dbg.value(metadata i64 0, metadata !140, metadata !DIExpression()), !dbg !176
// store atomic i64 0, i64* @atom_0_X0_2 monotonic, align 8, !dbg !94
// ST: Guess
iw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,2);
cw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,2)] == 0);
ASSUME(active[cw(0,2)] == 0);
ASSUME(sforbid(2,cw(0,2))== 0);
ASSUME(iw(0,2) >= 0);
ASSUME(iw(0,2) >= 0);
ASSUME(cw(0,2) >= iw(0,2));
ASSUME(cw(0,2) >= old_cw);
ASSUME(cw(0,2) >= cr(0,2));
ASSUME(cw(0,2) >= cl[0]);
ASSUME(cw(0,2) >= cisb[0]);
ASSUME(cw(0,2) >= cdy[0]);
ASSUME(cw(0,2) >= cdl[0]);
ASSUME(cw(0,2) >= cds[0]);
ASSUME(cw(0,2) >= cctrl[0]);
ASSUME(cw(0,2) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,2) = 0;
mem(2,cw(0,2)) = 0;
co(2,cw(0,2))+=1;
delta(2,cw(0,2)) = -1;
ASSUME(creturn[0] >= cw(0,2));
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !141, metadata !DIExpression()), !dbg !178
// call void @llvm.dbg.value(metadata i64 0, metadata !143, metadata !DIExpression()), !dbg !178
// store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !96
// ST: Guess
iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,3);
cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,3)] == 0);
ASSUME(active[cw(0,3)] == 0);
ASSUME(sforbid(3,cw(0,3))== 0);
ASSUME(iw(0,3) >= 0);
ASSUME(iw(0,3) >= 0);
ASSUME(cw(0,3) >= iw(0,3));
ASSUME(cw(0,3) >= old_cw);
ASSUME(cw(0,3) >= cr(0,3));
ASSUME(cw(0,3) >= cl[0]);
ASSUME(cw(0,3) >= cisb[0]);
ASSUME(cw(0,3) >= cdy[0]);
ASSUME(cw(0,3) >= cdl[0]);
ASSUME(cw(0,3) >= cds[0]);
ASSUME(cw(0,3) >= cctrl[0]);
ASSUME(cw(0,3) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,3) = 0;
mem(3,cw(0,3)) = 0;
co(3,cw(0,3))+=1;
delta(3,cw(0,3)) = -1;
ASSUME(creturn[0] >= cw(0,3));
// call void @llvm.dbg.value(metadata i64* @atom_1_X4_1, metadata !144, metadata !DIExpression()), !dbg !180
// call void @llvm.dbg.value(metadata i64 0, metadata !146, metadata !DIExpression()), !dbg !180
// store atomic i64 0, i64* @atom_1_X4_1 monotonic, align 8, !dbg !98
// ST: Guess
iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,4);
cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,4)] == 0);
ASSUME(active[cw(0,4)] == 0);
ASSUME(sforbid(4,cw(0,4))== 0);
ASSUME(iw(0,4) >= 0);
ASSUME(iw(0,4) >= 0);
ASSUME(cw(0,4) >= iw(0,4));
ASSUME(cw(0,4) >= old_cw);
ASSUME(cw(0,4) >= cr(0,4));
ASSUME(cw(0,4) >= cl[0]);
ASSUME(cw(0,4) >= cisb[0]);
ASSUME(cw(0,4) >= cdy[0]);
ASSUME(cw(0,4) >= cdl[0]);
ASSUME(cw(0,4) >= cds[0]);
ASSUME(cw(0,4) >= cctrl[0]);
ASSUME(cw(0,4) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,4) = 0;
mem(4,cw(0,4)) = 0;
co(4,cw(0,4))+=1;
delta(4,cw(0,4)) = -1;
ASSUME(creturn[0] >= cw(0,4));
// %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !99
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[1] >= cdy[0]);
// %call9 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !100
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[2] >= cdy[0]);
// %2 = load i64, i64* %thr0, align 8, !dbg !101, !tbaa !102
// LD: Guess
old_cr = cr(0,5);
cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,5)] == 0);
ASSUME(cr(0,5) >= iw(0,5));
ASSUME(cr(0,5) >= 0);
ASSUME(cr(0,5) >= cdy[0]);
ASSUME(cr(0,5) >= cisb[0]);
ASSUME(cr(0,5) >= cdl[0]);
ASSUME(cr(0,5) >= cl[0]);
// Update
creg_r8 = cr(0,5);
crmax(0,5) = max(crmax(0,5),cr(0,5));
caddr[0] = max(caddr[0],0);
if(cr(0,5) < cw(0,5)) {
r8 = buff(0,5);
} else {
if(pw(0,5) != co(5,cr(0,5))) {
ASSUME(cr(0,5) >= old_cr);
}
pw(0,5) = co(5,cr(0,5));
r8 = mem(5,cr(0,5));
}
ASSUME(creturn[0] >= cr(0,5));
// %call10 = call i32 @pthread_join(i64 noundef %2, i8** noundef null), !dbg !106
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[1]);
// %3 = load i64, i64* %thr1, align 8, !dbg !107, !tbaa !102
// LD: Guess
old_cr = cr(0,6);
cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,6)] == 0);
ASSUME(cr(0,6) >= iw(0,6));
ASSUME(cr(0,6) >= 0);
ASSUME(cr(0,6) >= cdy[0]);
ASSUME(cr(0,6) >= cisb[0]);
ASSUME(cr(0,6) >= cdl[0]);
ASSUME(cr(0,6) >= cl[0]);
// Update
creg_r9 = cr(0,6);
crmax(0,6) = max(crmax(0,6),cr(0,6));
caddr[0] = max(caddr[0],0);
if(cr(0,6) < cw(0,6)) {
r9 = buff(0,6);
} else {
if(pw(0,6) != co(6,cr(0,6))) {
ASSUME(cr(0,6) >= old_cr);
}
pw(0,6) = co(6,cr(0,6));
r9 = mem(6,cr(0,6));
}
ASSUME(creturn[0] >= cr(0,6));
// %call11 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !108
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[2]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !148, metadata !DIExpression()), !dbg !192
// %4 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) seq_cst, align 8, !dbg !110
// LD: Guess
old_cr = cr(0,0+1*1);
cr(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,0+1*1)] == 0);
ASSUME(cr(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cr(0,0+1*1) >= 0);
ASSUME(cr(0,0+1*1) >= cdy[0]);
ASSUME(cr(0,0+1*1) >= cisb[0]);
ASSUME(cr(0,0+1*1) >= cdl[0]);
ASSUME(cr(0,0+1*1) >= cl[0]);
// Update
creg_r10 = cr(0,0+1*1);
crmax(0,0+1*1) = max(crmax(0,0+1*1),cr(0,0+1*1));
caddr[0] = max(caddr[0],0);
if(cr(0,0+1*1) < cw(0,0+1*1)) {
r10 = buff(0,0+1*1);
} else {
if(pw(0,0+1*1) != co(0+1*1,cr(0,0+1*1))) {
ASSUME(cr(0,0+1*1) >= old_cr);
}
pw(0,0+1*1) = co(0+1*1,cr(0,0+1*1));
r10 = mem(0+1*1,cr(0,0+1*1));
}
ASSUME(creturn[0] >= cr(0,0+1*1));
// call void @llvm.dbg.value(metadata i64 %4, metadata !150, metadata !DIExpression()), !dbg !192
// %conv = trunc i64 %4 to i32, !dbg !111
// call void @llvm.dbg.value(metadata i32 %conv, metadata !147, metadata !DIExpression()), !dbg !167
// %cmp = icmp eq i32 %conv, 2, !dbg !112
// %conv12 = zext i1 %cmp to i32, !dbg !112
// call void @llvm.dbg.value(metadata i32 %conv12, metadata !151, metadata !DIExpression()), !dbg !167
// call void @llvm.dbg.value(metadata i64* @atom_0_X0_2, metadata !153, metadata !DIExpression()), !dbg !196
// %5 = load atomic i64, i64* @atom_0_X0_2 seq_cst, align 8, !dbg !114
// LD: Guess
old_cr = cr(0,2);
cr(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,2)] == 0);
ASSUME(cr(0,2) >= iw(0,2));
ASSUME(cr(0,2) >= 0);
ASSUME(cr(0,2) >= cdy[0]);
ASSUME(cr(0,2) >= cisb[0]);
ASSUME(cr(0,2) >= cdl[0]);
ASSUME(cr(0,2) >= cl[0]);
// Update
creg_r11 = cr(0,2);
crmax(0,2) = max(crmax(0,2),cr(0,2));
caddr[0] = max(caddr[0],0);
if(cr(0,2) < cw(0,2)) {
r11 = buff(0,2);
} else {
if(pw(0,2) != co(2,cr(0,2))) {
ASSUME(cr(0,2) >= old_cr);
}
pw(0,2) = co(2,cr(0,2));
r11 = mem(2,cr(0,2));
}
ASSUME(creturn[0] >= cr(0,2));
// call void @llvm.dbg.value(metadata i64 %5, metadata !155, metadata !DIExpression()), !dbg !196
// %conv16 = trunc i64 %5 to i32, !dbg !115
// call void @llvm.dbg.value(metadata i32 %conv16, metadata !152, metadata !DIExpression()), !dbg !167
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !157, metadata !DIExpression()), !dbg !199
// %6 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !117
// LD: Guess
old_cr = cr(0,3);
cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,3)] == 0);
ASSUME(cr(0,3) >= iw(0,3));
ASSUME(cr(0,3) >= 0);
ASSUME(cr(0,3) >= cdy[0]);
ASSUME(cr(0,3) >= cisb[0]);
ASSUME(cr(0,3) >= cdl[0]);
ASSUME(cr(0,3) >= cl[0]);
// Update
creg_r12 = cr(0,3);
crmax(0,3) = max(crmax(0,3),cr(0,3));
caddr[0] = max(caddr[0],0);
if(cr(0,3) < cw(0,3)) {
r12 = buff(0,3);
} else {
if(pw(0,3) != co(3,cr(0,3))) {
ASSUME(cr(0,3) >= old_cr);
}
pw(0,3) = co(3,cr(0,3));
r12 = mem(3,cr(0,3));
}
ASSUME(creturn[0] >= cr(0,3));
// call void @llvm.dbg.value(metadata i64 %6, metadata !159, metadata !DIExpression()), !dbg !199
// %conv20 = trunc i64 %6 to i32, !dbg !118
// call void @llvm.dbg.value(metadata i32 %conv20, metadata !156, metadata !DIExpression()), !dbg !167
// call void @llvm.dbg.value(metadata i64* @atom_1_X4_1, metadata !161, metadata !DIExpression()), !dbg !202
// %7 = load atomic i64, i64* @atom_1_X4_1 seq_cst, align 8, !dbg !120
// LD: Guess
old_cr = cr(0,4);
cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,4)] == 0);
ASSUME(cr(0,4) >= iw(0,4));
ASSUME(cr(0,4) >= 0);
ASSUME(cr(0,4) >= cdy[0]);
ASSUME(cr(0,4) >= cisb[0]);
ASSUME(cr(0,4) >= cdl[0]);
ASSUME(cr(0,4) >= cl[0]);
// Update
creg_r13 = cr(0,4);
crmax(0,4) = max(crmax(0,4),cr(0,4));
caddr[0] = max(caddr[0],0);
if(cr(0,4) < cw(0,4)) {
r13 = buff(0,4);
} else {
if(pw(0,4) != co(4,cr(0,4))) {
ASSUME(cr(0,4) >= old_cr);
}
pw(0,4) = co(4,cr(0,4));
r13 = mem(4,cr(0,4));
}
ASSUME(creturn[0] >= cr(0,4));
// call void @llvm.dbg.value(metadata i64 %7, metadata !163, metadata !DIExpression()), !dbg !202
// %conv24 = trunc i64 %7 to i32, !dbg !121
// call void @llvm.dbg.value(metadata i32 %conv24, metadata !160, metadata !DIExpression()), !dbg !167
// %and = and i32 %conv20, %conv24, !dbg !122
creg_r14 = max(creg_r12,creg_r13);
ASSUME(active[creg_r14] == 0);
r14 = r12 & r13;
// call void @llvm.dbg.value(metadata i32 %and, metadata !164, metadata !DIExpression()), !dbg !167
// %and25 = and i32 %conv16, %and, !dbg !123
creg_r15 = max(creg_r11,creg_r14);
ASSUME(active[creg_r15] == 0);
r15 = r11 & r14;
// call void @llvm.dbg.value(metadata i32 %and25, metadata !165, metadata !DIExpression()), !dbg !167
// %and26 = and i32 %conv12, %and25, !dbg !124
creg_r16 = max(max(creg_r10,0),creg_r15);
ASSUME(active[creg_r16] == 0);
r16 = (r10==2) & r15;
// call void @llvm.dbg.value(metadata i32 %and26, metadata !166, metadata !DIExpression()), !dbg !167
// %cmp27 = icmp eq i32 %and26, 1, !dbg !125
// br i1 %cmp27, label %if.then, label %if.end, !dbg !127
old_cctrl = cctrl[0];
cctrl[0] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[0] >= old_cctrl);
ASSUME(cctrl[0] >= creg_r16);
ASSUME(cctrl[0] >= 0);
if((r16==1)) {
goto T0BLOCK1;
} else {
goto T0BLOCK2;
}
T0BLOCK1:
// call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([137 x i8], [137 x i8]* @.str.1, i64 0, i64 0), i32 noundef 69, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !128
// unreachable, !dbg !128
r17 = 1;
T0BLOCK2:
// %8 = bitcast i64* %thr1 to i8*, !dbg !131
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %8) #7, !dbg !131
// %9 = bitcast i64* %thr0 to i8*, !dbg !131
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) #7, !dbg !131
// ret i32 0, !dbg !132
ret_thread_0 = 0;
ASSERT(r17== 0);
}
| [
"tuan-phong.ngo@it.uu.se"
] | tuan-phong.ngo@it.uu.se |
cd5e62fb89f011dcbfae468c1104ed0dc49c933d | 2b84e114db3c996d6d2ea99df103753f8588ce14 | /main.cpp | 854b36d87af432994c7fd492dc88cb21e19a8fd5 | [] | no_license | Xiaolian-Liu/MRIA-LAB | 18dda3471eb0666d620b551115fecc0adc3194d7 | 7fba1a557e229d5d2c212fdadc6aa164071d0a16 | refs/heads/main | 2023-03-30T16:53:37.977433 | 2021-03-22T02:58:28 | 2021-03-22T02:58:28 | 350,184,870 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,436 | cpp | #include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <sys/mman.h>
#include <malloc.h>
#include <math.h>
#include <ecrt.h>
#include <iostream>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdint.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <sys/mman.h>
#include <malloc.h>
#include <sched.h> /* sched_setscheduler() */
#include <limits.h>
#include <pthread.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include "ecat.h"
using namespace std;
static int latency_target_fd;
int32_t latency_target_value = 0;
int run = 1;
void signal_stop(int sig)
{
run = 0;
}
static void set_latency_target(void)
{
struct stat s;
int err;
err = stat("/dev/cpu_dma_latency", &s);
if (err == -1) {
perror("WARN: stat /dev/cpu_dma_latency failed: ");
return;
}
latency_target_fd = open("/dev/cpu_dma_latency", O_RDWR);
if (latency_target_fd == -1) {
perror("WARN: open /dev/cpu_dma_latency: ");
return;
}
err = write(latency_target_fd, &latency_target_value, 4);
if (err < 1) {
printf("# error setting cpu_dma_latency to %d!", latency_target_value);
close(latency_target_fd);
return;
}
printf("# /dev/cpu_dma_latency set to %dus\n", latency_target_value);
}
int main()
{
struct sched_param param;
pthread_attr_t attr;
pthread_t thread;
int ret;
signal(SIGINT, signal_stop);
signal(SIGTERM, signal_stop);
if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1){
printf("mlockall failed: %m\n");
exit(-2);
}
set_latency_target();
ret = pthread_attr_init(&attr);
if(ret)
{
perror("init pthread attributes failed\n");
exit(EXIT_FAILURE);
}
ret = pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN);
if (ret) {
printf("pthread setstacksize failed\n");
goto out;
}
ret = pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
if (ret) {
printf("pthread setschedpolicy failed\n");
goto out;
}
param.sched_priority = 98;
ret = pthread_attr_setschedparam(&attr, ¶m);
if (ret) {
printf("pthread setschedparam failed\n");
goto out;
}
/* Use scheduling parameters of attr */
ret = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
if (ret) {
printf("pthread setinheritsched failed\n");
goto out;
}
/* Create a pthread with specified attributes */
ret = pthread_create(&thread, &attr, ecat_task, NULL);
if (ret) {
printf("create pthread failed\n");
goto out;
}
while(run)
{
usleep(100000);
}
out:
close(latency_target_fd);
munlockall();
ret = pthread_join(thread, NULL);
if (ret)
printf("join pthread failed: %m\n");
cout << "Hello World!" << endl;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
adfb4a225bbb2ab8194280c357f5329620d9377b | 89485890afeeacdae996de966b8b13ba0c1bbc9a | /mplib/include/zrecieveprogressbar.h | 95da06c89c2b4e9d729a45b00b7a076b8eebd741 | [] | no_license | weinkym/src_miao | b7c8a35a80e5928470bea07d5eb7e36d54966da9 | 0759c1f819c15c8bb2172fe2558fcb728a186ff8 | refs/heads/master | 2021-08-07T17:55:52.239541 | 2021-06-17T03:38:44 | 2021-06-17T03:38:44 | 64,458,033 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 886 | h | #ifndef ZRECIEVEPROGRESSBAR_H
#define ZRECIEVEPROGRESSBAR_H
#include <QDialog>
#include "mplib_global.h"
class Ui_ZRecieveProgressBar;
class MPLIBSHARED_EXPORT ZRecieveProgressBar : public QDialog
{
Q_OBJECT
public:
ZRecieveProgressBar(QWidget* parent = 0, Qt::WindowFlags f = 0);
~ZRecieveProgressBar();
void setId(const QString& id);
public slots:
void onRecieveButtonClicked();
void onRejectButtonClicked();
void onFileReceiveProgress(qint64 done, qint64 total);
void onFinished();
signals:
void sigRecieve();
void sigRecieve(const QString& id);
void sigCancel();
void sigCancel(const QString& id);
void sigRejected();
void sigRejected(const QString& id);
private:
enum E_STATUS_TYPE{E_RECIEVE,E_CANCEL};
Ui_ZRecieveProgressBar* ui;
E_STATUS_TYPE m_type;
QString m_id;
};
#endif // ZRECIEVEPROGRESSBAR_H
| [
"weinkym@qq.com"
] | weinkym@qq.com |
dac2ee0d80b272ef6a8dc6c0075a97653c44f238 | 05c82b8c01b443638f83d98ab1207fce796a9c90 | /src/collision/shapes/ObjectSetter.hpp | 30dd3a1e5f1a65d57a3db750726f88d689c30941 | [] | no_license | aljazk/powerball | c2bfc22bd3ee0492bd27b411889810131b16268a | ccea1c4b5167a6ad4a55d29b865be19e32e1708f | refs/heads/master | 2021-05-03T09:35:29.809372 | 2016-11-05T19:11:30 | 2016-11-05T19:11:30 | 70,336,586 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 792 | hpp | #ifndef OBJECTSETTER_H
#define OBJECTSETTER_H
#include "Polygon.hpp"
#include "Circle.hpp"
#include <vector>
#include <unordered_set>
#include <memory>
class ObjectSetter{
std::vector<Polygon> polygons;
std::vector<Circle> circles; // make so it can be made out of multiple shapes -- just skip collision if they have same object id
public:
ObjectSetter();
void reset();
void clear();
void add(const Polygon &);
void add(const Circle &);
float position_x, position_y;
float velocity_x, velocity_y;
float rotation; // make rotations
float mass, elasticity;
std::vector<Polygon> getPolygons();
std::vector<Circle> getCircles();
std::unordered_set<std::shared_ptr<Polygon>> getPolygons1();
std::unordered_set<std::shared_ptr<Circle>> getCircles1();
};
#endif | [
"aljaz.konecnik@gmail.com"
] | aljaz.konecnik@gmail.com |
08e63ac702540f31bcb3d7b237a7b5af3e3d7aa3 | 7e4ef7ec81cefef0f2092eb9ba65d72263026437 | /Siv3D/src/Siv3D/FFT/IFFT.hpp | 3ad064508f6c35a67c2822387f1c4011587ab975 | [
"MIT"
] | permissive | zakuro9715/OpenSiv3D | 0fb50580212cc667f2f749f8e39dcb696764cbc4 | 6cf5fc00f71cfc39883a2c57a71ad8f51bc69b5d | refs/heads/master | 2023-03-06T13:42:56.410816 | 2023-03-03T13:38:54 | 2023-03-03T13:38:54 | 208,563,311 | 0 | 0 | MIT | 2019-09-15T08:22:18 | 2019-09-15T08:22:17 | null | UTF-8 | C++ | false | false | 980 | hpp | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2022 Ryo Suzuki
// Copyright (c) 2016-2022 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include <Siv3D/Common.hpp>
# include <Siv3D/Array.hpp>
# include <Siv3D/WaveSample.hpp>
namespace s3d
{
struct FFTResult;
class Wave;
enum class FFTSampleLength : uint8;
class SIV3D_NOVTABLE ISiv3DFFT
{
public:
static ISiv3DFFT* Create();
virtual ~ISiv3DFFT() = default;
virtual void init() = 0;
virtual void fft(FFTResult& result, const Wave& wave, uint32 pos, FFTSampleLength sampleLength) = 0;
virtual void fft(FFTResult& result, const Array<WaveSampleS16>& wave, uint32 pos, uint32 sampleRate, FFTSampleLength sampleLength) = 0;
virtual void fft(FFTResult& result, const float* input, size_t size, uint32 sampleRate, FFTSampleLength sampleLength) = 0;
};
}
| [
"reputeless+github@gmail.com"
] | reputeless+github@gmail.com |
729f19e339f5929035e2048131972612fceddd42 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5686275109552128_0/C++/Jianzhi/infinitehouseofpancakes2.cpp | 055389a8f7c643c9d7ebdca21c1f3ee3e180ea3d | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 700 | cpp | #include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;
double arr[1001];
int main(){
freopen("B-small-attempt0.in", "r", stdin);
freopen("B-small-attempt0.out", "w", stdout);
int tc;
cin >> tc;
int a, b;
int maxi = 1000000000;
int cur = 0;
for (int i = 0; i < tc; i++){
maxi = 1000000000;
cin >> a;
for (int j = 0; j < a; j++){
cin >> arr[j];
}
sort(arr, arr + a);
for (int j = 1000; j > 0; j--){
cur = 0;
for (int k = a - 1; arr[k] > j; k--){
cur = cur + ceil((arr[k]/j)) - 1;
}
maxi = min(maxi, cur + j);
}
cout << "Case #" << i + 1 << ": " << maxi << endl;
}
}
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
cf33be72d29ef510ef0a1d2e0d1ac9ee91a3faf3 | 19586b3c44ceaa4dc9056c9b36962d0ea759f6f7 | /marble.cpp | fd258ca0b6f0069226394f648dccfa4310f48b10 | [] | no_license | SerketCity/collectionofgames | 922e231ebf91fca9a53cb47bdc2a5d7d34cfb569 | 4db8457809390fa39f87b30fc226fbccbb54a9ea | refs/heads/master | 2022-12-15T10:33:46.012112 | 2020-09-17T22:42:32 | 2020-09-17T22:42:32 | 296,457,536 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 236 | cpp | #include <string>
#include "marble.h"
using namespace std;
Marble::Marble()
{
color = "Blue";
}
Marble::Marble(string s)
{
color = s;
}
void Marble::setColor(string s)
{
color = s;
}
string Marble::getColor()
{
return color;
}
| [
"johnrice1997@gmail.com"
] | johnrice1997@gmail.com |
85b727a4bf4030d64c6a18b124624069a1a16490 | 8ae31e5db1f7c25b6ce1c708655ab55c15dde14e | /比赛/学校/2019-6-2测试/folding/folding.cpp | 8a4965f99648be28f60616f8c6e1cb3a3c89b236 | [] | no_license | LeverImmy/Codes | 99786afd826ae786b5024a3a73c8f92af09aae5d | ca28e61f55977e5b45d6731bc993c66e09f716a3 | refs/heads/master | 2020-09-03T13:00:29.025752 | 2019-12-16T12:11:23 | 2019-12-16T12:11:23 | 219,466,644 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,115 | cpp | #include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
#include <cctype>
#define rgi register int
#define il inline
#define ll long long
#define maxn 110
#define maxl 10010
using namespace std;
int n, l, flag, cnt;
int t[maxn], A[maxl], B[maxl];
il int read()
{
rgi x = 0, f = 0, ch;
while(!isdigit(ch = getchar())) f |= ch == '-';
while(isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
return f ? -x : x;
}
il void write(int x)
{
if(x < 0) putchar('-'), x = -x;
if(x > 9) write(x / 10);
putchar(x % 10 + 48);
}
void check(int A[], int pos, int end)
{
while(pos < end)
{
if(A[pos] != A[end])
{
flag = 0;
return;
}
else
pos++, end--;
}
}
int main()
{
n = read(), l = read();
for(rgi i = 1; i <= n; ++i)
{
t[i] = read();
A[t[i]] = 1;
}
for(rgi i = 1; i <= n; ++i)
{
flag = 1;
check(A, t[i], l);
if(flag)
cnt++;
//printf("::%d\n::", (t[i] + l) >> 1);
flag = 1;
check(A, 0, t[i]);
if(flag)
cnt++;
//printf("::%d\n::", (0 + t[i]) >> 1);
}
write(cnt - 2);
return 0;
}
| [
"506503360@qq.com"
] | 506503360@qq.com |
bd512cf606a66c3e3bbd078ec82526b7cdcdd8b5 | 44a44a01fed981e1e05fdea3699069f89667e880 | /src/bitcoinrpc.cpp | 4b4c667c75b3fead52bcf46f01649065d76c1855 | [
"MIT"
] | permissive | eagleflies/eagle_cur | 76174c70d60e1cff8012c9d4076ce5b2904cc981 | e638fffe1e75c1d60db94972619a151b7a252379 | refs/heads/master | 2016-09-01T21:24:30.454970 | 2014-10-07T18:39:40 | 2014-10-07T18:39:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 119,493 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 The Litecoin Developers
// Copyright (c) 2013 adam m.
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "wallet.h"
#include "db.h"
#include "walletdb.h"
#include "net.h"
#include "init.h"
#include "ui_interface.h"
#include "base58.h"
#include "bitcoinrpc.h"
#undef printf
#include <boost/asio.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/shared_ptr.hpp>
#include <list>
#define printf OutputDebugStringF
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
void ThreadRPCServer2(void* parg);
static std::string strRPCUserColonPass;
static int64 nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
extern Value getconnectioncount(const Array& params, bool fHelp); // in rpcnet.cpp
extern Value getpeerinfo(const Array& params, bool fHelp);
extern Value dumpprivkey(const Array& params, bool fHelp); // in rpcdump.cpp
extern Value importprivkey(const Array& params, bool fHelp);
extern Value getrawtransaction(const Array& params, bool fHelp); // in rcprawtransaction.cpp
extern Value listunspent(const Array& params, bool fHelp);
extern Value createrawtransaction(const Array& params, bool fHelp);
extern Value decoderawtransaction(const Array& params, bool fHelp);
extern Value signrawtransaction(const Array& params, bool fHelp);
extern Value sendrawtransaction(const Array& params, bool fHelp);
const Object emptyobj;
void ThreadRPCServer3(void* parg);
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (v.type() != t)
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(-3, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (v.type() == null_type)
throw JSONRPCError(-3, strprintf("Missing %s", t.first.c_str()));
if (v.type() != t.second)
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
throw JSONRPCError(-3, err);
}
}
}
double GetDifficulty(const CBlockIndex* blockindex = NULL)
{
// Floating point number that is a multiple of the minimum difficulty,
// minimum difficulty = 1.0.
if (blockindex == NULL)
{
if (pindexBest == NULL)
return 1.0;
else
blockindex = pindexBest;
}
int nShift = (blockindex->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
while (nShift < 29)
{
dDiff *= 256.0;
nShift++;
}
while (nShift > 29)
{
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
int64 AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > 84000000.0)
throw JSONRPCError(-3, "Invalid amount");
int64 nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(-3, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64 amount)
{
return (double)amount / (double)COIN;
}
std::string
HexBits(unsigned int nBits)
{
union {
int32_t nBits;
char cBits[4];
} uBits;
uBits.nBits = htonl((int32_t)nBits);
return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
}
std::string
HelpRequiringPassphrase()
{
return pwalletMain->IsCrypted()
? "\nrequires wallet passphrase to be set with walletpassphrase first"
: "";
}
void
EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
}
void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
{
int confirms = wtx.GetDepthInMainChain();
entry.push_back(Pair("confirmations", confirms));
if (confirms)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
}
entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const Value& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(-11, "Invalid account name");
return strAccount;
}
Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex)
{
Object result;
result.push_back(Pair("hash", block.GetHash().GetHex()));
CMerkleTx txGen(block.vtx[0]);
txGen.SetMerkleBranch(&block);
result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain()));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
Array txs;
BOOST_FOREACH(const CTransaction&tx, block.vtx)
txs.push_back(tx.GetHash().GetHex());
result.push_back(Pair("tx", txs));
result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime()));
result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce));
result.push_back(Pair("bits", HexBits(block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
if (blockindex->pnext)
result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));
return result;
}
/// Note: This interface may still be subject to change.
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"stop\n"
"Stop eagle_cur server.");
// Shutdown will take long enough that the response should get back
StartShutdown();
return "eagle_cur server has now stopped running!";
}
Value getblockcount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockcount\n"
"Returns the number of blocks in the longest block chain.");
return nBestHeight;
}
Value getdifficulty(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getdifficulty\n"
"Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");
return GetDifficulty();
}
// Litecoin: Return average network hashes per second based on last number of blocks.
Value GetNetworkHashPS(int lookup) {
if (pindexBest == NULL)
return 0;
// If lookup is -1, then use blocks since last difficulty change.
if (lookup <= 0)
lookup = pindexBest->nHeight % 2016 + 1;
// If lookup is larger than chain, then set it to chain length.
if (lookup > pindexBest->nHeight)
lookup = pindexBest->nHeight;
CBlockIndex* pindexPrev = pindexBest;
for (int i = 0; i < lookup; i++)
pindexPrev = pindexPrev->pprev;
double timeDiff = pindexBest->GetBlockTime() - pindexPrev->GetBlockTime();
double timePerBlock = timeDiff / lookup;
return (boost::int64_t)(((double)GetDifficulty() * pow(2.0, 32)) / timePerBlock);
}
Value getnetworkhashps(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnetworkhashps [blocks]\n"
"Returns the estimated network hashes per second based on the last 120 blocks.\n"
"Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.");
return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120);
}
Value getgenerate(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getgenerate\n"
"Returns true or false.");
return GetBoolArg("-gen");
}
Value setgenerate(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setgenerate <generate> [genproclimit]\n"
"<generate> is true or false to turn generation on or off.\n"
"Generation is limited to [genproclimit] processors, -1 is unlimited.");
bool fGenerate = true;
if (params.size() > 0)
fGenerate = params[0].get_bool();
if (params.size() > 1)
{
int nGenProcLimit = params[1].get_int();
mapArgs["-genproclimit"] = itostr(nGenProcLimit);
if (nGenProcLimit == 0)
fGenerate = false;
}
mapArgs["-gen"] = (fGenerate ? "1" : "0");
GenerateBitcoins(fGenerate, pwalletMain);
return Value::null;
}
Value gethashespersec(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"gethashespersec\n"
"Returns a recent hashes per second performance measurement while generating.");
if (GetTimeMillis() - nHPSTimerStart > 8000)
return (boost::int64_t)0;
return (boost::int64_t)dHashesPerSec;
}
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.");
CService addrProxy;
GetProxy(NET_IPV4, addrProxy);
Object obj;
obj.push_back(Pair("version", (int)CLIENT_VERSION));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (addrProxy.IsValid() ? addrProxy.ToStringIPPort() : string())));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("testnet", fTestNet));
obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", pwalletMain->GetKeyPoolSize()));
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue)));
if (pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime / 1000));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
Value getmininginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"Returns an object containing mining-related information.");
Object obj;
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("generate", GetBoolArg("-gen")));
obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
obj.push_back(Pair("networkhashps", getnetworkhashps(params, false)));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("testnet", fTestNet));
return obj;
}
Value getnewaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress [account]\n"
"Returns a new eagle_cur address for receiving payments. "
"If [account] is specified (recommended), it is added to the address book "
"so payments received with the address will be credited to [account].");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey, false))
throw JSONRPCError(-12, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount);
return CBitcoinAddress(keyID).ToString();
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey;
scriptPubKey.SetDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false))
throw JSONRPCError(-12, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount);
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
Value getaccountaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress <account>\n"
"Returns the current eagle_cur address for receiving payments to this account.");
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
Value ret;
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
Value setaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount <eagle_cur address> <account>\n"
"Sets the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(-5, "Invalid eagle_cur address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
string strOldAccount = pwalletMain->mapAddressBook[address.Get()];
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBookName(address.Get(), strAccount);
return Value::null;
}
Value getaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount <eagle_cur address>\n"
"Returns the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(-5, "Invalid eagle_cur address");
string strAccount;
map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
strAccount = (*mi).second;
return strAccount;
}
Value getaddressesbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount <account>\n"
"Returns the list of addresses for the given account.");
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
Array ret;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
Value settxfee(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"settxfee <amount>\n"
"<amount> is a real and is rounded to the nearest 0.00000001");
// Amount
int64 nAmount = 0;
if (params[0].get_real() != 0.0)
nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
nTransactionFee = nAmount;
return true;
}
Value setmininput(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"setmininput <amount>\n"
"<amount> is a real and is rounded to the nearest 0.00000001");
// Amount
int64 nAmount = 0;
if (params[0].get_real() != 0.0)
nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
nMinimumInputValue = nAmount;
return true;
}
Value sendtoaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddress <eagle_cur address> <amount> [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase());
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(-5, "Invalid eagle_cur address");
// Amount
int64 nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
if (pwalletMain->IsLocked())
throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(-4, strError);
return wtx.GetHash().GetHex();
}
Value signmessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage <eagle_cur address> <message>\n"
"Sign a message with the private key of an address");
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(-3, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(-3, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(-4, "Private key not available");
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
throw JSONRPCError(-5, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage <eagle_cur address> <signature> <message>\n"
"Verify a signed message");
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(-3, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(-3, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(-5, "Malformed base64 encoding");
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CKey key;
if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig))
return false;
return (key.GetPubKey().GetID() == keyID);
}
Value getreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress <eagle_cur address> [minconf=1]\n"
"Returns the total amount received by <eagle_cur address> in transactions with at least [minconf] confirmations.");
// eagle_cur address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
CScript scriptPubKey;
if (!address.IsValid())
throw JSONRPCError(-5, "Invalid eagle_cur address");
scriptPubKey.SetDestination(address.Get());
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook)
{
const CTxDestination& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
setAddress.insert(address);
}
}
Value getreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount <account> [minconf=1]\n"
"Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress;
GetAccountAddresses(strAccount, setAddress);
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
{
int64 nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal())
continue;
int64 nGenerated, nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nGenerated, nReceived, nSent, nFee);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
nBalance += nReceived;
nBalance += nGenerated - nSent - nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
int64 GetAccountBalance(const string& strAccount, int nMinDepth)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth);
}
Value getbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getbalance [account] [minconf=1]\n"
"If [account] is not specified, returns the server's total available balance.\n"
"If [account] is specified, returns the balance in the account.");
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and getbalance '*' should always return the same number.
int64 nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal())
continue;
int64 allGeneratedImmature, allGeneratedMature, allFee;
allGeneratedImmature = allGeneratedMature = allFee = 0;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
nBalance += r.second;
}
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent)
nBalance -= r.second;
nBalance -= allFee;
nBalance += allGeneratedMature;
}
return ValueFromAmount(nBalance);
}
string strAccount = AccountFromValue(params[0]);
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
return ValueFromAmount(nBalance);
}
Value movecmd(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
"Move from one account in your wallet to another.");
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
int64 nAmount = AmountFromValue(params[2]);
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(-20, "database error");
int64 nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
walletdb.WriteAccountingEntry(debit);
// Credit
CAccountingEntry credit;
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
walletdb.WriteAccountingEntry(credit);
if (!walletdb.TxnCommit())
throw JSONRPCError(-20, "database error");
return true;
}
Value sendfrom(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom <fromaccount> <to eagle_cur address> <amount> [minconf=1] [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(-5, "Invalid eagle_cur address");
int64 nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (nAmount > nBalance)
throw JSONRPCError(-6, "Account has insufficient funds");
// Send
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(-4, strError);
return wtx.GetHash().GetHex();
}
Value sendmany(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
"amounts are double-precision floating point numbers"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
Object sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
set<CBitcoinAddress> setAddress;
vector<pair<CScript, int64> > vecSend;
int64 totalAmount = 0;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(-5, string("Invalid eagle_cur address:")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(-8, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64 nAmount = AmountFromValue(s.value_);
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
EnsureWalletIsUnlocked();
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (totalAmount > nBalance)
throw JSONRPCError(-6, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
int64 nFeeRequired = 0;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
if (!fCreated)
{
if (totalAmount + nFeeRequired > pwalletMain->GetBalance())
throw JSONRPCError(-6, "Insufficient funds");
throw JSONRPCError(-4, "Transaction creation failed");
}
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(-4, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
Value addmultisigaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
{
string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
"Add a nrequired-to-sign multisignature address to the wallet\"\n"
"each key is a eagle_cur address or hex-encoded public key\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %d keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
// Case 1: eagle_cur address and we have full public key:
CBitcoinAddress address(ks);
if (address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key",ks.c_str()));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s",ks.c_str()));
if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey))
throw runtime_error(" Invalid public key: "+ks);
}
// Case 2: hex public key
else if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey))
throw runtime_error(" Invalid public key: "+ks);
}
else
{
throw runtime_error(" Invalid public key: "+ks);
}
}
// Construct using pay-to-script-hash:
CScript inner;
inner.SetMultisig(nRequired, pubkeys);
CScriptID innerID = inner.GetID();
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
struct tallyitem
{
int64 nAmount;
int nConf;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
}
};
Value ListReceived(const Array& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
}
}
// Reply
Array ret;
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
int64 nAmount = 0;
int nConf = std::numeric_limits<int>::max();
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
}
else
{
Object obj;
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
if (fByAccounts)
{
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
int64 nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
Object obj;
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
return ret;
}
Value listreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaddress [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include addresses that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"address\" : receiving address\n"
" \"account\" : the account of the receiving address\n"
" \"amount\" : total amount received by the address\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, false);
}
Value listreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaccount [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include accounts that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"account\" : the account of the receiving addresses\n"
" \"amount\" : total amount received by addresses with this account\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, true);
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
{
int64 nGeneratedImmature, nGeneratedMature, nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
bool fAllAccounts = (strAccount == string("*"));
// Generated blocks assigned to account ""
if ((nGeneratedMature+nGeneratedImmature) != 0 && (fAllAccounts || strAccount == ""))
{
Object entry;
entry.push_back(Pair("account", string("")));
if (nGeneratedImmature)
{
entry.push_back(Pair("category", wtx.GetDepthInMainChain() ? "immature" : "orphan"));
entry.push_back(Pair("amount", ValueFromAmount(nGeneratedImmature)));
}
else
{
entry.push_back(Pair("category", "generate"));
entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature)));
}
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
{
Object entry;
entry.push_back(Pair("account", strSentAccount));
entry.push_back(Pair("address", CBitcoinAddress(s.first).ToString()));
entry.push_back(Pair("category", "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
{
string account;
if (pwalletMain->mapAddressBook.count(r.first))
account = pwalletMain->mapAddressBook[r.first];
if (fAllAccounts || (account == strAccount))
{
Object entry;
entry.push_back(Pair("account", account));
entry.push_back(Pair("address", CBitcoinAddress(r.first).ToString()));
entry.push_back(Pair("category", "receive"));
entry.push_back(Pair("amount", ValueFromAmount(r.second)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
Object entry;
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
Value listtransactions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listtransactions [account] [count=10] [from=0]\n"
"Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
if (nCount < 0)
throw JSONRPCError(-8, "Negative count");
if (nFrom < 0)
throw JSONRPCError(-8, "Negative from");
Array ret;
CWalletDB walletdb(pwalletMain->strWalletFile);
// First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef multimap<int64, TxPair > TxItems;
TxItems txByTime;
// Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
// would make this much faster for applications that do this a lot.
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
CWalletTx* wtx = &((*it).second);
txByTime.insert(make_pair(wtx->GetTxTime(), TxPair(wtx, (CAccountingEntry*)0)));
}
list<CAccountingEntry> acentries;
walletdb.ListAccountCreditDebit(strAccount, acentries);
BOOST_FOREACH(CAccountingEntry& entry, acentries)
{
txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
}
// iterate backwards until we have nCount items to return:
for (TxItems::reverse_iterator it = txByTime.rbegin(); it != txByTime.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
Array::iterator first = ret.begin();
std::advance(first, nFrom);
Array::iterator last = ret.begin();
std::advance(last, nFrom+nCount);
if (last != ret.end()) ret.erase(last, ret.end());
if (first != ret.begin()) ret.erase(ret.begin(), first);
std::reverse(ret.begin(), ret.end()); // Return oldest to newest
return ret;
}
Value listaccounts(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"listaccounts [minconf=1]\n"
"Returns Object that has account names as keys, account balances as values.");
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
map<string, int64> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first)) // This address belongs to me
mapAccountBalances[entry.second] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
int64 nGeneratedImmature, nGeneratedMature, nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
mapAccountBalances[strSentAccount] -= s.second;
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
mapAccountBalances[""] += nGeneratedMature;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.first))
mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
else
mapAccountBalances[""] += r.second;
}
}
list<CAccountingEntry> acentries;
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
Object ret;
BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
Value listsinceblock(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listsinceblock [blockhash] [target-confirmations]\n"
"Get all transactions in blocks since block [blockhash], or all transactions if omitted");
CBlockIndex *pindex = NULL;
int target_confirms = 1;
if (params.size() > 0)
{
uint256 blockId = 0;
blockId.SetHex(params[0].get_str());
pindex = CBlockLocator(blockId).GetBlockIndex();
}
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(-8, "Invalid parameter");
}
int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1;
Array transactions;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain() < depth)
ListTransactions(tx, "*", 0, true, transactions);
}
uint256 lastblock;
if (target_confirms == 1)
{
lastblock = hashBestChain;
}
else
{
int target_height = pindexBest->nHeight + 1 - target_confirms;
CBlockIndex *block;
for (block = pindexBest;
block && block->nHeight > target_height;
block = block->pprev) { }
lastblock = block ? block->GetBlockHash() : 0;
}
Object ret;
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
Value gettransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"gettransaction <txid>\n"
"Get detailed information about in-wallet transaction <txid>");
uint256 hash;
hash.SetHex(params[0].get_str());
Object entry;
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(-5, "Invalid or non-wallet transaction id");
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
int64 nCredit = wtx.GetCredit();
int64 nDebit = wtx.GetDebit();
int64 nNet = nCredit - nDebit;
int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe())
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
Array details;
ListTransactions(wtx, "*", 0, false, details);
entry.push_back(Pair("details", details));
return entry;
}
Value backupwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet <destination>\n"
"Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
string strDest = params[0].get_str();
BackupWallet(*pwalletMain, strDest);
return Value::null;
}
Value keypoolrefill(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"keypoolrefill\n"
"Fills the keypool."
+ HelpRequiringPassphrase());
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool();
if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100))
throw JSONRPCError(-4, "Error refreshing keypool.");
return Value::null;
}
void ThreadTopUpKeyPool(void* parg)
{
// Make this thread recognisable as the key-topping-up thread
RenameThread("bitcoin-key-top");
pwalletMain->TopUpKeyPool();
}
void ThreadCleanWalletPassphrase(void* parg)
{
// Make this thread recognisable as the wallet relocking thread
RenameThread("bitcoin-lock-wa");
int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000;
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
if (nWalletUnlockTime == 0)
{
nWalletUnlockTime = nMyWakeTime;
do
{
if (nWalletUnlockTime==0)
break;
int64 nToSleep = nWalletUnlockTime - GetTimeMillis();
if (nToSleep <= 0)
break;
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
Sleep(nToSleep);
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
} while(1);
if (nWalletUnlockTime)
{
nWalletUnlockTime = 0;
pwalletMain->Lock();
}
}
else
{
if (nWalletUnlockTime < nMyWakeTime)
nWalletUnlockTime = nMyWakeTime;
}
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
delete (int64*)parg;
}
Value walletpassphrase(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
if (!pwalletMain->IsLocked())
throw JSONRPCError(-17, "Error: Wallet is already unlocked.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() > 0)
{
if (!pwalletMain->Unlock(strWalletPass))
throw JSONRPCError(-14, "Error: The wallet passphrase entered was incorrect.");
}
else
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
CreateThread(ThreadTopUpKeyPool, NULL);
int64* pnSleepTime = new int64(params[1].get_int64());
CreateThread(ThreadCleanWalletPassphrase, pnSleepTime);
return Value::null;
}
Value walletpassphrasechange(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(-14, "Error: The wallet passphrase entered was incorrect.");
return Value::null;
}
Value walletlock(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"Removes the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return Value::null;
}
Value encryptwallet(const Array& params, bool fHelp)
{
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(-15, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(-16, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; eagle_cur server stopping, restart to run with encrypted wallet";
}
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey.Raw())));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <eagle_cur address>\n"
"Return information about <eagle_cur address>.");
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = IsMine(*pwalletMain, dest);
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
}
return ret;
}
Value getworkex(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getworkex [data, coinbase]\n"
"If [data, coinbase] is not specified, returns extended work data.\n"
);
if (vNodes.empty())
throw JSONRPCError(-9, "eagle_cur server is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "eagle_cur server is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock;
static vector<CBlock*> vNewBlock;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
nTransactionsUpdatedLast = nTransactionsUpdated;
pindexPrev = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(reservekey);
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
vNewBlock.push_back(pblock);
}
// Update nTime
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Prebuild hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
CTransaction coinbaseTx = pblock->vtx[0];
std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
Object result;
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << coinbaseTx;
result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
Array merkle_arr;
printf("DEBUG: merkle size %i\n", merkle.size());
BOOST_FOREACH(uint256 merkleh, merkle) {
printf("%s\n", merkleh.ToString().c_str());
merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
}
result.push_back(Pair("merkle", merkle_arr));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
vector<unsigned char> coinbase;
if(params.size() == 2)
coinbase = ParseHex(params[1].get_str());
if (vchData.size() != 128)
throw JSONRPCError(-8, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
if(coinbase.size() == 0)
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
else
CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(-9, "eagle_cur server is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "eagle_cur server is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlock*> vNewBlock;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
nTransactionsUpdatedLast = nTransactionsUpdated;
pindexPrev = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(reservekey);
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
vNewBlock.push_back(pblock);
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Prebuild hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
result.push_back(Pair("algorithm", "scrypt:1024,1,1")); // specify that we should use the scrypt algorithm
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(-8, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getblocktemplate(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblocktemplate [params]\n"
"If [params] does not contain a \"data\" key, returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
" \"previousblockhash\" : hash of current highest block\n"
" \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
" \"coinbaseaux\" : data that should be included in coinbase\n"
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
" \"target\" : hash target\n"
" \"mintime\" : minimum timestamp appropriate for next block\n"
" \"curtime\" : current timestamp\n"
" \"mutable\" : list of ways the block template may be changed\n"
" \"noncerange\" : range of valid nonces\n"
" \"sigoplimit\" : limit of sigops in blocks\n"
" \"sizelimit\" : limit of block size\n"
" \"bits\" : compressed target of next block\n"
" \"height\" : height of the next block\n"
"If [params] does contain a \"data\" key, tries to solve the block and returns null if it was successful (and \"rejected\" if not)\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
const Object& oparam = params[0].get_obj();
std::string strMode;
{
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
strMode = modeval.get_str();
else
if (find_value(oparam, "data").type() == null_type)
strMode = "template";
else
strMode = "submit";
}
if (strMode == "template")
{
if (vNodes.empty())
throw JSONRPCError(-9, "eagle_cur server is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "eagle_cur server is downloading blocks...");
static CReserveKey reservekey(pwalletMain);
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
{
nTransactionsUpdatedLast = nTransactionsUpdated;
pindexPrev = pindexBest;
nStart = GetTime();
// Create new block
if(pblock)
delete pblock;
pblock = CreateNewBlock(reservekey);
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
int i = 0;
CTxDB txdb("r");
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
{
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase())
continue;
Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
Array deps;
BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
{
if (setTxIndex.count(inp.first))
deps.push_back(setTxIndex[inp.first]);
}
entry.push_back(Pair("depends", deps));
int64_t nSigOps = tx.GetLegacySigOpCount();
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
entry.push_back(Pair("sigops", nSigOps));
}
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
if (aMutable.empty())
{
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", HexBits(pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
return result;
}
else
if (strMode == "submit")
{
// Parse parameters
CDataStream ssBlock(ParseHex(find_value(oparam, "data").get_str()), SER_NETWORK, PROTOCOL_VERSION);
CBlock pblock;
ssBlock >> pblock;
bool fAccepted = ProcessBlock(NULL, &pblock);
return fAccepted ? Value::null : "rejected";
}
throw JSONRPCError(-8, "Invalid mode");
}
Value getrawmempool(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getrawmempool\n"
"Returns all transaction ids in memory pool.");
vector<uint256> vtxid;
mempool.queryHashes(vtxid);
Array a;
BOOST_FOREACH(const uint256& hash, vtxid)
a.push_back(hash.ToString());
return a;
}
Value getblockhash(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblockhash <index>\n"
"Returns hash of block in best-block-chain at <index>.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
return pblockindex->phashBlock->GetHex();
}
Value getblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblock <hash>\n"
"Returns details of a block with given block-hash.");
std::string strHash = params[0].get_str();
uint256 hash(strHash);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(-5, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex, true);
return blockToJSON(block, pblockindex);
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name function safe mode?
// ------------------------ ----------------------- ----------
{ "help", &help, true },
{ "stop", &stop, true },
{ "getblockcount", &getblockcount, true },
{ "getconnectioncount", &getconnectioncount, true },
{ "getpeerinfo", &getpeerinfo, true },
{ "getdifficulty", &getdifficulty, true },
{ "getnetworkhashps", &getnetworkhashps, true },
{ "getgenerate", &getgenerate, true },
{ "setgenerate", &setgenerate, true },
{ "gethashespersec", &gethashespersec, true },
{ "getinfo", &getinfo, true },
{ "getmininginfo", &getmininginfo, true },
{ "getnewaddress", &getnewaddress, true },
{ "getaccountaddress", &getaccountaddress, true },
{ "setaccount", &setaccount, true },
{ "getaccount", &getaccount, false },
{ "getaddressesbyaccount", &getaddressesbyaccount, true },
{ "sendtoaddress", &sendtoaddress, false },
{ "getreceivedbyaddress", &getreceivedbyaddress, false },
{ "getreceivedbyaccount", &getreceivedbyaccount, false },
{ "listreceivedbyaddress", &listreceivedbyaddress, false },
{ "listreceivedbyaccount", &listreceivedbyaccount, false },
{ "backupwallet", &backupwallet, true },
{ "keypoolrefill", &keypoolrefill, true },
{ "walletpassphrase", &walletpassphrase, true },
{ "walletpassphrasechange", &walletpassphrasechange, false },
{ "walletlock", &walletlock, true },
{ "encryptwallet", &encryptwallet, false },
{ "validateaddress", &validateaddress, true },
{ "getbalance", &getbalance, false },
{ "move", &movecmd, false },
{ "sendfrom", &sendfrom, false },
{ "sendmany", &sendmany, false },
{ "addmultisigaddress", &addmultisigaddress, false },
{ "getrawmempool", &getrawmempool, true },
{ "getblock", &getblock, false },
{ "getblockhash", &getblockhash, false },
{ "gettransaction", &gettransaction, false },
{ "listtransactions", &listtransactions, false },
{ "signmessage", &signmessage, false },
{ "verifymessage", &verifymessage, false },
{ "getwork", &getwork, true },
{ "getworkex", &getworkex, true },
{ "listaccounts", &listaccounts, false },
{ "settxfee", &settxfee, false },
{ "setmininput", &setmininput, false },
{ "getblocktemplate", &getblocktemplate, true },
{ "listsinceblock", &listsinceblock, false },
{ "dumpprivkey", &dumpprivkey, false },
{ "importprivkey", &importprivkey, false },
{ "listunspent", &listunspent, false },
{ "getrawtransaction", &getrawtransaction, false },
{ "createrawtransaction", &createrawtransaction, false },
{ "decoderawtransaction", &decoderawtransaction, false },
{ "signrawtransaction", &signrawtransaction, false },
{ "sendrawtransaction", &sendrawtransaction, false },
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: eagle_cur-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want posix (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == 401)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: eagle_cur-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == 200) cStatus = "OK";
else if (nStatus == 400) cStatus = "Bad Request";
else if (nStatus == 403) cStatus = "Forbidden";
else if (nStatus == 404) cStatus = "Not Found";
else if (nStatus == 500) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %d\r\n"
"Content-Type: application/json\r\n"
"Server: eagle_cur-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return 500;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
loop
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Read header
int nLen = ReadHTTPHeader(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return 500;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return nStatus;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return strUserPass == strRPCUserColonPass;
}
//
// JSON-RPC protocol. eagle_cur speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = 500;
int code = find_value(objError, "code").get_int();
if (code == -32600) nStatus = 400;
else if (code == -32601) nStatus = 404;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Chech whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ThreadRPCServer(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg));
// Make this thread recognisable as the RPC listener
RenameThread("bitcoin-rpclist");
try
{
vnThreadsRunning[THREAD_RPCLISTENER]++;
ThreadRPCServer2(parg);
vnThreadsRunning[THREAD_RPCLISTENER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_RPCLISTENER]--;
PrintException(&e, "ThreadRPCServer()");
} catch (...) {
vnThreadsRunning[THREAD_RPCLISTENER]--;
PrintException(NULL, "ThreadRPCServer()");
}
printf("ThreadRPCServer exited\n");
}
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
vnThreadsRunning[THREAD_RPCLISTENER]++;
// Immediately start accepting new connections, except when we're canceled or our socket is closed.
if (error != asio::error::operation_aborted
&& acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn
&& !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(403, "", false) << std::flush;
delete conn;
}
// start HTTP client thread
else if (!CreateThread(ThreadRPCServer3, conn)) {
printf("Failed to create RPC server client thread\n");
delete conn;
}
vnThreadsRunning[THREAD_RPCLISTENER]--;
}
void ThreadRPCServer2(void* parg)
{
printf("ThreadRPCServer started\n");
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if (mapArgs["-rpcpassword"] == "")
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use eagle_cur";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n %s\n"
"It is recommended you use the following random password:\n"
"rpcuser=eagle_currpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
_("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
StartShutdown();
return;
}
const bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
if (fUseSSL)
{
context.set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) context.use_certificate_chain_file(pathCertFile.string());
else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 55554));
boost::signals2::signal<void ()> StopRequests;
try
{
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
boost::system::error_code v6_only_error;
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, context, fUseSSL);
// Cancel outstanding listen-requests for this acceptor when shutting down
StopRequests.connect(signals2::slot<void ()>(
static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
.track(acceptor));
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, context, fUseSSL);
// Cancel outstanding listen-requests for this acceptor when shutting down
StopRequests.connect(signals2::slot<void ()>(
static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
.track(acceptor));
}
}
catch(boost::system::system_error &e)
{
uiInterface.ThreadSafeMessageBox(strprintf(_("An error occured while setting up the RPC port %i for listening: %s"), endpoint.port(), e.what()),
_("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
StartShutdown();
return;
}
vnThreadsRunning[THREAD_RPCLISTENER]--;
while (!fShutdown)
io_service.run_one();
vnThreadsRunning[THREAD_RPCLISTENER]++;
StopRequests();
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(-32600, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(-32600, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(-32600, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getblocktemplate")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(-32600, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(-32700, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
static CCriticalSection cs_THREAD_RPCHANDLER;
void ThreadRPCServer3(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer3(parg));
// Make this thread recognisable as the RPC handler
RenameThread("bitcoin-rpchand");
{
LOCK(cs_THREAD_RPCHANDLER);
vnThreadsRunning[THREAD_RPCHANDLER]++;
}
AcceptedConnection *conn = (AcceptedConnection *) parg;
bool fRun = true;
loop {
if (fShutdown || !fRun)
{
conn->close();
delete conn;
{
LOCK(cs_THREAD_RPCHANDLER);
--vnThreadsRunning[THREAD_RPCHANDLER];
}
return;
}
map<string, string> mapHeaders;
string strRequest;
ReadHTTP(conn->stream(), mapHeaders, strRequest);
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(401, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DOS the user really
shouldn't have their RPC port exposed.*/
if (mapArgs["-rpcpassword"].size() < 20)
Sleep(250);
conn->stream() << HTTPReply(401, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(-32700, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(-32700, "Top-level object parse error");
conn->stream() << HTTPReply(200, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(-32700, e.what()), jreq.id);
break;
}
}
delete conn;
{
LOCK(cs_THREAD_RPCHANDLER);
vnThreadsRunning[THREAD_RPCHANDLER]--;
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(-32601, "Method not found");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
!pcmd->okSafeMode)
throw JSONRPCError(-2, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(-1, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "55554")))
throw runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive reply
map<string, string> mapHeaders;
string strReply;
int nStatus = ReadHTTP(stream, mapHeaders, strReply);
if (nStatus == 401)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value)
{
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
value = value2.get_value<T>();
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "setmininput" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2]);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (std::exception& e)
{
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...)
{
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
| [
"myeagleflies@gmail.com"
] | myeagleflies@gmail.com |
ba7cc49992dbc4c2b707490a0a218f678893860c | 3e9be13eb25bd08b76fcac79f702e1c689f2e455 | /source/entity/effects/transientEffect.hpp | 5b25fc505cf41ad98e19b9971d23470f8df9afc3 | [
"MIT"
] | permissive | fourks/blind-jump-portable | 02c64c00496387564506bd32fe7471f4ff659d20 | a4a0bbce23c6916ae6ad3ddc5eaff08a42f3a96d | refs/heads/master | 2022-11-19T09:59:17.186597 | 2020-07-08T23:43:59 | 2020-07-08T23:43:59 | 278,217,425 | 0 | 0 | null | 2020-07-08T23:44:32 | 2020-07-08T23:44:31 | null | UTF-8 | C++ | false | false | 550 | hpp | #pragma once
#include "entity/entity.hpp"
#include "graphics/animation.hpp"
class Game;
class Platform;
template <TextureIndex InitialTexture, u32 AnimLen, u32 AnimInterval>
class TransientEffect : public Entity {
public:
TransientEffect()
{
animation_.bind(sprite_);
}
void update(Platform&, Game&, Microseconds dt)
{
if (animation_.advance(sprite_, dt) and animation_.done(sprite_)) {
this->kill();
}
}
private:
Animation<InitialTexture, AnimLen, AnimInterval> animation_;
};
| [
"ebowman@bu.edu"
] | ebowman@bu.edu |
edcf6f858afdb16305754aa0193545a52c6ded2d | d956ffdbe73474a2f2e463623e0ff9fac563f8fe | /Tính toán đơn giản/HERON.cpp | 7c6eeb6a276f4ecd5e4847f8adf1a2fff5069a49 | [] | no_license | NghiaST/VinhDinhCoder | a5c5babe71e1dc742eae42a5940d699947e8aa70 | 7c7f9f428ecb4d4e66ceed617c576f5d0061cd73 | refs/heads/main | 2023-08-19T20:17:41.669372 | 2021-10-26T07:51:07 | 2021-10-26T07:51:07 | 361,578,717 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 210 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
long double a, b, c, res, p;
cin >> a >> b >> c;
p = (a + b + c) / 2;
res = sqrt(p*(p-a)*(p-b)*(p-c));
cout << setprecision(2) << fixed << res;
}
| [
"noreply@github.com"
] | noreply@github.com |
e031211965b3737275720bbc95bf298d4bd874ca | 8c89782663a343f7c3d362573620f79d275a6142 | /src/2000/2455.cpp14.cpp | 33ea728dc2c7a52ffd164e8c42b4f6c3e5383c42 | [
"MIT"
] | permissive | upple/BOJ | 14a8c8e372131b9a50ba7c1e7428ba7e57b4702d | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | refs/heads/master | 2021-06-21T07:17:57.974279 | 2019-06-28T17:56:30 | 2019-06-28T17:56:30 | 128,779,781 | 13 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 253 | cpp | #include <cstdio>
#define max(x, y) ((x)>(y)?(x):(y))
using namespace std;
int main()
{
int t, l, ans=0, left=0;
for (int i = 0; i < 4; i++)
{
scanf("%d %d", &l, &t);
left += t - l;
ans = max(ans, left);
}
printf("%d\n", ans);
return 0;
}
| [
"upple_@naver.com"
] | upple_@naver.com |
f065d65b4a454754fdbd2a2a0e2908584926159c | f03f7d715357e2208f81b609bd39ad56eac695d6 | /src/socket/Handler.cpp | 5ea10127354dac5cb6591a2187c7823f04c49c9a | [] | no_license | Loriot-n/zia | 23157525bdac65c8a8598a3d064c53bb6b6a3058 | df9e290d5c267998e16942100e297664b2b0a10b | refs/heads/master | 2020-04-20T05:55:07.220012 | 2018-02-25T21:53:24 | 2018-02-25T21:53:24 | 168,669,114 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 112 | cpp | #include "socket/Handler.hpp"
namespace zia {
Handler::~Handler() {}
Handler::Handler() : _reactor(0) {}
} | [
"nicolas.loriot@epitech.eu"
] | nicolas.loriot@epitech.eu |
f3dcae880b86d513be53b965de9e57456e041278 | c746f4ff9b5b75d6b7d76d29243d7323254d7dc1 | /Anterminator/GPUAnt/KeyManager.h | 10adbc18cbca5945166c6d3b154345246a832232 | [] | no_license | Ionsto/Anterminator | beb3284acaf83873cc0f43aef525e59fa03bdc45 | 3a65b51128235a515228e47f55393ccbf195dead | refs/heads/master | 2023-09-01T01:46:43.152664 | 2021-10-08T13:38:19 | 2021-10-08T13:38:19 | 275,383,101 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 354 | h | #pragma once
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <utility>
#include <array>
class KeyManager
{
public:
static constexpr int KeyCount = 258;
private:
std::array<bool,KeyCount> State = { false };
std::array<bool,KeyCount> Toggle = { false };
public:
void UpdateState(GLFWwindow* window);
std::pair<bool, bool> GetState(int Key);
};
| [
"sam.sutcliffe2@gmail.com"
] | sam.sutcliffe2@gmail.com |
6671e99f0764ab7114568b253319ec46bc9028f3 | 2cef7b6bb27822ccb7e85d6212ff1684b743055c | /Asm lib project(Cpp, Asm)/C++lib/C++lib/Source.cpp | dade55ef953c68c39e0a2578d9285032295202fc | [] | no_license | DrSzuriad/Project | dbb7f13e85d35e182ce76b2cdabb12e3daa5201e | ae2a466c424fa0279783088bdc045475c555c631 | refs/heads/main | 2023-05-06T10:20:44.254613 | 2021-06-01T19:23:14 | 2021-06-01T19:23:14 | 358,201,007 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 829 | cpp | #include "pch.h" // use stdafx.h in Visual Studio 2017 and earlier
#include <utility>
#include <limits.h>
#include "cpplib.h"
double cppobliczvx(double *tab)
{
return (1 / tab[0]) * (tab[1] * (tab[2] * tab[3] + tab[0] * tab[4]) - (tab[2] * tab[3]));
}
double cppobliczvy(double* tab)
{
return (1 / tab[0]) * tab[4] * (tab[0] * tab[2] + tab[1] * tab[3]) - (tab[1] * tab[3]) / tab[0];
}
double cppobliczsx(double* tab)
{
return (tab[0]/ tab[1]) * tab[2] * (-tab[4] * tab[5] / tab[1] - tab[6]) - (tab[4] * tab[5] * tab[3] / tab[1]) - (tab[0] / tab[1]) * (-tab[4] * tab[5] / tab[1] - tab[6]) + tab[7];
}
double cppobliczsy(double* tab)
{
return tab[3] - ((-(tab[0] + (tab[1] * tab[2]) / tab[4]) * (tab[1] / tab[4]) * tab[5] - tab[6] * tab[1] * tab[2] / tab[4]) + ((tab[1] / tab[4]) * (tab[0] + tab[1] * tab[2] / tab[4])));
}
| [
"darek.kluczewski@gmail.com"
] | darek.kluczewski@gmail.com |
b10d2281465d329e3986421b853269ea66989423 | 2f4a00682618271527e8f38282cbc6f65a0acc85 | /src/DecisionTree.cpp | 8edda90f96eec2e6a7d26a77476cb229a958d06d | [
"FSFAP",
"MIT"
] | permissive | derekrfelson/classifier-demo | 29faad01af69411f14a161af2de78003b8eb9a2c | 3469c8d9a15eff143d84b1585bec5d0cc530b2fa | refs/heads/master | 2021-01-16T22:38:10.402576 | 2016-03-31T00:38:35 | 2016-03-31T00:38:35 | 54,147,617 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,742 | cpp | /*
* DecisionTree.cpp
*
* Created on: Mar 24, 2016
* Author: derek
*/
#include "DecisionTree.h"
#include "Types.h"
#include <cmath>
#include <vector>
#include <algorithm>
#include <cassert>
#include <ostream>
#include <sstream>
#include <iostream>
#include <iomanip>
static std::vector<uint8_t> colToStdVector(const ColVector& col);
static std::vector<uint8_t> rowToStdVector(const RowVector& row);
static std::vector<uint8_t> getUniqueValues(std::vector<uint8_t> vec);
DecisionTree::DecisionTree(const TypeVector& types, const DataMatrix& data)
: nodeCount{0}
{
root = std::make_unique<Node>(types, data, *this);
}
/**
* Initialize a root node on the decision tree.
*/
DecisionTree::Node::Node(const TypeVector& types, const DataMatrix& data,
DecisionTree& dt)
: Node{NoParentAttrValue, nullptr, types, data, 0, dt}
{
}
/**
* Initialize a child node on the decision tree.
*
* Each node on the tree looks at an attribute, the value of which can
* fall into several different classes.
*
* parentAttrValue: Value matched for the parent's distinguishing attribute
*/
DecisionTree::Node::Node(size_t parentAttrValue, const Node* parent,
const TypeVector& types, const DataMatrix& data,
size_t attributesChecked, DecisionTree& dt)
: parentAttrValue{parentAttrValue},
parent{parent},
attributesChecked{attributesChecked},
children{},
attributeIndex{NoAttrIndex},
type{NoType},
nodeNumber{dt.nodeCount++},
dataSize{static_cast<size_t>(data.rows())},
dataEntropy{entropy(types)}
{
// Turn this node into a correct leaf node, or make its children
if (dataEntropy == 0)
{
// Case 1: The subset consists of only 1 type. Perfect!
// In an ideal leaf node every data point is of the same type,
// which is the type returned by the classifier.
type = types(0, 0);
}
else
{
// Find the most informative attribute to base the children on.
// Note that this returns NoAttrIndex if none of the attributes
// will help improve the match.
attributeIndex = bestAttribute(types, data);
// If the data still fall into more than one class, but we've already
// checked all the attributes (or if checking the remaining attributes
// won't improve our accuracy), stop and set the type to whatever one
// has the maximum likelihood (count and see what's the most common).
if (attributesChecked >= data.cols() || attributeIndex == NoAttrIndex)
{
// Case 2: We've checked all the attributes
// and we still can't build a perfect classifier
// Return the most likely type
auto uniqueTypes
= getUniqueValues(colToStdVector(types.cast<Decimal>()));
std::vector<size_t> counts(uniqueTypes.size(), 0);
for (auto i = 0; i < uniqueTypes.size(); ++i)
{
for (auto j = 0; j < types.size(); ++j)
{
if (types[j] == uniqueTypes[i])
{
++counts[i];
}
}
}
type = uniqueTypes[*std::max_element(cbegin(counts),
cend(counts))];
}
else
{
// Case 3: We can improve by checking more attributes,
// so generate child nodes.
// We'll need a new child for every unique value in the column
auto uniqueValues = getUniqueValues(colToStdVector(
data.col(attributeIndex)));
// Make the children
for (auto val : uniqueValues)
{
// Calculate how big the data subset will be
auto subsetSize = 0;
for (auto i = 0; i < data.rows(); ++i)
{
if (data(i, attributeIndex) == val)
{
++subsetSize;
}
}
assert(subsetSize > 0);
// Populate the subset with the right rows from the original
DataMatrix subsetData{subsetSize, data.cols()};
TypeVector subsetTypes{subsetSize, 1};
auto insertIndex = 0;
for (auto i = 0; i < data.rows(); ++i)
{
if (data(i, attributeIndex) == val)
{
subsetTypes.row(insertIndex) = types.row(i);
subsetData.row(insertIndex) = data.row(i);
++insertIndex;
}
}
children.emplace_front(val, this, subsetTypes, subsetData,
attributesChecked + 1, dt);
}
}
}
}
/**
* Tells you what class a data point belongs to.
*/
uint8_t DecisionTree::classify(const RowVector& dataPoint) const
{
const auto *node = root.get();
while (node != nullptr)
{
bool foundChild = false;
// Stop if the current node has no children
if (node->children.size() == 0)
{
assert(node->type != NoType);
return node->type;
}
// Advance to the correct child, based on the data point we have
for (const auto& child : node->children)
{
assert(child.parentAttrValue != NoParentAttrValue);
assert(node->attributeIndex != NoAttrIndex);
if (child.parentAttrValue == dataPoint[node->attributeIndex])
{
node = &child;
foundChild = true;
break;
}
}
// If we reach here and there was no correct child, that means
// we are unable to classify the given data point because we
// had nothing like it in the training set.
//
// This actually happens quite a bit if the training set is too
// small or some dimensions have rare values.
if (!foundChild)
{
return NoType;
}
}
// Failed to find a type for unknown reasons. Should never happen.
assert(false);
return NoType; // Just prevents a compiler warning
}
std::ostream& DecisionTree::Node::print(std::ostream& out) const
{
// Limit output in number of decimal places
auto oldflags = out.flags();
auto oldprecision = out.precision();
out << std::fixed << std::setprecision(3);
if (children.size() == 0)
{
out << nodeNumber << " [";
if (dataEntropy > 0)
{
out << "color=\"red\",";
}
out << "label=\"Type " << static_cast<int>(type)
<< " |{ " << dataSize << " | "
<< dataEntropy << "}" << "\"]" << std::endl;
}
else
{
out << nodeNumber << " [label=\"Attr "
<< attributeIndex
<< " |{ " << dataSize << " | "
<< dataEntropy << "}" << "\"]"
<< std::endl;
for (const auto& child : children)
{
out << nodeNumber
<< " -> " << child.nodeNumber
<< " [label=\" =" << static_cast<int>(child.parentAttrValue)
<< "\"]" << std::endl;
child.print(out);
}
}
// Restore old output behaviour
out.flags(oldflags);
out.precision(oldprecision);
return out;
}
std::ostream& DecisionTree::print(std::ostream& out) const
{
out << "digraph DT {" << std::endl
<< " node [shape=record, fontname=\"Arial\"];" << std::endl;
root->print(out);
out << "}" << std::endl;
return out;
}
std::ostream& operator<<(std::ostream& out, const DecisionTree& dt)
{
return dt.print(out);
}
/**
* Calculates the entropy of a dataset by splitting it into two parts
* based on class and seeing what proportion of the data belongs to each.
*/
double entropy(const TypeVector& types)
{
assert(types.rows() > 0);
std::vector<uint8_t> sortedTypes(types.data(),
types.data() + types.rows());
std::sort(begin(sortedTypes), end(sortedTypes));
double ret = 0;
auto currentType = sortedTypes[0];
auto currentTypeMatches = 0;
for (auto type : sortedTypes)
{
if (currentType == type)
{
++currentTypeMatches;
}
else
{
// Every time we see a new class, add the entropy from the last one
auto p = static_cast<double>(currentTypeMatches) / types.rows();
ret -= (p) * log2(p);
currentTypeMatches = 1;
currentType = type;
}
}
// Add the entropy from the final class
auto p = static_cast<double>(currentTypeMatches) / types.rows();
ret -= p * log2(p);
return ret;
}
double entropy(const std::vector<uint8_t>& types)
{
TypeVector tv(types.size());
for (auto i = 0; i < types.size(); ++i)
{
tv[i] = types[i];
}
return entropy(tv);
}
/*
* Calculates how many bits you will save by knowing the value of an attribute.
* It's a measure of how well the given column of your data can predict
* the type.
*/
double gain(const TypeVector& types, const ColVector& dataColumn)
{
assert(types.rows() > 0);
assert(types.rows() == dataColumn.rows());
// Find all the unique values in the column
auto uniqueValues = getUniqueValues(colToStdVector(dataColumn));
// Gain is entropy(types) - something per each unique value
double ret = entropy(types);
for (auto value : uniqueValues)
{
// Select all the data points where that column = that value
std::vector<uint8_t> subsetTypes;
for (auto i = 0; i < dataColumn.rows(); ++i)
{
if (dataColumn[i] == value)
{
subsetTypes.push_back(types[i]);
}
}
assert(subsetTypes.size() > 0);
// Add the entropy gained by knowing that column = that value
ret -= static_cast<double>(subsetTypes.size())/dataColumn.rows()
* entropy(subsetTypes);
}
return ret;
}
/*
* Gives you the 0-based index of the column that maximizes information gain.
*/
size_t bestAttribute(const TypeVector& types, const DataMatrix& data)
{
double maxGain = -999;
size_t ret = 999;
for (auto i = 0; i < data.cols(); ++i)
{
auto colGain = gain(types, data.col(i));
if (colGain > maxGain)
{
ret = i;
maxGain = colGain;
}
}
// If none of the columns improved the entropy, we can't really say
// that there is a best column. Instead of defaulting to attribute 0,
// we return a special value.
if (maxGain == 0)
{
return NoAttrIndex;
}
return ret;
}
std::vector<uint8_t> colToStdVector(const ColVector& col)
{
return std::vector<uint8_t>(col.data(), col.data() + col.rows());
}
std::vector<uint8_t> rowToStdVector(const RowVector& row)
{
return std::vector<uint8_t>(row.data(), row.data() + row.cols());
}
/**
* Utility function to get the unique values from a vector.
*
* Unlike std::unique, data does not have to be in sorted order.
*/
std::vector<uint8_t> getUniqueValues(std::vector<uint8_t> vec)
{
std::sort(begin(vec), end(vec));
vec.erase(std::unique(begin(vec), end(vec)), end(vec));
return vec;
}
| [
"drfelson@gmail.com"
] | drfelson@gmail.com |
96d2076d59e6db1bf58f8c106a14c1376323e548 | ddb3dad3526bd69f5a4ec325694742dd2da53eb4 | /1_PPP 2nd Edition/Chap. 04/4-3.cpp | aceae6d2c33960727ca657837d814041ce692946 | [] | no_license | RapidWorkers/CPP-and-PPP | 026925bda1ffd18e07070797c4fe4813e93d0345 | 1ec0190bf2786781a19cff2fd1ec52f73033a94b | refs/heads/master | 2021-08-07T13:05:31.643097 | 2020-04-22T15:54:05 | 2020-04-22T15:54:05 | 159,464,498 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 865 | cpp | #include "std_lib_facilities.h"
//4장 실습문제 7~11번.
int main(){
double num;
string unit;
double max;
double min;
double sum = 0;
vector<double> v;
while (cin>>num)
{
cin >> unit;
if (unit == "m")
{
v.push_back(num);
}else if (unit == "cm")
{
v.push_back(num/100);
}else if (unit == "in")
{
v.push_back(num*2.54/100);
}else if (unit == "ft")
{
v.push_back(num*12*2.54/100);
}else{
cout << "그런 단위는 모름! \n";
}
}
if(v.size() == 0){
cout << "입력한 값이 없습니다. 종료.\n";
return 0;
}else{
cout << "입력값 : \n";
sort(v);
max = v[v.size()-1];
min = v[0];
for (double x : v){
cout << x << "\n";
sum += x;
}
cout << "최대값 : " << max
<< " 최소값 : " << min
<< " 값의 합 : " << sum
<< " 값의 개수 : " << v.size();
return 0;
}
} | [
"RapidWorkers@users.noreply.github.com"
] | RapidWorkers@users.noreply.github.com |
12ca7c31e044a7c4a4ec8d27c100311a847f4eb3 | 9c97f70931759dd048f644d7392085d208718830 | /motivation/num-accesses-by-videos/gen-data/src/conf.cpp | 5e8f3d5f8b91754bb8cf76f9b9ccef5a016e9a07 | [] | no_license | hobinyoon/cp-mec-170730 | 78c81fab322c9d153e053b4989acae9d787884df | d65c9575d58189cfe8193db5dd310cc6e88988b9 | refs/heads/master | 2021-06-24T20:21:33.912195 | 2017-09-14T21:32:35 | 2017-09-14T21:32:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,523 | cpp | #include <iostream>
#include <boost/regex.hpp>
#include "cons.h"
#include "conf.h"
#include "util.h"
using namespace std;
namespace Conf {
namespace po = boost::program_options;
po::variables_map _vm;
void _ParseArgs(int argc, char* argv[]) {
po::options_description od("Allowed options");
od.add_options()
("in_file", po::value<string>()->default_value(
"~/work/castnet-data/youtube/150812-143151-tweets-5667779-noads-3837612-inusa-551666"), "Input file name")
("out_file", po::value<string>()->default_value(".result/num-accesses-by-videos"), "Output file name")
("help", "show help message")
;
po::positional_options_description pod;
pod.add("in_file", 1);
pod.add("out_file", 1);
po::store(po::command_line_parser(argc, argv).options(od).positional(pod).run(), _vm);
po::notify(_vm);
if (_vm.count("help") > 0) {
// well... this doesn't show boolean as string.
cout << std::boolalpha;
cout << od << "\n";
exit(0);
}
// Print all parameters
Cons::P("Options:");
for (const auto o: _vm) {
Cons::P(boost::format(" %s=%s") % o.first % o.second.as<string>());
}
}
void Init(int argc, char* argv[]) {
_ParseArgs(argc, argv);
}
const string GetFn(const string& k) {
// Use boost::regex. C++11 regex works from 4.9. Ubuntu 14.04 has g++ 4.8.4.
// http://stackoverflow.com/questions/8060025/is-this-c11-regex-error-me-or-the-compiler
return boost::regex_replace(
_vm[k].as<string>()
, boost::regex("~")
, Util::HomeDir());
}
};
| [
"hobinyoon@gmail.com"
] | hobinyoon@gmail.com |
4858b972b4446f3217896e4f2758d6877c2816f6 | 520ece9e54fad8a5da4af7f4911b5b8ddde77a59 | /HDU/HDU 3360 National Treasures(最小点覆盖+奇偶建图).cpp | 0527af567b3427c01880ce7c9837c960dbb392b7 | [] | no_license | yyyeader/ACM | cde945fab00d2842ed663f711d9432522fca5836 | de976cbfc2f9d68c5e8dc208cfc5756cc4b0f589 | refs/heads/master | 2020-05-27T07:02:14.125658 | 2019-05-26T11:20:25 | 2019-05-26T11:20:25 | 188,526,628 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,944 | cpp | #include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
const int N=1e2+5;
vector<int>v[N*N];
int n,m,xN,yN;
int link[N*N],num[N][N],mp[N][N];
bool vis[N*N];
int dir[][2] = {{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,0},{0,1},{1,0},{0,-1}};
bool dfs(int u){
for(int i=0;i<v[u].size();i++){
int t=v[u][i];
if(!vis[t]){
vis[t]=true;
if(link[t]==-1||dfs(link[t])){
link[t]=u;
return true;
}
}
}
return false;
}
int max_match(){
memset(link,-1,sizeof(link));
int ans=0;
for(int i=1;i<=xN;i++){
memset(vis,false,sizeof(vis));
if(dfs(i)) ans++;
}
return ans;
}
bool check(int x,int y){
if(x<=0||y<=0||x>n||y>m||mp[x][y]==-1) return false;
return true;
}
void init(){
xN=yN=0;
for(int i=0;i<=n*m;i++) v[i].clear();
}
int main(){
int cas=0;
while(~scanf("%d%d",&n,&m)&&n&&m){
init();
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if((i+j)%2==0) num[i][j]=++xN;
else num[i][j]=++yN;
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
scanf("%d",&mp[i][j]);
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(mp[i][j]==-1) continue;
for(int k=0;k<12;k++){
if(mp[i][j]&(1<<k)){
int x=i+dir[k][0];
int y=j+dir[k][1];
if(!check(x,y)) continue;
if((i+j)%2==0) v[num[i][j]].push_back(num[x][y]);
else v[num[x][y]].push_back(num[i][j]);
}
}
}
}
printf("%d. %d\n",++cas,max_match());
}
return 0;
}
| [
"964096646@qq.com"
] | 964096646@qq.com |
abfc5228fa5987dfb2289ba3a8b202157d8c4c93 | 93c3b88b2c7d9a5891d861d20c93edf72b6e85f4 | /esp32_texecom.ino | c82ae7017dd7a6208eab9a6dc6b74e9b9f58f60f | [] | no_license | crashza/arduino | def4448ac110ad07a0965ca98e5e684e8ac455fa | 81d2536ccbfd7623b700020d99b35e23a25c3096 | refs/heads/master | 2022-04-19T19:26:13.658716 | 2020-04-11T22:10:49 | 2020-04-11T22:10:49 | 254,174,311 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 18,573 | ino | //
// Texecom ESP WiFi Controller/Reader
// MQTT commands and status
//
// Author Trevor Steyn <trevor@webon.co.za>
//
#include <WiFi.h>
#include <WiFiMulti.h>
#include <PubSubClient.h>
#define LED 2
#define ZONES 32
//Global Vars
// Configs
const char* wifiSsid = "AP_NAME";
const char* wifiPassword = "*************";
const char* mqttServer = "10.0.0.1";
const char* mqttUser = "mqtt_user";
const char* mqttPass = "mqtt_pass";
const int mqttPort = 1883;
IPAddress server(10, 0, 0, 1);
const char alarmPin[5] = "1234";
//Zone Vars
char ZONE_INFO_HEALTH[ZONES]; // Zone health
char C_ZONE_INFO_HEALTH[ZONES]; // Zone health compare for changes
char ZONE_STATUS[ZONES]; // Zone Status Clear or Motion etc
char C_ZONE_STATUS[ZONES]; // Zone Status compare for changes
char ZONE_BYPASS[ZONES]; // Zone Bypass Status
char C_ZONE_BYPASS[ZONES]; // Zone Bypass compare for changes
char ZONE_ABYPASS[ZONES]; // Zone AutBypass Status
char C_ZONE_ABYPASS[ZONES]; // Zone AutBypass Status
char ZONE_ALARMED[ZONES]; // Zone Alarmed
char C_ZONE_ALARMED[ZONES]; // Zone Alarmed
// Alarm Vars
char ALARM_DURESS[4];
char C_ALARM_DURESS[4];
char ALARM_BURGLAR[4];
char C_ALARM_BURGLAR[4];
char ALARM_ARMED[4];
char C_ALARM_ARMED[4];
char ALARM_ALARMED[4];
char C_ALARM_ALARMED[4];
char ALARM_RESET[4];
char C_ALARM_RESET[4];
char ALARM_READY[4];
char C_ALARM_READY[4];
// Alarm Commands
const byte ALARM_DURESS_COMMAND[1][4] = {
{'\\', 'A', 0x01, '/'}
};
const byte ALARM_ARM_AWAY_COMMAND[4][4] = {
{'\\', 'A', 0x01, '/'},
{'\\', 'A', 0x02, '/'},
{'\\', 'A', 0x04, '/'},
{'\\', 'A', 0x08, '/'}
};
const byte ALARM_ARM_STAY_COMMAND[4][4] = {
{'\\', 'Y', 0x01, '/'},
{'\\', 'Y', 0x02, '/'},
{'\\', 'Y', 0x04, '/'},
{'\\', 'Y', 0x08, '/'}
};
const byte ALARM_RESET_COMMAND[4][4] = {
{'\\', 'R', 0x01, '/'},
{'\\', 'R', 0x02, '/'},
{'\\', 'R', 0x04, '/'},
{'\\', 'R', 0x08, '/'}
};
const byte ALARM_DISARM_COMMAND[4][4] = {
{'\\', 'D', 0x01, '/'},
{'\\', 'D', 0x02, '/'},
{'\\', 'D', 0x04, '/'},
{'\\', 'D', 0x08, '/'}
};
// ZONE Commands
const byte ZONE_BYPASS_COMMAND[32][4] = {
{'\\', 'B', 0x01, '/'},
{'\\', 'B', 0x02, '/'},
{'\\', 'B', 0x03, '/'},
{'\\', 'B', 0x04, '/'},
{'\\', 'B', 0x05, '/'},
{'\\', 'B', 0x06, '/'},
{'\\', 'B', 0x07, '/'},
{'\\', 'B', 0x08, '/'},
{'\\', 'B', 0x09, '/'},
{'\\', 'B', 0x0A, '/'},
{'\\', 'B', 0x0B, '/'},
{'\\', 'B', 0x0C, '/'},
{'\\', 'B', 0x0D, '/'},
{'\\', 'B', 0x0E, '/'},
{'\\', 'B', 0x0F, '/'},
{'\\', 'B', 0x10, '/'},
{'\\', 'B', 0x11, '/'},
{'\\', 'B', 0x12, '/'},
{'\\', 'B', 0x13, '/'},
{'\\', 'B', 0x14, '/'},
{'\\', 'B', 0x15, '/'},
{'\\', 'B', 0x16, '/'},
{'\\', 'B', 0x17, '/'},
{'\\', 'B', 0x18, '/'},
{'\\', 'B', 0x19, '/'},
{'\\', 'B', 0x1A, '/'},
{'\\', 'B', 0x1B, '/'},
{'\\', 'B', 0x1C, '/'},
{'\\', 'B', 0x1D, '/'},
{'\\', 'B', 0x1E, '/'},
{'\\', 'B', 0x1F, '/'},
{'\\', 'B', 0x20, '/'}
};
const byte ZONE_UNBYPASS_COMMAND[32][4] = {
{'\\', 'U', 0x01, '/'},
{'\\', 'U', 0x02, '/'},
{'\\', 'U', 0x03, '/'},
{'\\', 'U', 0x04, '/'},
{'\\', 'U', 0x05, '/'},
{'\\', 'U', 0x06, '/'},
{'\\', 'U', 0x07, '/'},
{'\\', 'U', 0x08, '/'},
{'\\', 'U', 0x09, '/'},
{'\\', 'U', 0x0A, '/'},
{'\\', 'U', 0x0B, '/'},
{'\\', 'U', 0x0C, '/'},
{'\\', 'U', 0x0D, '/'},
{'\\', 'U', 0x0E, '/'},
{'\\', 'U', 0x0F, '/'},
{'\\', 'U', 0x10, '/'},
{'\\', 'U', 0x11, '/'},
{'\\', 'U', 0x12, '/'},
{'\\', 'U', 0x13, '/'},
{'\\', 'U', 0x14, '/'},
{'\\', 'U', 0x15, '/'},
{'\\', 'U', 0x16, '/'},
{'\\', 'U', 0x17, '/'},
{'\\', 'U', 0x18, '/'},
{'\\', 'U', 0x19, '/'},
{'\\', 'U', 0x1A, '/'},
{'\\', 'U', 0x1B, '/'},
{'\\', 'U', 0x1C, '/'},
{'\\', 'U', 0x1D, '/'},
{'\\', 'U', 0x1E, '/'},
{'\\', 'U', 0x1F, '/'},
{'\\', 'U', 0x20, '/'}
};
// Timer for pushing all data to mqtt
unsigned long timer;
// Get some modules ready
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
timer = millis(); // initialise timer
pinMode(LED, OUTPUT); // LED pin as output.
digitalWrite(LED, HIGH);
delay(2000);
digitalWrite(LED, LOW);
delay(2000);
digitalWrite(LED, HIGH);
//swSer.begin(19200);
Serial.begin(19200,SERIAL_8N1,18,20); // Srial for Debugging
Serial2.begin(19200,SERIAL_8N2); // Initialize the Serial interface
Serial.println("Serial Initialised...");
client.setServer(server, 1883);
client.setCallback(callback);
WiFi.begin(wifiSsid, wifiPassword);
while (WiFi.status() != WL_CONNECTED){
digitalWrite(LED, LOW);
delay(500);
digitalWrite(LED, HIGH);
}
// Wifi Connected
Serial.println("WIFI CONNECTE");
Serial2.write("\\W1234/"); // Gain Access to Alarm Panel
Serial2.readStringUntil('\n'); // Remove the OK from buffer
Serial.println("Setup Loop completed");
}
// HA Send Commands as such
// /home/alarm/set/AA10 AA11 AW01
// Z01B Z01U
void callback(char* topic, byte* payload, unsigned int length) {
char command_sent[length];
strncpy(command_sent, (char*)payload, length);
int INDEX = atoi(command_sent +2) -1; // This is our partition or zone number
if (payload[0] == 'A') { // Alarm Panel Command Recieved
if (payload[1] == 'A') {
// Serial2.write(ALARM_RESET_COMMAND[INDEX], sizeof(ALARM_RESET_COMMAND[INDEX]));
// Serial2.readStringUntil('\n');
if (C_ALARM_RESET[INDEX] == 'Y') {
Serial2.write(ALARM_RESET_COMMAND[INDEX], sizeof(ALARM_RESET_COMMAND[INDEX]));
Serial2.readStringUntil('\n');
}
Serial2.write(ALARM_ARM_AWAY_COMMAND[INDEX], sizeof(ALARM_ARM_AWAY_COMMAND[INDEX]));
Serial2.readStringUntil('\n');
} else if (payload[1] == 'S') {
// Serial2.write(ALARM_RESET_COMMAND[INDEX], sizeof(ALARM_RESET_COMMAND[INDEX]));
// Serial2.readStringUntil('\n');
if (C_ALARM_RESET[INDEX] == 'Y') {
Serial2.write(ALARM_RESET_COMMAND[INDEX], sizeof(ALARM_RESET_COMMAND[INDEX]));
Serial2.readStringUntil('\n');
}
Serial2.write(ALARM_ARM_STAY_COMMAND[INDEX], sizeof(ALARM_ARM_STAY_COMMAND[INDEX]));
Serial2.readStringUntil('\n');
} else if (payload[1] == 'D') {
Serial2.write(ALARM_DISARM_COMMAND[INDEX], sizeof(ALARM_DISARM_COMMAND[INDEX]));
Serial2.readStringUntil('\n');
} else if (payload[1] == 'R') {
Serial2.write(ALARM_RESET_COMMAND[INDEX], sizeof(ALARM_RESET_COMMAND[INDEX]));
Serial2.readStringUntil('\n');
} else if (payload[1] == 'P') {
//TODO GET CODE ETC
}
// Zone Code
}else if (payload[0] == 'Z') {
Serial.println("Zone Command Recived");
if (payload[1] == 'B') {
Serial2.write(ZONE_BYPASS_COMMAND[INDEX], sizeof(ZONE_BYPASS_COMMAND[INDEX]));
Serial2.readStringUntil('\n');
}else if (payload[1] == 'U') {
Serial2.write(ZONE_UNBYPASS_COMMAND[INDEX], sizeof(ZONE_UNBYPASS_COMMAND[INDEX]));
Serial2.readStringUntil('\n');
}
}
}
void check_alarm_panel(byte alarm_array[50],int array_size) {
if (array_size != 20){
Serial2.write("\\W1234/"); // Gain Access to Alarm Panel
Serial2.readStringUntil('\n'); // Remove the OK from buffer
Serial.print(array_size);
Serial.println("Does not equal 20 for Alarm Info");
return;
}
// Loop through 4 Partitions
for ( int i = 0 ; i < 4; i++ ) {
// Duress first byte upper nibble
if (bitRead(alarm_array[0], 0 + i) == 1) {
ALARM_DURESS[i] = 'Y';
} else {
ALARM_DURESS[i] = 'N';
}
if (ALARM_DURESS[i] != C_ALARM_DURESS[i]){
C_ALARM_DURESS[i] = ALARM_DURESS[i];
mqttPublish(i + 1, "AD", ALARM_DURESS[i]);
}
// Burglar Alarm
if (bitRead(alarm_array[1], 0 + i) == 1) {
ALARM_BURGLAR[i] = 'Y';
} else {
ALARM_BURGLAR[i] = 'N';
}
if (ALARM_BURGLAR[i] != C_ALARM_BURGLAR[i]){
C_ALARM_BURGLAR[i] = ALARM_BURGLAR[i];
mqttPublish(i + 1, "AB", ALARM_BURGLAR[i]);
}
// Alarm Armed/Armed Away
if (bitRead(alarm_array[8], 4 + i) == 1) {
ALARM_ARMED[i] = 'S'; // Stay Armed
} else if (bitRead(alarm_array[8], 0 + i) == 1) {
ALARM_ARMED[i] = 'A'; // Away Armed
} else {
ALARM_ARMED[i] = 'R'; // Ready
}
if (ALARM_ARMED[i] != C_ALARM_ARMED[i]){
C_ALARM_ARMED[i] = ALARM_ARMED[i];
mqttPublish(i + 1, "AA", ALARM_ARMED[i]);
}
// Confirmed Alarm
if (bitRead(alarm_array[15], 0 + i) == 1) {
ALARM_ALARMED[i] = 'Y';
} else {
ALARM_ALARMED[i] = 'N';
}
if (ALARM_ALARMED[i] != C_ALARM_ALARMED[i]){
C_ALARM_ALARMED[i] = ALARM_ALARMED[i];
mqttPublish(i + 1, "AC", ALARM_ALARMED[i]);
}
// Reset Required
if (bitRead(alarm_array[14], 0 + i) == 1) {
ALARM_RESET[i] = 'Y';
} else {
ALARM_RESET[i] = 'N';
}
if (ALARM_RESET[i] != C_ALARM_RESET[i]){
C_ALARM_RESET[i] = ALARM_RESET[i];
mqttPublish(i + 1, "AR", ALARM_RESET[i]);
}
if (bitRead(alarm_array[9], 0 + i) == 1) {
ALARM_READY[i] = 'Y'; // Alarm Ready
} else {
ALARM_READY[i] = 'N';
}
if (ALARM_READY[i] != C_ALARM_READY[i]){
C_ALARM_READY[i] = ALARM_READY[i];
mqttPublish(i + 1, "AL", ALARM_READY[i]);
}
}
}
void check_zone_info(byte zone_array[50],int array_size) {
if (array_size - 1 != ZONES) {
//Serial.println("Does not matvh zones");
// Data Incorrect Lets reconnect with panel
Serial2.write("\\W1234/"); // Gain Access to Alarm Panel
Serial2.readStringUntil('\n'); // Remove the OK from buffer
return;
}
for ( int i = 0 ; i <= ZONES-1; i++ ) {
// This section checks the health of the Zones
if ((bitRead(zone_array[i], 0) == 0) && (bitRead(zone_array[i], 1) == 0) ){
ZONE_INFO_HEALTH[i] = 'H';
} else if ((bitRead(zone_array[i], 0) == 1) && (bitRead(zone_array[i], 1) == 0) ){
ZONE_INFO_HEALTH[i] = 'A';
} else if ((bitRead(zone_array[i], 0) == 0) && (bitRead(zone_array[i], 1) == 1) ){
ZONE_INFO_HEALTH[i] = 'T';
} else if ((bitRead(zone_array[i], 0) == 1) && (bitRead(zone_array[i], 1) == 1) ){
ZONE_INFO_HEALTH[i] = 'S';
}
if (ZONE_INFO_HEALTH[i] != C_ZONE_INFO_HEALTH[i] ) {
C_ZONE_INFO_HEALTH[i] = ZONE_INFO_HEALTH[i];
mqttPublish(i + 1, "ZH", ZONE_INFO_HEALTH[i]); // TODO Lets change health to an int to save memory
}
// This section checks each zone for bypass
//if ((bitRead(zone_array[i], 5) == 1) or (bitRead(zone_array[i], 6) == 1)) {
if (bitRead(zone_array[i], 5) == 1) {
ZONE_BYPASS[i] = 'Y';
} else {
ZONE_BYPASS[i] = 'N';
}
if (ZONE_BYPASS[i] != C_ZONE_BYPASS[i]) {
C_ZONE_BYPASS[i] = ZONE_BYPASS[i];
mqttPublish(i + 1, "ZB", ZONE_BYPASS[i]);
}
// This section check each zone for auto bypass
if (bitRead(zone_array[i], 6) == 1) {
ZONE_ABYPASS[i] = 'Y';
} else {
ZONE_ABYPASS[i] = 'N';
}
if (ZONE_ABYPASS[i] != C_ZONE_ABYPASS[i]) {
C_ZONE_ABYPASS[i] = ZONE_ABYPASS[i];
mqttPublish(i + 1, "ZA", ZONE_ABYPASS[i]);
}
// This section checks if zone is alarmed
if (bitRead(zone_array[i], 4) == 1) {
ZONE_ALARMED[i] = 'Y';
} else {
ZONE_ALARMED[i] = 'N';
}
if (ZONE_ALARMED[i] != C_ZONE_ALARMED[i]) {
C_ZONE_ALARMED[i] = ZONE_ALARMED[i];
mqttPublish(i + 1, "ZZ", ZONE_ALARMED[i]);
}
}
}
void mqttPublish( int INDEX, char CMD[2], char STATE) {
int ZONE_GG = INDEX;
char STATUS[2] = {STATE};
STATUS[1] = '\0';
char BASE[] = "/home/alarm/";
char TOPIC[50] = "/home/alarm/";
int LENGTH = sizeof(BASE);
char C_INDEX = INDEX + '0';
String BIGZONES = String(INDEX);
Serial.print("Change Discovered: Command:");
Serial.print(CMD);
Serial.print(" Zone/Partition: ");
Serial.print(INDEX);
Serial.print(" and STATE: ");
Serial.println(STATE);
if (CMD[0] == 'A') {
TOPIC[LENGTH-1] = 'A';
if (CMD[1] == 'D') {
TOPIC[LENGTH] = C_INDEX;
LENGTH = LENGTH + 1;
char bypass[] = "/duress";
int bypass_l = sizeof(bypass);
Serial.println(bypass_l);
int COUNT = LENGTH;
for (int i=0; i < bypass_l; i++) {
COUNT = LENGTH + i;
TOPIC[COUNT] = bypass[i];
}
client.publish(TOPIC,STATUS,true);
return;
} else if (CMD[1] == 'B') {
TOPIC[LENGTH] = C_INDEX;
LENGTH = LENGTH + 1;
char bypass[] = "/burglar";
int bypass_l = sizeof(bypass);
Serial.println(bypass_l);
int COUNT = LENGTH;
for (int i=0; i < bypass_l; i++) {
COUNT = LENGTH + i;
TOPIC[COUNT] = bypass[i];
}
client.publish(TOPIC,STATUS,true);
return;
} else if (CMD[1] == 'L') {
TOPIC[LENGTH] = C_INDEX;
LENGTH = LENGTH + 1;
char topic[] = "/ready";
int topic_l = sizeof(topic);
int COUNT = LENGTH;
for (int i=0; i < topic_l; i++) {
COUNT = LENGTH + i;
TOPIC[COUNT] = topic[i];
}
client.publish(TOPIC,STATUS,true);
return;
} else if (CMD[1] == 'A') {
TOPIC[LENGTH] = C_INDEX;
LENGTH = LENGTH + 1;
//char bypass[] = "/burglar";
//int bypass_l = sizeof(bypass);
//Serial.println(bypass_l);
//int COUNT = LENGTH;
//for (int i=0; i < bypass_l; i++) {
// COUNT = LENGTH + i;
// TOPIC[COUNT] = bypass[i];
//}
if ( STATUS[0] == 'A' ) {
client.publish(TOPIC,"armed_away",true);
} else if ( STATUS[0] == 'S' ) {
client.publish(TOPIC,"armed_home",true);
} else if ( STATUS[0] == 'R' ) {
client.publish(TOPIC,"disarmed",true);
}
return;
}
}else if (CMD[0] == 'Z') {
//Set Topic
Serial.println("Getting into the zone hahaha");
TOPIC[LENGTH-1] = 'Z';
TOPIC[LENGTH] = BIGZONES[0];
LENGTH = LENGTH + 1;
if (INDEX > 9) {
TOPIC[LENGTH] = BIGZONES[1];
LENGTH = LENGTH + 1;
}
Serial.println("Zone Update will be sent");
if (CMD[1] == 'B') {
// TOPIC[LENGTH] = C_INDEX;
// LENGTH = LENGTH + 1;
char bypass[] = "/bypass";
int bypass_l = sizeof(bypass);
Serial.println(bypass_l);
int COUNT = LENGTH;
for (int i=0; i < bypass_l; i++) {
COUNT = LENGTH + i;
TOPIC[COUNT] = bypass[i];
}
client.publish(TOPIC,STATUS,true);
return;
} else if (CMD[1] == 'A') {
// TOPIC[LENGTH] = C_INDEX;
// LENGTH = LENGTH + 1;
char bypass[] = "/abypass";
int bypass_l = sizeof(bypass);
//Serial.println(bypass_l);
int COUNT = LENGTH;
for (int i=0; i < bypass_l; i++) {
COUNT = LENGTH + i;
TOPIC[COUNT] = bypass[i];
}
client.publish(TOPIC,STATUS,true);
return;
} else if (CMD[1] == 'H') {
// TOPIC[LENGTH] = C_INDEX;
// LENGTH = LENGTH + 1;
char bypass[] = "/health";
int bypass_l = sizeof(bypass);
//Serial.println(bypass_l);
int COUNT = LENGTH;
for (int i=0; i < bypass_l; i++) {
COUNT = LENGTH + i;
TOPIC[COUNT] = bypass[i];
}
client.publish(TOPIC,STATUS,true);
return;
} else if (CMD[1] == 'Z') {
// TOPIC[LENGTH] = C_INDEX;
// LENGTH = LENGTH + 1;
char bypass[] = "/alarmed";
int bypass_l = sizeof(bypass);
//Serial.println(bypass_l);
int COUNT = LENGTH;
for (int i=0; i < bypass_l; i++) {
COUNT = LENGTH + i;
TOPIC[COUNT] = bypass[i];
}
client.publish(TOPIC,STATUS,true);
return;
}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266TexecomClient-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect("texecom-alarm",mqttUser,mqttPass)) {
//if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("/home/alarm", "hello world");
// ... and resubscribe
client.subscribe("/home/alarm/set");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
// the loop function runs over and over again forever
void loop() {
if (WiFi.status() == WL_CONNECTED) {
// Reconnect to Mqtt if not connected
if (!client.connected()) {
reconnect();
}
digitalWrite(LED, LOW);
client.loop();
digitalWrite(LED, HIGH);
// Resend all data every 5 minutes
if (millis() - timer >= 300000) {
memset(C_ZONE_INFO_HEALTH,'$', strlen(C_ZONE_INFO_HEALTH));
memset(C_ZONE_STATUS,'$', strlen(C_ZONE_STATUS));
memset(C_ZONE_BYPASS,'$', strlen(C_ZONE_BYPASS));
memset(C_ZONE_ALARMED,'$', strlen(C_ZONE_ALARMED));
memset(C_ALARM_DURESS,'$', strlen(C_ALARM_DURESS));
memset(C_ALARM_BURGLAR,'$', strlen(C_ALARM_BURGLAR));
memset(C_ALARM_ARMED,'$', strlen(C_ALARM_ARMED));
memset(C_ALARM_ALARMED,'$', strlen(C_ALARM_ALARMED));
memset(C_ALARM_RESET,'$', strlen(C_ALARM_RESET));
memset(C_ALARM_READY,'$', strlen(C_ALARM_READY));
timer = millis();
}
// Get Zone status
Serial2.write("\\Z");
Serial2.write(0x00);
Serial2.write(0x20);
Serial2.write("/");
byte zone_binary[50];
int ZoneSize = Serial2.readBytesUntil('\n',zone_binary, 50);
check_zone_info(zone_binary,ZoneSize);
client.loop();
// Check Alarm Status
Serial2.write("\\P");
Serial2.write(0x00);
Serial2.write(0x13);
Serial2.write("/");
byte alarm_binary[50];
int AlarmSize = Serial2.readBytesUntil('\n',alarm_binary, 50);
check_alarm_panel(alarm_binary, AlarmSize);
// mqtt get commands etc
} else {
Serial.println("Wifi Failed");
}
}
| [
"noreply@github.com"
] | noreply@github.com |
869d4c9cb79fdb98fafca56b9e5d43a86d4682e0 | 4c4a17ddb659849c0e46df83ef910cc5e74a6afd | /src/marnav/nmea/gtd.hpp | af7c028f40ccac4831a612490f95aa9107dd11c2 | [
"BSD-3-Clause",
"BSD-4-Clause"
] | permissive | Kasetkin/marnav | 39e8754d8c0223b4c99df0799b5d259024d240c8 | 7cb912387d6f66dc3e9201c2f4cdabed86f08e16 | refs/heads/master | 2021-01-23T05:03:51.172254 | 2017-03-19T23:08:16 | 2017-03-19T23:08:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,232 | hpp | #ifndef MARNAV__NMEA__GTD__HPP
#define MARNAV__NMEA__GTD__HPP
#include <array>
#include <marnav/nmea/sentence.hpp>
#include <marnav/utils/optional.hpp>
namespace marnav
{
namespace nmea
{
/// @brief GTD - Geographic Location in Time Differences
///
/// @code
/// 1 2 3 4 5
/// | | | | |
/// $--GTD,x.x,x.x,x.x,x.x,x.x*hh<CR><LF>
/// @endcode
///
/// Field Number:
/// 1. time difference
/// 2. time difference
/// 3. time difference
/// 4. time difference
/// 5. time difference
///
class gtd : public sentence
{
friend class detail::factory;
public:
constexpr static const sentence_id ID = sentence_id::GTD;
constexpr static const char * TAG = "GTD";
constexpr static const int max_time_diffs = 5;
gtd();
gtd(const gtd &) = default;
gtd & operator=(const gtd &) = default;
gtd(gtd &&) = default;
gtd & operator=(gtd &&) = default;
protected:
gtd(talker talk, fields::const_iterator first, fields::const_iterator last);
virtual void append_data_to(std::string &) const override;
private:
std::array<double, max_time_diffs> time_diffs;
void check_index(int index) const;
public:
double get_time_diff(int index) const;
void set_time_diff(int index, double value);
};
}
}
#endif
| [
"mario.konrad@gmx.net"
] | mario.konrad@gmx.net |
f5ddfb1eb3169e5265b5fb6aac1e9f66b7e35e94 | ce8b793fe89321e1045980a803d0e6d9e3388c9f | /Week_09/387.first-unique-character-in-a-string/Solution.cpp | 2344416d5e37dd941670ac6c517d82819b558b5c | [] | no_license | HaigCode/algorithm021 | 8d6415d37633ea6ae82536e9c62d9795b2f90404 | 71c639a2d1dbf82a9804a91976899ea9369b9d7b | refs/heads/main | 2023-02-26T04:53:15.181246 | 2021-01-31T15:55:27 | 2021-01-31T15:55:27 | 316,988,813 | 0 | 0 | null | 2020-11-29T16:03:47 | 2020-11-29T16:03:46 | null | UTF-8 | C++ | false | false | 379 | cpp | //
// Created by HaigCode.
//
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<int, int> frequency;
for (char ch: s) {
++frequency[ch];
}
for (int i = 0; i < s.size(); ++i) {
if (frequency[s[i]] == 1) {
return i;
}
}
return -1;
}
}; | [
"haigcode@163.com"
] | haigcode@163.com |
a1e59f82bd9046359ec4fcec7666640705ba4de4 | 26384ca5e851843c6b071d6e54a9303e3e303fe5 | /LAB/LAB 6/EJERCICIO 6.cpp | ac7a739ce549591bd89ecafb8a1d02af3a6ea691 | [] | no_license | F70443969/portafolio00022319 | 6a599afe196f61af1a1807a8e36601c0b5de3fff | d4a5ae2e8a5f417c0cfa96172821e8d201f62617 | refs/heads/master | 2020-07-08T23:28:36.073253 | 2019-11-20T01:17:44 | 2019-11-20T01:17:44 | 203,810,520 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,922 | cpp | #include <iostream>
using namespace std;
struct nodo{
int info;
struct nodo *izq;
struct nodo *der;
};
typedef struct nodo Nodo;
typedef struct nodo *Arbol;
struct Lista{
int info;
struct Lista *sig;
};
typedef struct Lista lista;
lista *pInicio;
Arbol crearArbol(int x){
Arbol p = new Nodo;
p->info = x;
p->izq = NULL;
p->der = NULL;
return p;
}
void asignarIzq(Arbol a, int unDato){
if(a == NULL)
cout << "Error: arbol vacio" << endl;
else if(a->izq != NULL)
cout << "Error: subarbol IZQ ya existe" << endl;
else
a->izq = crearArbol(unDato);
}
void asignarDer(Arbol a, int unDato){
if(a == NULL)
cout << "Error: arbol vacio" << endl;
else if(a->der != NULL)
cout << "Error: subarbol DER ya existe" << endl;
else
a->der = crearArbol(unDato);
}
void agregarNodo(Arbol a, int numero){
Arbol p = a;
while(true){
if(numero == p->info){
cout << "Error: " << numero << " ya existe" << endl;
return;
}
else if(numero < p->info){
if(p->izq == NULL)
break;
else
p = p->izq;
}
else{
if(p->der == NULL)
break;
else
p = p->der;
}
}
if(numero < p->info)
asignarIzq(p, numero);
else
asignarDer(p, numero);
}
void preorden(Arbol a){
if(a != NULL){
cout << " " << a->info;
preorden(a->izq);
preorden(a->der);
}
}
void recorrerArbol(Arbol a){
cout << "Recorrido PRE orden:"; preorden(a); cout << endl;
}
void insertarlista(int num) {
lista *nuevo = new lista;
nuevo->info = num;
nuevo->sig = NULL;
if (pInicio == NULL) {
pInicio = nuevo;
} else {
lista *p = pInicio;
lista *q = NULL;
while (p != NULL) {
q = p;
p = p->sig;
}
q->sig = nuevo;
}
}
int main(){
cout<<"Inicializando lista...\n";
int opcion = 0;
bool continuar = true;
int numero = 0;
do{
cout << "\n\t1) Agregar Numero a la lista\n\t2) Detener ingreso de numeros y crear arbol\n\tOpcion elegida: ";
cin >> opcion;
switch(opcion){
case 1: cout <<"Agregar numero: "; cin >> numero;
insertarlista(numero); break;
case 2: continuar = false; break;
default: cout << "Opcion invalida";
}
}while(continuar);
Arbol arbol = crearArbol(pInicio->info);
lista *p = pInicio->sig;
while(p != NULL){
agregarNodo(arbol, p->info);
p = p->sig;
}
p = pInicio->sig;
lista *q = p->sig;
while(q != NULL && p != NULL){
delete(p);
p = q;
q = q->sig;
}
recorrerArbol(arbol);
return 0;
}
| [
"54407072+F70443969@users.noreply.github.com"
] | 54407072+F70443969@users.noreply.github.com |
a3d473f0b25bd62d682b1f7cb6964383f47f3df6 | b13817ca05df887a2163c83445dba17be701746f | /node_modules/gdal/deps/libgdal/gdal/frmts/pcidsk/sdk/segment/cpcidskapmodel.h | 6f5266b67ed1a73566e54f23dfd560d595d56408 | [
"LicenseRef-scancode-warranty-disclaimer",
"SunPro",
"LicenseRef-scancode-info-zip-2005-02",
"MIT",
"LicenseRef-scancode-public-domain",
"Apache-2.0"
] | permissive | drownedout/datamap | ba7ac3c9942aa24f96ca01b3ac419a555db93ead | 5909603ee8ab4fa33a774297dfe08271f957029f | refs/heads/master | 2020-04-22T12:53:52.013230 | 2015-09-23T18:12:35 | 2015-09-23T18:12:35 | 42,612,774 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,159 | h | /******************************************************************************
*
* Purpose: Declaration of the APMODEL segment.
*
******************************************************************************
* Copyright (c) 2010
* PCI Geomatics, 50 West Wilmot Street, Richmond Hill, Ont, Canada
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#ifndef __INCLUDE_SEGMENT_CPCIDSKAPMODEL_H
#define __INCLUDE_SEGMENT_CPCIDSKAPMODEL_H
#include "pcidsk_airphoto.h"
#include "segment/cpcidsksegment.h"
#include <string>
#include <vector>
namespace PCIDSK {
class CPCIDSKAPModelSegment : virtual public CPCIDSKSegment,
public PCIDSKAPModelSegment
{
public:
CPCIDSKAPModelSegment(PCIDSKFile *file, int segment,
const char *segment_pointer);
~CPCIDSKAPModelSegment();
unsigned int GetWidth(void) const;
unsigned int GetHeight(void) const;
unsigned int GetDownsampleFactor(void) const;
// Interior Orientation Parameters
PCIDSKAPModelIOParams const& GetInteriorOrientationParams(void) const;
// Exterior Orientation Parameters
PCIDSKAPModelEOParams const& GetExteriorOrientationParams(void) const;
// ProjInfo
PCIDSKAPModelMiscParams const& GetAdditionalParams(void) const;
std::string GetMapUnitsString(void) const;
std::string GetUTMUnitsString(void) const;
std::vector<double> const& GetProjParams(void) const;
private:
void UpdateFromDisk();
PCIDSKBuffer buf;
std::string map_units_, utm_units_;
std::vector<double> proj_parms_;
PCIDSKAPModelIOParams* io_params_;
PCIDSKAPModelEOParams* eo_params_;
PCIDSKAPModelMiscParams* misc_params_;
unsigned int width_, height_, downsample_;
bool filled_;
};
} // end namespace PCIDSK
#endif // __INCLUDE_SEGMENT_CPCIDSKAPMODEL_H
| [
"danielcdonnelly@gmail.com"
] | danielcdonnelly@gmail.com |
f19171b1598540ae504075b766fbd2e084ddddd6 | d66c72d9d399a177a0a4b0659dcefddc458e8aca | /vl53l0x/include/VL53L0X.hpp | d1e1b5ebe4980a0538bad6082dc47242b1266032 | [] | no_license | gyroknight/eyeris-mcu | 5b7e582790610b90b97a7c21b9f0432be894661b | e8c44f809969f5642b1dba0886e8041b9cb580b8 | refs/heads/master | 2023-03-31T01:47:46.328880 | 2021-04-09T01:30:16 | 2021-04-09T01:30:16 | 343,229,507 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,658 | hpp | /**
* Most of the functionality of this library is based on the VL53L0X API
*provided by ST (STSW-IMG005) and some of the explanatory comments are quoted
*or paraphrased from the API source code, API user manual (UM2039), and the
*VL53L0X datasheet.
**/
#ifndef _VL53L0X_H
#define _VL53L0X_H
#include <cstdint>
#include <fstream>
#include <mutex>
#include "VL53L0X_defines.hpp"
class VL53L0X {
public:
/*** Constructors and destructors ***/
/**
* \brief Initialize sensor using sequence Based on VL53L0X_DataInit(),
* VL53L0X_StaticInit(), and VL53L0X_PerformRefCalibration().
*
* \param xshutGPIOPin - host's GPIO pin used to toggle sensor on and off.
* Defaults to -1 (unused). \param ioMode2v8 - whether to configure the sensor
* for 2V8 mode (2.8V logic instead of 1.8V). Defaults to true. \param address
* - I2C bus address of the sensor. Defaults to sensor's default address,
* change only if sensor was initialized to another address beforehand.
*
* This function does not perform reference SPAD calibration
* (VL53L0X_PerformRefSpadManagement()), since the API user manual says that
* it is performed by ST on the bare modules; It seems like that should work
* well enough unless a cover glass is added.
*/
VL53L0X(const int16_t xshutGPIOPin = -1, bool ioMode2v8 = true,
const uint8_t address = VL53L0X_ADDRESS_DEFAULT);
/*** Public methods ***/
/**
* \brief Initialize the sensor's hardware and, if needed, GPIO access on the
* host side.
*
* It's not part of the constructor as it can throw errors.
*/
void initialize();
/**
* Power on the sensor by setting its XSHUT pin to high via host's GPIO.
*/
void powerOn();
/**
* Power off the sensor by setting its XSHUT pin to low via host's GPIO.
*/
void powerOff();
/**
* Change sensor's I2C address (sets both the address on the physical sensor
* and within sensor's object).
*/
void setAddress(uint8_t newAddress);
/**
* Get sensor's I2C address as last set.
*/
inline uint8_t getAddress() { return this->address; }
/**
* Set the return signal rate limit check value in units of MCPS (mega counts
* per second).
*
* "This represents the amplitude of the signal reflected from the target and
* detected by the device"; setting this limit presumably determines the
* minimum measurement necessary for the sensor to report a valid reading.
* Setting a lower limit increases the potential range of the sensor but also
* seems to increase the likelihood of getting an inaccurate reading because
* of unwanted reflections from objects other than the intended target.
* Defaults to 0.25 MCPS as initialized by the ST API and this library.
*/
bool setSignalRateLimit(float limitMCPS);
/**
* Get the return signal rate limit check value in MCPS
*/
float getSignalRateLimit();
/**
* Set the measurement timing budget (in microseconds), which is the time
* allowed for one measurement.
*
* The ST API and this library take care of splitting the timing budget among
* the sub-steps in the ranging sequence. A longer timing budget allows for
* more accurate measurements. Increasing the budget by a factor of N
* decreases the range measurement standard deviation by a factor of sqrt(N).
* Defaults to about 33 milliseconds; the minimum is 20 ms.
* Based on VL53L0X_set_measurement_timing_budget_micro_seconds().
*/
bool setMeasurementTimingBudget(uint32_t budgetMicroseconds);
/**
* Get the measurement timing budget (in microseconds)
*
* Based on VL53L0X_get_measurement_timing_budget_micro_seconds()
*/
uint32_t getMeasurementTimingBudget();
/**
* Set the VCSEL (vertical cavity surface emitting laser) pulse period for the
* given period type (pre-range or final range) to the given value (in PCLKs).
*
* Longer periods seem to increase the potential range of the sensor.
* Valid values are (even numbers only): pre: 12 to 18 (initialized default:
* 14), final: 8 to 14 (initialized default: 10). Based on
* VL53L0X_set_vcsel_pulse_period().
*/
bool setVcselPulsePeriod(vl53l0xVcselPeriodType type, uint8_t periodPCLKs);
/**
* Get the VCSEL pulse period in PCLKs for the given period type.
*
* Based on VL53L0X_get_vcsel_pulse_period().
*/
uint8_t getVcselPulsePeriod(vl53l0xVcselPeriodType type);
/**
* Start continuous ranging measurements.
*
* If periodMilliseconds (optional) is 0 or not given, continuous back-to-back
* mode is used (the sensor takes measurements as often as possible);
* Otherwise, continuous timed mode is used, with the given inter-measurement
* period in milliseconds determining how often the sensor takes a
* measurement. Based on VL53L0X_StartMeasurement().
*/
void startContinuous(uint32_t periodMilliseconds = 0);
/**
* Stop continuous measurements.
*
* Based on VL53L0X_StopMeasurement().
*/
void stopContinuous();
/**
* Returns a range reading in millimeters when continuous mode is active.
* Warning: Blocking call!
*
* readRangeSingleMillimeters() also calls this function after starting a
* single-shot range measurement.
*/
uint16_t readRangeContinuousMillimeters();
/**
* Performs a single-shot range measurement and returns the reading in
* millimeters. Warning: Blocking call!
*
* Based on VL53L0X_PerformSingleRangingMeasurement().
*/
uint16_t readRangeSingleMillimeters();
/**
* Set value of timeout for measurements.
* 0 (dafault value) means no time limit for measurements (infinite wait).
*/
inline void setTimeout(uint16_t timeout) { this->ioTimeout = timeout; }
/**
* Get value of timeout for measurements as last set.
*/
inline uint16_t getTimeout() { return this->ioTimeout; }
/**
* Whether a timeout occurred in one of the read functions since the last call
* to timeoutOccurred().
*/
bool timeoutOccurred();
private:
/*** Private fields ***/
uint8_t address;
int16_t xshutGPIOPin;
bool ioMode2v8;
std::string gpioFilename;
std::mutex fileAccessMutex;
bool gpioInitialized;
uint32_t measurementTimingBudgetMicroseconds;
uint64_t timeoutStartMilliseconds;
uint64_t ioTimeout;
bool didTimeout;
// read by init and used when starting measurement; is StopVariable field of
// VL53L0X_DevData_t structure in API
uint8_t stopVariable;
/*** Private methods ***/
void initHardware();
void initGPIO();
/**
* Get reference SPAD (single photon avalanche diode) count and type.
*
* Based on VL53L0X_get_info_from_device(), but only gets reference SPAD count
* and type.
*/
bool getSPADInfo(uint8_t* count, bool* typeIsAperture);
/**
* Get sequence step enables.
*
* Based on VL53L0X_GetSequenceStepEnables().
*/
void getSequenceStepEnables(VL53L0XSequenceStepEnables* enables);
/**
* Get sequence step timeouts.
*
* Based on get_sequence_step_timeout(), but gets all timeouts instead of just
* the requested one, and also stores intermediate values.
*/
void getSequenceStepTimeouts(const VL53L0XSequenceStepEnables* enables,
VL53L0XSequenceStepTimeouts* timeouts);
/**
* Decode sequence step timeout in MCLKs from register value.
*
* Based on VL53L0X_decode_timeout().
* Note: the original function returned a uint32_t, but the return value is
* always stored in a uint16_t.
*/
static uint16_t decodeTimeout(uint16_t registerValue);
/**
* Encode sequence step timeout register value from timeout in MCLKs.
*
* Based on VL53L0X_encode_timeout().
* Note: the original function took a uint16_t, but the argument passed to it
* is always a uint16_t.
*/
static uint16_t encodeTimeout(uint16_t timeoutMCLKs);
/**
* Convert sequence step timeout from MCLKs to microseconds with given VCSEL
* period in PCLKs.
*
* Based on VL53L0X_calc_timeout_us().
*/
static uint32_t timeoutMclksToMicroseconds(uint16_t timeoutPeriodMCLKs,
uint8_t vcselPeriodPCLKs);
/**
* Convert sequence step timeout from microseconds to MCLKs with given VCSEL
* period in PCLKs.
*
* Based on VL53L0X_calc_timeout_mclks().
*/
static uint32_t timeoutMicrosecondsToMclks(uint32_t timeoutPeriodMicroseconds,
uint8_t vcselPeriodPCLKs);
/**
* Based on VL53L0X_perform_single_ref_calibration().
*/
bool performSingleRefCalibration(uint8_t vhvInitByte);
/*** I2C wrapper methods ***/
/**
* Write an 8-bit register.
*/
void writeRegister(uint8_t reg, uint8_t value);
/**
* Write a 16-bit register.
*/
void writeRegister16Bit(uint8_t reg, uint16_t value);
/**
* Write a 32-bit register.
*
* Based on VL53L0X_write_dword from VL53L0X kernel driver.
*/
void writeRegister32Bit(uint8_t reg, uint32_t value);
/**
* Write an arbitrary number of bytes from the given array to the sensor,
* starting at the given register.
*/
void writeRegisterMultiple(uint8_t reg, const uint8_t* source, uint8_t count);
/**
* Read an 8-bit register.
*/
uint8_t readRegister(uint8_t reg);
/**
* Read a 16-bit register.
*/
uint16_t readRegister16Bit(uint8_t reg);
/**
* Read a 32-bit register.
*/
uint32_t readRegister32Bit(uint8_t reg);
/**
* Read an arbitrary number of bytes from the sensor, starting at the given
* register, into the given array.
*/
void readRegisterMultiple(uint8_t reg, uint8_t* destination, uint8_t count);
};
#endif
| [
"gyroknight@users.noreply.github.com"
] | gyroknight@users.noreply.github.com |
896494c3221cca29075a26d297ad45a66efb83dd | ca7b94c3fc51f8db66ab41b32ee0b7a9ebd9c1ab | /wallet/universal_lib/include/CommonLib/FileMisc.h | 2fc349fbc882ef5ab44f99713381df88b006d1cb | [] | no_license | blockspacer/TronWallet | 9235b933b67de92cd06ca917382de8c69f53ce5a | ffc60e550d1aff5f0f6f1153e0fcde212d37bdc6 | refs/heads/master | 2021-09-15T15:17:47.632925 | 2018-06-05T14:28:16 | 2018-06-05T14:28:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,504 | h | // Author: TuotuoXP
#pragma once
#include "../Universal.h"
typedef std::list<WIN32_FIND_DATAW> EnumResultList;
#define ED_FILE 1
#define ED_DIRECTORY 2
namespace Universal
{
namespace FileMisc
{
UNIVERSAL_LIB_API bool IsFileExist(LPCWSTR lpszFile, bool bIncludeDirectory = false/* 是否连目录也算 */);
UNIVERSAL_LIB_API bool IsDirectory(LPCWSTR lpszPath);
UNIVERSAL_LIB_API bool IsPathValid(LPCWSTR lpszPath);
UNIVERSAL_LIB_API bool IsPathWritable(LPCWSTR lpszPath, bool bIsCreateDir = false/* 是否在当前目录创建文件夹 */); // 路径存在的情况下
UNIVERSAL_LIB_API bool CreateDirectory(LPCWSTR lpszDir);
UNIVERSAL_LIB_API bool RemoveDirectory(LPCWSTR lpszDir);
UNIVERSAL_LIB_API void EnumDirectory(LPCWSTR lpszEnumStr, EnumResultList& result, DWORD dwEnumFlag = ED_FILE | ED_DIRECTORY);
UNIVERSAL_LIB_API std::wstring NormalizePath(LPCWSTR lpszPath);
UNIVERSAL_LIB_API std::wstring GetSpecialPath(int nFolder);
UNIVERSAL_LIB_API HICON GetSpecialPathIcon(int nFolder);
UNIVERSAL_LIB_API std::wstring ExtractFileName(LPCWSTR lpszFullPathName);
UNIVERSAL_LIB_API std::wstring GetValidFileName(LPCWSTR lpszFileName);
UNIVERSAL_LIB_API bool GetFileVersion(LPCWSTR lpszFileName, VerInfo &ver);
UNIVERSAL_LIB_API bool GetFileTime(LPCWSTR lpszFileName, LPFILETIME lpCreationTime, LPFILETIME lpLastAccessTime, LPFILETIME lpLastWriteTime);
UNIVERSAL_LIB_API bool SetFileTime(LPCWSTR lpszFileName, LPFILETIME lpCreationTime, LPFILETIME lpLastAccessTime, LPFILETIME lpLastWriteTime);
UNIVERSAL_LIB_API UINT GetInvalidCharPosInTitle(const std::wstring &wstr);
UNIVERSAL_LIB_API LPSTR GetFileContent(LPCWSTR lpszFilePath, DWORD *pdwSize = NULL);
UNIVERSAL_LIB_API bool SetFileContent(LPCWSTR lpszFilePath, const void *lpData, int iSize);
UNIVERSAL_LIB_API std::wstring PathCombine(const wchar_t* pszDir, const wchar_t* pszFile);
UNIVERSAL_LIB_API std::wstring GetFileExtensionName(const std::wstring &strFileName);
UNIVERSAL_LIB_API bool FileBelongsToTypes(const std::wstring &strFileName, const std::vector<std::wstring> &vecTypes);
UNIVERSAL_LIB_API DWORD GetFileSize32(const std::wstring &strFilePath);
/*!
* 判断某目录是否为另一目录的子目录
* 支持传入相对路径, 如果目录自身进行判断, 返回值为 true
*
* \lpszSub 子目录
* \lpszParent 父目录
*
*/
UNIVERSAL_LIB_API bool IsSubFolder(LPCWSTR lpszSub, LPCWSTR lpszParent);
}
}
| [
"abce@live.cn"
] | abce@live.cn |
3623ad7514c0886119f7b84aaf4fa2ac90ed5a4a | f81fc0a836e468f2523b77c440333f6b2ebda014 | /SEGUNDO BIMESTRE/Ichau_Alexander_reloj/DEBER3_PERRO_GUARDIAN.ino | d58d34be9cb155d8d3a81e2068423fefcfd561af | [] | no_license | eichaui/Embebidos | 6bde09cce37ba7e9c03490413b9b8b6ccf75c313 | 28e40348f774337b6ce0227d6acb23240ad7e695 | refs/heads/master | 2023-03-11T15:22:38.512022 | 2023-03-06T15:06:32 | 2023-03-06T15:06:32 | 181,587,996 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,003 | ino | /*
* UNIVERSIDAD TECNICA DEL NORTE
* FICA-CIERCOM
* ALEXANDER ICHAU
* 22-01-2019
Realizar un programa que permita que el conversor análogo digital
configure al perro guardían a 10,20,30 y 40 segundos.
Este proceso se visualiza en una lcd.
*/
#include <MsTimer2.h>
#include <avr/wdt.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(13,12,11,10,9,8);
float conv=0;
int c;
int contador;
int led=6;
void setup() {
// wdt_disable();
Serial.begin(9600);
lcd.begin(16,2);
MsTimer2::set(500,conteo);
MsTimer2::start();
pinMode(led,OUTPUT);
}
void loop() {
lcd.clear();
conv=(analogRead(A0)*50)/1023;
Serial.println("El valor del CAD es:");
delay(600);
Serial.println(conv);
}
void conteo(){
if(conv==10){
contador++;
lcd.setCursor(4,0);
lcd.println("Contador :");
lcd.setCursor(5,1);
lcd.println(contador);
if(contador==10){
wdt_enable(WDTO_15MS);
wdt_reset();
}
}
if(conv==20){
contador++;
lcd.setCursor(4,0);
lcd.println("Contador :");
lcd.setCursor(5,1);
lcd.println(contador);
if(contador==20){
wdt_enable(WDTO_15MS);
wdt_reset();
}
}
if(conv==30){
contador++;
lcd.setCursor(4,0);
lcd.println("Contador :");
lcd.setCursor(5,1);
lcd.println(contador);
if(contador==30){
wdt_enable(WDTO_15MS);
wdt_reset();
} }
if(conv==40){
contador++;
lcd.setCursor(4,0);
lcd.println("Contador :");
lcd.setCursor(5,1);
lcd.println(contador);
if(contador==40){
wdt_enable(WDTO_15MS);
wdt_reset();
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
0a92c47ff1998d2dc006547694c769316e5aaa0a | a719c0f7c58c5662b5928bc9dcdb7873c0b5de4e | /src/HertzBoard.cpp | 09730be44ffe1f1e035b1be4b5033d6280bdb793 | [
"MIT"
] | permissive | m2m-solutions/M2M_Boards | d146940458c0f856f702e42a1d2cc8ddaef385d4 | ea026bab7fd34bc09339a55fdbdedfc5ee1a34c5 | refs/heads/master | 2021-07-17T02:42:24.225642 | 2020-04-17T14:56:45 | 2020-04-17T14:56:45 | 139,007,970 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,537 | cpp | //---------------------------------------------------------------------------------------------
//
// Library for the Mira One radio module.
//
// Copyright 2016-2017, M2M Solutions AB
// Written by Jonny Bergdahl, 2017-05-09
//
// Licensed under the MIT license, see the LICENSE.txt file.
//
//---------------------------------------------------------------------------------------------
//
#ifdef ARDUINO_PP_HERTZ
////////////////////////////////////////////////////////////////////////////////////////////////
//
// Includes
//
#include "HertzBoard.h"
#include "Wire.h"
#include "util/rgbled.h"
#define LM75A_ADDRESS 0x48
#define LM75A_REGISTER_TEMP 0
#define LM75A_INVALID_TEMPERATURE -1000.0f
HertzBoard::HertzBoard()
: watchdog()
{}
void HertzBoard::begin()
{
pinMode(CM_PWRKEY, OUTPUT);
digitalWrite(CM_PWRKEY, HIGH);
pinMode(FLASH_CS, OUTPUT);
digitalWrite(FLASH_CS, HIGH);
pinMode(MIRA_RESET, OUTPUT);
digitalWrite(MIRA_RESET, HIGH);
pinMode(RGB_LED, OUTPUT);
digitalWrite(RGB_LED, HIGH);
pinMode(SD_CS, OUTPUT);
digitalWrite(SD_CS, HIGH);
pinMode(CM_RI, INPUT);
pinMode(CM_STATUS, INPUT);
Wire.begin();
}
const char* HertzBoard::getSerialNumber()
{
return (char *)0x3FF3;
}
const char* HertzBoard::getMqttPassword()
{
return (char *)0x3F8F;
}
const char* HertzBoard::getEncryptionKey()
{
return (char *)0x3FB0;
}
const char* HertzBoard::getHashKey()
{
return (char *)0x3FD1;
}
float HertzBoard::getTemperature()
{
Wire.beginTransmission(LM75A_ADDRESS);
Wire.write(LM75A_REGISTER_TEMP);
uint16_t result = Wire.endTransmission();
if (result != 0)
{
return LM75A_INVALID_TEMPERATURE;
}
result = Wire.requestFrom(LM75A_ADDRESS, (uint8_t)2);
if (result != 2)
{
return -1000;
}
uint16_t response = Wire.read() << 8;
response |= Wire.read();
return response / 256;
}
float HertzBoard::getTemperatureInKelvin()
{
float result = getTemperature();
if (result != LM75A_INVALID_TEMPERATURE)
{
result += 273.15;
}
return result;
}
float HertzBoard::getTemperatureInFarenheit()
{
float result = getTemperature();
if (result != LM75A_INVALID_TEMPERATURE)
{
result = result * 9.0f / 15.0f + 32.0f;
}
return result;
}
uint8_t HertzBoard::getCellularStatus()
{
return !digitalRead(CM_STATUS);
}
void HertzBoard::setLed(uint8_t red, uint8_t green, uint8_t blue)
{
setRgbLed(RGB_LED, red, green, blue, _ledIntensity);
}
void HertzBoard::setLedIntensity(uint8_t percentage)
{
_ledIntensity = percentage;
}
#endif | [
"jonny@bergdahl.it"
] | jonny@bergdahl.it |
9782357e268d299b99a02ee6961bc32802d73442 | cd3833b4f9b39669ad0224a8d2cbea8cb7020d59 | /src/q2557.cpp | a60205427b50657fb3467e7363d9de0230c6ae69 | [] | no_license | nieah914/cpp_algorithm | 1c87fa4adb3a2e80e352cd0c93b5e94c0dc57be0 | a5938a165703af39138aeaebd6159bca10ee0b70 | refs/heads/master | 2020-03-22T06:45:00.559118 | 2018-07-04T02:15:24 | 2018-07-04T02:15:24 | 139,655,076 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 437 | cpp | //============================================================================
// Name : q2557.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl; // prints !!!Hello World!!!
return 0;
}
| [
"nieah@DESKTOP-P94D4VG"
] | nieah@DESKTOP-P94D4VG |
e044e312d3109fc7b9d46f9f9fc4a5632fc39cdb | 546654962a755ad29be937de1ea82a20586a1f2b | /book/basics/building/Car.hpp | 7b3f8d909beee5fe5e5e2ee350453f079187953b | [
"MIT"
] | permissive | luanics/cpp-illustrated | c8424937b0dc39b3d1bd522106b3261b2856dbff | 6049de2119a53d656a63b65d9441e680355ef196 | refs/heads/master | 2020-03-27T09:52:51.366497 | 2019-04-07T22:50:18 | 2019-04-07T22:50:18 | 146,379,846 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | hpp | #pragma once
// Interface
class Car {
public:
int speedInMph() const;
void go();
void stop();
private:
int speedInMph_;
};
| [
"dsmith@inky"
] | dsmith@inky |
82f99dd04e01c3eec031ef63a7b6cbbb45b66a19 | 4bba3838c668dd4846640a2aa9d4b1f717d15306 | /topcoder/template.cpp | 928ea5b168c86e4d6735a6520ad7550819bf27aa | [] | no_license | dnr2/maratona | 0189fa17b99663aeeb14f389b018865791325d04 | 65163739c645802ac38e605e5706551c3cdf302a | refs/heads/master | 2021-01-15T16:29:31.101196 | 2015-11-27T08:21:21 | 2015-11-27T08:21:21 | 12,200,323 | 22 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 407 | cpp | // Paste me into the FileEdit configuration dialog
#include <string>
#include <vector>
using namespace std;
#define DB(x) db(x)
#define FT first
#define SD second
#define PII pair<int,int>
#define MP make_pair
const int maxn = 1000;
int dx[] = {0,1,0,-1};
int dy[] = {-1,0,1,0};
class $CLASSNAME$ {
public:
$RC$ $METHODNAME$( $METHODPARMS$ ) {
}
};
$BEGINCUT$
$TESTCODE$
$DEFAULTMAIN$
$ENDCUT$
| [
"dnr2@cin.ufpe.br"
] | dnr2@cin.ufpe.br |
0eed479e4f45fd11099e03f83e2e30742be88609 | e413e4020617f2645f7f3ed89ec698183c17e919 | /ftkGUI/SelectionUtilities.cpp | fc312c8aa1eb3c30c8d14e7141d125a1d067a46b | [] | no_license | YanXuHappygela/Farsight-latest | 5c349421b75262f89352cc05093c04d3d6dfb9b0 | 021b1766dc69138dcd64a5f834fdb558bc558a27 | refs/heads/master | 2020-04-24T13:28:25.601628 | 2014-09-30T18:51:29 | 2014-09-30T18:51:29 | 24,650,739 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,217 | cpp | #include "SelectionUtilities.h"
vtkSelection * SelectionUtilities::ConvertIDsToVTKSelection(vtkIdTypeArray * vtkIDs)
{
/*!
* create a vtk selection from a vtk id array
*/
vtkSmartPointer<vtkSelectionNode> selectNodeList = vtkSmartPointer<vtkSelectionNode>::New();
selectNodeList->SetSelectionList( vtkIDs );
selectNodeList->SetFieldType( vtkSelectionNode::VERTEX );
selectNodeList->SetContentType( vtkSelectionNode::INDICES );
vtkSelection * TableRowSelection = vtkSelection::New();
TableRowSelection->RemoveAllNodes();
TableRowSelection->AddNode(selectNodeList);
return TableRowSelection;
}
vtkIdTypeArray * SelectionUtilities::ConvertVTKSelectionToIDArray(vtkSelection * inputSelection)
{
/*!
* Convert a vtk selection into vtk id array
*/
vtkSelectionNode* vertices = NULL;
vtkIdTypeArray* vertexList;
if( inputSelection->GetNode(0))
{
if( inputSelection->GetNode(0)->GetFieldType() == vtkSelectionNode::VERTEX)
{
vertices = inputSelection->GetNode(0);
}
}
if( inputSelection->GetNode(1))
{
if( inputSelection->GetNode(1)->GetFieldType() == vtkSelectionNode::VERTEX)
{
vertices = inputSelection->GetNode(1);
}
}
if( vertices != NULL)
{
vertexList = vtkIdTypeArray::SafeDownCast(vertices->GetSelectionList());
}
return vertexList;
}
std::set< vtkIdType > SelectionUtilities::ObjectSelectionToIDSet(std::set<long int> curSel)
{
/*!
* convert objectSelection into form selective
* clustering can use for operations
*/
std::set<long int>::iterator iter = curSel.begin();
std::set< vtkIdType > Selection;
for (; iter != curSel.end(); iter++)
{
vtkIdType id = (vtkIdType) (*iter);
Selection.insert(id);
}
return Selection;
}
void SelectionUtilities::RemoveRowAndReMapTable(vtkIdType key, vtkSmartPointer<vtkTable> modTable, std::map< vtkIdType, vtkIdType> TableIDMap)
{
/*!
* remove a row from table
* rebuild map
*/
std::map< vtkIdType, vtkIdType>::iterator TableIDIter = TableIDMap.find(key);
if (TableIDIter != TableIDMap.end())
{
modTable->RemoveRow((*TableIDIter).second);
}
for (vtkIdType row = 0; row != modTable->GetNumberOfRows(); row++)
{
vtkIdType value = modTable->GetValue(row,0).ToTypeInt64();
TableIDMap[value] = row;
}
} | [
"xy198908@gmail.com"
] | xy198908@gmail.com |
dae1346faa48981884c51a8c5b4c12f4f64fcfd5 | 6d32a95ecf5f9eedeb9b64aa9d2415ae189110a8 | /reshoot/reshoot/Character.h | f6251ef1bd08b33812e78b3061b399e4d3eab0fb | [
"MIT"
] | permissive | ashkeys/reshoot | c9412b1202678840d0de59f23861eaf150d7c656 | acc9f7184de062729c8f65b03e7d5482944d0ffd | refs/heads/master | 2021-01-20T11:35:11.613494 | 2014-11-20T09:39:56 | 2014-11-20T09:39:56 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 860 | h | #ifndef __CHARACTER_H__
#define __CHARACTER_H__
/**
* @file Character.h
* @brief Characterクラスヘッダー
*
* @note 凍結中
*/
// include
#include <string>
#include "DrawObj.h"
// 前方宣言
enum DrawType;
/**
* @brief Characterクラス
*
* プレイヤーや敵などの基本となるクラス
*
*/
class Character : public DrawObj{
typedef DrawObj Base; ///< 基底クラスをtypedef
public:
Character();
~Character();
void Init(const double x, const double y, const char* fileName, DrawType type);
void Input(const int buf);
void Update();
//void Draw();
protected:
virtual void Draw();
private:
//アニメーション用画像クラスへのポインタ
double x, y;
double dx, dy;
//Vector2D dir;
// キャラクターパラメータ
std::string name;
int hp;
double speed;
//所持Weapon
};
#endif | [
"ashkeys1120@gmail.com"
] | ashkeys1120@gmail.com |
7f1de8154db5e44982e03eaf4af69250a621191a | 41fd2e43649ccc2c9cdd6bbcddf159babdf36dba | /compass/regressions/C++/Inheritance 8/test.cpp | c0670dd6020bd27e14285b4e3ac137e54c19b43d | [] | no_license | fredfeng/compass | 84d37183c11692da77b3c8cf7666c15a5b524390 | 3063df1a86e9473bbd62d52e9002743fd7e90c3b | refs/heads/master | 2020-04-10T11:57:17.616921 | 2015-03-10T16:54:21 | 2015-03-10T16:54:21 | 31,969,036 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,326 | cpp |
enum animal_type {
GENERIC_ANIMAL,
SQUIRREL,
RABBIT
};
class Food {
public:
virtual int get_num_calories() = 0;
static bool is_low_calorie_food(Food* f) {return f->get_num_calories() < 30;};
static bool is_high_calorie_food(Food* f) {return f->get_num_calories() >= 30;};
};
class Carrot: public Food
{
public:
Carrot()
{
}
virtual int get_num_calories()
{
return 5;
}
};
class Nut: public Food
{
public:
Nut() {};
virtual int get_num_calories()
{
return 50;
}
};
class Animal
{
protected:
int length;
int weight;
animal_type at;
public:
Animal(int length, int weight): length(length), weight(weight) {};
int get_length() {return length;};
int get_weight() {return weight;};
int get_animal_type() {return at;};
virtual Food* get_favorite_food() =0;
virtual bool is_mammal() = 0;
};
class Rabbit: public Animal
{
Food* favorite_food;
public:
Rabbit(int length, int weight, Food* favorite_food): Animal(length, weight)
{
this->at = RABBIT;
this->favorite_food = favorite_food;
}
virtual Food* get_favorite_food()
{
return favorite_food;
}
virtual bool is_mammal()
{
return true;
}
};
class Squirrel: public Animal
{
Food* favorite_food;
public:
Squirrel(int length, int weight, Food* favorite_food): Animal(length, weight)
{
this->at = SQUIRREL;
this->favorite_food = favorite_food;
}
virtual Food* get_favorite_food()
{
return favorite_food;
}
virtual bool is_mammal()
{
return true;
}
};
void test()
{
Food* c = new Carrot();
Animal* pet1 = new Rabbit(5, 10, c);
static_assert(pet1->get_animal_type() == RABBIT);
static_assert(pet1->get_favorite_food()->get_num_calories() == 5);
static_assert(Food::is_low_calorie_food(pet1->get_favorite_food()));
Food* n = new Nut();
Animal* pet2 = new Squirrel(4, 8, n);
static_assert(Food::is_high_calorie_food(pet2->get_favorite_food()));
int num_pets = 2;
Animal* my_pets[2];
my_pets[0] = pet1;
my_pets[1] = pet2;
static_assert(my_pets[0]->get_animal_type() == RABBIT);
static_assert(my_pets[1]->get_animal_type() == SQUIRREL);
for(int i=0; i<num_pets; i++) {
static_assert(my_pets[i]->is_mammal());
}
} | [
"fengyu8299@gmail.com"
] | fengyu8299@gmail.com |
3a58cd3e67f3a6485a3e01beceb8e4df3d42cc63 | 87daa268a2c2ea9eb2ece3088444fe538706e61a | /lab12/tree/main.cpp | 200244baed7ff2558a355ae724c2e9ed3a180954 | [] | no_license | patryk7891/jimp2 | 659a99437532ac4116324eb1c86cc3a4558db850 | e93c7d224dc2d85d475607c648851aef44dcb54c | refs/heads/master | 2021-01-25T14:22:14.325972 | 2018-06-05T06:36:04 | 2018-06-05T06:36:04 | 123,685,904 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 59 | cpp | //
// Created by mikolaj on 29.05.18.
//
#include "Tree.h" | [
"mikiogarek@gmail.com"
] | mikiogarek@gmail.com |
1b914e5d89541aaeedc1aa438ec831c18ccb4a36 | 92d57a900758d96f9aadbdb9d1a3b9fa6c1a8fa3 | /cpp/process.cpp | 26f69fe9673acc3e27210ad20c35849871b8a3de | [] | no_license | phreeza/planetwars_bot | 055ce6164b0e2aa3cde4e0fb7da51ec0498c5245 | 023f10461445f5d22e86853b5a59341f04d5e42e | refs/heads/master | 2021-03-12T22:19:42.739702 | 2010-11-28T21:39:38 | 2010-11-28T21:39:38 | 1,120,208 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,112 | cpp | /*
* process.cpp
* PlanetWars
*
* Created by Albert Zeyer on 15.09.10.
* code under GPLv3
*
*/
#ifndef _WIN32
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h> // strerror etc
#include <unistd.h> // pipe, fork, etc
#include <errno.h>
#include <signal.h> // kill etc
#include <fcntl.h>
#include <sys/wait.h>
#include <string.h>
#include "process.h"
#include "utils.h"
void Process::run() {
using namespace std;
int pipe_mainToFork[2]; // 0: read from, 1: write to
if(pipe(pipe_mainToFork) != 0) { // error creating pipe
cerr << "Process::run(): cannot create first pipe: " << strerror(errno) << endl;
return;
}
int pipe_forkToMain[2]; // 0: read from, 1: write to
if(pipe(pipe_forkToMain) != 0) { // error creating pipe
cerr << "Process::run(): cannot create second pipe: " << strerror(errno) << endl;
return;
}
pid_t p = fork();
if(p < 0) { // error forking
cerr << "Process::run(): cannot fork: " << strerror(errno) << endl;
return;
}
else if(p == 0) { // fork
// close other ends of pipes
close(pipe_mainToFork[1]);
close(pipe_forkToMain[0]);
// redirect stdin/stdout to our pipes
dup2(pipe_mainToFork[0], STDIN_FILENO);
dup2(pipe_forkToMain[1], STDOUT_FILENO);
// run
std::vector<std::string> paramsS = Tokenize(cmd, " ");
if(paramsS.size() == 0) paramsS.push_back("");
char** params = new char*[paramsS.size() + 1];
for(size_t i = 0; i < paramsS.size(); ++i)
params[i] = (char*)paramsS[i].c_str();
params[paramsS.size()] = NULL;
execvp(params[0], params);
cerr << "ERROR: cannot run '" << cmd << "': " << strerror(errno) << endl;
_exit(0);
}
else { // parent
// close other ends
close(pipe_mainToFork[0]);
close(pipe_forkToMain[1]);
forkId = p;
running = true;
forkInputFd = pipe_mainToFork[1];
forkOutputFd = pipe_forkToMain[0];
// we don't want blocking on the fork output reading
fcntl(forkOutputFd, F_SETFL, O_NONBLOCK);
}
}
void Process::destroy() {
if(running) {
kill(forkId, SIGTERM);
}
}
void Process::waitForExit() {
if(running) {
waitpid(forkId, NULL, 0);
close(forkInputFd);
close(forkOutputFd);
*this = Process(); // reset
}
}
static timeval millisecsToTimeval(size_t ms) {
timeval v;
v.tv_sec = ms / 1000;
v.tv_usec = (ms % 1000) * 1000;
return v;
}
bool Process::readLine(std::string& s, size_t timeout) {
size_t startTime = (size_t)currentTimeMillis();
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(forkOutputFd, &fdset);
while(true) {
char c;
while(read(forkOutputFd, &c, 1) > 0) {
if(c == '\n') {
s = outbuffer;
outbuffer = "";
return true;
}
outbuffer += c;
}
size_t dt = currentTimeMillis() - startTime;
if((size_t)dt > timeout) return false;
timeval t = millisecsToTimeval(timeout - dt);
if(select(FD_SETSIZE, &fdset, NULL, NULL, &t) <= 0) // timeout or error
return false;
}
return false;
}
void Process::flush() {
size_t n = 0;
while(n < inbuffer.size())
n += write(forkInputFd, inbuffer.c_str() + n, inbuffer.size() - n);
inbuffer = "";
}
#endif // not _WIN32
| [
"tom@Thomas-McColgans-MacBook.local"
] | tom@Thomas-McColgans-MacBook.local |
c5c1b92635b90057c466852167f07ccb1bdc93d6 | 8e78505d5f48d9df121c6c32b45bb902c1f6653f | /webserver/Statistics.cpp | 7b8316cee469e92266cc46bc52c6775eb8977f74 | [] | no_license | ariszaf/syspro3 | a9ab0c4fa014f81aa7ae5dce52325c3f80e45abc | 7a9dbe7b8363ac64d05f5e39e372694508da5444 | refs/heads/master | 2020-05-21T09:45:14.900366 | 2019-05-10T14:50:28 | 2019-05-10T14:50:28 | 186,004,528 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,607 | cpp | #include <cstring>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include "Statistics.h"
Statistics::Statistics() : bytes(0), pages(0) {
pthread_mutex_init(&lock, 0);
}
Statistics::~Statistics() {
pthread_mutex_destroy(&lock);
}
// Server up for 10:02:03.45, served 124 pages, 345539 bytes
char* Statistics::convertToString(long int time) {
char* totalRes;
int resultLenght = 130;
totalRes = new char [resultLenght]();
// https://stackoverflow.com/questions/10874048/from-milliseconds-to-hour-minutes-seconds-and-milliseconds
char* chartime;
chartime = (char*) malloc(sizeof time + 1); // https://stackoverflow.com/questions/37042323/c-error-when-allocating-dynamic-memory-for-linked-list-node
sprintf(chartime, "%ld", time);
long int seconds = (time / 1000) % 60;
char* charseconds;
charseconds = (char*) malloc(sizeof seconds + 1); // https://stackoverflow.com/questions/37042323/c-error-when-allocating-dynamic-memory-for-linked-list-node
sprintf(charseconds, "%ld", seconds);
long int minutes = (time / (1000 * 60)) % 60;
char* charminutes;
charminutes = (char*) malloc(sizeof minutes + 1); // https://stackoverflow.com/questions/37042323/c-error-when-allocating-dynamic-memory-for-linked-list-node
sprintf(charminutes, "%ld", minutes);
char* timer = new char [40]();
strcat(timer, charminutes);
strcat(timer, ":");
strcat(timer, charseconds);
strcat(timer, ".");
strcat(timer, chartime);
pthread_mutex_lock(&lock);
char* charbytes;
charbytes = (char*) malloc(sizeof bytes + 1); // https://stackoverflow.com/questions/37042323/c-error-when-allocating-dynamic-memory-for-linked-list-node
sprintf(charbytes, "%ld", bytes);
char* charpages;
charpages = (char*) malloc(sizeof pages + 1); // https://stackoverflow.com/questions/37042323/c-error-when-allocating-dynamic-memory-for-linked-list-node
sprintf(charpages, "%d", pages);
pthread_mutex_unlock(&lock);
//Server up for 02:03.45, served 124 pages, 345539 bytes
strcat(totalRes, "Server up for ");
strcat(totalRes, timer);
strcat(totalRes, ", served ");
strcat(totalRes, charpages);
strcat(totalRes, " pages, ");
strcat(totalRes, charbytes);
strcat(totalRes, " bytes");
return totalRes;
}
void Statistics::setBytes(long int bytes) {
pthread_mutex_lock(&lock);
this->bytes += bytes;
pthread_mutex_unlock(&lock);
}
void Statistics::setPages(int pages) {
pthread_mutex_lock(&lock);
this->pages += 1;
pthread_mutex_unlock(&lock);
}
| [
"sdi1100169@di.uoa.gr"
] | sdi1100169@di.uoa.gr |
d4348a0b2847cf3ab98ce9d44738f0d06f34b85c | 2fa880c8a06d635eb11ccf9e64b77382e3e825fa | /LUCKY47.cpp | 6ae9d7d04a88694d08bd4855fd5fff49e343aa67 | [] | no_license | AtomicOrbital/SPOJ_PTIT | 469e2acf66d4cd8851cc653c0df78f7c5f9d2625 | d80395a87a13b564bfa370bb299e1216b3781a9e | refs/heads/main | 2023-06-06T04:53:27.359301 | 2021-06-21T17:27:03 | 2021-06-21T17:27:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 302 | cpp | #include<iostream>
using namespace std;
long long n,s;
void dfs(long long x,int s4,int s7)
{
if((x>=n)&&(s4==s7)&&((x<s)||(s==0)))s=x;
if(x<n*100)
{
dfs(x*10+4,s4+1,s7);
dfs(x*10+7,s4,s7+1);
}
}
int main()
{
cin>>n;
dfs(0,0,0);
if(n==0)s=47;
cout<<s;
}
| [
"noreply@github.com"
] | noreply@github.com |
e1d845930d741c9e4583420c39a3bceda55140e3 | a4d2162b012b1bae5c5d435bd1ccc1ffd6bf1e41 | /HackerRank/Minimum Loss.cpp | d8993f2ef787a6936ac6e9cc3059f079d6976edb | [] | no_license | Shadat-tonmoy/ACM-Problem-Solution | dedd1f6a9d35c418c008622c310912b498abf875 | cc11267da7f73b45b3cd75719d313cf09e364653 | refs/heads/master | 2022-04-08T17:21:56.984194 | 2020-03-08T05:25:38 | 2020-03-08T05:25:38 | 110,290,215 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 608 | cpp | #include<bits/stdc++.h>
using namespace std;
long long int num[200005];
int main()
{
long long int i,j,k,l,m,n,a,b,c,maxi,pos,mini;
while(cin>>n)
{
map<long long int,long long int> index;
for(i=0; i<n; i++)
{
cin>>num[i];
index[num[i]] = i;
}
mini = 9999999999999999;
sort(num,num+n);
for(i=0; i<n-1; i++)
{
if(index[num[i+1]] < index[num[i]])
{
mini = min(mini,num[i+1]-num[i]);
}
}
cout<<mini<<endl;
}
}
| [
"shadat.tonmoy@gmail.com"
] | shadat.tonmoy@gmail.com |
8505dfc1f5f2f6c7bbd43ae150489887f1cba496 | a99c71bde9b080549d3a1c770ba6401a65b13516 | /work 2017/fingerprint_bluetooth_slave/fingerprint_bluetooth_slave.ino | 47530ecfb029a75d418277003fc7cc8d25ecad1f | [] | no_license | thulfekar/arduino-simple-projects | 6a74028b7a98a3d243af919da79ea13ce989d1e3 | f95e404b7d02bfc0c0002ff12e68cb14b25fb837 | refs/heads/master | 2021-09-03T11:12:53.591408 | 2018-01-08T15:55:41 | 2018-01-08T15:55:41 | 116,693,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,134 | ino | char command ;
#include <LiquidCrystal.h>
LiquidCrystal lcd(19, 18, 17, 16, 15, 14);
void setup() {
// put your setup code here, to run once:
lcd.begin(16, 2);
Serial.begin (9600);
lcd.setCursor(3, 0 );
lcd.print(" WELCOME ");
}
void loop() {
// put your main code here, to run repeatedly:
while (!Serial.available()) { }
command = Serial.read();
Serial.println(command);
switch (command) {
case 'A' :
lcd.setCursor(1, 1 );
lcd.print(" ");
lcd.setCursor(3, 1 );
lcd.print(" MUSTAFA ");
break;
case 'B' :
lcd.setCursor(1, 1 );
lcd.print(" ");
lcd.setCursor(3, 1 );
lcd.print(" MUTHAFAR ");
break;
case 'C' :
lcd.setCursor(1, 1 );
lcd.print(" ");
lcd.setCursor(3, 1 );
lcd.print(" YAZIN ");
break;
case 'D' :
lcd.setCursor(1, 1 );
lcd.print(" ");
lcd.setCursor(1, 1 );
lcd.print("MUSTAFA RAHEEM");
break;
case 'X' :
lcd.setCursor(1, 1 );
lcd.print(" ");
lcd.setCursor(1, 1 );
lcd.print("THULFEKAR");
break;
default:
;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
752ebf8da55f6dedda30f52a0fc5c6514d6e180a | c1b099926e6f1cdad6865d0b2e9d3569d7cbbff3 | /src/AglFragmentShaderPNT.cpp | 9574a7084eb579f10c553417ee57827d0a3559fe | [
"MIT"
] | permissive | philiphubbard/Agl | 6980df43b5d0ce72d65448d582f551c0406791e6 | 7ee5c6911d4cf2199f1ebf56f28d01d3e051e789 | refs/heads/master | 2016-09-06T02:54:18.531275 | 2013-12-10T04:37:03 | 2013-12-10T04:37:03 | 12,683,823 | 1 | 0 | null | 2013-12-10T04:37:03 | 2013-09-08T16:38:04 | C++ | UTF-8 | C++ | false | false | 1,818 | cpp | // Copyright (c) 2013 Philip M. Hubbard
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// http://opensource.org/licenses/MIT
//
// AglFragmentShaderPNT.cpp
//
#include "AglFragmentShaderPNT.h"
namespace Agl
{
FragmentShaderPNT::FragmentShaderPNT(const std::string& code)
: Shader(GL_FRAGMENT_SHADER, code)
{
}
FragmentShaderPNT::~FragmentShaderPNT()
{
}
void FragmentShaderPNT::surfaceAdded(SurfacePNT*)
{
}
void FragmentShaderPNT::postLink()
{
}
void FragmentShaderPNT::postLink(SurfacePNT*)
{
}
void FragmentShaderPNT::preDraw()
{
}
void FragmentShaderPNT::preDraw(SurfacePNT* surface)
{
}
void FragmentShaderPNT::postDraw()
{
}
}
| [
"philip2@Philips-MacBook-Pro.local"
] | philip2@Philips-MacBook-Pro.local |
909600d0b897f956f0c0b0540529dd4ca0223905 | e8b9b8a44705a4b8241d83cfcca89bd9fe0a396c | /Sources/CTRPluginFrameworkImpl/System/EventManager.cpp | 0bd937414fb034d822ccdfd22253fbf092018c7b | [] | no_license | Zetta-D/CTRPluginFramework-Source-Code | f998bb8b05196cbcb92f3eafbe99163625731c58 | 64e5125324cbd1fc3474ff6264fd592a5a0e0232 | refs/heads/master | 2022-12-05T10:47:08.961846 | 2020-08-26T13:14:54 | 2020-08-26T13:14:54 | 287,932,861 | 7 | 2 | null | 2020-08-24T20:11:47 | 2020-08-16T11:45:24 | C++ | UTF-8 | C++ | false | false | 15,706 | cpp | /* This file has been generated by the Hex-Rays decompiler.
Copyright (c) 2007-2017 Hex-Rays <info@hex-rays.com>
Detected compiler: GNU C++
*/
#include <defs.h>
//-------------------------------------------------------------------------
// Function declarations
CTRPluginFramework::EventManager *__fastcall CTRPluginFramework::EventManager::EventManager(CTRPluginFramework::EventManager *this);
int __fastcall std::deque<CTRPluginFramework::Event,std::allocator<CTRPluginFramework::Event>>::_M_push_back_aux<CTRPluginFramework::Event const&>(void **a1, int *a2);
int __fastcall std::deque<CTRPluginFramework::Event,std::allocator<CTRPluginFramework::Event>>::push_back(int a1, int *a2);
int __fastcall CTRPluginFramework::EventManager::PushEvent(CTRPluginFramework::EventManager *this, const Event *a2);
int __fastcall CTRPluginFramework::EventManager::ProcessEvents(CTRPluginFramework::EventManager *this, int a2, __int64 a3);
signed int __fastcall CTRPluginFramework::EventManager::PopEvent(__int64 this, int a2);
signed int __fastcall CTRPluginFramework::EventManager::PollEvent(__int64 this);
signed int __fastcall CTRPluginFramework::EventManager::WaitEvent(__int64 this);
// _DWORD __cdecl operator new(unsigned int); idb
// void *memmove(void *dest, const void *src, size_t n);
// void __noreturn std::__throw_bad_alloc(void); idb
// void __cdecl operator delete(void *); idb
// _DWORD CTRPluginFramework::Controller::Update(CTRPluginFramework::Controller *__hidden this); idb
// int __fastcall CTRPluginFramework::Controller::IsKeyPressed(_DWORD); weak
// int __fastcall CTRPluginFramework::Controller::IsKeyDown(_DWORD); weak
// int __fastcall CTRPluginFramework::Controller::IsKeyReleased(_DWORD); weak
// int __fastcall hidTouchRead(_DWORD); weak
// _DWORD __cdecl CTRPluginFramework::Milliseconds(CTRPluginFramework *__hidden this, int); idb
// _DWORD __cdecl CTRPluginFramework::Sleep(CTRPluginFramework *__hidden this, Time); idb
//-------------------------------------------------------------------------
// Data declarations
char CTRPluginFramework::EventManager::PopEvent(CTRPluginFramework::Event &,bool)::refresh = '\x01'; // weak
char CTRPluginFramework::EventManager::ProcessEvents(void)::isTouching; // weak
int CTRPluginFramework::EventManager::ProcessEvents(void)::firstTouch; // weak
//----- (00000008) --------------------------------------------------------
CTRPluginFramework::EventManager *__fastcall CTRPluginFramework::EventManager::EventManager(CTRPluginFramework::EventManager *this)
{
CTRPluginFramework::EventManager *v1; // r4
int v2; // r0
int v3; // r6
unsigned int v4; // r5
int v5; // r7
int v6; // r0
*(_DWORD *)this = 0;
*((_DWORD *)this + 2) = 0;
*((_DWORD *)this + 3) = 0;
*((_DWORD *)this + 4) = 0;
*((_DWORD *)this + 5) = 0;
*((_DWORD *)this + 6) = 0;
*((_DWORD *)this + 7) = 0;
*((_DWORD *)this + 8) = 0;
*((_DWORD *)this + 9) = 0;
v1 = this;
*((_DWORD *)this + 1) = 8;
v2 = operator new(0x20u);
v3 = v2;
v4 = (unsigned int)(*((_DWORD *)v1 + 1) - 1) >> 1;
v5 = v2 + 4 * v4;
*(_DWORD *)v1 = v2;
v6 = operator new(0x1F8u);
*(_DWORD *)(v3 + 4 * v4) = v6;
*((_DWORD *)v1 + 3) = v6;
*((_DWORD *)v1 + 7) = v6;
*((_DWORD *)v1 + 2) = v6;
*((_DWORD *)v1 + 6) = v6;
*((_DWORD *)v1 + 5) = v5;
*((_DWORD *)v1 + 4) = v6 + 504;
*((_DWORD *)v1 + 9) = v5;
*((_DWORD *)v1 + 8) = v6 + 504;
return v1;
}
//----- (00000098) --------------------------------------------------------
int __fastcall std::deque<CTRPluginFramework::Event,std::allocator<CTRPluginFramework::Event>>::_M_push_back_aux<CTRPluginFramework::Event const&>(void **a1, int *a2)
{
void **v2; // r4
unsigned int v3; // r3
_BYTE *v4; // r2
_BYTE *v5; // r0
int *v6; // r7
void **v7; // r1
int v8; // r6
int v9; // r5
void **v10; // r5
int v11; // r3
size_t v12; // r2
void **v13; // r0
char *v14; // r3
int v15; // r6
char *v16; // r3
_DWORD *v17; // r5
int *v18; // r3
int result; // r0
int v20; // r1
int v21; // r2
_DWORD *v22; // r3
int v23; // r3
signed int v24; // r8
unsigned int v25; // r8
char *v26; // r0
const void *v27; // r1
int v28; // r2
void *v29; // r9
v2 = a1;
v3 = (unsigned int)a1[1];
v4 = a1[9];
v5 = *a1;
v6 = a2;
if ( v3 - ((v4 - v5) >> 2) <= 1 )
{
v7 = (void **)v2[5];
v8 = (v4 - (_BYTE *)v7) >> 2;
v9 = v8 + 2;
if ( v3 <= 2 * (v8 + 2) )
{
if ( v3 )
v24 = v3;
else
v24 = 1;
v25 = v3 + 2 + v24;
if ( v25 > 0x3FFFFFFF )
std::__throw_bad_alloc();
v26 = (char *)operator new(4 * v25);
v27 = v2[5];
v28 = (int)v2[9] + 4;
v29 = v26;
v10 = (void **)&v26[4 * ((v25 - v9) >> 1)];
if ( v27 != (const void *)v28 )
memmove(v10, v27, v28 - (_DWORD)v27);
operator delete(*v2);
*v2 = v29;
v2[1] = (void *)v25;
goto LABEL_6;
}
v10 = (void **)&v5[4 * ((v3 - v9) >> 1)];
v11 = (int)(v4 + 4);
v12 = v4 + 4 - (_BYTE *)v7;
if ( v7 <= v10 )
{
if ( v7 != (void **)v11 )
{
v13 = (void **)((char *)v10 + 4 * (v8 + 1) - v12);
goto LABEL_10;
}
}
else if ( v7 != (void **)v11 )
{
v13 = v10;
LABEL_10:
memmove(v13, v7, v12);
goto LABEL_6;
}
LABEL_6:
v2[5] = v10;
v14 = (char *)*v10;
v15 = v8 + 0x40000000;
v2[3] = *v10;
v2[4] = v14 + 504;
v2[9] = &v10[v15];
v16 = (char *)v10[v15];
v2[7] = v16;
v2[8] = v16 + 504;
}
v17 = v2[9];
v17[1] = operator new(0x1F8u);
v18 = (int *)v2[6];
result = *v6;
v20 = v6[1];
v21 = v6[2];
*v18 = *v6;
v18[1] = v20;
v18[2] = v21;
v22 = v2[9];
v2[9] = v22 + 1;
v23 = v22[1];
v2[7] = (void *)v23;
v2[8] = (void *)(v23 + 504);
v2[6] = (void *)v23;
return result;
}
//----- (000001F8) --------------------------------------------------------
int __fastcall std::deque<CTRPluginFramework::Event,std::allocator<CTRPluginFramework::Event>>::push_back(int a1, int *a2)
{
int *v2; // r12
int v3; // r3
int result; // r0
int v5; // t0
int v6; // r1
int v7; // r2
v2 = *(int **)(a1 + 24);
if ( v2 == (int *)(*(_DWORD *)(a1 + 32) - 12) )
return std::deque<CTRPluginFramework::Event,std::allocator<CTRPluginFramework::Event>>::_M_push_back_aux<CTRPluginFramework::Event const&>(
(void **)a1,
a2);
v3 = a1;
result = *a2;
v5 = (int)(a2 + 1);
v6 = a2[1];
v7 = *(_DWORD *)(v5 + 4);
*v2 = result;
v2[1] = v6;
v2[2] = v7;
*(_DWORD *)(v3 + 24) += 12;
return result;
}
//----- (00000234) --------------------------------------------------------
int __fastcall CTRPluginFramework::EventManager::PushEvent(CTRPluginFramework::EventManager *this, const Event *a2)
{
return std::deque<CTRPluginFramework::Event,std::allocator<CTRPluginFramework::Event>>::push_back(
(int)this,
(int *)a2);
}
//----- (00000240) --------------------------------------------------------
int __fastcall CTRPluginFramework::EventManager::ProcessEvents(CTRPluginFramework::EventManager *this, int a2, __int64 a3)
{
int v3; // r6
CTRPluginFramework::EventManager *v4; // r4
int result; // r0
__int64 v6; // r2
signed int v7; // r1
bool v8; // zf
int v9; // r3
int v10; // r6
int v11; // r5
char v12; // r3
signed int v13; // r7
signed int v14; // r8
_BOOL4 v15; // r6
_BOOL4 v16; // r5
CTRPluginFramework::EventManager *v17; // [sp+0h] [bp-28h]
int v18; // [sp+4h] [bp-24h]
__int64 v19; // [sp+8h] [bp-20h]
v17 = this;
v18 = a2;
v19 = a3;
v3 = 0;
v4 = this;
CTRPluginFramework::Controller::Update(this);
do
{
if ( CTRPluginFramework::Controller::IsKeyPressed(1 << v3) )
{
LOBYTE(v18) = 0;
LODWORD(v19) = 1 << v3;
std::deque<CTRPluginFramework::Event,std::allocator<CTRPluginFramework::Event>>::push_back((int)v4, &v18);
}
if ( CTRPluginFramework::Controller::IsKeyDown(1 << v3) )
{
LOBYTE(v18) = 1;
LODWORD(v19) = 1 << v3;
std::deque<CTRPluginFramework::Event,std::allocator<CTRPluginFramework::Event>>::push_back((int)v4, &v18);
}
if ( CTRPluginFramework::Controller::IsKeyReleased(1 << v3) )
{
LOBYTE(v18) = 2;
LODWORD(v19) = 1 << v3;
std::deque<CTRPluginFramework::Event,std::allocator<CTRPluginFramework::Event>>::push_back((int)v4, &v18);
}
++v3;
}
while ( v3 != 32 );
hidTouchRead(&v17);
result = CTRPluginFramework::Controller::IsKeyDown(0x100000);
if ( result )
{
LODWORD(v6) = (unsigned __int16)v17;
HIDWORD(v6) = HIWORD(v17);
result = (unsigned __int8)CTRPluginFramework::EventManager::ProcessEvents(void)::isTouching;
if ( *((unsigned __int16 *)v4 + 20) != (unsigned __int16)v17
|| *((unsigned __int16 *)v4 + 21) != HIWORD(v17)
|| !CTRPluginFramework::EventManager::ProcessEvents(void)::isTouching )
{
v7 = (signed int)v17;
v8 = CTRPluginFramework::EventManager::ProcessEvents(void)::isTouching == 0;
*((_DWORD *)v4 + 10) = v17;
if ( result )
v7 = 6;
else
LOBYTE(result) = 5;
if ( v8 )
CTRPluginFramework::EventManager::ProcessEvents(void)::firstTouch = v7;
else
LOBYTE(v18) = v7;
if ( v8 )
LOBYTE(v18) = result;
CTRPluginFramework::EventManager::ProcessEvents(void)::isTouching = 1;
v19 = v6;
result = std::deque<CTRPluginFramework::Event,std::allocator<CTRPluginFramework::Event>>::push_back((int)v4, &v18);
*((_DWORD *)v4 + 10) = v17;
}
return result;
}
if ( !CTRPluginFramework::EventManager::ProcessEvents(void)::isTouching )
return result;
LOBYTE(v18) = 7;
v9 = *((unsigned __int16 *)v4 + 20);
CTRPluginFramework::EventManager::ProcessEvents(void)::isTouching = 0;
LODWORD(v19) = v9;
HIDWORD(v19) = *((unsigned __int16 *)v4 + 21);
result = std::deque<CTRPluginFramework::Event,std::allocator<CTRPluginFramework::Event>>::push_back((int)v4, &v18);
v10 = (unsigned __int16)CTRPluginFramework::EventManager::ProcessEvents(void)::firstTouch
- *((unsigned __int16 *)v4 + 20);
v11 = HIWORD(CTRPluginFramework::EventManager::ProcessEvents(void)::firstTouch) - *((unsigned __int16 *)v4 + 21);
LOBYTE(v18) = 8;
if ( abs(v10) <= 50 && abs(v11) <= 50 )
return result;
if ( v10 > 50 )
{
v12 = 2;
LABEL_31:
LOBYTE(v19) = v12;
result = std::deque<CTRPluginFramework::Event,std::allocator<CTRPluginFramework::Event>>::push_back((int)v4, &v18);
goto LABEL_32;
}
if ( (v10 + 50 < 0) ^ __OFADD__(v10, 50) )
{
v12 = 1;
goto LABEL_31;
}
LABEL_32:
if ( (v11 + 50 < 0) ^ __OFADD__(v11, 50) )
{
LOBYTE(v19) = 4;
LABEL_36:
result = std::deque<CTRPluginFramework::Event,std::allocator<CTRPluginFramework::Event>>::push_back((int)v4, &v18);
goto LABEL_37;
}
if ( v11 > 50 )
{
LOBYTE(v19) = 8;
goto LABEL_36;
}
LABEL_37:
if ( (v10 + 50 < 0) ^ __OFADD__(v10, 50) )
v13 = 1;
else
v13 = 0;
if ( (v11 + 50 < 0) ^ __OFADD__(v11, 50) )
v14 = 1;
else
v14 = 0;
if ( v13 & v14 )
{
LOBYTE(v19) = 5;
result = std::deque<CTRPluginFramework::Event,std::allocator<CTRPluginFramework::Event>>::push_back((int)v4, &v18);
}
v15 = v10 > 50;
if ( v14 & v15 )
{
LOBYTE(v19) = 6;
result = std::deque<CTRPluginFramework::Event,std::allocator<CTRPluginFramework::Event>>::push_back((int)v4, &v18);
}
v16 = v11 > 50;
if ( v13 & v16 )
{
LOBYTE(v19) = 9;
result = std::deque<CTRPluginFramework::Event,std::allocator<CTRPluginFramework::Event>>::push_back((int)v4, &v18);
}
if ( v15 && v16 )
{
LOBYTE(v19) = 10;
result = std::deque<CTRPluginFramework::Event,std::allocator<CTRPluginFramework::Event>>::push_back((int)v4, &v18);
}
return result;
}
// 2: using guessed type char CTRPluginFramework::EventManager::ProcessEvents(void)::isTouching;
// 4: using guessed type int CTRPluginFramework::EventManager::ProcessEvents(void)::firstTouch;
// 5F8: using guessed type int __fastcall CTRPluginFramework::Controller::IsKeyPressed(_DWORD);
// 5FC: using guessed type int __fastcall CTRPluginFramework::Controller::IsKeyDown(_DWORD);
// 600: using guessed type int __fastcall CTRPluginFramework::Controller::IsKeyReleased(_DWORD);
// 604: using guessed type int __fastcall hidTouchRead(_DWORD);
//----- (000004DC) --------------------------------------------------------
signed int __fastcall CTRPluginFramework::EventManager::PopEvent(__int64 this, int a2)
{
int v2; // r7
_DWORD *v3; // r6
int v4; // r4
__int64 v5; // r2
int v6; // r1
__int64 v7; // r2
_DWORD *v8; // r3
signed int result; // r0
int v10; // r1
int v11; // r2
int v12; // r3
int v13; // r3
int v14; // r3
__int64 v15; // [sp+0h] [bp-20h]
int v16; // [sp+8h] [bp-18h]
v15 = this;
v16 = a2;
v2 = a2;
LODWORD(v5) = (unsigned __int8)CTRPluginFramework::EventManager::PopEvent(CTRPluginFramework::Event &,bool)::refresh;
v3 = (_DWORD *)HIDWORD(this);
v4 = this;
HIDWORD(this) = *(_DWORD *)(this + 24);
HIDWORD(v5) = *(_DWORD *)(this + 8);
if ( CTRPluginFramework::EventManager::PopEvent(CTRPluginFramework::Event &,bool)::refresh )
{
if ( HIDWORD(this) == HIDWORD(v5) )
{
CTRPluginFramework::EventManager::ProcessEvents((CTRPluginFramework::EventManager *)this, SHIDWORD(this), v5);
if ( v2 )
{
while ( *(_DWORD *)(v4 + 8) == *(_DWORD *)(v4 + 24) )
{
CTRPluginFramework::Milliseconds((CTRPluginFramework *)&v15, 10);
CTRPluginFramework::Sleep((CTRPluginFramework *)v15, HIDWORD(v15));
CTRPluginFramework::EventManager::ProcessEvents((CTRPluginFramework::EventManager *)v4, v6, v7);
}
}
}
}
else if ( HIDWORD(this) == HIDWORD(v5) )
{
CTRPluginFramework::EventManager::PopEvent(CTRPluginFramework::Event &,bool)::refresh = 1;
}
v8 = *(_DWORD **)(v4 + 8);
if ( *(_DWORD **)(v4 + 24) == v8 )
return 0;
v10 = v8[1];
v11 = v8[2];
*v3 = *v8;
v3[1] = v10;
v3[2] = v11;
v12 = *(_DWORD *)(v4 + 8);
if ( v12 == *(_DWORD *)(v4 + 16) - 12 )
{
operator delete(*(void **)(v4 + 12));
v14 = *(_DWORD *)(v4 + 20);
*(_DWORD *)(v4 + 20) = v14 + 4;
v13 = *(_DWORD *)(v14 + 4);
*(_DWORD *)(v4 + 12) = v13;
*(_DWORD *)(v4 + 16) = v13 + 504;
}
else
{
v13 = v12 + 12;
}
*(_DWORD *)(v4 + 8) = v13;
result = 1;
if ( *(_DWORD *)(v4 + 24) == *(_DWORD *)(v4 + 8) )
CTRPluginFramework::EventManager::PopEvent(CTRPluginFramework::Event &,bool)::refresh = 0;
return result;
}
// 1: using guessed type char CTRPluginFramework::EventManager::PopEvent(CTRPluginFramework::Event &,bool)::refresh;
//----- (000005D4) --------------------------------------------------------
signed int __fastcall CTRPluginFramework::EventManager::PollEvent(__int64 this)
{
return CTRPluginFramework::EventManager::PopEvent(this, 0);
}
//----- (000005DC) --------------------------------------------------------
signed int __fastcall CTRPluginFramework::EventManager::WaitEvent(__int64 this)
{
return CTRPluginFramework::EventManager::PopEvent(this, 1);
}
// ALL OK, 8 function(s) have been successfully decompiled
| [
"noreply@github.com"
] | noreply@github.com |
c276e251e385049fe58740af230044e901006f43 | b56afd085c7d90919507fb37d6cb812f268a617a | /include/gf/ColorRamp.h | 6b1e6dbc269648152c093b17b09843ebb88f5a87 | [
"Zlib",
"MIT",
"BSL-1.0"
] | permissive | GamedevFramework/gf | b606cd3a2619115565c05c15610aaeda40bd5a4f | a7bf9d9dfe86a1ecd47c38915a3c0322630dd50f | refs/heads/master | 2023-09-03T20:13:10.972644 | 2023-08-29T06:53:10 | 2023-08-29T06:53:10 | 54,277,592 | 201 | 52 | NOASSERTION | 2023-01-12T16:24:46 | 2016-03-19T17:13:43 | C++ | UTF-8 | C++ | false | false | 3,680 | h | /*
* Gamedev Framework (gf)
* Copyright (C) 2016-2022 Julien Bernard
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef GF_COLOR_RAMP_H
#define GF_COLOR_RAMP_H
#include <cassert>
#include <map>
#include <type_traits>
#include <utility>
#include "Color.h"
#include "CoreApi.h"
#include "Vector.h"
#include "VectorOps.h"
namespace gf {
#ifndef DOXYGEN_SHOULD_SKIP_THIS
inline namespace v1 {
#endif
/**
* @ingroup core_color
* @brief A color ramp
*
* A color ramp (or color gradient) specifies a range of colors that depends
* on a position.
*
* @sa gf::ColorBase, gf::Color4f
*/
template<typename T>
struct ColorRampBase {
static_assert(std::is_floating_point<T>::value, "T must be a floating point type.");
public:
/**
* @brief Check if the color ramp is empty
*
* @return True if the ramp is empty
*/
bool isEmpty() const {
return m_map.empty();
}
/**
* @brief Add a color stop
*
* @param offset The offset of the color
* @param color The color
*/
void addColorStop(T offset, const Color4<T>& color) {
if (isEmpty()) {
m_min = m_max = offset;
} else {
if (offset < m_min) {
m_min = offset;
}
if (offset > m_max) {
m_max = offset;
}
}
m_map.insert(std::make_pair(offset, color));
}
/**
* @brief Compute a color from an offset
*
* @param offset The offset of the wanted color
* @return A color
*/
Color4<T> computeColor(T offset) const {
if (m_map.empty()) {
return ColorBase<T>::White;
}
if (offset < m_min) {
return m_map.begin()->second;
}
if (offset > m_max) {
return m_map.rbegin()->second;
}
auto it = m_map.lower_bound(offset);
assert(it != m_map.end());
T t2 = it->first;
Color4<T> c2 = it->second;
if (it == m_map.begin()) {
return c2;
}
--it;
T t1 = it->first;
Color4<T> c1 = it->second;
return gf::lerp(c1, c2, (offset - t1) / (t2 - t1));
}
private:
T m_min;
T m_max;
std::map<T, Color4<T>> m_map;
};
/**
* @ingroup core_color
* @brief Instantiation of ColoRampBase for `float`
*/
using ColorRampF = ColorRampBase<float>;
/**
* @ingroup core_color
* @brief Instantiation of ColoRampBase for `double`
*/
using ColorRampD = ColorRampBase<double>;
/**
* @ingroup core_color
* @brief Instantiation of ColoRampBase for `float`
*/
using ColorRamp = ColorRampF;
// MSVC does not like extern template
#ifndef _MSC_VER
extern template struct GF_CORE_API ColorRampBase<float>;
extern template struct GF_CORE_API ColorRampBase<double>;
#endif
#ifndef DOXYGEN_SHOULD_SKIP_THIS
}
#endif
}
#endif // GF_COLOR_RAMP_H
| [
"julien.bernard@univ-fcomte.fr"
] | julien.bernard@univ-fcomte.fr |
c7f18bd7e4e4123d207bc6baf249d48041ad5028 | 82bba04be05e518845b99d749a3293668725e9e7 | /QHG3/genes/CrossComp.cpp | 69f73fdf2fa8c030664c5b00efa07fe816971b3c | [] | no_license | Achandroth/QHG | e914618776f38ed765da3f9c64ec62b983fc3df3 | 7e64d82dc3b798a05f2a725da4286621d2ba9241 | refs/heads/master | 2023-06-04T06:24:41.078369 | 2018-07-04T11:01:08 | 2018-07-04T11:01:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,799 | cpp |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hdf5.h>
#include <map>
#include <vector>
#include <algorithm>
#include "ParamReader.h"
#include "LineReader.h"
#include "types.h"
#include "strutils.h"
#include "QDFUtils.h"
#include "QDFArray.h"
#include "QDFArray.cpp"
#include "CrossDistMat.h"
#include "GeneUtils.h"
#include "BinGeneFile.h"
//----------------------------------------------------------------------------
// usage
//
void usage(char *pApp) {
printf("%s - crosswise genetic distances between two sets of genomes\n", pApp);
printf("Usage;\n");
printf(" %s -g <genomefile0> -g <genomefile0> -o <outputfile>\n", pApp);
printf("where\n");
printf(" genomefile0 a bin-file (as created by QDFSampler)\n");
printf(" genomefile1 a bin-file (as created by QDFSampler)\n");
printf(" outputfile output file name\n");
printf("\n");
}
//----------------------------------------------------------------------------
// readGenomes2
// try to read given file a s binary
//
BinGeneFile *readGenomes2(const char *pGeneFile) {
int iNumGenomes = -1;
BinGeneFile *pBG = BinGeneFile::createInstance(pGeneFile);
if (pBG != NULL) {
iNumGenomes = pBG->read();
if (iNumGenomes <= 0) {
delete pBG;
pBG = NULL;
}
}
return pBG;
}
//----------------------------------------------------------------------------
// reorderGenes
//
ulong **reorderGenes(id_genomes &mIDGen, tnamed_ids &mvIDs) {
ulong **pAllGenomes = new ulong*[mIDGen.size()];
int iC = 0;
tnamed_ids::const_iterator it;
for (it = mvIDs.begin(); it != mvIDs.end(); ++it) {
for (uint k = 0; k < it->second.size(); k++) {
pAllGenomes[iC++] = mIDGen[it->second[k]];
}
}
return pAllGenomes;
}
//----------------------------------------------------------------------------
// writeFullMatrix
//
int writeFullMatrix(const char *pOutput, int **pM, int iNumGenes0, tnamed_ids &mvIDs0, int iNumGenes1, tnamed_ids &mvIDs1) {
int iResult = -1;
FILE *fOut = NULL;
fOut = fopen(pOutput, "wt");
if (fOut != NULL) {
iResult = 0;
int iMin = 100000;
int iMax = -100000;
double dAvg = 0;
tnamed_ids::const_iterator it0;
tnamed_ids::const_iterator it1;
int iW = 0;
for (it1 = mvIDs1.begin(); it1 != mvIDs1.end(); ++it1) {
iW += it1->second.size();
}
int iH = 0;
for (it0 = mvIDs0.begin(); it0 != mvIDs0.end(); ++it0) {
iH += it0->second.size();
}
// write distances with prepended location and agent ID
// int i = 0;
// for (it0 = mvIDs0.begin(); it0 != mvIDs0.end(); ++it0) {
// for (uint k0 = 0; k0 < it0->second.size(); k0++) {
for (int i = 0; i < iH; i++) {
// int j = 0;
// for (it1 = mvIDs1.begin(); it1 != mvIDs1.end(); ++it1) {
// for (uint k1 = 0; k1 < it1->second.size(); k1++) {
for (int j = 0; j < iW; j++) {
fprintf(fOut, "%d\t", pM[i][j]);
dAvg += pM[i][j];
if (pM[i][j] < iMin) {
iMin = pM[i][j];
}
if (pM[i][j] > iMax) {
iMax = pM[i][j];
}
// }
// j++;
}
// i++;
fprintf(fOut, "\n");
// }
}
fclose(fOut);
printf("Writing full distance matrix\n [%s]\n", pOutput);
dAvg /= (iW*iH);
printf("cc Num Distances: %d x %d = %d\n", iW, iH, iW*iH);
printf("cc Avg Distance: %f\n", dAvg);
printf("cc Min Distance: %d\n", iMin);
printf("cc Max Distance: %d\n", iMax);
} else {
fprintf(stderr, "Couldn't open output file [%s]\n", pOutput);
}
return iResult;
}
//----------------------------------------------------------------------------
// createAndWriteDistMat
//
int createAndWriteDistMat(int iGenomeSize, id_genomes &mIDGen0, tnamed_ids &mvIDs0, id_genomes &mIDGen1, tnamed_ids &mvIDs1, const char *pOutput) {
int iResult = -1;
ulong **pGenomes0 = NULL;
pGenomes0 = reorderGenes(mIDGen0, mvIDs0);
ulong **pGenomes1 = NULL;
pGenomes1 = reorderGenes(mIDGen1, mvIDs1);
CrossDistMat *pCDM = CrossDistMat::createCrossDistMat(iGenomeSize, pGenomes0, mIDGen0.size(), pGenomes1, mIDGen1.size());
if (pCDM != NULL) {
int **pM = pCDM->createMatrix();
char sName1[512];
sprintf(sName1, "%s.full.mat", pOutput);
iResult = writeFullMatrix(sName1, pM, mIDGen0.size(), mvIDs0, mIDGen1.size(), mvIDs1);
pCDM->showStats();
delete pCDM;
}
if ((pGenomes0 != NULL) && (pGenomes1 != NULL)) {
delete[] pGenomes0;
pGenomes0 = NULL;
delete[] pGenomes1;
pGenomes1 = NULL;
}
return iResult;
}
//----------------------------------------------------------------------------
// main
//
int main(int iArgC, char *apArgV[]) {
int iResult =-1;
char *pGeneFile0 = NULL;
char *pGeneFile1 = NULL;
char *pOutput = NULL;
ParamReader *pPR = new ParamReader();
if (pPR != NULL) {
bool bOK = pPR->setOptions(3,
"-G:S!", &pGeneFile0,
"-g:S!", &pGeneFile1,
"-o:S!", &pOutput);
if (bOK) {
iResult = pPR->getParams(iArgC, apArgV);
if (iResult >= 0) {
int iGenomeSize0 = -1;
int iGenomeSize1 = -1;
id_genomes mIDGen0;
id_genomes mIDGen1;
tnamed_ids mvIDs0;
tnamed_ids mvIDs1;
iResult = -1;
std::map<int,int> mIDNodes;
tnamed_ids mvIDs;
id_locs mIdLocs;
id_genomes mIDGen;
BinGeneFile *pBG0 = readGenomes2(pGeneFile0);
if (pBG0 != NULL) {
iGenomeSize0 = pBG0->getGenomeSize();
mvIDs0 = pBG0->getvIDs();
mIDGen0 = pBG0->getIDGen();
BinGeneFile *pBG1 = readGenomes2(pGeneFile1);
if (pBG1 != NULL) {
iGenomeSize1 = pBG1->getGenomeSize();
mvIDs1 = pBG1->getvIDs();
mIDGen1 = pBG1->getIDGen();
if (iGenomeSize0 == iGenomeSize1) {
iResult = createAndWriteDistMat(iGenomeSize0, mIDGen0, mvIDs0, mIDGen1, mvIDs1, pOutput);
} else {
printf("Genome sizes don't match: %d != %d\n", iGenomeSize0, iGenomeSize1);
iResult = -1;
}
delete pBG1;
} else {
printf("Couldn't read [%s]\n", pGeneFile1);
iResult = -1;
}
delete pBG0;
} else {
printf("Couldn't read [%s]\n", pGeneFile0);
iResult = -1;
}
} else {
usage(apArgV[0]);
}
} else {
fprintf(stderr, "Couldn't set ParamReader options\n");
}
delete pPR;
} else {
fprintf(stderr, "Couldn't create ParamReader\n");
}
if (iResult == 0) {
printf("+++ success +++\n");
}
return iResult;
}
| [
"jody@aim.uzh.ch"
] | jody@aim.uzh.ch |
cc7c62249a5dd1ebe57c83ad1402e1fcfd11fc02 | b7142e895c186b8bd50e543fa082ddff4e63ab3e | /src/main.cpp | 2979647aaa99e8176591d29987be8fc6dba81e68 | [] | no_license | rChen10/g6-shapes | ab207eddefef4133863f23c91dc17387eeca2fb7 | ec8f168351cd1b472ade3a00fd78e1824ab60890 | refs/heads/master | 2021-04-09T10:47:18.556121 | 2018-03-19T18:46:22 | 2018-03-19T18:46:22 | 125,523,044 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 275 | cpp | #include "../include/parser.h"
int main(int argc, char **argv){
screen s = screen(500, 500);
matrix transform = matrix(4, 4);
matrix edges = matrix();
if(argc > 0){
std::cout << "reading script...";
parse_file(argv[1], transform, edges, s);
}
else
return 1;
}
| [
"rchen10@stuy.edu"
] | rchen10@stuy.edu |
76b1930b33afffde2800c2a625722534e0580056 | 582ecfc2e57b66d2aa6e1623524b0936d2fc436f | /include/geng/graphics/Shaders.h | 1102047161b709a4141601484a498e160d15d78a | [] | no_license | grynca/geng | 3950018e14b349d18e6ea0e866022f10d1f25316 | 92b760b7b06bc8b46c2a089423ec0b33a9d63abe | refs/heads/master | 2021-05-15T01:44:22.905486 | 2018-03-06T11:10:25 | 2018-03-06T11:10:25 | 40,620,852 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 483 | h | #ifndef SHADERS_H
#define SHADERS_H
#include "types/Manager.h"
namespace grynca {
// fw
class Shader;
class Window;
class Shaders : public ManagerSingletons<Shader> {
public:
Shaders(Window& w);
Shader* getBoundShader();
Window& getWindow();
std::string getTypesDebugString()const;
private:
friend class Shader;
Window* window_;
u32 bound_id_;
};
}
#include "Shaders.inl"
#endif //SHADERS_H
| [
"grynca@gmail.com"
] | grynca@gmail.com |
7eb1ab4819da4bd6a0d018c64fa65526beec8b5b | 2c37c298a494ed37bff11b0b240371eaba6575b7 | /0543/main.cpp | 902cdb9548ff5d1548ccb9ae9f44b651414e093f | [] | no_license | chichuyun/LeetCode | 04ec78bf5b05d4febfd8daff5e0e0145cfcfacf4 | 44752f2b58cd7a850b8e02cd3735f93bb82bcb85 | refs/heads/master | 2021-06-04T11:03:04.297131 | 2020-11-19T14:48:32 | 2020-11-19T14:48:32 | 148,440,792 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 619 | cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
int depth(TreeNode* root, int& ans) {
if(!root) return 0;
int L=0, R=0;
if(root->left) L = depth(root->left, ans);
if(root->right) R = depth(root->right, ans);
ans = max(L+R, ans);
return max(L,R) + 1;
}
public:
int diameterOfBinaryTree(TreeNode* root) {
int ans=0;
depth(root, ans);
return ans;
}
}; | [
"442307054@qq.com"
] | 442307054@qq.com |
3e955069cce794d70aa4c20b1e907b9214282569 | 30b7ffd17845db982883a91ce8d04551281658c4 | /Codeforces/Educational/Educational 75/B.cpp | b758ac967f608caf4c2141fc922de9575fc2803e | [] | no_license | shas9/codehub | 95418765b602b52edb0d48a473ad7e7a798f76e5 | bda856bf6ca0f3a1d59980895cfab82f690c75a2 | refs/heads/master | 2023-06-21T01:09:34.275708 | 2021-07-26T14:54:03 | 2021-07-26T14:54:03 | 389,404,954 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,190 | cpp | #include <bits/stdc++.h>`
#define slld(longvalue) scanf("%lld", &longvalue)
#define plld(longvalue) printf("%lld\n", longvalue)
#define slf(longvalue) scanf("%lf", &longvalue)
#define plf(longvalue) printf("%lf\n", longvalue)
#define sc(letter) scanf("%c", &letter)
#define pc(letter) printf("%c", letter)
#define ss(name) scanf("%s", name)
#define ps(name) printf("%s", name)
#define pnew printf("\n")
#define ll long long
#define ull unsigned long long
#define pll pair < long long, long long >
#define pii pair < int, int >
#define printcase(indexing,ans) printf("Case %lld: %lld\n", indexing, ans)
#define pb(x) push_back(x)
#define bug printf("BUG\n")
#define mxlld LLONG_MAX
#define mnlld -LLONG_MAX
#define mxd 2e8
#define mnd -2e8
#define pi 3.14159265359
#define mod 1000000009
using namespace std;
bool check(ll n, ll pos)
{
return n & (1LL << pos);
}
ll Set(ll n, ll pos)
{
return n = n | (1LL << pos);
}
vector < ll > vec;
string str;
int main()
{
ll i, j, k, l, m, n, o, r, q;
ll testcase;
ll input, flag, tag, ans;
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
slld(testcase);
for(ll cs = 1; cs <= testcase; cs++)
{
slld(n);
vec.clear();
ll zero = 0, one = 0;
for(i = 1; i <= n; i++)
{
cin >> str;
for(j = 0; j < str.size(); j++)
{
if(str[j] == '0') zero++;
else one++;
}
vec.push_back(str.size());
}
ans = 0;
sort(vec.begin(),vec.end());
for(i = 0; i < n; i++)
{
if(vec[i] <= zero)
{
ans++;
zero -= vec[i];
}
else if(vec[i] <= one)
{
ans++;
one -= vec[i];
}
else if(vec[i] % 2)
{
if(one % 2)
{
if(zero + one >= vec[i])
{
ans++;
zero -= vec[i] - one;
}
}
else
{
if(zero + (one - 1) >= vec[i])
{
ans++;
zero -= vec[i] - (one - 1);
one = 1;
}
}
}
else
{
if(one % 2)
{
if(zero + (one - 1) >= vec[i])
{
ans++;
zero -= vec[i] - (one - 1);
one = 1;
}
}
else
{
if(zero + one >= vec[i])
{
ans++;
zero -= vec[i] - one;
}
}
}
}
cout << ans << endl;
}
}
| [
"shahwathasnaine@gmail.com"
] | shahwathasnaine@gmail.com |
895de775a6d0277aba4b9f81529de647116480c8 | f6355f5fcd17ff3531e694c2ba544df3905b1a48 | /Utils/bin/FakeRate_TTbar.cpp | 15f45688ecbd5bfba59477d2d8a8941736a5e7d5 | [] | no_license | jasperlauwers/FakeRate | dbb6833bc6ff9e7d955a188317c9d554739c4a5d | 917f52dcc8b0a3ca38dd8b2d5db03d3f0f51d1da | refs/heads/master | 2020-06-04T22:25:57.780780 | 2015-08-24T13:35:20 | 2015-08-24T13:35:20 | 29,358,201 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 28,875 | cpp | // C++ includes
#include <iostream>
#include <cmath>
#include <vector>
#include <dirent.h>
#include <time.h>
#include <iomanip>
// ROOT includes
#include "TFile.h"
#include "TTree.h"
#include "TString.h"
#include "TClonesArray.h"
#include "TH2F.h"
#include "TCanvas.h"
#include "TMath.h"
#include "TChain.h"
#include "TLorentzVector.h"
// Bacon includes
#include "BaconAna/DataFormats/interface/TElectron.hh"
#include "BaconAna/DataFormats/interface/TMuon.hh"
#include "BaconAna/DataFormats/interface/TJet.hh"
#include "BaconAna/DataFormats/interface/TGenParticle.hh"
#include "BaconAna/DataFormats/interface/TEventInfo.hh"
using namespace std;
using namespace baconhep;
bool passElectronID(TElectron* elec, const float (&cuts)[10], double rho );
bool passTightMuonID(TMuon* muon);
bool passLooseMuonID(TMuon* muon);
// Loadbar: x = iEvent,n = totEvents, w = width
static inline void loadbar(unsigned int x, unsigned int n, unsigned int r = 20, unsigned int w = 20)
{
if ( x % (n/r+1) != 0 ) return;
float ratio = x/(float)n;
unsigned int c = ratio * w;
cout << setw(3) << (int)(ratio*100) << "% [";
for (unsigned int x=0; x<c; x++) cout << "=";
for (unsigned int x=c; x<w; x++) cout << " ";
cout << "]\r" << flush;
}
int main(int argc, char* argv[]) {
// ----- Variables to be set --------------
// Selection
bool eJet = true; // eJet = true: jet -> e
bool tightSel = true; // tight or loose lepton selection
float leptonPt = 20;
// Binning
const int nEtaBinsEl = 6, nPtBinsEl = 6;
const Double_t etaBinsEl[nEtaBinsEl+1] = {0,0.5,1,1.5,1.75,2,2.5};
const Double_t ptBinsEl[nPtBinsEl+1] = {20,30,50,80,120,180,300};
// ID cuts
const float looseElCuts[2][10] = {{0.004,0.06,0.01,0.12,0.02,0.1,0.05,0.15,1e-6,1},{0.007,0.03,0.03,0.1,0.02,0.1,0.05,0.15,1e-6,1}};
// veto cuts
// const float tightElCuts[2][10] = {{0.006574,0.022868,0.010181,0.037553,0.009924,0.015310,0.131191,0.074355,1,1},{0.005681,0.032046,0.028766,0.081902,0.027261,0.147154,0.106055,0.090185,1,1}};
const float tightElCuts[2][10] = {{0.004,0.03,0.01,0.12,0.02,0.1,0.05,0.1,1e-6,0},{0.005,0.02,0.03,0.1,0.02,0.1,0.05,0.1,1e-6,0}};
// Directories
int maxInFiles=500;
// TString outDirPNG = "/afs/cern.ch/user/j/jlauwers/www/protected/VBS/TP/FakeRate_rebin/";
TString outDirROOT = "/afs/cern.ch/work/j/jlauwers/VBS/TP/FakeRate/Results/";
TString eosDir = "/afs/cern.ch/work/j/jlauwers/VBS/TP/FakeRate/";
TString inDir = "eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/rgerosa/TP_ANALYSIS/BACON_TREES/PYTHIA6_Tauola_TTbar_TuneZ2star_14TeV-TP2023HGCALDR/";
// TString inDir = "/afs/cern.ch/work/j/jlauwers/VBS/TP/FakeRate/BaconTrees/";
// Constants
const Float_t pi = 3.1416;
// Verbose output
int verbose = 2; // 0: no messages - 1: basic output and load bar - 2: calculate lepton efficiency - 3: all debug information
// ----------------------------------------
// Parse command line parameters
if (argc < 2) {
cout << cout << "Studying jet -> " << (eJet?"e":"mu") << " process" << endl;
}
else if( string(argv[1]) == "e" ){
eJet = true;
if( verbose > 0 ) cout << "Studying jet -> e process" << endl;
}
else if( string(argv[1]) == "m" ){
eJet = false;
if( verbose > 0 ) cout << "Studying jet -> mu process" << endl;
}
// Set timer
clock_t t1,t2;
t1=clock();
// Add all BaconTrees to a chain
TChain* tree = new TChain("Events");
DIR *dpdf;
struct dirent *epdf;
int nFiles = 0;
if( verbose > 2 ) maxInFiles=1;
dpdf = opendir(eosDir+inDir);
if (dpdf != NULL){
while ((epdf = readdir(dpdf))){
string fname = epdf->d_name;
if (fname != "." && fname != "..") {
tree->Add(eosDir+inDir+fname);
nFiles++;
if( verbose > 2 ) cout << "Adding file: " << epdf->d_name << endl;
if( nFiles == maxInFiles ) break;
}
}
}
else cout << "Nothing in: " << eosDir << inDir << endl;
if( verbose > 0 ) cout << "Added " << nFiles << " files to chain." << endl;
tree->SetBranchStatus("*",0);
tree->SetBranchStatus("Electron*",1);
tree->SetBranchStatus("Muon*",1);
tree->SetBranchStatus("Jet04*",1);
tree->SetBranchStatus("GenParticle*",1);
tree->SetBranchStatus("rhoIso",1);
TClonesArray *fElectron = new TClonesArray("baconhep::TElectron");
TClonesArray *fMuon = new TClonesArray("baconhep::TMuon");
TClonesArray *fJet = new TClonesArray("baconhep::TJet");
TClonesArray *fGenParticle = new TClonesArray("baconhep::TGenParticle");
TEventInfo *eventInfo=0;
tree->SetBranchAddress("Electron", &fElectron);
tree->SetBranchAddress("Muon", &fMuon);
tree->SetBranchAddress("Jet04", &fJet);
tree->SetBranchAddress("GenParticle", &fGenParticle);
tree->SetBranchAddress("Info", &eventInfo);
TString strSel = "jet_to";
if( eJet ) strSel += "_e";
else strSel += "_mu";
TH1::SetDefaultSumw2();
TH2F *hJetNum, *hDenom, *hJetNumB, *hDenomB;
TH2D *hBinCentres, *hBinCentresB;
hJetNum= new TH2F("Jet_Numerator_"+strSel,"Jet_Numerator_"+strSel,nEtaBinsEl, etaBinsEl, nPtBinsEl, ptBinsEl);
hDenom = new TH2F("Denominator_"+strSel,"Denominator_"+strSel,nEtaBinsEl, etaBinsEl, nPtBinsEl, ptBinsEl);
hBinCentres = new TH2D("Pt_centre_"+strSel,"Pt_centre_"+strSel,nEtaBinsEl, etaBinsEl, nPtBinsEl, ptBinsEl);
hJetNumB= new TH2F("Jet_Numerator_b_"+strSel,"Jet_Numerator_"+strSel,nEtaBinsEl, etaBinsEl, nPtBinsEl, ptBinsEl);
hDenomB = new TH2F("Denominator_b_"+strSel,"Denominator_"+strSel,nEtaBinsEl, etaBinsEl, nPtBinsEl, ptBinsEl);
hBinCentresB = new TH2D("Pt_centre_b_"+strSel,"Pt_centre_"+strSel,nEtaBinsEl, etaBinsEl, nPtBinsEl, ptBinsEl);
TH2F *hPtMigrationB=0, *hPtMigration=0;
TH1D *hMigrationBinCentres=0, *hBMigrationBinCentres;
hPtMigrationB = new TH2F("Pt_migration_b_"+strSel,"Pt_migration_b_"+strSel,nPtBinsEl, ptBinsEl, 60, -50., 250.);
hPtMigration = new TH2F("Pt_migration_"+strSel,"Pt_migration_"+strSel,nPtBinsEl, ptBinsEl, 60, -50., 250.);
hMigrationBinCentres = new TH1D("Pt_migration_centre_"+strSel,"Pt_migration_centre_"+strSel, nPtBinsEl, ptBinsEl);
hBMigrationBinCentres = new TH1D("Pt_migration_b_centre_"+strSel,"Pt_migration_b_centre_"+strSel, nPtBinsEl, ptBinsEl);
int lepElec=0, lepMuon=0, jetElec=0, jetMuon=0, l1NotMatched=0, l2NotMatched=0, elNotFound=0;
float elecEffDenom=0, elecEffNum=0, muonEffDenom=0, muonEffNum=0;
int jetlep2GenMatch=0, wLept=0, bJetEvents=0, nonBJetEvents=0;
int cJets=0;
// Loop over events
int nevents = tree->GetEntries(); // GetEntriesFast fails for chain
if( verbose > 2 ) nevents=1000;
if( verbose > 0 ) cout << "nevents: " << nevents << endl;
for( int i = 0; i < nevents; ++i ) {
if( verbose > 0 ) loadbar(i+1,nevents);
tree->GetEntry(i);
int nElectrons = fElectron->GetEntriesFast();
int nMuons = fMuon->GetEntriesFast();
int nGenParticles = fGenParticle->GetEntriesFast();
int nJets = fJet->GetEntriesFast();
if( verbose > 2 ) cout << "nElectrons: " << nElectrons << ", nMuons: " << nMuons << endl;
// Calculate lepton efficiencies
if( verbose > 0 ) {
for( int iE = 0; iE < nElectrons; ++iE ) {
TElectron *elec = (TElectron*)((*fElectron)[iE]);
if( fabs(elec->eta) < 2.5 && elec->pt > leptonPt) {
elecEffDenom++;
bool inEndcap = fabs(elec->scEta) > 1.479;
bool passSel;
if( tightSel) passSel = passElectronID(elec, tightElCuts[inEndcap], eventInfo->rhoIso);
else passSel = passElectronID(elec, looseElCuts[inEndcap], eventInfo->rhoIso);
if( passSel ) elecEffNum++;
}
}
for( int iM = 0; iM < nMuons; ++iM ) {
TMuon *muon = (TMuon*)((*fMuon)[iM]);
if( fabs(muon->eta) < 2.5 && muon->pt > leptonPt) {
muonEffDenom++;
bool passSel;
if( tightSel) passSel = passTightMuonID(muon);
else passSel = passLooseMuonID(muon);
if( passSel ) muonEffNum++;
}
}
}
// -- Require genLeptons in tracker to be matched --
vector<int> genElecIndex, genMuonIndex;
vector<float> elecEta, elecPhi, muonEta, muonPhi; // Has to be removed from jet collection
unsigned int nElecReq=0, nMuonReq=0;
const unsigned int parentId = 24;
// Count number of electrons and muons expected in tracker
for( int iG = 0; iG < nGenParticles; ++iG ) {
TGenParticle *genP = (TGenParticle*)((*fGenParticle)[iG]);
if( genP->status == 1 && genP->parent>=0 && fabs(genP->eta) < 2.8 ) { // 2.8 to correct for dR
if( abs(genP->pdgId) == 11 ) {
bool foundW = false, stuck = false/*, inTracker = fabs(genP->eta) < 2.5*/;
do {
if(genP->parent>=0) {
TGenParticle *genTemp = (TGenParticle*)((*fGenParticle)[genP->parent]);
genP = genTemp;
}
else stuck = true;
if( abs(genP->pdgId) == parentId) {
foundW = true;
}
} while( !stuck && !foundW );
if( foundW ) {
genElecIndex.push_back(iG);
/*if( inTracker )*/ nElecReq++;
}
}
if( abs(genP->pdgId) == 13 ) {
bool foundW = false, stuck = false/*, inTracker = fabs(genP->eta) < 2.5*/;
do {
if(genP->parent>=0) {
TGenParticle *genTemp = (TGenParticle*)((*fGenParticle)[genP->parent]);
genP = genTemp;
}
else stuck = true;
if( abs(genP->pdgId) == parentId) {
foundW = true;
}
} while( !stuck && !foundW );
if( foundW ) {
genMuonIndex.push_back(iG);
/*if( inTracker )*/ nMuonReq++;
}
}
}
}
if( verbose > 2 ) cout << "Required electrons in tracker: " << nElecReq << endl;
if( verbose > 2 ) cout << "Required muons in tracker: " << nMuonReq << endl;
vector<int> genElecIndex2 = genElecIndex, genMuonIndex2 = genMuonIndex;
if( nElecReq > 0 ) {
for( int iE = 0; iE < nElectrons; ++iE ) {
TElectron *elec = (TElectron*)((*fElectron)[iE]);
// bool inEndcap = fabs(elec->scEta) > 1.479;
bool passSel;
if( tightSel) passSel = true/*elec->pt > leptonPt && passElectronID(elec, tightElCuts[inEndcap], eventInfo->rhoIso )*/;
else passSel = true/*elec->pt > leptonPt && passElectronID(elec, looseElCuts[inEndcap], eventInfo->rhoIso )*/;
if( passSel ) {
l1NotMatched++;
if( verbose > 2 ) cout << "Electron " << iE <<" passed lepton id" << endl;
// Match with genParticle
for( vector<int>::iterator iG = genElecIndex.begin(); iG != genElecIndex.end(); ++iG ) {
TGenParticle *genP = (TGenParticle*)((*fGenParticle)[*iG]);
Double_t dR = TMath::Sqrt( TMath::Power(genP->eta - elec->eta, 2) + TMath::Power(fabs(fabs(genP->phi - elec->phi)-pi)-pi, 2) );
bool sameCharge = genP->pdgId == (elec->q)*-11.;
if( verbose > 2 ) cout << "dR: " << (dR < 0.3) << ", sameCharge: " << sameCharge << endl;
if( sameCharge && dR < 0.3 ) {
lepElec++;
if( verbose > 2 ) cout << "Matched with genElectron " << *iG << " from W" << endl;
elecEta.push_back(elec->eta);
elecPhi.push_back(elec->phi);
// if( fabs(genP->eta) >= 2.5 ) nLeptonsReq++; // corection for genLepton outside tracker en reco lepton inside
genElecIndex.erase(iG); // genLepton can only be matched to one reco lepton
wLept++;
l1NotMatched--;
break;
}
}
}
}
if( elecEta.size() != nElecReq ) {
if( verbose > 2 ) cout << "Electron not found" << endl;
elNotFound++;
continue;
}
}
if( nMuonReq > 0 ) {
for( int iM = 0; iM < nMuons; ++iM ) {
TMuon *muon = (TMuon*)((*fMuon)[iM]);
bool passSel/*= fabs(muon->eta) < 2.5 && ((muon->typeBits)/32)%2*/; // otherwise too many muons
if( tightSel) passSel = true /*muon->pt > leptonPt && passTightMuonID(muon)*/;
else passSel = muon->pt > leptonPt && passLooseMuonID(muon);
if( passSel ) {
l1NotMatched++;
if( verbose > 2 ) cout << "Muon " << iM << " passed lepton id" << endl;
// Match with genParticle
for( vector<int>::iterator iG = genMuonIndex.begin(); iG != genMuonIndex.end(); ++iG ) {
if( verbose > 2 ) cout << "Genleptons left: " << genMuonIndex.size() << endl;
TGenParticle *genP = (TGenParticle*)((*fGenParticle)[*iG]);
Double_t dR = TMath::Sqrt( TMath::Power(genP->eta - muon->eta, 2) + TMath::Power(fabs(fabs(genP->phi - muon->phi)-pi)-pi, 2) );
bool sameCharge = genP->pdgId == (muon->q)*-13.;
if( verbose > 2 ) cout << "dR: " << (dR < 0.3) << ", sameCharge: " << sameCharge << "gen charge: " << genP->pdgId << ", reco charge: " << (muon->q)*-13 << endl;
if( sameCharge && dR < 0.3 ) {
lepMuon++;
if( verbose > 2 ) cout << "Matched with genMuon " << *iG << " from W" << endl;
muonEta.push_back(muon->eta);
muonPhi.push_back(muon->phi);
// if( fabs(genP->eta) >= 2.5 ) nLeptonsReq++; // corection for genLepton outside tracker en reco lepton inside
genMuonIndex.erase(iG); // genLepton can only be matched to one reco lepton
wLept++;
l1NotMatched--;
break;
}
}
}
}
if( muonEta.size() != nMuonReq ) {
if( verbose > 2 ) cout << "Muon not found" << endl;
continue;
}
}
// -- Check if there is a third lepton --
int secLeptIndex = -1; // more than 1 leptons from jets is negligible
TMuon *muon=0;
TElectron *elec=0;
// Jet -> e
if( eJet ) {
for( int iE = 0; iE < nElectrons; ++iE ) {
TElectron *elec = (TElectron*)((*fElectron)[iE]);
bool inEndcap = fabs(elec->scEta) > 1.479;
bool passSel;
if( tightSel) passSel = elec->pt > leptonPt && fabs(elec->eta) < 2.5 && passElectronID(elec, tightElCuts[inEndcap], eventInfo->rhoIso);
else passSel = elec->pt > leptonPt && fabs(elec->eta) < 2.5 && passElectronID(elec, looseElCuts[inEndcap], eventInfo->rhoIso);
if( passSel ) {
// skip previously matched electron
bool isWLepton = false;
for( unsigned int iLep=0; iLep < elecEta.size(); ++iLep ) {
if( elecEta[iLep] == elec->eta || elecPhi[iLep] == elec->phi) isWLepton = true;
}
if( isWLepton ) continue;
// Match with genParticle to be sure it doesn't come from W
for( vector<int>::iterator iG = genElecIndex2.begin(); iG != genElecIndex2.end(); ++iG ) {
TGenParticle *genP = (TGenParticle*)((*fGenParticle)[*iG]);
Double_t dR = TMath::Sqrt( TMath::Power(genP->eta - elec->eta, 2) + TMath::Power(fabs(fabs(genP->phi - elec->phi)-pi)-pi, 2) );
// bool sameCharge = genP->pdgId == (elec->q)*-11.;
if( dR < 0.3 /*&& sameCharge*/ ) {
isWLepton=true;
break;
}
}
if( isWLepton ) continue;
secLeptIndex = iE;
if( verbose > 2 ) cout << "Electron " << iE <<" passed lepton id" << endl;
jetElec++;
break;
}
}
if( secLeptIndex >= 0 )
elec = (TElectron*)((*fElectron)[secLeptIndex]);
}
// Jet -> mu
else {
for( int iM = 0; iM < nMuons; ++iM ) {
TMuon *muon = (TMuon*)((*fMuon)[iM]);
bool passSel;
if( tightSel) passSel = muon->pt > leptonPt && fabs(muon->eta) < 2.5 && passTightMuonID(muon);
else passSel = muon->pt > leptonPt && fabs(muon->eta) < 2.5 && passLooseMuonID(muon);
if( passSel ) {
// skip previously matched muon
bool isWLepton = false;
for( unsigned int iLep=0; iLep < muonEta.size(); ++iLep ) {
if( muonEta[iLep] == muon->eta && muonPhi[iLep] == muon->phi) isWLepton = true;
}
if( isWLepton ) continue;
// Match with genParticle to be sure it doesn't come from W
for( vector<int>::iterator iG = genMuonIndex2.begin(); iG != genMuonIndex2.end(); ++iG ) {
TGenParticle *genP = (TGenParticle*)((*fGenParticle)[*iG]);
Double_t dR = TMath::Sqrt( TMath::Power(genP->eta - muon->eta, 2) + TMath::Power(fabs(fabs(genP->phi - muon->phi)-pi)-pi, 2) );
// bool sameCharge = genP->pdgId == (muon->q)*-13.;
if( dR < 0.3 /*&& sameCharge*/ ) {
isWLepton=true;
break;
}
}
if( isWLepton ) continue;
secLeptIndex = iM;
if( verbose > 2 ) cout << "Muon " << iM <<" passed lepton id" << endl;
jetMuon++;
break;
}
}
if( secLeptIndex >= 0 )
muon = (TMuon*)((*fMuon)[secLeptIndex]);
}
// -- Loop over jets --
for( int iJ = 0; iJ < nJets; ++iJ ) {
TJet *jet = (TJet*)((*fJet)[iJ]);
// Skip W leptons
bool skipJet = false;
for( unsigned int iLep=0; iLep < elecEta.size(); ++iLep ) {
Double_t dR = TMath::Sqrt( TMath::Power(elecEta[iLep] - jet->eta, 2) + TMath::Power(fabs(fabs(elecPhi[iLep] - jet->phi)-pi)-pi, 2) );
if( dR < 0.3 ) skipJet = true;
}
for( unsigned int iLep=0; iLep < muonEta.size(); ++iLep ) {
Double_t dR = TMath::Sqrt( TMath::Power(muonEta[iLep] - jet->eta, 2) + TMath::Power(fabs(fabs(muonPhi[iLep] - jet->phi)-pi)-pi, 2) );
if( dR < 0.3 ) skipJet = true;
}
if( skipJet ) {
if( verbose > 2 ) cout << "Skipping jet, matched to lepton." << endl;
continue;
}
// Skip PU jets ( jets not matched to gen jet )
if( jet->genpt == 0.0 ) {
if( verbose > 2 ) cout << "Skipping pu jet." << endl;
continue;
}
// Skip b-tagged jets
if( jet->csv > 0.679 ) {
if( verbose > 2 ) cout << "Skipping b-tagged jet." << endl;
bJetEvents++;
if( eJet ) continue; // muon fake rate independent of b-tag
}
else nonBJetEvents++;
// Fill histograms
bool bJet = false;
if( abs(jet->mcFlavor) == 5 ) bJet = true;
if(bJet) {
hDenomB->Fill(fabs(jet->eta), jet->pt);
int binNumber = hBinCentresB->FindBin(fabs(jet->eta),jet->pt);
hBinCentresB->SetBinContent(binNumber, hBinCentresB->GetBinContent(binNumber) + jet->pt );
}
else {
hDenom->Fill(fabs(jet->eta), jet->pt);
int binNumber = hBinCentres->FindBin(fabs(jet->eta),jet->pt);
hBinCentres->SetBinContent(binNumber, hBinCentres->GetBinContent(binNumber) + jet->pt );
}
if( secLeptIndex >= 0 ) {
Double_t dR;
if(eJet) dR = TMath::Sqrt( TMath::Power(elec->eta - jet->eta, 2) + TMath::Power(fabs(fabs(elec->phi - jet->phi)-pi)-pi, 2) );
else dR = TMath::Sqrt( TMath::Power(muon->eta - jet->eta, 2) + TMath::Power(fabs(fabs(muon->phi - jet->phi)-pi)-pi, 2) );
if( dR < 0.3 ) {
if(eJet) {
if( bJet ) {
hPtMigrationB->Fill(jet->pt, jet->pt - elec->pt);
}
else {
hPtMigration->Fill(jet->pt, jet->pt - elec->pt);
}
}
else {
if( bJet ) {
hPtMigrationB->Fill(jet->pt, jet->pt - muon->pt);
}
else {
hPtMigration->Fill(jet->pt, jet->pt - muon->pt);
}
}
if( bJet) {
int binNumber = hBMigrationBinCentres->FindBin(jet->pt);
hBMigrationBinCentres->SetBinContent(binNumber, hBMigrationBinCentres->GetBinContent(binNumber) + jet->pt );
hJetNumB->Fill(fabs(jet->eta), jet->pt);
}
else {
int binNumber = hMigrationBinCentres->FindBin(jet->pt);
hMigrationBinCentres->SetBinContent(binNumber, hMigrationBinCentres->GetBinContent(binNumber) + jet->pt );
hJetNum->Fill(fabs(jet->eta), jet->pt);
}
if( abs(jet->mcFlavor) == 4 && fabs(jet->eta) < 2.5 && jet->csv < 0.679) cJets++;
secLeptIndex = -1; // match with only 1 jet
if( verbose > 2 ) cout << "Matched with jet" << endl;
}
}
}
// Lepton should be matched
if( secLeptIndex >= 0 ) {
l2NotMatched++;
}
}
// Output
cout << "Electron efficiency: " << elecEffNum/elecEffDenom << ", Muon efficiency: " << muonEffNum/muonEffDenom << endl;
cout << "# elec1 passing sel and matched to gen electron: " << lepElec << ", # muons1 passing sel and matched to gen muon: " << lepMuon << endl;
cout << "# elec1 not found: " << elNotFound << endl;
cout << "# elec2 passing sel: " << jetElec << ", # muons2 passing sel: " << jetMuon << endl;
cout << "lep1 not matched with W: " << l1NotMatched << ", lep2 not matched with jet: " << l2NotMatched << endl;
cout << "lep1 matched to W: " << wLept << endl;
cout << "lept2 matched with a gen lepton: " << jetlep2GenMatch << endl;
cout << "b-tagged jets: " << bJetEvents << ", non b-taged jets: " << nonBJetEvents << endl;
cout << "c-jets in numerator: " << cJets << endl;
cout << "Fake rate: " << hJetNum->Integral()/hDenom->Integral() << endl;
cout << "Fake rate b-jets: " << hJetNumB->Integral()/hDenomB->Integral() << endl;
cout << "Average fake rate: " << (hJetNumB->Integral()+hJetNum->Integral())/(hDenomB->Integral()+hDenom->Integral()) << endl;
// -- Calculate and draw fake rate --
TFile* outFile = new TFile(outDirROOT+"FakeRate_TTbar_14TeV_HGCal.root","UPDATE");
hJetNum->Write();
hJetNumB->Write();
hDenom->Write();
hDenomB->Write();
hPtMigrationB->Write();
hPtMigration->Write();
// Bin centres
hBinCentres->Divide(hDenom);
hBinCentresB->Divide(hDenomB);
TH1D *hPtMigBins = hPtMigration->ProjectionX("_ptbinsce");
TH1D *hPtBMigBins = hPtMigrationB->ProjectionX("B_ptbinsce");
hMigrationBinCentres->Divide(hPtMigBins);
hBMigrationBinCentres->Divide(hPtBMigBins);
hBinCentres->Write();
hMigrationBinCentres->Write();
hBinCentresB->Write();
hBMigrationBinCentres->Write();
outFile->Delete();
t2=clock();
float diff ((float)t2-(float)t1);
cout<< " Total runtime: " << diff/CLOCKS_PER_SEC <<endl;
}
bool passElectronID(TElectron* elec, const float (&cuts)[10], double rho ) {
// electron iso rho correction
float eff_area;
if( abs(elec->eta)<1.0 ) eff_area = 0.13;
else if(abs(elec->eta)>1.0 && abs(elec->eta)<1.479 ) eff_area = 0.14;
else if(abs(elec->eta)>1.479 && abs(elec->eta)<2.0 ) eff_area = 0.07;
else if(abs(elec->eta)>2.0 && abs(elec->eta)<2.2 ) eff_area = 0.09;
else if(abs(elec->eta)>2.2 && abs(elec->eta)<2.3 ) eff_area = 0.11;
else if(abs(elec->eta)>2.3 && abs(elec->eta)<2.4 ) eff_area = 0.11;
else eff_area = 0.14;
return( fabs(elec->dEtaIn) < cuts[0] &&
fabs(elec->dPhiIn) < cuts[1] &&
elec->sieie < cuts[2] &&
elec->hovere < cuts[3] &&
fabs(elec->d0) < cuts[4] &&
fabs(elec->dz) < cuts[5] &&
fabs((1 - elec->eoverp)/elec->ecalEnergy) < cuts[6] &&
// ((elec->chHadIso03 + max(elec->gammaIso03+elec->neuHadIso03-0.5* elec->puIso03,0.0))/elec->pt) < cuts[7] && // electron iso dBeta
(elec->chHadIso03 + max(elec->gammaIso03 + elec->neuHadIso03 - max(rho, 0.0)*eff_area, 0.0))/elec->pt < cuts[7] && // electron iso rho correction
(!elec->isConv) &&
elec->nMissingHits <= cuts[9]
);
}
bool passTightMuonID(TMuon* muon) {
return( ((muon->typeBits)/2)%2 &&
((muon->typeBits)/32)%2 &&
muon->tkNchi2 < 10 && //
muon->nValidHits > 0 &&
muon->nMatchStn > 1 &&
fabs(muon->d0) < 0.2 && // d0 = -dxy
fabs(muon->dz) < 0.5 &&
muon->nPixHits > 0 &&
muon->nTkLayers > 5 &&
((muon->chHadIso04 + max(muon->gammaIso04+muon->neuHadIso04-0.5* muon->puIso04,0.0))/muon->pt) < 0.12 // muon iso
);
}
// bool passLooseMuonID(TMuon* muon) {
// return( ((muon->typeBits)/32)%2 &&
// ( ((muon->typeBits)/2)%2 || ((muon->typeBits)/4)%2 ) &&
// ((muon->chHadIso04 + max(muon->gammaIso04+muon->neuHadIso04-0.5* muon->puIso04,0.0))/muon->pt) < 0.2 // muon iso
// );
// }
bool passLooseMuonID(TMuon* muon) {
return( ((muon->typeBits)/2)%2 &&
((muon->typeBits)/32)%2 &&
muon->tkNchi2 < 10 && //
muon->nValidHits > 0 &&
muon->nMatchStn > 1 &&
fabs(muon->d0) < 0.2 && // d0 = -dxy
fabs(muon->dz) < 0.5 &&
muon->nPixHits > 0 &&
muon->nTkLayers > 5 &&
((muon->chHadIso04 + max(muon->gammaIso04+muon->neuHadIso04-0.5* muon->puIso04,0.0))/muon->pt) < 0.16 // muon iso
);
}
| [
"jasper.lauwers@uantwerpen.be"
] | jasper.lauwers@uantwerpen.be |
733f74214854f849342f09b109acec6be6f341d6 | 38de6b6ac97be636849da93ed0481286a15e973f | /ffmpeg/src/main/cpp/ffmpeg-player/VideoChannel.h | 490712a4d6bb07d5ade1d096d1e893df01b92713 | [] | no_license | tainzhi/VideoPlayer | cbecde10d17321da6f58a9760d4728d5a10d4142 | f82b1b34e7841dd20843c26cb3e6bd1ed6275cdd | refs/heads/master | 2022-02-19T15:50:13.320798 | 2022-02-14T00:08:02 | 2022-02-14T00:08:02 | 55,685,709 | 49 | 8 | null | 2022-02-14T00:08:03 | 2016-04-07T10:29:12 | C | UTF-8 | C++ | false | false | 927 | h | #ifndef NDK_SAMPLE_VIDEOCHANNEL_H
#define NDK_SAMPLE_VIDEOCHANNEL_H
#include "BaseChannel.h"
#include "AudioChannel.h"
#include <unistd.h>
extern "C" {
#include <libswscale/swscale.h>
#include <libavutil/imgutils.h>
}
typedef void (*RenderCallback)(uint8_t *, int, int, int);
class VideoChannel : public BaseChannel {
public:
VideoChannel(int stream_index, AVCodecContext *pContext, AVRational, int,JNICallback* jniCallback);
~VideoChannel();
void start();
void stop();
void video_decode();
void video_player();
void setRenderCallback(RenderCallback renderCallback);
void setAudioChannel(AudioChannel* audioChannel);
void release();
void restart();
private:
pthread_t pid_video_decode;
pthread_t pid_video_player;
RenderCallback renderCallback;
int fpsValue;//视频 fps
AudioChannel* audioChannel = 0;
};
#endif //NDK_SAMPLE_VIDEOCHANNEL_H
| [
"qfq61@qq.com"
] | qfq61@qq.com |
657cdcdf137dcc574ba51a7fdb71ec29493fb7df | e893340c8a9d2f4b40b242f2d7f6c789645b6a24 | /Proteomics/Protein/Protein.cpp | a1aa630ec6c8bf06c7f2738826254057bf087de0 | [] | no_license | edgargabriel/HPCmzLib | f3a57307985b1aacf401d4c3ac1d64ca32cf81e1 | dd54d285e9bbc27aba18f0b3077c9221581d8748 | refs/heads/master | 2023-06-30T19:44:33.748636 | 2020-07-30T14:13:16 | 2020-07-30T14:13:16 | 283,791,032 | 0 | 0 | null | 2020-07-30T14:01:47 | 2020-07-30T14:01:46 | null | UTF-8 | C++ | false | false | 13,089 | cpp | #include "Protein.h"
#include "../Modifications/Modification.h"
#include "SequenceVariation.h"
#include "DisulfideBond.h"
#include "SpliceSite.h"
#include "ProteolysisProduct.h"
#include "DatabaseReference.h"
#include "../Modifications/ModificationLocalization.h"
#include "stringhelper.h"
//using namespace Proteomics::ProteolyticDigestion;
#include "VariantApplication.h"
namespace Proteomics
{
Protein::Protein(const std::string &sequence,
const std::string &accession,
const std::string &organism,
std::vector<std::tuple<std::string, std::string>> geneNames,
std::unordered_map<int, std::vector<Modification*>> oneBasedModifications,
std::vector<ProteolysisProduct*> proteolysisProducts,
const std::string &name,
const std::string &fullName,
bool isDecoy, bool isContaminant,
std::vector<DatabaseReference*> databaseReferences,
std::vector<SequenceVariation*> sequenceVariations,
std::vector<SequenceVariation*> appliedSequenceVariations,
const std::string &sampleNameForVariants,
std::vector<DisulfideBond*> disulfideBonds,
std::vector<SpliceSite*> spliceSites,
const std::string &databaseFilePath)
{
// Mandatory
privateBaseSequence = sequence;
privateNonVariantProtein = this;
privateAccession = accession;
privateName = name;
privateOrganism = organism;
privateFullName = fullName;
privateIsDecoy = isDecoy;
privateIsContaminant = isContaminant;
privateDatabaseFilePath = databaseFilePath;
privateSampleNameForVariants = sampleNameForVariants;
#ifdef ORIG
privateGeneNames = geneNames ? geneNames : std::vector<std::tuple<std::string, std::string>>();
privateProteolysisProducts = proteolysisProducts ? proteolysisProducts : std::vector<ProteolysisProduct*>();
privateSequenceVariations = sequenceVariations ? sequenceVariations : std::vector<SequenceVariation*>();
privateAppliedSequenceVariations = appliedSequenceVariations ? appliedSequenceVariations : std::vector<SequenceVariation*>();
setOriginalNonVariantModifications(oneBasedModifications ? oneBasedModifications : std::unordered_map<int, std::vector<Modification*>>());
#endif
// EG: in Theory, a reference can never have a null value in C++;
privateGeneNames = geneNames;
privateProteolysisProducts = proteolysisProducts;
privateSequenceVariations = sequenceVariations;
privateAppliedSequenceVariations = appliedSequenceVariations;
setOriginalNonVariantModifications(oneBasedModifications);
if (!oneBasedModifications.empty()) {
setOneBasedPossibleLocalizedModifications(SelectValidOneBaseMods(oneBasedModifications));
}
else {
setOneBasedPossibleLocalizedModifications(std::unordered_map<int, std::vector<Modification*>>());
}
privateDatabaseReferences = databaseReferences ;
privateDisulfideBonds = disulfideBonds;
privateSpliceSites = spliceSites;
}
Protein::Protein(std::string variantBaseSequence,
Protein *protein,
std::vector<SequenceVariation*> appliedSequenceVariations,
std::vector<ProteolysisProduct*> applicableProteolysisProducts,
std::unordered_map<int, std::vector<Modification*>> oneBasedModifications,
std::string sampleNameForVariants) {
Protein(variantBaseSequence,
VariantApplication::GetAccession(protein, appliedSequenceVariations),
protein->getOrganism(),
protein->getGeneNames(),
oneBasedModifications,
applicableProteolysisProducts,
GetName(appliedSequenceVariations, protein->getName()),
GetName(appliedSequenceVariations, protein->getFullName()),
protein->getIsDecoy(),
protein->getIsContaminant(),
protein->getDatabaseReferences(),
protein->getSequenceVariations(),
appliedSequenceVariations,
sampleNameForVariants,
protein->getDisulfideBonds(),
protein->getSpliceSites(),
protein->getDatabaseFilePath());
privateNonVariantProtein = protein->getNonVariantProtein();
std::unordered_map<int, std::vector<Modification*>> v = getNonVariantProtein()->getOriginalNonVariantModifications();
std::unordered_map<int, std::vector<Modification*>> &v2 =v;
setOriginalNonVariantModifications(v2);
}
std::unordered_map<int, std::vector<Modification*>> Protein::getOneBasedPossibleLocalizedModifications() const
{
return privateOneBasedPossibleLocalizedModifications;
}
void Protein::setOneBasedPossibleLocalizedModifications(const std::unordered_map<int, std::vector<Modification*>> &value)
{
privateOneBasedPossibleLocalizedModifications = value;
}
std::vector<std::tuple<std::string, std::string>> Protein::getGeneNames() const
{
return privateGeneNames;
}
std::string Protein::getAccession() const
{
return privateAccession;
}
std::string Protein::getBaseSequence() const
{
return privateBaseSequence;
}
std::string Protein::getOrganism() const
{
return privateOrganism;
}
bool Protein::getIsDecoy() const
{
return privateIsDecoy;
}
std::vector<SequenceVariation*> Protein::getSequenceVariations() const
{
return privateSequenceVariations;
}
std::vector<DisulfideBond*> Protein::getDisulfideBonds() const
{
return privateDisulfideBonds;
}
std::vector<SpliceSite*> Protein::getSpliceSites() const
{
return privateSpliceSites;
}
std::vector<ProteolysisProduct*> Protein::getProteolysisProducts() const
{
return privateProteolysisProducts;
}
std::vector<DatabaseReference*> Protein::getDatabaseReferences() const
{
return privateDatabaseReferences;
}
std::string Protein::getDatabaseFilePath() const
{
return privateDatabaseFilePath;
}
Protein* Protein::getNonVariantProtein() const
{
return privateNonVariantProtein;
}
std::vector<SequenceVariation*> Protein::getAppliedSequenceVariations() const
{
return privateAppliedSequenceVariations;
}
std::string Protein::getSampleNameForVariants() const
{
return privateSampleNameForVariants;
}
int Protein::getLength() const
{
return privateBaseSequence.length();
}
std::string Protein::getFullDescription() const
{
return privateAccession + "|" + privateName + "|" + privateFullName;
}
std::string Protein::getName() const
{
return privateName;
}
std::string Protein::getFullName() const
{
return privateFullName;
}
bool Protein::getIsContaminant() const
{
return privateIsContaminant;
}
std::unordered_map<int, std::vector<Modification*>> Protein::getOriginalNonVariantModifications() const
{
return privateOriginalNonVariantModifications;
}
void Protein::setOriginalNonVariantModifications(std::unordered_map<int, std::vector<Modification*>> &value)
{
privateOriginalNonVariantModifications = value;
}
#ifdef LATER
char <missing_class_definition>::operator [](int zeroBasedIndex)
{
return BaseSequence[zeroBasedIndex];
}
#endif
std::string Protein::GetUniProtFastaHeader()
{
#ifdef ORIG
auto n = privateGeneNames->FirstOrDefault();
std::string geneName = n == nullptr ? "" : n->Item2;
#endif
std::tuple<std::string, std::string> n = privateGeneNames[0];
std::string geneName = std::get<1>(n);
#ifdef ORIG
return StringHelper::formatSimple("mz|{0}|{1} {2} OS={3} GN={4}", privateAccession, privateName,
privateFullName, privateOrganism, geneName);
#endif
std::string s = "mz|" + privateAccession + "|" + privateName + " " + privateFullName + " OS=" +
privateOrganism + " GN=" + geneName;
return s;
}
std::string Protein::GetEnsemblFastaHeader()
{
return StringHelper::formatSimple("{0} {1}", privateAccession, privateFullName);
}
bool Protein::Equals(Protein *obj)
{
#ifdef ORIG
// C++ Note: this is Microsoft C++ extension not supported by g++
return __super::Equals(obj);
// Using the version from the current repository ( 07/21/2019) instead
// of the previos verions. The C# code is as follows.
// Protein otherProtein = (Protein)obj;
// return otherProtein != null && otherProtein.Accession.Equals(Accession) &&
// otherProtein.BaseSequence.Equals(BaseSequence);
#endif
return obj != nullptr &&
privateAccession == obj->getAccession() &&
privateBaseSequence == obj->getBaseSequence() ;
}
int Protein::GetHashCode()
{
#ifdef ORIG
return __super::GetHashCode();
// Using the version from the current repository (07/21/2019) instead
// of the one used by the convertor. Original C# code is as follows.
// return this.BaseSequence.GetHashCode();
#endif
return StringHelper::GetHashCode(privateBaseSequence);
}
std::vector<PeptideWithSetModifications*> Protein::Digest(DigestionParams *digestionParams,
std::vector<Modification*> &allKnownFixedModifications,
std::vector<Modification*> &variableModifications)
{
ProteinDigestion *digestion = new ProteinDigestion(digestionParams, allKnownFixedModifications,
variableModifications);
//delete digestion;
return digestionParams->getSearchModeType() == CleavageSpecificity::Semi ? digestion->SpeedySemiSpecificDigestion(this) : digestion->Digestion(this);
}
std::vector<Protein*> Protein::GetVariantProteins(int maxAllowedVariantsForCombinitorics, int minAlleleDepth)
{
return VariantApplication::ApplyVariants(this, privateSequenceVariations,
maxAllowedVariantsForCombinitorics,
minAlleleDepth);
}
void Protein::RestoreUnfilteredModifications()
{
privateOneBasedPossibleLocalizedModifications = privateOriginalNonVariantModifications;
}
std::unordered_map<int, std::vector<Modification*>> Protein::SelectValidOneBaseMods(std::unordered_map<int, std::vector<Modification*>> &dict)
{
std::unordered_map<int, std::vector<Modification*>> validModDictionary;
for (auto entry =dict.begin(); entry != dict.end(); entry++ )
{
std::vector<Modification*> validMods;
for (auto m : entry->second )
{
// mod must be valid mod and the motif of the mod must be present in the protein at the
// specified location
if (m->getValidModification() && ModificationLocalization::ModFits(m, privateBaseSequence, 0,
privateBaseSequence.length(),
entry->first))
{
validMods.push_back(m);
}
}
if (!validMods.empty())
{
if (validModDictionary.find(entry->first) != validModDictionary.end() )
{
validModDictionary[entry->first].insert(validModDictionary[entry->first].end(),
validMods.begin(), validMods.end());
}
else
{
validModDictionary.emplace(entry->first, validMods);
}
}
}
return validModDictionary;
}
std::string Protein::GetName(std::vector<SequenceVariation*> &appliedVariations, const std::string &name)
{
bool emptyVars = appliedVariations.empty() || appliedVariations.size() == 0;
if (name == "" && emptyVars)
{
return "";
}
else
{
std::string variantTag = emptyVars ? "" : StringHelper::formatSimple(" variant:{0}", VariantApplication::CombineDescriptions(appliedVariations));
return name + variantTag;
}
}
}
| [
"egabriel@central.uh.edu"
] | egabriel@central.uh.edu |
e7921764a3eec423b80566394c3b4d8a52aab00a | 6b40e9cba1dd06cd31a289adff90e9ea622387ac | /Develop/Game/DummyClient/XDummyBot_WarpField.cpp | f992faa29db4093fd0353b2d39e71d0fc7dcb487 | [] | no_license | AmesianX/SHZPublicDev | c70a84f9170438256bc9b2a4d397d22c9c0e1fb9 | 0f53e3b94a34cef1bc32a06c80730b0d8afaef7d | refs/heads/master | 2022-02-09T07:34:44.339038 | 2014-06-09T09:20:04 | 2014-06-09T09:20:04 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 6,626 | cpp | #include "StdAfx.h"
#include "XDummyBot_WarpField.h"
#include "XBirdDummyAgent.h"
#include "XDummyMaster.h"
#include "XDummyHelper.h"
#include "CCommandResultTable.h"
#include "XFieldInfo.h"
#include "MCsvParser.h"
XDummyBot_WarpField::XDummyBot_WarpField(XBirdDummyAgent* pAgent, XDummyAgentInfo* pAgentInfo)
: XDummyBot(pAgent, pAgentInfo)
, m_bPostGMInit(false)
, m_ePhase(PHASE_0_STARTING)
{
m_rgltTimeout.Stop();
m_rgltWarpDelay.Stop();
if (!InitTestFieldList())
return;
InitTestDelayTime();
}
bool XDummyBot_WarpField::InitTestFieldList()
{
wstring strFieldList = m_pAgentInfo->GetValue(L"fieldlist");
if (strFieldList.empty())
{
OnError("XDummyBot_WarpField, fieldlist attribute is empty");
return false;
}
MCsvParser csv_parser;
USES_CONVERSION_EX;
csv_parser.LoadFromStream(W2A_EX(strFieldList.c_str(), 0));
int nColCount = csv_parser.GetColCount(0);
char szBuff[1024];
for (int nCol = 0; nCol < nColCount; nCol++)
{
if (csv_parser.GetData(nCol, 0, szBuff, 1024))
{
m_vecTestFieldID.push_back(atoi(szBuff));
}
}
if (m_vecTestFieldID.empty())
{
OnError("InitTestFieldList(), Not Exist Valid FieldList");
return false;
}
return true;
}
void XDummyBot_WarpField::InitTestDelayTime()
{
/// 워프 시도할 때의 Delay Time 계산
const float DEFAULT_DELAY_WARP_SEC = 1.0f;
float fWarpDelaySec = 0.0f;
wstring strWarpDelayMS = m_pAgentInfo->GetValue(L"warp_delay_ms");
if (strWarpDelayMS.empty())
fWarpDelaySec = DEFAULT_DELAY_WARP_SEC;
else
fWarpDelaySec = (0.001f * _wtoi(strWarpDelayMS.c_str()));
m_rgltWarpDelay.SetTickTime(fWarpDelaySec);
/// 워프 체크 대기 Timeout
const float DEFAULT_TIMEOUT_WARP_SEC = 300.0f;
float fWarpTimeoutSec = 0.0f;
wstring strWarpTimeoutMS = m_pAgentInfo->GetValue(L"warp_timeout_ms");
if (strWarpTimeoutMS.empty())
fWarpTimeoutSec = DEFAULT_TIMEOUT_WARP_SEC;
else
fWarpTimeoutSec = (0.001f * _wtoi(strWarpTimeoutMS.c_str()));
m_rgltTimeout.SetTickTime(fWarpTimeoutSec);
}
void XDummyBot_WarpField::OnRun(float fDelta)
{
if (XBirdDummyAgent::DAS_ERROR == m_pAgent->GetStatus()) return;
if (m_bPostGMInit == false)
{
XBIRDPOSTCMD2(m_pAgent->GetClient(), MC_GM_SET_ME_REQ, MCommandParameterWideString(L"grade"), MCommandParameterWideString(L"3"));
XBIRDPOSTCMD0(m_pAgent->GetClient(), MC_GM_GOD_REQ);
m_bPostGMInit = true;
}
switch (GetPhase())
{
case PHASE_1_WARP: OnRun_Warp(fDelta); return;
case PHASE_2_CHECK: OnRun_Check(fDelta); return;
}
}
void XDummyBot_WarpField::OnRun_Warp(float fDelta)
{
if (m_rgltWarpDelay.IsActive() && !m_rgltWarpDelay.IsReady(fDelta))
return;
m_rgltWarpDelay.Stop();
int nIgnoreFieldID = m_pAgent->GetLoginFieldID();
int nFieldID = XDummyHelper::GetRandomIDFromList(m_vecTestFieldID, nIgnoreFieldID);
if (nFieldID == INVALID_ID)
{
OnError("Random FieldID is INVALID!");
return;
}
XBirdClient* pClient = m_pAgent->GetClient();
XBIRDPOSTCMD2(pClient, MC_GM_MOVE_REQ, MCommandParameterInt(nFieldID), MCommandParameterVector(m_pAgent->GetCenter()));
SetPhase(PHASE_2_CHECK);
m_stExpectedDestInfo.nFieldID = nFieldID;
m_pAgent->SetLoginField(0, 0, m_pAgent->GetCenter());
StartTimeoutTimer();
}
void XDummyBot_WarpField::OnRun_Check(float fDelta)
{
if (m_rgltTimeout.IsActive() && m_rgltTimeout.IsReady(fDelta))
{
char szLog[512]="";
sprintf_s(szLog, 512, "Timeout! (PreFieldID=%d, DestFieldID=%d, Delta=%f)"
, m_pAgent->GetPreStayFieldID(), m_stExpectedDestInfo.nFieldID, fDelta);
OnError(szLog);
return;
}
return;
}
void XDummyBot_WarpField::OnError(string strLog)
{
m_pAgent->SetStatusError();
char szErrorLog[1024] = {0};
sprintf_s(szErrorLog, 1024, "(%S) XDummyBot_WarpField::OnError(), %s\n", m_pAgent->GetLoginID(), strLog.c_str());
mlog3(szErrorLog);
}
//////////////////////////////////////////////////////////////////////////
/// Command Handler
MCommandResult XDummyBot_WarpField::OnCommand(XBirdDummyAgent* pAgent, MCommand* pCmd)
{
XDummyBot::OnCommand(pAgent, pCmd);
XBirdClient* pClient = pAgent->GetClient();
switch(pCmd->GetID())
{
case MC_FIELD_CHANGE_FIELD: return OnFieldChangeField(pAgent, pClient, pCmd);
case MC_FIELD_START_GAME: return OnFieldStartGame(pAgent, pClient, pCmd);
case MC_FIELD_CANCEL_CHANGE_FIELD: return OnFieldCancelChangeField(pAgent, pClient, pCmd);
}
return CR_FALSE;
}
MCommandResult XDummyBot_WarpField::OnFieldChangeField(XBirdDummyAgent* pAgent, XBirdClient* pClient, MCommand* pCmd)
{
if (PHASE_2_CHECK != GetPhase()) return CR_FALSE;
if (INVALID_ID == m_stExpectedDestInfo.nFieldID) return CR_FALSE;
if (XBirdDummyAgent::DAS_ERROR == pAgent->GetStatus())
{
pAgent->SetStatusRunning();
char szrLog[1024] = {0};
sprintf_s(szrLog, 1024, "(%S) XDummyBot_WarpField::OnFieldStartGame(), Restoration!\n", m_pAgent->GetLoginID());
mlog3(szrLog);
}
int nFieldID;
if (!pCmd->GetParameter(&nFieldID, 0, MPT_INT)) return CR_ERROR;
if (m_stExpectedDestInfo.nFieldID != nFieldID)
{
char szLog[512]="";
sprintf_s(szLog, 512, "Failed! Not Matched Result Field, Current=%d, Expect=%d, Result=%d"
, m_pAgent->GetPreStayFieldID(), m_stExpectedDestInfo.nFieldID, nFieldID);
OnError(szLog);
}
m_stExpectedDestInfo.Reset();
StopTimeoutTimer();
return CR_FALSE;
}
MCommandResult XDummyBot_WarpField::OnFieldStartGame(XBirdDummyAgent* pAgent, XBirdClient* pClient, MCommand* pCmd)
{
if (XBirdDummyAgent::DAS_ERROR == pAgent->GetStatus())
{
pAgent->SetStatusRunning();
char szrLog[1024] = {0};
sprintf_s(szrLog, 1024, "(%S) XDummyBot_WarpField::OnFieldStartGame(), Restoration!\n", m_pAgent->GetLoginID());
mlog3(szrLog);
}
SetPhase(PHASE_1_WARP);
m_rgltWarpDelay.Start();
return CR_TRUE;
}
MCommandResult XDummyBot_WarpField::OnFieldCancelChangeField(XBirdDummyAgent* pAgent, XBirdClient* pClient, MCommand* pCmd)
{
pAgent->SetStatusRunning();
char szrLog[1024] = {0};
sprintf_s(szrLog, 1024, "(%S) XDummyBot_WarpField::OnFieldCancelChangeField()\n", m_pAgent->GetLoginID());
mlog3(szrLog);
SetPhase(PHASE_1_WARP);
m_rgltWarpDelay.Start();
return CR_TRUE;
}
//////////////////////////////////////////////////////////////////////////
void XDummyBot_WarpField::StartTimeoutTimer()
{
m_rgltTimeout.Start();
}
void XDummyBot_WarpField::StopTimeoutTimer()
{
m_rgltTimeout.Stop();
}
void XDummyBot_WarpField::SetPhase(BOT_PHASE ePhase)
{
m_ePhase = ePhase;
} | [
"shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4"
] | shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4 |
7264ff935bcc656938f0d66ae6ec135670c6b5a3 | 9c6fe966772eb3bf240b4f344001f086a4261612 | /POV_Display.ino | f55db35fd8a593b340a9fe9790874fb11b49c707 | [] | no_license | danielj-n/POV-Display | c4cee4672f7fa2a9fc7cc650281cecc560d7a19c | f86484042eff9c51f3cb738f70e1ed2c455bd5d0 | refs/heads/master | 2021-05-10T11:04:29.445660 | 2018-01-22T03:37:20 | 2018-01-22T03:37:20 | 118,400,577 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,195 | ino | #include <SPI.h>
#include <WiFi101.h>
#include <WiFiUdp.h>
unsigned long timeToGoAround = 9000;
int currentByte = 0;
int currentFrame = 0;
int currentImage = 0;
byte numOfImages = 1;
byte FPR = 90;
byte pauseTime = 0;
byte*** Images;
byte* inputBuffer;
char ssid[] = "(SSID)";
char pass[] = "(PASSORD)";
unsigned int port = 1337;
WiFiUDP Udp;
void setup() {
Serial.begin(9600);
int status = WL_IDLE_STATUS;
while ( status != WL_CONNECTED) {
status = WiFi.begin(ssid, pass);
Serial.println("Trying to connect...");
delay(10000);
}
IPAddress ip = WiFi.localIP();
Serial.println(ip);
Udp.begin(1337);
// ARM C for timer setup
REG_GCLK_CLKCTRL = (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID_TCC0_TCC1) ;
while ( GCLK->STATUS.bit.SYNCBUSY == 1 );
TCC0->CTRLA.reg |= TCC_CTRLA_PRESCALER_DIV256;
TCC0->CTRLA.reg |= TCC_CTRLA_PRESCSYNC_RESYNC;
TCC0->WAVE.reg |= TCC_WAVE_WAVEGEN_MFRQ;
while (TCC0->SYNCBUSY.bit.WAVE == 1);
TCC0->CC[0].reg = 46875 / 3;
while (TCC0->SYNCBUSY.bit.CC0 == 1);
TCC0->INTENSET.reg = 0;
TCC0->INTENSET.bit.MC0 = 1;
NVIC_EnableIRQ(TCC0_IRQn);
TCC1->CTRLA.reg |= TCC_CTRLA_PRESCALER_DIV256;
TCC1->CTRLA.reg |= TCC_CTRLA_PRESCSYNC_RESYNC;
TCC1->WAVE.reg |= TCC_WAVE_WAVEGEN_MFRQ;
while (TCC1->SYNCBUSY.bit.WAVE == 1);
TCC1->CC[0].reg = 46875 / 2;
while (TCC1->SYNCBUSY.bit.CC0 == 1);
TCC1->INTENSET.reg = 0;
TCC1->INTENSET.bit.MC0 = 1;
NVIC_EnableIRQ(TCC1_IRQn);
REG_GCLK_CLKCTRL = (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID_TCC2_TC3) ;
while ( GCLK->STATUS.bit.SYNCBUSY == 1 );
TCC2->CTRLA.reg |= TCC_CTRLA_PRESCALER_DIV256;
TCC2->CTRLA.reg |= TCC_CTRLA_PRESCSYNC_RESYNC;
TCC2->WAVE.reg |= TCC_WAVE_WAVEGEN_MFRQ;
while (TCC2->SYNCBUSY.bit.WAVE == 1);
TCC2->CC[0].reg = 0;
while (TCC2->SYNCBUSY.bit.CC0 == 1);
TCC2->INTENSET.reg = 0;
TCC2->INTENSET.bit.MC0 = 1;
NVIC_EnableIRQ(TCC2_IRQn);
// End of ARM C for timer setup
for (int pin = 0; pin < 6; pin++) {
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
}
Images = new byte**[numOfImages];
for (int image = 0; image < numOfImages; image++) {
Images[image] = new byte*[FPR];
for (int pos = 0; pos < FPR; pos++) {
Images[image][pos] = new byte[6];
for (int value = 0; value < 6; value++) {
Images[image][pos][value]= 0;
}
}
}
inputBuffer = new byte[256];
for (int b = 0; b < 256; b++) {
inputBuffer[b] = 0;
}
SPI.begin();
SPI.beginTransaction(SPISettings(1000000, LSBFIRST, SPI_MODE0));
attachInterrupt(6, reset, FALLING);
}
void enableTimers() {
TCC0->CTRLA.reg |= TCC_CTRLA_ENABLE ;
while (TCC0->SYNCBUSY.bit.ENABLE == 1);
TCC1->CTRLA.reg |= TCC_CTRLA_ENABLE ;
while (TCC1->SYNCBUSY.bit.ENABLE == 1);
TCC2->CTRLA.reg |= TCC_CTRLA_ENABLE ;
while (TCC2->SYNCBUSY.bit.ENABLE == 1);
attachInterrupt(6, reset, FALLING);
}
void disableTimers() {
TCC0->CTRLA.bit.ENABLE = 0;
while (TCC0->SYNCBUSY.bit.ENABLE == 1);
TCC1->CTRLA.bit.ENABLE = 0;
while (TCC1->SYNCBUSY.bit.ENABLE == 1);
TCC2->CTRLA.bit.ENABLE = 0;
while (TCC2->SYNCBUSY.bit.ENABLE == 1);
detachInterrupt(6);
}
void TCC0_Handler() {
if (currentFrame == FPR) {
currentFrame = 0;
}
outputData(Images[currentImage][currentFrame]);
currentFrame++;
TCC0->INTFLAG.bit.MC0 = 1;
}
void TCC1_Handler() {
if (currentImage == numOfImages - 1) {
currentImage = 0;
}
else {
currentImage++;
}
TCC1->INTFLAG.bit.MC0 = 1;
}
void TCC2_Handler() {
timeToGoAround++;
TCC2->INTFLAG.bit.MC0 = 1;
}
void outputData(byte* data) {
for (int dataNum = 0; dataNum < 6; ++dataNum) {
digitalWrite(dataNum, HIGH);
SPI.transfer(data[dataNum]);
digitalWrite(dataNum, LOW);
}
}
void reset() {
TCC0->CTRLBSET.reg |= TCC_CTRLBSET_CMD_RETRIGGER;
TCC0->CC[0].reg = timeToGoAround / FPR + 48000000 / 256 / 14 / 900;
currentFrame = 0;
TCC2->CTRLBSET.reg |= TCC_CTRLBSET_CMD_RETRIGGER;
timeToGoAround = 0;
}
void awaitNextPacketByte() {
int packetSize = Udp.parsePacket();
while (true) {
packetSize = Udp.parsePacket();
if (packetSize)
{
disableTimers();
delete(inputBuffer);
inputBuffer = new byte[256];
Udp.read(inputBuffer, 256);
break;
}
}
}
void deleteOldImages() {
for (int image = 0; image < numOfImages; image++) {
for (int pos = 0; pos < FPR; pos++) {
delete(Images[image][pos]);
}
delete(Images[image]);
}
delete(Images);
}
void getImages() {
awaitNextPacketByte();
deleteOldImages();
FPR = inputBuffer[0];
TCC0->CC[1].reg = (int)(48000000 * (((double)inputBuffer[1] + 1.0) / 128) / 1024);
numOfImages = inputBuffer[2];
int dataNum = 2;
Images = new byte**[numOfImages];
for (int image = 0; image < numOfImages; image++) {
Images[image] = new byte*[FPR];
for (int pos = 0; pos < FPR; pos++) {
Images[image][pos] = new byte[6];
}
}
for (int image = 0; image < numOfImages; image++) {
for (int pos = 0; pos < FPR; pos++) {
for (int value = 0; value < 6; value++) {
dataNum++;
if (dataNum == 256) {
dataNum = 0;
awaitNextPacketByte();
}
Images[image][pos][value] = inputBuffer[dataNum];
}
}
}
enableTimers();
}
void loop() {
while (true) {
getImages();
}
}
| [
"noreply@github.com"
] | noreply@github.com |
74dde971a5d961a82ccfefef9532cb12e0b1e778 | c0caed81b5b3e1498cbca4c1627513c456908e38 | /src/numeric/kdtree/KDTree.hh | 641d8644f8c58fdcc56b131b15cbe1699a43650b | [] | no_license | malaifa/source | 5b34ac0a4e7777265b291fc824da8837ecc3ee84 | fc0af245885de0fb82e0a1144422796a6674aeae | refs/heads/master | 2021-01-19T22:10:22.942155 | 2017-04-19T14:13:07 | 2017-04-19T14:13:07 | 88,761,668 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,782 | hh | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington UW TechTransfer, email: license@u.washington.edu.
/// @file numeric/kdtree/KDTree.hh
/// @brief Implementation of a tree in a kd-tree. See numeric/kdtree/kdtree.hh
/// for more information.
/// @author James Thompson
//
#ifndef INCLUDED_numeric_kdtree_KDTree_hh
#define INCLUDED_numeric_kdtree_KDTree_hh
#include <numeric/types.hh>
#include <numeric/kdtree/KDNode.fwd.hh>
#include <numeric/kdtree/KDTree.fwd.hh>
#include <numeric/kdtree/HyperRectangle.hh>
#include <numeric/kdtree/HyperRectangle.fwd.hh>
#include <utility/vector1.hh>
#include <utility/pointer/ReferenceCount.fwd.hh>
namespace numeric {
namespace kdtree {
class KDTree : public utility::pointer::ReferenceCount {
public:
/// @brief Automatically generated virtual destructor for class deriving directly from ReferenceCount
virtual ~KDTree();
/// @brief Empty constructor.
KDTree();
/// @brief Constructs a balanced kd-tree from the set of k-dimensional
/// input points.
KDTree(
utility::vector1< utility::vector1< numeric::Real > > & pts
);
KDTree(
utility::vector1< utility::vector1< numeric::Real > > & pts,
utility::vector1< utility::pointer::ReferenceCountOP > & data
);
/// @brief Number of points in the kd-tree.
numeric::Size size() const;
/// @brief Number of dimensions in the kd-tree. This is the "k" in kd.
numeric::Size ndim() const;
/// @brief Returns the KDNodeOP that is the root of the balanced kd-tree.
KDNodeOP root() const;
/// @brief Returns the HyperRectangle that bounds all of the points in the
/// kd-tree.
/// @details A HyperRectangle is defined as two vectors upper and lower, with
/// each dimension of lower having the minimum value seen in each dimension,
/// and each dimension of higher having the maximum value seen in each
/// dimension.
HyperRectangleOP bounds() const;
/// @brief Sets the number of points in this kd-tree.
void size( numeric::Size new_size );
/// @brief Sets the root of the kd-tree.
void root( KDNodeOP new_root );
/// @brief Pushes out the bounds of the HyperRectangle bounding this kd-tree
/// if necessary.
void extend_bounds( utility::vector1< numeric::Real > const & pt );
private:
numeric::Size size_;
KDNodeOP root_;
HyperRectangleOP bounds_;
}; // class KDTree
} // kdtree
} // numeric
#endif
| [
"malaifa@yahoo.com"
] | malaifa@yahoo.com |
2e75f933d16b6284ccb8c221c6dd2fa817a9ad72 | 75149a083591df706166e5849e1480ee665be039 | /multiThreadCalc.cpp | 527f2bbdc2ad36965de1a38fe297b67906936b39 | [] | no_license | BlackLuny/MyCode | f89917ee1766fe3567f7e6f0798c9ee3d56e2502 | 40be241725453ec7d307cab96d1d4b3c71fbce6e | refs/heads/master | 2021-01-22T01:18:06.280538 | 2018-07-19T01:00:54 | 2018-07-19T01:00:54 | 102,215,616 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,514 | cpp | #include <iostream>
#include <vector>
#include <string>
#include <list>
#include <set>
#include <map>
#include <sstream>
using namespace std;
class calc;
template <class T>
string ouput_pack(vector<T> &vec,string op)
{
ostringstream os;
for (int i = 0; i < vec.size(); ++i)
{
if (i!=0)
os<<op<<vec[i];
else
os<<vec[i];
}
return os.str();
}
bool cmp_vec(const vector<int> &lh, const vector<int> &rh)
{
if (lh.size() == rh.size())
{
for (int i = 0; i < lh.size(); ++i)
{
if (lh[i] < rh[i])
return true;
if (lh[i] > rh[i])
return false;
}
}else{
return lh.size() < rh.size();
}
return false; //完全相同
}
class calc
{
public:
calc():cap_add(1),cap_mul(1){};
void input(const char *str)
{
vector<string> tmp;
split(str, "+", tmp);
for (int i = 0; i < tmp.size(); ++i)
{
string tmp_s = tmp[i];
if (tmp_s.length() == 1)
{
//add
vec_org_add.push_back(*tmp_s.c_str() - '0');
//cout << *tmp_s.c_str() - '0' << endl;
}else{
const char *tmp_c_str = tmp_s.c_str();
vector<int> tmp_vec;
while(*tmp_c_str!='\0')
{ char tmp_char = *tmp_c_str;
if (tmp_char >= '0' && tmp_char <= '9')
tmp_vec.push_back(*tmp_c_str - '0');
tmp_c_str++;
}
sort(tmp_vec.begin(), tmp_vec.end());
vec_org_mul.push_back(tmp_vec);
}
}
sort(vec_org_add.begin(), vec_org_add.end());
sort(vec_org_mul.begin(), vec_org_mul.end(),cmp_vec);
}
void setCapability(unsigned int n, unsigned int m)
{
cap_add = n;
cap_mul = m;
}
int GetRoundResult(unsigned int Round, char*output)
{
string res;
vec_add = vec_org_add;
vec_mul = vec_org_mul;
for (int i = 0; i < Round; ++i)
{
op_add();op_mul();
if (i == Round - 1)
res = this->output();
update_vec();
}
strcpy(output,res.c_str());
}
unsigned int GetRound(void)
{
vec_add = vec_org_add;
vec_mul = vec_org_mul;
unsigned int res = 1;
while(vec_add.size() != 1){
op_add();op_mul();update_vec();
res++;
}
return res;
}
void Clear()
{
vec_org_add.clear();
vec_org_mul.clear();
cap_add = 1;
cap_mul = 1;
}
private:
unsigned int cap_add;
unsigned int cap_mul;
vector<int> vec_add,vec_org_add;
vector< vector<int> > vec_mul,vec_org_mul;
void op_add()
{
vector<int> tmp_vec = vec_add;
size_t vec_size = tmp_vec.size();
int cnt = min(cap_add,vec_size/2);
if (cnt == 0) return;
vec_add.clear();
for (int i = 0; i < cnt; ++i)
{
int a = tmp_vec[2*i];
int b = tmp_vec[2*i+1];
vec_add.push_back(a+b);
//i++;//跳过下一个
}
//将后面没有参与运算的还原
for (int i = cnt*2; i < vec_size; ++i)
{
vec_add.push_back(tmp_vec[i]);
}
}
//对一个乘法组的元素进行一次乘法运算
void op_mul_per(vector<int> &sub_mul)
{
vector<int> tmp_vec = sub_mul;
size_t vec_size = tmp_vec.size();
int cnt = min(1,vec_size/2);
if (cnt == 0) return;
sub_mul.clear();
for (int i = 0; i < cnt; ++i)
{
int a = tmp_vec[2*i];
int b = tmp_vec[2*i+1];
sub_mul.push_back(a*b);
}
//将后面没有参与运算的还原
for (int i = 2 * cnt; i < vec_size; ++i)
{
sub_mul.push_back(tmp_vec[i]);
}
}
void op_mul()
{
vector< vector<int> > tmp_vec = vec_mul;
size_t vec_size = tmp_vec.size();
int cnt = min(cap_mul,vec_size);
if (cnt == 0) return;
vec_mul.clear();
for (int i = 0; i < cnt; ++i)
{
op_mul_per(tmp_vec[i]);
vec_mul.push_back(tmp_vec[i]);
}
//将后面没有参与运算的还原
for (int i = cnt; i < vec_size; ++i)
{
vec_mul.push_back(tmp_vec[i]);
}
}
string output()
{
vector<string> tmp_vec;
ostringstream os;
//先填写加法的
for (int i = 0; i < vec_add.size(); ++i)
{
os<<vec_add[i];
tmp_vec.push_back(os.str());
//cout << os.str() << endl;
os.str("");
}
//再填写乘法的
for (int i = 0; i < vec_mul.size(); ++i)
{
os<<ouput_pack<int>(vec_mul[i],"*");
tmp_vec.push_back(os.str());
os.str("");
}
return ouput_pack<string>(tmp_vec,"+");
}
//如果乘法运算之后只剩1个数,则将这个数放到加法运算符里面去,同时进行排序操作,准备进行下一次运算
void update_vec()
{
vector< vector<int> >::iterator itr;
for (itr = vec_mul.begin(); itr != vec_mul.end(); )
{
if ((*itr).size() == 1)
{
vec_add.push_back((*itr)[0]);
itr = vec_mul.erase(itr);
continue;
}
sort(((*itr)).begin(),(*itr).end());
itr++;
}
sort(vec_add.begin(), vec_add.end());
sort(vec_mul.begin(), vec_mul.end(),cmp_vec);
//show_vec_add();show_vec_mul();
}
int min(const int a, const int b)
{
return a < b ? a : b;
}
void split(const char *str, char *sp, vector<string> &vec_out)
{
vec_out.clear();
string tmp = str;
int index = 0;
size_t len = tmp.size();
while (index < len)
{
int index_next = tmp.find_first_of(sp,index);
if (index_next == -1)
{
vec_out.push_back(tmp.substr(index, len - index));
break;
}
else{
vec_out.push_back(tmp.substr(index, index_next - index));
}
index = index_next + 1;
}
}
};
calc g_calc;
void setCapability(unsigned int N, unsigned int M)
{
g_calc.setCapability(N, M);
}
void setInput(const char* input)
{
g_calc.input(input);
}
unsigned int GetRound(void)
{
return g_calc.GetRound();
}
void Clear()
{
g_calc.Clear();
}
int main()
{
setCapability(2,2);
setInput("1+8+3*4+5*6*7+9*2+7*8*9*3+2");
char str[256] = {0};
for (int i = 0; i < GetRound(); ++i)
{
g_calc.GetRoundResult(i,str);
cout << str<<endl;
}
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
8cb5f5e0d004480d4d539217205617f8fd227679 | e1f96e7f7420ab6b8278b5d928f7dacd09fcff55 | /inc/logger.h | fc73c77278ea805accae9e4d74a27e2595e2ff2b | [] | no_license | sgh1/dev-lib | 42083df8ad560586dc0975d0b837c425899e57c9 | 68681f04780fdba2b02ab89afabff1c1b3a3c31e | refs/heads/master | 2021-08-16T02:43:47.466637 | 2017-11-18T21:31:15 | 2017-11-18T21:31:15 | 111,161,020 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,284 | h |
//
// Logger adapted from Dr. Dobbs article, "A Lightweight Logger for C++",
// By Filip Janiszewski, January 31, 2013
//
#ifndef LOGGING_H_
#define LOGGING_H_
#include <memory>
#include <mutex>
#include <string>
namespace devlib
{
namespace logging
{
// Interface for logging policies.
class log_policy_interface
{
public:
virtual void open_ostream(const std::string& name) = 0;
virtual void close_ostream() = 0;
virtual void write(const std::string& msg) = 0;
};
// Implementation which allow to write into a file.
class file_log_policy : public log_policy_interface
{
std::unique_ptr< std::ofstream > out_stream;
public:
file_log_policy() : out_stream( new std::ofstream ) {}
void open_ostream(const std::string& name);
void close_ostream();
void write(const std::string& msg);
~file_log_policy();
};
// Implementation which allow to write to stdout.
class console_log_policy : public log_policy_interface
{
public:
void open_ostream(const std::string& name);
void close_ostream();
void write(const std::string& msg);
};
// Severity level.
enum severity_type
{
debug = 1,
message,
error,
warning
};
// Main logger template.
template< typename log_policy >
class logger
{
unsigned log_line_number;
// Creates timestamp string.
std::string get_time()
{
std::string time_str;
time_t raw_time;
time( & raw_time );
time_str = ctime( &raw_time );
//without the newline character
return time_str.substr( 0 , time_str.size() - 1 );
}
// Build the first part of the log entry (line no. + timestamp).
std::string get_logline_header()
{
std::stringstream header;
header.str("");
header.fill('0');
header.width(7);
header << log_line_number++ <<" < "<<get_time()<<" - ";
header.fill('0');
header.width(7);
header <<clock()<<" > ~ ";
return header.str();
}
std::stringstream log_stream;
log_policy* policy;
std::mutex write_mutex;
//Core printing functionality
void print_impl()
{
policy->write( get_logline_header() + log_stream.str() );
log_stream.str("");
}
template<typename First, typename...Rest >
void print_impl(First parm1, Rest...parm)
{
log_stream<<parm1;
print_impl(parm...);
}
public:
logger( const std::string& name );
template< typename...Args >
void print( Args...args )
{
write_mutex.lock();
switch( severity )
{
case severity_type::debug:
log_stream<<"<DEBUG> :";
break;
case severity_type::message:
log_stream<<"<MESSAGE> :";
break;
case severity_type::warning:
log_stream<<"<WARNING> :";
break;
case severity_type::error:
log_stream<<"<ERROR> :";
break;
};
print_impl( args... );
write_mutex.unlock();
}
~logger();
};
}
}
// ?? We might need to use a scheme like boost::logger.
//static logging::logger< logging::file_log_policy > log_inst( "execution.log" );
static logging::logger< logging::console_log_policy > log_inst( "" );
#define LOG log_inst.print< logging::severity_type::debug >
#define LOG_ERR log_inst.print< logging::severity_type::error >
#define LOG_WARN log_inst.print< logging::severity_type::warning >
#endif | [
"sean@my.desk"
] | sean@my.desk |
ded08e5ec6c8d6f1f345d40335c3a29228c1943a | 9b353d433c44caad3709c45cb762f271ffeeb2b7 | /Dependencies/SFML/linux/include/SFML/Graphics/VertexBuffer.hpp | fc3ab1fac82a4041722c709cddfd59a0db798f17 | [] | no_license | igobrado/Memory | bc281ce1916f4c9cd8b8b93103bd961a8a104690 | 272d907440bed6e0917f7b4fdf203256da4e0e63 | refs/heads/master | 2023-06-06T07:03:36.226040 | 2021-06-28T10:44:46 | 2021-06-28T10:44:46 | 380,996,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,789 | hpp | ////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2018 Laurent Gomila (laurent@sfml-dev.org)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_VERTEXBUFFER_HPP
#define SFML_VERTEXBUFFER_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/PrimitiveType.hpp>
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Window/GlResource.hpp>
namespace sf
{
class RenderTarget;
class Vertex;
////////////////////////////////////////////////////////////
/// \brief Vertex buffer storage for one or more 2D primitives
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API VertexBuffer : public Drawable, private GlResource
{
public:
////////////////////////////////////////////////////////////
/// \brief Usage specifiers
///
/// If data is going to be updated once or more every frame,
/// set the usage to Stream. If data is going to be set once
/// and used for a long time without being modified, set the
/// usage to Static. For everything else Dynamic should be a
/// good compromise.
///
////////////////////////////////////////////////////////////
enum Usage
{
Stream, ///< Constantly changing data
Dynamic, ///< Occasionally changing data
Static ///< Rarely changing data
};
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Creates an empty vertex buffer.
///
////////////////////////////////////////////////////////////
VertexBuffer();
////////////////////////////////////////////////////////////
/// \brief Construct a VertexBuffer with a specific PrimitiveType
///
/// Creates an empty vertex buffer and sets its primitive type to \p type.
///
/// \param type Type of primitive
///
////////////////////////////////////////////////////////////
explicit VertexBuffer(PrimitiveType type);
////////////////////////////////////////////////////////////
/// \brief Construct a VertexBuffer with a specific usage specifier
///
/// Creates an empty vertex buffer and sets its usage to \p usage.
///
/// \param usage Usage specifier
///
////////////////////////////////////////////////////////////
explicit VertexBuffer(Usage usage);
////////////////////////////////////////////////////////////
/// \brief Construct a VertexBuffer with a specific PrimitiveType and usage specifier
///
/// Creates an empty vertex buffer and sets its primitive type
/// to \p type and usage to \p usage.
///
/// \param type Type of primitive
/// \param usage Usage specifier
///
////////////////////////////////////////////////////////////
VertexBuffer(PrimitiveType type, Usage usage);
////////////////////////////////////////////////////////////
/// \brief Copy constructor
///
/// \param copy instance to copy
///
////////////////////////////////////////////////////////////
VertexBuffer(const VertexBuffer& copy);
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
~VertexBuffer();
////////////////////////////////////////////////////////////
/// \brief Create the vertex buffer
///
/// Creates the vertex buffer and allocates enough graphics
/// memory to hold \p vertexCount vertices. Any previously
/// allocated memory is freed in the process.
///
/// In order to deallocate previously allocated memory pass 0
/// as \p vertexCount. Don't forget to recreate with a non-zero
/// value when graphics memory should be allocated again.
///
/// \param vertexCount Number of vertices worth of memory to allocate
///
/// \return True if creation was successful
///
////////////////////////////////////////////////////////////
bool create(std::size_t vertexCount);
////////////////////////////////////////////////////////////
/// \brief Return the vertex count
///
/// \return Number of vertices in the vertex buffer
///
////////////////////////////////////////////////////////////
std::size_t getVertexCount() const;
////////////////////////////////////////////////////////////
/// \brief update the whole buffer from an array of vertices
///
/// The \a vertex array is assumed to have the same size as
/// the \a created buffer.
///
/// No additional check is performed on the size of the vertex
/// array, passing invalid arguments will lead to undefined
/// behavior.
///
/// This function does nothing if \a vertices is null or if the
/// buffer was not previously created.
///
/// \param vertices Array of vertices to copy to the buffer
///
/// \return True if the update was successful
///
////////////////////////////////////////////////////////////
bool update(const Vertex* vertices);
////////////////////////////////////////////////////////////
/// \brief update a part of the buffer from an array of vertices
///
/// \p offset is specified as the number of vertices to skip
/// from the beginning of the buffer.
///
/// If \p offset is 0 and \p vertexCount is equal to the size of
/// the currently created buffer, its whole contents are replaced.
///
/// If \p offset is 0 and \p vertexCount is greater than the
/// size of the currently created buffer, a new buffer is created
/// containing the vertex data.
///
/// If \p offset is 0 and \p vertexCount is less than the size of
/// the currently created buffer, only the corresponding region
/// is updated.
///
/// If \p offset is not 0 and \p offset + \p vertexCount is greater
/// than the size of the currently created buffer, the update fails.
///
/// No additional check is performed on the size of the vertex
/// array, passing invalid arguments will lead to undefined
/// behavior.
///
/// \param vertices Array of vertices to copy to the buffer
/// \param vertexCount Number of vertices to copy
/// \param offset Offset in the buffer to copy to
///
/// \return True if the update was successful
///
////////////////////////////////////////////////////////////
bool update(const Vertex* vertices, std::size_t vertexCount, unsigned int offset);
////////////////////////////////////////////////////////////
/// \brief Copy the contents of another buffer into this buffer
///
/// \param vertexBuffer Vertex buffer whose contents to copy into this vertex buffer
///
/// \return True if the copy was successful
///
////////////////////////////////////////////////////////////
bool update(const VertexBuffer& vertexBuffer);
////////////////////////////////////////////////////////////
/// \brief Overload of assignment operator
///
/// \param right Instance to assign
///
/// \return Reference to self
///
////////////////////////////////////////////////////////////
VertexBuffer& operator =(const VertexBuffer& right);
////////////////////////////////////////////////////////////
/// \brief Swap the contents of this vertex buffer with those of another
///
/// \param right Instance to swap with
///
////////////////////////////////////////////////////////////
void swap(VertexBuffer& right);
////////////////////////////////////////////////////////////
/// \brief Get the underlying OpenGL handle of the vertex buffer.
///
/// You shouldn't need to use this function, unless you have
/// very specific stuff to implement that SFML doesn't support,
/// or implement a temporary workaround until a bug is fixed.
///
/// \return OpenGL handle of the vertex buffer or 0 if not yet created
///
////////////////////////////////////////////////////////////
unsigned int getNativeHandle() const;
////////////////////////////////////////////////////////////
/// \brief Set the type of primitives to draw
///
/// This function defines how the vertices must be interpreted
/// when it's time to draw them.
///
/// The default primitive type is sf::Points.
///
/// \param type Type of primitive
///
////////////////////////////////////////////////////////////
void setPrimitiveType(PrimitiveType type);
////////////////////////////////////////////////////////////
/// \brief Get the type of primitives drawn by the vertex buffer
///
/// \return Primitive type
///
////////////////////////////////////////////////////////////
PrimitiveType getPrimitiveType() const;
////////////////////////////////////////////////////////////
/// \brief Set the usage specifier of this vertex buffer
///
/// This function provides a hint about how this vertex buffer is
/// going to be used in terms of data update frequency.
///
/// After changing the usage specifier, the vertex buffer has
/// to be updated with new data for the usage specifier to
/// take effect.
///
/// The default primitive type is sf::VertexBuffer::Stream.
///
/// \param usage Usage specifier
///
////////////////////////////////////////////////////////////
void setUsage(Usage usage);
////////////////////////////////////////////////////////////
/// \brief Get the usage specifier of this vertex buffer
///
/// \return Usage specifier
///
////////////////////////////////////////////////////////////
Usage getUsage() const;
////////////////////////////////////////////////////////////
/// \brief Bind a vertex buffer for rendering
///
/// This function is not part of the graphics API, it mustn't be
/// used when drawing SFML entities. It must be used only if you
/// mix sf::VertexBuffer with OpenGL code.
///
/// \code
/// sf::VertexBuffer vb1, vb2;
/// ...
/// sf::VertexBuffer::bind(&vb1);
/// // draw OpenGL stuff that use vb1...
/// sf::VertexBuffer::bind(&vb2);
/// // draw OpenGL stuff that use vb2...
/// sf::VertexBuffer::bind(NULL);
/// // draw OpenGL stuff that use no vertex buffer...
/// \endcode
///
/// \param vertexBuffer Pointer to the vertex buffer to bind, can be null to use no vertex buffer
///
////////////////////////////////////////////////////////////
static void bind(const VertexBuffer* vertexBuffer);
////////////////////////////////////////////////////////////
/// \brief Tell whether or not the system supports vertex buffers
///
/// This function should always be called before using
/// the vertex buffer features. If it returns false, then
/// any attempt to use sf::VertexBuffer will fail.
///
/// \return True if vertex buffers are supported, false otherwise
///
////////////////////////////////////////////////////////////
static bool isAvailable();
private:
////////////////////////////////////////////////////////////
/// \brief draw the vertex buffer to a render target
///
/// \param target Render target to draw to
/// \param states Current render states
///
////////////////////////////////////////////////////////////
virtual void draw(RenderTarget& target, RenderStates states) const;
private:
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
unsigned int m_buffer; ///< Internal buffer identifier
std::size_t m_size; ///< Size in Vertexes of the currently allocated buffer
PrimitiveType m_primitiveType; ///< Type of primitives to draw
Usage m_usage; ///< How this vertex buffer is to be used
};
} // namespace sf
#endif // SFML_VERTEXBUFFER_HPP
////////////////////////////////////////////////////////////
/// \class sf::VertexBuffer
/// \ingroup graphics
///
/// sf::VertexBuffer is a simple wrapper around a dynamic
/// buffer of vertices and a primitives type.
///
/// Unlike sf::VertexArray, the vertex data is stored in
/// graphics memory.
///
/// In situations where a large amount of vertex data would
/// have to be transferred from system memory to graphics memory
/// every frame, using sf::VertexBuffer can help. By using a
/// sf::VertexBuffer, data that has not been changed between frames
/// does not have to be re-transferred from system to graphics
/// memory as would be the case with sf::VertexArray. If data transfer
/// is a bottleneck, this can lead to performance gains.
///
/// Using sf::VertexBuffer, the user also has the ability to only modify
/// a portion of the buffer in graphics memory. This way, a large buffer
/// can be allocated at the start of the application and only the
/// applicable portions of it need to be updated during the course of
/// the application. This allows the user to take full control of data
/// transfers between system and graphics memory if they need to.
///
/// In special cases, the user can make use of multiple threads to update
/// vertex data in multiple distinct regions of the buffer simultaneously.
/// This might make sense when e.g. the position of multiple objects has to
/// be recalculated very frequently. The computation load can be spread
/// across multiple threads as long as there are no other data dependencies.
///
/// Simultaneous updates to the vertex buffer are not guaranteed to be
/// carried out by the driver in any specific order. Updating the same
/// region of the buffer from multiple threads will not cause undefined
/// behaviour, however the final state of the buffer will be unpredictable.
///
/// Simultaneous updates of distinct non-overlapping regions of the buffer
/// are also not guaranteed to complete in a specific order. However, in
/// this case the user can make sure to synchronize the writer threads at
/// well-defined points in their code. The driver will make sure that all
/// pending data transfers complete before the vertex buffer is sourced
/// by the rendering pipeline.
///
/// It inherits sf::Drawable, but unlike other drawables it
/// is not transformable.
///
/// Example:
/// \code
/// sf::Vertex vertices[15];
/// ...
/// sf::VertexBuffer triangles(sf::Triangles);
/// triangles.create(15);
/// triangles.update(vertices);
/// ...
/// window.draw(triangles);
/// \endcode
///
/// \see sf::Vertex, sf::VertexArray
///
////////////////////////////////////////////////////////////
| [
"extern.igor.obradovic@porsche.de"
] | extern.igor.obradovic@porsche.de |
d86985f61f3cc642e7af84ad78e61d116227c808 | ed49bcc399ac0f2686848cd7374e1e601625bd82 | /src/http2.cc | 22a739429137dca860ca0d098bc7aea59944a9bc | [
"MIT"
] | permissive | liuwei000000/nghttp2 | f366b1f45d4c49fdffc0dfaab8472bbb441c8094 | 05f982dcfb21f0892e04a9abe5d240db293ad6b3 | refs/heads/master | 2021-01-18T05:57:56.668079 | 2014-08-07T14:27:13 | 2014-08-07T14:27:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,414 | cc | /*
* nghttp2 - HTTP/2 C Library
*
* Copyright (c) 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "http2.h"
#include "util.h"
namespace nghttp2 {
namespace http2 {
std::string get_status_string(unsigned int status_code)
{
switch(status_code) {
case 100: return "100 Continue";
case 101: return "101 Switching Protocols";
case 200: return "200 OK";
case 201: return "201 Created";
case 202: return "202 Accepted";
case 203: return "203 Non-Authoritative Information";
case 204: return "204 No Content";
case 205: return "205 Reset Content";
case 206: return "206 Partial Content";
case 300: return "300 Multiple Choices";
case 301: return "301 Moved Permanently";
case 302: return "302 Found";
case 303: return "303 See Other";
case 304: return "304 Not Modified";
case 305: return "305 Use Proxy";
// case 306: return "306 (Unused)";
case 307: return "307 Temporary Redirect";
case 400: return "400 Bad Request";
case 401: return "401 Unauthorized";
case 402: return "402 Payment Required";
case 403: return "403 Forbidden";
case 404: return "404 Not Found";
case 405: return "405 Method Not Allowed";
case 406: return "406 Not Acceptable";
case 407: return "407 Proxy Authentication Required";
case 408: return "408 Request Timeout";
case 409: return "409 Conflict";
case 410: return "410 Gone";
case 411: return "411 Length Required";
case 412: return "412 Precondition Failed";
case 413: return "413 Payload Too Large";
case 414: return "414 URI Too Long";
case 415: return "415 Unsupported Media Type";
case 416: return "416 Requested Range Not Satisfiable";
case 417: return "417 Expectation Failed";
case 426: return "426 Upgrade Required";
case 428: return "428 Precondition Required";
case 429: return "429 Too Many Requests";
case 431: return "431 Request Header Fields Too Large";
case 500: return "500 Internal Server Error";
case 501: return "501 Not Implemented";
case 502: return "502 Bad Gateway";
case 503: return "503 Service Unavailable";
case 504: return "504 Gateway Timeout";
case 505: return "505 HTTP Version Not Supported";
case 511: return "511 Network Authentication Required";
default: return util::utos(status_code);
}
}
void capitalize(std::string& s, size_t offset)
{
s[offset] = util::upcase(s[offset]);
for(size_t i = offset+1, eoi = s.size(); i < eoi; ++i) {
if(s[i-1] == '-') {
s[i] = util::upcase(s[i]);
} else {
s[i] = util::lowcase(s[i]);
}
}
}
bool lws(const char *value)
{
for(; *value; ++value) {
switch(*value) {
case '\t':
case ' ':
continue;
default:
return false;
}
}
return true;
}
void sanitize_header_value(std::string& s, size_t offset)
{
// Since both nghttp2 and spdylay do not allow \n and \r in header
// values, we don't have to do this anymore.
// for(size_t i = offset, eoi = s.size(); i < eoi; ++i) {
// if(s[i] == '\r' || s[i] == '\n') {
// s[i] = ' ';
// }
// }
}
void copy_url_component(std::string& dest, const http_parser_url *u, int field,
const char* url)
{
if(u->field_set & (1 << field)) {
dest.assign(url+u->field_data[field].off, u->field_data[field].len);
}
}
bool check_http2_allowed_header(const char *name)
{
return check_http2_allowed_header(reinterpret_cast<const uint8_t*>(name),
strlen(name));
}
bool check_http2_allowed_header(const uint8_t *name, size_t namelen)
{
return
!util::strieq("connection", name, namelen) &&
!util::strieq("host", name, namelen) &&
!util::strieq("keep-alive", name, namelen) &&
!util::strieq("proxy-connection", name, namelen) &&
!util::strieq("te", name, namelen) &&
!util::strieq("transfer-encoding", name, namelen) &&
!util::strieq("upgrade", name, namelen);
}
namespace {
const char *DISALLOWED_HD[] = {
"connection",
"keep-alive",
"proxy-connection",
"te",
"transfer-encoding",
"upgrade",
};
} // namespace
namespace {
size_t DISALLOWED_HDLEN = sizeof(DISALLOWED_HD)/sizeof(DISALLOWED_HD[0]);
} // namespace
namespace {
const char *REQUEST_PSEUDO_HD[] = {
":authority",
":method",
":path",
":scheme",
};
} // namespace
namespace {
size_t REQUEST_PSEUDO_HDLEN =
sizeof(REQUEST_PSEUDO_HD) / sizeof(REQUEST_PSEUDO_HD[0]);
} // namespace
namespace {
const char *RESPONSE_PSEUDO_HD[] = {
":status",
};
} // namespace
namespace {
size_t RESPONSE_PSEUDO_HDLEN =
sizeof(RESPONSE_PSEUDO_HD) / sizeof(RESPONSE_PSEUDO_HD[0]);
} // namespace
namespace {
const char *IGN_HD[] = {
"connection",
"http2-settings",
"keep-alive",
"proxy-connection",
"te",
"transfer-encoding",
"upgrade",
"via",
"x-forwarded-for",
"x-forwarded-proto",
};
} // namespace
namespace {
size_t IGN_HDLEN = sizeof(IGN_HD)/sizeof(IGN_HD[0]);
} // namespace
namespace {
const char *HTTP1_IGN_HD[] = {
"connection",
"cookie",
"http2-settings",
"keep-alive",
"proxy-connection",
"upgrade",
"via",
"x-forwarded-for",
"x-forwarded-proto",
};
} // namespace
namespace {
size_t HTTP1_IGN_HDLEN = sizeof(HTTP1_IGN_HD)/sizeof(HTTP1_IGN_HD[0]);
} // namespace
bool name_less(const Headers::value_type& lhs,
const Headers::value_type& rhs)
{
if(lhs.name.c_str()[0] == ':') {
if(rhs.name.c_str()[0] != ':') {
return true;
}
} else if(rhs.name.c_str()[0] == ':') {
return false;
}
return lhs.name < rhs.name;
}
bool check_http2_headers(const Headers& nva)
{
for(size_t i = 0; i < DISALLOWED_HDLEN; ++i) {
if(std::binary_search(std::begin(nva), std::end(nva),
Header(DISALLOWED_HD[i], ""), name_less)) {
return false;
}
}
return true;
}
namespace {
template<typename InputIterator>
bool check_pseudo_headers(const Headers& nva,
InputIterator allowed_first,
InputIterator allowed_last)
{
bool expect_no_pseudo_header = false;
// strict checking for pseudo headers.
for(auto& hd : nva) {
auto c = hd.name.c_str()[0];
if(c != ':') {
expect_no_pseudo_header = true;
continue;
}
// Pseudo headers must come before normal headers
if(expect_no_pseudo_header) {
return false;
}
auto i = allowed_first;
for(; i != allowed_last; ++i) {
if(hd.name == *i) {
break;
}
}
if(i == allowed_last) {
return false;
}
}
return true;
}
} // namespace
bool check_http2_request_pseudo_headers_without_sort(const Headers& nva)
{
return check_pseudo_headers(nva, REQUEST_PSEUDO_HD,
REQUEST_PSEUDO_HD + REQUEST_PSEUDO_HDLEN);
}
bool check_http2_response_pseudo_headers_without_sort(const Headers& nva)
{
return check_pseudo_headers(nva, RESPONSE_PSEUDO_HD,
RESPONSE_PSEUDO_HD + RESPONSE_PSEUDO_HDLEN);
}
void normalize_headers(Headers& nva)
{
for(auto& kv : nva) {
util::inp_strlower(kv.name);
}
std::stable_sort(std::begin(nva), std::end(nva), name_less);
}
Headers::value_type to_header(const uint8_t *name, size_t namelen,
const uint8_t *value, size_t valuelen,
bool no_index)
{
return Header(std::string(reinterpret_cast<const char*>(name),
namelen),
std::string(reinterpret_cast<const char*>(value),
valuelen),
no_index);
}
void add_header(Headers& nva,
const uint8_t *name, size_t namelen,
const uint8_t *value, size_t valuelen,
bool no_index)
{
nva.push_back(to_header(name, namelen, value, valuelen, no_index));
}
const Headers::value_type* get_unique_header(const Headers& nva,
const char *name)
{
auto nv = Headers::value_type(name, "");
auto i = std::lower_bound(std::begin(nva), std::end(nva), nv, name_less);
if(i != std::end(nva) && (*i).name == nv.name) {
auto j = i + 1;
if(j == std::end(nva) || (*j).name != nv.name) {
return &(*i);
}
}
return nullptr;
}
const Headers::value_type* get_header(const Headers& nva, const char *name)
{
auto nv = Headers::value_type(name, "");
auto i = std::lower_bound(std::begin(nva), std::end(nva), nv, name_less);
if(i != std::end(nva) && (*i).name == nv.name) {
return &(*i);
}
return nullptr;
}
std::string value_to_str(const Headers::value_type *nv)
{
if(nv) {
return nv->value;
}
return "";
}
bool value_lws(const Headers::value_type *nv)
{
return (*nv).value.find_first_not_of("\t ") == std::string::npos;
}
bool non_empty_value(const Headers::value_type *nv)
{
return nv && !value_lws(nv);
}
nghttp2_nv make_nv(const std::string& name, const std::string& value,
bool no_index)
{
uint8_t flags;
flags = no_index ? NGHTTP2_NV_FLAG_NO_INDEX : NGHTTP2_NV_FLAG_NONE;
return {(uint8_t*)name.c_str(), (uint8_t*)value.c_str(),
name.size(), value.size(), flags};
}
void copy_norm_headers_to_nva
(std::vector<nghttp2_nv>& nva, const Headers& headers)
{
size_t i, j;
for(i = 0, j = 0; i < headers.size() && j < IGN_HDLEN;) {
auto& kv = headers[i];
int rv = strcmp(kv.name.c_str(), IGN_HD[j]);
if(rv < 0) {
if(!kv.name.empty() && kv.name.c_str()[0] != ':') {
nva.push_back(make_nv(kv.name, kv.value, kv.no_index));
}
++i;
} else if(rv > 0) {
++j;
} else {
++i;
}
}
for(; i < headers.size(); ++i) {
auto& kv = headers[i];
if(!kv.name.empty() && kv.name.c_str()[0] != ':') {
nva.push_back(make_nv(kv.name, kv.value, kv.no_index));
}
}
}
void build_http1_headers_from_norm_headers
(std::string& hdrs, const Headers& headers)
{
size_t i, j;
for(i = 0, j = 0; i < headers.size() && j < HTTP1_IGN_HDLEN;) {
auto& kv = headers[i];
auto rv = strcmp(kv.name.c_str(), HTTP1_IGN_HD[j]);
if(rv < 0) {
if(!kv.name.empty() && kv.name.c_str()[0] != ':') {
hdrs += kv.name;
capitalize(hdrs, hdrs.size() - kv.name.size());
hdrs += ": ";
hdrs += kv.value;
sanitize_header_value(hdrs, hdrs.size() - kv.value.size());
hdrs += "\r\n";
}
++i;
} else if(rv > 0) {
++j;
} else {
++i;
}
}
for(; i < headers.size(); ++i) {
auto& kv = headers[i];
if(!kv.name.empty() && kv.name.c_str()[0] != ':') {
hdrs += kv.name;
capitalize(hdrs, hdrs.size() - kv.name.size());
hdrs += ": ";
hdrs += kv.value;
sanitize_header_value(hdrs, hdrs.size() - kv.value.size());
hdrs += "\r\n";
}
}
}
int32_t determine_window_update_transmission(nghttp2_session *session,
int32_t stream_id)
{
int32_t recv_length, window_size;
if(stream_id == 0) {
recv_length = nghttp2_session_get_effective_recv_data_length(session);
window_size = nghttp2_session_get_effective_local_window_size(session);
} else {
recv_length = nghttp2_session_get_stream_effective_recv_data_length
(session, stream_id);
window_size = nghttp2_session_get_stream_effective_local_window_size
(session, stream_id);
}
if(recv_length != -1 && window_size != -1) {
if(recv_length >= window_size / 2) {
return recv_length;
}
}
return -1;
}
void dump_nv(FILE *out, const char **nv)
{
for(size_t i = 0; nv[i]; i += 2) {
fwrite(nv[i], strlen(nv[i]), 1, out);
fwrite(": ", 2, 1, out);
fwrite(nv[i+1], strlen(nv[i+1]), 1, out);
fwrite("\n", 1, 1, out);
}
fwrite("\n", 1, 1, out);
fflush(out);
}
void dump_nv(FILE *out, const nghttp2_nv *nva, size_t nvlen)
{
auto end = nva + nvlen;
for(; nva != end; ++nva) {
fwrite(nva->name, nva->namelen, 1, out);
fwrite(": ", 2, 1, out);
fwrite(nva->value, nva->valuelen, 1, out);
fwrite("\n", 1, 1, out);
}
fwrite("\n", 1, 1, out);
fflush(out);
}
void dump_nv(FILE *out, const Headers& nva)
{
for(auto& nv : nva) {
fwrite(nv.name.c_str(), nv.name.size(), 1, out);
fwrite(": ", 2, 1, out);
fwrite(nv.value.c_str(), nv.value.size(), 1, out);
fwrite("\n", 1, 1, out);
}
fwrite("\n", 1, 1, out);
fflush(out);
}
std::string rewrite_location_uri(const std::string& uri,
const http_parser_url& u,
const std::string& request_host,
const std::string& upstream_scheme,
uint16_t upstream_port)
{
// We just rewrite host and optionally port. We don't rewrite https
// link. Not sure it happens in practice.
if(u.field_set & (1 << UF_SCHEMA)) {
auto field = &u.field_data[UF_SCHEMA];
if(!util::streq("http", &uri[field->off], field->len)) {
return "";
}
}
if((u.field_set & (1 << UF_HOST)) == 0) {
return "";
}
auto field = &u.field_data[UF_HOST];
if(!util::startsWith(std::begin(request_host), std::end(request_host),
&uri[field->off], &uri[field->off] + field->len) ||
(request_host.size() != field->len &&
request_host[field->len] != ':')) {
return "";
}
std::string res = upstream_scheme;
res += "://";
res.append(&uri[field->off], field->len);
if(upstream_scheme == "http") {
if(upstream_port != 80) {
res += ":";
res += util::utos(upstream_port);
}
} else if(upstream_scheme == "https") {
if(upstream_port != 443) {
res += ":";
res += util::utos(upstream_port);
}
}
if(u.field_set & (1 << UF_PATH)) {
field = &u.field_data[UF_PATH];
res.append(&uri[field->off], field->len);
}
if(u.field_set & (1 << UF_QUERY)) {
field = &u.field_data[UF_QUERY];
res += "?";
res.append(&uri[field->off], field->len);
}
if(u.field_set & (1 << UF_FRAGMENT)) {
field = &u.field_data[UF_FRAGMENT];
res += "#";
res.append(&uri[field->off], field->len);
}
return res;
}
int check_nv(const uint8_t *name, size_t namelen,
const uint8_t *value, size_t valuelen)
{
if(!nghttp2_check_header_name(name, namelen)) {
return 0;
}
if(!nghttp2_check_header_value(value, valuelen)) {
return 0;
}
return 1;
}
} // namespace http2
} // namespace nghttp2
| [
"tatsuhiro.t@gmail.com"
] | tatsuhiro.t@gmail.com |
f016c23f7c1266d28b7673bdc706f629d4b19c2c | 24f377ba9be8984cb9e136aee46e544f16f1a277 | /app/src/main/cpp/opengl/WlFilterYUV.cpp | df62d0a35f9d6454118f239e9e8b476d7568360f | [] | no_license | toberole/temp_xxxx | 9652fd5317abbf828ab097105f1ab5456ef99f42 | 978c09b19dba579f8dde68c1613905b0ab521791 | refs/heads/master | 2022-11-17T16:45:30.387379 | 2020-07-17T12:38:16 | 2020-07-17T12:38:16 | 280,420,372 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,947 | cpp | //
// Created by yangw on 2019-4-11.
//
#include <cstdlib>
#include "WlFilterYUV.h"
WlFilterYUV::WlFilterYUV() {
}
WlFilterYUV::~WlFilterYUV() {
}
void WlFilterYUV::onCreate() {
vertex = "attribute vec4 v_Position;\n"
"attribute vec2 f_Position;\n"
"varying vec2 ft_Position;\n"
"uniform mat4 u_Matrix;\n"
"void main() {\n"
" ft_Position = f_Position;\n"
" gl_Position = v_Position * u_Matrix;\n"
"}";
fragment = "precision mediump float;\n"
"varying vec2 ft_Position;\n"
"uniform sampler2D sampler_y;\n"
"uniform sampler2D sampler_u;\n"
"uniform sampler2D sampler_v;\n"
"void main() {\n"
" float y,u,v;\n"
" y = texture2D(sampler_y,ft_Position).r;\n"
" u = texture2D(sampler_u,ft_Position).r - 0.5;\n"
" v = texture2D(sampler_v,ft_Position).r - 0.5;\n"
"\n"
" vec3 rgb;\n"
" rgb.r = y + 1.403 * v;\n"
" rgb.g = y - 0.344 * u - 0.714 * v;\n"
" rgb.b = y + 1.770 * u;\n"
"\n"
" gl_FragColor = vec4(rgb,1);\n"
"}";
program = createProgrm(vertex, fragment, &vShader, &fShader);
LOGD("opengl program is %d %d %d", program, vShader, fShader);
vPosition = glGetAttribLocation(program, "v_Position");//顶点坐标
fPosition = glGetAttribLocation(program, "f_Position");//纹理坐标
sampler_y = glGetUniformLocation(program, "sampler_y");
sampler_u = glGetUniformLocation(program, "sampler_u");
sampler_v = glGetUniformLocation(program, "sampler_v");
u_matrix = glGetUniformLocation(program, "u_Matrix");
glGenTextures(3, samplers);
for(int i = 0; i < 3; i++)
{
glBindTexture(GL_TEXTURE_2D, samplers[i]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
}
}
void WlFilterYUV::onChange(int width, int height) {
surface_width = width;
surface_height = height;
glViewport(0, 0, width, height);
setMatrix(width, height);
}
void WlFilterYUV::draw() {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(program);
glUniformMatrix4fv(u_matrix, 1, GL_FALSE, matrix);
glEnableVertexAttribArray(vPosition);
glVertexAttribPointer(vPosition, 2, GL_FLOAT, false, 8, vertexs);
glEnableVertexAttribArray(fPosition);
glVertexAttribPointer(fPosition, 2, GL_FLOAT, false, 8, fragments);
if(yuv_wdith > 0 && yuv_height >0)
{
if(y != NULL)
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, samplers[0]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, yuv_wdith, yuv_height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, y);
glUniform1i(sampler_y, 0);
}
if(u != NULL)
{
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, samplers[1]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, yuv_wdith / 2, yuv_height / 2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, u);
glUniform1i(sampler_u, 1);
}
if(v != NULL)
{
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, samplers[2]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, yuv_wdith / 2, yuv_height / 2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, v);
glUniform1i(sampler_v, 2);
}
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glBindTexture(GL_TEXTURE_2D, 0);
}
}
void WlFilterYUV::destroy() {
glDeleteTextures(3, samplers);
glDetachShader(program, vShader);
glDetachShader(program, fShader);
glDeleteShader(vShader);
glDeleteShader(fShader);
glDeleteProgram(program);
}
void WlFilterYUV::destorySorce() {
yuv_wdith = 0;
yuv_height = 0;
if(y != NULL)
{
free(y);
y = NULL;
}
if(u != NULL)
{
free(u);
u = NULL;
}
if(v != NULL)
{
free(v);
v = NULL;
}
}
void WlFilterYUV::setMatrix(int width, int height) {
initMatrix(matrix);
if(yuv_wdith > 0 && yuv_height > 0)
{
float screen_r = 1.0 * width / height;
float picture_r = 1.0 * yuv_wdith / yuv_height;
if(screen_r > picture_r) //图片宽度缩放
{
float r = width / (1.0 * height / yuv_height * yuv_wdith);
orthoM(-r, r, -1, 1, matrix);
} else{//图片高度缩放
float r = height / (1.0 * width / yuv_wdith * yuv_height);
orthoM(-1, 1, -r, r, matrix);
}
}
}
void WlFilterYUV::setYuvData(void *Y, void *U, void *V, int width, int height) {
if(width > 0 && height > 0)
{
if(yuv_wdith != width || yuv_height != height)
{
yuv_wdith = width;
yuv_height = height;
if(y != NULL)
{
free(y);
y = NULL;
}
if(u != NULL)
{
free(u);
u = NULL;
}
if(v != NULL)
{
free(v);
v = NULL;
}
y = malloc(yuv_wdith * yuv_height);
u = malloc(yuv_wdith * yuv_height / 4);
v = malloc(yuv_wdith * yuv_height / 4);
setMatrix(surface_width, surface_height);
}
memcpy(y, Y, yuv_wdith * yuv_height);
memcpy(u, U, yuv_wdith * yuv_height / 4);
memcpy(v, V, yuv_wdith * yuv_height / 4);
}
}
| [
"zhouwei215664@sogou-inc.com"
] | zhouwei215664@sogou-inc.com |
61ea0b13e5005deca0d2473bec99a44479270067 | 918007d35dd24d34b17203d9867b57a37223c868 | /thrift/lib/cpp2/transport/rsocket/test/StreamingTest.cpp | 840ed78de7d75795a2a05cab1c2c91367efe3220 | [
"Apache-2.0"
] | permissive | lucyge/FBThrift | fed5e0d927740a97f7ebcb9e457c6ddc5567f1af | 2cb49e1c1ee1712416db9cc1f4b833382b04d8cd | refs/heads/master | 2020-03-31T11:04:37.222776 | 2019-01-14T01:03:48 | 2019-01-14T01:03:48 | 152,162,358 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,153 | cpp | /*
* Copyright 2017-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/io/async/ScopedEventBaseThread.h>
#include <gflags/gflags.h>
#include <gmock/gmock.h>
#include <thrift/lib/cpp2/server/ThriftServer.h>
#include <thrift/lib/cpp2/transport/core/ClientConnectionIf.h>
#include <thrift/lib/cpp2/transport/core/TransportRoutingHandler.h>
#include <thrift/lib/cpp2/transport/core/testutil/FakeServerObserver.h>
#include <thrift/lib/cpp2/transport/rsocket/client/StreamThriftClient.h>
#include <thrift/lib/cpp2/transport/rsocket/server/RSRoutingHandler.h>
#include <thrift/lib/cpp2/transport/rsocket/test/util/TestServiceMock.h>
#include <thrift/lib/cpp2/transport/util/ConnectionManager.h>
DECLARE_int32(num_client_connections);
DECLARE_string(transport); // ConnectionManager depends on this flag.
namespace apache {
namespace thrift {
using namespace apache::thrift;
using namespace apache::thrift::transport;
using namespace testing;
using namespace testutil::testservice;
using testutil::testservice::Message;
// Testing transport layers for their support to Streaming
class StreamingTest : public testing::Test {
private:
// Event handler to attach to the Thrift server so we know when it is
// ready to serve and also so we can determine the port it is
// listening on.
class TestEventHandler : public server::TServerEventHandler {
public:
// This is a callback that is called when the Thrift server has
// initialized and is ready to serve RPCs.
void preServe(const folly::SocketAddress* address) override {
port_ = address->getPort();
baton_.post();
}
int32_t waitForPortAssignment() {
baton_.wait();
return port_;
}
private:
folly::Baton<> baton_;
int32_t port_;
};
public:
StreamingTest() : workerThread_("TransportCompatibilityTest_WorkerThread") {
// override the default
FLAGS_transport = "rsocket"; // client's transport
handler_ = std::make_shared<StrictMock<TestServiceMock>>();
auto cpp2PFac =
std::make_shared<ThriftServerAsyncProcessorFactory<TestServiceMock>>(
handler_);
server_ = std::make_unique<ThriftServer>();
observer_ = std::make_shared<FakeServerObserver>();
server_->setObserver(observer_);
server_->setPort(0);
server_->setNumIOWorkerThreads(numIOThreads_);
server_->setNumCPUWorkerThreads(numWorkerThreads_);
server_->setProcessorFactory(cpp2PFac);
server_->addRoutingHandler(
std::make_unique<apache::thrift::RSRoutingHandler>(
server_->getThriftProcessor(), *server_));
auto eventHandler = std::make_shared<TestEventHandler>();
server_->setServerEventHandler(eventHandler);
server_->setup();
// Get the port that the server has bound to
port_ = eventHandler->waitForPortAssignment();
}
virtual ~StreamingTest() {
if (server_) {
server_->cleanUp();
server_.reset();
handler_.reset();
}
}
void connectToServer(
folly::Function<void(
std::unique_ptr<testutil::testservice::StreamServiceAsyncClient>)>
callMe) {
connectToServer([callMe = std::move(callMe)](
std::unique_ptr<StreamServiceAsyncClient> client,
auto) mutable { callMe(std::move(client)); });
}
void connectToServer(
folly::Function<void(
std::unique_ptr<testutil::testservice::StreamServiceAsyncClient>,
std::shared_ptr<ClientConnectionIf>)> callMe) {
CHECK_GT(port_, 0) << "Check if the server has started already";
auto mgr = ConnectionManager::getInstance();
auto connection = mgr->getConnection("::1", port_);
auto channel = StreamThriftClient::Ptr(
new StreamThriftClient(connection, workerThread_.getEventBase()));
channel->setProtocolId(apache::thrift::protocol::T_COMPACT_PROTOCOL);
auto client =
std::make_unique<StreamServiceAsyncClient>(std::move(channel));
callMe(std::move(client), std::move(connection));
}
public:
std::shared_ptr<FakeServerObserver> observer_;
std::shared_ptr<testing::StrictMock<testutil::testservice::TestServiceMock>>
handler_;
std::unique_ptr<ThriftServer> server_;
uint16_t port_;
folly::ScopedEventBaseThread workerThread_;
int numIOThreads_{10};
int numWorkerThreads_{10};
};
TEST_F(StreamingTest, SimpleStream) {
connectToServer([](std::unique_ptr<StreamServiceAsyncClient> client) {
auto result = client->range(0, 10);
int j = 0;
folly::Baton<> done;
result->subscribe(
[&j](auto i) mutable { EXPECT_EQ(j++, i); },
[](auto ex) { FAIL() << "Should not call onError: " << ex.what(); },
[&done]() { done.post(); });
EXPECT_TRUE(done.try_wait_for(std::chrono::milliseconds(100)));
EXPECT_EQ(10, j);
});
}
TEST_F(StreamingTest, SimpleChannel) {
connectToServer([](std::unique_ptr<StreamServiceAsyncClient> client) {
auto input = yarpl::flowable::Flowables::range(0, 10)->map(
[](auto i) { return (int32_t)i; });
auto result = client->prefixSumIOThread(input);
int j = 0, k = 1;
folly::Baton<> done;
result->subscribe(
[&j, k](auto i) mutable {
EXPECT_EQ(j, i);
j = j + k;
++k;
},
[](auto ex) { FAIL() << "Should not call onError: " << ex.what(); },
[&done]() { done.post(); });
EXPECT_TRUE(done.try_wait_for(std::chrono::milliseconds(100)));
EXPECT_EQ(55, j);
});
}
TEST_F(StreamingTest, DefaultStreamImplementation) {
connectToServer([](std::unique_ptr<StreamServiceAsyncClient> client) {
auto result = client->nonImplementedStream("test");
folly::Baton<> done;
result->subscribe(
[](auto) { FAIL() << "Should not call onNext"; },
[&done](auto) { done.post(); },
[]() { FAIL() << "Should not complete successfully"; });
EXPECT_TRUE(done.try_wait_for(std::chrono::milliseconds(100)));
});
}
TEST_F(StreamingTest, DefaultChannelImplementation) {
connectToServer([](std::unique_ptr<StreamServiceAsyncClient> client) {
auto input = yarpl::flowable::Flowables::just(Message());
auto result = client->nonImplementedChannel(input, "test");
folly::Baton<> done;
result->subscribe(
[](auto) mutable { FAIL() << "Should not call onNext"; },
[&done](auto) { done.post(); },
[]() { FAIL() << "Should not complete successfully"; });
EXPECT_TRUE(done.try_wait_for(std::chrono::milliseconds(100)));
});
}
TEST_F(StreamingTest, ReturnsNullptr) {
// User function should return a Stream, but it returns a nullptr.
connectToServer([](std::unique_ptr<StreamServiceAsyncClient> client) {
auto result = client->returnNullptr();
folly::Baton<> done;
result->subscribe(
[](auto) mutable { FAIL() << "Should not call onNext"; },
[&done](auto) { done.post(); },
[]() { FAIL() << "Should not complete successfully"; });
EXPECT_TRUE(done.try_wait_for(std::chrono::milliseconds(100)));
});
}
TEST_F(StreamingTest, ThrowsException) {
// User function throws an exception.
connectToServer([](std::unique_ptr<StreamServiceAsyncClient> client) {
auto input = yarpl::flowable::Flowables::just(Message());
auto result = client->throwException(input);
folly::Baton<> done;
result->subscribe(
[](auto) mutable { FAIL() << "Should not call onNext"; },
[&done](auto) { done.post(); },
[]() { FAIL() << "Should not complete successfully"; });
EXPECT_TRUE(done.try_wait_for(std::chrono::milliseconds(100)));
});
}
} // namespace thrift
} // namespace apache
| [
"shufange@hedviginc.com"
] | shufange@hedviginc.com |
469f395a38ff7feef3b91bcd78113906ab1f8ca6 | 4864529f1b5b41e5f62b54d6b8a7353ac18ef9b7 | /include/controllers/axis/NoDeadbandValue.h | be49f051cbd84bd969757181437d6e17433e2e9f | [
"MIT"
] | permissive | Team302/2019DestinationDeepSpace | 14bc179f70bd43d82e348a16caab5c57011b5f8b | 65f96cfeba1ee9d8d29a1412fed80b598d95a1aa | refs/heads/master | 2020-04-15T14:18:13.990918 | 2019-07-29T01:31:42 | 2019-07-29T01:31:42 | 164,750,317 | 1 | 1 | MIT | 2019-03-20T22:01:54 | 2019-01-08T23:29:05 | C++ | UTF-8 | C++ | false | false | 3,490 | h |
/*========================================================================================================
* NoDeadbandValue.h
*========================================================================================================
*
* File Description: Returns raw value without a deadband
*
*========================================================================================================*/
//====================================================================================================================================================
// Copyright 2018 Lake Orion Robobitcs FIRST Team 302
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.
//====================================================================================================================================================
#ifndef SRC_MAIN_INCLUDE_COMMON_CONTROLLERS_AXIS_NODEADBANDVALUE_H_
#define SRC_MAIN_INCLUDE_COMMON_CONTROLLERS_AXIS_NODEADBANDVALUE_H_
#include <controllers/axis/IDeadband.h>
//==================================================================================
/// <summary>
/// Class: NoDeadbandValue
/// Description: This class doesn't apply a deadband to axis values
/// </summary>
//==================================================================================
class NoDeadbandValue : public IDeadband
{
public:
//==================================================================================
/// <summary>
/// Method: GetInstance
/// Description: Static singleton method to create the object
/// Returns: DeadbandValue* Singleton deadband object
/// </summary>
//==================================================================================
static NoDeadbandValue* GetInstance();
//==================================================================================
/// <summary>
/// Method: ApplyDeadband
/// Description: Apply the standard deadband
/// </summary>
//==================================================================================
double ApplyDeadband
(
double inputVal // <I> - value to apply profile to
) const override;
private:
NoDeadbandValue() = default;
static NoDeadbandValue* m_instance;
};
#endif
| [
"noreply@github.com"
] | noreply@github.com |
73f6c92e7309be5ffaedb1aa9e6778d46a27f3e8 | 676c8ff64fb2b9d6bcaa21f08f030c7885baa58d | /bin/src/trilateral3/matrix/MatrixDozen.cpp | 415b50f36e4103ede5af42a9d37ba05a926af162 | [
"MIT"
] | permissive | TrilateralX/TrilateralGluonSVG | 3854174499ec013088113a3aa4a04eb1c4f1628c | 40e893bff12b8d7dfd69bc2b51c375adf76a88e6 | refs/heads/master | 2022-10-18T14:14:20.323143 | 2020-06-11T13:49:39 | 2020-06-11T13:49:39 | 271,168,845 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 6,483 | cpp | // Generated by Haxe 4.2.0-rc.1+354c24d30
#include <hxcpp.h>
#ifndef INCLUDED_trilateral3_matrix_MatrixDozen
#include <trilateral3/matrix/MatrixDozen.h>
#endif
namespace trilateral3{
namespace matrix{
void MatrixDozen_obj::__construct(Float a,Float b,Float c,Float d,Float e,Float f,Float g,Float h,Float i,Float j,Float k,Float l){
this->l = ((Float)0.);
this->k = ((Float)0.);
this->j = ((Float)0.);
this->i = ((Float)0.);
this->h = ((Float)0.);
this->g = ((Float)0.);
this->f = ((Float)0.);
this->e = ((Float)0.);
this->d = ((Float)0.);
this->c = ((Float)0.);
this->b = ((Float)0.);
this->a = ((Float)0.);
this->a = a;
this->b = b;
this->c = c;
this->d = d;
this->e = e;
this->f = f;
this->g = g;
this->h = h;
this->i = i;
this->j = j;
this->k = k;
this->l = l;
}
Dynamic MatrixDozen_obj::__CreateEmpty() { return new MatrixDozen_obj; }
void *MatrixDozen_obj::_hx_vtable = 0;
Dynamic MatrixDozen_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< MatrixDozen_obj > _hx_result = new MatrixDozen_obj();
_hx_result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3],inArgs[4],inArgs[5],inArgs[6],inArgs[7],inArgs[8],inArgs[9],inArgs[10],inArgs[11]);
return _hx_result;
}
bool MatrixDozen_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x285f83bb;
}
MatrixDozen_obj::MatrixDozen_obj()
{
}
::hx::Val MatrixDozen_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 1:
if (HX_FIELD_EQ(inName,"a") ) { return ::hx::Val( a ); }
if (HX_FIELD_EQ(inName,"b") ) { return ::hx::Val( b ); }
if (HX_FIELD_EQ(inName,"c") ) { return ::hx::Val( c ); }
if (HX_FIELD_EQ(inName,"d") ) { return ::hx::Val( d ); }
if (HX_FIELD_EQ(inName,"e") ) { return ::hx::Val( e ); }
if (HX_FIELD_EQ(inName,"f") ) { return ::hx::Val( f ); }
if (HX_FIELD_EQ(inName,"g") ) { return ::hx::Val( g ); }
if (HX_FIELD_EQ(inName,"h") ) { return ::hx::Val( h ); }
if (HX_FIELD_EQ(inName,"i") ) { return ::hx::Val( i ); }
if (HX_FIELD_EQ(inName,"j") ) { return ::hx::Val( j ); }
if (HX_FIELD_EQ(inName,"k") ) { return ::hx::Val( k ); }
if (HX_FIELD_EQ(inName,"l") ) { return ::hx::Val( l ); }
}
return super::__Field(inName,inCallProp);
}
::hx::Val MatrixDozen_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 1:
if (HX_FIELD_EQ(inName,"a") ) { a=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"b") ) { b=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"c") ) { c=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"d") ) { d=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"e") ) { e=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"f") ) { f=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"g") ) { g=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"h") ) { h=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"i") ) { i=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"j") ) { j=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"k") ) { k=inValue.Cast< Float >(); return inValue; }
if (HX_FIELD_EQ(inName,"l") ) { l=inValue.Cast< Float >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void MatrixDozen_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("a",61,00,00,00));
outFields->push(HX_("b",62,00,00,00));
outFields->push(HX_("c",63,00,00,00));
outFields->push(HX_("d",64,00,00,00));
outFields->push(HX_("e",65,00,00,00));
outFields->push(HX_("f",66,00,00,00));
outFields->push(HX_("g",67,00,00,00));
outFields->push(HX_("h",68,00,00,00));
outFields->push(HX_("i",69,00,00,00));
outFields->push(HX_("j",6a,00,00,00));
outFields->push(HX_("k",6b,00,00,00));
outFields->push(HX_("l",6c,00,00,00));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo MatrixDozen_obj_sMemberStorageInfo[] = {
{::hx::fsFloat,(int)offsetof(MatrixDozen_obj,a),HX_("a",61,00,00,00)},
{::hx::fsFloat,(int)offsetof(MatrixDozen_obj,b),HX_("b",62,00,00,00)},
{::hx::fsFloat,(int)offsetof(MatrixDozen_obj,c),HX_("c",63,00,00,00)},
{::hx::fsFloat,(int)offsetof(MatrixDozen_obj,d),HX_("d",64,00,00,00)},
{::hx::fsFloat,(int)offsetof(MatrixDozen_obj,e),HX_("e",65,00,00,00)},
{::hx::fsFloat,(int)offsetof(MatrixDozen_obj,f),HX_("f",66,00,00,00)},
{::hx::fsFloat,(int)offsetof(MatrixDozen_obj,g),HX_("g",67,00,00,00)},
{::hx::fsFloat,(int)offsetof(MatrixDozen_obj,h),HX_("h",68,00,00,00)},
{::hx::fsFloat,(int)offsetof(MatrixDozen_obj,i),HX_("i",69,00,00,00)},
{::hx::fsFloat,(int)offsetof(MatrixDozen_obj,j),HX_("j",6a,00,00,00)},
{::hx::fsFloat,(int)offsetof(MatrixDozen_obj,k),HX_("k",6b,00,00,00)},
{::hx::fsFloat,(int)offsetof(MatrixDozen_obj,l),HX_("l",6c,00,00,00)},
{ ::hx::fsUnknown, 0, null()}
};
static ::hx::StaticInfo *MatrixDozen_obj_sStaticStorageInfo = 0;
#endif
static ::String MatrixDozen_obj_sMemberFields[] = {
HX_("a",61,00,00,00),
HX_("b",62,00,00,00),
HX_("c",63,00,00,00),
HX_("d",64,00,00,00),
HX_("e",65,00,00,00),
HX_("f",66,00,00,00),
HX_("g",67,00,00,00),
HX_("h",68,00,00,00),
HX_("i",69,00,00,00),
HX_("j",6a,00,00,00),
HX_("k",6b,00,00,00),
HX_("l",6c,00,00,00),
::String(null()) };
::hx::Class MatrixDozen_obj::__mClass;
void MatrixDozen_obj::__register()
{
MatrixDozen_obj _hx_dummy;
MatrixDozen_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("trilateral3.matrix.MatrixDozen",f1,de,9e,d8);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(MatrixDozen_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< MatrixDozen_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = MatrixDozen_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = MatrixDozen_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace trilateral3
} // end namespace matrix
| [
"none"
] | none |
c7816c1b12bce39f9d00bad9ec36a065bc935e5b | b3fe10c73eb8dd6fdaa8005698896fd433b0eeae | /binary.cpp | 62867771b0737b261bb2174bd02a526d871dbc8b | [] | no_license | DDUC-CS-Sanjeet/binarysearch-shruti2726 | c3dcc3f42323f828f12cd7ec26cf4ed9cf61cb35 | 854a8611ea727f26f0b1bfff2e4366c715a3d4ba | refs/heads/master | 2020-12-14T21:51:09.861449 | 2020-01-24T16:38:13 | 2020-01-24T16:38:13 | 234,881,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,549 | cpp | #include<iostream>
#include<algorithm>
using namespace std;
bool binarySearchIterative(int* array, int startIndex, int lastIndex, int element)
{
int midindex;
sort(array,array+lastIndex);
while(startIndex<lastIndex)
{
midindex=(startIndex+lastIndex)/2;
if(array[midindex]>element)
{
lastIndex=midindex-1;
}
else if(array[midindex]<element)
{
startIndex=midindex+1;
}
else if(element==array[midindex])
{
return true;
}
}
}
bool binarySearchReacursive(int* array, int startIndex, int lastIndex, int element)
{
int midindex;
sort(array,array+lastIndex);
midindex=(startIndex+lastIndex)/2;
if(startIndex>lastIndex)
return false;
if(element==array[midindex])
return true;
else if(array[midindex]>element)
binarySearchReacursive(array,startIndex,midindex-1,element);
else if(array[midindex]<element)
binarySearchReacursive(array,midindex+1,lastIndex,element);
}
int main()
{
int a,n,array[20];
bool result,result1=0;
cout<<"enter the size of the array";
cin>>n;
cout<<"enter elements of array";
for(int i=0;i<n;i++)
{
cin>>array[i];
}
cout<<"enter the element to be searched";
cin>>a;
result=binarySearchIterative(array,0,n-1,a);
if(result==0)
{
cout<<"not found by iteration \n";
}
else
cout<<"found by iteration \n";
result1=binarySearchReacursive(array,0,n-1,a);
if(result1==0)
{
cout<<"not found by recursion \n";
}
else
cout<<"found by recursion";
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
90d6535de1c94f7aab05cfd901854adedc49c5ad | 5d4b70ac5e555e3c8b68534ef1790ce041a0f65e | /include/slg/textures/densitygrid.h | 366ca027f71b20e01b7eb6b8610bc02d06e353ab | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | LuxCoreRender/LuxCore | eddb0e3710cbc8fa28cb80f16d908f1ec3cc72db | 2f35684a04d9e1bd48d6ffa88b19a88871e90942 | refs/heads/master | 2023-08-17T01:28:23.931381 | 2023-05-28T22:25:00 | 2023-05-28T22:25:00 | 111,695,279 | 1,055 | 154 | Apache-2.0 | 2023-08-03T20:21:05 | 2017-11-22T14:36:32 | C++ | UTF-8 | C++ | false | false | 3,451 | h | /***************************************************************************
* Copyright 1998-2013 by authors (see AUTHORS.txt) *
* *
* This file is part of LuxCoreRender. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*
* See the License for the specific language governing permissions and *
* limitations under the License. *
***************************************************************************/
#ifndef _SLG_DENSITYGRIDTEX_H
#define _SLG_DENSITYGRIDTEX_H
#include "slg/textures/texture.h"
#include "slg/imagemap/imagemap.h"
namespace slg {
//------------------------------------------------------------------------------
// DensityGrid texture
//------------------------------------------------------------------------------
class DensityGridTexture : public Texture {
public:
DensityGridTexture(const TextureMapping3D *mp, const u_int nx, const u_int ny, const u_int nz,
const ImageMap *imageMap);
virtual ~DensityGridTexture() { }
virtual TextureType GetType() const { return DENSITYGRID_TEX; }
virtual float GetFloatValue(const HitPoint &hitPoint) const;
virtual luxrays::Spectrum GetSpectrumValue(const HitPoint &hitPoint) const;
virtual float Y() const { return imageMap->GetSpectrumMeanY(); }
virtual float Filter() const { return imageMap->GetSpectrumMean(); }
u_int GetWidth() const { return nx; }
u_int GetHeight() const { return ny; }
u_int GetDepth() const { return nz; }
const ImageMap *GetImageMap() const { return imageMap; }
virtual void AddReferencedImageMaps(boost::unordered_set<const ImageMap *> &referencedImgMaps) const {
referencedImgMaps.insert(imageMap);
}
virtual luxrays::Properties ToProperties(const ImageMapCache &imgMapCache, const bool useRealFileName) const;
const TextureMapping3D *GetTextureMapping() const { return mapping; }
static ImageMap *ParseData(const luxrays::Property &Property,
const bool isRGB,
const u_int nx, const u_int ny, const u_int nz,
const ImageMapStorage::StorageType storageType,
const ImageMapStorage::WrapType wrapMode);
static ImageMap *ParseOpenVDB(const std::string &fileName, const std::string &gridName,
const u_int nx, const u_int ny, const u_int nz,
const ImageMapStorage::StorageType storageType,
const ImageMapStorage::WrapType wrapMode);
private:
luxrays::Spectrum D(int x, int y, int z) const;
const TextureMapping3D *mapping;
const int nx, ny, nz;
const ImageMap *imageMap;
};
}
#endif /* _SLG_DENSITYGRIDTEX_H */
| [
"dade916@gmail.com"
] | dade916@gmail.com |
231d8282bdce383f63deeafde248c30c5fc37059 | dc25b23f8132469fd95cee14189672cebc06aa56 | /vendor/mediatek/proprietary/hardware/mtkcam/legacy/platform/mt6795/include/mtkcam/algorithm/libsync3a/AppSyncAf.h | 72ad7a2772c8be7eb07f1fea5b7d93ebb1ce65e5 | [] | no_license | nofearnohappy/alps_mm | b407d3ab2ea9fa0a36d09333a2af480b42cfe65c | 9907611f8c2298fe4a45767df91276ec3118dd27 | refs/heads/master | 2020-04-23T08:46:58.421689 | 2019-03-28T21:19:33 | 2019-03-28T21:19:33 | 171,048,255 | 1 | 5 | null | 2020-03-08T03:49:37 | 2019-02-16T20:25:00 | Java | UTF-8 | C++ | false | false | 4,678 | h | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. and/or its licensors.
* Without the prior written permission of MediaTek inc. and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
*/
/* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek Software")
* have been modified by MediaTek Inc. All revisions are subject to any receiver's
* applicable license agreements with MediaTek Inc.
*/
/********************************************************************************************
* LEGAL DISCLAIMER
*
* (Header of MediaTek Software/Firmware Release or Documentation)
*
* BY OPENING OR USING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") RECEIVED
* FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON AN "AS-IS" BASIS
* ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR
* A PARTICULAR PURPOSE OR NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY
* WHATSOEVER WITH RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK
* ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO
* NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S SPECIFICATION
* OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM.
*
* BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE LIABILITY WITH
* RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION,
TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE
* FEES OR SERVICE CHARGE PAID BY BUYER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE WITH THE LAWS
* OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF LAWS PRINCIPLES.
************************************************************************************************/
#ifndef _APP_SYNCAF_H
#define _APP_SYNCAF_H
#include "MTKSyncAf.h"
/*****************************************************************************
Class Define
******************************************************************************/
class AppSyncAf : public MTKSyncAf {
public:
static MTKSyncAf* getInstance();
virtual void destroyInstance();
AppSyncAf();
virtual ~AppSyncAf();
// Process Control
MRESULT SyncAfInit(void* InitInData);
MRESULT SyncAfMain();
MRESULT SyncAfReset(); //Reset
// Feature Control
MRESULT SyncAfFeatureCtrl(MUINT32 FeatureID, void* pParaIn, void* pParaOut);
private:
};
#endif
| [
"fetpoh@mail.ru"
] | fetpoh@mail.ru |
6695061e0bee2ef4b9db9391c398948c0118cd57 | 610dfa590d5863e9465cc5a07a2045c9ee0c9385 | /src/Externals/boost/libs/thread/test/sync/futures/async/async_pass.cpp | 347dd884f02fa56e3609241cf62b0d3a8c88d7fe | [
"BSL-1.0"
] | permissive | SCI-ElVis/ElVis | f275322dea593ed39c4771b072399573819624c0 | 7978b5898ef7d0a0f7711c77dda0e69167716efa | refs/heads/master | 2021-01-01T06:18:45.390678 | 2015-10-19T09:00:23 | 2015-10-19T09:00:23 | 8,036,991 | 14 | 4 | null | 2020-10-13T00:43:47 | 2013-02-05T20:11:59 | C++ | UTF-8 | C++ | false | false | 17,074 | cpp | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Copyright (C) 2011 Vicente J. Botet Escriba
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// <boost/thread/future.hpp>
// template <class F, class... Args>
// future<typename result_of<F(Args...)>::type>
// async(F&& f, Args&&... args);
// template <class F, class... Args>
// future<typename result_of<F(Args...)>::type>
// async(launch policy, F&& f, Args&&... args);
//#define BOOST_THREAD_VERSION 3
#define BOOST_THREAD_VERSION 4
#include <iostream>
#include <boost/thread/future.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/detail/memory.hpp>
#include <boost/interprocess/smart_ptr/unique_ptr.hpp>
#include <memory>
#include <boost/detail/lightweight_test.hpp>
typedef boost::chrono::high_resolution_clock Clock;
typedef boost::chrono::milliseconds ms;
class A
{
long data_;
public:
typedef long result_type;
explicit A(long i) : data_(i) {}
long operator()() const
{
boost::this_thread::sleep_for(ms(200));
return data_;
}
};
class MoveOnly
{
public:
typedef int result_type;
int value;
BOOST_THREAD_MOVABLE_ONLY(MoveOnly)
MoveOnly()
{
value=0;
}
MoveOnly(BOOST_THREAD_RV_REF(MoveOnly))
{
value=1;
}
MoveOnly& operator=(BOOST_THREAD_RV_REF(MoveOnly))
{
value=2;
return *this;
}
int operator()()
{
boost::this_thread::sleep_for(ms(200));
return 3;
}
template <typename OS>
friend OS& operator<<(OS& os, MoveOnly const& v)
{
os << v.value;
return os;
}
};
namespace boost {
BOOST_THREAD_DCL_MOVABLE(MoveOnly)
}
int f0()
{
boost::this_thread::sleep_for(ms(200));
return 3;
}
int i = 0;
int& f1()
{
boost::this_thread::sleep_for(ms(200));
return i;
}
void f2()
{
boost::this_thread::sleep_for(ms(200));
}
boost::interprocess::unique_ptr<int, boost::default_delete<int> > f3_0()
{
boost::this_thread::sleep_for(ms(200));
boost::interprocess::unique_ptr<int, boost::default_delete<int> > r((new int(3)));
return boost::move(r);
}
MoveOnly f3_1()
{
boost::this_thread::sleep_for(ms(200));
MoveOnly r;
return boost::move(r);
}
boost::interprocess::unique_ptr<int, boost::default_delete<int> > f3(int i)
{
boost::this_thread::sleep_for(ms(200));
return boost::interprocess::unique_ptr<int, boost::default_delete<int> >(new int(i));
}
boost::interprocess::unique_ptr<int, boost::default_delete<int> > f4(
BOOST_THREAD_RV_REF_BEG boost::interprocess::unique_ptr<int, boost::default_delete<int> > BOOST_THREAD_RV_REF_END p
)
{
boost::this_thread::sleep_for(ms(200));
return boost::move(p);
}
int main()
{
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<int> f = boost::async(f0);
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
BOOST_TEST(f.get() == 3);
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 < ms(300));
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<int> f = boost::async(boost::launch::async, f0);
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
BOOST_TEST(f.get() == 3);
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 < ms(200));
std::cout << __FILE__ <<"["<<__LINE__<<"] "<< (t1 - t0).count() << std::endl;
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<long> f = boost::async(boost::launch::async, A(3));
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
BOOST_TEST(f.get() == 3);
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 < ms(200));
std::cout << __FILE__ <<"["<<__LINE__<<"] "<< (t1 - t0).count() << std::endl;
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<int> f = boost::async(boost::launch::async, BOOST_THREAD_MAKE_RV_REF(MoveOnly()));
// boost::this_thread::sleep_for(ms(300));
// Clock::time_point t0 = Clock::now();
// BOOST_TEST(f.get() == 3);
// Clock::time_point t1 = Clock::now();
// BOOST_TEST(t1 - t0 < ms(200));
// std::cout << __FILE__ <<"["<<__LINE__<<"] "<< (t1 - t0).count() << std::endl;
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<int> f = boost::async(boost::launch::any, f0);
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
BOOST_TEST(f.get() == 3);
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 < ms(200));
std::cout << __FILE__ <<"["<<__LINE__<<"] "<< (t1 - t0).count() << std::endl;
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<int> f = boost::async(boost::launch::deferred, f0);
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
BOOST_TEST(f.get() == 3);
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 > ms(100));
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
#endif
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<int&> f = boost::async(f1);
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
BOOST_TEST(&f.get() == &i);
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 < ms(200));
std::cout << __FILE__ <<"["<<__LINE__<<"] "<< (t1 - t0).count() << std::endl;
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<int&> f = boost::async(boost::launch::async, f1);
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
BOOST_TEST(&f.get() == &i);
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 < ms(200));
std::cout << __FILE__ <<"["<<__LINE__<<"] "<< (t1 - t0).count() << std::endl;
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<int&> f = boost::async(boost::launch::any, f1);
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
BOOST_TEST(&f.get() == &i);
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 < ms(200));
std::cout << __FILE__ <<"["<<__LINE__<<"] "<< (t1 - t0).count() << std::endl;
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<int&> f = boost::async(boost::launch::deferred, f1);
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
BOOST_TEST(&f.get() == &i);
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 > ms(100));
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
#endif
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<void> f = boost::async(f2);
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
f.get();
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 < ms(200));
std::cout << __FILE__ <<"["<<__LINE__<<"] "<< (t1 - t0).count() << std::endl;
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<void> f = boost::async(boost::launch::async, f2);
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
f.get();
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 < ms(200));
std::cout << __FILE__ <<"["<<__LINE__<<"] "<< (t1 - t0).count() << std::endl;
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<void> f = boost::async(boost::launch::any, f2);
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
f.get();
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 < ms(200));
std::cout << __FILE__ <<"["<<__LINE__<<"] "<< (t1 - t0).count() << std::endl;
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<void> f = boost::async(boost::launch::deferred, f2);
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
f.get();
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 > ms(100));
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
#endif
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<MoveOnly> f = boost::async(&f3_1);
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
BOOST_TEST(f.get().value == 1);
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 < ms(200));
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<MoveOnly> f;
f = boost::async(&f3_1);
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
BOOST_TEST(f.get().value == 1);
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 < ms(200));
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<boost::interprocess::unique_ptr<int, boost::default_delete<int> > > f = boost::async(&f3_0);
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
BOOST_TEST(*f.get() == 3);
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 < ms(200));
std::cout << __FILE__ <<"["<<__LINE__<<"] "<< (t1 - t0).count() << std::endl;
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<boost::interprocess::unique_ptr<int, boost::default_delete<int> > > f = boost::async(boost::launch::async, &f3, 3);
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
BOOST_TEST(*f.get() == 3);
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 < ms(200));
std::cout << __FILE__ <<"["<<__LINE__<<"] "<< (t1 - t0).count() << std::endl;
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<boost::interprocess::unique_ptr<int, boost::default_delete<int> > > f = boost::async(&f3, 3);
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
BOOST_TEST(*f.get() == 3);
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 < ms(200));
std::cout << __FILE__ <<"["<<__LINE__<<"] "<< (t1 - t0).count() << std::endl;
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
#endif
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<boost::interprocess::unique_ptr<int, boost::default_delete<int> > > f = boost::async(boost::launch::async, &f4, boost::interprocess::unique_ptr<int, boost::default_delete<int> >(new int(3)));
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
BOOST_TEST(*f.get() == 3);
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 < ms(200));
std::cout << __FILE__ <<"["<<__LINE__<<"] "<< (t1 - t0).count() << std::endl;
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<std::endl;
{
try {
boost::future<boost::interprocess::unique_ptr<int, boost::default_delete<int> > > f = boost::async(&f4, boost::interprocess::unique_ptr<int, boost::default_delete<int> >(new int(3)));
boost::this_thread::sleep_for(ms(300));
Clock::time_point t0 = Clock::now();
BOOST_TEST(*f.get() == 3);
Clock::time_point t1 = Clock::now();
BOOST_TEST(t1 - t0 < ms(200));
std::cout << __FILE__ <<"["<<__LINE__<<"] "<< (t1 - t0).count() << std::endl;
} catch (std::exception& ex) {
std::cout << __FILE__ <<"["<<__LINE__<<"]"<<ex.what() << std::endl;
BOOST_TEST(false && "exception thrown");
} catch (...) {
BOOST_TEST(false && "exception thrown");
}
}
#endif
return boost::report_errors();
}
| [
"gpayne@155-99-168-187.uconnect.utah.edu"
] | gpayne@155-99-168-187.uconnect.utah.edu |
36c4a12264df69e7f48fbe69cd725a36380017a4 | 69d178c2d42d715f3ecfdb58ca782b2493b2bb44 | /src/main.cpp | 8d786a3ef5542b4c9940e3b3135bf66ae98abcd7 | [] | no_license | slowbull/AsyDSPGplus | 160a89e007515fcc943fe911630aa5811dbd93ad | 30f0a9acbf1a4d2b7277dab1baeeb0e53a9138d8 | refs/heads/master | 2020-04-19T20:13:42.927891 | 2019-01-30T20:38:16 | 2019-01-30T20:38:16 | 168,408,871 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 981 | cpp | /*
* Copyright 2016 [See AUTHORS file for list of authors]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include "run.h"
// Flags for application types.
DEFINE_bool(logistic_l2_l1, false, "logistic loss with l2 norm and l1 norm regularization type.");
int main(int argc, char **argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
if (FLAGS_logistic_l2_l1) {
Run<LOGISTICL2L1Model, LIBSVMDatapoint>();
}
}
| [
"huozhouyuan@gmail.com"
] | huozhouyuan@gmail.com |
9ec25abfde7b611b29c86a822b14bdca9cb9bfed | f19a734ebeaa22ae0d8a0d347aea5810f159d9bc | /Persistent Segment Tree (Zhuxi Tree)/BZOJ1901.cpp | cc102e3c54b7f95e141fcdbcae44027f39576a77 | [] | no_license | iiyiyi/solution-book-till-2020 | 2d0b75dc9e1468d846b176551acaa2a930428afb | faf1c04735627df8ee600b55d72df9bec50089b5 | refs/heads/master | 2023-03-07T05:54:48.824987 | 2021-02-20T10:59:55 | 2021-02-20T10:59:55 | 340,558,407 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,924 | cpp | #include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#define lson l,m
#define rson m+1,r
using namespace std;
const int MAXN=60000+50;//注意要开60000,原来50000个数加修改操作中可能另外出现的10000个数
int n,q,tot,m,d;
struct node
{
int l,r,k,Q;
}op[MAXN];
int a[MAXN<<2],hash[MAXN<<2],T[MAXN<<2],S[MAXN<<2],use[MAXN<<2];
int L[MAXN<<5],R[MAXN<<5],sum[MAXN<<5];
int lowbit(int x)
{
return (x&(-x));
}
int build(int l,int r)
{
int rt=++tot;
sum[rt]=0;
if (l!=r)
{
int m=(l+r)>>1;
L[rt]=build(lson);
R[rt]=build(rson);
}
return rt;
}
int update(int pre,int l,int r,int x,int op)
{
int rt=++tot;
L[rt]=L[pre],R[rt]=R[pre],sum[rt]=sum[pre]+op;
if (l<r)
{
int m=(l+r)>>1;
if (x<=m) L[rt]=update(L[pre],lson,x,op);
else R[rt]=update(R[pre],rson,x,op);
}
return rt;
}
int Sum(int x)
{
int ret=0;
while (x>0)
{
ret+=sum[L[use[x]]];
x-=lowbit(x);
}
return ret;
}
int query(int Sl,int Sr,int Tl,int Tr,int l,int r,int k)
{
if (l==r) return l;
int m=(l+r)>>1;
int tmp=Sum(Sr)-Sum(Sl)+sum[L[Tr]]-sum[L[Tl]];
if (tmp>=k)
{
for (int i=Sl;i;i-=lowbit(i)) use[i]=L[use[i]];
for (int i=Sr;i;i-=lowbit(i)) use[i]=L[use[i]];
return query(Sl,Sr,L[Tl],L[Tr],lson,k);
}
else
{
for (int i=Sl;i;i-=lowbit(i)) use[i]=R[use[i]];
for (int i=Sr;i;i-=lowbit(i)) use[i]=R[use[i]];
return query(Sl,Sr,R[Tl],R[Tr],rson,k-tmp);
}
}
void modify(int x,int p,int delta)
{
while (x<=n)
{
S[x]=update(S[x],1,d,p,delta);
x+=lowbit(x);
}
}
void init()
{
tot=0;
m=0;
d=0;
scanf("%d%d",&n,&q);
for (int i=1;i<=n;i++) scanf("%d",&a[i]),hash[++m]=a[i];
for (int i=0;i<q;i++)
{
char s[10];
scanf("%s",s);
if (s[0]=='Q') scanf("%d%d%d",&op[i].l,&op[i].r,&op[i].k),op[i].Q=1;
else
{
scanf("%d%d",&op[i].l,&op[i].r);
op[i].Q=0;
hash[++m]=op[i].r;
}
}
/*因为修改后的数可能不在初始几个数的范围内,故要先输入完查询*/
sort(hash+1,hash+m+1);
d=unique(hash+1,hash+1+m)-hash-1;
T[0]=build(1,d);//T表示每一步T树的树根
for (int i=1;i<=n;i++)
{
int x=lower_bound(hash+1,hash+d+1,a[i])-hash;
T[i]=update(T[i-1],1,d,x,1);
}
for (int i=1;i<=n;i++) S[i]=T[0];
}
void solve()
{
//不要忘记了离散化之后的范围上界为d而不是m
for (int i=0;i<q;i++)
{
if (op[i].Q)
{
for (int j=op[i].l-1;j;j-=lowbit(j)) use[j]=S[j];
for (int j=op[i].r;j;j-=lowbit(j)) use[j]=S[j];
int ans=query(op[i].l-1,op[i].r,T[op[i].l-1],T[op[i].r],1,d,op[i].k);
printf("%d\n",hash[ans]);
}
else
{
int x=lower_bound(hash+1,hash+d+1,a[op[i].l])-hash;
int y=lower_bound(hash+1,hash+d+1,op[i].r)-hash;
modify(op[i].l,x,-1);
modify(op[i].l,y,1);
a[op[i].l] =op[i].r;
}
}
}
int main()
{
freopen("dynrank.in","r",stdin);
freopen("dynrank.out","w",stdout);
int T;
scanf("%d",&T);
while (T--)
{
init();
solve();
}
return 0;
}
| [
"yicai0123@outlook.com"
] | yicai0123@outlook.com |
029b5dd121f4af6e98560e0dc251a7f6815d6cce | d20e0e77ef5b6dbeaa84eda184d2566d834d0ab0 | /DeleteNodeInABST_450.cpp | 1ef6823ff0751910bebefd21b290008014faeecc | [] | no_license | tridibsamanta/LeetCode_Solutions | 4cdd53c0c5f62ed346c23fa02224d1dc225cfa2e | 983bc7552820460a45543b7e491a19981a7c1296 | refs/heads/master | 2023-07-26T02:49:28.142041 | 2023-07-14T04:55:17 | 2023-07-14T04:55:17 | 245,427,239 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,461 | cpp | /*
~ Author : leetcode.com/tridib_2003/
~ Problem : 450. Delete Node in a BST
~ Link : https://leetcode.com/problems/delete-node-in-a-bst/
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root == NULL) return root;
else if(key < root->val)
root->left = deleteNode(root->left, key);
else if(key > root->val)
root->right = deleteNode(root->right, key);
else {
if(root->left == NULL && root->right == NULL) {
delete root;
root = NULL;
}
else if(root->left == NULL) {
TreeNode* temp = root;
root = root->right;
delete temp;
}
else if(root->right == NULL) {
TreeNode* temp = root;
root = root->left;
delete temp;
}
else {
TreeNode* temp = root->right;
while(temp->left != NULL)
temp = temp->left;
root->val = temp->val;
root->right = deleteNode(root->right, temp->val);
}
}
return root;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
4c7e2927e5d014d65e982fc836b12f1dd0e7495f | c3bbdbbbc5f47577e332a280f81bd905617423c9 | /Source/AllProjects/CommUtils/CIDWebSock/CIDWebSock_WSEngine.hpp | 04804e787f77c41f073fb2ebffd451884394ca1b | [
"MIT"
] | permissive | DeanRoddey/CIDLib | 65850f56cb60b16a63bbe7d6d67e4fddd3ecce57 | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | refs/heads/develop | 2023-03-11T03:08:59.207530 | 2021-11-06T16:40:44 | 2021-11-06T16:40:44 | 174,652,391 | 227 | 33 | MIT | 2020-09-16T11:33:26 | 2019-03-09T05:26:26 | C++ | UTF-8 | C++ | false | false | 11,793 | hpp | //
// FILE NAME: CIDWebSock_WSEngine.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 05/24/2017
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This is the header file for the CIDWebSock_WSEngine.cpp file. This file implements the
// class that server side web socket applications would derive from to create a handler
// for a single Websockets session. See the main facility header for high level info about
// how it all works.
//
// The application's derivative will override methods that get called when we get messages
// from clients or other websockets events occur. So the derived class has to be event
// driven and state based. That's just the nature of WebSockets. We will maintain the
// WebSockets level state info, but the derived class will typically have to maintain some
// application level state of his own.
//
// We provide an idle callback so that the derived class can do some periodic processing
// even if nothing is currently happening in terms of incoming msgs from the client. This
// callback must be quick and to the point, so that we can go right back to listening for
// incoming messages. It should catch any errors, otherwise we will terminate the connection
// and this object will be dead. A new one will have to be created.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
#pragma once
#pragma CIDLIB_PACK(CIDLIBPACK)
class TSChannel;
// ---------------------------------------------------------------------------
// CLASS: TCIDWebSockThread
// PREFIX: thr
// ---------------------------------------------------------------------------
class CIDWEBSOCKEXP TCIDWebSockThread : public TThread
{
public :
// --------------------------------------------------------------------
// Public, static methods
// --------------------------------------------------------------------
static tCIDLib::TBoolean bIsControlType
(
const tCIDLib::TCard1 c1Type
);
// --------------------------------------------------------------------
// Destructor
// --------------------------------------------------------------------
TCIDWebSockThread() = delete;
TCIDWebSockThread(const TCIDWebSockThread&) = delete;
~TCIDWebSockThread();
// --------------------------------------------------------------------
// Pubilc operators
// --------------------------------------------------------------------
TCIDWebSockThread& operator=(const TCIDWebSockThread&) = delete;
// --------------------------------------------------------------------
// Public, non-virtual methods
// --------------------------------------------------------------------
tCIDLib::TVoid EnableMsgLogging
(
const tCIDLib::TBoolean bState
, const TString& strPath
);
tCIDLib::TVoid SendTextMsg
(
const TString& strText
);
tCIDLib::TVoid StartShutdown
(
const tCIDLib::TCard2 c2Err
);
protected :
// --------------------------------------------------------------------
// Hidden constructors
// --------------------------------------------------------------------
TCIDWebSockThread
(
const TString& strName
, TCIDDataSrc* const pcdsToUse
, const tCIDLib::TBoolean bAdoptSrc
);
// --------------------------------------------------------------------
// Protected, inherited methods
// --------------------------------------------------------------------
tCIDLib::EExitCodes eProcess() final;
// --------------------------------------------------------------------
// Protected, virtual methods
// --------------------------------------------------------------------
virtual tCIDLib::TBoolean bWSInitialize() = 0;
virtual tCIDLib::TVoid WSCheckShutdownReq() const = 0;
virtual tCIDLib::TVoid WSConnected() = 0;
virtual tCIDLib::TVoid WSDisconnected() = 0;
virtual tCIDLib::TVoid WSIdle() = 0;
virtual tCIDLib::TVoid WSProcessMsg
(
const TString& strMsg
) = 0;
virtual tCIDLib::TVoid WSTerminate();
// --------------------------------------------------------------------
// Protected, non-virtual methods
// --------------------------------------------------------------------
tCIDLib::TVoid SendBinMsg
(
const tCIDLib::TCard1 c1Type
, const tCIDLib::TCard2 c2Payload
);
tCIDLib::TVoid SendMsg
(
const tCIDLib::TCard1 c1Type
, const THeapBuf& mbufData
, const tCIDLib::TCard4 c4DataCnt
);
tCIDLib::TVoid SendMsg
(
const tCIDLib::TCard1 c1Type
, const tCIDLib::TVoid* const pData
, const tCIDLib::TCard4 c4DataCnt
);
private :
// --------------------------------------------------------------------
// Protected, non-virtual methods
// --------------------------------------------------------------------
tCIDLib::TBoolean bGetFragment
(
tCIDLib::TCard1& c1Type
, tCIDLib::TBoolean& bFinal
, TMemBuf& mbufToFill
, tCIDLib::TCard4& c4MsgBytes
);
tCIDLib::TVoid Cleanup();
tCIDLib::EExitCodes eServiceClient();
tCIDLib::TVoid HandleMsg
(
const tCIDLib::TCard1 c1Type
, const THeapBuf& mbufData
, const tCIDLib::TCard4 c4DataCnt
);
tCIDLib::TVoid SendClose
(
const tCIDLib::TCard2 c2Code
);
tCIDLib::TVoid SendPing();
// --------------------------------------------------------------------
// Private data members
//
// m_bAdoptSrc
// Indicates if we are to adopt the provided data source or not. If so, then
// we clean it up when we terminate. We will always clean it up in terms of
// the socket session, but may also clean up the actual object if we own it.
//
// m_bSimMode
// Some programs may want directly call the service client method for testing
// purposes, i.e. avoid the extra thread that they don't control. This is
// defaulted to true. If eProcess gets called, it will set it to false since
// we know we were started on a separate thread. If not in sim mode then we
// can do things like check for standard thread shutdown requests.
//
// m_bWaitPong
// m_c4PingVal
// Remember if we are waiting for a pong response to a ping we have sent.
// We send a 32 bit value in each ping, which we increment each time, so
// this is the value we should get back in the pong. The byte order doesn't
// matter since the client doesn't interpret it, it just echoes it back.
//
// m_colFields
// The derived class can ask us to monitor fields. We set up these fields
// on the poll engine. We get back a poll info object for each field
// which we use to check for changes.
//
// m_eState
// Our current state, which the main loop uses to know what to do. It
// starts out in Connecting state and moves towards eventually one of the
// close states.
//
// m_enctEndTimer
// When we start a close from our side, we will wait for up to a certain
// amount of time for the other side to respond. Else we'll give up.
//
// m_enctLastInMsg
// m_enctLastOutMsg
// We track the last time we sent a message (on behalf of the derived class
// primarily) and the last time we got one from the client. If we haven't
// sent a message in the last 30 seconds, we'll send a ping so that the
// client doesn't give up on us.
//
// m_mbufRead
// The eGetFragment method reads in raw fragments. If it's masked, then
// it's read first into m_mbufRead, then unmasked into the caller's buffer
// Else it's read directly into the caller's buffer.
//
// m_mbufReadFrag
// This is used for reading in fragments. It's passed to eGetFragment()
// get any incoming fragement content. This is used by the main processing
// loop.
//
// m_mbufReadMsg
// We need a buffer to build up fragments into to create the final msg. This
// is used by the main processing loop, which just adds fragements into it
// until the final one.
//
// m_mbufWriteMsg
// For text messages, we need an intermediate buffer to convert outgoing
// text to UTF-8 encoding, and to build up the outgoing data whether binary
// or text.
//
// m_pcdsServer
// We are given the data source. We may or may not own it, depending on
// m_bAdoptSrc.
//
// m_pstrmLog
// The derived class can enable a log of messages exchanged. If enabled
// this is set, else it's null.
//
// m_strTextDispatch
// A temp string to use for transcoding text messages to a string to pass
// on to the derived class.
//
// m_tcvtText
// Text messages must be encoded to UTF8, so we keep one of these around
// for encoding outgoing and decoding text messages.
//
// m_tmLog
// A time object we use in logging. We pre-set it up for the desired time
// format, and just set it to the current time any time we want to output
// it to the log.
//
// m_urlReq
// The original request URL from the first HTTP line. We keep it around so
// that we can make it available to the derived class if needed.
// --------------------------------------------------------------------
tCIDLib::TBoolean m_bAdoptSrc;
tCIDLib::TBoolean m_bSimMode;
tCIDLib::TBoolean m_bWaitPong;
tCIDLib::TCard4 m_c4PingVal;
tCIDWebSock::EStates m_eState;
tCIDLib::TEncodedTime m_enctEndTimer;
tCIDLib::TEncodedTime m_enctLastInMsg;
tCIDLib::TEncodedTime m_enctLastOutMsg;
THeapBuf m_mbufRead;
THeapBuf m_mbufReadFrag;
THeapBuf m_mbufReadMsg;
THeapBuf m_mbufWriteMsg;
TCIDDataSrc* m_pcdsServer;
TTextFileOutStream* m_pstrmLog;
TString m_strTextDispatch;
TUTF8Converter m_tcvtText;
TTime m_tmLog;
TURL m_urlReq;
};
#pragma CIDLIB_POPPACK
| [
"droddey@charmedquark.com"
] | droddey@charmedquark.com |
36bdd5edf60eec48fe2160dc9f117f020807d0de | 733ce5efa9fa9c0e3881132caa87b28719c23316 | /projects/qgfx/include/qgfx/vulkan/vulkan_window.h | 89df475d8df027fe03272aeacc18bd437b60e3ca | [
"MIT"
] | permissive | Quadrion/qgfx | 1eeaa9ac57e5c01b71c9e9194cc48a429ebbecf2 | e853d5e357df052e0c09d4678c43ed96b4998778 | refs/heads/master | 2020-04-16T08:50:05.273804 | 2019-02-02T22:25:44 | 2019-02-02T22:25:44 | 165,439,946 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 593 | h | #ifndef vulkan_window_h__
#define vulkan_window_h__
#include "qgfx/api/iwindow.h"
#include "GLFW/glfw3.h"
class VulkanWindow : public IWindow
{
public:
VulkanWindow();
~VulkanWindow();
void construct(const WindowCreationParameters& params) override;
void construct(const uint32_t width, const uint32_t height, const qtl::string& title, const bool fullscreen = false, const bool vsync = false) override;
void* getPlatformHandle() const override;
bool shouldClose() const override;
void poll() const override;
private:
GLFWwindow* mWindow;
};
#endif // vulkan_window_h__ | [
"roderick.griffioen@gmail.com"
] | roderick.griffioen@gmail.com |
7bdfeaac132ecd1bc91dc41163f4a8a0bf25bab7 | 87909cb9d4d17eb5e403a907179befe40d94823e | /Chapter4/4.10.cpp | f9afa82ddeaba3a824a5f6bfaf38355559dfc842 | [] | no_license | DUNDUN-ww/C--Practices | 7c7975a821e69170f397881d8ea886a3ca95bb85 | fac46083e6076835501cf416064f3b2cbd21c9ed | refs/heads/main | 2023-06-17T16:21:45.148010 | 2021-07-25T15:13:54 | 2021-07-25T15:13:54 | 367,222,295 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 139 | cpp | #include<iostream>
using namespace std;
int main()
{
int num;
while (cin >> num && num != 42)
{
cout << num << endl;
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
449dabece9dbfb8bfe77ba43103c3e32ee69c29a | 33cda0dda919ec510727092a5e7c8ed7ed487b47 | /rover.ino | 554eff9e54fb77d26f10e3f796499a1cd82e1027 | [] | no_license | usfsoar/NSL_17-18_Rover | 79dbf5e0b32aaff890502c06af596ad895c22a41 | 43e2f68cdffcff6c649341a12f854d4415c0705d | refs/heads/master | 2021-09-11T13:34:02.635265 | 2018-04-08T01:52:50 | 2018-04-08T01:52:50 | 110,897,521 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 574 | ino |
#include <SoftwareSerial.h>
//SoftwareSerial xbee(1,0);
String readString;
void setup()
{
Serial.begin(9600);
Serial.println("rover is ready");
}
void loop() {
while (Serial.available()) { //as long as there is data on incoming serial buffer...
//Characers are read from the serial buffer and concatinated
char c = Serial.read();
readString += c;
delay(2);
}
if(readString ==" rover deployed."){
Serial.print("Rover is roving...");
}
else Serial.print(readString);
readString="";
}
| [
"noreply@github.com"
] | noreply@github.com |
bb9b311f7084238f9e4eabdabd4a01561fecf327 | 1f0a59409972f72a2a766e2c33927f5aaf6646a6 | /ex2/FilterTwo.cpp | cafbe8ea8eb818b1b4476a535c1ba607e28fb7fa | [] | no_license | BorisKolev/Cpp-Assignment | e671a15b5a246a29261bdea8483402188fd8b39e | 8d4f3a4eaba6f59f5509777bc496110d28165463 | refs/heads/master | 2020-12-19T05:32:01.389863 | 2020-01-22T17:59:51 | 2020-01-22T17:59:51 | 235,620,819 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 612 | cpp |
#include "FilterTwo.h"
bool FilterTwo::filter(std::string word) {
bool hasAlpha = false;
bool hasDigit = false;
// Iterate through the word one character at a time
for(int i = 0; i < word.length(); i++){
// If is alphanumeric character, make a note of it
if(isalpha(word[i])){
hasAlpha = true;
}
// If digit, make a note of it
if(isdigit(word[i])){
hasDigit = true;
}
}
// If satisfies the filter, return true
// Otherwise it hasn't satisfied the filter, thus return false
return hasAlpha && hasDigit;
};
| [
"bk18145@essex.ac.uk"
] | bk18145@essex.ac.uk |
7e71a462665bbc7f6e04e321fabde5fb6e3bf479 | 74060cc6c998a226ad4fe9e8ccabff5055fced3f | /tools/blm_scalar_emulation/juce/JuceLibraryCode/modules/juce_core/streams/juce_MemoryOutputStream.cpp | 79d51d41fb97af740c3cacda667aa7ecc8bb7235 | [] | no_license | antichambre/MIOS32 | 897d8bbdf712f8e61ad63ac32c71fe764f2a4283 | e165abe2923674d0d12c1fef888f81919d733a04 | refs/heads/master | 2022-08-06T00:58:47.762241 | 2021-01-24T10:14:38 | 2021-01-24T10:14:38 | 183,661,458 | 4 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 4,932 | cpp | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
: data (internalBlock),
position (0),
size (0)
{
internalBlock.setSize (initialSize, false);
}
MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
const bool appendToExistingBlockContent)
: data (memoryBlockToWriteTo),
position (0),
size (0)
{
if (appendToExistingBlockContent)
position = size = memoryBlockToWriteTo.getSize();
}
MemoryOutputStream::~MemoryOutputStream()
{
trimExternalBlockSize();
}
void MemoryOutputStream::flush()
{
trimExternalBlockSize();
}
void MemoryOutputStream::trimExternalBlockSize()
{
if (&data != &internalBlock)
data.setSize (size, false);
}
void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
{
data.ensureSize (bytesToPreallocate + 1);
}
void MemoryOutputStream::reset() noexcept
{
position = 0;
size = 0;
}
void MemoryOutputStream::prepareToWrite (size_t numBytes)
{
jassert ((ssize_t) numBytes >= 0);
size_t storageNeeded = position + numBytes;
if (storageNeeded >= data.getSize())
data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31u);
}
bool MemoryOutputStream::write (const void* const buffer, size_t howMany)
{
jassert (buffer != nullptr && ((ssize_t) howMany) >= 0);
if (howMany > 0)
{
prepareToWrite (howMany);
memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
position += howMany;
size = jmax (size, position);
}
return true;
}
void MemoryOutputStream::writeRepeatedByte (uint8 byte, size_t howMany)
{
if (howMany > 0)
{
prepareToWrite (howMany);
memset (static_cast<char*> (data.getData()) + position, byte, howMany);
position += howMany;
size = jmax (size, position);
}
}
MemoryBlock MemoryOutputStream::getMemoryBlock() const
{
return MemoryBlock (getData(), getDataSize());
}
const void* MemoryOutputStream::getData() const noexcept
{
if (data.getSize() > size)
static_cast <char*> (data.getData()) [size] = 0;
return data.getData();
}
bool MemoryOutputStream::setPosition (int64 newPosition)
{
if (newPosition <= (int64) size)
{
// ok to seek backwards
position = jlimit ((size_t) 0, size, (size_t) newPosition);
return true;
}
// can't move beyond the end of the stream..
return false;
}
int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
{
// before writing from an input, see if we can preallocate to make it more efficient..
int64 availableData = source.getTotalLength() - source.getPosition();
if (availableData > 0)
{
if (maxNumBytesToWrite > availableData)
maxNumBytesToWrite = availableData;
preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
}
return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
}
String MemoryOutputStream::toUTF8() const
{
const char* const d = static_cast <const char*> (getData());
return String (CharPointer_UTF8 (d), CharPointer_UTF8 (d + getDataSize()));
}
String MemoryOutputStream::toString() const
{
return String::createStringFromData (getData(), (int) getDataSize());
}
OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
{
const size_t dataSize = streamToRead.getDataSize();
if (dataSize > 0)
stream.write (streamToRead.getData(), dataSize);
return stream;
}
| [
"bdupeyron@gmail.com"
] | bdupeyron@gmail.com |
b74de9c711a8e1e2f27ca16d88ce044f802d8bfe | 500cefdd4be437ffcab13d20b88ea0d413d711e8 | /debug/moc_loginwindow.cpp | a1a38819db4bfa3747c71e7fe4f7a73916d3863d | [] | no_license | rstrzelczyk/multikina | 03d3f02ac28947a01a7f9b51fb59914aebc75c63 | 78caee162bd622ccba37eea176d0185def730ccc | refs/heads/master | 2021-01-10T04:33:57.951921 | 2016-01-19T10:00:45 | 2016-01-19T10:00:45 | 49,642,417 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,273 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'loginwindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.0.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../loginwindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'loginwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.0.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_LoginWindow_t {
QByteArrayData data[3];
char stringdata[42];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
offsetof(qt_meta_stringdata_LoginWindow_t, stringdata) + ofs \
- idx * sizeof(QByteArrayData) \
)
static const qt_meta_stringdata_LoginWindow_t qt_meta_stringdata_LoginWindow = {
{
QT_MOC_LITERAL(0, 0, 11),
QT_MOC_LITERAL(1, 12, 27),
QT_MOC_LITERAL(2, 40, 0)
},
"LoginWindow\0on_pushButtonlog_in_clicked\0"
"\0"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_LoginWindow[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 19, 2, 0x08,
// slots: parameters
QMetaType::Void,
0 // eod
};
void LoginWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
LoginWindow *_t = static_cast<LoginWindow *>(_o);
switch (_id) {
case 0: _t->on_pushButtonlog_in_clicked(); break;
default: ;
}
}
Q_UNUSED(_a);
}
const QMetaObject LoginWindow::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_LoginWindow.data,
qt_meta_data_LoginWindow, qt_static_metacall, 0, 0}
};
const QMetaObject *LoginWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *LoginWindow::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_LoginWindow.stringdata))
return static_cast<void*>(const_cast< LoginWindow*>(this));
return QMainWindow::qt_metacast(_clname);
}
int LoginWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 1)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 1;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"strzelczyk.renata@gmail.com"
] | strzelczyk.renata@gmail.com |
bdc7ef891d38312741d5ba291c06fc41b6caa795 | 28e0086f6788fda57bbe6eb329734bc527e1c46a | /mh2-re/CPlayer.cpp | f3bc10f410e8bc5ab0167c952281fc8f622bcdf0 | [] | no_license | Sor3nt/Manhunt-2-Keyboard-Mapping | 0aef034be58135eb4f051b760670cba03be59422 | 980ed5d5f772ac45169ab2fea4c06587089d10ef | refs/heads/master | 2021-02-18T10:36:32.056042 | 2020-09-13T09:30:50 | 2020-09-13T09:30:50 | 245,186,962 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 119 | cpp | #include "CPlayer.h"
int CPlayer::GetExecuteStage(int entity)
{
return ((int(__thiscall*)(int))0x599840)(entity);
}
| [
"hyp3rdaewoo"
] | hyp3rdaewoo |
7bf54c23a23341ee47d9aad6d9d05fbc98035fa7 | 5a0368cb6e6ba47114923f8066e06f1ab2b4b58f | /src/Led.h | dc9aefefce43ad16285c321614d19958a5632418 | [
"MIT"
] | permissive | jjankowski87/IotHome.ESP8266Sensor | 2c27fd0839a93306e3b01191fcf5b86bd010cd47 | bcf53f615523cc632745b4869cdef192cdbdd6e0 | refs/heads/master | 2023-06-07T22:11:58.686831 | 2023-06-01T05:28:14 | 2023-06-01T05:28:14 | 236,956,045 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 458 | h | #ifndef Led_h
#define Led_h
#include "Enums.h"
#include <Arduino.h>
#include <Ticker.h>
class Led
{
public:
Led(byte greenPin, byte redPin);
~Led();
void blink(LedColor color, float seconds);
void on(LedColor color);
void off(LedColor color);
private:
byte _greenPin;
Ticker* _greenTicker;
byte _redPin;
Ticker* _redTicker;
void toggle(byte pin);
};
#endif | [
"jjankowski@future-processing.com"
] | jjankowski@future-processing.com |
d31fc041e4732dc016c146dba68c65d5c4c86e1b | 25bb3a29838f65e9bca3b4b490ecd1a7db43bd09 | /Data Structure/Discretization.cpp | 5a22770a6bc96d40aea26edf0e40bf27969a56e4 | [] | no_license | katoli/GZHU-Pour_Cappuccino_to_OJ | 7144732822bc3c9cf58135ab8415f7a7de6ed23e | 7c9f1e987f0cae97e3e76374e5f6560b4bf435f2 | refs/heads/master | 2022-09-16T20:23:32.157784 | 2020-06-05T10:41:41 | 2020-06-05T10:41:41 | 278,049,545 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 776 | cpp | /*--waltz26--*/
//去重离散化
//a为原数组(离散化数组),b为离散化对照数组,c为映射数组
int a[1000005],b[1000005],c[1000005];
int main()
{
int n;
cin>>n;
for (int i=1;i<=n;i++)
{
cin>>a[i];
b[i]=a[i];
}
sort(b+1,b+n+1);
int m=unique(b+1,b+n+1)-(b+1);
for (int i=1;i<=n;i++)
{
int v=a[i];
a[i]=lower_bound(b+1,b+m+1,v)-b;
c[a[i]]+=v;
}
}
/*--waltz26--*/
//不去重离散化
int a[500005],r[500005]; //离散化数组
bool cmp(const int &x,const int &y)
{
return a[x]<a[y];
}
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
r[i]=i; //初始化r
}
sort(r+1,r+1+n,cmp); //离散化
}
| [
"noreply@github.com"
] | noreply@github.com |
b2ad8804e26e1f735f1df43a38298f1b344a8c51 | 6efb28d0ab32d25f04f864a5e9188a222fd12635 | /src/prox_lp.cpp | 1535e0a414a9fc194ddc744c43c51d52aeaa80d3 | [] | no_license | lxiao0620/gradfps | aea45e976bedcdb0f9325661be2a83481bd37329 | 88ed8a9475bff9b61061f6926b9fe1b49c11ada5 | refs/heads/master | 2022-10-02T15:08:37.819535 | 2020-05-25T17:06:15 | 2020-05-25T17:06:15 | 270,347,049 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,353 | cpp | #include "prox_lp.h"
using Rcpp::NumericVector;
using Rcpp::NumericMatrix;
//' Proximal operator of squared Lp norm
//'
//' This function solves the optimization problem
//' \deqn{\min\quad\frac{1}{2}||x||_p^2 + \frac{1}{2\alpha}||x - v||^2}{min 0.5 * ||x||_p^2 + (0.5 / \alpha) * ||x - v||^2}
//'
//' @param v A numeric vector.
//' @param V A symmetric matrix.
//' @param p Norm parameter.
//' @param alpha Proximal parameter.
//' @param eps Precision of the result.
//' @param maxiter Maximum number of iterations.
//' @param verbose Level of verbosity.
//'
// [[Rcpp::export]]
NumericVector prox_lp(NumericVector v, double p, double alpha,
double eps = 1e-6, int maxiter = 100, int verbose = 0)
{
const int n = v.length();
MapConstVec vv(v.begin(), n);
NumericVector res(n);
MapVec x(res.begin(), n);
prox_lp_impl(vv, p, alpha, x, eps, maxiter, verbose);
return res;
}
//' @rdname prox_lp
//'
// [[Rcpp::export]]
NumericMatrix prox_lp_mat(NumericMatrix V, double p, double alpha,
double eps = 1e-6, int maxiter = 100, int verbose = 0)
{
const int n = V.nrow();
MapConstMat VV(V.begin(), n, n);
NumericMatrix res(n, n);
MapMat X(res.begin(), n, n);
prox_lp_mat_impl(VV, p, alpha, X, eps, maxiter, verbose);
return res;
}
| [
"yixuanq@gmail.com"
] | yixuanq@gmail.com |
7c9236340975a83d29ae2c8c3702640401cac0f9 | c8486a1ed5af5d30c104e31b6eb45b54bb9029b4 | /memento/src/textrecordmemento.cpp | b95c14d117db99778c38c54db1dd3329d186a066 | [] | no_license | raidenawkward/design_pattern | 5c9b2885bdc0697ffc6e31d033db2f399404326b | 28cbed5d23e3937a7ed8bf2b976c9ce9d239d568 | refs/heads/master | 2021-01-10T20:18:52.801821 | 2014-02-17T15:12:03 | 2014-02-17T15:12:03 | 9,130,398 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 120 | cpp | #include "textrecordmemento.h"
TextRecordMemento::TextRecordMemento()
{
}
TextRecordMemento::~TextRecordMemento()
{
}
| [
"raiden.ht@gmail.com"
] | raiden.ht@gmail.com |
488577b9c8996d813016e294e2b319085da5465f | 0fd71c6826d2fef1b8a4654bf61c1ff359a04c7c | /DataFile.h | 68fbf7ec8baf453012f86da54efb27911da3b784 | [] | no_license | m2c2-project/DolphinParser | 8f6edf1aa0a4cd5fcc227466b4d7dd9762b1634c | 8e76eb894744b6b513e4094bca25f6987acf4ca1 | refs/heads/master | 2023-03-11T08:00:12.911426 | 2021-02-15T19:56:29 | 2021-02-15T19:56:29 | 181,764,803 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 900 | h |
#ifndef DATA_FILE_FH
#define DATA_FILE_FH 1
#include "main.h"
class DataElement;
class GameData;
class ExtraData;
// this class is for each individual file read
// each individual file is from one session
// so it contains:
// 1 pack
// 1 user
// 1 session id
// a list of game data (a pack can contain multiple games)
// a list of survey data
// it saves
class DataFile
{
public:
DataFile(KString sfilename);
~DataFile();
KString filename;
// extra info
KString ID;
bool surveyComplete;
int sessionID;
KString packName;
KString exitStatus;
KString exitScreen;
void HandleExtraInfo(DataElement* data);
void Read();
GList<DataElement*> elementList;
GList<GameData*> gameDataList;
GList<KString> tableLine;
void MakeTableLine(GList<KString>* headerList);
};
#endif
| [
"curt@ctkling.com"
] | curt@ctkling.com |
f5f4a995ee2c6d37f0fead356cb017e365ffab0e | 4fba6b009fae3f860e7e740d6176b8a8ff57ab8f | /src/compute_autocorrelation.h | 73db7e073eab0eb08fc647eb13dbd9f2da584fbd | [] | no_license | allaisandrea/ising-model | df0b427d9ad80ec13fc3e6d0fd903875d399494a | 97723f84d05b0d00b8d5940b55504c9ff0a69b7a | refs/heads/master | 2022-04-26T00:50:00.748175 | 2020-04-28T00:20:23 | 2020-04-28T00:20:23 | 126,037,197 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,952 | h | #pragma once
#include "udh_file_group.h"
#include <Eigen/Core>
#include <array>
inline Eigen::ArrayXd ComputeAutocorrelation(uint64_t n_ac, uint64_t n_read,
UdhFileGroup *file_group) {
if (n_read == 0) {
throw std::logic_error("n_read must be greater than zero");
}
const UdhFileGroup::Position position = file_group->GetPosition();
Eigen::Array3d mean;
mean.setZero();
UdhObservables observables;
for (uint64_t i = 0; i < n_read; ++i) {
if (!file_group->NextObservables(&observables)) {
throw std::runtime_error(
"Reached end of data at i = " + std::to_string(i) + " / " +
std::to_string(n_read));
}
mean(0) += observables.n_down();
mean(1) += observables.n_holes();
mean(2) += observables.n_up();
}
mean /= n_read;
Eigen::Array3d var;
Eigen::Array3d cov;
var.setZero();
cov.setZero();
file_group->SetPosition(position);
auto circular_next = [](uint64_t i, uint64_t n) {
++i;
if (i >= n) {
i = 0;
}
return i;
};
uint64_t hist_size = n_ac + 1;
Eigen::ArrayXXd delta(3, hist_size);
std::vector<uint64_t> file_index(hist_size);
Eigen::ArrayXXd autocovariance = Eigen::ArrayXXd::Zero(3, hist_size);
std::vector<uint64_t> count(hist_size, 0);
uint64_t hist_begin = 0;
uint64_t hist_end = 0;
for (uint64_t i = 0; i < n_read; ++i) {
if (!file_group->NextObservables(&observables,
&file_index.at(hist_end))) {
throw std::runtime_error(
"Reached end of data at i = " + std::to_string(i) + " / " +
std::to_string(n_read));
}
delta(0, hist_end) = observables.n_down() - mean(0);
delta(1, hist_end) = observables.n_holes() - mean(1);
delta(2, hist_end) = observables.n_up() - mean(2);
const uint64_t hist_last = hist_end;
hist_end = circular_next(hist_end, hist_size);
if (hist_end == hist_begin) {
hist_begin = circular_next(hist_begin, hist_size);
}
for (uint64_t j = hist_begin; j != hist_end;
j = circular_next(j, hist_size)) {
const uint64_t k = (hist_last + hist_size - j) % hist_size;
if (file_index.at(k) == file_index.at(hist_last)) {
autocovariance.col(k) += delta.col(j) * delta.col(hist_last);
++count.at(k);
}
}
}
Eigen::ArrayXd autocorrelation(2 * n_ac);
for (uint64_t i = 0; i < n_ac; ++i) {
autocorrelation(2 * i) =
0.5 * (autocovariance(0, i) / autocovariance(0, 0) +
autocovariance(2, i) / autocovariance(2, 0));
autocorrelation(2 * i + 1) =
autocovariance(1, i) / autocovariance(1, 0);
}
return autocorrelation;
}
| [
"allais.andrea@gmail.com"
] | allais.andrea@gmail.com |
7db889c520016ce318353826fe3b204284aa8d04 | 01188d936daa415d4ca7584b222685bc7aa451bd | /7~9/7-42.cpp | 63ea1db7eeb8e68e89ffe64d4cb2cef312066858 | [] | no_license | csy-59/C-Study | fe44d76e469defc21652a1bf4088e87a015a5863 | a835b4db75ecdb9248104f64c9ec0f2d2e5985cd | refs/heads/master | 2023-03-21T17:38:32.042786 | 2021-02-28T11:17:28 | 2021-02-28T11:17:28 | 343,084,444 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 645 | cpp | #include <iostream>
using namespace std;
void dec2Hex(int value, char hexString[]);
int main() {
int value;
char hexString[20] = { '\0' };
cout << "Enter number: ";
cin >> value;
dec2Hex(value, hexString);
return 0;
}
void dec2Hex(int value, char hexString[]) {
int i = 0;
while (value >= 16) {
if (value % 16 > 9)
hexString[i] = 'a' + value % 16 - 10;
else
hexString[i] = '0' + value % 16;
value /= 16;
i++;
}
if (value > 9)
hexString[i] = 'a' + value - 10;
else
hexString[i] = '0' + value;
cout << "Result is ";
for (int j = strlen(hexString) - 1;j >= 0;j--)
cout << hexString[j];
cout << endl;
} | [
"csy010509@naver.com"
] | csy010509@naver.com |
6295d2b1246c065672e898c2385f2306b7b436e9 | c2acfd598c62802d30527c7ccb88678a2a816e43 | /include/genericdp/state_iterator_factory.h | cfd4529c189b16549ec0c8fead4b06f70ffcbe9c | [] | no_license | kajames2/genericdp | f18fd80d55e7f096fe0fbfe33ab53e5715187cec | d7d8217a9e674fde5872984de6837efdf8917bd2 | refs/heads/master | 2021-09-19T11:49:24.777673 | 2018-07-27T18:39:19 | 2018-07-27T18:39:19 | 107,728,697 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 710 | h | #ifndef _GENERICDP_STATE_ITERATOR_FACTORY_H_
#define _GENERICDP_STATE_ITERATOR_FACTORY_H_
#include <memory>
#include "genericdp/state.h"
#include "genericdp/state_iterator.h"
namespace genericdp {
template <typename InState, typename OutDec>
class DPStateIteratorFactory {
public:
virtual std::unique_ptr<StateIterator<InState, OutDec>> GetIterator(
const State<InState, OutDec>& input) const = 0;
DPStateIteratorFactory() = default;
DPStateIteratorFactory(const DPStateIteratorFactory&) = delete;
DPStateIteratorFactory& operator=(const DPStateIteratorFactory&) = delete;
virtual ~DPStateIteratorFactory() {}
};
} // namespace genericdp
#endif // _GENERICDP_DP_STATE_ITERATOR_FACTORY_H_
| [
"james144@mail.chapman.edu"
] | james144@mail.chapman.edu |
a51abbe1ca0cfa250a92e9222f869507d14d07a7 | 7e8c72c099b231078a763ea7da6bba4bd6bac77b | /other_projects/base_station_monitor/Client/reference SDK/General_NetSDK_Chn_IS_V3.36.0.R.100505/Demo/综合应用/VC_Demo/AlarmCtrlDlg.h | 7e90c89e0af8a7d8ebb6b514584ad9641962cddf | [] | no_license | github188/demodemo | fd910a340d5c5fbf4c8755580db8ab871759290b | 96ed049eb398c4c188a688e9c1bc2fe8cd2dc80b | refs/heads/master | 2021-01-12T17:16:36.199708 | 2012-08-15T14:20:51 | 2012-08-15T14:20:51 | 71,537,068 | 1 | 2 | null | 2016-10-21T06:38:22 | 2016-10-21T06:38:22 | null | GB18030 | C++ | false | false | 1,609 | h | #if !defined(AFX_ALARMCTRLDLG_H__6DE10DCD_44E8_4830_ABA3_915908E9B71C__INCLUDED_)
#define AFX_ALARMCTRLDLG_H__6DE10DCD_44E8_4830_ABA3_915908E9B71C__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// AlarmCtrlDlg.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CAlarmCtrlDlg dialog
#define MAX_IO_NUM DH_MAX_ALARM_IN_NUM
class CAlarmCtrlDlg : public CDialog
{
LONG m_DeviceId;
int m_inNum;
int m_outNum;
ALARM_CONTROL m_inState[MAX_IO_NUM];
ALARM_CONTROL m_outState[MAX_IO_NUM];
ALARMCTRL_PARAM m_triggerIn[MAX_IO_NUM];
// Construction
public:
CAlarmCtrlDlg(CWnd* pParent = NULL); // standard constructor
void SetDeviceId(LONG nDeviceId); //设置当前设备ID
// Dialog Data
//{{AFX_DATA(CAlarmCtrlDlg)
enum { IDD = IDD_ALARMCTRL };
// NOTE: the ClassWizard will add data members here
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAlarmCtrlDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CAlarmCtrlDlg)
afx_msg void OnSaveIo();
afx_msg void OnCancel();
virtual BOOL OnInitDialog();
afx_msg void OnTrigger();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_ALARMCTRLDLG_H__6DE10DCD_44E8_4830_ABA3_915908E9B71C__INCLUDED_)
| [
"thinkinnight@b18a5524-d64a-0410-9f42-ad3cd61580fb"
] | thinkinnight@b18a5524-d64a-0410-9f42-ad3cd61580fb |
c187ef06a1254b60db2011c894e35577e71794c3 | ec904b09618d7c3b760c7111538ee0e60359f01a | /main.cpp | 03a62f819c726fe013f0b5a003ebc1c133573497 | [] | no_license | LeXgv/posix-thread | 958b800bd9d1ee06ef0c5bf16dd95096b20a40e8 | 370697df2b7a9725b9e4eb28f6384bd43db4bff9 | refs/heads/master | 2021-06-21T20:16:51.423136 | 2017-08-14T13:48:01 | 2017-08-14T13:48:01 | 100,273,175 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 898 | cpp | #include <pthread.h>
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
void *thread_func(void *arg)
{
std::cout << "Запущен новый поток\n";
while(true){}
return NULL;
}
int main()
{
std::cout << "программа запущена/n";
pid_t pid = getpid();
int fd = open("main.pid", O_CREAT | O_TRUNC | O_RDWR, 0777);
char buf[50] = {0};
snprintf(buf, 50, "%d", (int)pid);
write(fd,buf, strlen(buf));
std::cout << pid << std::endl;
close(fd);
pthread_t p_id;
pthread_attr_t attr;
//инициализация атрибутов
pthread_attr_init(&attr);
//запуск потока
pthread_create(&p_id, &attr, thread_func, NULL);
//ожидание потока
std::cout <<"переход в режим ожидания потока\n";
void *t;
pthread_join(p_id, &t);
return 1;
}
| [
"alekseu147147@yandex.ru"
] | alekseu147147@yandex.ru |
3c15dd856f74b46bf2bb8ec8a83706f36cb42372 | 38c10c01007624cd2056884f25e0d6ab85442194 | /chrome/browser/extensions/stubs_apitest.cc | 052a2dbee250687b1f77f075063e5f48f482d418 | [
"BSD-3-Clause"
] | permissive | zenoalbisser/chromium | 6ecf37b6c030c84f1b26282bc4ef95769c62a9b2 | e71f21b9b4b9b839f5093301974a45545dad2691 | refs/heads/master | 2022-12-25T14:23:18.568575 | 2016-07-14T21:49:52 | 2016-07-23T08:02:51 | 63,980,627 | 0 | 2 | BSD-3-Clause | 2022-12-12T12:43:41 | 2016-07-22T20:14:04 | null | UTF-8 | C++ | false | false | 1,608 | cc | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/ui_test_utils.h"
#include "extensions/test/result_catcher.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "url/gurl.h"
// Tests that we throw errors when you try using extension APIs that aren't
// supported in content scripts.
// Timey-outy on mac. http://crbug.com/89116
#if defined(OS_MACOSX)
#define MAYBE_Stubs DISABLED_Stubs
#else
#define MAYBE_Stubs Stubs
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Stubs) {
ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
ASSERT_TRUE(RunExtensionTest("stubs")) << message_;
// Navigate to a simple http:// page, which should get the content script
// injected and run the rest of the test.
GURL url(embedded_test_server()->GetURL("/extensions/test_file.html"));
ui_test_utils::NavigateToURL(browser(), url);
extensions::ResultCatcher catcher;
ASSERT_TRUE(catcher.GetNextResult());
}
// Tests that all API features that are available to a platform app actually
// can be used in an app. For example, this test will fail if a developer adds
// an API feature without providing a schema. http://crbug.com/369318
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, StubsApp) {
ASSERT_TRUE(RunPlatformAppTestWithFlags(
"stubs_app", static_cast<int>(kFlagIgnoreManifestWarnings)))
<< message_;
}
| [
"zeno.albisser@hemispherian.com"
] | zeno.albisser@hemispherian.com |
f14a93b9cedb8ff0ba928037a8686d0520e124ed | dcfc11ac9669c00153265347d16a87722c3d6003 | /Lect2/zoo.cpp | c04a2cf9d635782b1d012cdf1be002a64995a3e7 | [] | no_license | MrIvanushka/cpp_2sem | fdaf09691767408ac10c6e9ae9582532d14f66dc | b16f153efc5c413b25ef81e67134ef4e2f68fca4 | refs/heads/main | 2023-04-07T03:02:18.844719 | 2021-04-15T22:30:22 | 2021-04-15T22:30:22 | 344,608,365 | 0 | 0 | null | 2021-04-15T22:30:22 | 2021-03-04T21:01:20 | C++ | UTF-8 | C++ | false | false | 2,117 | cpp | #include <iostream>
#include <string.h>
using namespace std;
/*
Пишем класс, который умеет взаимодействовать с другими классами.
Причём другие классы могут быть очень разные - иерархия наследования
у них может оказаться очень развесистой.Но наш класс общается с
ними через единый интерфейс, благодаря чему отдельной обработки
всех случаев писать не требуется.
У вас есть зоопарк разных классов.У них есть общий интерфейс.Вот такой :
*/
class Animal {
public:
virtual string getType() = 0;
virtual bool isDangerous() = 0;
};
/*
Сколько и каких конкретных зверей будет потом
создано - вы не знаете.Но для вас интерфейс к ним всем будет таким.
Нужно написать класс смотрителя зоопарка. Классу передают на вход зверей,
он их всех последовательно осматривает и пересчитывает, сколько из них было опасных.
*/
class ZooKeeper {
public:
// Создаём смотрителя зоопарка
ZooKeeper();
// Смотрителя попросили обработать очередного зверя.
// Если зверь был опасный, смотритель фиксирует у себя этот факт.
void handleAnimal(Animal* a);
// Возвращает, сколько опасных зверей было обработано на данный момент.
int getDangerousCount();
private:
int DangerousCount;
};
ZooKeeper::ZooKeeper() : DangerousCount(0)
{ }
void ZooKeeper::handleAnimal(Animal* a)
{
if (a->isDangerous())
DangerousCount++;
}
int ZooKeeper::getDangerousCount()
{
return DangerousCount;
}
| [
"74343782+MrIvanushka@users.noreply.github.com"
] | 74343782+MrIvanushka@users.noreply.github.com |
60d0a7cdcd543eb0440f97dabc354df89148e7b1 | 435734fea3031191e9e00d5d54d8b14d7b01ee48 | /cpp/trial97.cpp | 97dffabd1d0294c70390c2754432663013f3a231 | [] | no_license | sumansourabh26/everyday_codes | 1f4bc4b05fdb51512b68c37371933535d90edf10 | 2a8c097adbb64d103dc823bdb9987e99dfd9943b | refs/heads/master | 2020-05-04T15:22:13.872019 | 2014-11-05T16:11:08 | 2014-11-05T16:11:08 | 17,599,784 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,758 | cpp | #include<iostream>
using namespace std;
void assign_s(string &pattern, int s[]){
s[0]=0;
int i = 1;
int l = 0;
for(; i<pattern.size();){
l=i-1;
while(true){
if(pattern[s[l]]==pattern[i]){
s[i]=s[l]+1;
i++;
break;
}
else{
if(l==0){
s[i]=0;
i++;
break;
}
else{
l = s[l-1];
}
}
}
}
}
void assign_f(string &pattern,int s[], int f[]){
f[0]=-1;
int i = 1;
int l = 0;
for(; i<pattern.size();){
l=s[i-1];
while(true){
if(pattern[l]!=pattern[i]){
f[i]=l;
i++;
break;
}
else{
if(l==0){
f[i]=-1;
i++;
break;
}
else{
l = s[l-1];
}
}
}
}
}
int main(){
string text;
cin>>text;
int no_of_inputs;
cin>>no_of_inputs;
string pattern[no_of_inputs];
int answer=0;
for(int counter = 0; counter<no_of_inputs;counter++){
cin>>pattern[counter];
}
for(int counter = 0; counter<no_of_inputs;counter++){
string pattern1 = pattern[counter];
int size_of_pattern = pattern1.size();
int s[size_of_pattern];
int f[size_of_pattern];
assign_s(pattern1, s);
assign_f(pattern1, s, f);
//for(int i = 0; i < size_of_pattern;i++){
//cout<<s[i]<<' ';
//}//cout<<endl;
//for(int i = 0; i < size_of_pattern;i++){
//cout<<f[i]<<' ';
//}//cout<<endl;
int p = 0;
for(int st = 0; st < text.size();){
if(pattern1[p]==text[st]){
p++;
st++;
if(p==size_of_pattern){
if(pattern1[s[p-1]] == text[st]){
p = s[p-1];
}
else{
p = 0;
}
answer = answer+1;
//cout<<"match at "<<st-size_of_pattern<<endl;
}
}
else{
if( f[p] == -1){
p = 0;
st++;
}
else{
p = f[p];
}
}
}
//cout<<"answer:";
//cout<<answer<<endl;
}
cout<<answer;
}
| [
"sumansourabh26@outlook.in"
] | sumansourabh26@outlook.in |
11cbcba8f2dbf70375753ff29e235ab655201431 | b9f92f49089d5dd53e79acad61c103687f50d27c | /amm.cpp | f7ed0fa421868642ba7aaf4aaee01955d3939a77 | [] | no_license | Sabbir1234/Problem-Solving | 54c5cd58c809e724b695843a918bf02ac2d5fff9 | a1cdcb640500ae6926cafbfb082f2ed1190b1fa4 | refs/heads/master | 2022-11-22T02:27:24.464805 | 2020-07-27T14:07:57 | 2020-07-27T14:07:57 | 282,916,027 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 243 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int t;
string s,a;
cin>>t;
while(t--){
cin>>s;
a=s;
for(int i=1;i<a.length();i++){
if(a[i]==a[i-1]){
s[i]='#';
}
}
cout<<s<<endl;
}
}
| [
"sabbirhimu31@gmail.com"
] | sabbirhimu31@gmail.com |
aa42b8712d1a32d02f55e74be57b749614e850c2 | 89055b236e39e867c22dc6a06b0d9d77bafed292 | /media/papers/OpenPatternMatching/artifact/code/guards.cpp | 747f19d886c282968c276a22566df0f699b3dea1 | [
"BSD-3-Clause"
] | permissive | gabrielPeart/Mach7 | 6a6713216ab1981e658df60455b2190a1df6d5ec | 926ba15667f815159be814a9229b620871abe38b | refs/heads/master | 2020-05-29T11:34:41.875361 | 2015-09-30T07:18:02 | 2015-09-30T07:18:02 | 43,492,033 | 1 | 0 | null | 2015-10-01T11:08:25 | 2015-10-01T11:08:24 | null | UTF-8 | C++ | false | false | 3,519 | cpp | ///
/// \file
///
/// This file is a part of pattern matching testing suite.
///
/// \author Yuriy Solodkyy <yuriy.solodkyy@gmail.com>
///
/// This file is a part of Mach7 library (http://parasol.tamu.edu/mach7/).
/// Copyright (C) 2011-2012 Texas A&M University.
/// All rights reserved.
///
#include "match.hpp" // Support for Match statement
#include "patterns/combinators.hpp" // Support for pattern combinators
#include "patterns/constructor.hpp" // Support for constructor patterns
#include "patterns/guard.hpp" // Support for guard patterns
#include "patterns/n+k.hpp" // Support for n+k patterns
#include <complex>
#include <iostream>
enum { cart = mch::default_layout, plar = 1 };
namespace mch ///< Mach7 library namespace
{
#if defined(_MSC_VER) && _MSC_VER >= 1700 || defined(__GNUC__) && XTL_GCC_VERSION > 40700
/// C++ 11 introduced a weird overload for numeric types T for
/// std::real<T>, std::imag<T>, std::abs<T> and std::arg<T>, which messed up our
/// nice syntax, and which is why we had to take address of member-functions
/// or do the explicit cast first:
template <typename T> struct bindings<std::complex<T>, cart> { CM(0,std::complex<T>::real); CM(1,std::complex<T>::imag); };
template <typename T> struct bindings<std::complex<T>, plar> { CM(0,(T (&)(const std::complex<T>&))std::abs<T>); CM(1,(T (&)(const std::complex<T>&))std::arg<T>); };
#else
/// Otherwise you should be able to write nicely like this:
template <typename T> struct bindings<std::complex<T>, cart> { CM(0,std::real<T>); CM(1,std::imag<T>); };
template <typename T> struct bindings<std::complex<T>, plar> { CM(0,std::abs<T>); CM(1,std::arg<T>); };
#endif
} // of namespace mch
typedef mch::view<std::complex<double>,cart> cartesian;
typedef mch::view<std::complex<double>,plar> polar;
int main()
{
const std::complex<double> i(0.0,1.0);
mch::var<double> a,b,r,f;
mch::wildcard _;
Match(i)
{
Qua(cartesian,a,b) std::cout << a << "+" << b << "*i" << std::endl;
When(a,b |= a < b) std::cout << a << "<" << b << std::endl;
When(a,b |= a ==b) std::cout << a << "==" << b << std::endl;
When(a,b |= a > b) std::cout << a << ">" << b << std::endl;
When(0,1) std::cout << "(0,1)" << std::endl;
When(1+a,1+b) std::cout << "1+" << a << ",1+" << b << std::endl;
When(a+1,b+1) std::cout << a << "+1," << b << "+1"<< std::endl;
Qua(polar, r,f) std::cout << r << "*e^i" << f << std::endl;
When(r,f |= r < f) std::cout << r << "<" << f << std::endl;
When(r,f |= r ==f) std::cout << r << "==" << f << std::endl;
When(r,f |= r > f) std::cout << r << ">" << f << std::endl;
When(2*r,2*f) std::cout << "2*" << r << ",2*" << f << std::endl;
When(r*2,f*2) std::cout << r << "*2," << f << "*2" << std::endl;
When(r*2 |= r > 0.6,f*2) std::cout << r << "*2>1.2," << f << "*2" << std::endl;
When(r*2,f*2 |= f > 0.6) std::cout << r << "*2," << f << "*2>1.2" << std::endl;
When(r*2, _) std::cout << r << "*2, ???" << std::endl;
//When(r*2, _ |= r < 0.6) std::cout << r << "*2<1.2, ???" << std::endl;
When(r*2, f |= r < 0.6) std::cout << r << "*2<1.2, ???" << std::endl; // FIX: Replaced _ with f in the above as currently we don't have guard specialization
}
EndMatch
}
| [
"yuriy.solodkyy@gmail.com"
] | yuriy.solodkyy@gmail.com |
9ade77bf9e56d9d157114089484f7c214dee9254 | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/multimedia/directx/gamectrl/client/creditst.cpp | 5fbad089d154a3a7fdeec2ab51c2acf14581ac2e | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,231 | cpp | // CreditStatic.cpp : implementation file
//
#include "stdafx.h"
#include "CreditSt.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// defined in MAIN.CPP
extern HINSTANCE ghInstance;
#define DISPLAY_TIMER_ID 150 // timer id
/////////////////////////////////////////////////////////////////////////////
// CCreditStatic
CCreditStatic::CCreditStatic()
{
m_Colors[0] = RGB(0,0,255); // Black
m_Colors[1] = RGB(255,0,0); // Red
m_Colors[2] = RGB(0,128,0); // John Deer Green
m_Colors[3] = RGB(0,255,255); // Turquoise
m_Colors[4] = RGB(255,255,255); // White
m_TextHeights[0] = 36;
m_TextHeights[1] = 34;
m_TextHeights[2] = 34;
m_TextHeights[3] = 30;
m_nCurrentFontHeight = m_TextHeights[NORMAL_TEXT_HEIGHT];
m_Escapes[0] = '\t';
m_Escapes[1] = '\n';
m_Escapes[2] = '\r';
m_Escapes[3] = '^';
/*
m_DisplaySpeed[0] = 75;
m_DisplaySpeed[1] = 65;
m_DisplaySpeed[2] = 15;
*/
m_CurrentSpeed = 15; //DISPLAY_FAST;
m_ScrollAmount = -1;
m_ArrIndex = NULL;
m_nCounter = 31;
m_nClip = 0;
m_bFirstTurn = TRUE;
m_Gradient = GRADIENT_RIGHT_DARK;
n_MaxWidth = 0;
TimerOn = 0;
m_szWork = NULL;
}
CCreditStatic::~CCreditStatic()
{
}
BEGIN_MESSAGE_MAP(CCreditStatic, CStatic)
//{{AFX_MSG_MAP(CCreditStatic)
ON_WM_ERASEBKGND()
ON_WM_TIMER()
ON_WM_DESTROY()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CCreditStatic message handlers
BOOL CCreditStatic::StartScrolling()
{
if(m_pArrCredit->IsEmpty())
return FALSE;
if (m_BmpMain)
{
DeleteObject(m_BmpMain);
m_BmpMain = NULL;
}
::GetClientRect(this->m_hWnd, &m_ScrollRect);
TimerOn = (UINT)SetTimer(DISPLAY_TIMER_ID, m_CurrentSpeed, NULL);
ASSERT(TimerOn != 0);
m_ArrIndex = m_pArrCredit->GetHeadPosition();
// m_nCounter = 1;
// m_nClip = 0;
return TRUE;
}
void CCreditStatic::EndScrolling()
{
KillTimer(DISPLAY_TIMER_ID);
TimerOn = 0;
if (m_BmpMain)
{
DeleteObject(m_BmpMain);
m_BmpMain = NULL;
}
}
void CCreditStatic::SetCredits(LPCTSTR credits,TCHAR delimiter)
{
LPTSTR str,ptr1,ptr2;
ASSERT(credits);
if ((str = _tcsdup(credits)) == NULL)
return;
m_pArrCredit = new (CStringList);
ASSERT (m_pArrCredit);
m_pArrCredit->RemoveAll();
ptr1 = str;
while((ptr2 = _tcschr(ptr1,delimiter)) != NULL)
{
*ptr2 = '\0';
m_pArrCredit->AddTail(ptr1);
ptr1 = ptr2+1;
}
m_pArrCredit->AddTail(ptr1);
free(str);
m_ArrIndex = m_pArrCredit->GetHeadPosition();
// m_nCounter = 1;
// m_nClip = 0;
}
BOOL CCreditStatic::OnEraseBkgnd(CDC* pDC)
{
return TRUE;
// return CStatic::OnEraseBkgnd(pDC);
}
//************************************************************************
// OnTimer
//
// On each of the display timers, scroll the window 1 unit. Each 20
// units, fetch the next array element and load into work string. Call
// Invalidate and UpdateWindow to invoke the OnPaint which will paint
// the contents of the newly updated work string.
//************************************************************************
void CCreditStatic::OnTimer(UINT nIDEvent)
{
BOOL bCheck = FALSE;
if (m_nCounter++ % m_nCurrentFontHeight == 0) // every x timer events, show new line
{
m_nCounter=1;
m_szWork = (LPCTSTR)m_pArrCredit->GetNext(m_ArrIndex);
if(m_bFirstTurn)
bCheck = TRUE;
if (m_ArrIndex == NULL)
{
m_bFirstTurn = FALSE;
m_ArrIndex = m_pArrCredit->GetHeadPosition();
}
m_nClip = 0;
}
HDC hMainDC = this->GetDC()->m_hDC;
RECT rc = m_ScrollRect;
rc.left = ((rc.right-rc.left)-n_MaxWidth)/2;
rc.right = rc.left + n_MaxWidth;
HDC hDC = ::CreateCompatibleDC(hMainDC);
// Don't try to scroll credits you don't have!
if (m_szWork)
MoveCredit(&hMainDC, rc, bCheck);
else
FillGradient(&hMainDC, m_ScrollRect);
::SelectObject(hDC, m_BmpMain);
::BitBlt(hMainDC, 0, 0, m_ScrollRect.right-m_ScrollRect.left, m_ScrollRect.bottom-m_ScrollRect.top, hDC, 0, 0, SRCCOPY);
::ReleaseDC(this->m_hWnd, hMainDC);
::DeleteDC(hDC);
CStatic::OnTimer(nIDEvent);
}
void CCreditStatic::FillGradient(HDC *pDC, RECT& FillRect)
{
float fStep,fRStep,fGStep,fBStep; // How large is each band?
WORD R = GetRValue(m_Colors[BACKGROUND_COLOR]);
WORD G = GetGValue(m_Colors[BACKGROUND_COLOR]);
WORD B = GetBValue(m_Colors[BACKGROUND_COLOR]);
// Determine how large each band should be in order to cover the
// client with 256 bands (one for every color intensity level)
//if(m_Gradient % 2)
//{
fRStep = (float)R / 255.0f;
fGStep = (float)G / 255.0f;
fBStep = (float)B / 255.0f;
/*
}
else
{
fRStep = (float)(255-R) / 255.0f;
fGStep = (float)(255-G) / 255.0f;
fBStep = (float)(255-B) / 255.0f;
}
*/
COLORREF OldCol = ::GetBkColor(*pDC);
RECT rc;
// Start filling bands
fStep = (float)(m_ScrollRect.right-m_ScrollRect.left) / 256.0f;
for (short iOnBand = (short)((256*FillRect.left)/(m_ScrollRect.right-m_ScrollRect.left));
(int)(iOnBand*fStep) < FillRect.right && iOnBand < 256; iOnBand++)
{
::SetRect(&rc,
(int)(iOnBand * fStep),
FillRect.top,
(int)((iOnBand+1) * fStep),
FillRect.bottom+1);
// If we want to enable gradient filling from any direction!
/*
switch(m_Gradient)
{
case GRADIENT_RIGHT_DARK:
col = RGB((int)(R-iOnBand*fRStep),(int)(G-iOnBand*fGStep),(int)(B-iOnBand*fBStep));
break;
case GRADIENT_RIGHT_LIGHT:
col = RGB((int)(R+iOnBand*fRStep),(int)(G+iOnBand*fGStep),(int)(B+iOnBand*fBStep));
break;
case GRADIENT_LEFT_DARK:
col = RGB((int)(iOnBand*fRStep),(int)(iOnBand*fGStep),(int)(iOnBand*fBStep));
break;
case GRADIENT_LEFT_LIGHT:
col = RGB(255-(int)(iOnBand*fRStep),255-(int)(iOnBand*fGStep),255-(int)(iOnBand*fBStep));
break;
default:
return;
}
*/
::SetBkColor(*pDC, RGB((int)(R-iOnBand*fRStep),(int)(G-iOnBand*fGStep),(int)(B-iOnBand*fBStep)));
::ExtTextOut(*pDC, 0, 0, ETO_OPAQUE, &rc, NULL, 0, NULL);
}
::SetBkColor(*pDC, OldCol);
}
void CCreditStatic::MoveCredit(HDC* pDC, RECT& ClientRect, BOOL bCheck)
{
HDC hMemDC = ::CreateCompatibleDC(*pDC);
HBITMAP *pOldMemDCBitmap = NULL;
HFONT *pOldFont = NULL;
RECT r1;
if (m_BmpMain == NULL)
{
m_BmpMain = ::CreateCompatibleBitmap(*pDC, m_ScrollRect.right-m_ScrollRect.left, m_ScrollRect.bottom-m_ScrollRect.top );
pOldMemDCBitmap = (HBITMAP *)::SelectObject(hMemDC, m_BmpMain);
FillGradient(&hMemDC, m_ScrollRect);
} else pOldMemDCBitmap = (HBITMAP *)::SelectObject(hMemDC, m_BmpMain);
if ((ClientRect.right-ClientRect.left) > 0)
{
::ScrollDC(hMemDC, 0, m_ScrollAmount, &m_ScrollRect, &ClientRect, NULL, &r1);
}
else
{
r1 = m_ScrollRect;
r1.top = r1.bottom-abs(m_ScrollAmount);
}
m_nClip = m_nClip + abs(m_ScrollAmount);
//*********************************************************************
// FONT SELECTIlON
short rmcode = 1;
if (lstrlen(m_szWork))
{
BYTE bUnderline, bItalic;
bUnderline = bItalic = FALSE;
COLORREF nTmpColour = m_Colors[TOP_LEVEL_GROUP_COLOR];
TCHAR c = m_szWork[lstrlen(m_szWork)-1];
if(c == m_Escapes[TOP_LEVEL_GROUP])
{
m_nCurrentFontHeight = m_TextHeights[TOP_LEVEL_GROUP_HEIGHT];
}
else if(c == m_Escapes[GROUP_TITLE])
{
m_nCurrentFontHeight = m_TextHeights[GROUP_TITLE_HEIGHT];
nTmpColour = m_Colors[GROUP_TITLE_COLOR];
}
else if(c == m_Escapes[TOP_LEVEL_TITLE])
{
m_nCurrentFontHeight = m_TextHeights[TOP_LEVEL_TITLE_HEIGHT];
nTmpColour = m_Colors[TOP_LEVEL_TITLE_COLOR];
}
// If this were application critical, I'd make an array of fonts a member
// and create all the fonts prior to starting the timer!
HFONT pfntArial = ::CreateFont(m_nCurrentFontHeight, 0, 0, 0,
FW_BOLD, bItalic, bUnderline, 0,
ANSI_CHARSET,
OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS,
PROOF_QUALITY,
VARIABLE_PITCH | 0x04 | FF_DONTCARE,
(LPCTSTR)"Arial");
::SetTextColor(hMemDC, nTmpColour);
if (pOldFont != NULL)
::SelectObject(hMemDC, pOldFont);
pOldFont = (HFONT *)::SelectObject(hMemDC, pfntArial);
}
FillGradient(&hMemDC, r1);
::SetBkMode(hMemDC, TRANSPARENT);
if(bCheck)
{
SIZE size;
::GetTextExtentPoint(hMemDC, (LPCTSTR)m_szWork,lstrlen(m_szWork)-rmcode, &size);
if (size.cx > n_MaxWidth)
{
n_MaxWidth = (short)((size.cx > (m_ScrollRect.right-m_ScrollRect.left)) ? (m_ScrollRect.right-m_ScrollRect.left) : size.cx);
ClientRect.left = ((m_ScrollRect.right-m_ScrollRect.left)-n_MaxWidth)/2;
ClientRect.right = ClientRect.left + n_MaxWidth;
}
}
RECT r = ClientRect;
r.top = r.bottom-m_nClip;
DrawText(hMemDC, (LPCTSTR)m_szWork,lstrlen(m_szWork)-rmcode,&r,DT_TOP|DT_CENTER|DT_NOPREFIX | DT_SINGLELINE);
if (pOldFont != NULL)
::SelectObject(hMemDC, pOldFont);
::SelectObject(hMemDC, pOldMemDCBitmap);
::DeleteDC(hMemDC);
}
void CCreditStatic::OnDestroy()
{
CStatic::OnDestroy();
m_pArrCredit->RemoveAll();
if (m_pArrCredit)
delete (m_pArrCredit);
if(TimerOn)
EndScrolling();
}
/* In the event we ever want a few library routines!
void CCreditStatic::SetCredits(UINT nID, TCHAR delimiter)
{
LPTSTR lpCredits = new (TCHAR[255]);
ASSERT (lpCredits);
::LoadString(ghInstance, nID, lpCredits, 255);
SetCredits((LPCTSTR)lpCredits, delimiter);
if (lpCredits)
delete[] (lpCredits);
}
void CCreditStatic::SetSpeed(UINT index, int speed)
{
ASSERT(index <= DISPLAY_FAST);
if(speed)
m_DisplaySpeed[index] = speed;
m_CurrentSpeed = index;
}
void CCreditStatic::SetColor(UINT index, COLORREF col)
{
ASSERT(index <= NORMAL_TEXT_COLOR);
m_Colors[index] = col;
}
void CCreditStatic::SetTextHeight(UINT index, int height)
{
ASSERT(index <= NORMAL_TEXT_HEIGHT);
m_TextHeights[index] = height;
}
void CCreditStatic::SetEscape(UINT index, char escape)
{
ASSERT(index <= DISPLAY_BITMAP);
m_Escapes[index] = escape;
}
void CCreditStatic::SetGradient(UINT value)
{
ASSERT(value <= GRADIENT_LEFT_LIGHT);
m_Gradient = value;
}
void CCreditStatic::SetTransparent(BOOL bTransparent)
{
m_bTransparent = bTransparent;
}
*/
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
0fd9b5aa5d51ec88c5de7436ff464e3cf6999bcb | 394cd6c045789a90d1826117c43322610476c853 | /BCH_grande/BCH/bch.h | 375ed1cdb845de6e3676fbef965efaa9f3b2d5a8 | [] | no_license | grganzaroli/BCH_VS | 2631fd60212a2259b6443f63f7cd1830fbc2f4c4 | e13fd64a646cc3b60bfb0314528be014ff4dcee9 | refs/heads/master | 2021-09-05T20:04:49.957957 | 2018-01-30T19:06:49 | 2018-01-30T19:06:49 | 117,262,428 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,362 | h | #ifndef BCH_H
#define BCH_H
class bch
{
private:
int n; //quantidade de bits de entrada
int k; //quantidade de bits de saída
int t; //capacidade de correção de erros
int m; //ordem do decodificador
int n_extension; //numero de zeros a adicionar ao inicio da palavra-codigo recebida para obter n+n_extension = (2^m)-1
unsigned char *pol_primitivo; //polinomio primitivo
unsigned char *pol_gerador; //polinomio gerador
int *GF; //campo de galois [potencias] = valor decimal
int *inv_GF; //campo de galois [valor decimal] = potencias
int *tab_inv_alpha; //tabela inversa alpha
int *tab_inv_dec; //tabela inversa decimal
int *p_erros; //posicao dos erros
public:
void init(int n, int k, int t, int m); //inicializa variavais
void set_pol_prim(unsigned char *p_prim); //polinomio primitivo para decodificação
void set_pol_ger(unsigned char *p_ger); //polinomio gerador para codificação
void calc_gf(); // calculo do campo de galois
void calc_tab_inv(); // calculo da tabela inversa
void encode(unsigned char *u, unsigned char *v); // codifica u[k] em v[n+n_extension] (nao funciona direito)
bool decode(unsigned char *rr, int &n_err); //decodifica [r] e retorna sucessso (true) ou fracasso (false) na decodificação
int tab_mult(int multi1, int multi2);
int det_gf(int **MAT, int size);
int det(int **MAT, int size);
};
#endif
| [
"g.rossiganza@gmail.com"
] | g.rossiganza@gmail.com |
5269fecfaf6693e6cb97be346fb9ba220f36306b | ae37876fe82941d793de3cea1ca4f061fe20e177 | /C3/5_check_file_access.cpp | 3888b957e885a64ceaec4b81bdce8d4b3f21c51d | [] | no_license | caizr/APUE | 31c0a00bda3d83bf8d18310d4861af24476a474b | c0da38e16f2c640d415267572477bf9cdbf6e571 | refs/heads/master | 2023-01-04T02:29:44.332479 | 2020-11-08T15:50:41 | 2020-11-08T15:50:41 | 268,302,080 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 897 | cpp | /* 检查文件的访问权限
*/
#include<iostream>
#include<fcntl.h>
#include<sys/stat.h>
#include<unistd.h>
int main(int argc, char ** argv){
using namespace std;
struct stat buf;
// 检测是否调用错误
if(argc <2 ){
cout<<"usage error!"<<endl;
return -1;
}
for(int i=1;i<argc;++i){
cout<<argv[i]<<" :";
//read test
if(access(argv[i],R_OK)<0)
cout<<"read error!"<<" ";
else
cout<<"read sucess!"<<" ";
// 测试该文件是否能打开?
if(open(argv[i],O_RDONLY)<0){
cout<<"open "<<argv[i]<<" error!"<<endl;
continue;
}
//wriet test
if(access(argv[i],W_OK)<0)
cout<<"write error!"<<" ";
//execute test
if(access(argv[i],X_OK)<0)
cout<<"execute error!"<<" ";
cout<<endl;
}
} | [
"0@caizr.com"
] | 0@caizr.com |
3d600097aef4bc61c89e6f6cacb380578b9f2b97 | 9cbe211c7ba4d0e505e04d7ff07712a0c9a54daf | /qq/qq/main.cpp | 5d87021626e94831ae109ac664f8cd56f3325bed | [] | no_license | chengyoude00/cstudy | ad3fd5b589bff01cfd8898373044e9ca4f878ce2 | 9e715a552351fd20ec3ac740db8111f184b07a3f | refs/heads/master | 2021-09-08T15:58:11.246264 | 2018-03-08T06:15:10 | 2018-03-08T06:15:10 | 118,839,568 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 584 | cpp | #include "linklist.h"
#include <iostream>
using namespace std;
int main()
{
int tempi;
char tempc;
cout << "请输入一个整数和一个字符:"<< endl;
cin >> tempi >> tempc;
Linklinst a(tempi,tempc);
a.Locte(tempi);
a.Insert(1,'C');
a.Insert(2,'B');
a.Insert(3, 'F');
cout << "After Insert"<< endl;
a.Show();
a.Locte('B');
a.Delete();
cout << "After Delete"<< endl;
a.Show();
Linklinst b(a);
cout << "This is Linklist b"<< endl;
a.Show();
a.Destroy();
cout << "After Destory"<< endl;
a.Show();
cout <<"This is Linklist b" << endl;
b.Show();
return 0;
} | [
"643064906@qq.com"
] | 643064906@qq.com |
517dfe3f325c589fe0cb6df5e4324fdc5d6d084c | 7cd7aac512f867463f341bbb8c98e942a84b7755 | /lab4.2.1/prj/src/sort_benchmark.cpp | 8df3491df8cfbf5f58ddb9efc99c2230dacee4f6 | [] | no_license | martynabandura/pamsi2 | cea4a9df38d78d0fd07264caf508e726b35c4338 | cf933a6c81e62ddd431c3d4e3c3ddf302c7d14be | refs/heads/master | 2016-09-06T01:38:49.859910 | 2014-06-03T20:43:10 | 2014-06-03T20:43:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,363 | cpp | #include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include <ctime>
#include "../inc/quick.hpp"
#include "../inc/merge.hpp"
using namespace std;
/**
*\file
*\brief Benchmark
* Zawiera najważniejsze fukcje programu jak rozmiar tablicy.
* Benchmark sortowanie quick i merge
*/
int rozmiar[] = {10000, 50000, 100000, 500000, 1000000};
//~ int rozmiar[] = {100, 500, 1000, 5000, 10000};
void qsort_benchmark(ofstream& plik) {
Quick Q;
plik << "sortowanie szybkie: " << endl;
for(int j=0; j<5; j++) {
plik << "rozmiar tablicy" << rozmiar[j] << endl;
int l_wierszy = 100;
int l_kolumn = rozmiar[j];
int **tablica = new int*[l_wierszy];
for (int x = 0; x < l_wierszy; x++)
tablica[x] = new int[l_kolumn];
int posortowane[] = {0, 25, 50, 75, 95, 99};
for(int i=0; i<6; i++){
plik << "posortowane" << posortowane[i] << "% elementow ";
Q.wypelnij(tablica, rozmiar[j], posortowane[i]);
cout << Q.sprawdz_porzadek(tablica, rozmiar[j]) << " ";
clock_t start, stop;
start=clock();
for(int i=0; i<100; i++) {
Q.quick_sort(tablica[i], tablica[i]+(l_kolumn-1));
}
stop=clock();
double czas = (double)(stop - start)/CLOCKS_PER_SEC;
plik << "czas: " << czas << "s\n";
cout << Q.sprawdz_porzadek(tablica, rozmiar[j]) << " ";
}
plik << "posortowane odwrotnie ";
Q.wypelnij_odwrotnie(tablica, rozmiar[j]);
cout << Q.sprawdz_porzadek(tablica, rozmiar[j]) << " ";
clock_t start, stop;
start=clock();
for(int i=0; i<100; i++) {
Q.quick_sort(tablica[i], tablica[i]+(l_kolumn-1));
}
stop=clock();
double czas = (double)(stop - start)/CLOCKS_PER_SEC;
plik << "czas: " << czas << "s\n";
cout << Q.sprawdz_porzadek(tablica, rozmiar[j]) << " ";
cout << endl;
for (int x = 0; x < l_wierszy; x++)
delete [] tablica[x];
delete [] tablica;
}
}
void msort_benchmark(ofstream& plik) {
Merge M;
plik << "sortowanie merge: " << endl;
for(int j=0; j<5; j++){
plik << "rozmiar tablicy" << rozmiar[j] << endl;
int l_wierszy = 100;
int l_kolumn = rozmiar[j];
int **tablica = new int*[l_wierszy];
for (int x = 0; x < l_wierszy; x++)
tablica[x] = new int[l_kolumn];
int posortowane[] = {0, 25, 50, 75, 95, 99};
for(int i=0; i<6; i++){
plik << "posortowane" << posortowane[i] << "% elementow ";
M.wypelnij(tablica, rozmiar[j], posortowane[i]);
cout << M.sprawdz_porzadek(tablica, rozmiar[j]) << " ";
clock_t start, stop;
start=clock();
for(int i=0; i<100; i++) {
M.merge_sort(tablica[i], 0, (l_kolumn-1));
}
stop=clock();
double czas = (double)(stop - start)/CLOCKS_PER_SEC;
plik << "czas: " << czas << "s\n";
cout << M.sprawdz_porzadek(tablica, rozmiar[j]) << " ";
}
plik << "posortowane odwrotnie ";
M.wypelnij_odwrotnie(tablica, rozmiar[j]);
cout << M.sprawdz_porzadek(tablica, rozmiar[j]) << " ";
clock_t start, stop;
start=clock();
for(int i=0; i<100; i++) {
M.merge_sort(tablica[i], 0, (l_kolumn-1));
}
stop=clock();
double czas = (double)(stop - start)/CLOCKS_PER_SEC;
plik << "czas: " << czas << "s\n";
cout << M.sprawdz_porzadek(tablica, rozmiar[j]) << "\n";
for (int x = 0; x < l_wierszy; x++)
delete [] tablica[x];
delete [] tablica;
}
}
| [
"200425@student.pwr.edu.pl"
] | 200425@student.pwr.edu.pl |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.