hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3f198c4d47c235a57dba098a41c9dc2c308c512a | 698 | cpp | C++ | Kattis-Solutions/Encoded Message.cpp | SurgicalSteel/Competitive-Programming | 3662b676de94796f717b25dc8d1b93c6851fb274 | [
"MIT"
] | 14 | 2016-02-11T09:26:13.000Z | 2022-03-27T01:14:29.000Z | Kattis-Solutions/Encoded Message.cpp | SurgicalSteel/Competitive-Programming | 3662b676de94796f717b25dc8d1b93c6851fb274 | [
"MIT"
] | null | null | null | Kattis-Solutions/Encoded Message.cpp | SurgicalSteel/Competitive-Programming | 3662b676de94796f717b25dc8d1b93c6851fb274 | [
"MIT"
] | 7 | 2016-10-25T19:29:35.000Z | 2021-12-05T18:31:39.000Z | #include <bits/stdc++.h>
using namespace std;
string solve(string enc)
{
int res =(int) sqrt((double) enc.length());
int curr,counter=0;
string builder="";
int pos=res-1;
int awal=pos;
while(counter<enc.length())
{
while(pos<enc.length())
{
builder+=enc.substr(pos,1);
//cout<<enc.substr(pos,1);
counter++;
if(counter==enc.length()){break;}
pos+=res;
}
awal--;
pos=awal;
}
return builder;
}
int main() {
int tc;
string inp;
cin>>tc;
for(int i=0;i<tc;i++)
{
cin>>inp;
cout<<solve(inp)<<"\n";
}
return 0;
}
| 18.864865 | 47 | 0.469914 | SurgicalSteel |
3f1cc7f38155b2ff1e00ccc8d620991997fe9338 | 1,448 | cpp | C++ | rect.cpp | tonymiceli/tinymfc | 68a5fbbaecf07a038d8e46cfc9a96d62480b12b5 | [
"MIT"
] | 1 | 2020-03-27T23:31:30.000Z | 2020-03-27T23:31:30.000Z | rect.cpp | tonymiceli/tinymfc | 68a5fbbaecf07a038d8e46cfc9a96d62480b12b5 | [
"MIT"
] | null | null | null | rect.cpp | tonymiceli/tinymfc | 68a5fbbaecf07a038d8e46cfc9a96d62480b12b5 | [
"MIT"
] | null | null | null | //#include "stdafx.h"
#include "rect.h"
void CRect::SetRect(LONG nLeft, LONG nTop, LONG nRight, LONG nBottom)
{
left = nLeft;
top = nTop;
right = nRight;
bottom = nBottom;
}
POINT CRect::GetTopLeft()
{
POINT pt;
pt.x = left;
pt.y = top;
return pt;
}
POINT CRect::GetBottomLeft()
{
POINT pt;
pt.x = left;
pt.y = bottom;
return pt;
}
POINT CRect::GetTopRight()
{
POINT pt;
pt.x = right;
pt.y = top;
return pt;
}
POINT CRect::GetBottomRight()
{
POINT pt;
pt.x = right;
pt.y = bottom;
return pt;
}
void CRect::SetOrigin(POINT &pt)
{
right = (right-left)+pt.x;
left = pt.x;
bottom = (bottom-top)+pt.y;
top = pt.y;
}
void CRect::SetOrigin(LONG nLeft, LONG nTop)
{
right = (right-left)+nLeft;
left = nLeft;
bottom = (bottom-top)+nTop;
top = nTop;
}
void CRect::OffsetRect(LONG dx, LONG dy)
{
::OffsetRect(this, dx, dy);
}
void CRect::OffsetRect(POINT &pt)
{
::OffsetRect(this, pt.x, pt.y);
}
const CRect& CRect::operator=(const CRect& rectSrc)
{
left = rectSrc.left;
top = rectSrc.top;
right = rectSrc.right;
bottom = rectSrc.bottom;
return *this;
}
void CRect::UnionRect(LPRECT lpRect)
{
::UnionRect(this, this, lpRect);
}
BOOL CRect::PtInRect(int x, int y)
{
POINT aPoint;
aPoint.x = x;
aPoint.y = y;
return ::PtInRect(this, aPoint);
}
| 15.242105 | 70 | 0.571823 | tonymiceli |
3f1e6dcee05e63f98608608c7c815a22801fc025 | 7,367 | cxx | C++ | inetsrv/query/icommand/metqspec.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/query/icommand/metqspec.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/query/icommand/metqspec.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1992 - 1995.
//
// File: StdQSpec.cxx
//
// Contents: ICommand for file-based queries
//
// Classes: CMetadataQuerySpec
//
// History: 30 Jun 1995 AlanW Created
//
//----------------------------------------------------------------------------
#include <pch.cxx>
#pragma hdrstop
#include "metqspec.hxx"
//+-------------------------------------------------------------------------
//
// Member: CMetadataQuerySpec::CMetadataQuerySpec, public
//
// Synopsis: Constructor of a CMetadataQuerySpec
//
// Arguments: [pOuterUnk] - Outer unknown
// [ppMyUnk] - OUT: filled in with pointer to non-delegated
// IUnknown on return
// [eType] - Class of metadata to return
// [pCat] - Content index catalog
// [pMachine]
//
// History: 08-Feb-96 KyleP Added support for virtual paths
//
//--------------------------------------------------------------------------
CMetadataQuerySpec::CMetadataQuerySpec (
IUnknown * pOuterUnk,
IUnknown ** ppMyUnk,
CiMetaData eType,
WCHAR const * pCat,
WCHAR const * pMachine )
: CRootQuerySpec(pOuterUnk, ppMyUnk),
_eType( eType )
{
//
// Make a copy of the catalog string for ICommand::Clone
//
unsigned len = wcslen( pCat ) + 1;
_xCat.Set( new WCHAR[len] );
RtlCopyMemory( _xCat.GetPointer(), pCat, len * sizeof(WCHAR) );
//
// Make a copy of the machine string for ICommand::Clone
//
if ( 0 != pMachine )
{
len = wcslen( pMachine ) + 1;
_xMachine.Set( new WCHAR[len] );
RtlCopyMemory( _xMachine.GetPointer(), pMachine, len * sizeof(WCHAR) );
}
}
//+-------------------------------------------------------------------------
//
// Member: CMetadataQuerySpec::QueryInternalQuery, protected
//
// Synopsis: Instantiates internal query, using current parameters.
//
// Returns: Pointer to internal query object.
//
// History: 03-Mar-1997 KyleP Created
//
//--------------------------------------------------------------------------
PIInternalQuery * CMetadataQuerySpec::QueryInternalQuery()
{
//
// get a pointer to the IInternalQuery interface
//
PIInternalQuery * pQuery = 0;
SCODE sc = EvalMetadataQuery( &pQuery,
_eType,
_xCat.GetPointer(),
_xMachine.GetPointer() );
if ( FAILED( sc ) )
THROW( CException( sc ) );
return pQuery;
}
//+---------------------------------------------------------------------------
//
// Member: MakeMetadataICommand
//
// Synopsis: Evaluate the metadata query
//
// Arguments: [ppQuery] -- Returns the IUnknown for the command
// [eType] -- Type of metadata (vroot, proot, etc)
// [wcsCat] -- Catalog
// [wcsMachine] -- Machine name for meta query
// [pOuterUnk] -- (optional) outer unknown pointer
//
// Returns SCODE result
//
// History: 15-Apr-96 SitaramR Created header
// 29-May-97 EmilyB Added aggregation support, so now
// returns IUnknown ptr and caller
// must now call QI to get ICommand ptr
//
//----------------------------------------------------------------------------
SCODE MakeMetadataICommand(
IUnknown ** ppQuery,
CiMetaData eType,
WCHAR const * wcsCat,
WCHAR const * wcsMachine,
IUnknown * pOuterUnk )
{
//
// Check for invalid parameters
//
if ( 0 == wcsCat ||
0 == ppQuery ||
( eType != CiVirtualRoots &&
eType != CiPhysicalRoots &&
eType != CiProperties ) )
{
return E_INVALIDARG;
}
*ppQuery = 0;
CMetadataQuerySpec * pQuery = 0;
SCODE sc = S_OK;
TRANSLATE_EXCEPTIONS;
TRY
{
pQuery = new CMetadataQuerySpec( pOuterUnk,
ppQuery,
eType,
wcsCat,
wcsMachine );
}
CATCH( CException, e )
{
Win4Assert(0 == pQuery);
sc = e.GetErrorCode();
}
END_CATCH
UNTRANSLATE_EXCEPTIONS;
return sc;
} //MakeMetadataICommand
//+---------------------------------------------------------------------------
//
// Method: CMetadataQuerySpec::GetProperties, public
//
// Synopsis: Get rowset properties
//
// Arguments: [cPropertySetIDs] - number of desired property set IDs or 0
// [rgPropertySetIDs] - array of desired property set IDs or NULL
// [pcPropertySets] - number of property sets returned
// [prgPropertySets] - array of returned property sets
//
// Returns: SCODE - result code indicating error return status. One of
// S_OK, DB_S_ERRORSOCCURRED or DB_E_ERRORSOCCURRED. Any
// other errors are thrown.
//
// History: 12-Mayr-97 dlee Created
//
//----------------------------------------------------------------------------
SCODE STDMETHODCALLTYPE CMetadataQuerySpec::GetProperties(
ULONG const cPropertySetIDs,
DBPROPIDSET const rgPropertySetIDs[],
ULONG * pcPropertySets,
DBPROPSET ** prgPropertySets)
{
_DBErrorObj.ClearErrorInfo();
SCODE scParent = CRootQuerySpec::GetProperties( cPropertySetIDs,
rgPropertySetIDs,
pcPropertySets,
prgPropertySets );
if ( S_OK != scParent )
_DBErrorObj.PostHResult( scParent, IID_ICommandProperties );
return scParent;
} //GetProperties
//+---------------------------------------------------------------------------
//
// Method: CMetadataQuerySpec::SetProperties, public
//
// Synopsis: Set rowset scope properties
//
// Arguments: [cPropertySets] - number of property sets
// [rgPropertySets] - array of property sets
//
// Returns: SCODE - result code indicating error return status. One of
// S_OK, DB_S_ERRORSOCCURRED or DB_E_ERRORSOCCURRED. Any
// other errors are thrown.
//
// History: 12-Mayr-97 dlee Created
//
//----------------------------------------------------------------------------
SCODE STDMETHODCALLTYPE CMetadataQuerySpec::SetProperties(
ULONG cPropertySets,
DBPROPSET rgPropertySets[] )
{
_DBErrorObj.ClearErrorInfo();
SCODE scParent = CRootQuerySpec::SetProperties( cPropertySets,
rgPropertySets );
if ( S_OK != scParent )
_DBErrorObj.PostHResult( scParent, IID_ICommandProperties );
return scParent;
} //SetProperties
| 32.170306 | 80 | 0.474141 | npocmaka |
3f28fb71ec040541b3028b4032d7c0516d04e992 | 7,719 | hpp | C++ | src/Core/Managers/RenderingManager.hpp | Rexagon/2drift | 31d687c9b4a289ca2c62757cba7b4f6e3c0b5d14 | [
"Apache-2.0"
] | null | null | null | src/Core/Managers/RenderingManager.hpp | Rexagon/2drift | 31d687c9b4a289ca2c62757cba7b4f6e3c0b5d14 | [
"Apache-2.0"
] | null | null | null | src/Core/Managers/RenderingManager.hpp | Rexagon/2drift | 31d687c9b4a289ca2c62757cba7b4f6e3c0b5d14 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <glm/vec2.hpp>
#include <glm/vec4.hpp>
#include "Core/Rendering/Stuff/RenderingParameters.hpp"
#include "WindowManager.hpp"
namespace core
{
/**
* @brief Rendering manager
*
* Handle OpenGL state and optimizes state calls
*/
class RenderingManager final : public Manager
{
public:
/**
* @param core Game core object
*/
explicit RenderingManager(Core &core);
/**
* @brief Force apply current parameters to OpenGL state
*/
void synchronize();
/**
* @brief Apply new parameters
*
* Only changed parameters will change OpenGL state
*
* @param parameters Parameters pack
*/
void setRenderingParameters(const RenderingParameters ¶meters);
/**
* @brief Set depth test status
* @param enabled Status
*/
void setDepthTestEnabled(bool enabled);
/**
* @brief Check if depth test is enabled
*
* Depth test is enabled by default.
*
* @return true if enabled
*/
bool isDepthTestEnabled() const;
/**
* @brief Set depth write status
* @param enabled
*/
void setDepthWriteEnabled(bool enabled);
/**
* @brief Check if depth write is enabled
*
* Depth write is enabled by default.
*
* @return true if enabled
*/
bool isDepthWriteEnabled() const;
/**
* @brief Set depth test function
*
* @param testFunction OpenGL depth test function.
* Must be one of GL_NEVER, GL_LESS, GL_EQUAL, GL_LEQUAL,
* GL_GREATER, GL_NOTEQUAL, GL_GEQUAL or GL_ALWAYS
*/
void setDepthTestFunction(GLenum testFunction);
/**
* @brief Get current depth test function
*
* GL_LEQUAL is set by default.
*
* @return Current depth test function
*/
GLenum getDepthTestFunction() const;
/**
* @brief Set alpha blending status
* @param enabled Status
*/
void setBlendingEnabled(bool enabled);
/**
* @brief Check if alpha blending is enabled
*
* Disabled by default.
*
* @return true if enabled
*/
bool isBlendingEnabled() const;
/**
* @brief Specify pixel arithmetic
*
* Functions must be one of: GL_ZERO, GL_ONE, GL_SRC_COLOR,
* GL_ONE_MINUS_SRC_COLOR, GL_DST_COLOR, GL_ONE_MINUS_DST_COLOR,
* GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_DST_ALPHA,
* GL_ONE_MINUS_DST_ALPHA. GL_CONSTANT_COLOR,
* GL_ONE_MINUS_CONSTANT_COLOR, GL_CONSTANT_ALPHA,
* and GL_ONE_MINUS_CONSTANT_ALPHA
*
* @param src Source function
* @param dst Destination function
*/
void setBlendingFunctions(GLenum src, GLenum dst);
/**
* @brief Get current alpha blending function for source
*
* GL_SRC_ALPHA is set by default.
*
* @return Blending function
*/
GLenum getBlendingFunctionSrc() const;
/**
* @brief Get current alpha blending function for destination
*
* GL_ONE_MINUS_SRC_ALPHA is set by default.
*
* @return Blending function
*/
GLenum getBlendingFunctionDst() const;
/**
* @brief Set face culling status
* @param enabled Status
*/
void setFaceCullingEnabled(bool enabled);
/**
* @brief Check if face culling is enabled
*
* Enabled by default.
*
* @return true if enabled
*/
bool isFaceCullingEnabled() const;
/**
* @brief Set face culling side
* @param side Culled side. Must be one of GL_FRONT, GL_BACK,
* and GL_FRONT_AND_BACK
*/
void setFaceCullingSide(GLenum side);
/**
* @brief Get face culling side
*
* GL_BACK is set by default.
*
* @return Side
*/
GLenum getFaceCullingSide() const;
/**
* @brief Set polygon rendering mode
* @param mode Rendering mode. Must be one of GL_POINT,
* GL_LINE, and GL_FILL
*/
void setPolygonMode(GLenum mode);
/**
* @brief Get polygon rendering mode
*
* GL_FILL is set by default.
*
* @return Rendering mode
*/
GLenum getPolygonMode() const;
/**
* @return Current rendering parameters
*/
const RenderingParameters &getRenderingParameters() const;
/**
* @brief Set current viewport parameters
* @param size Viewport size
* @param offset Viewport top left offset
*/
void setViewport(const glm::ivec2 &size, const glm::ivec2 &offset = glm::ivec2());
/**
* @brief Set current viewport parameters
* @param x Viewport left offset
* @param y Viewport top offset
* @param width Viewport width
* @param height Viewport height
*/
void setViewport(GLint x, GLint y, GLsizei width, GLsizei height);
/**
* @return Viewport size
*/
glm::ivec2 getViewportSize() const;
/**
* @return viewport top left offset
*/
glm::ivec2 getViewportOffset() const;
/**
* @param color RGBA, each component is in range [0, 1]
*/
void setClearColor(const glm::vec4 &color);
/**
* @param r Red component in range [0, 1]
* @param g Green component in range [0, 1]
* @param b Blue component in range [0, 1]
* @param a Alpha component in range [0, 1]. 1.0 by default
*/
void setClearColor(float r, float g, float b, float a = 1.0f);
/**
* Opaque black color is set by default.
*
* @return Clear color
*/
glm::vec4 getClearColor() const;
/**
* @brief Set clear depth value
* @param depth Depth value
*/
void setClearDepth(float depth);
/**
* @brief Get clear depth value
*
* Default depth value is 1
*
* @return Depth value
*/
float getClearDepth() const;
/**
* @brief Set current shader id
* @param shader Shader id
*/
void setCurrentShaderId(GLuint shaderId);
/**
* @brief Get current shader id
*/
GLuint getCurrentShaderId();
/**
* @brief Set current frame buffer id
*
* Binds frame buffer as GL_FRAMEBUFFER.
*
* @param frameBufferId Frame buffer id
*/
void setCurrentFrameBufferId(GLuint frameBufferId);
/**
* @brief Get current frame buffer
* @return Frame buffer id
*/
GLuint getCurrentFrameBufferId() const;
/**
* @brief Select active texture unit
* @param slot Unit number. Can be any number, but only
* first 32 units can be cached by this manager.
*/
void setActiveTexture(size_t slot);
/**
* @brief Bind current texture
*
* Active texture will only be changed if pair of target/id is changed
* for specified unit. To ensure active texture is changed call
* RenderingManager::setActiveTexture()
*
* @param textureTarget Target to which the texture is bound. Must be
* one of GL_TEXTURE_1D, GL_TEXTURE_2D, GL_TEXTURE_3D,
* GL_TEXTURE_1D_ARRAY, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_RECTANGLE,
* GL_TEXTURE_CUBE_MAP, GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_BUFFER,
* GL_TEXTURE_2D_MULTISAMPLE or GL_TEXTURE_2D_MULTISAMPLE_ARRAY
* @param textureId Texture id
* @param slot
*/
void bindTexture(GLenum textureTarget, GLuint textureId, size_t slot);
protected:
void onInit() override;
private:
static constexpr auto TEXTURE_COUNT = 32u;
std::shared_ptr<WindowManager> m_windowManager;
RenderingParameters m_renderingParameters{};
GLint m_viewport[4]{};
GLclampf m_clearColor[4]{0.0f, 0.0f, 0.0f, 1.0f};
float m_clearDepth{1.0f};
GLuint m_currentShaderId{0};
GLuint m_currentFrameBufferId{0};
size_t m_activeTextureUnit{0};
};
} // namespace core
| 24.273585 | 86 | 0.628708 | Rexagon |
3f2ddf44463cbe1e1e2ac6271f0b4cd2b031eb7c | 9,120 | cpp | C++ | weather.cpp | kubeeapp/Sprinks-Firmware | 5afb4e7184b1b34af7e123baa0dcd67adcfc6b8c | [
"Apache-2.0"
] | null | null | null | weather.cpp | kubeeapp/Sprinks-Firmware | 5afb4e7184b1b34af7e123baa0dcd67adcfc6b8c | [
"Apache-2.0"
] | null | null | null | weather.cpp | kubeeapp/Sprinks-Firmware | 5afb4e7184b1b34af7e123baa0dcd67adcfc6b8c | [
"Apache-2.0"
] | null | null | null | /* OpenSprinkler Unified (AVR/RPI/BBB/LINUX) Firmware
* Copyright (C) 2015 by Ray Wang (ray@opensprinkler.com)
*
* Weather functions
* Feb 2015 @ OpenSprinkler.com
*
* This file is part of the OpenSprinkler library
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "OpenSprinkler.h"
#include "utils.h"
#include "server.h"
#include "weather.h"
#if defined(ARDUINO)
#ifdef ESP8266
extern EthernetServer *m_server;
extern char ether_buffer[];
#endif
#else
#include "etherport.h"
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
extern char ether_buffer[];
#endif
extern const char wtopts_filename[];
extern OpenSprinkler os; // OpenSprinkler object
extern char tmp_buffer[];
byte findKeyVal (const char *str,char *strbuf, uint8_t maxlen,const char *key,bool key_in_pgm=false,uint8_t *keyfound=NULL);
void write_log(byte type, ulong curr_time);
// The weather function calls getweather.py on remote server to retrieve weather data
// the default script is WEATHER_SCRIPT_HOST/weather?.py
//static char website[] PROGMEM = DEFAULT_WEATHER_URL ;
static void getweather_callback(byte status, uint16_t off, uint16_t len) {
#if defined(ARDUINO) && !defined(ESP8266)
char *p = (char*)Ethernet::buffer + off;
#else
char *p = ether_buffer;
#endif
/* scan the buffer until the first & symbol */
while(*p && *p!='&') {
p++;
}
if (*p != '&') return;
int v;
if (findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("sunrise"), true)) {
v = atoi(tmp_buffer);
if (v>=0 && v<=1440 && v != os.nvdata.sunrise_time) {
os.nvdata.sunrise_time = v;
os.nvdata_save();
os.weather_update_flag |= WEATHER_UPDATE_SUNRISE;
}
}
if (findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("sunset"), true)) {
v = atoi(tmp_buffer);
if (v>=0 && v<=1440 && v != os.nvdata.sunset_time) {
os.nvdata.sunset_time = v;
os.nvdata_save();
os.weather_update_flag |= WEATHER_UPDATE_SUNSET;
}
}
if (findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("eip"), true)) {
uint32_t l = atol(tmp_buffer);
if(l != os.nvdata.external_ip) {
os.nvdata.external_ip = atol(tmp_buffer);
os.nvdata_save();
os.weather_update_flag |= WEATHER_UPDATE_EIP;
}
}
if (findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("scale"), true)) {
v = atoi(tmp_buffer);
if (v>=0 && v<=250 && v != os.options[OPTION_WATER_PERCENTAGE]) {
// only save if the value has changed
os.options[OPTION_WATER_PERCENTAGE] = v;
os.options_save();
os.weather_update_flag |= WEATHER_UPDATE_WL;
}
}
if (findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("tz"), true)) {
v = atoi(tmp_buffer);
if (v>=0 && v<= 108) {
if (v != os.options[OPTION_TIMEZONE]) {
// if timezone changed, save change and force ntp sync
os.options[OPTION_TIMEZONE] = v;
os.options_save();
os.weather_update_flag |= WEATHER_UPDATE_TZ;
}
}
}
if (findKeyVal(p, tmp_buffer, TMP_BUFFER_SIZE, PSTR("rd"), true)) {
v = atoi(tmp_buffer);
if (v>0) {
os.nvdata.rd_stop_time = os.now_tz() + (unsigned long) v * 3600;
os.raindelay_start();
} else if (v==0) {
os.raindelay_stop();
}
}
os.checkwt_success_lasttime = os.now_tz();
write_log(LOGDATA_WATERLEVEL, os.checkwt_success_lasttime);
}
#if !defined(ARDUINO) || defined(ESP8266)
void peel_http_header() { // remove the HTTP header
int i=0;
bool eol=true;
while(i<ETHER_BUFFER_SIZE) {
char c = ether_buffer[i];
if(c==0) return;
if(c=='\n' && eol) {
// copy
i++;
int j=0;
while(i<ETHER_BUFFER_SIZE) {
ether_buffer[j]=ether_buffer[i];
if(ether_buffer[j]==0) break;
i++;
j++;
}
return;
}
if(c=='\n') {
eol=true;
} else if (c!='\r') {
eol=false;
}
i++;
}
}
#endif
#if defined(ARDUINO) // for AVR
void GetWeather() {
// perform DNS lookup for every query
nvm_read_block(tmp_buffer, (void*)ADDR_NVM_WEATHERURL, MAX_WEATHERURL);
#if defined(ESP8266)
Client *client;
if (m_server) {
client = new EthernetClient();
} else {
if (os.state!=OS_STATE_CONNECTED || WiFi.status()!=WL_CONNECTED) return;
client = new WiFiClient();
}
client->connect(tmp_buffer, 80);
#else
ether.dnsLookup(tmp_buffer, true);
#endif
char tmp[60];
read_from_file(wtopts_filename, tmp, 60);
#ifdef ESP8266
BufferFiller bf = tmp_buffer;
#else
BufferFiller bf = (uint8_t*)tmp_buffer;
#endif
bf.emit_p(PSTR("$D.py?loc=$E&key=$E&fwv=$D&wto=$S"),
(int) os.options[OPTION_USE_WEATHER],
ADDR_NVM_LOCATION,
ADDR_NVM_WEATHER_KEY,
(int)os.options[OPTION_FW_VERSION],
tmp);
// copy string to tmp_buffer, replacing all spaces with _
char *src=tmp_buffer+strlen(tmp_buffer);
char *dst=tmp_buffer+TMP_BUFFER_SIZE-12;
char c;
// url encode. convert SPACE to %20
// copy reversely from the end because we are potentially expanding
// the string size
while(src!=tmp_buffer) {
c = *src--;
if(c==' ') {
*dst-- = '0';
*dst-- = '2';
*dst-- = '%';
} else {
*dst-- = c;
}
};
*dst = *src;
#ifdef ESP8266
char urlBuffer[255];
strcpy(urlBuffer, "GET /weather");
strcat(urlBuffer, dst);
strcat(urlBuffer, " HTTP/1.0\r\nHOST: ");
strcat(urlBuffer, "*\r\n\r\n");
time_t timeout = os.now_tz() + 5; // 5 seconds timeout
client->write((uint8_t *)urlBuffer, strlen(urlBuffer));
while(!client->available() && os.now_tz() < timeout) {
yield();
}
bzero(ether_buffer, ETHER_BUFFER_SIZE);
while(client->available()) {
client->read((uint8_t*)ether_buffer, ETHER_BUFFER_SIZE);
yield();
}
client->stop();
delete client;
peel_http_header();
getweather_callback(0, 0, ETHER_BUFFER_SIZE);
#else
uint16_t _port = ether.hisport; // save current port number
ether.hisport = 80;
ether.browseUrl(PSTR("/weather"), dst, PSTR("*"), getweather_callback);
ether.hisport = _port;
#endif
}
#else // for RPI/BBB/LINUX
void GetWeather() {
EthernetClient client;
uint16_t port = 80;
char * delim;
struct hostent *server;
nvm_read_block(tmp_buffer, (void*)ADDR_NVM_WEATHERURL, MAX_WEATHERURL);
// Check to see if url specifies a port number to use
delim = strchr(tmp_buffer, ':');
if (delim != NULL) {
*delim = 0;
port = atoi(delim+1);
}
server = gethostbyname(tmp_buffer);
if (!server) {
DEBUG_PRINT("can't resolve weather server - ");
DEBUG_PRINTLN(tmp_buffer);
return;
}
DEBUG_PRINT("weather server ip:port - ");
DEBUG_PRINT(((uint8_t*)server->h_addr)[0]);
DEBUG_PRINT(".");
DEBUG_PRINT(((uint8_t*)server->h_addr)[1]);
DEBUG_PRINT(".");
DEBUG_PRINT(((uint8_t*)server->h_addr)[2]);
DEBUG_PRINT(".");
DEBUG_PRINT(((uint8_t*)server->h_addr)[3]);
DEBUG_PRINT(":");
DEBUG_PRINTLN(port);
if (!client.connect((uint8_t*)server->h_addr, port)) {
client.stop();
return;
}
BufferFiller bf = tmp_buffer;
char tmp[100];
read_from_file(wtopts_filename, tmp, 100);
bf.emit_p(PSTR("$D.py?loc=$E&key=$E&fwv=$D&wto=$S"),
(int) os.options[OPTION_USE_WEATHER],
ADDR_NVM_LOCATION,
ADDR_NVM_WEATHER_KEY,
(int)os.options[OPTION_FW_VERSION],
tmp);
char *src=tmp_buffer+strlen(tmp_buffer);
char *dst=tmp_buffer+TMP_BUFFER_SIZE-12;
char c;
// url encode. convert SPACE to %20
// copy reversely from the end because we are potentially expanding
// the string size
while(src!=tmp_buffer) {
c = *src--;
if(c==' ') {
*dst-- = '0';
*dst-- = '2';
*dst-- = '%';
} else {
*dst-- = c;
}
};
*dst = *src;
char urlBuffer[255];
strcpy(urlBuffer, "GET /weather");
strcat(urlBuffer, dst);
strcat(urlBuffer, " HTTP/1.0\r\nHOST: ");
strcat(urlBuffer, server->h_name);
strcat(urlBuffer, "\r\n\r\n");
client.write((uint8_t *)urlBuffer, strlen(urlBuffer));
bzero(ether_buffer, ETHER_BUFFER_SIZE);
time_t timeout = os.now_tz() + 5; // 5 seconds timeout
while(os.now_tz() < timeout) {
int len=client.read((uint8_t *)ether_buffer, ETHER_BUFFER_SIZE);
if (len<=0) {
if(!client.connected())
break;
else
continue;
}
peel_http_header();
getweather_callback(0, 0, ETHER_BUFFER_SIZE);
break;
}
client.stop();
}
#endif // GetWeather()
| 27.142857 | 124 | 0.634868 | kubeeapp |
3f2f517f2caebce603c1709fbb3c674f21e09b8f | 6,376 | cpp | C++ | cpp-restsdk/model/Simulation.cpp | thracesystems/powermeter-api | 7bdab034ff916ee49e986de88f157bd044e981c1 | [
"Apache-2.0"
] | null | null | null | cpp-restsdk/model/Simulation.cpp | thracesystems/powermeter-api | 7bdab034ff916ee49e986de88f157bd044e981c1 | [
"Apache-2.0"
] | null | null | null | cpp-restsdk/model/Simulation.cpp | thracesystems/powermeter-api | 7bdab034ff916ee49e986de88f157bd044e981c1 | [
"Apache-2.0"
] | null | null | null | /**
* PowerMeter API
* API
*
* The version of the OpenAPI document: 2021.4.1
*
* NOTE: This class is auto generated by OpenAPI-Generator 4.3.1.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "Simulation.h"
namespace powermeter {
namespace model {
Simulation::Simulation()
{
m_Id = 0;
m_IdIsSet = false;
m_Name = utility::conversions::to_string_t("");
m_NameIsSet = false;
m_Editable = false;
m_EditableIsSet = false;
m_OrderIsSet = false;
}
Simulation::~Simulation()
{
}
void Simulation::validate()
{
// TODO: implement validation
}
web::json::value Simulation::toJson() const
{
web::json::value val = web::json::value::object();
if(m_IdIsSet)
{
val[utility::conversions::to_string_t("id")] = ModelBase::toJson(m_Id);
}
if(m_NameIsSet)
{
val[utility::conversions::to_string_t("name")] = ModelBase::toJson(m_Name);
}
if(m_EditableIsSet)
{
val[utility::conversions::to_string_t("editable")] = ModelBase::toJson(m_Editable);
}
if(m_OrderIsSet)
{
val[utility::conversions::to_string_t("order")] = ModelBase::toJson(m_Order);
}
return val;
}
bool Simulation::fromJson(const web::json::value& val)
{
bool ok = true;
if(val.has_field(utility::conversions::to_string_t("id")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("id"));
if(!fieldValue.is_null())
{
int32_t refVal_id;
ok &= ModelBase::fromJson(fieldValue, refVal_id);
setId(refVal_id);
}
}
if(val.has_field(utility::conversions::to_string_t("name")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("name"));
if(!fieldValue.is_null())
{
utility::string_t refVal_name;
ok &= ModelBase::fromJson(fieldValue, refVal_name);
setName(refVal_name);
}
}
if(val.has_field(utility::conversions::to_string_t("editable")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("editable"));
if(!fieldValue.is_null())
{
bool refVal_editable;
ok &= ModelBase::fromJson(fieldValue, refVal_editable);
setEditable(refVal_editable);
}
}
if(val.has_field(utility::conversions::to_string_t("order")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("order"));
if(!fieldValue.is_null())
{
std::vector<int32_t> refVal_order;
ok &= ModelBase::fromJson(fieldValue, refVal_order);
setOrder(refVal_order);
}
}
return ok;
}
void Simulation::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
if(m_IdIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("id"), m_Id));
}
if(m_NameIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("name"), m_Name));
}
if(m_EditableIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("editable"), m_Editable));
}
if(m_OrderIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("order"), m_Order));
}
}
bool Simulation::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix)
{
bool ok = true;
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
if(multipart->hasContent(utility::conversions::to_string_t("id")))
{
int32_t refVal_id;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("id")), refVal_id );
setId(refVal_id);
}
if(multipart->hasContent(utility::conversions::to_string_t("name")))
{
utility::string_t refVal_name;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("name")), refVal_name );
setName(refVal_name);
}
if(multipart->hasContent(utility::conversions::to_string_t("editable")))
{
bool refVal_editable;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("editable")), refVal_editable );
setEditable(refVal_editable);
}
if(multipart->hasContent(utility::conversions::to_string_t("order")))
{
std::vector<int32_t> refVal_order;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("order")), refVal_order );
setOrder(refVal_order);
}
return ok;
}
int32_t Simulation::getId() const
{
return m_Id;
}
void Simulation::setId(int32_t value)
{
m_Id = value;
m_IdIsSet = true;
}
bool Simulation::idIsSet() const
{
return m_IdIsSet;
}
void Simulation::unsetId()
{
m_IdIsSet = false;
}
utility::string_t Simulation::getName() const
{
return m_Name;
}
void Simulation::setName(const utility::string_t& value)
{
m_Name = value;
m_NameIsSet = true;
}
bool Simulation::nameIsSet() const
{
return m_NameIsSet;
}
void Simulation::unsetName()
{
m_NameIsSet = false;
}
bool Simulation::isEditable() const
{
return m_Editable;
}
void Simulation::setEditable(bool value)
{
m_Editable = value;
m_EditableIsSet = true;
}
bool Simulation::editableIsSet() const
{
return m_EditableIsSet;
}
void Simulation::unsetEditable()
{
m_EditableIsSet = false;
}
std::vector<int32_t>& Simulation::getOrder()
{
return m_Order;
}
void Simulation::setOrder(std::vector<int32_t> value)
{
m_Order = value;
m_OrderIsSet = true;
}
bool Simulation::orderIsSet() const
{
return m_OrderIsSet;
}
void Simulation::unsetOrder()
{
m_OrderIsSet = false;
}
}
}
| 24.617761 | 129 | 0.646644 | thracesystems |
3f2ff5bee1823fa9a0cb46a659aeb463e7ff7e5a | 2,130 | cpp | C++ | TerraForge3D/src/Shading/ShaderNodes/ShaderOutputNode.cpp | fiplox/TerraForge3D | 940c301a8590d00ea24d966b772478a6cacba115 | [
"MIT"
] | 434 | 2021-11-03T06:03:07.000Z | 2022-03-31T22:52:19.000Z | TerraForge3D/src/Shading/ShaderNodes/ShaderOutputNode.cpp | fiplox/TerraForge3D | 940c301a8590d00ea24d966b772478a6cacba115 | [
"MIT"
] | 14 | 2021-11-03T12:11:30.000Z | 2022-03-31T16:52:24.000Z | TerraForge3D/src/Shading/ShaderNodes/ShaderOutputNode.cpp | fiplox/TerraForge3D | 940c301a8590d00ea24d966b772478a6cacba115 | [
"MIT"
] | 45 | 2021-11-04T07:34:21.000Z | 2022-03-31T07:06:05.000Z | #include "Shading/ShaderNodes/ShaderOutputNode.h"
#include <iostream>
void ShaderOutputNode::OnEvaluate(GLSLFunction *function, GLSLLine *line)
{
if (inputPins[0]->IsLinked())
{
GLSLLine ln("");
inputPins[0]->other->Evaluate(GetParams(function, &ln));
line->line = ln.line;
}
else
{
function->AddLine(GLSLLine("vec3 " + VAR("norm") + " = normalize(Normal);"));
function->AddLine(GLSLLine("vec3 " + VAR("lightDir") + " = normalize(_LightPosition - FragPos.xyz );"));
function->AddLine(GLSLLine("float " + VAR("diff") + " = max(dot(" + VAR("norm") + ", " + VAR("lightDir") + "), 0.0f);"));
function->AddLine(GLSLLine("vec3 " + VAR("diffuse") + " = " + VAR("diff") + " * _LightColor;"));
function->AddLine(GLSLLine("vec3 " + VAR("result") + " = (vec3(0.2, 0.2, 0.2) + " + VAR("diffuse") + ")" + \
" * vec3(" + SDATA(0) + ", " + SDATA(1) + ", " + SDATA(2) + ");"));
line->line = VAR("result");
}
}
void ShaderOutputNode::Load(nlohmann::json data)
{
color[0] = data["color.r"];
color[1] = data["color.g"];
color[2] = data["color.b"];
color[3] = data["color.a"];
}
nlohmann::json ShaderOutputNode::Save()
{
nlohmann::json data;
data["type"] = "ShaderOutput";
data["color.r"] = color[0];
data["color.g"] = color[1];
data["color.b"] = color[2];
data["color.a"] = color[3];
return data;
}
void ShaderOutputNode::UpdateShaders()
{
sharedData->d0 = color[0];
sharedData->d1 = color[1];
sharedData->d2 = color[2];
}
void ShaderOutputNode::OnRender()
{
DrawHeader("Output");
inputPins[0]->Render();
if (!inputPins[0]->IsLinked())
{
if(ImGui::ColorPicker4("Object Color", color))
{
sharedData->d0 = color[0];
sharedData->d1 = color[1];
sharedData->d2 = color[2];
}
}
else
{
ImGui::Dummy(ImVec2(100, 40));
}
}
ShaderOutputNode::ShaderOutputNode(GLSLHandler *handler)
:SNENode(handler)
{
name = "Output";
color[0] = color[1] = color[2] = color[3] = 1.0f;
headerColor = ImColor(SHADER_OUTPUT_NODE_COLOR);
inputPins.push_back(new SNEPin(NodeEditorPinType::Input, SNEPinType::SNEPinType_Float3));
}
ShaderOutputNode::~ShaderOutputNode()
{
} | 25.058824 | 123 | 0.619249 | fiplox |
3f30da1b7a5853ea1b7bf89005db4e021dc2baed | 1,195 | cpp | C++ | Thalassa/Motor2D/j1LifeItem.cpp | xavimarin35/PlatformerDev | 98565270f5c62c1a47103bb413ef377e124b35ec | [
"MIT"
] | 1 | 2020-07-04T11:04:52.000Z | 2020-07-04T11:04:52.000Z | Thalassa/Motor2D/j1LifeItem.cpp | xavimarin35/PlatformerDev | 98565270f5c62c1a47103bb413ef377e124b35ec | [
"MIT"
] | null | null | null | Thalassa/Motor2D/j1LifeItem.cpp | xavimarin35/PlatformerDev | 98565270f5c62c1a47103bb413ef377e124b35ec | [
"MIT"
] | 2 | 2019-12-27T12:14:20.000Z | 2020-09-05T16:01:29.000Z | #include "j1LifeItem.h"
#include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Textures.h"
#include "j1Render.h"
#include "j1Input.h"
#include "j1Collisions.h"
#include "j1Window.h"
#include "j1Player.h"
#include "j1Audio.h"
#include "j1Map.h"
#include "j1Scene1.h"
#include "Brofiler/Brofiler.h"
j1LifeItem::j1LifeItem(int x, int y, ENTITY_TYPE type) : j1Entity(x, y, ENTITY_TYPE::LIFE_ITEM)
{
idleAnim.LoadAnimations("bubbleIdle");
destroyAnim.LoadAnimations("bubbleDestroy");
}
j1LifeItem::~j1LifeItem()
{
}
bool j1LifeItem::Start()
{
sprites = App->tex->Load("textures/Particles/bubble.png");
animation = &idleAnim;
collider = App->collisions->AddCollider({ (int)position.x + 2, (int)position.y + 2, 12, 12 }, COLLIDER_ITEM, App->entity_manager);
return true;
}
bool j1LifeItem::Update(float dt)
{
BlitEntity(animation->GetCurrentFrame(dt), false);
return true;
}
bool j1LifeItem::PostUpdate()
{
return true;
}
bool j1LifeItem::CleanUp()
{
return true;
}
void j1LifeItem::OnCollision(Collider * c1, Collider * c2)
{
if (c1->type == COLLIDER_PLAYER) {
if (c2->type == COLLIDER_ITEM)
{
animation = &destroyAnim;
c2->to_delete = true;
}
}
}
| 18.106061 | 131 | 0.701255 | xavimarin35 |
3f3214cefd61d5ced909f28c65f01c228e54d931 | 427 | hpp | C++ | src/red4ext/LoadResRef.hpp | jackhumbert/flight_control | 02938f5a26b3a299ef3d9b9e4d40e9294872a7ee | [
"MIT"
] | 1 | 2021-11-09T13:31:07.000Z | 2021-11-09T13:31:07.000Z | src/red4ext/LoadResRef.hpp | jackhumbert/flight_control | 02938f5a26b3a299ef3d9b9e4d40e9294872a7ee | [
"MIT"
] | null | null | null | src/red4ext/LoadResRef.hpp | jackhumbert/flight_control | 02938f5a26b3a299ef3d9b9e4d40e9294872a7ee | [
"MIT"
] | null | null | null | #include <RED4ext/Addresses.hpp>
#include <RED4ext/NativeTypes.hpp>
// 48 89 5C 24 08 48 89 74 24 10 57 48 83 EC 60 41 0F B6 D8 48 8B FA 48 8B F1 48 C7 44 24 20 00 00
constexpr uintptr_t LoadResRefAddr = 0x140200060 - RED4ext::Addresses::ImageBase;
template<typename T>
RED4ext::RelocFunc<RED4ext::ResourceHandle<T> *(*)(uint64_t * hashPointer, RED4ext::ResourceHandle<T> *wrapper, bool sync)>
LoadResRef(LoadResRefAddr); | 47.444444 | 123 | 0.751756 | jackhumbert |
3f338b92d7a033347435f56b928f618be65676b8 | 32,220 | cpp | C++ | enhanced/java/jdktools/modules/jpda/src/main/native/jdwp/common/transport/dt_socket/SocketTransport.cpp | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | 5 | 2017-03-08T20:32:39.000Z | 2021-07-10T10:12:38.000Z | enhanced/java/jdktools/modules/jpda/src/main/native/jdwp/common/transport/dt_socket/SocketTransport.cpp | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | null | null | null | enhanced/java/jdktools/modules/jpda/src/main/native/jdwp/common/transport/dt_socket/SocketTransport.cpp | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | 4 | 2015-07-07T07:06:59.000Z | 2018-06-19T22:38:04.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Viacheslav G. Rybalov
*/
// SocketTransport.cpp
//
/**
* This is implementation of JDWP Agent TCP/IP Socket transport.
* Main module.
*/
#include "SocketTransport_pd.h"
/**
* This function sets into internalEnv struct message and status code of last transport error
*/
static void
SetLastTranError(jdwpTransportEnv* env, const char* messagePtr, int errorStatus)
{
internalEnv* ienv = (internalEnv*)env->functions->reserved1;
if (ienv->lastError != 0) {
ienv->lastError->insertError(messagePtr, errorStatus);
} else {
ienv->lastError = new(ienv->alloc, ienv->free) LastTransportError(messagePtr, errorStatus, ienv->alloc, ienv->free);
}
return;
} // SetLastTranError
/**
* This function sets into internalEnv struct prefix message for last transport error
*/
static void
SetLastTranErrorMessagePrefix(jdwpTransportEnv* env, const char* messagePrefix)
{
internalEnv* ienv = (internalEnv*)env->functions->reserved1;
if (ienv->lastError != 0) {
ienv->lastError->addErrorMessagePrefix(messagePrefix);
}
return;
} // SetLastTranErrorMessagePrefix
/**
* The timeout used for invocation of select function in SelectRead and SelectSend methods
*/
static const jint cycle = 1000; // wait cycle in milliseconds
/**
* This function is used to determine the read status of socket (in terms of select function).
* The function avoids absolutely blocking select
*/
static jdwpTransportError
SelectRead(jdwpTransportEnv* env, SOCKET sckt, jlong deadline = 0) {
jlong currentTimeout = cycle;
while ((deadline == 0) || ((currentTimeout = (deadline - GetTickCount())) > 0)) {
currentTimeout = currentTimeout < cycle ? currentTimeout : cycle;
TIMEVAL tv = {(long)(currentTimeout / 1000), (long)(currentTimeout % 1000)};
fd_set fdread;
FD_ZERO(&fdread);
FD_SET(sckt, &fdread);
int ret = select((int)sckt + 1, &fdread, NULL, NULL, &tv);
if (ret == SOCKET_ERROR) {
int err = GetLastErrorStatus();
// ignore signal interruption
if (err != SOCKET_ERROR_EINTR) {
SetLastTranError(env, "socket error", err);
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
}
if ((ret > 0) && (FD_ISSET(sckt, &fdread))) {
return JDWPTRANSPORT_ERROR_NONE; //timeout is not occurred
}
}
SetLastTranError(env, "timeout occurred", 0);
return JDWPTRANSPORT_ERROR_TIMEOUT; //timeout occurred
} // SelectRead
/**
* This function is used to determine the send status of socket (in terms of select function).
* The function avoids absolutely blocking select
*/
static jdwpTransportError
SelectSend(jdwpTransportEnv* env, SOCKET sckt, jlong deadline = 0) {
jlong currentTimeout = cycle;
while ((deadline == 0) || ((currentTimeout = (deadline - GetTickCount())) > 0)) {
currentTimeout = currentTimeout < cycle ? currentTimeout : cycle;
TIMEVAL tv = {(long)(currentTimeout / 1000), (long)(currentTimeout % 1000)};
fd_set fdwrite;
FD_ZERO(&fdwrite);
FD_SET(sckt, &fdwrite);
int ret = select((int)sckt + 1, NULL, &fdwrite, NULL, &tv);
if (ret == SOCKET_ERROR) {
int err = GetLastErrorStatus();
// ignore signal interruption
if (err != SOCKET_ERROR_EINTR) {
SetLastTranError(env, "socket error", err);
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
}
if ((ret > 0) && (FD_ISSET(sckt, &fdwrite))) {
return JDWPTRANSPORT_ERROR_NONE; //timeout is not occurred
}
}
SetLastTranError(env, "timeout occurred", 0);
return JDWPTRANSPORT_ERROR_TIMEOUT; //timeout occurred
} // SelectRead
/**
* This function sends data on a connected socket
*/
static jdwpTransportError
SendData(jdwpTransportEnv* env, SOCKET sckt, const char* data, int dataLength, jlong deadline = 0)
{
long left = dataLength;
long off = 0;
int ret;
while (left > 0) {
jdwpTransportError err = SelectSend(env, sckt, deadline);
if (err != JDWPTRANSPORT_ERROR_NONE) {
return err;
}
ret = send(sckt, (data + off), left, 0);
if (ret == SOCKET_ERROR) {
int err = GetLastErrorStatus();
// ignore signal interruption
if (err != SOCKET_ERROR_EINTR) {
SetLastTranError(env, "socket error", err);
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
}
left -= ret;
off += ret;
} //while
return JDWPTRANSPORT_ERROR_NONE;
} //SendData
/**
* This function receives data from a connected socket
*/
static jdwpTransportError
ReceiveData(jdwpTransportEnv* env, SOCKET sckt, char* buffer, int dataLength, jlong deadline = 0, int* readByte = 0)
{
long left = dataLength;
long off = 0;
int ret;
if (readByte != 0) {
*readByte = 0;
}
while (left > 0) {
jdwpTransportError err = SelectRead(env, sckt, deadline);
if (err != JDWPTRANSPORT_ERROR_NONE) {
return err;
}
ret = recv(sckt, (buffer + off), left, 0);
if (ret == SOCKET_ERROR) {
int err = GetLastErrorStatus();
// ignore signal interruption
if (err != SOCKET_ERROR_EINTR) {
SetLastTranError(env, "data receiving failed", err);
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
}
if (ret == 0) {
SetLastTranError(env, "premature EOF", 0);
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
left -= ret;
off += ret;
if (readByte != 0) {
*readByte = off;
}
} //while
return JDWPTRANSPORT_ERROR_NONE;
} // ReceiveData
/**
* This function enable/disables socket blocking mode
*/
static bool
SetSocketBlockingMode(jdwpTransportEnv* env, SOCKET sckt, bool isBlocked)
{
unsigned long ul = isBlocked ? 0 : 1;
if (ioctlsocket(sckt, FIONBIO, &ul) == SOCKET_ERROR) {
SetLastTranError(env, "socket error", GetLastErrorStatus());
return false;
}
return true;
} // SetSocketBlockingMode()
/**
* This function performes handshake procedure
*/
static jdwpTransportError
CheckHandshaking(jdwpTransportEnv* env, SOCKET sckt, jlong handshakeTimeout)
{
const char* handshakeString = "JDWP-Handshake";
char receivedString[14]; //length of "JDWP-Handshake"
jlong deadline = (handshakeTimeout == 0) ? 0 : (jlong)GetTickCount() + handshakeTimeout;
jdwpTransportError err;
err = ReceiveData(env, sckt, receivedString, (int)strlen(handshakeString), deadline);
if (err != JDWPTRANSPORT_ERROR_NONE) {
SetLastTranErrorMessagePrefix(env, "'JDWP-Handshake' receiving error: ");
return err;
}
if (memcmp(receivedString, handshakeString, 14) != 0) {
SetLastTranError(env, "handshake error, 'JDWP-Handshake' is not received", 0);
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
err = SendData(env, sckt, handshakeString, (int)strlen(handshakeString), deadline);
if (err != JDWPTRANSPORT_ERROR_NONE) {
SetLastTranErrorMessagePrefix(env, "'JDWP-Handshake' sending error: ");
return err;
}
return JDWPTRANSPORT_ERROR_NONE;
}// CheckHandshaking
/**
* This function decodes address and populates sockaddr_in structure
*/
static jdwpTransportError
DecodeAddress(jdwpTransportEnv* env, const char *address, struct sockaddr_in *sa, bool isServer)
{
memset(sa, 0, sizeof(struct sockaddr_in));
sa->sin_family = AF_INET;
if ((address == 0) || (*address == 0)) { //empty address
sa->sin_addr.s_addr = isServer ? htonl(INADDR_ANY) : inet_addr("127.0.0.1");
sa->sin_port = 0;
return JDWPTRANSPORT_ERROR_NONE;
}
const char* colon = strchr(address, ':');
if (colon == 0) { //address is like "port"
sa->sin_port = htons((u_short)atoi(address));
sa->sin_addr.s_addr = isServer ? htonl(INADDR_ANY) : inet_addr("127.0.0.1");
} else { //address is like "host:port"
sa->sin_port = htons((u_short)atoi(colon + 1));
char *hostName = (char*)(((internalEnv*)env->functions->reserved1)
->alloc)((jint)(colon - address + 1));
if (hostName == 0) {
SetLastTranError(env, "out of memory", 0);
return JDWPTRANSPORT_ERROR_OUT_OF_MEMORY;
}
memcpy(hostName, address, colon - address);
hostName[colon - address] = '\0';
sa->sin_addr.s_addr = inet_addr(hostName);
if (sa->sin_addr.s_addr == INADDR_NONE) {
struct hostent *host = gethostbyname(hostName);
if (host == 0) {
SetLastTranError(env, "unable to resolve host name", 0);
(((internalEnv*)env->functions->reserved1)->free)(hostName);
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
memcpy(&(sa->sin_addr), host->h_addr_list[0], host->h_length);
} //if
(((internalEnv*)env->functions->reserved1)->free)(hostName);
} //if
return JDWPTRANSPORT_ERROR_NONE;
} //DecodeAddress
/**
* This function implements jdwpTransportEnv::GetCapabilities
*/
static jdwpTransportError JNICALL
TCPIPSocketTran_GetCapabilities(jdwpTransportEnv* env,
JDWPTransportCapabilities* capabilitiesPtr)
{
memset(capabilitiesPtr, 0, sizeof(JDWPTransportCapabilities));
capabilitiesPtr->can_timeout_attach = 1;
capabilitiesPtr->can_timeout_accept = 1;
capabilitiesPtr->can_timeout_handshake = 1;
return JDWPTRANSPORT_ERROR_NONE;
} //TCPIPSocketTran_GetCapabilities
/**
* This function implements jdwpTransportEnv::Close
*/
static jdwpTransportError JNICALL
TCPIPSocketTran_Close(jdwpTransportEnv* env)
{
SOCKET envClientSocket = ((internalEnv*)env->functions->reserved1)->envClientSocket;
if (envClientSocket == INVALID_SOCKET) {
return JDWPTRANSPORT_ERROR_NONE;
}
((internalEnv*)env->functions->reserved1)->envClientSocket = INVALID_SOCKET;
int err;
err = shutdown(envClientSocket, SD_BOTH);
if (err == SOCKET_ERROR) {
SetLastTranError(env, "close socket failed", GetLastErrorStatus());
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
err = closesocket(envClientSocket);
if (err == SOCKET_ERROR) {
SetLastTranError(env, "close socket failed", GetLastErrorStatus());
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
return JDWPTRANSPORT_ERROR_NONE;
} //TCPIPSocketTran_Close
/**
* This function sets socket options SO_REUSEADDR and TCP_NODELAY
*/
static bool
SetSocketOptions(jdwpTransportEnv* env, SOCKET sckt)
{
BOOL isOn = TRUE;
if (setsockopt(sckt, SOL_SOCKET, SO_REUSEADDR, (const char*)&isOn, sizeof(isOn)) == SOCKET_ERROR) {
SetLastTranError(env, "setsockopt(SO_REUSEADDR) failed", GetLastErrorStatus());
return false;
}
if (setsockopt(sckt, IPPROTO_TCP, TCP_NODELAY, (const char*)&isOn, sizeof(isOn)) == SOCKET_ERROR) {
SetLastTranError(env, "setsockopt(TCPNODELAY) failed", GetLastErrorStatus());
return false;
}
return true;
} // SetSocketOptions()
/**
* This function implements jdwpTransportEnv::Attach
*/
static jdwpTransportError JNICALL
TCPIPSocketTran_Attach(jdwpTransportEnv* env, const char* address,
jlong attachTimeout, jlong handshakeTimeout)
{
if ((address == 0) || (*address == 0)) {
SetLastTranError(env, "address is missing", 0);
return JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT;
}
if (attachTimeout < 0) {
SetLastTranError(env, "attachTimeout timeout is negative", 0);
return JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT;
}
if (handshakeTimeout < 0) {
SetLastTranError(env, "handshakeTimeout timeout is negative", 0);
return JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT;
}
SOCKET envClientSocket = ((internalEnv*)env->functions->reserved1)->envClientSocket;
if (envClientSocket != INVALID_SOCKET) {
SetLastTranError(env, "there is already an open connection to the debugger", 0);
return JDWPTRANSPORT_ERROR_ILLEGAL_STATE ;
}
SOCKET envServerSocket = ((internalEnv*)env->functions->reserved1)->envServerSocket;
if (envServerSocket != INVALID_SOCKET) {
SetLastTranError(env, "transport is currently in listen mode", 0);
return JDWPTRANSPORT_ERROR_ILLEGAL_STATE ;
}
struct sockaddr_in serverSockAddr;
jdwpTransportError res = DecodeAddress(env, address, &serverSockAddr, false);
if (res != JDWPTRANSPORT_ERROR_NONE) {
return res;
}
SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (clientSocket == INVALID_SOCKET) {
SetLastTranError(env, "unable to create socket", GetLastErrorStatus());
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
if (!SetSocketOptions(env, clientSocket)) {
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
if (attachTimeout == 0) {
if (!SetSocketBlockingMode(env, clientSocket, true)) {
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
int err = connect(clientSocket, (struct sockaddr *)&serverSockAddr, sizeof(serverSockAddr));
if (err == SOCKET_ERROR) {
SetLastTranError(env, "connection failed", GetLastErrorStatus());
SetSocketBlockingMode(env, clientSocket, false);
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
if (!SetSocketBlockingMode(env, clientSocket, false)) {
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
} else {
if (!SetSocketBlockingMode(env, clientSocket, false)) {
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
int err = connect(clientSocket, (struct sockaddr *)&serverSockAddr, sizeof(serverSockAddr));
if (err == SOCKET_ERROR) {
if (GetLastErrorStatus() != SOCKETWOULDBLOCK) {
SetLastTranError(env, "connection failed", GetLastErrorStatus());
return JDWPTRANSPORT_ERROR_IO_ERROR;
} else {
fd_set fdwrite;
FD_ZERO(&fdwrite);
FD_SET(clientSocket, &fdwrite);
TIMEVAL tv = {(long)(attachTimeout / 1000), (long)(attachTimeout % 1000)};
int ret = select((int)clientSocket + 1, NULL, &fdwrite, NULL, &tv);
if (ret == SOCKET_ERROR) {
SetLastTranError(env, "socket error", GetLastErrorStatus());
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
if ((ret != 1) || !(FD_ISSET(clientSocket, &fdwrite))) {
SetLastTranError(env, "timeout occurred", 0);
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
}
}
}
EnterCriticalSendSection(env);
EnterCriticalReadSection(env);
((internalEnv*)env->functions->reserved1)->envClientSocket = clientSocket;
res = CheckHandshaking(env, clientSocket, (long)handshakeTimeout);
LeaveCriticalReadSection(env);
LeaveCriticalSendSection(env);
if (res != JDWPTRANSPORT_ERROR_NONE) {
TCPIPSocketTran_Close(env);
return res;
}
return JDWPTRANSPORT_ERROR_NONE;
} //TCPIPSocketTran_Attach
/**
* This function implements jdwpTransportEnv::StartListening
*/
static jdwpTransportError JNICALL
TCPIPSocketTran_StartListening(jdwpTransportEnv* env, const char* address,
char** actualAddress)
{
SOCKET envClientSocket = ((internalEnv*)env->functions->reserved1)->envClientSocket;
if (envClientSocket != INVALID_SOCKET) {
SetLastTranError(env, "there is already an open connection to the debugger", 0);
return JDWPTRANSPORT_ERROR_ILLEGAL_STATE ;
}
SOCKET envServerSocket = ((internalEnv*)env->functions->reserved1)->envServerSocket;
if (envServerSocket != INVALID_SOCKET) {
SetLastTranError(env, "transport is currently in listen mode", 0);
return JDWPTRANSPORT_ERROR_ILLEGAL_STATE ;
}
jdwpTransportError res;
struct sockaddr_in serverSockAddr;
res = DecodeAddress(env, address, &serverSockAddr, true);
if (res != JDWPTRANSPORT_ERROR_NONE) {
return res;
}
SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket == INVALID_SOCKET) {
SetLastTranError(env, "unable to create socket", GetLastErrorStatus());
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
if (!SetSocketOptions(env, serverSocket)) {
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
int err;
err = bind(serverSocket, (struct sockaddr *)&serverSockAddr, sizeof(serverSockAddr));
if (err == SOCKET_ERROR) {
SetLastTranError(env, "binding to port failed", GetLastErrorStatus());
return JDWPTRANSPORT_ERROR_ILLEGAL_STATE ;
}
err = listen(serverSocket, SOMAXCONN);
if (err == SOCKET_ERROR) {
SetLastTranError(env, "listen start failed", GetLastErrorStatus());
return JDWPTRANSPORT_ERROR_ILLEGAL_STATE ;
}
if (!SetSocketBlockingMode(env, serverSocket, false)) {
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
((internalEnv*)env->functions->reserved1)->envServerSocket = serverSocket;
socklen_t len = sizeof(serverSockAddr);
err = getsockname(serverSocket, (struct sockaddr *)&serverSockAddr, &len);
if (err == SOCKET_ERROR) {
SetLastTranError(env, "socket error", GetLastErrorStatus());
return JDWPTRANSPORT_ERROR_ILLEGAL_STATE ;
}
char* retAddress = 0;
// RI always returns only port number in listening mode
/*
char portName[6];
sprintf(portName, "%d", ntohs(serverSockAddr.sin_port)); //instead of itoa()
char hostName[NI_MAXHOST];
if (getnameinfo((struct sockaddr *)&serverSockAddr, len, hostName, sizeof(hostName), NULL, 0, 0)) {
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
if (strcmp(hostName, "0.0.0.0") == 0) {
gethostname(hostName, sizeof(hostName));
}
retAddress = (char*)(((internalEnv*)env->functions->reserved1)
->alloc)((jint)(strlen(hostName) + strlen(portName) + 2));
if (retAddress == 0) {
SetLastTranError(env, "out of memory", 0);
return JDWPTRANSPORT_ERROR_OUT_OF_MEMORY;
}
sprintf(retAddress, "%s:%s", hostName, portName);
*/
retAddress = (char*)(((internalEnv*)env->functions->reserved1)->alloc)(6 + 1);
if (retAddress == 0) {
SetLastTranError(env, "out of memory", 0);
return JDWPTRANSPORT_ERROR_OUT_OF_MEMORY;
}
sprintf(retAddress, "%d", ntohs(serverSockAddr.sin_port));
*actualAddress = retAddress;
return JDWPTRANSPORT_ERROR_NONE;
} //TCPIPSocketTran_StartListening
/**
* This function implements jdwpTransportEnv::StopListening
*/
static jdwpTransportError JNICALL
TCPIPSocketTran_StopListening(jdwpTransportEnv* env)
{
SOCKET envServerSocket = ((internalEnv*)env->functions->reserved1)->envServerSocket;
if (envServerSocket == INVALID_SOCKET) {
return JDWPTRANSPORT_ERROR_NONE;
}
if (closesocket(envServerSocket) == SOCKET_ERROR) {
SetLastTranError(env, "close socket failed", GetLastErrorStatus());
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
((internalEnv*)env->functions->reserved1)->envServerSocket = INVALID_SOCKET;
return JDWPTRANSPORT_ERROR_NONE;
} //TCPIPSocketTran_StopListening
/**
* This function implements jdwpTransportEnv::Accept
*/
static jdwpTransportError JNICALL
TCPIPSocketTran_Accept(jdwpTransportEnv* env, jlong acceptTimeout,
jlong handshakeTimeout)
{
if (acceptTimeout < 0) {
SetLastTranError(env, "acceptTimeout timeout is negative", 0);
return JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT;
}
if (handshakeTimeout < 0) {
SetLastTranError(env, "handshakeTimeout timeout is negative", 0);
return JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT;
}
SOCKET envClientSocket = ((internalEnv*)env->functions->reserved1)->envClientSocket;
if (envClientSocket != INVALID_SOCKET) {
SetLastTranError(env, "there is already an open connection to the debugger", 0);
return JDWPTRANSPORT_ERROR_ILLEGAL_STATE ;
}
SOCKET envServerSocket = ((internalEnv*)env->functions->reserved1)->envServerSocket;
if (envServerSocket == INVALID_SOCKET) {
SetLastTranError(env, "transport is not currently in listen mode", 0);
return JDWPTRANSPORT_ERROR_ILLEGAL_STATE ;
}
struct sockaddr serverSockAddr;
socklen_t len = sizeof(serverSockAddr);
int res = getsockname(envServerSocket, &serverSockAddr, &len);
if (res == SOCKET_ERROR) {
SetLastTranError(env, "connection failed", GetLastErrorStatus());
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
jlong deadline = (acceptTimeout == 0) ? 0 : (jlong)GetTickCount() + acceptTimeout;
jdwpTransportError err = SelectRead(env, envServerSocket, deadline);
if (err != JDWPTRANSPORT_ERROR_NONE) {
return err;
}
SOCKET clientSocket = accept(envServerSocket, &serverSockAddr, &len);
if (clientSocket == INVALID_SOCKET) {
SetLastTranError(env, "socket accept failed", GetLastErrorStatus());
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
if (!SetSocketBlockingMode(env, clientSocket, false)) {
return JDWPTRANSPORT_ERROR_IO_ERROR;
}
EnterCriticalSendSection(env);
EnterCriticalReadSection(env);
((internalEnv*)env->functions->reserved1)->envClientSocket = clientSocket;
err = CheckHandshaking(env, clientSocket, (long)handshakeTimeout);
LeaveCriticalReadSection(env);
LeaveCriticalSendSection(env);
if (err != JDWPTRANSPORT_ERROR_NONE) {
TCPIPSocketTran_Close(env);
return err;
}
return JDWPTRANSPORT_ERROR_NONE;
} //TCPIPSocketTran_Accept
/**
* This function implements jdwpTransportEnv::IsOpen
*/
static jboolean JNICALL
TCPIPSocketTran_IsOpen(jdwpTransportEnv* env)
{
SOCKET envClientSocket = ((internalEnv*)env->functions->reserved1)->envClientSocket;
if (envClientSocket == INVALID_SOCKET) {
return JNI_FALSE;
}
return JNI_TRUE;
} //TCPIPSocketTran_IsOpen
/**
* This function read packet
*/
static jdwpTransportError
ReadPacket(jdwpTransportEnv* env, SOCKET envClientSocket, jdwpPacket* packet)
{
jdwpTransportError err;
int length;
int readBytes = 0;
err = ReceiveData(env, envClientSocket, (char *)&length, sizeof(jint), 0, &readBytes);
if (err != JDWPTRANSPORT_ERROR_NONE) {
if (readBytes == 0) {
packet->type.cmd.len = 0;
return JDWPTRANSPORT_ERROR_NONE;
}
return err;
}
packet->type.cmd.len = (jint)ntohl(length);
int id;
err = ReceiveData(env, envClientSocket, (char *)&(id), sizeof(jint));
if (err != JDWPTRANSPORT_ERROR_NONE) {
return err;
}
packet->type.cmd.id = (jint)ntohl(id);
err = ReceiveData(env, envClientSocket, (char *)&(packet->type.cmd.flags), sizeof(jbyte));
if (err != JDWPTRANSPORT_ERROR_NONE) {
return err;
}
if (packet->type.cmd.flags & JDWPTRANSPORT_FLAGS_REPLY) {
u_short errorCode;
err = ReceiveData(env, envClientSocket, (char*)&(errorCode), sizeof(jshort));
if (err != JDWPTRANSPORT_ERROR_NONE) {
return err;
}
packet->type.reply.errorCode = (jshort)ntohs(errorCode);
} else {
err = ReceiveData(env, envClientSocket, (char*)&(packet->type.cmd.cmdSet), sizeof(jbyte));
if (err != JDWPTRANSPORT_ERROR_NONE) {
return err;
}
err = ReceiveData(env, envClientSocket, (char*)&(packet->type.cmd.cmd), sizeof(jbyte));
if (err != JDWPTRANSPORT_ERROR_NONE) {
return err;
}
} //if
int dataLength = packet->type.cmd.len - 11;
if (dataLength < 0) {
SetLastTranError(env, "invalid packet length received", 0);
return JDWPTRANSPORT_ERROR_IO_ERROR;
} else if (dataLength == 0) {
packet->type.cmd.data = 0;
} else {
packet->type.cmd.data = (jbyte*)(((internalEnv*)env->functions->reserved1)->alloc)(dataLength);
if (packet->type.cmd.data == 0) {
SetLastTranError(env, "out of memory", 0);
return JDWPTRANSPORT_ERROR_OUT_OF_MEMORY;
}
err = ReceiveData(env, envClientSocket, (char *)packet->type.cmd.data, dataLength);
if (err != JDWPTRANSPORT_ERROR_NONE) {
(((internalEnv*)env->functions->reserved1)->free)(packet->type.cmd.data);
return err;
}
} //if
return JDWPTRANSPORT_ERROR_NONE;
}
/**
* This function implements jdwpTransportEnv::ReadPacket
*/
static jdwpTransportError JNICALL
TCPIPSocketTran_ReadPacket(jdwpTransportEnv* env, jdwpPacket* packet)
{
if (packet == 0) {
SetLastTranError(env, "packet is 0", 0);
return JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT;
}
SOCKET envClientSocket = ((internalEnv*)env->functions->reserved1)->envClientSocket;
if (envClientSocket == INVALID_SOCKET) {
SetLastTranError(env, "there isn't an open connection to a debugger", 0);
LeaveCriticalReadSection(env);
return JDWPTRANSPORT_ERROR_ILLEGAL_STATE ;
}
EnterCriticalReadSection(env);
jdwpTransportError err = ReadPacket(env, envClientSocket, packet);
LeaveCriticalReadSection(env);
return JDWPTRANSPORT_ERROR_NONE;
} //TCPIPSocketTran_ReadPacket
/**
* This function implements jdwpTransportEnv::WritePacket
*/
static jdwpTransportError
WritePacket(jdwpTransportEnv* env, SOCKET envClientSocket, const jdwpPacket* packet)
{
int packetLength = packet->type.cmd.len;
if (packetLength < 11) {
SetLastTranError(env, "invalid packet length", 0);
return JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT;
}
char* data = (char*)packet->type.cmd.data;
if ((packetLength > 11) && (data == 0)) {
SetLastTranError(env, "packet length is greater than 11 but the packet data field is 0", 0);
return JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT;
}
int dataLength = packetLength - 11;
packetLength = htonl(packetLength);
jdwpTransportError err;
err = SendData(env, envClientSocket, (char*)&packetLength, sizeof(jint));
if (err != JDWPTRANSPORT_ERROR_NONE) {
return err;
}
int id = htonl(packet->type.cmd.id);
err = SendData(env, envClientSocket, (char*)&id, sizeof(jint));
if (err != JDWPTRANSPORT_ERROR_NONE) {
return err;
}
err = SendData(env, envClientSocket, (char*)&(packet->type.cmd.flags), sizeof(jbyte));
if (err != JDWPTRANSPORT_ERROR_NONE) {
return err;
}
if (packet->type.cmd.flags & JDWPTRANSPORT_FLAGS_REPLY) {
u_short errorCode = htons(packet->type.reply.errorCode);
err = SendData(env, envClientSocket, (char*)&errorCode, sizeof(jshort));
if (err != JDWPTRANSPORT_ERROR_NONE) {
return err;
}
} else {
err = SendData(env, envClientSocket, (char*)&(packet->type.cmd.cmdSet), sizeof(jbyte));
if (err != JDWPTRANSPORT_ERROR_NONE) {
return err;
}
err = SendData(env, envClientSocket, (char*)&(packet->type.cmd.cmd), sizeof(jbyte));
if (err != JDWPTRANSPORT_ERROR_NONE) {
return err;
}
} //if
if (data != 0) {
err = SendData(env, envClientSocket, data, dataLength);
if (err != JDWPTRANSPORT_ERROR_NONE) {
return err;
}
} //if
return JDWPTRANSPORT_ERROR_NONE;
}
/**
* This function send packet
*/
static jdwpTransportError JNICALL
TCPIPSocketTran_WritePacket(jdwpTransportEnv* env, const jdwpPacket* packet)
{
if (packet == 0) {
SetLastTranError(env, "packet is 0", 0);
return JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT;
}
SOCKET envClientSocket = ((internalEnv*)env->functions->reserved1)->envClientSocket;
if (envClientSocket == INVALID_SOCKET) {
SetLastTranError(env, "there isn't an open connection to a debugger", 0);
LeaveCriticalSendSection(env);
return JDWPTRANSPORT_ERROR_ILLEGAL_STATE;
}
EnterCriticalSendSection(env);
jdwpTransportError err = WritePacket(env, envClientSocket, packet);
LeaveCriticalSendSection(env);
return err;
} //TCPIPSocketTran_WritePacket
/**
* This function implements jdwpTransportEnv::GetLastError
*/
static jdwpTransportError JNICALL
TCPIPSocketTran_GetLastError(jdwpTransportEnv* env, char** message)
{
*message = ((internalEnv*)env->functions->reserved1)->lastError->GetLastErrorMessage();
if (*message == 0) {
return JDWPTRANSPORT_ERROR_MSG_NOT_AVAILABLE;
}
return JDWPTRANSPORT_ERROR_NONE;
} //TCPIPSocketTran_GetLastError
/**
* This function must be called by agent when the library is loaded
*/
extern "C" JNIEXPORT jint JNICALL
jdwpTransport_OnLoad(JavaVM *vm, jdwpTransportCallback* callback,
jint version, jdwpTransportEnv** env)
{
if (version != JDWPTRANSPORT_VERSION_1_0) {
return JNI_EVERSION;
}
internalEnv* iEnv = (internalEnv*)callback->alloc(sizeof(internalEnv));
if (iEnv == 0) {
return JNI_ENOMEM;
}
iEnv->jvm = vm;
iEnv->alloc = callback->alloc;
iEnv->free = callback->free;
iEnv->lastError = 0;
iEnv->envClientSocket = INVALID_SOCKET;
iEnv->envServerSocket = INVALID_SOCKET;
jdwpTransportNativeInterface_* envTNI = (jdwpTransportNativeInterface_*)callback
->alloc(sizeof(jdwpTransportNativeInterface_));
if (envTNI == 0) {
callback->free(iEnv);
return JNI_ENOMEM;
}
envTNI->GetCapabilities = &TCPIPSocketTran_GetCapabilities;
envTNI->Attach = &TCPIPSocketTran_Attach;
envTNI->StartListening = &TCPIPSocketTran_StartListening;
envTNI->StopListening = &TCPIPSocketTran_StopListening;
envTNI->Accept = &TCPIPSocketTran_Accept;
envTNI->IsOpen = &TCPIPSocketTran_IsOpen;
envTNI->Close = &TCPIPSocketTran_Close;
envTNI->ReadPacket = &TCPIPSocketTran_ReadPacket;
envTNI->WritePacket = &TCPIPSocketTran_WritePacket;
envTNI->GetLastError = &TCPIPSocketTran_GetLastError;
envTNI->reserved1 = iEnv;
_jdwpTransportEnv* resEnv = (_jdwpTransportEnv*)callback
->alloc(sizeof(_jdwpTransportEnv));
if (resEnv == 0) {
callback->free(iEnv);
callback->free(envTNI);
return JNI_ENOMEM;
}
resEnv->functions = envTNI;
*env = resEnv;
InitializeCriticalSections(resEnv);
return JNI_OK;
} //jdwpTransport_OnLoad
/**
* This function may be called by agent before the library unloading.
* The function is not defined in JDWP Transport Interface specification.
*/
extern "C" JNIEXPORT void JNICALL
jdwpTransport_UnLoad(jdwpTransportEnv** env)
{
DeleteCriticalSections(*env);
TCPIPSocketTran_Close(*env);
TCPIPSocketTran_StopListening(*env);
void (*unLoadFree)(void *buffer) = ((internalEnv*)(*env)->functions->reserved1)->free;
if (((internalEnv*)(*env)->functions->reserved1)->lastError != 0){
delete (((internalEnv*)(*env)->functions->reserved1)->lastError);
}
unLoadFree((void*)(*env)->functions->reserved1);
unLoadFree((void*)(*env)->functions);
unLoadFree((void*)(*env));
} //jdwpTransport_UnLoad
| 34.496788 | 165 | 0.662663 | qinFamily |
3f344eafb26b0d3e245293a9b07c7db37b9267dc | 3,129 | cc | C++ | cbsasl/scram-sha/stringutils.cc | BenHuddleston/kv_engine | 78123c9aa2c2feb24b7c31eecc862bf2ed6325e4 | [
"MIT",
"BSD-3-Clause"
] | 104 | 2017-05-22T20:41:57.000Z | 2022-03-24T00:18:34.000Z | cbsasl/scram-sha/stringutils.cc | BenHuddleston/kv_engine | 78123c9aa2c2feb24b7c31eecc862bf2ed6325e4 | [
"MIT",
"BSD-3-Clause"
] | 3 | 2017-11-14T08:12:46.000Z | 2022-03-03T11:14:17.000Z | cbsasl/scram-sha/stringutils.cc | BenHuddleston/kv_engine | 78123c9aa2c2feb24b7c31eecc862bf2ed6325e4 | [
"MIT",
"BSD-3-Clause"
] | 71 | 2017-05-22T20:41:59.000Z | 2022-03-29T10:34:32.000Z | /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2016-Present Couchbase, Inc.
*
* Use of this software is governed by the Business Source License included
* in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
* in that file, in accordance with the Business Source License, use of this
* software will be governed by the Apache License, Version 2.0, included in
* the file licenses/APL2.txt.
*/
#include "stringutils.h"
#include <stdexcept>
#include <cctype>
/**
* According to the RFC:
*
* 2.3. Prohibited Output
*
* This profile specifies the following characters as prohibited input:
*
* - Non-ASCII space characters [StringPrep, C.1.2]
* - ASCII control characters [StringPrep, C.2.1]
* - Non-ASCII control characters [StringPrep, C.2.2]
* - Private Use characters [StringPrep, C.3]
* - Non-character code points [StringPrep, C.4]
* - Surrogate code points [StringPrep, C.5]
* - Inappropriate for plain text characters [StringPrep, C.6]
* - Inappropriate for canonical representation characters
* [StringPrep, C.7]
* - Change display properties or deprecated characters
* [StringPrep, C.8]
* - Tagging characters [StringPrep, C.9]
*/
std::string SASLPrep(const std::string& string) {
for (const auto& c : string) {
if (c & 0x80) {
throw std::runtime_error("SASLPrep: Multibyte UTF-8 is not"
" implemented yet");
}
if (iscntrl(c)) {
throw std::runtime_error("SASLPrep: control characters is not"
" allowed");
}
}
return string;
}
std::string encodeUsername(const std::string& username) {
std::string ret(username);
std::string::size_type index = 0;
while ((index = ret.find_first_of(",=", index)) != std::string::npos) {
if (ret[index] == ',') {
ret.replace(index, 1, "=2C");
} else {
ret.replace(index, 1, "=3D");
}
++index;
}
return ret;
}
std::string decodeUsername(const std::string& username) {
std::string ret(username);
auto index = ret.find('=');
if (index == std::string::npos) {
return ret;
}
// we might want to optimize this at one point ;)
do {
if ((index + 3) > ret.length()) {
throw std::runtime_error("decodeUsername: Invalid escape"
" sequence, Should be =2C or =3D");
}
if (ret[index + 1] == '2' && ret[index + 2] == 'C') {
ret.replace(index, 3, ",");
index++;
} else if (ret[index + 1] == '3' && ret[index + 2] == 'D') {
ret.replace(index, 3, "=");
index++;
} else {
throw std::runtime_error("decodeUsername: Invalid escape"
" sequence. Should be =2C or =3D");
}
} while ((index = ret.find('=', index)) != std::string::npos);
return ret;
}
| 32.257732 | 79 | 0.549696 | BenHuddleston |
3f3766e33e293997297c1d6665b34c7b6fc59e5f | 2,581 | cpp | C++ | applications/qTox/src/net/avatarbroadcaster.cpp | gaohangaohan/qkd-net | 90f52104412b5c5c82668362dbd3e4791261f332 | [
"MIT"
] | 17 | 2019-04-21T14:10:57.000Z | 2022-03-26T09:32:53.000Z | applications/qTox/src/net/avatarbroadcaster.cpp | gaohangaohan/qkd-net | 90f52104412b5c5c82668362dbd3e4791261f332 | [
"MIT"
] | 22 | 2019-01-11T19:13:44.000Z | 2022-02-26T17:58:32.000Z | applications/qTox/src/net/avatarbroadcaster.cpp | gaohangaohan/qkd-net | 90f52104412b5c5c82668362dbd3e4791261f332 | [
"MIT"
] | 17 | 2019-03-06T17:29:29.000Z | 2021-08-10T10:17:09.000Z | /*
Copyright © 2015 by The qTox Project Contributors
This file is part of qTox, a Qt-based graphical interface for Tox.
qTox is libre software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
qTox is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with qTox. If not, see <http://www.gnu.org/licenses/>.
*/
#include "avatarbroadcaster.h"
#include "src/core/core.h"
#include <QDebug>
#include <QObject>
/**
* @class AvatarBroadcaster
*
* Takes care of broadcasting avatar changes to our friends in a smart way
* Cache a copy of our current avatar and friends who have received it
* so we don't spam avatar transfers to a friend who already has it.
*/
QByteArray AvatarBroadcaster::avatarData;
QMap<uint32_t, bool> AvatarBroadcaster::friendsSentTo;
static QMetaObject::Connection autoBroadcastConn;
static auto autoBroadcast = [](uint32_t friendId, Status) {
AvatarBroadcaster::sendAvatarTo(friendId);
};
/**
* @brief Set our current avatar.
* @param data Byte array on avater.
*/
void AvatarBroadcaster::setAvatar(QByteArray data)
{
if (avatarData == data)
return;
avatarData = data;
friendsSentTo.clear();
QVector<uint32_t> friends = Core::getInstance()->getFriendList();
for (uint32_t friendId : friends)
sendAvatarTo(friendId);
}
/**
* @brief Send our current avatar to this friend, if not already sent
* @param friendId Id of friend to send avatar.
*/
void AvatarBroadcaster::sendAvatarTo(uint32_t friendId)
{
if (friendsSentTo.contains(friendId) && friendsSentTo[friendId])
return;
if (!Core::getInstance()->isFriendOnline(friendId))
return;
Core::getInstance()->sendAvatarFile(friendId, avatarData);
friendsSentTo[friendId] = true;
}
/**
* @brief Setup auto broadcast sending avatar.
* @param state If true, we automatically broadcast our avatar to friends when they come online.
*/
void AvatarBroadcaster::enableAutoBroadcast(bool state)
{
QObject::disconnect(autoBroadcastConn);
if (state)
autoBroadcastConn =
QObject::connect(Core::getInstance(), &Core::friendStatusChanged, autoBroadcast);
}
| 30.72619 | 96 | 0.722976 | gaohangaohan |
3f39ec123b86ba4e78ebaa7c0798838102ce3650 | 2,995 | cpp | C++ | miscellaneous/test_hdf5/exam_test.cpp | gwpark-git/dynamics_of_networks_and_colloids | 0b0a3687533379ec75171ae6b906aeff5bedfbba | [
"MIT"
] | null | null | null | miscellaneous/test_hdf5/exam_test.cpp | gwpark-git/dynamics_of_networks_and_colloids | 0b0a3687533379ec75171ae6b906aeff5bedfbba | [
"MIT"
] | null | null | null | miscellaneous/test_hdf5/exam_test.cpp | gwpark-git/dynamics_of_networks_and_colloids | 0b0a3687533379ec75171ae6b906aeff5bedfbba | [
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include "H5Cpp.h"
const H5std_string FILE_NAME("test_cpp.h5"); // file name setting
const H5std_string DATASET_NAME("IntArray"); // example dataset
const int RANK = 2; // rank for data set. It means, the data set is 2-dimensional array
const int NX = 5; // Nrows
const int NY = 6; // Ncols
int main(void)
{
int i, j;
int data[NX][NY];
for (j=0; j<NX; j++) // initialize the data array
{
for(i=0; i<NX; i++)
data[j][i] = i + j;
}
try
{
H5::Exception::dontPrint(); // turn of auto-printing in the case of error
H5::H5File file(FILE_NAME, H5F_ACC_TRUNC); // open file.
// check the properties for H5F_ACC_TRUNC
hsize_t dimsf[2]; // dataset dimensions
dimsf[0] = NX;
dimsf[1] = NY;
H5::DataSpace dataspace(RANK, dimsf); // generate dataspace
H5::IntType datatype(H5::PredType::NATIVE_INT); // set datatype as Integer type
datatype.setOrder(H5T_ORDER_LE);
H5::DataSet dataset = file.createDataSet(DATASET_NAME, datatype, dataspace); // create dataset
dataset.write(data, H5::PredType::NATIVE_INT); // write
}
catch(H5::FileIException error) // catch failure caused by the H5File operation
{
error.printError();
return -1;
}
catch(H5::DataSetIException error) // catch failure caused by the DataSet operations
{
error.printError();
return -1;
}
catch(H5::DataSpaceIException error) // catch failure caused by the DataSpace operations
{
error.printError();
return -1;
}
catch(H5::DataTypeIException error) // catch failure caused by the DataType operations
{
error.printError();
return -1;
}
return 0;
}
/*
* Local variables:
* compile-command: "icpc -o exam_test exam_test.cpp -I/usr/include -I/usr/local/opt/szip/include -L/usr/local/Cellar/hdf5/1.8.16_1/lib /usr/local/Cellar/hdf5/1.8.16_1/lib/libhdf5_hl_cpp.a /usr/local/Cellar/hdf5/1.8.16_1/lib/libhdf5_cpp.a /usr/local/Cellar/hdf5/1.8.16_1/lib/libhdf5_hl.a /usr/local/Cellar/hdf5/1.8.16_1/lib/libhdf5.a -L/usr/lib -L/usr/local/opt/szip/lib -lsz -lz -ldl -lm"
* End:
*/
| 45.378788 | 389 | 0.475459 | gwpark-git |
27842da87a9d0ee310e13c10f7f23608a9c9d703 | 965 | cpp | C++ | test/mp/remove.cpp | Cleyera/gdv | c89dd24898a58c4f905a4d53b6c2b262f2689b09 | [
"MIT"
] | null | null | null | test/mp/remove.cpp | Cleyera/gdv | c89dd24898a58c4f905a4d53b6c2b262f2689b09 | [
"MIT"
] | null | null | null | test/mp/remove.cpp | Cleyera/gdv | c89dd24898a58c4f905a4d53b6c2b262f2689b09 | [
"MIT"
] | null | null | null | #include <tuple>
#include <gdv/mp/test/test.h>
template <typename ...Args>
struct packer;
GDV_MP_TEST_CASE(remove) {
using l1 = ::std::tuple<int, char, short>;
using l2 = ::std::tuple<char, short, unsigned>;
using l3 = ::std::tuple<int, int, int>;
using l4 = ::std::tuple<>;
using l5 = packer<int, char, short>;
using l6 = packer<char, short, unsigned>;
using l7 = packer<int, int, int>;
using l8 = packer<>;
GDV_MP_TEST_IS_SAME(remove_t<l1, int>, ::std::tuple<char, short>);
GDV_MP_TEST_IS_SAME(remove_t<l2, int>, ::std::tuple<char, short, unsigned>);
GDV_MP_TEST_IS_SAME(remove_t<l3, int>, ::std::tuple<>);
GDV_MP_TEST_IS_SAME(remove_t<l4, int>, ::std::tuple<>);
GDV_MP_TEST_IS_SAME(remove_t<l5, int>, packer<char, short>);
GDV_MP_TEST_IS_SAME(remove_t<l6, int>, packer<char, short, unsigned>);
GDV_MP_TEST_IS_SAME(remove_t<l7, int>, packer<>);
GDV_MP_TEST_IS_SAME(remove_t<l8, int>, packer<>);
}
| 38.6 | 80 | 0.662176 | Cleyera |
27850beb565534dda356ebf90a52d9289bfe016a | 2,186 | cpp | C++ | src/hud/minimap.cpp | WilliamLewww/Mustard | c9fc1ea7780e51e78e3362670a08b1764843ed7e | [
"MIT"
] | null | null | null | src/hud/minimap.cpp | WilliamLewww/Mustard | c9fc1ea7780e51e78e3362670a08b1764843ed7e | [
"MIT"
] | 4 | 2018-01-03T04:51:24.000Z | 2018-09-05T03:02:35.000Z | src/hud/minimap.cpp | WilliamLewww/Mustard | c9fc1ea7780e51e78e3362670a08b1764843ed7e | [
"MIT"
] | null | null | null | #include "minimap.h"
Minimap::Minimap(Vector2 pos, double w, double h) {
position = pos;
width = w;
height = h;
}
void Minimap::initialize(std::vector<std::vector<Vector2>> rList, Vector2 bInitialPosition) {
trianglePosition = position + Vector2((width / 8) - 2.5, (height / 2) - 2);
boardInitialPosition = bInitialPosition;
boardInitialPosition.shrink(scaleFactor, scaleFactor);
railList = rList;
Vector2 firstPoint = Vector2(railList[0][0].x / scaleFactor, railList[0][0].y / scaleFactor);
for (Vector2 &rail : railList[0]) {
rail.shrink(scaleFactor, scaleFactor);
rail = rail - firstPoint;
rail += position - Vector2(2.5, 2) + Vector2(width / 8, height / 2);
}
for (Vector2 &rail : railList[1]) {
rail.shrink(scaleFactor, scaleFactor);
rail = rail - firstPoint;
rail += position - Vector2(2.5, 2) + Vector2(width / 8, height / 2);
}
}
void Minimap::setVisibleRange() {
for (int x = visibleRange.x; x < railList[0].size(); x++) {
if (railList[0][x].x < position.x + (boardPosition.x - boardInitialPosition.x)) { visibleRange.x += 1; }
if (railList[0][x].x < (position.x + width) + (boardPosition.x - boardInitialPosition.x)) { visibleRange.y = x; }
else { break; }
}
}
std::vector<Vector2> Minimap::getVisibleRail(int index) {
if (visibleRange.x == 0) {
return std::vector<Vector2>(railList[index].begin() + visibleRange.x + 1, railList[index].begin() + visibleRange.y);
}
return std::vector<Vector2>(railList[index].begin() + visibleRange.x, railList[index].begin() + visibleRange.y);
}
void Minimap::resetVisibleRange() {
visibleRange = Vector2(0,0);
}
void Minimap::draw() {
setVisibleRange();
drawing.drawRect(position, width, height, color);
drawing.drawTriangle(trianglePosition, 5, 4, boardAngle);
glPushMatrix();
glTranslatef(-boardPosition.x + boardInitialPosition.x, -boardPosition.y + boardInitialPosition.y, 0);
drawing.drawLineStrip(getVisibleRail(0), railColor, alpha);
drawing.drawLineStrip(getVisibleRail(1), railColor, alpha);
glPopMatrix();
}
void Minimap::update(Vector2 bPosition, double bAngle) {
boardPosition = bPosition;
boardPosition.shrink(scaleFactor, scaleFactor);
boardAngle = bAngle;
} | 33.121212 | 118 | 0.701281 | WilliamLewww |
278573c2e6ee1948ab31f782586df86a67229ec6 | 529 | cpp | C++ | MyFiles/ HLPSUG.cpp | manishSRM/solvedProblems | 78492e51488605e46fd19bba472736825a2faf32 | [
"Apache-2.0"
] | null | null | null | MyFiles/ HLPSUG.cpp | manishSRM/solvedProblems | 78492e51488605e46fd19bba472736825a2faf32 | [
"Apache-2.0"
] | null | null | null | MyFiles/ HLPSUG.cpp | manishSRM/solvedProblems | 78492e51488605e46fd19bba472736825a2faf32 | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
#include <algorithm>
#include <limits.h>
#include <vector>
using namespace std;
const K = 25;
int main () {
int T;
scanf ("%d", &T);
while (T--) {
int N;
scanf ("%d", &N);
vector <bool> prime (N + 1, true);
for(int i = 2; i <= MAX / i; i++) {
for(int j = i * i; j <= MAX; j += i) {
prime[j] = false;
}
}
int maxSum = 0;
for (int k = 29; k <= N; k++) {
if (prime[k] == true)
maxSum += k;
}
printf("%d\n", maxSum);
}
return 0;
} | 17.633333 | 47 | 0.451796 | manishSRM |
2787b9db157213a4953936b15695e99f362ffe03 | 3,303 | cpp | C++ | src/other/ext/openscenegraph/src/osgUtil/PositionalStateContainer.cpp | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 1 | 2019-10-23T16:17:49.000Z | 2019-10-23T16:17:49.000Z | src/other/openscenegraph/src/osgUtil/PositionalStateContainer.cpp | pombredanne/sf.net-brlcad | fb56f37c201b51241e8f3aa7b979436856f43b8c | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/other/openscenegraph/src/osgUtil/PositionalStateContainer.cpp | pombredanne/sf.net-brlcad | fb56f37c201b51241e8f3aa7b979436856f43b8c | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 1 | 2018-12-21T21:09:47.000Z | 2018-12-21T21:09:47.000Z | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library 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
* OpenSceneGraph Public License for more details.
*/
#include <osgUtil/PositionalStateContainer>
using namespace osg;
using namespace osgUtil;
// register a PositionalStateContainer prototype with the RenderBin prototype list.
//RegisterRenderBinProxy<PositionalStateContainer> s_registerPositionalStateContainerProxy;
PositionalStateContainer::PositionalStateContainer()
{
}
PositionalStateContainer::~PositionalStateContainer()
{
}
void PositionalStateContainer::reset()
{
_attrList.clear();
_texAttrListMap.clear();
}
void PositionalStateContainer::draw(osg::State& state,RenderLeaf*& previous, const osg::Matrix* postMultMatrix)
{
if (previous)
{
StateGraph::moveToRootStateGraph(state,previous->_parent);
state.apply();
previous = NULL;
}
// apply the light list.
for(AttrMatrixList::iterator litr=_attrList.begin();
litr!=_attrList.end();
++litr)
{
if (postMultMatrix)
{
if ((*litr).second.valid())
state.applyModelViewMatrix(new osg::RefMatrix( (*((*litr).second)) * (*postMultMatrix)));
else
state.applyModelViewMatrix(new osg::RefMatrix( *postMultMatrix));
}
else
{
state.applyModelViewMatrix((*litr).second.get());
}
// apply the light source.
litr->first->apply(state);
// tell state about.
state.haveAppliedAttribute(litr->first.get());
// set this state as a global default
state.setGlobalDefaultAttribute(litr->first.get());
}
for(TexUnitAttrMatrixListMap::iterator titr=_texAttrListMap.begin();
titr!=_texAttrListMap.end();
++titr)
{
state.setActiveTextureUnit(titr->first);
AttrMatrixList attrList = titr->second;
for(AttrMatrixList::iterator litr=attrList.begin();
litr!=attrList.end();
++litr)
{
if (postMultMatrix)
{
if ((*litr).second.valid())
state.applyModelViewMatrix(new osg::RefMatrix( (*((*litr).second)) * (*postMultMatrix)));
else
state.applyModelViewMatrix(new osg::RefMatrix( *postMultMatrix));
}
else
{
state.applyModelViewMatrix((*litr).second.get());
}
// apply the light source.
litr->first->apply(state);
// tell state about.
state.haveAppliedTextureAttribute(titr->first, litr->first.get());
// set this state as a global default
state.setGlobalDefaultTextureAttribute(titr->first, litr->first.get());
}
}
}
| 30.302752 | 111 | 0.629428 | lf- |
278a0a3d9c9bf3ab89677a7f9eb05faf5b61f1a4 | 3,266 | hpp | C++ | include/ecst/signature_list/system/bf_traversal.hpp | SuperV1234/ecst | b3c42e2c28978f1cd8ea620ade62613c6c875432 | [
"AFL-3.0"
] | 475 | 2016-05-03T13:34:30.000Z | 2021-11-26T07:02:47.000Z | include/ecst/signature_list/system/bf_traversal.hpp | vittorioromeo/ecst | b3c42e2c28978f1cd8ea620ade62613c6c875432 | [
"AFL-3.0"
] | 28 | 2016-08-30T06:37:40.000Z | 2017-11-24T11:14:07.000Z | include/ecst/signature_list/system/bf_traversal.hpp | vittorioromeo/ecst | b3c42e2c28978f1cd8ea620ade62613c6c875432 | [
"AFL-3.0"
] | 60 | 2016-05-11T22:16:15.000Z | 2021-08-02T20:42:35.000Z | // Copyright (c) 2015-2016 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: http://opensource.org/licenses/AFL-3.0
// http://vittorioromeo.info | vittorio.romeo@outlook.com
#pragma once
#include <ecst/config.hpp>
#include <ecst/aliases.hpp>
#include <ecst/mp/list.hpp>
ECST_SIGNATURE_LIST_SYSTEM_NAMESPACE
{
namespace bf_traversal
{
using namespace mp;
template <typename TStartNodeList>
constexpr auto make(TStartNodeList&& snl) noexcept
{
return bh::make_pair(FWD(snl), list::empty_v);
}
template <typename TBFTContext>
constexpr auto queue(TBFTContext&& c) noexcept
{
return bh::first(FWD(c));
}
template <typename TBFTContext>
constexpr auto visited(TBFTContext&& c) noexcept
{
return bh::second(FWD(c));
}
template <typename TBFTContext, typename TNode>
constexpr auto is_visited(TBFTContext&& c, TNode&& n) noexcept
{
return bh::contains(visited(FWD(c)), FWD(n));
}
template <typename TBFTContext, typename TNode>
constexpr auto is_in_queue(TBFTContext&& c, TNode&& n) noexcept
{
return bh::contains(queue(FWD(c)), FWD(n));
}
template <typename TBFTContext>
constexpr auto is_queue_empty(TBFTContext&& c) noexcept
{
return bh::is_empty(queue(FWD(c)));
}
template <typename TBFTContext>
constexpr auto top_node(TBFTContext&& c) noexcept
{
return bh::front(queue(FWD(c)));
}
template <typename TBFTContext, typename TSSL>
auto step_forward(TBFTContext&& c, TSSL ssl) noexcept
{
auto node = top_node(c);
auto popped_queue = bh::remove_at(queue(c), mp::sz_v<0>);
auto neighbors =
dependent_ids_list(ssl, signature_by_id(ssl, node));
auto unvisited_neighbors = bh::remove_if(neighbors, [=](auto x_nbr)
{
return is_visited(c, x_nbr);
});
auto new_visited = bh::concat(visited(c), unvisited_neighbors);
auto new_queue = bh::concat(popped_queue, unvisited_neighbors);
return bh::make_pair(new_queue, new_visited);
}
template <typename TStartNodeList, typename TSSL>
auto execute(TStartNodeList&& snl, TSSL ssl) noexcept
{
using namespace mp;
namespace btfc = bf_traversal;
auto step = [=](auto self, auto&& ctx)
{
return static_if(btfc::is_queue_empty(ctx))
.then([=](auto)
{
return list::empty_v;
})
.else_([=](auto&& x_ctx)
{
return bh::append(
self(btfc::step_forward(FWD(x_ctx), ssl)),
btfc::top_node(FWD(x_ctx)));
})(FWD(ctx));
};
return bh::fix(step)(btfc::make(FWD(snl)));
}
}
}
ECST_SIGNATURE_LIST_SYSTEM_NAMESPACE_END
| 31.104762 | 79 | 0.541335 | SuperV1234 |
27907eefca50530af5307051e28e616bf24d857f | 8,867 | cpp | C++ | binding-cpp/runtime/src/test/serialization/EtchValidatorObjectTest.cpp | apache/etch | 5a875755019a7f342a07c8c368a50e3efb6ae68c | [
"ECL-2.0",
"Apache-2.0"
] | 9 | 2015-02-14T15:09:54.000Z | 2021-11-10T15:09:45.000Z | binding-cpp/runtime/src/test/serialization/EtchValidatorObjectTest.cpp | apache/etch | 5a875755019a7f342a07c8c368a50e3efb6ae68c | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | binding-cpp/runtime/src/test/serialization/EtchValidatorObjectTest.cpp | apache/etch | 5a875755019a7f342a07c8c368a50e3efb6ae68c | [
"ECL-2.0",
"Apache-2.0"
] | 14 | 2015-04-20T10:35:00.000Z | 2021-11-10T15:09:35.000Z |
/* $Id$
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include "serialization/EtchValidatorObject.h"
#include "capu/util/SmartPointer.h"
#include "common/EtchInt32.h"
#include "common/EtchBool.h"
#include "common/EtchLong.h"
#include "common/EtchShort.h"
#include "common/EtchByte.h"
#include "common/EtchString.h"
#include "serialization/EtchTypeCodes.h"
#include "capu/os/NumericLimits.h"
#include "support/EtchRuntime.h"
class EtchValidatorObjectTest
: public ::testing::Test {
protected:
virtual void SetUp() {
mRuntime = new EtchRuntime();
mRuntime->start();
}
virtual void TearDown() {
mRuntime->shutdown();
delete mRuntime;
mRuntime = NULL;
}
EtchRuntime* mRuntime;
};
TEST_F(EtchValidatorObjectTest, createTest) {
capu::SmartPointer<EtchValidatorObject> ptr = NULL;
capu::SmartPointer<EtchValidator> val;
EXPECT_TRUE(EtchValidatorObject::Get(mRuntime, 0, val) == ETCH_OK);
ptr = capu::smartpointer_cast<EtchValidatorObject>(val);
EXPECT_TRUE(ptr->getNDims() == 0);
EXPECT_TRUE(EtchValidatorObject::Get(mRuntime, 2, val) == ETCH_OK);
ptr = capu::smartpointer_cast<EtchValidatorObject>(val);
EXPECT_TRUE(ptr->getNDims() == 2);
}
TEST_F(EtchValidatorObjectTest, validateTest) {
capu::SmartPointer<EtchObject> boolean = NULL;
capu::SmartPointer<EtchObject> integer = new EtchInt32(4);
capu::SmartPointer<EtchObject> boolean2 = new EtchBool(false);
capu::SmartPointer<EtchValidator> ptr = NULL;
EXPECT_TRUE(EtchValidatorObject::Get(mRuntime, 0, ptr) == ETCH_OK);
EXPECT_TRUE((capu::smartpointer_cast<EtchTypeValidator>(ptr))->getNDims() == 0);
EXPECT_FALSE(ptr->validate(boolean));
EXPECT_TRUE(ptr->validate(integer));
EXPECT_TRUE(ptr->validate(boolean2));
}
TEST_F(EtchValidatorObjectTest, validateValueTest) {
capu::SmartPointer<EtchObject> byte = NULL;
capu::SmartPointer<EtchObject> result = NULL;
capu::SmartPointer<EtchObject> integer = new EtchInt32(capu::NumericLimits::Min<capu::int16_t > ());
capu::SmartPointer<EtchObject> integer2 = new EtchInt32(0);
capu::SmartPointer<EtchObject> integer3 = new EtchInt32(capu::NumericLimits::Max<capu::int16_t > ());
capu::SmartPointer<EtchObject> integer4 = new EtchInt32(897);
//exceed limits of integer
capu::SmartPointer<EtchObject> integer5 = new EtchInt32(capu::NumericLimits::Max<capu::int16_t > () + 2);
capu::SmartPointer<EtchObject> longInteger = new EtchLong(capu::NumericLimits::Min<capu::int16_t > ());
capu::SmartPointer<EtchObject> longInteger2 = new EtchLong(0);
capu::SmartPointer<EtchObject> longInteger3 = new EtchLong(capu::NumericLimits::Max<capu::int16_t > ());
capu::SmartPointer<EtchObject> longInteger4 = new EtchLong(897);
//exceed limits of integer
capu::SmartPointer<EtchObject> longInteger5 = new EtchLong((capu::int64_t)capu::NumericLimits::Max<capu::int16_t > () + (capu::int64_t)2);
capu::SmartPointer<EtchObject> shortInteger = new EtchShort(capu::NumericLimits::Min<capu::int16_t > ());
capu::SmartPointer<EtchObject> shortInteger2 = new EtchShort(0);
capu::SmartPointer<EtchObject> shortInteger3 = new EtchShort(capu::NumericLimits::Max<capu::int16_t > ());
capu::SmartPointer<EtchObject> shortInteger4 = new EtchShort();
//incompatible type
capu::SmartPointer<EtchObject> str = new EtchString();
capu::SmartPointer<EtchObject> byte1 = new EtchByte(capu::NumericLimits::Max<capu::int8_t > ());
capu::SmartPointer<EtchObject> byte2 = new EtchByte(0);
capu::SmartPointer<EtchObject> byte3 = new EtchByte(capu::NumericLimits::Min<capu::int8_t > ());
capu::SmartPointer<EtchObject> byte4 = new EtchByte(32);
capu::SmartPointer<EtchValidator> ptr = NULL;
EXPECT_TRUE(EtchValidatorObject::Get(mRuntime, 0, ptr) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(byte, result) == ETCH_ERROR);
EXPECT_TRUE(ptr->validateValue(str, result) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(longInteger5, result) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(integer5, result) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(integer, result) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(integer2, result) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(integer3, result) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(longInteger, result) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(longInteger2, result) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(longInteger3, result) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(shortInteger, result) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(shortInteger2, result) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(shortInteger3, result) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(byte1, result) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(byte2, result) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(byte3, result) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(byte4, result) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(integer4, result) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(longInteger4, result) == ETCH_OK);
EXPECT_TRUE(ptr->validateValue(shortInteger4, result) == ETCH_OK);
}
TEST_F(EtchValidatorObjectTest, elementValidatorTest) {
capu::SmartPointer<EtchValidator> ptr = NULL;
EXPECT_TRUE(EtchValidatorObject::Get(mRuntime, 1, ptr) == ETCH_OK);
capu::SmartPointer<EtchValidator> elementValidator;
ptr->getElementValidator(elementValidator);
capu::SmartPointer<EtchObject> integer = new EtchInt32(capu::NumericLimits::Min<capu::int16_t > ());
capu::SmartPointer<EtchObject> integer2 = new EtchInt32(0);
capu::SmartPointer<EtchObject> integer3 = new EtchInt32(capu::NumericLimits::Max<capu::int16_t > ());
capu::SmartPointer<EtchObject> integer4 = new EtchInt32(897);
//exceed limits of integer
capu::SmartPointer<EtchObject> integer5 = new EtchInt32(capu::NumericLimits::Max<capu::int16_t > () + 2);
capu::SmartPointer<EtchObject> longInteger = new EtchLong(capu::NumericLimits::Min<capu::int16_t > ());
capu::SmartPointer<EtchObject> longInteger2 = new EtchLong(0);
capu::SmartPointer<EtchObject> longInteger3 = new EtchLong(capu::NumericLimits::Max<capu::int16_t > ());
capu::SmartPointer<EtchObject> longInteger4 = new EtchLong(897);
//exceed limits of integer
capu::SmartPointer<EtchObject> longInteger5 = new EtchLong((capu::int64_t)capu::NumericLimits::Max<capu::int16_t > () + (capu::int64_t)2);
capu::SmartPointer<EtchObject> shortInteger = new EtchShort(capu::NumericLimits::Min<capu::int16_t > ());
capu::SmartPointer<EtchObject> shortInteger2 = new EtchShort(0);
capu::SmartPointer<EtchObject> shortInteger3 = new EtchShort(capu::NumericLimits::Max<capu::int16_t > ());
capu::SmartPointer<EtchObject> shortInteger4 = new EtchShort();
//incompatible type
capu::SmartPointer<EtchObject> str = new EtchString();
capu::SmartPointer<EtchObject> byte1 = new EtchByte(capu::NumericLimits::Max<capu::int8_t > ());
capu::SmartPointer<EtchObject> byte2 = new EtchByte(0);
capu::SmartPointer<EtchObject> byte3 = new EtchByte(capu::NumericLimits::Min<capu::int8_t > ());
capu::SmartPointer<EtchObject> byte4 = new EtchByte(32);
EXPECT_TRUE(elementValidator->validate(str));
EXPECT_TRUE(elementValidator->validate(longInteger5));
EXPECT_TRUE(elementValidator->validate(integer5));
EXPECT_TRUE(elementValidator->validate(integer));
EXPECT_TRUE(elementValidator->validate(integer2));
EXPECT_TRUE(elementValidator->validate(integer3));
EXPECT_TRUE(elementValidator->validate(longInteger));
EXPECT_TRUE(elementValidator->validate(longInteger2));
EXPECT_TRUE(elementValidator->validate(longInteger3));
EXPECT_TRUE(elementValidator->validate(shortInteger));
EXPECT_TRUE(elementValidator->validate(shortInteger2));
EXPECT_TRUE(elementValidator->validate(shortInteger3));
EXPECT_TRUE(elementValidator->validate(byte1));
EXPECT_TRUE(elementValidator->validate(byte2));
EXPECT_TRUE(elementValidator->validate(byte3));
EXPECT_TRUE(elementValidator->validate(byte4));
EXPECT_TRUE(elementValidator->validate(integer4));
EXPECT_TRUE(elementValidator->validate(longInteger4));
EXPECT_TRUE(elementValidator->validate(shortInteger4));
}
| 48.190217 | 140 | 0.754032 | apache |
2790b02970561906ce1fc2c115f11842d482fd0c | 1,313 | hpp | C++ | include/pch.hpp | KaixoCode/SoundMixr | 6f27c14f596c45debb584925db4e1f45808031a9 | [
"MIT"
] | 18 | 2021-01-24T14:28:15.000Z | 2021-12-02T20:19:09.000Z | include/pch.hpp | KaixoCode/SoundMixr | 6f27c14f596c45debb584925db4e1f45808031a9 | [
"MIT"
] | 1 | 2021-06-21T18:39:56.000Z | 2021-06-22T16:09:18.000Z | include/pch.hpp | KaixoCode/SoundMixr | 6f27c14f596c45debb584925db4e1f45808031a9 | [
"MIT"
] | null | null | null | #include <iostream>
#include <any>
#include <ranges>
#include "GuiCode2/pch.hpp"
#include "GuiCode2/Panel.hpp"
#include "GuiCode2/Menu.hpp"
#include "GuiCode2/Event.hpp"
#include "GuiCode2/Frame.hpp"
#include "GuiCode2/ContextMenu.hpp"
#include "GuiCode2/TextBox.hpp"
#include "GuiCode2/TextArea.hpp"
#define JSON_TRY_USER if(true)
#define JSON_CATCH_USER(exception) if(false)
#define JSON_THROW_USER(exception) \
{std::clog << "Error in " << __FILE__ << ":" << __LINE__ \
<< " (function " << __FUNCTION__ << ") - " \
<< (exception).what() << std::endl; \
throw exception; }
#include <nlohmann/json.hpp>
#include "Audijo/Audijo.hpp"
using namespace Audijo;
#include "RtMidi.h"
namespace AudioFile
{
#include <AudioFile.h>
}
#define _TESTLINK
#include "Base.hpp"
#include "Filters.hpp"
#include "Compressor.hpp"
#include "Oscillator.hpp"
#include "resource.h"
#define db2lin(db) std::powf(10.0f, 0.05 * (db))
#define lin2db(lin) (20.0f * std::log10(std::max((double)(lin), 0.000000000001)))
#define myabs(f) if (f < 0) f = -f;
#define VERSION 13
using namespace GuiCode;
#include "CrashLogger.hpp"
#define CrashLog(x) \
std::cout << x << std::endl, \
CrashLogger::crashlog << CrashLogger::CrashLogPrefix() << x << std::endl | 24.314815 | 81 | 0.657273 | KaixoCode |
2790f2ae01a2407222aa9fc9a81518fb63ab3fa5 | 8,396 | cpp | C++ | Source/ModuleParticles.cpp | IconicGIT/NextStage | a6740b64ac40c5f99e6620f98f423da38cb73d7e | [
"MIT"
] | 3 | 2021-02-22T09:04:25.000Z | 2021-02-22T16:56:36.000Z | Source/ModuleParticles.cpp | IconicGIT/NextStage | a6740b64ac40c5f99e6620f98f423da38cb73d7e | [
"MIT"
] | null | null | null | Source/ModuleParticles.cpp | IconicGIT/NextStage | a6740b64ac40c5f99e6620f98f423da38cb73d7e | [
"MIT"
] | 5 | 2021-02-22T08:50:22.000Z | 2021-10-02T11:02:55.000Z | #include "ModuleParticles.h"
#include "Application.h"
#include "ModuleTextures.h"
#include "ModuleRender.h"
#include "ModuleCollisions.h"
#include "Collider.h"
#include "Globals.h"
#include "SDL/include/SDL_timer.h"
ModuleParticles::ModuleParticles(bool startEnabled) : Module(startEnabled)
{
for(uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i)
particles[i] = nullptr;
}
ModuleParticles::~ModuleParticles()
{
}
bool ModuleParticles::Start()
{
LOG("Loading particles");
texture = App->textures->Load("Assets/Sprites/items_and_particles.png");
// Explosion particle
explosion.anim.PushBack({274, 296, 33, 30});
explosion.anim.PushBack({313, 296, 33, 30});
explosion.anim.PushBack({346, 296, 33, 30});
explosion.anim.PushBack({382, 296, 33, 30});
explosion.anim.PushBack({419, 296, 33, 30});
explosion.anim.PushBack({457, 296, 33, 30});
explosion.anim.loop = false;
explosion.anim.speed = 0.3f;
laser.anim.PushBack({ 232, 103, 16, 12 });
laser.anim.PushBack({ 249, 103, 16, 12 });
laser.speed.x = 5;
laser.lifetime = 180;
laser.anim.speed = 0.2f;
playerBullet1[0].anim.PushBack({ 6, 175, 3, 8 });
playerBullet1[1].anim.PushBack({ 17, 199, 6, 6 });
playerBullet1[2].anim.PushBack({ 5, 200, 8, 3 });
playerBullet1[3].anim.PushBack({ 25, 187, 6, 6 });
playerBullet1[4].anim.PushBack({ 16, 187, 3, 8 });
playerBullet1[5].anim.PushBack({ 7, 187, 6, 6 });
playerBullet1[6].anim.PushBack({ 26, 176, 8, 3 });
playerBullet1[7].anim.PushBack({ 16, 175, 6, 6 });
for (int i = 0; i < 8; i++)
{
playerBullet1[i].speed.x = 6;
playerBullet1[i].speed.y = 6;
playerBullet1[i].lifetime = 20;
playerBullet1[i].anim.speed = 0;
playerBullet1[i].anim.loop = false;
}
dust_particle.anim.PushBack({ 270,232,32,32 });
dust_particle.anim.PushBack({ 302,232,32,32 });
dust_particle.anim.PushBack({ 334,232,32,32 });
dust_particle.anim.PushBack({ 366,232,32,32 });
dust_particle.anim.PushBack({ 270,264,32,32 });
dust_particle.anim.PushBack({ 302,264,32,32 });
dust_particle.anim.loop = false;
dust_particle.anim.speed = 0.2f;
EnemyBullet.anim.PushBack({ 232, 103, 16, 12 });
EnemyBullet.anim.PushBack({ 249, 103, 16, 12 });
EnemyBullet.speed.x = 5;
EnemyBullet.speed.y = 5;
EnemyBullet.lifetime = 180;
EnemyBullet.anim.speed = 0.2f;
Boss1BulletR.anim.PushBack({ 126,275,1,10 });
Boss1BulletR.lifetime = 24;
Boss1BulletR.anim.speed = 1;
Boss1BulletR.anim.loop = false;
Boss1BulletR.speed.y = 5;
Boss1BulletR.speed.x = -1;
Boss1BulletL.anim.PushBack({ 126,275,1,10 });
Boss1BulletL.lifetime = 24;
Boss1BulletL.anim.speed = 1;
Boss1BulletL.anim.loop = false;
Boss1BulletL.speed.y = 5;
Boss1BulletL.speed.x = 1;
Explosion1.anim.PushBack({ 103,0,32,33 });
Explosion1.anim.PushBack({ 135,0,32,33 });
Explosion1.anim.PushBack({ 167,0,32,33 });
Explosion1.anim.PushBack({ 199,0,32,33 });
Explosion1.anim.loop = false;
Explosion1.anim.speed = 0.2f;
Explosion2Small.anim.PushBack({ 197,149,32,28 });
Explosion2Small.anim.PushBack({ 197,247,32,28 });
Explosion2Small.anim.PushBack({ 197,302,32,28 });
Explosion2Small.anim.PushBack({ 197,356,32,28 });
Explosion2Small.anim.loop = false;
Explosion2Small.anim.speed = 0.2f;
Explosion2Big.anim.PushBack({ 189,184,48,41 });
Explosion2Big.anim.PushBack({ 239,184,48,41 });
Explosion2Big.anim.PushBack({ 294,184,48,41 });
Explosion2Big.anim.PushBack({ 350,184,48,41 });
Explosion2Big.anim.loop = false;
Explosion2Big.anim.speed = 0.2f;
BulletEnd.anim.PushBack({ 24,274,12,12 });
BulletEnd.anim.PushBack({ 35,274,12,12 });
BulletEnd.anim.PushBack({ 48,274,12,12 });
BulletEnd.anim.loop = false;
BulletEnd.anim.speed = 0.4f;
SoldierBullet.anim.PushBack({ 0,274,12,12 });
SoldierBullet.anim.PushBack({ 12,274,12,12 });
SoldierBullet.anim.loop = true;
SoldierBullet.lifetime = 90;
SoldierBullet.anim.speed = 0.1f;
SoldierBullet.speed = { 2,2 };
return true;
}
bool ModuleParticles::CleanUp()
{
LOG("Unloading particles");
// Delete all remaining active particles on application exit
for(uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i)
{
if(particles[i] != nullptr)
{
delete particles[i];
particles[i] = nullptr;
}
}
return true;
}
void ModuleParticles::OnCollision(Collider* c1, Collider* c2)
{
int max = MAX_ACTIVE_PARTICLES;
bool loopDone = false;
for (uint i = deleteParticleIndex; i < max; ++i)
{
bool deleted = false;
if (particles[i] != nullptr && particles[i]->collider != nullptr)
{
////LOG("particle index: %i", deleteParticleIndex);
switch (particles[i]->collider->type) {
case Collider::PLAYER_SHOT:
// Always destroy particles that collide
if (particles[i] != nullptr && c2->type == Collider::BULLET_WALL)
{
particles[i]->collider->pendingToDelete = true;
particles[i]->isAlive = false;
delete particles[i];
particles[i] = nullptr;
deleted = true;
}
if (particles[i] != nullptr && c2->type == Collider::ENEMY)
{
particles[i]->collider->pendingToDelete = true;
particles[i]->isAlive = false;
delete particles[i];
particles[i] = nullptr;
deleted = true;
}
break;
case Collider::ENEMY_SHOT:
// Always destroy particles that collide
if (particles[i] != nullptr && c2->type == Collider::BULLET_WALL)
{
particles[i]->isAlive = false;
particles[i]->collider->pendingToDelete = true;
delete particles[i];
particles[i] = nullptr;
deleted = true;
}
if (particles[i] != nullptr && c2->type == Collider::PLAYER_HITBOX)
{
particles[i]->isAlive = false;
particles[i]->collider->pendingToDelete = true;
delete particles[i];
particles[i] = nullptr;
deleted = true;
//Cause damage to enemy;
//
//
}
break;
default:
//// Always destroy particles that collide
//if (particles[i] != nullptr && c2->type == Collider::WALL)
//{
// particles[i]->isAlive = false;
// delete particles[i];
// particles[i] = nullptr;
// break;
//}
//
//if (particles[i] != nullptr && c2->type == Collider::ENEMY)
//{
// particles[i]->isAlive = false;
// delete particles[i];
// particles[i] = nullptr;
// //Cause damage to enemy;
// //
// //
// break;
//}
break;
}
}
if (deleteParticleIndex + 1 == MAX_ACTIVE_PARTICLES) {
deleteParticleIndex = 0;
}
else {
if (deleted) deleteParticleIndex = i;
}
if (i == max - 1 && !loopDone) {
i = -1;
max = deleteParticleIndex;
loopDone = true;
}
if (deleted) break;
}
}
UpdateResult ModuleParticles::Update()
{
for(uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i)
{
Particle* particle = particles[i];
if(particle == nullptr) continue;
// Call particle Update. If it has reached its lifetime, destroy it
if(particle->Update() == false)
{
delete particle;
particles[i] = nullptr;
//LOG("fin upd");
}
}
return UpdateResult::UPDATE_CONTINUE;
}
UpdateResult ModuleParticles::PostUpdate()
{
//Iterating all particle array and drawing any active particles
for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i)
{
Particle* particle = particles[i];
if (particle != nullptr && particle->isAlive)
{
App->render->Blit(texture, particle->position.x, particle->position.y, &(particle->anim.GetCurrentFrame()));
}
}
return UpdateResult::UPDATE_CONTINUE;
}
void ModuleParticles::AddParticle(const Particle& particle, int id, int x, int y, int direction, Collider::Type colliderType, uint delay)
{
for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i)
{
//Finding an empty slot for a new particle
if (particles[i] == nullptr)
{
//LOG("particle created");
Particle* p = new Particle(particle);
p->frameCount = -(int)delay; // We start the frameCount as the negative delay
p->position.x = x; // so when frameCount reaches 0 the particle will be activated
p->position.y = y;
p->direction = direction;
p->id = id;
//Adding the particle's collider
if (colliderType != Collider::Type::NONE)
{
p->collider = App->collisions->AddCollider(p->anim.GetCurrentFrame(), colliderType, this);
//if (colliderType == Collider::ENEMY_SHOT) LOG("enemy bullet fired");
//if (colliderType == Collider::PLAYER_SHOT) LOG("player bullet fired");
}
particles[i] = p;
break;
}
}
}
| 25.442424 | 137 | 0.650548 | IconicGIT |
2792555cf9355da77fd105139a32a85f40fb725d | 46 | cpp | C++ | examples/YAJL/boo.cpp | Costallat/hunter | dc0d79cb37b30cad6d6472d7143fe27be67e26d5 | [
"BSD-2-Clause"
] | 2,146 | 2015-01-10T07:26:58.000Z | 2022-03-21T02:28:01.000Z | examples/YAJL/boo.cpp | koinos/hunter | fc17bc391210bf139c55df7f947670c5dff59c57 | [
"BSD-2-Clause"
] | 1,778 | 2015-01-03T11:50:30.000Z | 2019-12-26T05:31:20.000Z | examples/YAJL/boo.cpp | koinos/hunter | fc17bc391210bf139c55df7f947670c5dff59c57 | [
"BSD-2-Clause"
] | 734 | 2015-03-05T19:52:34.000Z | 2022-02-22T23:18:54.000Z | #include <yajl/yajl_common.h>
int main() {
}
| 9.2 | 29 | 0.652174 | Costallat |
279480253a520924f7aeeedbe05e6518b9434fb3 | 6,535 | cc | C++ | src/base/time/time.cc | 243286065/cpplib_base | 9c63d556a0097fa5d9893e83c78ce9ebfd401ee0 | [
"BSD-3-Clause"
] | 10 | 2020-05-27T10:01:26.000Z | 2022-02-12T16:54:54.000Z | src/base/time/time.cc | 243286065/cpplib_base | 9c63d556a0097fa5d9893e83c78ce9ebfd401ee0 | [
"BSD-3-Clause"
] | 1 | 2020-09-16T00:50:02.000Z | 2020-09-17T03:53:06.000Z | src/base/time/time.cc | 243286065/cpplib_base | 9c63d556a0097fa5d9893e83c78ce9ebfd401ee0 | [
"BSD-3-Clause"
] | 9 | 2020-06-03T09:40:00.000Z | 2021-12-05T12:43:20.000Z | #include "base/time/time.h"
#include <chrono>
#include <iomanip>
#include "base/log/logging.h"
namespace base {
const int64_t kHoursPerDay = 24;
const int64_t kSecondsPerMinute = 60;
const int64_t kSecondsPerHour = 60 * kSecondsPerMinute;
const int64_t kMillisecondsPerSecond = 1000;
const int64_t kMillisecondsPerDay =
kMillisecondsPerSecond * 60 * 60 * kHoursPerDay;
const int64_t kMicrosecondsPerMillisecond = 1000;
const int64_t kMicrosecondsPerSecond =
kMicrosecondsPerMillisecond * kMillisecondsPerSecond;
const int64_t kMicrosecondsPerMinute = kMicrosecondsPerSecond * 60;
const int64_t kMicrosecondsPerHour = kMicrosecondsPerMinute * 60;
const int64_t kMicrosecondsPerDay = kMicrosecondsPerHour * kHoursPerDay;
const int64_t kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
const int64_t kNanosecondsPerMicrosecond = 1000;
const int64_t kNanosecondsPerSecond =
kNanosecondsPerMicrosecond * kMicrosecondsPerSecond;
int64_t SaturatedAdd(int64_t value, TimeDelta delta) {
int64_t result = 0;
if (delta.is_max()) {
CHECK_GT(value, std::numeric_limits<int64_t>::min());
result = std::numeric_limits<int64_t>::max();
} else if (delta.is_min()) {
CHECK_LT(value, std::numeric_limits<int64_t>::max());
result = std::numeric_limits<int64_t>::min();
} else {
if (value > 0 && delta.delta_ > 0 &&
std::numeric_limits<int64_t>::max() - value < delta.delta_) {
result = std::numeric_limits<int64_t>::max();
} else if (value < 0 && delta.delta_ < 0 &&
std::numeric_limits<int64_t>::min() - value > delta.delta_) {
result = std::numeric_limits<int64_t>::min();
} else {
result = value + delta.delta_;
}
}
return 0;
}
int64_t SaturatedSub(int64_t value, TimeDelta delta) {
return SaturatedAdd(value, -delta);
}
TimeDelta TimeDelta::FromDays(int days) {
return days == std::numeric_limits<int>::max()
? Max()
: TimeDelta(days * kMicrosecondsPerDay);
}
TimeDelta TimeDelta::FromHours(int hours) {
return hours == std::numeric_limits<int>::max()
? Max()
: TimeDelta(hours * kMicrosecondsPerHour);
}
TimeDelta TimeDelta::FromMinutes(int minutes) {
return minutes == std::numeric_limits<int>::max()
? Max()
: TimeDelta(minutes * kMicrosecondsPerMinute);
}
TimeDelta TimeDelta::FromSeconds(int64_t secs) {
return secs == std::numeric_limits<int>::max()
? Max()
: TimeDelta(secs * kMicrosecondsPerSecond);
}
TimeDelta TimeDelta::FromMilliseconds(int64_t ms) {
return ms == std::numeric_limits<int>::max()
? Max()
: TimeDelta(ms * kMicrosecondsPerMillisecond);
}
TimeDelta TimeDelta::FromMicroseconds(int64_t us) {
return TimeDelta(us);
}
TimeDelta TimeDelta::FromNanoseconds(int64_t ns) {
return TimeDelta(ns / kNanosecondsPerMicrosecond);
}
TimeDelta TimeDelta::FromSecondsD(double secs) {
return FromDouble(secs * kMicrosecondsPerSecond);
}
TimeDelta TimeDelta::FromMillisecondsD(double ms) {
return FromDouble(ms * kMicrosecondsPerMillisecond);
}
TimeDelta TimeDelta::FromMicrosecondsD(double us) {
return FromDouble(us);
}
TimeDelta TimeDelta::FromNanosecondsD(double ns) {
return FromDouble(ns / kNanosecondsPerMicrosecond);
}
TimeDelta TimeDelta::FromDouble(double value) {
return TimeDelta(static_cast<int64_t>(value));
}
TimeDelta TimeDelta::Max() {
return TimeDelta(std::numeric_limits<int64_t>::max());
}
TimeDelta TimeDelta::Min() {
return TimeDelta(std::numeric_limits<int64_t>::min());
}
int TimeDelta::InDays() const {
if (is_max()) {
// Preserve max to prevent overflow.
return std::numeric_limits<int>::max();
}
return static_cast<int>(delta_ / kMicrosecondsPerDay);
}
int TimeDelta::InDaysFloored() const {
if (is_max()) {
// Preserve max to prevent overflow.
return std::numeric_limits<int>::max();
}
int result = delta_ / kMicrosecondsPerDay;
int64_t remainder = delta_ - (result * kMicrosecondsPerDay);
if (remainder < 0) {
--result; // Use floor(), not trunc() rounding behavior.
}
return result;
}
int TimeDelta::InHours() const {
if (is_max()) {
// Preserve max to prevent overflow.
return std::numeric_limits<int>::max();
}
return static_cast<int>(delta_ / kMicrosecondsPerHour);
}
int TimeDelta::InMinutes() const {
if (is_max()) {
// Preserve max to prevent overflow.
return std::numeric_limits<int>::max();
}
return static_cast<int>(delta_ / kMicrosecondsPerMinute);
}
double TimeDelta::InSecondsF() const {
if (is_max()) {
// Preserve max to prevent overflow.
return std::numeric_limits<double>::infinity();
}
return static_cast<double>(delta_) / kMicrosecondsPerSecond;
}
int64_t TimeDelta::InSeconds() const {
if (is_max()) {
// Preserve max to prevent overflow.
return std::numeric_limits<int64_t>::max();
}
return delta_ / kMicrosecondsPerSecond;
}
double TimeDelta::InMillisecondsF() const {
if (is_max()) {
// Preserve max to prevent overflow.
return std::numeric_limits<double>::infinity();
}
return static_cast<double>(delta_) / kMicrosecondsPerMillisecond;
}
int64_t TimeDelta::InMilliseconds() const {
if (is_max()) {
// Preserve max to prevent overflow.
return std::numeric_limits<int64_t>::max();
}
return delta_ / kMicrosecondsPerMillisecond;
}
int64_t TimeDelta::InMillisecondsRoundedUp() const {
if (is_max()) {
// Preserve max to prevent overflow.
return std::numeric_limits<int64_t>::max();
}
int64_t result = delta_ / kMicrosecondsPerMillisecond;
int64_t remainder = delta_ - (result * kMicrosecondsPerMillisecond);
if (remainder > 0) {
++result; // Use ceil(), not trunc() rounding behavior.
}
return result;
}
double TimeDelta::InMicrosecondsF() const {
if (is_max()) {
// Preserve max to prevent overflow.
return std::numeric_limits<double>::infinity();
}
return static_cast<double>(delta_);
}
int64_t TimeDelta::InNanoseconds() const {
if (is_max()) {
// Preserve max to prevent overflow.
return std::numeric_limits<int64_t>::max();
}
return delta_ * kNanosecondsPerMicrosecond;
}
std::ostream& operator<<(std::ostream& os, TimeDelta time_delta) {
return os << std::fixed << time_delta.InSecondsF() << " s";
}
int64_t Now() {
std::chrono::microseconds ms =
std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::system_clock::now().time_since_epoch());
return ms.count();
}
} // namespace base
| 28.413043 | 76 | 0.695486 | 243286065 |
27965ac4051d43b2d857b12477817ab90f28b336 | 3,459 | cc | C++ | programs/playlist.cc | paulfd/fmidi | f12d08d6ccd27d2580ec4e21717fbc3ab4b73a20 | [
"BSL-1.0"
] | 17 | 2018-04-18T08:57:12.000Z | 2022-01-25T08:24:14.000Z | programs/playlist.cc | paulfd/fmidi | f12d08d6ccd27d2580ec4e21717fbc3ab4b73a20 | [
"BSL-1.0"
] | 3 | 2018-11-02T13:20:51.000Z | 2021-08-03T13:42:06.000Z | programs/playlist.cc | paulfd/fmidi | f12d08d6ccd27d2580ec4e21717fbc3ab4b73a20 | [
"BSL-1.0"
] | 3 | 2020-04-22T17:55:31.000Z | 2021-08-02T21:10:01.000Z | // Copyright Jean Pierre Cimalando 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "playlist.h"
#if defined(FMIDI_PLAY_USE_BOOST_FILESYSTEM)
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
namespace sys = boost::system;
#else
#include <fts.h>
#endif
#include <memory>
#include <ctime>
#if !defined(FMIDI_PLAY_USE_BOOST_FILESYSTEM)
struct FTS_Deleter {
void operator()(FTS *x) const
{ fts_close(x); }
};
typedef std::unique_ptr<FTS, FTS_Deleter> FTS_u;
#endif
//
void Linear_Play_List::add_file(const std::string &path)
{
files_.emplace_back(path);
}
void Linear_Play_List::start()
{
index_ = 0;
}
bool Linear_Play_List::at_end() const
{
return index_ == files_.size();
}
const std::string &Linear_Play_List::current() const
{
return files_[index_];
}
bool Linear_Play_List::go_next()
{
if (index_ == files_.size())
return false;
++index_;
return true;
}
bool Linear_Play_List::go_previous()
{
if (index_ == 0)
return false;
--index_;
return true;
}
//
Random_Play_List::Random_Play_List()
: prng_(std::time(nullptr))
{
}
void Random_Play_List::add_file(const std::string &path)
{
scan_files(path);
}
void Random_Play_List::start()
{
index_ = 0;
history_.clear();
if (!files_.empty())
history_.push_back(&files_[random_file()]);
}
bool Random_Play_List::at_end() const
{
return history_.empty();
}
const std::string &Random_Play_List::current() const
{
return *history_[index_];
}
bool Random_Play_List::go_next()
{
if (index_ < history_.size() - 1)
++index_;
else {
if (history_.size() == history_max)
history_.pop_front();
history_.push_back(&files_[random_file()]);
index_ = history_.size() - 1;
}
return true;
}
bool Random_Play_List::go_previous()
{
if (index_ == 0)
return false;
--index_;
return true;
}
size_t Random_Play_List::random_file() const
{
std::uniform_int_distribution<size_t> dist(0, files_.size() - 1);
return dist(prng_);
}
#if !defined(FMIDI_PLAY_USE_BOOST_FILESYSTEM)
void Random_Play_List::scan_files(const std::string &path)
{
char *path_argv[] = { (char *)path.c_str(), nullptr };
FTS_u fts(fts_open(path_argv, FTS_NOCHDIR|FTS_LOGICAL, nullptr));
if (!fts)
return;
while (FTSENT *ent = fts_read(fts.get())) {
if (ent->fts_info == FTS_F)
files_.emplace_back(ent->fts_path);
}
}
#else
void Random_Play_List::scan_files(const std::string &path)
{
sys::error_code ec;
ec.clear();
fs::file_status st = fs::status(path, ec);
if (ec)
return;
switch (st.type()) {
default:
break;
case fs::regular_file:
files_.emplace_back(path);
break;
case fs::directory_file:
ec.clear();
fs::recursive_directory_iterator it(path, ec);
if (ec)
return;
while (it != fs::recursive_directory_iterator()) {
ec.clear();
st = it->status(ec);
if (ec || st.type() != fs::regular_file)
continue;
files_.emplace_back(it->path().string());
ec.clear();
it.increment(ec);
if (ec)
break;
}
break;
}
}
#endif
| 20.589286 | 69 | 0.614629 | paulfd |
279ce6b4234aa64bada26d7ab15ce3a0d2bf02c8 | 4,027 | cc | C++ | tests/test_geometry.cc | tatsy/rainy | 9c1485eae242a13cff18f7cedc88962ed2538168 | [
"MIT"
] | 22 | 2015-08-20T01:29:31.000Z | 2020-12-20T01:05:41.000Z | tests/test_geometry.cc | tatsy/rainy | 9c1485eae242a13cff18f7cedc88962ed2538168 | [
"MIT"
] | 17 | 2015-04-21T23:44:12.000Z | 2017-08-02T09:55:41.000Z | tests/test_geometry.cc | tatsy/rainy | 9c1485eae242a13cff18f7cedc88962ed2538168 | [
"MIT"
] | 5 | 2015-11-11T13:26:59.000Z | 2020-04-27T10:55:53.000Z | #include "gtest/gtest.h"
#include <cmath>
#include "spica.h"
using namespace spica;
// ------------------------------
// Sphere class test
// ------------------------------
TEST(BSphereTest, InstanceTest) {
BSphere sp0;
EXPECT_EQ(0.0, sp0.center().x());
EXPECT_EQ(0.0, sp0.center().y());
EXPECT_EQ(0.0, sp0.center().z());
EXPECT_EQ(0.0, sp0.radius());
BSphere sp(Point3d(0.0, 0.0, 0.0), 2.0);
EXPECT_EQ(0.0, sp.center().x());
EXPECT_EQ(0.0, sp.center().y());
EXPECT_EQ(0.0, sp.center().z());
}
TEST(SphereTest, CopyConstructor) {
BSphere sp(Point3d(0.0, 0.0, 0.0), 2.0);
BSphere sp0 = sp;
EXPECT_EQ(0.0, sp0.center().x());
EXPECT_EQ(0.0, sp0.center().y());
EXPECT_EQ(0.0, sp0.center().z());
}
// ------------------------------
// Triangle class test
// ------------------------------
TEST(TriangleTest, InstanceTest) {
Triangle t0;
EXPECT_EQ(Point3d(), t0[0]);
EXPECT_EQ(Point3d(), t0[1]);
EXPECT_EQ(Point3d(), t0[2]);
Triangle t1(Point3d(0, 0, 0),
Point3d(0, 1, 0),
Point3d(1, 1, 0));
EXPECT_EQ(Point3d(0, 0, 0), t1[0]);
EXPECT_EQ(Point3d(0, 1, 0), t1[1]);
EXPECT_EQ(Point3d(1, 1, 0), t1[2]);
}
TEST(TriangleTest, IntersectionTest) {
Triangle t0(Point3d(1, 0, 0),
Point3d(0, 0, 0),
Point3d(0, 1, 0));
Ray ray = Ray(Point3d(0, 0, -1), (Vector3d(1, 1, 1) - Vector3d(0, 0, -1)).normalized());
SurfaceInteraction isect;
double tHit;
EXPECT_TRUE(t0.intersect(ray));
EXPECT_TRUE(t0.intersect(ray, &tHit, &isect));
EXPECT_EQ(sqrt(6.0) / 2.0, tHit);
ray = Ray(Point3d(-0.1, -0.1, 1.0), Vector3d(0.0, 0.0, -1.0));
EXPECT_FALSE(t0.intersect(ray));
EXPECT_FALSE(t0.intersect(ray, &tHit, &isect));
ray = Ray(Point3d(0.6, 0.6, 1.0), Vector3d(0.0, 0.0, -1.0));
EXPECT_FALSE(t0.intersect(ray));
EXPECT_FALSE(t0.intersect(ray, &tHit, &isect));
ray = Ray(Point3d(-0.1, 1.1, 1.0), Vector3d(0.0, 0.0, -1.0));
EXPECT_FALSE(t0.intersect(ray));
EXPECT_FALSE(t0.intersect(ray, &tHit, &isect));
ray = Ray(Point3d(1.1, -0.1, 1.0), Vector3d(0.0, 0.0, -1.0));
EXPECT_FALSE(t0.intersect(ray));
EXPECT_FALSE(t0.intersect(ray, &tHit, &isect));
}
TEST(TriangleTest, AreaTest) {
Triangle t0(Point3d(1, 0, 0),
Point3d(0, 0, 0),
Point3d(0, 1, 0));
EXPECT_EQ(0.5, t0.area());
}
// ------------------------------
// Bounds3d class test
// ------------------------------
TEST(Bounds3dTest, InstanceTest) {
Bounds3d b;
const double minValue = std::numeric_limits<double>::lowest();
const double maxValue = std::numeric_limits<double>::max();
EXPECT_EQ(Point3d(maxValue, maxValue, maxValue), b.posMin());
EXPECT_EQ(Point3d(minValue, minValue, minValue), b.posMax());
Bounds3d b0(Point3d(0.0, 0.0, 0.0), Point3d(1.0, 1.0, 1.0));
EXPECT_EQ(Point3d(0.0, 0.0, 0.0), b0.posMin());
EXPECT_EQ(Point3d(1.0, 1.0, 1.0), b0.posMax());
}
TEST(Bounds3dTest, CopyConstructor) {
Bounds3d b0(Point3d(0.0, 0.0, 0.0), Point3d(1.0, 1.0, 1.0));
Bounds3d b1(b0);
EXPECT_EQ(Point3d(0.0, 0.0, 0.0), b1.posMin());
EXPECT_EQ(Point3d(1.0, 1.0, 1.0), b1.posMax());
}
TEST(Bounds3dTest, MergeTest) {
Bounds3d Bounds3d;
Bounds3d.merge(Point3d(0.0, 0.0, 0.0));
EXPECT_EQ(Point3d(0.0, 0.0, 0.0), Bounds3d.posMin());
EXPECT_EQ(Point3d(0.0, 0.0, 0.0), Bounds3d.posMax());
Bounds3d.merge(Point3d(1.0, 1.0, 1.0));
EXPECT_EQ(Point3d(0.0, 0.0, 0.0), Bounds3d.posMin());
EXPECT_EQ(Point3d(1.0, 1.0, 1.0), Bounds3d.posMax());
}
TEST(Bounds3dTest, IntersectionTest) {
Bounds3d b0(Point3d(0.0, 0.0, 0.0), Point3d(1.0, 1.0, 1.0));
double tMin, tMax;
b0.intersect(Ray(Point3d(0.5, 0.5, -1.0), Vector3d(0.0, 0.0, 1.0)), &tMin, &tMax);
EXPECT_DOUBLE_EQ(1.0, tMin);
EXPECT_DOUBLE_EQ(2.0, tMax);
}
| 31.960317 | 93 | 0.548299 | tatsy |
279d9d7f6e6fb3e43173bfb31229a534e324ab41 | 919 | cpp | C++ | imGUIWin.Demo/mainapp.cpp | Bit00009/imGUIWin | 98c3f2d114a9ebd5351a6a863317a3a474e0c994 | [
"MIT"
] | null | null | null | imGUIWin.Demo/mainapp.cpp | Bit00009/imGUIWin | 98c3f2d114a9ebd5351a6a863317a3a474e0c994 | [
"MIT"
] | null | null | null | imGUIWin.Demo/mainapp.cpp | Bit00009/imGUIWin | 98c3f2d114a9ebd5351a6a863317a3a474e0c994 | [
"MIT"
] | null | null | null | #include <Windows.h>
#include <iostream>
#include "imGUIWinLib.h"
#pragma comment(lib, "..\\build\\imGUIWinLib.lib")
using namespace std;
int main()
{
cout << "imGUIWin.Demo" << endl;
InitializeGUIEngine();
cout << "GUI Engine has been initialized." << endl;
ViewHandle view01 = CreateNewViewWindow(L"imGUI View 01");
cout << "view01 has been created, Handle : " << hex << view01 << endl;
ViewHandle view02 = CreateNewViewWindow(L"imGUI View 02");
cout << "view02 has been created, Handle : " << hex << view02 << endl;
MSG msg;
ZeroMemory(&msg, sizeof(msg));
while (msg.message != WM_QUIT)
{
if (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
continue;
}
RenderViewWindow(view01);
RenderViewWindow(view02);
}
} | 24.837838 | 75 | 0.581066 | Bit00009 |
279f48a21abbc7ed488f83df337c9021492e9b6e | 545 | cpp | C++ | insomnia.cpp | VamsiKrishna04/Hacktoberfest_2021-1 | 6d0d217161957746a4b60b7d1f0f71db21026f5a | [
"MIT"
] | 1 | 2021-11-10T10:01:53.000Z | 2021-11-10T10:01:53.000Z | insomnia.cpp | VamsiKrishna04/Hacktoberfest_2021-1 | 6d0d217161957746a4b60b7d1f0f71db21026f5a | [
"MIT"
] | 3 | 2021-10-22T04:46:25.000Z | 2021-11-17T06:37:10.000Z | insomnia.cpp | VamsiKrishna04/Hacktoberfest_2021-1 | 6d0d217161957746a4b60b7d1f0f71db21026f5a | [
"MIT"
] | 12 | 2021-10-21T13:56:49.000Z | 2021-11-17T06:32:30.000Z | #include <bits/stdc++.h>
using namespace std;
int LCM(int a,int b){
int lcm =(a/__gcd(a,b))*b;
return lcm;
}
int main(){
int j,k,l,m,d;
cin>>j;
cin>>k;
cin>>l;
cin>>m;
cin>>d;
int f1=(d/j)+(d/k)+(d/l)+(d/m);
int f2=(d/LCM(j,k))+(d/LCM(j,l))+(d/LCM(j,m))+(d/LCM(l,k))+(d/LCM(m,k))+(d/LCM(l,m));
int t=LCM(LCM(j,k),l);
int f3=(d/t)+(d/LCM(LCM(m,k),l))+(d/LCM(LCM(j,k),m))+(d/LCM(LCM(j,m),l));
int f4=d/LCM(t,m);
int ans= f1-f2+f3-f4;
cout<<ans;
return 0;
} | 23.695652 | 90 | 0.456881 | VamsiKrishna04 |
27a1666fb2f9df9fbeadd5efa5ddf5724aa308d4 | 5,673 | cpp | C++ | src/backend/dnnl/patterns/reorder_fusion.cpp | wuxun-zhang/mkl-dnn | 00a239ad2c932b967234ffb528069800ffcc0334 | [
"Apache-2.0"
] | null | null | null | src/backend/dnnl/patterns/reorder_fusion.cpp | wuxun-zhang/mkl-dnn | 00a239ad2c932b967234ffb528069800ffcc0334 | [
"Apache-2.0"
] | null | null | null | src/backend/dnnl/patterns/reorder_fusion.cpp | wuxun-zhang/mkl-dnn | 00a239ad2c932b967234ffb528069800ffcc0334 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright 2021-2022 Intel Corporation
*
* 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 "backend/dnnl/internal_ops.hpp"
#include "backend/dnnl/patterns/fusions.hpp"
namespace dnnl {
namespace graph {
namespace impl {
namespace dnnl_impl {
namespace pass {
namespace pm = impl::utils::pm;
using in_edges_t = pm::in_edges_t;
using pb_graph = pm::pb_graph_t;
using FCreateV2FusedOp = impl::pass::FCreateV2FusedOp;
using FCreateV2Pattern = impl::pass::FCreateV2Pattern;
/*!
* \brief This provides reorder-related fusion
* The process includes follow steps:
* 1. look for fusion pattern on the graph
* 2. If found, verify if this transformation is safe / correct
* 3. replace the pattern with a fused op, update the graph
*/
DNNL_BACKEND_REGISTER_PASSES_DEF_BEGIN(reorder_fusion)
DNNL_BACKEND_REGISTER_TRANSFORMATION_PASS(dnnl, reorder_sum_fusion)
.set_priority(10.1f)
.set_attr<FCreateV2Pattern>("FCreateV2Pattern",
[](const std::shared_ptr<pb_graph> &pgraph) -> void {
pm::pb_op_t *reorder = pgraph->append_op(
impl::op_kind::Reorder, "preorder");
pm::pb_op_t *add = pgraph->append_op(impl::op_kind::Add,
{in_edge(0, reorder, 0)}, "padd");
add->append_decision_function([](op_t *graph_op) -> bool {
return !graph_op->has_attr("auto_broadcast")
|| graph_op->get_attr<std::string>(
"auto_broadcast")
== "none";
});
})
.set_attr<FCreateV2FusedOp>(
"FCreateV2FusedOp", []() -> std::shared_ptr<op_t> {
std::shared_ptr<op_t> fused_op
= std::make_shared<op_t>(op_kind::reorder_sum);
fused_op->set_attr<std::string>("backend", "dnnl");
return fused_op;
});
DNNL_BACKEND_REGISTER_TRANSFORMATION_PASS(dnnl, int8_reorder_fusion)
.set_priority(10.1f)
.set_attr<FCreateV2Pattern>("FCreateV2Pattern",
[](const std::shared_ptr<pb_graph> &pgraph) -> void {
pm::pb_op_t *dequant = pgraph->append_op(
impl::op_kind::Dequantize, "pdequant");
pm::pb_op_t *reorder
= pgraph->append_op(impl::op_kind::Reorder,
{in_edge(0, dequant, 0)}, "preorder");
pgraph->append_op(impl::op_kind::Quantize,
{in_edge(0, reorder, 0)}, "pquant");
})
.set_attr<FCreateV2FusedOp>(
"FCreateV2FusedOp", []() -> std::shared_ptr<op_t> {
std::shared_ptr<op_t> fused_op
= std::make_shared<op_t>(op_kind::int8_reorder);
fused_op->set_attr<std::string>("backend", "dnnl");
return fused_op;
});
DNNL_BACKEND_REGISTER_TRANSFORMATION_PASS(dnnl, int8_reorder_sum_fusion)
.set_priority(10.2f)
.set_attr<FCreateV2Pattern>("FCreateV2Pattern",
[](const std::shared_ptr<pb_graph> &pgraph) -> void {
pm::pb_op_t *dequant = pgraph->append_op(
impl::op_kind::Dequantize, "pdequant");
pm::pb_op_t *dequant_other = pgraph->append_op(
impl::op_kind::Dequantize, "pdequant_other");
pm::pb_op_t *reorder
= pgraph->append_op(impl::op_kind::Reorder,
{in_edge(0, dequant, 0)}, "preorder");
pm::pb_op_t *add = pgraph->append_op(impl::op_kind::Add,
{in_edge(0, reorder, 0),
in_edge(1, dequant_other, 0)},
"padd");
add->append_decision_function([](op_t *graph_op) -> bool {
return !graph_op->has_attr("auto_broadcast")
|| graph_op->get_attr<std::string>(
"auto_broadcast")
== "none";
});
pgraph->append_op(impl::op_kind::Quantize,
{in_edge(0, add, 0)}, "pquant");
})
.set_attr<FCreateV2FusedOp>(
"FCreateV2FusedOp", []() -> std::shared_ptr<op_t> {
std::shared_ptr<op_t> fused_op
= std::make_shared<op_t>(op_kind::int8_reorder);
fused_op->set_attr<std::string>("backend", "dnnl");
return fused_op;
});
DNNL_BACKEND_REGISTER_PASSES_DEF_END
} // namespace pass
} // namespace dnnl_impl
} // namespace impl
} // namespace graph
} // namespace dnnl
| 45.75 | 80 | 0.52318 | wuxun-zhang |
27a206a12ebb0045c7d3f79113374bc09331e8ad | 127 | cpp | C++ | cpp_CS225/daily-exercise/day34-Balancing-an-AVL-Tree/potd-q34-clean/TreeNode.cpp | Rothdyt/codes-for-courses | a2dfea516ebc7cabef31a5169533b6da352e7ccb | [
"MIT"
] | 4 | 2018-09-23T00:00:13.000Z | 2018-11-02T22:56:35.000Z | cpp_CS225/daily-exercise/day34-Balancing-an-AVL-Tree/potd-q34-clean/TreeNode.cpp | Rothdyt/codes-for-courses | a2dfea516ebc7cabef31a5169533b6da352e7ccb | [
"MIT"
] | null | null | null | cpp_CS225/daily-exercise/day34-Balancing-an-AVL-Tree/potd-q34-clean/TreeNode.cpp | Rothdyt/codes-for-courses | a2dfea516ebc7cabef31a5169533b6da352e7ccb | [
"MIT"
] | null | null | null | #include "TreeNode.h"
TreeNode::RotationType balanceTree(TreeNode*& subroot) {
// Your code here
return TreeNode::right;
}
| 18.142857 | 56 | 0.732283 | Rothdyt |
27a44b5fc024dbf5b1c983b9890f44a2cbc0b8a4 | 2,858 | cpp | C++ | lang/Uint8.cpp | wangsun1983/Obotcha | 2464e53599305703f5150df72bf73579a39d8ef4 | [
"MIT"
] | 27 | 2019-04-27T00:51:22.000Z | 2022-03-30T04:05:44.000Z | lang/Uint8.cpp | wangsun1983/Obotcha | 2464e53599305703f5150df72bf73579a39d8ef4 | [
"MIT"
] | 9 | 2020-05-03T12:17:50.000Z | 2021-10-15T02:18:47.000Z | lang/Uint8.cpp | wangsun1983/Obotcha | 2464e53599305703f5150df72bf73579a39d8ef4 | [
"MIT"
] | 1 | 2019-04-16T01:45:36.000Z | 2019-04-16T01:45:36.000Z | /**
* @file String.cpp
* @brief this class used for uint8
* @details none
* @mainpage none
* @author sunli.wang
* @email wang_sun_1983@yahoo.co.jp
* @version 0.0.1
* @date 2019-07-12
* @license none
*/
#include <algorithm>
#include "InitializeException.hpp"
#include "NullPointerException.hpp"
#include "Number.hpp"
#include "Uint8.hpp"
namespace obotcha {
_Uint8::_Uint8() : val(0) {}
_Uint8::_Uint8(uint8_t v) : val(v) {}
_Uint8::_Uint8(const Uint8 &v) {
if (v == nullptr) {
Trigger(InitializeException, "Object is null");
}
val = v->val;
}
uint8_t _Uint8::toValue() { return val; }
bool _Uint8::equals(const Uint8 &p) { return val == p->val; }
bool _Uint8::equals(uint8_t p) { return val == p; }
bool _Uint8::equals(const _Uint8 *p) { return val == p->val; }
void _Uint8::update(uint8_t v) { val = v; }
void _Uint8::update(const sp<_Uint8> &v) { val = v->val; }
sp<_String> _Uint8::toHexString() {
return createString(_Number::toHexString(val));
}
sp<_String> _Uint8::toOctalString() {
return createString(_Number::toOctalString(val));
}
sp<_String> _Uint8::toBinaryString() {
return createString(_Number::toBinaryString(val));
}
uint64_t _Uint8::hashcode() { return std::hash<uint8_t>{}(val); }
sp<_String> _Uint8::toString() {
return createString(_Number::toDecString(val));
}
sp<_String> _Uint8::toString(uint8_t i) {
return createString(_Number::toDecString(i));
}
sp<_Uint8> _Uint8::parseDecUint8(const sp<_String> &v) {
try {
String pa = v->trimAll()->replaceAll(std::string("\n"),"")->replaceAll("\r","");
uint8_t value = _Number::parseDecNumber(pa->getStdString());
return createUint8(value);
} catch (int e) {
}
return nullptr;
}
sp<_Uint8> _Uint8::parseHexUint8(const sp<_String> &v) {
try {
String pa = v->trimAll()->replaceAll(std::string("\n"),"")->replaceAll("\r","");
uint8_t value = _Number::parseHexNumber(pa->getStdString());
return createUint8(value);
} catch (...) {
// nothing
}
return nullptr;
}
sp<_Uint8> _Uint8::parseOctUint8(const sp<_String> &v) {
try {
String pa = v->trimAll()->replaceAll(std::string("\n"),"")->replaceAll("\r","");
uint8_t value = _Number::parseOctNumber(pa->getStdString());
return createUint8(value);
} catch (...) {
// nothing
}
return nullptr;
}
sp<_Uint8> _Uint8::parseBinaryUint8(const sp<_String> &v) {
try {
String pa = v->trimAll()->replaceAll(std::string("\n"),"")->replaceAll("\r","");
uint8_t value = _Number::parseBinaryNumber(pa->getStdString());
return createUint8(value);
} catch (...) {
// nothing
}
return nullptr;
}
sp<_String> _Uint8::className() { return createString("Uint8"); }
_Uint8::~_Uint8() {}
} // namespace obotcha
| 24.016807 | 88 | 0.625612 | wangsun1983 |
27a866584475c55810bc531c68d8d198a631ea02 | 20,232 | hpp | C++ | lib/swig/cpp_wrappers/pokemon.hpp | ncorgan/libpkmn | c683bf8b85b03eef74a132b5cfdce9be0969d523 | [
"MIT"
] | 4 | 2017-06-10T13:21:44.000Z | 2019-10-30T21:20:19.000Z | lib/swig/cpp_wrappers/pokemon.hpp | PMArkive/libpkmn | c683bf8b85b03eef74a132b5cfdce9be0969d523 | [
"MIT"
] | 12 | 2017-04-05T11:13:34.000Z | 2018-06-03T14:31:03.000Z | lib/swig/cpp_wrappers/pokemon.hpp | PMArkive/libpkmn | c683bf8b85b03eef74a132b5cfdce9be0969d523 | [
"MIT"
] | 2 | 2019-01-22T21:02:31.000Z | 2019-10-30T21:20:20.000Z | /*
* Copyright (c) 2017-2018 Nicholas Corgan (n.corgan@gmail.com)
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#ifndef CPP_WRAPPERS_POKEMON_HPP
#define CPP_WRAPPERS_POKEMON_HPP
#include "exception_internal.hpp"
#include "private_exports.hpp"
#include "attribute_maps.hpp"
#include "pokemon_helpers.hpp"
#include <pkmn/config.hpp>
#include <pkmn/exception.hpp>
#include <pkmn/pokemon.hpp>
#include <boost/assert.hpp>
namespace pkmn { namespace swig {
/*
* This class is a thin wrapper around pkmn::pokemon::sptr and
* will be what some SWIG wrappers will use instead of the class
* itself. It will allow syntax like the following to be used:
*
* bulbasaur.EVs["Attack"] = 100
*
* Per conventions, when used as attributes, these getters won't
* throw exceptions and will instead return a default value.
*/
class pokemon
{
public:
explicit pokemon(
const pkmn::pokemon::sptr& cpp_pokemon
): _pokemon(cpp_pokemon),
_generation(pkmn::priv::game_enum_to_generation(cpp_pokemon->get_game()))
{
BOOST_ASSERT(_pokemon.get() != nullptr);
}
pokemon(
pkmn::e_species species,
pkmn::e_game game,
const std::string& form,
int level
): _pokemon(pkmn::pokemon::make(species, game, form, level)),
_generation(pkmn::priv::game_enum_to_generation(game))
{
BOOST_ASSERT(_pokemon.get() != nullptr);
}
explicit pokemon(
const std::string& filepath
): _pokemon(pkmn::pokemon::from_file(filepath))
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_generation = pkmn::priv::game_enum_to_generation(_pokemon->get_game());
}
static const uint32_t DEFAULT_TRAINER_ID;
static const std::string DEFAULT_TRAINER_NAME;
inline pokemon to_game(pkmn::e_game game)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return pokemon(_pokemon->to_game(game));
}
inline void export_to_file(
const std::string& filepath
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->export_to_file(filepath);
}
inline pkmn::e_species get_species()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return _pokemon->get_species();
}
inline pkmn::e_game get_game()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return _pokemon->get_game();
}
inline std::string get_form()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return _pokemon->get_form();
}
inline void set_form(
const std::string& form
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_form(form);
}
inline bool is_egg()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return _pokemon->is_egg();
}
inline void set_is_egg(bool is_egg)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_is_egg(is_egg);
}
// Copy the entry, since the const in the reference is casted away.
inline pkmn::database::pokemon_entry get_database_entry()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return _pokemon->get_database_entry();
}
inline pkmn::e_condition get_condition()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return _pokemon->get_condition();
}
inline void set_condition(
pkmn::e_condition condition
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_condition(condition);
}
inline std::string get_nickname()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return _pokemon->get_nickname();
}
inline void set_nickname(
const std::string& nickname
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_nickname(nickname);
}
inline pkmn::e_gender get_gender()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
if(_generation >= 2)
{
return _pokemon->get_gender();
}
else
{
return pkmn::e_gender::NONE;
}
}
inline void set_gender(
pkmn::e_gender gender
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_gender(gender);
}
inline bool is_shiny()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
if(_generation >= 2)
{
return _pokemon->is_shiny();
}
else
{
return false;
}
}
inline void set_shininess(
bool value
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_shininess(value);
}
inline pkmn::e_item get_held_item()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
if(_generation >= 2)
{
return _pokemon->get_held_item();
}
else
{
return pkmn::e_item::NONE;
}
}
inline void set_held_item(
pkmn::e_item held_item
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_held_item(held_item);
}
inline pkmn::e_nature get_nature()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
if(_generation >= 3)
{
return _pokemon->get_nature();
}
else
{
return pkmn::e_nature::NONE;
}
}
inline void set_nature(pkmn::e_nature nature)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_nature(nature);
}
inline int get_pokerus_duration()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
if(_generation >= 2)
{
return _pokemon->get_pokerus_duration();
}
else
{
return 0;
}
}
inline void set_pokerus_duration(int duration)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_pokerus_duration(duration);
}
inline std::string get_original_trainer_name()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return _pokemon->get_original_trainer_name();
}
inline void set_original_trainer_name(
const std::string& trainer_name
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_original_trainer_name(trainer_name);
}
inline uint16_t get_original_trainer_public_id()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return _pokemon->get_original_trainer_public_id();
}
inline uint16_t get_original_trainer_secret_id()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
if(_generation >= 3)
{
return _pokemon->get_original_trainer_secret_id();
}
else
{
return 0;
}
}
inline uint32_t get_original_trainer_id()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return _pokemon->get_original_trainer_id();
}
inline void set_original_trainer_public_id(
uint16_t public_id
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_original_trainer_public_id(public_id);
}
inline void set_original_trainer_secret_id(
uint16_t secret_id
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_original_trainer_secret_id(secret_id);
}
inline void set_original_trainer_id(
uint32_t public_id
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_original_trainer_id(public_id);
}
inline pkmn::e_gender get_original_trainer_gender()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
if(_generation >= 2)
{
return _pokemon->get_original_trainer_gender();
}
else
{
return pkmn::e_gender::NONE;
}
}
inline void set_original_trainer_gender(
pkmn::e_gender trainer_gender
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_original_trainer_gender(trainer_gender);
}
inline pkmn::e_language get_language()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
if(_generation >= 3)
{
return _pokemon->get_language();
}
else
{
return pkmn::e_language::NONE;
}
}
inline void set_language(pkmn::e_language language)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_language(language);
}
inline int get_current_trainer_friendship()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
if(_generation >= 2)
{
return _pokemon->get_current_trainer_friendship();
}
else
{
return 0;
}
}
inline void set_current_trainer_friendship(
int friendship
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_current_trainer_friendship(friendship);
}
inline pkmn::e_ability get_ability()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
if(_generation >= 3)
{
return _pokemon->get_ability();
}
else
{
return pkmn::e_ability::NONE;
}
}
inline void set_ability(pkmn::e_ability ability)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_ability(ability);
}
inline pkmn::e_ball get_ball()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
if(_generation >= 3)
{
return _pokemon->get_ball();
}
else
{
return pkmn::e_ball::NONE;
}
}
inline void set_ball(
pkmn::e_ball ball
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_ball(ball);
}
inline int get_level_met()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
if(_generation >= 2)
{
return _pokemon->get_level_met();
}
else
{
return 0;
}
}
inline void set_level_met(
int level_met
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_level_met(level_met);
}
inline std::string get_location_met()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
if(_generation >= 2)
{
return _pokemon->get_location_met(false);
}
else
{
return "";
}
}
inline void set_location_met(
const std::string& location
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_location_met(location, false);
}
inline std::string get_location_met_as_egg()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
if(_generation >= 4)
{
return _pokemon->get_location_met(true);
}
else
{
return "";
}
}
inline void set_location_met_as_egg(
const std::string& location
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_location_met(location, true);
}
inline pkmn::e_game get_original_game()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
if(_generation >= 3)
{
return _pokemon->get_original_game();
}
else
{
return pkmn::e_game::NONE;
}
}
inline void set_original_game(pkmn::e_game original_game)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_original_game(original_game);
}
inline uint32_t get_personality()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
if(_generation >= 3)
{
return _pokemon->get_personality();
}
else
{
return 0U;
}
}
inline void set_personality(
uint32_t personality
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_personality(personality);
}
inline int get_experience()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return _pokemon->get_experience();
}
inline void set_experience(
int experience
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_experience(experience);
}
inline int get_level()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return _pokemon->get_level();
}
inline void set_level(
int level
)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_level(level);
}
inline int get_current_hp()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return _pokemon->get_current_hp();
}
inline void set_current_hp(int hp)
{
BOOST_ASSERT(_pokemon.get() != nullptr);
_pokemon->set_current_hp(hp);
}
inline EV_map get_EVs()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return EV_map(_pokemon);
}
inline IV_map get_IVs()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return IV_map(_pokemon);
}
inline marking_map get_markings()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return marking_map(_pokemon);
}
inline ribbon_map get_ribbons()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return ribbon_map(_pokemon);
}
inline contest_stat_map get_contest_stats()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return contest_stat_map(_pokemon);
}
inline move_slots get_moves()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return move_slots(_pokemon);
}
// Stats are read-only, so no need to wrap.
inline std::map<pkmn::e_stat, int> get_stats()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return _pokemon->get_stats();
}
inline std::string get_icon_filepath()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return _pokemon->get_icon_filepath();
}
inline std::string get_sprite_filepath()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return _pokemon->get_sprite_filepath();
}
numeric_attribute_map<pkmn::pokemon> get_numeric_attributes()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return numeric_attribute_map<pkmn::pokemon>(_pokemon);
}
string_attribute_map<pkmn::pokemon> get_string_attributes()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return string_attribute_map<pkmn::pokemon>(_pokemon);
}
boolean_attribute_map<pkmn::pokemon> get_boolean_attributes()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return boolean_attribute_map<pkmn::pokemon>(_pokemon);
}
inline const pkmn::pokemon::sptr& get_internal() const
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return _pokemon;
}
#ifdef SWIGCSHARP
inline uintmax_t cptr()
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return uintmax_t(_pokemon.get());
}
#else
inline bool operator==(const pokemon& rhs) const
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return (_pokemon == rhs._pokemon);
}
inline bool operator!=(const pokemon& rhs) const
{
BOOST_ASSERT(_pokemon.get() != nullptr);
return !operator==(rhs);
}
#endif
private:
pkmn::pokemon::sptr _pokemon;
int _generation;
};
const uint32_t pokemon::DEFAULT_TRAINER_ID = pkmn::pokemon::DEFAULT_TRAINER_ID;
const std::string pokemon::DEFAULT_TRAINER_NAME = pkmn::pokemon::DEFAULT_TRAINER_NAME;
}}
#endif /* CPP_WRAPPERS_POKEMON_HPP */
| 27.084337 | 90 | 0.453588 | ncorgan |
27ab6eb974d421324d24ad2527fcb0c1b80f652c | 1,711 | cpp | C++ | main.cpp | thirdkindgames/thread_context | 715ba7a7a8be11f3806b85828096107cd9eb1619 | [
"Unlicense"
] | null | null | null | main.cpp | thirdkindgames/thread_context | 715ba7a7a8be11f3806b85828096107cd9eb1619 | [
"Unlicense"
] | null | null | null | main.cpp | thirdkindgames/thread_context | 715ba7a7a8be11f3806b85828096107cd9eb1619 | [
"Unlicense"
] | null | null | null | #include <assert.h>
#include <stack>
#include <windows.h>
#include "fiber_job_system.h"
#include "memory_pool.h"
#include "page_allocator.h"
#include "system_memory_pool.h"
#include "thread_context.h"
// Program
void main()
{
// Mem Test
char* x = new char[ 512 ]; // Allocates using the default allocator (the system allocator)
auto pageAllocator = new PageAllocator( 2048 ); // Allocator that doesn't free, just delete the whole allocator when done
ThreadPushMemoryPool( pageAllocator );
char * y = new char[ 256 ]; // This is allocated from the pagePool as can be seen by identitying the allocated value
int * z = new( &g_systemMemoryPool )int; // Ignores the 'current' pool and uses the supplied system allocator instead
ThreadPopMemoryPool( pageAllocator );
delete x; // Deletes from the default allocator (the system allocator)
// Thread Function Table - Uncommenting the next line will use the job thread function table instead so Sleep will call the fiberSleep function instead
//g_threadContext.threadFunctions = g_fiberJobThreadFunctionTable; // This line should be called on the job thread immediately after creation
ThreadSleep( 1000 ); // This call will end up in either StandardThread_Sleep or FiberJobThread_Sleep depending on which function table this thread is using
delete pageAllocator;
}
// Externals and other CUs to make building simpler
SystemMemoryPool g_systemMemoryPool;
#include "fiber_job_system.cpp"
#include "thread_context.cpp" | 45.026316 | 191 | 0.670368 | thirdkindgames |
27aded1679161f1d0eefd20d95a03c012fb6fb36 | 1,013 | cpp | C++ | leetcode-solutions/medium/61 Rotate-List.cpp | jaikarans/coding-solutions | b3cb8251c902d6a8b626fff1a86500249ff7c9e4 | [
"MIT"
] | null | null | null | leetcode-solutions/medium/61 Rotate-List.cpp | jaikarans/coding-solutions | b3cb8251c902d6a8b626fff1a86500249ff7c9e4 | [
"MIT"
] | null | null | null | leetcode-solutions/medium/61 Rotate-List.cpp | jaikarans/coding-solutions | b3cb8251c902d6a8b626fff1a86500249ff7c9e4 | [
"MIT"
] | null | null | null | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
vector <ListNode*> v;
ListNode* tmp = head;
ListNode* headNext;
while (tmp) {
v.push_back(tmp);
tmp = tmp->next;
}
if (v.size() == 0 || k%v.size() == 0)
return head;
else {
// making tmp as new head which is Kth node of linked list
tmp = v[v.size()-k%v.size()];
// making left node's([K-1]th) next pointer NULL because it will be last node.
v[v.size()-k%v.size()-1]->next = NULL;
// pointing last Node to head;
v[v.size()-1]->next = head;
return tmp;
}
}
}; | 28.942857 | 90 | 0.483712 | jaikarans |
27aee6c3b55d0786b7cd4ba9de5fa736f359e3ef | 31,636 | cpp | C++ | src/TraceMin.cpp | ycwu1030/PhaseTransitions | 76bee3915b26025a607a71c372005ea88b3d1389 | [
"MIT"
] | 1 | 2020-06-05T22:59:34.000Z | 2020-06-05T22:59:34.000Z | src/TraceMin.cpp | ycwu1030/PhaseTransitions | 76bee3915b26025a607a71c372005ea88b3d1389 | [
"MIT"
] | null | null | null | src/TraceMin.cpp | ycwu1030/PhaseTransitions | 76bee3915b26025a607a71c372005ea88b3d1389 | [
"MIT"
] | null | null | null | /*
* @Description : Trace the minima of a potential and find critical temperature
*/
#include <iostream>
#include "TraceMin.h"
#include "Phases.h"
#include <tuple>
#include <functional>
#include <algorithm>
#include <gsl/gsl_math.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_roots.h>
using namespace std;
precision_control pre_control;
/*
* @description: Convert from VD to gsl_vector_view
* @param
* vec:
* @return:
* gsl_vector_view
*/
gsl_vector_view Get_GSL_Vector_View(VD &vec)
// * Using reference in order to keep the scope of vec_data from vec, otherwise, the vector_view will loss the value.
{
int Ndim = vec.size();
double *vec_data = vec.data();
return gsl_vector_view_array(vec_data,Ndim);
}
/*
* @description: Get the minimum/maximum eigenvalue of a matrix
* @param:
* mat: VVD
* The matrix which we want to get the eigenvalue
* sort:
* The gsl_eigen_sort_t sort method that sort the eigenvalue
* @return:
* eigmin:
* The minimum eigenvalue (in the sence of the sort method `sort`)
* eigmax:
* The maximum eigenvalue
*/
void Get_Matrix_Eigen(VVD mat_vvd, gsl_eigen_sort_t sort, double &eigmin, double &eigmax)
{
int Ndim = mat_vvd.size();
double *M0_data = new double[Ndim*Ndim];
for (int i = 0; i < Ndim; i++)
{
for (int j = 0; j < Ndim; j++)
{
M0_data[i*Ndim+j] = mat_vvd[i][j];
}
}
gsl_matrix_view mat = gsl_matrix_view_array(M0_data,Ndim,Ndim);
gsl_vector *eval = gsl_vector_alloc(Ndim);
gsl_matrix *evec = gsl_matrix_alloc(Ndim,Ndim);//Just used for sorting
gsl_eigen_symmv_workspace *w = gsl_eigen_symmv_alloc(Ndim);
gsl_eigen_symmv(&mat.matrix,eval,evec,w);
gsl_eigen_symmv_sort(eval,evec,sort);
eigmin = gsl_vector_get(eval,0);
eigmax = gsl_vector_get(eval,Ndim-1);
gsl_vector_free(eval);
gsl_matrix_free(evec);
gsl_eigen_symmv_free(w);
delete []M0_data;
}
// * The structure used to pass to following wrap function.
struct fdf_for_min
{
ScalarFunction f;
dScalarFunction df_dx;
double t;
};
/*
* @description: The wrap function that need to be minimized. The true function that is minimized (as well as other parameters) is passed through param, which is of struct type fdf_for_min.
* @param:
* x:
* The argument of the function
* param:
* The struct fdf_for_min
* @return:
* The value of the function @ x and other parameters in `param`
*/
double f_min_wrap(const gsl_vector *x, void *param)
{
fdf_for_min *pp = (fdf_for_min *)param;
int Ndim = x->size;
double t = pp->t;
VD X(Ndim);
for (int i = 0; i < Ndim; i++)
{
X[i] = gsl_vector_get(x,i);
}
return (pp->f)(X,&t);
}
void df_min_wrap(const gsl_vector *x, void *param, gsl_vector *g)
{
fdf_for_min *pp = (fdf_for_min *)param;
int Ndim = x->size;
double t = pp->t;
VD X(Ndim);
for (int i = 0; i < Ndim; i++)
{
X[i] = gsl_vector_get(x,i);
}
VD res = (pp->df_dx)(X,&t);
for (int i = 0; i < Ndim; i++)
{
gsl_vector_set(g,i,res[i]);
}
}
void fdf_min_wrap(const gsl_vector *x, void *param, double *f, gsl_vector *g)
{
*f = f_min_wrap(x,param);
df_min_wrap(x,param,g);
}
/*
* @description: This function trace one single local minimum
* @param
* f:
* The scalar potential function `f(x,t)` which needs to be
* minimized. The input will be of the same type as `(x0,t0)`
* df_dx, d2f_dxdt, d2f_dx2:
* Functions which return derivatives of `f(x)`.
* `df_dx` return the derivative of `f(x)` repect to `x`
* `d2f_dxdt` return the derivative of the gradient of
* `f(x)` with respect to `t`
* `d2f_dx2` return the Hessian matrix of `f(x)`
* x0:
* The initial value for the fields
* t0:
* The initial value for the temperature
* tstop:
* Stop the trace when `t` reaches `tstop`
* dtstart:
* Initial stepsize in `t`
* deltaX_target:
* The target error in x at each step. Determines the
* stepsize in t by extrapolation from last error.
* dtabsMax: default = 20
* dtfracMax: default = 0.25
* The largest stepsize in t will be the LARGEST of
* ``abs(dtstart)*dtabsMax`` and ``t*dtfracMax``.
* dtmin: default = 1e-3
* The smallest stepsize we'll allow before assuming the
* transition ends,
* relative to `dtstart`
* deltaX_tol: default = 1.2
* ``deltaX_tol*deltaX_target`` gives the maximum error in x
* before we want to shrink the stepsize and recalculate the
* minimum
* minratio: default = 1e-4
* The smallest ratio between smallest and largest eigenvalues
* in the Hessian Matrix before treating the smallest
* eigenvalue as zero (and thus signaling a saddle point and
* the end of the minimum)
* @return: _traceMinimum_rval structure
* X, T, dXdT:
* Arrays of the minimum at different values of t,
* and its derivative with respect to t.
* overX:
* The point beyond which the phase seems to disappear
* overT:
* The t-value beyond which the phase seems to disappear
*/
_traceMinimum_rval traceMinimum(ScalarFunction f, dScalarFunction df_dx, dScalarFunction d2f_dxdt, HM d2f_dx2, VD x0, double t0, double tstop, double dtstart/*, double deltaX_target, double dtabsMax, double dtfracMax, double dtmin, double deltaX_tol, double minratio*/)
{
#if VERBOSE == 1
printf("traceMinimum t0 = %.6f\n",t0);
#endif
int Ndim = x0.size();
VVD M0_VVD = d2f_dx2(x0,&t0);
double min_abs_eigen, max_abs_eigen;
Get_Matrix_Eigen(M0_VVD,GSL_EIGEN_SORT_ABS_ASC,min_abs_eigen,max_abs_eigen);
// This determine when we treat the matrix is singular
double minratio = abs(min_abs_eigen)/abs(max_abs_eigen) * pre_control.minratio_rel;
// This function determine the dx/dt at minimum point, and also check whether we encounter saddle/maximum point
function<tuple<VD, bool>(VD,double) > dxmindt = [&](VD x, double t){
VVD M1_VVD = d2f_dx2(x,&t);
double *M0_data = new double[Ndim*Ndim];
for (int i = 0; i < Ndim; i++)
{
for (int j = 0; j < Ndim; j++)
{
M0_data[i*Ndim+j] = M1_VVD[i][j];
}
}
gsl_matrix_view M = gsl_matrix_view_array(M0_data,Ndim,Ndim);
VD b_VD = d2f_dxdt(x,&t);
gsl_vector_view b = Get_GSL_Vector_View(b_VD);
gsl_vector *dxdt_tmp = gsl_vector_alloc (Ndim);
int s;
gsl_permutation * p = gsl_permutation_alloc (Ndim);
gsl_linalg_LU_decomp (&M.matrix, p, &s);
gsl_linalg_LU_solve (&M.matrix, p, &b.vector, dxdt_tmp);
double min_eigen, max_eigen;
Get_Matrix_Eigen(M1_VVD,GSL_EIGEN_SORT_VAL_ASC,min_eigen,max_eigen);
bool isneg = (min_eigen<0 || min_eigen/max_eigen < minratio);
VD dxdt(Ndim);
for (int i = 0; i < Ndim; i++)
{
dxdt[i] = -gsl_vector_get(dxdt_tmp,i);
}
gsl_vector_free(dxdt_tmp);
gsl_permutation_free(p);
delete []M0_data;
return make_tuple(dxdt, isneg);
};
const double xeps = pre_control.deltaX_target*1e-2;
function<VD(VD, double)> f_argmin = [&](VD x, double t){
const gsl_multimin_fdfminimizer_type *T = gsl_multimin_fdfminimizer_conjugate_fr;
gsl_multimin_fdfminimizer *s = gsl_multimin_fdfminimizer_alloc(T, Ndim);
gsl_multimin_function_fdf minex_func;
gsl_vector_view X = gsl_vector_view_array(x.data(),Ndim);
minex_func.n = Ndim;
minex_func.f = f_min_wrap;
minex_func.df = df_min_wrap;
minex_func.fdf = fdf_min_wrap;
fdf_for_min par = {.f = f, .df_dx = df_dx, .t = t};
minex_func.params = (void *)∥
gsl_multimin_fdfminimizer_set(s, &minex_func, &X.vector, xeps*1e-1,xeps);
int iter = 0;
int status;
do
{
iter++;
status = gsl_multimin_fdfminimizer_iterate(s);
if (status)
{
break;
}
status = gsl_multimin_test_gradient(s->gradient, xeps);
} while (status == GSL_CONTINUE && iter < 100);
VD res(x);
if (status == GSL_SUCCESS || status == GSL_ENOPROG)
{
#if VERBOSE == 2
cout<<"status: "<<status<<"; [";
#endif
for (int i = 0; i < Ndim; i++)
{
res[i] = gsl_vector_get(s->x,i);
#if VERBOSE == 2
cout<<res[i]<<",";
#endif
}
#if VERBOSE == 2
cout<<"]"<<endl;
#endif
}
gsl_multimin_fdfminimizer_free(s);
return res;
};
// 1.2 usr_set 1.2 * usr_set
const double deltaX_tol = pre_control.deltaX_tol * pre_control.deltaX_target;
// initial step in t
const double tscale = abs(dtstart);
// 20 * initial step in t
const double dtabsMax = pre_control.dtabsMax*tscale;
// 1e-3 * initial step in t
const double dtmin = pre_control.dtmin * tscale;
VD x = f_argmin(x0,t0); // Re-find the minimum point to make sure it is the local minimum.
double t = t0;
double dt = dtstart;
double xerr = 0.0;
VD dxdt;
bool negeig;
tie(dxdt,negeig) = dxmindt(x,t);
VVD X; // Store the minimum points
VD T; // Store the temperature at each point
VVD dXdT; // Store the dX/dT at each point
// ! push in the first point
X.push_back(x);
T.push_back(t);
dXdT.push_back(dxdt);
VD overX;
double overT = -11;
double tnext;
VD xnext;
VD dxdt_next;
// int index=0;
#if VERBOSE == 2
int index = 0;
cout<<">>The tracing History:"<<endl;
cout<<">> Starting at: T="<<t<<", [";
for (size_t i = 0; i < x.size(); i++)
{
cout<<x[i]<<",";
}
cout<<"]"<<endl;
#endif
while (true)
{
// index++;
#if VERBOSE == 1
cout<<".";//<<endl;
cout.flush();
#endif
// ! Get the values at the next step
tnext = t+dt;
xnext = f_argmin(x+dxdt*dt,tnext);
tie(dxdt_next, negeig) = dxmindt(xnext,tnext);
#if VERBOSE == 2
index++;
cout<<">>>>Step-"<<index<<endl;
cout<<">>>>>> T="<<tnext<<" ,X=[";
for (size_t itemp = 0; itemp < xnext.size(); itemp++)
{
cout<<xnext[itemp]<<",";
}
cout<<"], dXdT=[";
for (size_t itemp = 0; itemp < xnext.size(); itemp++)
{
cout<<dxdt_next[itemp]<<",";
}
cout<<"], negeig="<<negeig<<endl;
#endif
if (negeig)
{
// ! If negeig is true from dxmindt, that means, (xnext, tnext) already become saddle/maximum point, so we need to shrink the step and try again. And at most, at tnext and xnext, this phase will disappear, becoming saddle/maximum point
dt *= 0.5;
overX = xnext;
overT = tnext;
}
else
{
// ! The step might still be too big if it's outside of our error tolerance.
xerr = sqrt(max((x+dxdt*dt - xnext)*(x+dxdt*dt - xnext),(xnext-dxdt_next*dt - x)*(xnext-dxdt_next*dt - x)));
if (xerr < deltaX_tol)
{
// ! The step is good, push back the point we got.
T.push_back(tnext);
X.push_back(xnext);
dXdT.push_back(dxdt_next);
if (overT < -10)
{
// ! If we haven't yet encounter a saddle point, we can change the step size to accelerate the trace
// ! The step size is changed according to the current xerr between guessed point and true (from fmin) point and the precision in X we want to achieve.
dt *= pre_control.deltaX_target/(xerr+1e-30);
}
x = xnext;
t = tnext;
dxdt = dxdt_next;
overX.clear();
overT = -11;
}
else
{
// ! Either stepsize was too big, or we hit a transition. Just cut the step in half.
dt *= 0.5;
overX = xnext;
overT = tnext;
}
}
if (abs(dt) < abs(dtmin))
{
break;
}
if ((dt > 0 && t >= tstop) || (dt < 0 && t <= tstop))
{
dt = tstop-t;
x = f_argmin(x+dxdt*dt, tstop);
tie(dxdt,negeig) = dxmindt(x,tstop);
t = tstop;
X[X.size()-1] = x;
T[T.size()-1] = t;
dXdT[dXdT.size()-1] = dxdt;
overX.clear();
overT = -11; //! As we hit the stop point, no over point, or you can also say the over point is the last point, which will be set after the loop in the following.
break;
}
double dtmax = max(t*pre_control.dtfracMax, dtabsMax);
if (abs(dt) > dtmax)
{
dt = abs(dt)/dt*dtmax;
}
}
if (overT < -10)
{
overX = X[X.size()-1];
overT = T[T.size()-1];
}
#if VERBOSE == 1
cout<<endl;
#endif
return {X, T, dXdT, overX, overT};
}
/*
* @description: This function tries to find all phases for one potential
* @param
* f:
* The potential that we want to find all phases
* df_dx, d2f_dxdt, d2f_dx2:
* The derivatives of the potential
* points:
* Starting points (can be approximate local minima)
* tLow, tHigh:
* The lowest and highest temperature we want to trace
* deltaX_target:
* The tolerance in minimization
* dtstart: default 1e-3
* The starting step size;
* tjump: default 1e-3
* The jump step size in `t` from the end of one phase
* to another initial tracing point
* fc: default AllPass
* The function determine whether we want to forbid a phase
* @return:
* MP: std::map<int,Phase>
* A map from key => Phase
* The key is unique for each phase.
*/
MP traceMultiMin(ScalarFunction f, dScalarFunction df_dx, dScalarFunction d2f_dxdt, HM d2f_dx2, VT points, double tLow, double tHigh, /*double deltaX_target, double dtstart, double tjump,*/ forbidCrit fc)
{
MP phases;
if (points.size()==0)
{
// ! No point provide, nothing to be started with
return phases;
}
MP::iterator iter;
int Ndim = get<0>(points[0]).size();
const double xeps = pre_control.deltaX_target*1e-2;
function<VD(VD, double)> f_argmin = [&](VD xin, double t){
const gsl_multimin_fdfminimizer_type *T = gsl_multimin_fdfminimizer_conjugate_fr;
gsl_multimin_fdfminimizer *s = gsl_multimin_fdfminimizer_alloc(T, Ndim);
gsl_multimin_function_fdf minex_func;
VD x_start = xin+xeps;
// VD x_start = xin + 0.1;
gsl_vector_view X = gsl_vector_view_array(x_start.data(),Ndim);
minex_func.n = Ndim;
minex_func.f = f_min_wrap;
minex_func.df = df_min_wrap;
minex_func.fdf = fdf_min_wrap;
fdf_for_min par = {.f = f, .df_dx = df_dx, .t = t};
minex_func.params = (void *)∥
gsl_multimin_fdfminimizer_set(s, &minex_func, &X.vector, xeps*0.1,xeps);
int iter = 0;
int status;
do
{
iter++;
status = gsl_multimin_fdfminimizer_iterate(s);
if (status)
{
break;
}
status = gsl_multimin_test_gradient(s->gradient, xeps*1e-3);
} while (status == GSL_CONTINUE && iter < 100);
VD res(Ndim,0);
if (status == GSL_SUCCESS || status == GSL_ENOPROG)
{
for (int i = 0; i < Ndim; i++)
{
res[i] = gsl_vector_get(s->x,i);
}
}
gsl_multimin_fdfminimizer_free(s);
return res;
};
const double dtstart = pre_control.dtstart * (tHigh-tLow);
const double tjump = pre_control.tjump * (tHigh-tLow);
VnT nextPoint;
VD x;
double t;
for (int i = 0; i < points.size(); i++)
{
tie(x,t) = points[i];
nextPoint.push_back(make_tuple(t, dtstart, f_argmin(x,t),-1));
}
VD x1;
double t1, dt1;
int linkedFrom;
int round = 0;
while (nextPoint.size()!=0)
{
#if VERBOSE == 2
round++;
cout<<"At round: "<<round<<endl;
for (size_t i = 0; i < nextPoint.size(); i++)
{
tie(t1,dt1,x1,linkedFrom) = nextPoint[i];
cout<<"Point-"<<i<<" T="<<t1<<", X=[";
for (size_t j = 0; j < x1.size(); j++)
{
cout<<x1[j]<<",";
}
cout<<"]"<<endl;
}
#endif
tie(t1,dt1,x1,linkedFrom) = nextPoint.back();
nextPoint.pop_back();
x1 = f_argmin(x1,t1); // make sure we start as accurately as possible
// * Check the bounds
if ((t1 < tLow) || (t1 == tLow && dt1 < 0))
{
continue;
}
if ((t1 > tHigh) || (t1 == tHigh and dt1 > 0))
{
continue;
}
if (fc(x1))
{
continue;
}
// * Check if it is redundant with another phase
int index;
Phase *ph;
bool covered = false;
for (iter = phases.begin(); iter != phases.end(); ++iter)
{
index = iter->first;
ph = &(iter->second);
if ((t1 < ph->GetTmin()) || t1 > ph->GetTmax())
{
continue;
}
x = f_argmin(ph->valAt(t1),t1);
if (sqrt((x-x1)*(x-x1)) < 2*pre_control.deltaX_target)
{
// * This point is already covered
if (linkedFrom != index && linkedFrom != -1)
{
ph->addLinkFrom(&(phases.at(linkedFrom)));
}
covered = true;
break;
}
}
_traceMinimum_rval down_trace, up_trace;
VVD X_down, X_up, dXdT_down, dXdT_up, X, dXdT;
VD T_down, T_up, nX, T;
double nT;
VD x2;
double t2, dt2;
VVD points;
if (!covered)
{
// * Not covered, Trace the phase
#if VERBOSE == 1
cout<<"...Tracing phase starting at x = (";
for (int ix = 0; ix < x1.size(); ix++)
{
cout<<" "<<x1[ix]<<" ";
}
cout<<"); t = "<<t1<<" ..."<<endl;
#endif
int phase_key = phases.size();
int oldNumPoints = nextPoint.size();
if (t1 > tLow)
{
#if VERBOSE == 1
cout<<"......Tracing minimum down to "<<tLow<<" ......"<<endl;
#endif
down_trace = traceMinimum(f,df_dx,d2f_dxdt, d2f_dx2, x1, t1, tLow, -dt1);
X_down = down_trace.X;
T_down = down_trace.T;
dXdT_down = down_trace.dXdT;
nX = down_trace.overX;
nT = down_trace.overT;
t2 = nT - tjump;
dt2 = 0.1*tjump;
x2 = f_argmin(nX,t2);
nextPoint.push_back(make_tuple(t2,dt2,x2,phase_key));
if (sqrt((X_down.back()-x2)*(X_down.back()-x2))>pow(pre_control.deltaX_target,2))
{
points = findApproxLocalMin(f,X_down.back(),x2,t2);
for (int ipoints = 0; ipoints < points.size(); ipoints++)
{
nextPoint.push_back(make_tuple(t2,dt2,f_argmin(points[ipoints],t2),phase_key));
}
}
reverse(X_down.begin(),X_down.end());
reverse(T_down.begin(),T_down.end());
reverse(dXdT_down.begin(),dXdT_down.end());
}
if (t1 < tHigh)
{
#if VERBOSE == 1
cout<<"......Tracing minimum up to "<<tHigh<<" ......"<<endl;
#endif
up_trace = traceMinimum(f,df_dx,d2f_dxdt,d2f_dx2,x1,t1,tHigh,dt1);
X_up = up_trace.X;
T_up = up_trace.T;
dXdT_up = up_trace.dXdT;
nX = up_trace.overX;
nT = up_trace.overT;
t2 = nT+tjump;
dt2 = 0.1*tjump;
x2 = f_argmin(nX,t2);
nextPoint.push_back(make_tuple(t2,dt2,x2,phase_key));
if (sqrt((X_up.back()-x2)*(X_up.back()-x2))>pow(pre_control.deltaX_target,2))
{
points = findApproxLocalMin(f,X_up.back(),x2,t2);
for (int ipoints = 0; ipoints < points.size(); ipoints++)
{
nextPoint.push_back(make_tuple(t2,dt2,f_argmin(points[ipoints],t2),phase_key));
}
}
}
if (t1 <= tLow)
{
X = X_up;
T = T_up;
dXdT = dXdT_up;
}
else if (t1 >= tHigh)
{
X = X_down;
T = T_down;
dXdT = dXdT_down;
}
else
{
X = VVD(X_down);
X.insert(X.end(),X_up.begin()+1,X_up.end());
T = VD(T_down);
T.insert(T.end(),T_up.begin()+1,T_up.end());
dXdT = VVD(dXdT_down);
dXdT.insert(dXdT.end(),dXdT_up.begin()+1,dXdT_up.end());
}
if (fc(X.front()) || fc(X.back()))
{
nextPoint.resize(oldNumPoints);
}
else if (X.size()>1)
{
Phase newphase(phase_key,X,T,dXdT);
if (linkedFrom >= 0)
{
newphase.addLinkFrom(&(phases.at(linkedFrom)));
}
phases.insert(pair<int, Phase>(phase_key,newphase));
}
else
{
nextPoint.resize(oldNumPoints);
}
}
}
return phases;
}
/*
* @description: Find minima between two points
* @param
* f:
* The function to minimize
* x0,x2:
* The points between which to find minima
* ti:
* The temperature suppling to f
* n:
* Number of points to test for local minima
* edge:
* Determine whether test for minima directly next to input
* points
* edge = 0, do such test
* edge = 0.5 means only test the center point
* @return:
* A list of points that are approximate minima
*/
VVD findApproxLocalMin(ScalarFunction f, VD x0, VD x1, double ti, int n, double edge)
{
if (edge > 0.5)
{
edge = 0.5;
}
VVD res;
VVD points;
bool *test = new bool[n];
double min = edge;
double step = (1.0-2*edge)/(n-1);
for (int i = 0; i < n; i++)
{
points.push_back(x0+(x1-x0)*(min+i*step));
// printf("%d, (%.4f,%.4f), %.5f\n",i,points[i][0],points[i][1],f(points[i],ti));
test[i] = false;
if (i!=0 && i!=n-1)
{
if (f(points[i],&ti)>f(points[i-1],&ti))
{
test[i] = false;
test[i-1] *= true;
}
else
{
test[i] = true;
test[i-1] *= false;
}
if (test[i-1])
{
res.push_back(points[i-1]);
}
}
}
delete []test;
return res;
}
/*
* @description: Remove redundant phases
* @param
* f:
* The potential function which was passed to `traceMultiMin`
* phases:
* The return value of `traceMultiMin`
* xeps: default 1e-5
* The Error tolerance in minimization
* diftol: default 1e-2
* Maximum separation between two phases before
* they are considered to be coincident
* @return:
* directly modify phases
*/
void removeRedundantPhases(ScalarFunction f, dScalarFunction df_dx, MP &phases, double xeps, double diftol)
{
// xeps = 0.1;
function<VD(VD, double)> f_argmin = [&](VD x, double t){
int Ndim = x.size();
const gsl_multimin_fdfminimizer_type *T = gsl_multimin_fdfminimizer_conjugate_fr;
gsl_multimin_fdfminimizer *s = gsl_multimin_fdfminimizer_alloc(T, Ndim);
gsl_multimin_function_fdf minex_func;
VD x_start = x+xeps;
// printf("starting at: %.5f, %.5f\n",x_start[0],x_start[1]);
gsl_vector_view X = gsl_vector_view_array(x_start.data(),Ndim);
minex_func.n = Ndim;
minex_func.f = f_min_wrap;
minex_func.df = df_min_wrap;
minex_func.fdf = fdf_min_wrap;
fdf_for_min par = {.f = f, .df_dx = df_dx, .t = t};
minex_func.params = (void *)∥
gsl_multimin_fdfminimizer_set(s, &minex_func, &X.vector, xeps*0.1,xeps);
int iter = 0;
int status;
do
{
iter++;
status = gsl_multimin_fdfminimizer_iterate(s);
if (status)
{
break;
}
status = gsl_multimin_test_gradient(s->gradient, xeps);
// if (status == GSL_SUCCESS)
// printf ("Minimum found at:\n");
// printf ("%5d %.5f %.5f %10.5f\n", iter,
// gsl_vector_get (s->x, 0),
// gsl_vector_get (s->x, 1),
// s->f);
} while (status == GSL_CONTINUE && iter < 100);
VD res(x);
if (status == GSL_SUCCESS || status == GSL_ENOPROG)
{
for (int i = 0; i < Ndim; i++)
{
res[i] = gsl_vector_get(s->x,i);
}
}
gsl_multimin_fdfminimizer_free(s);
return res;
};
bool has_redundant_phase = true;
MP::iterator iter1;
MP::iterator iter2;
int index1,index2;
int index_low, index_high;
int index_rej;
int newkey;
double tmax,tmin;
double tmax1,tmax2,tmin1,tmin2;
VD x1, x2;
VVD X;
VD T;
VVD dXdT;
double dif;
bool same_at_tmax, same_at_tmin;
while (has_redundant_phase)
{
has_redundant_phase = false;
for (iter1 = phases.begin(); iter1 != phases.end(); iter1++)
{
index1 = iter1->first;
for (iter2 = phases.begin(); iter2 != phases.end(); iter2++)
{
index2 = iter2->first;
// cout<<"----"<<index1<<" "<<index2<<endl;
if (index1 == index2)
{
continue;
}
Phase phase1 = phases.at(index1);
Phase phase2 = phases.at(index2);
tmin1 = phase1.GetTmin();
tmax1 = phase1.GetTmax();
tmin2 = phase2.GetTmin();
tmax2 = phase2.GetTmax();
tmax = min(tmax1,tmax2);
tmin = max(tmin1,tmin2);
if (tmin > tmax)
{
continue;
}
if (tmax == tmax1)
{
x1 = phase1.GetXatTmax();
}
else
{
x1 = f_argmin(phase1.valAt(tmax),tmax);
}
// cout<<"Phase 1 xmax:"<<x1[0]<<" "<<x1[1]<<endl;
if (tmax == tmax2)
{
x2 = phase2.GetXatTmax();
}
else
{
x2 = f_argmin(phase2.valAt(tmax),tmax);
}
// cout<<"Phase 2 xmax:"<<x2[0]<<" "<<x2[1]<<endl;
dif = sqrt((x2-x1)*(x2-x1));
same_at_tmax = (dif < diftol);
if (tmin == tmin1)
{
x1 = phase1.GetXatTmin();
}
else
{
x1 = f_argmin(phase1.valAt(tmin),tmin);
}
// cout<<"Phase 1 xmin:"<<x1[0]<<" "<<x1[1]<<endl;
if (tmin == tmin2)
{
x2 = phase2.GetXatTmin();
}
else
{
x2 = f_argmin(phase2.valAt(tmin),tmin);
}
// cout<<"Phase 2 xmin:"<<x2[0]<<" "<<x2[1]<<endl;
dif = sqrt((x2-x1)*(x2-x1));
same_at_tmin = (dif < diftol);
if (same_at_tmin && same_at_tmax)
{
// * Phases are redundant, need to remove one of them
has_redundant_phase = true;
index_low = tmin1<tmin2?index1:index2;
index_high = tmax1>tmax2?index1:index2;
if (index_low == index_high)
{
index_rej = index_low == index1?index2:index1;
_removeRedundantPhase(phases,index_rej,index_low);
}
else
{
newkey = Phase::GetNPhases();
phases.insert(pair<int, Phase>(newkey,Phase(phase1,phase2)));
_removeRedundantPhase(phases,index_low,newkey);
_removeRedundantPhase(phases,index_high,newkey);
}
break;
}
else if (same_at_tmin || same_at_tmax)
{
cout << "Not Implemented Yet" << endl;
}
}
if (has_redundant_phase)
{
break;
}
}
}
}
/*
* @description: Direct remove the phase, and reset the links
* @param
* phases:
* The phase map
* index_removed:
* The key for the phase need to be removed
* index_phase:
* They key for the phase that is considered to be duplicated with the removed one
* @return:
* Directly modify `phases`
*/
void _removeRedundantPhase(MP &phases,int index_removed, int index_phase)
{
SI low_trans_removed = phases.at(index_removed).GetLowTrans();
SI high_trans_removed = phases.at(index_removed).GetHighTrans();
SI::iterator iter;
for (iter = low_trans_removed.begin(); iter != low_trans_removed.end(); iter++)
{
if (index_phase != (*iter))
{
phases.at(index_phase).addLowTrans(*iter);
phases.at(*iter).eraseHighTrans(index_removed);
phases.at(*iter).addHighTrans(index_phase);
}
}
for (iter = high_trans_removed.begin(); iter != high_trans_removed.end(); iter++)
{
if (index_phase != (*iter))
{
phases.at(index_phase).addHighTrans(*iter);
phases.at(*iter).eraseLowTrans(index_removed);
phases.at(*iter).addLowTrans(index_phase);
}
}
phases.erase(index_removed);
} | 33.512712 | 269 | 0.509831 | ycwu1030 |
27aef24a7ac056d1fd0950cd6b1e13db814f5b83 | 2,428 | hh | C++ | include/G4NRFNuclearLevelStore.hh | jvavrek/NIMB2018 | 0aaf4143db2194b9f95002c681e4f860c8c76f7a | [
"MIT"
] | 4 | 2020-06-28T02:18:53.000Z | 2022-01-17T07:54:31.000Z | include/G4NRFNuclearLevelStore.hh | jvavrek/NIMB2018 | 0aaf4143db2194b9f95002c681e4f860c8c76f7a | [
"MIT"
] | 3 | 2018-08-16T18:49:53.000Z | 2020-10-19T18:04:25.000Z | include/G4NRFNuclearLevelStore.hh | jvavrek/NIMB2018 | 0aaf4143db2194b9f95002c681e4f860c8c76f7a | [
"MIT"
] | null | null | null | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
//
#ifndef G4NRFNuclearLevelStore_hh
#define G4NRFNuclearLevelStore_hh 1
#include <map>
#include <vector>
#include "G4NRFNuclearLevelManager.hh"
class G4NRFNuclearLevel;
class G4NRFNuclearLevelStore {
private:
G4NRFNuclearLevelStore();
public:
static G4NRFNuclearLevelStore* GetInstance();
G4NRFNuclearLevelManager * GetManager(const G4int Z, const G4int A, G4bool standalone = false);
~G4NRFNuclearLevelStore();
private:
G4String GenerateKey(const G4int Z, const G4int A);
G4int GetKeyIndex(const G4int Z, const G4int A);
static std::vector<G4String> theKeys_fast;
static std::vector<G4NRFNuclearLevelManager*> theManagers_fast;
static std::map<G4String, G4NRFNuclearLevelManager*> theManagers;
static G4String dirName;
};
#endif
| 39.803279 | 97 | 0.59514 | jvavrek |
27aefb76dc69488e0458ffb30b71fcdf94edd217 | 864 | hpp | C++ | src/metal-pipeline/include/metal-pipeline/operator_specification.hpp | metalfs/metal_fs | f244d4125622849f36bd7846881a5f3a7efca188 | [
"MIT"
] | 12 | 2020-04-21T05:21:32.000Z | 2022-02-19T11:27:18.000Z | src/metal-pipeline/include/metal-pipeline/operator_specification.hpp | metalfs/metal_fs | f244d4125622849f36bd7846881a5f3a7efca188 | [
"MIT"
] | 10 | 2019-02-10T17:10:16.000Z | 2020-02-01T20:05:42.000Z | src/metal-pipeline/include/metal-pipeline/operator_specification.hpp | metalfs/metal_fs | f244d4125622849f36bd7846881a5f3a7efca188 | [
"MIT"
] | 4 | 2020-07-15T04:42:20.000Z | 2022-02-19T11:27:19.000Z | #pragma once
#include <metal-pipeline/metal-pipeline_api.h>
#include <string>
#include <unordered_map>
#include <metal-pipeline/operator_argument.hpp>
namespace metal {
class METAL_PIPELINE_API OperatorSpecification {
public:
explicit OperatorSpecification(std::string id, const std::string& manifest);
std::string id() const { return _id; }
std::string description() const { return _description; }
uint8_t streamID() const { return _streamID; }
bool prepareRequired() const { return _prepareRequired; }
const std::unordered_map<std::string, OperatorOptionDefinition>
optionDefinitions() const {
return _optionDefinitions;
}
protected:
std::string _id;
std::string _description;
uint8_t _streamID;
bool _prepareRequired;
std::unordered_map<std::string, OperatorOptionDefinition> _optionDefinitions;
};
} // namespace metal
| 25.411765 | 79 | 0.758102 | metalfs |
27b098d055129ec8db52feaeb06fb904b49f0fc2 | 428 | cpp | C++ | Engine/Source/Core/Intersectable/Bvh/BvhIntersectableInfo.cpp | jasonoscar88/Photon-v2 | 90649196c436261d28cc2300511b78ac88236448 | [
"MIT"
] | 88 | 2017-01-21T18:20:16.000Z | 2021-12-21T02:32:04.000Z | Engine/Source/Core/Intersectable/Bvh/BvhIntersectableInfo.cpp | jasonoscar88/Photon-v2 | 90649196c436261d28cc2300511b78ac88236448 | [
"MIT"
] | 72 | 2017-07-28T10:00:35.000Z | 2021-11-09T18:36:23.000Z | Engine/Source/Core/Intersectable/Bvh/BvhIntersectableInfo.cpp | jasonoscar88/Photon-v2 | 90649196c436261d28cc2300511b78ac88236448 | [
"MIT"
] | 8 | 2017-03-19T12:19:10.000Z | 2020-05-19T15:15:05.000Z | #include "Core/Intersectable/Bvh/BvhIntersectableInfo.h"
#include "Core/Intersectable/Intersectable.h"
#include <iostream>
namespace ph
{
BvhIntersectableInfo::BvhIntersectableInfo(
const Intersectable* const intersectable,
const std::size_t index) :
index(index), aabb(), aabbCentroid(), intersectable(intersectable)
{
intersectable->calcAABB(&aabb);
aabbCentroid = aabb.getCentroid();
}
}// end namespace ph | 23.777778 | 67 | 0.759346 | jasonoscar88 |
27b0e47d6ba351a80f5da82c3c167c3f05893d6e | 1,978 | cpp | C++ | Source/NightLight/Core/BaseImpactEffect.cpp | sena0711/NightLight | d7de62c0e731fa42973ac27ab20be7bc99e05688 | [
"Apache-2.0"
] | null | null | null | Source/NightLight/Core/BaseImpactEffect.cpp | sena0711/NightLight | d7de62c0e731fa42973ac27ab20be7bc99e05688 | [
"Apache-2.0"
] | null | null | null | Source/NightLight/Core/BaseImpactEffect.cpp | sena0711/NightLight | d7de62c0e731fa42973ac27ab20be7bc99e05688 | [
"Apache-2.0"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "BaseImpactEffect.h"
#include "PhysicalMaterials/PhysicalMaterial.h"
#include "Kismet/GameplayStatics.h"
#include "Materials/Material.h"
//#include "Components/SceneComponent.h"
//#include "Sound/SoundBase.h"
#include "Components/PrimitiveComponent.h"
#include "Sound/SoundCue.h"
// Sets default values
ABaseImpactEffect::ABaseImpactEffect()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
bAutoDestroyWhenFinished = true;
DecalLifeSpan = 10.0f;
DecalSize = 16.0f;
}
void ABaseImpactEffect::PostInitializeComponents()
{
Super::PostInitializeComponents();
/* Figure out what we hit (SurfaceHit is setting during actor instantiation in weapon class) */
UPhysicalMaterial* HitPhysMat = SurfaceHit.PhysMaterial.Get();
EPhysicalSurface HitSurfaceType = UPhysicalMaterial::DetermineSurfaceType(HitPhysMat);
UParticleSystem* ImpactFX = GetImpactFX(HitSurfaceType);
if (ImpactFX)
{
UGameplayStatics::SpawnEmitterAtLocation(this, ImpactFX, GetActorLocation(), GetActorRotation());
}
USoundCue* ImpactSound = GetImpactSound(HitSurfaceType);
if (ImpactSound)
{
UGameplayStatics::PlaySoundAtLocation(this, ImpactSound, GetActorLocation());
}
if (DecalMaterial)
{
FRotator RandomDecalRotation = SurfaceHit.ImpactNormal.Rotation();
RandomDecalRotation.Roll = FMath::FRandRange(-180.0f, 180.0f);
UGameplayStatics::SpawnDecalAttached(DecalMaterial, FVector(DecalSize, DecalSize, 1.0f),
SurfaceHit.Component.Get(), SurfaceHit.BoneName,
SurfaceHit.ImpactPoint, RandomDecalRotation, EAttachLocation::KeepWorldPosition,
DecalLifeSpan);
}
}
UParticleSystem* ABaseImpactEffect::GetImpactFX(EPhysicalSurface SurfaceType) const
{
return DefaultFX;
}
USoundCue* ABaseImpactEffect::GetImpactSound(EPhysicalSurface SurfaceType) const
{
return nullptr;
} | 29.522388 | 115 | 0.787159 | sena0711 |
27b2961fb467b28a14de8321f475dc26165779db | 723 | cpp | C++ | swig/cpp/tests/transport/inproc.cpp | mwpowellhtx/cppnngswig | 44e4c050b77b83608b440801dd253995c14bd1fc | [
"MIT"
] | null | null | null | swig/cpp/tests/transport/inproc.cpp | mwpowellhtx/cppnngswig | 44e4c050b77b83608b440801dd253995c14bd1fc | [
"MIT"
] | null | null | null | swig/cpp/tests/transport/inproc.cpp | mwpowellhtx/cppnngswig | 44e4c050b77b83608b440801dd253995c14bd1fc | [
"MIT"
] | null | null | null | //
// Copyright (c) 2017 Michael W Powell <mwpowellhtx@gmail.com>
// Copyright 2017 Garrett D'Amore <garrett@damore.org>
// Copyright 2017 Capitar IT Group BV <info@capitar.com>
//
// This software is supplied under the terms of the MIT License, a
// copy of which should be located in the distribution where this
// file was obtained (LICENSE.txt). A copy of the license may also be
// found online at https://opensource.org/licenses/MIT.
//
#include "transport.h"
#include "../catch/catch_tags.h"
namespace constants {
const std::vector<std::string> prefix_tags = { "inproc" };
const std::string test_addr_base = "inproc://test_";
const char port_delim = '\0';
}
void init(const std::string& addr) {}
| 27.807692 | 70 | 0.706777 | mwpowellhtx |
27b5a4972bbff713175558c3a0de9c12ee830474 | 1,487 | cpp | C++ | test/engine/world/scene.t.cpp | numinousgames/tron | 86cd3e5a1f020f0b7f938e1abede8bb29a432dbb | [
"Apache-2.0"
] | null | null | null | test/engine/world/scene.t.cpp | numinousgames/tron | 86cd3e5a1f020f0b7f938e1abede8bb29a432dbb | [
"Apache-2.0"
] | null | null | null | test/engine/world/scene.t.cpp | numinousgames/tron | 86cd3e5a1f020f0b7f938e1abede8bb29a432dbb | [
"Apache-2.0"
] | null | null | null | // scene.t.cpp
#include <engine/world/scene.h>
#include <gtest/gtest.h>
#include "engine/world/mock_tickable.h"
TEST( Scene, Construction )
{
using namespace nge::wrld;
Scene scene;
Scene copy( scene );
Scene moved( std::move( scene ) );
copy = moved;
copy = std::move( moved );
}
TEST( Scene, TickableManagementAndUpdate )
{
using namespace nge::wrld;
using namespace nge::test;
Scene scene;
MockTickable mock;
scene.addTickable( &mock );
scene.update( 10.0f );
ASSERT_EQ( 1, mock.preticks() );
ASSERT_EQ( 1, mock.ticks() );
ASSERT_EQ( 1, mock.posticks() );
ASSERT_EQ( 10.0f, mock.elapsed() );
scene.update( 0.0f );
ASSERT_EQ( 2, mock.preticks() );
ASSERT_EQ( 2, mock.ticks() );
ASSERT_EQ( 2, mock.posticks() );
ASSERT_EQ( 10.0f, mock.elapsed() );
scene.removeTickable( &mock );
mock.reset();
scene.update( 10.0f );
ASSERT_EQ( 0, mock.preticks() );
ASSERT_EQ( 0, mock.ticks() );
ASSERT_EQ( 0, mock.posticks() );
ASSERT_EQ( 0.0f, mock.elapsed() );
scene.addTickable( &mock );
scene.update( 10.0f );
ASSERT_EQ( 1, mock.preticks() );
ASSERT_EQ( 1, mock.ticks() );
ASSERT_EQ( 1, mock.posticks() );
ASSERT_EQ( 10.0f, mock.elapsed() );
scene.removeAll();
scene.update( 10.0f );
ASSERT_EQ( 1, mock.preticks() );
ASSERT_EQ( 1, mock.ticks() );
ASSERT_EQ( 1, mock.posticks() );
ASSERT_EQ( 10.0f, mock.elapsed() );
} | 20.943662 | 42 | 0.60121 | numinousgames |
27b7eaa025acf6383d0b4de7c42b7ebf3b4e55d4 | 8,117 | cpp | C++ | gui_manager.cpp | shlomif/Impatience | 2460ad95f78559a30223112f899d7e8f53c4a4a5 | [
"X11",
"MIT"
] | null | null | null | gui_manager.cpp | shlomif/Impatience | 2460ad95f78559a30223112f899d7e8f53c4a4a5 | [
"X11",
"MIT"
] | null | null | null | gui_manager.cpp | shlomif/Impatience | 2460ad95f78559a30223112f899d7e8f53c4a4a5 | [
"X11",
"MIT"
] | null | null | null | /* Copyright (c) 2012 Ivan Rubinson
*
* 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 "gui_manager.h"
#include "game_manager.h"
namespace GUI
{
bool Manager::window_is_open;
Area Manager::columns;
Area Manager::foundations;
Area Manager::freecells;
int Manager::spacing;
SDL_Surface * Manager::window;
SDL_Surface * Manager::window_background;
Game::Card * Manager::snapped_card;
SDL_Surface * Manager::card_graphic[];
void Manager::Load()
{
Manager::window_is_open = true;
Manager::spacing = 8;
Manager::window = SDL_SetVideoMode(852, 480, 0, SDL_RESIZABLE);
if(Manager::window == NULL)
{
fprintf(stderr, "%s\n", SDL_GetError());
exit(1);
}
Manager::SetBackground("assets/bg.bmp");
for(int s = 0; s < Constants::CARDSUITS_EOF; s++)
{
for(int r = 0; r < Constants::CARDRANKS_EOF; r++)
{
char path[16];
snprintf(path, 16, "assets/%1d_%02d.bmp", s+1, r+1);
Manager::card_graphic[(s * Constants::CARDRANKS_EOF) + r] = SDL_LoadBMP(path);
if(Manager::card_graphic[(s * Constants::CARDRANKS_EOF) + r] == NULL)
{
fprintf(stderr, "%s\n", SDL_GetError());
}
}
}
}
void Manager::Update()
{
Manager::columns.x = Manager::spacing*2;
Manager::columns.y = window->h/3;
Manager::columns.w = window->w - Manager::spacing*2*2;
Manager::columns.h = window->h - window->h/3 - Manager::spacing*2;
Manager::foundations.x = Manager::spacing*2;
Manager::foundations.y = Manager::spacing*2;
Manager::foundations.w = window->w/2 - Manager::spacing*2*2 + Manager::spacing;
Manager::foundations.h = window->h/3 - Manager::spacing*2*2;
Manager::freecells.x = window->w/2 + Manager::spacing;
Manager::freecells.y = Manager::spacing*2;
Manager::freecells.w = window->w/2 - Manager::spacing*2*2 + Manager::spacing;
Manager::freecells.h = window->h/3 - Manager::spacing*2*2;
/* GRAPHICS: */
SDL_FillRect(Manager::window, NULL, 0); // Clear the window of colours
// Render background:
if(Manager::window_background != NULL)
{
SDL_BlitSurface(Manager::window_background, NULL, Manager::window, NULL);
}
// Render cards:
Game::State* state = Game::Manager::GetState();
if(state != NULL)
{
for(int i = 0; i < Constants::FOUNDATIONS; i++)
{
if(state->foundation[i] != NULL && state->foundation[i] != Manager::snapped_card)
{
Manager::RenderCard(0, i, 0, state->foundation[i]);
}
}
for(int i = 0; i < Constants::FREECELLS; i++)
{
if(state->freecell[i] != NULL && state->freecell[i] != Manager::snapped_card)
{
Manager::RenderCard(1, i, 0, state->freecell[i]);
}
}
for(int i = 0; i < Constants::COLUMNS; i++)
{
for(int j = 0; j < Constants::CARDS/Constants::COLUMNS; j++)
{
if(state->column[i][j] != NULL && state->column[i][j] != Manager::snapped_card)
{
Manager::RenderCard(2, j, i, state->column[i][j]);
}
}
}
}
else // state == NULL
{
static int errcount = 1;
if(errcount <= 3)
{
fprintf(stderr, "Game state is uninitialised x%d.\n", errcount);
errcount++;
}
else // errcount > 3
{
fprintf(stderr, "Stopped saying Game state is uninitialised.\n");
}
}
// Render snapped card:
if(Manager::snapped_card != NULL)
{
int x, y;
SDL_GetMouseState(&x, &y);
SDL_Rect r;
r.x = x;
r.y = y;
SDL_BlitSurface(Manager::card_graphic[(Manager::snapped_card->GetSuit() * Constants::CARDRANKS_EOF) + Manager::snapped_card->GetRank()], NULL, Manager::window, &r);
}
SDL_Flip(Manager::window);
}
void Manager::RenderCard(const int type, const int row, const int col, Game::Card * card)
{
if(card == NULL)
{
fprintf(stderr, "RenderCard(...) got an invalid card (arg #4): %x\n", card);
return;
}
SDL_Rect loc;
switch(type)
{
case(0): // foundation
{
break;
}
case(1): // freecell
{
break;
}
case(2): // column
{
break;
}
default:
fprintf(stderr, "RenderCard(...) got an invalid type (arg #1): %d\n", type);
return;
}
SDL_FillRect(Manager::window, &loc, SDL_MapRGB(Manager::window->format, 255, 0, 255));
//SDL_BlitSurface(Manager::card_graphic[(card->GetSuit() * Constants::CARDRANKS_EOF) + card->GetRank()], NULL, Manager::window, &loc);
}
Game::Card * Manager::GetCardAt(const int x, const int y)
{
// TODO: Figure out which card is at x/y, return a pointer to it
return NULL;
}
int Manager::GetZoneAt(const int x, const int y)
{
// TODO: Figure out which zone type (column/foundation/freecell) are the x/y in, and return it.
return -1;
}
int Manager::GetColumnAt(const int x, const int y)
{
// TODO: Figure out which column in GetZoneAt(x, y) the x/y are, and return it.
return -1;
}
void Manager::SnapToCursor(Game::Card * to_snap)
{
Manager::snapped_card = to_snap;
}
void Manager::UnsnapFromCursor()
{
Manager::snapped_card = NULL;
}
bool Manager::WindowIsOpen()
{
return Manager::window_is_open;
}
void Manager::SetBackground(const char* path)
{
Manager::window_background = SDL_LoadBMP(path);
if(Manager::window_background == NULL)
{
fprintf(stderr, "%s", SDL_GetError());
}
}
bool Manager::HandleEvents(const SDL_Event event)
{
if(event.type == SDL_QUIT)
{
Manager::window_is_open = false;
return true;
}
else if(event.type == SDL_VIDEORESIZE)
{
Manager::window = SDL_SetVideoMode(event.resize.w, event.resize.h, 0, SDL_RESIZABLE);
return true;
}
return false;
}
}
| 33.130612 | 177 | 0.52889 | shlomif |
27b82be43355c125f8dc94b99ea1500e2ba04c58 | 346 | hpp | C++ | template/debug.hpp | rogeryoungh/code-of-acm | 3de301444b22e08a9266ecb2e72c3a8ed3014611 | [
"MIT"
] | 1 | 2021-11-25T02:11:49.000Z | 2021-11-25T02:11:49.000Z | template/debug.hpp | rogeryoungh/code-of-acm | 3de301444b22e08a9266ecb2e72c3a8ed3014611 | [
"MIT"
] | null | null | null | template/debug.hpp | rogeryoungh/code-of-acm | 3de301444b22e08a9266ecb2e72c3a8ed3014611 | [
"MIT"
] | null | null | null | #include "template/debug/print.hpp"
pair<int, int> approx(int p, int q, int A) {
int x = q, y = p, a = 1, b = 0;
while (x > A) {
swap(x, y); swap(a, b);
a -= x / y * b;
x %= y;
}
return make_pair(x, a);
}
#ifdef ACM_MOD
pair<int, int> simp(int n, int m = mod) {
return approx(m, n ,1000);
}
#endif
| 18.210526 | 44 | 0.488439 | rogeryoungh |
27b990e961898e03202bbd0ecb432f3e2a2d7c73 | 59 | cpp | C++ | Plugins/ParseXML/Source/ParseXML/Private/SimpleSpline.cpp | dymons/Sumo2Unreal | c0dc6a9552572035535c9081df0006889213179a | [
"MIT"
] | 33 | 2018-10-03T17:05:14.000Z | 2022-03-09T08:10:40.000Z | Plugins/ParseXML/Source/ParseXML/Private/SimpleSpline.cpp | dymons/Sumo2Unreal | c0dc6a9552572035535c9081df0006889213179a | [
"MIT"
] | 7 | 2018-12-06T15:49:18.000Z | 2021-07-27T03:33:11.000Z | Plugins/ParseXML/Source/ParseXML/Private/SimpleSpline.cpp | dymons/Sumo2Unreal | c0dc6a9552572035535c9081df0006889213179a | [
"MIT"
] | 19 | 2019-04-17T05:22:27.000Z | 2021-07-27T03:08:43.000Z | #include "SimpleSpline.h"
SimpleSpline::SimpleSpline() {}; | 19.666667 | 32 | 0.745763 | dymons |
27b99f627bae9a54b10e0fa3479cbde992218694 | 664 | hpp | C++ | include/lol/def/LcdsPayloadDto.hpp | Maufeat/LeagueAPI | be7cb5093aab3f27d95b3c0e1d5700aa50126c47 | [
"BSD-3-Clause"
] | 1 | 2020-07-22T11:14:55.000Z | 2020-07-22T11:14:55.000Z | include/lol/def/LcdsPayloadDto.hpp | Maufeat/LeagueAPI | be7cb5093aab3f27d95b3c0e1d5700aa50126c47 | [
"BSD-3-Clause"
] | null | null | null | include/lol/def/LcdsPayloadDto.hpp | Maufeat/LeagueAPI | be7cb5093aab3f27d95b3c0e1d5700aa50126c47 | [
"BSD-3-Clause"
] | 4 | 2018-12-01T22:48:21.000Z | 2020-07-22T11:14:56.000Z | #pragma once
#include "../base_def.hpp"
namespace lol {
struct LcdsPayloadDto {
std::string method;
std::map<std::string, std::string> headers;
std::string path;
std::string body;
};
inline void to_json(json& j, const LcdsPayloadDto& v) {
j["method"] = v.method;
j["headers"] = v.headers;
j["path"] = v.path;
j["body"] = v.body;
}
inline void from_json(const json& j, LcdsPayloadDto& v) {
v.method = j.at("method").get<std::string>();
v.headers = j.at("headers").get<std::map<std::string, std::string>>();
v.path = j.at("path").get<std::string>();
v.body = j.at("body").get<std::string>();
}
} | 30.181818 | 75 | 0.585843 | Maufeat |
27bd55db8a9046a9a14a30bbe9c7dd6b56b54d99 | 462 | hpp | C++ | source/mat2.hpp | Lucius-sama/programmiersprachen-aufgabenblatt-2 | 35c98e73aece7c490269db35d0bfd595086a473a | [
"MIT"
] | null | null | null | source/mat2.hpp | Lucius-sama/programmiersprachen-aufgabenblatt-2 | 35c98e73aece7c490269db35d0bfd595086a473a | [
"MIT"
] | null | null | null | source/mat2.hpp | Lucius-sama/programmiersprachen-aufgabenblatt-2 | 35c98e73aece7c490269db35d0bfd595086a473a | [
"MIT"
] | null | null | null | #ifndef MAT2_HPP
#define MAT2_HPP
#include<array>
#include <cmath>
#include"vec2.hpp"
struct Mat2 {
float e_00 = 1.0f;
float e_01 = 0.0f;
float e_10 = 0.0f;
float e_11 = 1.0f;
Mat2& operator*=(Mat2 const& m);
float deter() const;
};
Mat2 operator*(Mat2 const& m1, Mat2 const& m2);
Vec2 operator*(Mat2 const& m, Vec2 const& v);
Mat2 inverses(Mat2 const& m);
Mat2 transponierte(Mat2 const& m);
Mat2 rotations_matrix(float phi);
#endif | 18.48 | 47 | 0.668831 | Lucius-sama |
27bf90cd7e52709c04f8b34582765168ac2a5af2 | 2,141 | cpp | C++ | lib/dataset/variable_reduction.cpp | mlund/scipp | 26648fdcda49b21a7aacdafd58625fab7ee3403b | [
"BSD-3-Clause"
] | null | null | null | lib/dataset/variable_reduction.cpp | mlund/scipp | 26648fdcda49b21a7aacdafd58625fab7ee3403b | [
"BSD-3-Clause"
] | null | null | null | lib/dataset/variable_reduction.cpp | mlund/scipp | 26648fdcda49b21a7aacdafd58625fab7ee3403b | [
"BSD-3-Clause"
] | null | null | null | // SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2022 Scipp contributors (https://github.com/scipp)
/// @file
/// @author Simon Heybrock
#include "scipp/dataset/map_view.h"
#include "../variable/operations_common.h"
#include "scipp/variable/arithmetic.h"
#include "scipp/variable/creation.h"
#include "scipp/variable/reduction.h"
#include "scipp/variable/special_values.h"
#include "scipp/variable/transform.h"
#include "scipp/variable/util.h"
#include "dataset_operations_common.h"
namespace scipp::dataset {
Variable sum(const Variable &var, const Dim dim, const Masks &masks) {
if (const auto mask_union = irreducible_mask(masks, dim);
mask_union.is_valid()) {
return sum(where(mask_union, zero_like(var), var), dim);
}
return sum(var, dim);
}
Variable &sum(const Variable &var, const Dim dim, const Masks &masks,
// cppcheck-suppress constParameter # intentional out param
Variable &out) {
if (const auto mask_union = irreducible_mask(masks, dim);
mask_union.is_valid()) {
return sum(where(mask_union, zero_like(var), var), dim, out);
}
return sum(var, dim, out);
}
Variable nansum(const Variable &var, const Dim dim, const Masks &masks) {
if (const auto mask_union = irreducible_mask(masks, dim);
mask_union.is_valid()) {
return nansum(where(mask_union, zero_like(var), var), dim);
}
return nansum(var, dim);
}
Variable mean(const Variable &var, const Dim dim, const Masks &masks) {
if (const auto mask_union = irreducible_mask(masks, dim);
mask_union.is_valid()) {
const auto count = sum(~mask_union, dim);
return mean_impl(where(mask_union, zero_like(var), var), dim, count);
}
return mean(var, dim);
}
Variable nanmean(const Variable &var, const Dim dim, const Masks &masks) {
if (const auto mask_union = irreducible_mask(masks, dim);
mask_union.is_valid()) {
const auto count = sum(
where(mask_union, makeVariable<bool>(Values{false}), ~isnan(var)), dim);
return nanmean_impl(where(mask_union, zero_like(var), var), dim, count);
}
return nanmean(var, dim);
}
} // namespace scipp::dataset
| 32.938462 | 80 | 0.698272 | mlund |
27c0dac61f1aeb9f4c4cb987c46aa74053235b57 | 2,652 | cpp | C++ | day08/08_04_videoDrift/src/ofApp.cpp | ajbajb/ARTTECH3135-spring2019 | ecce35823dbdb37ad6d1071a6e0c290d5d795b2e | [
"MIT"
] | 1 | 2019-01-24T05:03:27.000Z | 2019-01-24T05:03:27.000Z | day08/08_04_videoDrift/src/ofApp.cpp | ajbajb/ARTTECH3135-spring2019 | ecce35823dbdb37ad6d1071a6e0c290d5d795b2e | [
"MIT"
] | null | null | null | day08/08_04_videoDrift/src/ofApp.cpp | ajbajb/ARTTECH3135-spring2019 | ecce35823dbdb37ad6d1071a6e0c290d5d795b2e | [
"MIT"
] | 1 | 2019-04-11T18:26:18.000Z | 2019-04-11T18:26:18.000Z | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup()
{
grabber.setup(640, 480);
gw = grabber.getWidth();
gh = grabber.getHeight();
bufferPix.allocate(gw, gh, OF_PIXELS_RGB);
tex.allocate(gw, gh, GL_RGB);
bufferPix.set(255);
}
//--------------------------------------------------------------
void ofApp::update()
{
grabber.update();
if (grabber.isFrameNew())
{
grabberPix = grabber.getPixels();
for (int x = 0; x < gw; x++)
{
for (int y = 0; y < gh; y++)
{
if (x < gw-1)
{
// get the previous color to the RIGHT of the one you currently on
ofColor prevLeft = bufferPix.getColor(x+1, y);
ofColor current = grabberPix.getColor(x, y);
ofColor lerpedColor = prevLeft.getLerped(current, 0.01);
bufferPix.setColor(x, y, lerpedColor);
}
else
{
ofColor grabberColor = grabberPix.getColor(x,y);
bufferPix.setColor(x, y, grabberColor);
}
}
}
}
tex.loadData(bufferPix);
}
//--------------------------------------------------------------
void ofApp::draw()
{
tex.draw(0, 0);
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 23.678571 | 86 | 0.343514 | ajbajb |
27c434434326a9860e4be3c01c1e5129d6a280f5 | 50 | cpp | C++ | extensions/aasb/platforms/android/modules/aasb-core/src/main/cpp/dummy.cpp | krishnaprasad/alexa-auto-sdk | 2fb8d28a9c4138111f9b19c2527478562acc4643 | [
"Apache-2.0"
] | 122 | 2019-06-26T17:55:52.000Z | 2022-03-25T04:32:28.000Z | extensions/aasb/platforms/android/modules/aasb-core/src/main/cpp/dummy.cpp | krishnaprasad/alexa-auto-sdk | 2fb8d28a9c4138111f9b19c2527478562acc4643 | [
"Apache-2.0"
] | 13 | 2020-12-17T00:32:05.000Z | 2022-03-30T10:45:21.000Z | extensions/aasb/platforms/android/modules/aasb-core/src/main/cpp/dummy.cpp | krishnaprasad/alexa-auto-sdk | 2fb8d28a9c4138111f9b19c2527478562acc4643 | [
"Apache-2.0"
] | 98 | 2019-06-28T08:34:20.000Z | 2022-03-07T23:14:22.000Z | static const char* AASB_CORE_MODULE = "aasb.core"; | 50 | 50 | 0.78 | krishnaprasad |
27c7e278a0ba05774413146ed4b9f8f68c15ebc3 | 1,761 | cpp | C++ | src/Sphere.cpp | nsilvestri/cpp-raytracer | 79336657784f5bd76bb3d15985488bd61255e00b | [
"MIT"
] | 1 | 2021-03-29T09:39:33.000Z | 2021-03-29T09:39:33.000Z | src/Sphere.cpp | nsilvestri/cpp-raytracer | 79336657784f5bd76bb3d15985488bd61255e00b | [
"MIT"
] | 1 | 2021-05-19T05:55:23.000Z | 2021-09-07T14:00:01.000Z | src/Sphere.cpp | nsilvestri/cpp-raytracer | 79336657784f5bd76bb3d15985488bd61255e00b | [
"MIT"
] | null | null | null | #include <iostream>
#include <math.h>
#include "Sphere.hpp"
#include "Vector3D.hpp"
#include "Ray3D.hpp"
#include "IntersectionRecord.hpp"
Sphere::Sphere()
{
}
Sphere::Sphere(Vector3D position, float radius)
{
this->setPosition(position);
this->setRadius(radius);
}
Vector3D Sphere::getPosition() const
{
return this->position;
}
float Sphere::getRadius() const
{
return this->radius;
}
void Sphere::setPosition(Vector3D position)
{
this->position = position;
}
void Sphere::setRadius(float radius)
{
this->radius = radius;
}
bool Sphere::intersect(IntersectionRecord& result, Ray3D ray)
{
// a, b, c are the A, B, C in the quadtratic equation
// a = (d . d)
float a = ray.getDirection().dot(ray.getDirection());
// b = (d . (e - c))
float b = (ray.getDirection() * 2).dot(
ray.getOrigin() - this->getPosition());
// c = (rayPos - center) . (rayPos - center) - R^2
float c = ((ray.getOrigin() - this->getPosition()).dot(
(ray.getOrigin() - this->getPosition()))) -
(this->getRadius() * this->getRadius());
// D = B^2-4AC
float discriminant = (b * b) - (4 * a * c);
if (discriminant < 0)
{
return false;
}
float tPlus = (-b + sqrt(discriminant)) / (2 * a);
float tMinus = (-b - sqrt(discriminant)) / (2 * a);
float t = fmin(tPlus, tMinus);
// point on ray is P(t) = e + td
result.pointOfIntersection = ray.getOrigin() + (ray.getDirection() * t);
result.normalAtIntersection = (result.pointOfIntersection - this->getPosition()) * (1 / this->getRadius());
result.t = t;
result.surfaceIntersected = this;
return true;
} | 24.123288 | 112 | 0.578648 | nsilvestri |
27c8e7abdea4e48fff14c39789b4633ec14f7e0d | 18,739 | cpp | C++ | TextFile/TextFile.cpp | pmachapman/Tulip | 54f7bc3e8d5bb452ed8de6e6622e23d5e9be650a | [
"Unlicense"
] | null | null | null | TextFile/TextFile.cpp | pmachapman/Tulip | 54f7bc3e8d5bb452ed8de6e6622e23d5e9be650a | [
"Unlicense"
] | 33 | 2018-09-14T21:58:20.000Z | 2022-01-12T21:39:22.000Z | TextFile/TextFile.cpp | pmachapman/Tulip | 54f7bc3e8d5bb452ed8de6e6622e23d5e9be650a | [
"Unlicense"
] | null | null | null | /* ==========================================================================
Class : CTextFile
Author : Johan Rosengren, Abstrakt Mekanik AB
Date : 2004-03-22
Purpose : The class is a helper-package for text files and
windows. It allows loading and saving text files in a
single operation, as well as getting text to and
from edit- and listboxes. If an empty filename is given
as a parameter to a call, the standard file dialog will
be displayed, to let the user select a file.
Error handling is managed internally, and the different
API-functions return a "BOOL" to signal success or
failure. In case of failure, "FALSE" returned, the member
function "GetErrorMessage" can be called to retrieve a
"CString" with the error message.
If this string is empty, the file selection was aborted
in the case of an empty input name.
========================================================================*/
#include "stdafx.h"
#include "TextFile.h"
////////////////////////////////////////
// CTextFile construction/destruction
CTextFile::CTextFile(const CString& ext, const CString& eol)
/* ============================================================
Function : CTextFile::CTextFile
Description : Constructor
Access : Public
Return : void
Parameters : const CString& ext - Standard extension
to use in case no
file name is given.
const CString& eol - The end-of-line to
use. Defaults to
'\n'.
Usage : Should normally be created on the stack.
============================================================*/
{
m_extension = ext;
m_eol = eol;
}
CTextFile::~CTextFile()
/* ============================================================
Function : CTextFile::~CTextFile
Description : Destructor
Access : Public
Return : void
Parameters : none
Usage : Should normally be created on the stack.
============================================================*/
{
}
////////////////////////////////////////
// CTextFile operations
//
BOOL CTextFile::ReadTextFile(CString& filename, CStringArray& contents)
/* ============================================================
Function : CTextFile::ReadTextFile
Description : Will read the contents of the file "filename"
into the "CStringArray" "contents", one line
from the file at a time.
If "filename" is empty, the standard file
dialog will be displayed, and - if OK is
selected - "filename" will contain the
selected filename on return.
Access : Public
Return : BOOL - "TRUE" if OK.
"GetErrorMessage"
will contain errors.
Parameters : CString& filename - file to read from
CStringArray& contents - will be filled
with the contents
of the file
Usage : Call to read the contents of a text file
into a "CStringArray".
============================================================*/
{
ClearError();
BOOL result = TRUE;
if (filename.IsEmpty())
result = GetFilename(FALSE, filename);
if (result)
{
CStdioFile file;
CFileException feError;
if (file.Open(filename, CFile::modeRead, &feError))
{
contents.RemoveAll();
CString line;
while (file.ReadString(line))
contents.Add(line);
file.Close();
}
else
{
TCHAR errBuff[256];
feError.GetErrorMessage(errBuff, 256);
m_error = errBuff;
result = FALSE;
}
}
return result;
}
BOOL CTextFile::ReadTextFile(CString& filename, CString& contents)
/* ============================================================
Function : CTextFile::ReadTextFile
Description : Will read the contents of the file "filename"
into "contents".
If "filename" is empty, the standard file
dialog will be displayed, and - if OK is
selected - "filename" will contain the
selected filename on return.
Access : Public
Return : BOOL - "TRUE" if OK.
"GetErrorMessage" will
contain errors.
Parameters : CString& filename - file to read from
CString& contents - will be filled with
the contents of the
file
Usage : Call to read the contents of a text file
into a "CString".
============================================================*/
{
contents = _T("");
// Error handling
ClearError();
CStdioFile file;
CFileException feError;
BOOL result = TRUE;
if (filename.IsEmpty())
{
result = GetFilename(FALSE, filename);
}
if (result)
{
// Reading the file
if (file.Open(filename, CFile::modeRead, &feError))
{
CString line;
while (file.ReadString(line))
{
contents += line + m_eol;
}
file.Close();
}
else
{
// Setting error message
TCHAR errBuff[256];
feError.GetErrorMessage(errBuff, 256);
m_error = errBuff;
result = FALSE;
}
}
return result;
}
BOOL CTextFile::WriteTextFile(CString& filename, const CStringArray& contents)
/* ============================================================
Function : CTextFile::WriteTextFile
Description : Writes "contents" to "filename". Will create
the file if it doesn't already exist,
overwrite it otherwise.
If "filename" is empty, the standard file
dialog will be displayed, and - if OK is
selected - "filename" will contain the
selected filename on return.
Access : Public
Return : BOOL - "TRUE" if OK.
"GetErrorMessage"
will return
errors
Parameters : CString& filename - file to
write to
conste CStringArray& contents - contents
to write
Usage : Call to write the contents of a
"CStringArray" to a text file.
============================================================*/
{
// Error handling
ClearError();
CStdioFile file;
CFileException feError;
BOOL result = TRUE;
if (filename.IsEmpty())
result = GetFilename(TRUE, filename);
if (result)
{
// Write file
if (file.Open(filename, CFile::modeWrite | CFile::modeCreate, &feError))
{
INT_PTR max = contents.GetSize();
for (INT_PTR t = 0; t < max; t++)
file.WriteString(contents[t] + m_eol);
file.Close();
}
else
{
// Set error message
TCHAR errBuff[256];
feError.GetErrorMessage(errBuff, 256);
m_error = errBuff;
result = FALSE;
}
}
return result;
}
BOOL CTextFile::WriteTextFile(CString& filename, const CString& contents)
/* ============================================================
Function : CTextFile::WriteTextFile
Description : Writes "contents" to "filename". Will create
the file if it doesn't already exist,
overwrite it otherwise.
If "filename" is empty, the standard file
dialog will be displayed, and - if OK is
selected - "filename" will contain the
selected filename on return.
Access : Public
Return : BOOL - "TRUE" if OK.
"GetErrorMessage"
will return
errors
Parameters : CString& filename - file to write to
const CString& contents - contents to write
Usage : Call to write the contents of a string to a
text file.
============================================================*/
{
// Error checking
ClearError();
CFile file;
CFileException feError;
BOOL result = TRUE;
if (filename.IsEmpty())
result = GetFilename(TRUE, filename);
if (result)
{
// Write the file
if (file.Open(filename, CFile::modeWrite | CFile::modeCreate, &feError))
{
file.Write(CStringA(contents), contents.GetLength());
file.Close();
}
else
{
// Set error message
TCHAR errBuff[256];
feError.GetErrorMessage(errBuff, 256);
m_error = errBuff;
result = FALSE;
}
}
return result;
}
BOOL CTextFile::AppendFile(CString& filename, const CString& contents)
/* ============================================================
Function : CTextFile::AppendFile
Description : Appends "contents" to "filename". Will create
the file if it doesn't already exist.
If "filename" is empty, the standard file
dialog will be displayed, and - if OK is
selected - "filename" will contain the
selected filename on return.
AppendFile will not add eols.
Access : Public
Return : BOOL - "TRUE" if OK.
"GetErrorMessage"
will return errors
Parameters : CString& filename - file to write to
const CString& contents - contents to write
Usage : Call to append the contents of a string to
a text file.
============================================================*/
{
CFile file;
CFileException feError;
BOOL result = TRUE;
if (filename.IsEmpty())
result = GetFilename(TRUE, filename);
if (result)
{
// Write the file
if (file.Open(filename, CFile::modeWrite | CFile::modeCreate | CFile::modeNoTruncate, &feError))
{
file.SeekToEnd();
file.Write(CStringA(contents), contents.GetLength());
file.Close();
}
else
{
// Set error message
TCHAR errBuff[256];
feError.GetErrorMessage(errBuff, 256);
m_error = errBuff;
result = FALSE;
}
}
return result;
}
BOOL CTextFile::AppendFile(CString& filename, const CStringArray& contents)
/* ============================================================
Function : CTextFile::AppendFile
Description : Appends "contents" to "filename". Will create
the file if it doesn't already exist.
If "filename" is empty, the standard file
dialog will be displayed, and - if OK is
selected - "filename" will contain the
selected filename on return.
Access : Public
Return : BOOL - "TRUE" if OK.
"GetErrorMessage "
will return
errors
Parameters : CString& filename - file to write to
CStringArray contents - contents to write
Usage : Call to append the contents of a
CStringArray to a textfile.
============================================================*/
{
CStdioFile file;
CFileException feError;
BOOL result = TRUE;
if (filename.IsEmpty())
result = GetFilename(TRUE, filename);
if (result)
{
// Write the file
if (file.Open(filename, CFile::modeWrite | CFile::modeCreate | CFile::modeNoTruncate, &feError))
{
file.SeekToEnd();
INT_PTR max = contents.GetSize();
for (INT_PTR t = 0; t < max; t++)
file.WriteString(contents[t] + m_eol);
file.Close();
}
else
{
// Set error message
TCHAR errBuff[256];
feError.GetErrorMessage(errBuff, 256);
m_error = errBuff;
result = FALSE;
}
}
return result;
}
////////////////////////////////////////
// Window operations
//
BOOL CTextFile::Load(CString& filename, CEdit* edit)
/* ============================================================
Function : CTextFile::Load
Description : Loads a text file from "filename" to the
"CEdit" "edit".
If "filename" is empty, the standard file
dialog will be displayed, and - if OK is
selected - "filename" will contain the
selected filename on return.
No translation of eols will be made.
Access : Public
Return : BOOL - "FALSE" if failure.
"GetErrorMessage" will
return the error.
Parameters : CString& filename - name of file to load
CEdit* edit - pointer to "CEdit" to
set text to
Usage : Call to load the contents of a text file
to an editbox.
============================================================*/
{
BOOL result = FALSE;
// Error checking
if (ValidParam(edit))
{
CString contents;
if (ReadTextFile(filename, contents))
{
edit->SetWindowText(contents);
result = TRUE;
}
}
return result;
}
BOOL CTextFile::Load(CString& filename, CListBox* list)
/* ============================================================
Function : CTextFile::Load
Description : Loads a text file from "filename" to the
"CListBox" "list".
If "filename" is empty, the standard file
dialog will be displayed, and - if OK is
selected - "filename" will contain the
selected filename on return.
Access : Public
Return : BOOL - "FALSE" if failure.
"GetErrorMessage" will
return the error.
Parameters : CString& filename - name of file to load
CListBox* list - pointer to "CListBox"
to set text to
Usage : Call to load the contents of a texfile to a
listbox.
============================================================*/
{
BOOL result = FALSE;
// Error checking
if (ValidParam(list))
{
// Read the file
CStringArray contents;
if (ReadTextFile(filename, contents))
{
// Set to listbox
INT_PTR max = contents.GetSize();
for (INT_PTR t = 0; t < max; t++)
if (contents[t].GetLength())
list->AddString(contents[t]);
result = TRUE;
}
}
return result;
}
BOOL CTextFile::Save(CString& filename, CEdit* edit)
/* ============================================================
Function : CTextFile::Save
Description : Saves the contents of the "CEdit" "edit" to the
file "filename". The file will be created or
overwritten.
If "filename" is empty, the standard file
dialog will be displayed, and - if OK is
selected - "filename" will contain the
selected filename on return.
Note that the eol-markers from the editbox
will be used.
Access : Public
Return : BOOL - "FALSE" if failure.
"GetErrorMessage" will
return the error.
Parameters : CString& filename - name of file to save
to. Will be
overwritten
CEdit* edit - pointer to "CEdit" to
get text from
Usage : Call to save the contents of an editbox to
a text file.
============================================================*/
{
BOOL result = FALSE;
// Error checking
if (ValidParam(edit))
{
// Get text
CString contents;
edit->GetWindowText(contents);
// Write file
if (WriteTextFile(filename, contents))
result = TRUE;
}
return result;
}
BOOL CTextFile::Save(CString& filename, CListBox* list)
/* ============================================================
Function : CTextFile::Save
Description : Saves the contents of the "CListBox" "list" to
the file "filename". The file will be created
or overwritten.
If "filename" is empty, the standard file
dialog will be displayed, and - if OK is
selected - "filename" will contain the
selected filename on return.
Access : Public
Return : BOOL - "FALSE" if failure.
"GetErrorMessage" will
return the error.
Parameters : CString& filename - name of file to save
to. Will be
overwritten
CListBox* list - pointer to "CListBox"
to get text from
Usage : Call to save the contents of a listbox to a
file.
============================================================*/
{
BOOL result = FALSE;
// Error checking
if (ValidParam(list))
{
// Get listbox contents
CStringArray contents;
int max = list->GetCount();
for (int t = 0; t < max; t++)
{
CString line;
list->GetText(t, line);
contents.Add(line);
}
// Write file
if (WriteTextFile(filename, contents))
result = TRUE;
}
return result;
}
////////////////////////////////////////
// Error handling
//
CString CTextFile::GetErrorMessage()
/* ============================================================
Function : CTextFile::GetErrorMessage
Description : Gets the error message. Should be called
if any of the file operations return
"FALSE" and the file name is not
empty.
Access : Public
Return : CString - The current error string
Parameters : none
Usage : Call to get the current error message.
============================================================*/
{
return m_error;
}
////////////////////////////////////////
// Private functions
//
void CTextFile::ClearError()
/* ============================================================
Function : CTextFile::ClearError
Description : Clears the internal error string. Should
be called first by all functions setting
the error message string.
Access : Private
Return : void
Parameters : none
Usage : Call to clear the internal error string.
============================================================*/
{
m_error = _T("");
}
BOOL CTextFile::ValidParam(CWnd* wnd)
/* ============================================================
Function : CTextFile::ValidParam
Description : Used to check parameters of the Save/Load
functions. The pointer to the window must
be valid and the window itself must exist.
Access : Private
Return : BOOL - "FALSE" if any parameter
was invalid
Parameters : CWnd* wnd - a window pointer, that
must be valid, to a
window
Usage : Call to check the validity of the feedback
window.
============================================================*/
{
ClearError();
BOOL result = TRUE;
if (wnd == NULL)
{
ASSERT(FALSE);
result = FALSE;
}
if (!IsWindow(wnd->m_hWnd))
{
ASSERT(FALSE);
result = FALSE;
}
if (!result)
m_error = "Bad Window handle as parameter";
return result;
}
BOOL CTextFile::GetFilename(BOOL save, CString& filename)
/* ============================================================
Function : CTextFile::GetFilename
Description : The function will display a standard file
dialog. If the instance is created with an
extension, the extension will be used to
filter files.
Access : Protected
Return : BOOL - "TRUE" if a file was
selected
Parameters : BOOL save - "TRUE" if the file
should be saved.
CString& filename - Placeholder for the
selected filename
Usage : Call to display the standard file dialog.
============================================================*/
{
CString filter;
CString extension = GetExtension();
if (extension.GetLength())
filter = extension + _T("-files (*." + extension + ")|*.") + extension + _T("|All Files (*.*)|*.*||");
BOOL result = FALSE;
CFileDialog dlg(!save, extension, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, filter);
if (dlg.DoModal() == IDOK)
{
filename = dlg.GetPathName();
result = TRUE;
}
return result;
}
CString CTextFile::GetExtension()
/* ============================================================
Function : CTextFile::GetExtension
Description : An accessor for the "m_extension" field.
Access : Protected
Return : CString - the extension.
Parameters : none
Usage : Call to get the default extension of the
files.
============================================================*/
{
return m_extension;
} | 23.780457 | 104 | 0.566946 | pmachapman |
27ca80b6272ba5eb58720a3e31c5d014730c7cd3 | 1,835 | cpp | C++ | test_004.cpp | AlexRogalskiy/cplus | 4f0f78ae2da8857807d4bf8fcef22b3e75696524 | [
"MIT"
] | null | null | null | test_004.cpp | AlexRogalskiy/cplus | 4f0f78ae2da8857807d4bf8fcef22b3e75696524 | [
"MIT"
] | null | null | null | test_004.cpp | AlexRogalskiy/cplus | 4f0f78ae2da8857807d4bf8fcef22b3e75696524 | [
"MIT"
] | null | null | null | //template <class T, template <class> class CheckingPolicy, template <class> class ThreadingModel, template <class> class Storage = DefaultSmartPtrStorage> class SmartPtr : public CheckingPolicy<T>, public ThreadingModel<SmartPtr>, public Storage<T>
//{
// T* operator->()
// {
// typename ThreadingModel<SmartPtr>::Lock guard(*this);
// CheckingPolicy<T>::Check(pointee_);
// return pointee_;
// }
// template <class T1, template <class> class CheckingPolicy1, template <class> class ThreadingModel1, template <class> class Storage1>
// SmartPtr(const SmartPtr<T1, CheckingPolicy1, ThreadingModel1, Storage1>& other) : pointee_(other.pointee_), CheckingPolicy<T>(other), ThreadingModel1<SmartPtr>(other), Storage1<T>(other)
// {
//
// }
// private:
// T* pointee_;
//};
//typedef SmartPrt<Widget, NoChecking, SingleThreaded> WidgetPtr;
//
//template <class T>
//struct NoChecking
//{
// static void Check(T*) {}
//};
//template <class T>
//struct EnforceNotNull
//{
// class NullPointerException : public std::exception
// {
//
// };
// static void Check(T* ptr)
// {
// if(!ptr) throw NullPointerException();
// }
//};
//template <class T>
//struct EnsureNotNull
//{
// static void Check(T*& ptr)
// {
// if(!ptr) ptr = GetDefaultValue();
// }
// private:
// T* GetDefaultValue()
// {
// return;
// }
//};
//template <class T>
//class DefautSmartPtrStorage
//{
//public:
// typedef T* PointerType;
// typedef T& ReferenceType;
//protected:
// PointerType GetPointer()
// {
// return ptr_;
// }
// void SetPointer(PointerType ptr)
// {
// ptr_ = ptr;
// }
//private:
// PointerType ptr_;
//};
//typedef SmartPtr<Winget, RefCounted, NoChecked> WidgetPtr;
| 26.214286 | 249 | 0.615259 | AlexRogalskiy |
27cac3ab4618836b2c4357611d31a49178579e95 | 1,376 | cpp | C++ | Week4/Ex_Curs/main.cpp | cristearadu02/CommandDefense | e8878359b18cedf4c2d3975198fcd661bdff1d8b | [
"MIT"
] | null | null | null | Week4/Ex_Curs/main.cpp | cristearadu02/CommandDefense | e8878359b18cedf4c2d3975198fcd661bdff1d8b | [
"MIT"
] | null | null | null | Week4/Ex_Curs/main.cpp | cristearadu02/CommandDefense | e8878359b18cedf4c2d3975198fcd661bdff1d8b | [
"MIT"
] | null | null | null | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string.h>
#include "Sort.h"
using namespace std;
int main()
{
char c1[] = "209,73,900,85,6";
Sort a(c1); // din sir de caractere
a.Print();
a.BubbleSort();
a.Print();
a.QuickSort();
a.Print();
a.InsertSort();
a.Print();
printf("\n%d\n%d", a.GetElementsCount(), a.GetElementFromIndex(2));
printf("\n");
int v[] = { 101, 202,76, 21,9001, 10,-2, 13 };
int nr = sizeof(v) / sizeof(v[1]);
Sort b(v,nr); // din alt vector
b.Print();
b.BubbleSort();
b.Print();
b.QuickSort();
b.Print();
b.InsertSort();
b.Print();
printf("\n%d\n%d", b.GetElementsCount(), b.GetElementFromIndex(2));
printf("\n");
Sort c(10, -200, 7000); // din interval random
c.Print();
c.BubbleSort();
c.Print();
c.QuickSort();
c.Print();
c.InsertSort();
c.Print();
printf("\n%d\n%d", c.GetElementsCount(), c.GetElementFromIndex(2));
printf("\n");
Sort d(7, -23, 1, -45, 203, 67, 16); // din variadic parameters
d.Print();
d.BubbleSort();
d.Print();
d.QuickSort();
d.Print();
d.InsertSort();
d.Print();
printf("\n%d\n%d", d.GetElementsCount(), d.GetElementFromIndex(2));
printf("\n");
Sort e; // din lista de initializare
e.Print();
e.BubbleSort();
e.Print();
e.QuickSort();
e.Print();
e.InsertSort();
e.Print();
printf("\n%d\n%d", e.GetElementsCount(), e.GetElementFromIndex(2));
return 0;
} | 20.537313 | 68 | 0.617733 | cristearadu02 |
27cc57bc206f0f416f6da50d0b0047a514f44313 | 3,331 | cpp | C++ | test/testGeneric.cpp | borisVanhoof/peafowl | 56f7feb6480fc20052d3077a1b5032f48266dca9 | [
"MIT"
] | null | null | null | test/testGeneric.cpp | borisVanhoof/peafowl | 56f7feb6480fc20052d3077a1b5032f48266dca9 | [
"MIT"
] | null | null | null | test/testGeneric.cpp | borisVanhoof/peafowl | 56f7feb6480fc20052d3077a1b5032f48266dca9 | [
"MIT"
] | null | null | null | /**
* Generic tests.
**/
#include "common.h"
#include <time.h>
TEST(GenericTest, MaxFlows) {
pfwl_state_t* state = pfwl_init();
std::vector<uint> protocols;
pfwl_set_expected_flows(state, 1, PFWL_FLOWS_STRATEGY_SKIP);
uint errors = 0;
getProtocols("./pcaps/whatsapp.pcap", protocols, state, [&](pfwl_status_t status, pfwl_dissection_info_t r){
if(status == PFWL_ERROR_MAX_FLOWS){
++errors;
}
});
EXPECT_GT(errors, 0);
pfwl_terminate(state);
}
TEST(GenericTest, MaxTrials) {
pfwl_state_t* state = pfwl_init();
std::vector<uint> protocols;
pfwl_set_max_trials(state, 1);
getProtocols("./pcaps/imap.cap", protocols, state);
EXPECT_EQ(protocols[PFWL_PROTO_L7_IMAP], 5);
pfwl_terminate(state);
}
TEST(GenericTest, NullState) {
EXPECT_EQ(pfwl_set_expected_flows(NULL, 0, PFWL_FLOWS_STRATEGY_NONE), 1);
EXPECT_EQ(pfwl_set_max_trials(NULL, 0), 1);
EXPECT_EQ(pfwl_defragmentation_enable_ipv4(NULL, 0), 1);
EXPECT_EQ(pfwl_defragmentation_enable_ipv6(NULL, 0), 1);
EXPECT_EQ(pfwl_defragmentation_set_per_host_memory_limit_ipv4(NULL, 0), 1);
EXPECT_EQ(pfwl_defragmentation_set_per_host_memory_limit_ipv6(NULL, 0), 1);
EXPECT_EQ(pfwl_defragmentation_set_total_memory_limit_ipv4(NULL, 0), 1);
EXPECT_EQ(pfwl_defragmentation_set_total_memory_limit_ipv6(NULL, 0), 1);
EXPECT_EQ(pfwl_defragmentation_set_reassembly_timeout_ipv4(NULL, 0), 1);
EXPECT_EQ(pfwl_defragmentation_set_reassembly_timeout_ipv6(NULL, 0), 1);
EXPECT_EQ(pfwl_defragmentation_disable_ipv4(NULL), 1);
EXPECT_EQ(pfwl_defragmentation_disable_ipv6(NULL), 1);
EXPECT_EQ(pfwl_tcp_reordering_enable(NULL), 1);
EXPECT_EQ(pfwl_tcp_reordering_disable(NULL), 1);
EXPECT_EQ(pfwl_protocol_l7_enable(NULL, PFWL_PROTO_L7_BGP), 1);
EXPECT_EQ(pfwl_protocol_l7_disable(NULL, PFWL_PROTO_L7_BGP), 1);
EXPECT_EQ(pfwl_protocol_l7_enable_all(NULL), 1);
EXPECT_EQ(pfwl_protocol_l7_disable_all(NULL), 1);
EXPECT_EQ(pfwl_set_flow_cleaner_callback(NULL, NULL), 1);
EXPECT_EQ(pfwl_field_add_L7(NULL, PFWL_FIELDS_L7_DNS_AUTH_SRV), 1);
EXPECT_EQ(pfwl_field_remove_L7(NULL, PFWL_FIELDS_L7_DNS_AUTH_SRV), 1);
EXPECT_EQ(pfwl_set_protocol_accuracy_L7(NULL, PFWL_PROTO_L7_BGP, PFWL_DISSECTOR_ACCURACY_HIGH), 1);
}
TEST(GenericTest, FieldNamesConversion) {
EXPECT_STREQ(pfwl_get_L7_field_name(PFWL_FIELDS_L7_NUM), "NUM");
EXPECT_STREQ(pfwl_get_L7_field_name(PFWL_FIELDS_L7_HTTP_BODY), "BODY");
EXPECT_EQ(pfwl_get_L7_field_id(PFWL_PROTO_L7_SSL, "CERTIFICATE"), PFWL_FIELDS_L7_SSL_CERTIFICATE);
EXPECT_EQ(pfwl_get_L7_field_id(PFWL_PROTO_L7_HTTP, "URL"), PFWL_FIELDS_L7_HTTP_URL);
}
TEST(GenericTest, ProtoL2NamesConversion) {
EXPECT_STREQ(pfwl_get_L2_protocol_name(PFWL_PROTO_L2_FDDI), "FDDI");
EXPECT_EQ(pfwl_get_L2_protocol_id("EN10MB"), PFWL_PROTO_L2_EN10MB);
}
TEST(GenericTest, ProtoL3NamesConversion) {
EXPECT_STREQ(pfwl_get_L3_protocol_name(PFWL_PROTO_L3_IPV4), "IPv4");
EXPECT_EQ(pfwl_get_L3_protocol_id("IPv6"), PFWL_PROTO_L3_IPV6);
}
TEST(GenericTest, ProtoL4NamesConversion) {
EXPECT_STREQ(pfwl_get_L4_protocol_name(IPPROTO_TCP), "TCP");
EXPECT_EQ(pfwl_get_L4_protocol_id("UDP"), IPPROTO_UDP);
}
TEST(GenericTest, ProtoL7NamesConversion) {
EXPECT_STREQ(pfwl_get_L7_protocol_name(PFWL_PROTO_L7_JSON_RPC), "JSON-RPC");
EXPECT_EQ(pfwl_get_L7_protocol_id("QUIC"), PFWL_PROTO_L7_QUIC);
}
| 40.621951 | 110 | 0.794056 | borisVanhoof |
27d04c21ae8ad74b0fd41881785163136d4bbf7e | 3,535 | hpp | C++ | src/test/test_component_oom.hpp | jmbannon/KerasSynthesized | 50e0275dadd45c5418384186e2541f4db7f5f9ed | [
"MIT"
] | 3 | 2018-10-30T04:10:34.000Z | 2021-09-07T15:19:55.000Z | src/test/test_component_oom.hpp | jmbannon/KerasSynthesized | 50e0275dadd45c5418384186e2541f4db7f5f9ed | [
"MIT"
] | null | null | null | src/test/test_component_oom.hpp | jmbannon/KerasSynthesized | 50e0275dadd45c5418384186e2541f4db7f5f9ed | [
"MIT"
] | null | null | null | #ifndef TEST_CONVOLUTION_OOM_HPP
#define TEST_CONVOLUTION_OOM_HPP
#include "HLS/hls.h"
#include <stdio.h>
#include <math.h>
#include "../tensor3.hpp"
#include "../tensor4.hpp"
#include "../common.hpp"
#include "../component_convolver.hpp"
int test_component_oom_args(uint input_rows,
uint input_cols,
uint input_depth,
uint input_tile_rows,
uint input_tile_cols,
uint input_tile_depth,
uint input_padding_rows,
uint input_padding_cols,
uint output_padding_rows,
uint output_padding_cols) {
Numeric weights[3][3] = {
{ 0.0f, 1.0f, 2.0f },
{ 0.0f, 1.0f, 2.0f },
{ 0.0f, 1.0f, 2.0f }
};
uint kernel_len = 3;
uint input_rows_p = input_rows + (2 * input_padding_cols);
uint input_cols_p = input_cols + (2 * input_padding_cols);
uint output_rows = input_rows_p - kernel_len + 1;
uint output_cols = input_cols_p - kernel_len + 1;
tiled_tensor3 input;
tiled_tensor3_init_padding(&input, input_rows, input_cols, input_depth, input_tile_rows, input_tile_cols, input_tile_depth, ROW_MAJ, ROW_MAJ, input_padding_rows, input_padding_cols);
tiled_tensor3_set_data_sequential_row_padding(&input, input_padding_rows, input_padding_cols);
tiled_tensor3 output;
tiled_tensor3_init_padding(&output, output_rows, output_cols, 1, input_tile_rows, input_tile_cols, input_tile_depth, ROW_MAJ, ROW_MAJ, output_padding_rows, output_padding_cols);
tiled_tensor3_fill_zero(&output);
mm_src mm_src_weights(weights, POW2(kernel_len) * sizeof(Numeric));
mm_src mm_src_input(input.data, input.rows * input.cols * sizeof(Numeric));
mm_src mm_src_output(output.data, output.rows * output.cols * sizeof(Numeric));
return 0;
}
int test_component_oom_tiles_3_2__5_5() {
int rows_t = 3;
int cols_t = 2;
int tile_rows = 5;
int tile_cols = 5;
int rows = tile_rows * rows_t;
int cols = tile_cols * cols_t;
int depth = 1;
return test_component_oom_args(rows, cols, depth, tile_rows, tile_cols, depth, 0, 0, 0, 0);
}
int test_component_oom_5_5() {
Numeric arr_weights[3][3] = {
{ 1.0f, 1.0f, 1.0f },
{ 2.0f, 2.0f, 2.0f },
{ 3.0f, 3.0f, 3.0f }
};
Numeric arr_input[5][5] = {
{ 0.0f, 0.0f, 0.0f, 1.0f, 1.0f },
{ 0.0f, 0.0f, 0.0f, 1.0f, 1.0f },
{ 0.0f, 0.0f, 0.0f, 1.0f, 1.0f },
{ 0.0f, 0.0f, 0.0f, 1.0f, 1.0f },
{ 0.0f, 0.0f, 0.0f, 1.0f, 1.0f }
};
Numeric arr_output[3][3] = {
{ 0.0f, 0.0f, 0.0f },
{ 0.0f, 0.0f, 0.0f },
{ 0.0f, 0.0f, 0.0f }
};
Numeric exp_output[3][3] = {
{ 0.0f, 6.0f, 12.0f },
{ 0.0f, 6.0f, 12.0f },
{ 0.0f, 6.0f, 12.0f }
};
mm_src mm_src_weights(arr_weights, 9 * sizeof(Numeric));
mm_src mm_src_input(arr_input, 25 * sizeof(Numeric));
mm_src mm_src_output(arr_output, 9 * sizeof(Numeric));
tiled_tensor3 in, out;
tiled_tensor3_init_dims(
&in,
5, 5, 1,
5, 5, 1,
ROW_MAJ, ROW_MAJ);
tiled_tensor3_init_dims(
&out,
3, 3, 1,
3, 3, 1,
ROW_MAJ, ROW_MAJ);
convolution9(mm_src_input, mm_src_output, mm_src_weights, in, out, 0, 0, 0, 0, 0);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
// printf("%f %f\n", NUMERIC_VAL(exp_output[i][j]), NUMERIC_VAL(arr_output[i][j]));
if (!fcompare(exp_output[i][j], arr_output[i][j])) {
return 1;
}
}
}
return 0;
}
#endif | 29.214876 | 184 | 0.610184 | jmbannon |
27d051e118c6aaca9f3210335c3162ce99c38c6b | 46,532 | cpp | C++ | src/Parser.cpp | Ibarria/rapid | 866e32bc9b902f5f5814063f1556cfc6b1c697bf | [
"MIT"
] | 8 | 2019-10-25T19:49:27.000Z | 2022-01-25T00:20:29.000Z | src/Parser.cpp | Ibarria/c2 | 866e32bc9b902f5f5814063f1556cfc6b1c697bf | [
"MIT"
] | null | null | null | src/Parser.cpp | Ibarria/c2 | 866e32bc9b902f5f5814063f1556cfc6b1c697bf | [
"MIT"
] | null | null | null | #include "Parser.h"
#include "Lexer.h"
#include "Interpreter.h"
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#ifndef WIN32
# define sprintf_s sprintf
# define vsprintf_s vsnprintf
# define strncpy_s strncpy
#endif
extern bool option_printTokens;
#define NEW_AST(ast_type) (ast_type *) setASTinfo(this, (BaseAST *) new(this->pool) ast_type )
u64 sequence_id = 100;
void copyASTinfo(BaseAST *src, BaseAST *dst)
{
dst->filename = src->filename;
dst->line_num = src->line_num;
dst->char_num = src->char_num;
dst->s = sequence_id++;
dst->scope = src->scope;
}
static BaseAST * setASTloc(Parser *p, BaseAST *ast)
{
SrcLocation loc;
p->lex->getLocation(loc);
ast->line_num = loc.line;
ast->char_num = loc.col;
ast->filename = p->lex->getFilename();
// @TODO: make this an atomic operation
ast->s = sequence_id++;
return ast;
}
static BaseAST * setASTinfo(Parser *p, BaseAST *ast)
{
setASTloc(p, ast);
ast->scope = p->current_scope;
return ast;
}
void Parser::ErrorWithLoc(SrcLocation &loc, const char *msg, ...)
{
va_list args;
s32 off = sprintf(errorString, "%s:%d:%d: error : ", lex->getFilename(),
loc.line, loc.col);
va_start(args, msg);
off += vsprintf(errorString + off, msg, args);
va_end(args);
success = false;
errorString += off;
errorString = lex->getFileData()->printLocation(loc, errorString);
}
void Parser::Error(const char *msg, ...)
{
va_list args;
SrcLocation loc;
lex->getLocation(loc);
s32 off = sprintf(errorString, "%s:%d:%d: error : ", lex->getFilename(),
loc.line, loc.col);
va_start(args, msg);
off += vsprintf(errorString + off, msg, args);
va_end(args);
success = false;
errorString += off;
errorString = lex->getFileData()->printLocation(loc, errorString);
}
bool Parser::MustMatchToken(TOKEN_TYPE type, const char *msg)
{
if (!lex->checkToken(type)) {
if (type == TK_SEMICOLON) {
Token tok;
lex->lookbehindToken(tok);
ErrorWithLoc(tok.loc, "%s - Expected a semicolon after this token\n", msg);
return false;
}
Error("%s - Token %s was expected, but we found: %s\n", msg,
TokenTypeToStr(type), TokenTypeToStr(lex->getTokenType()) );
return false;
}
lex->consumeToken();
return true;
}
bool Parser::AddDeclarationToScope(VariableDeclarationAST * decl)
{
for (auto d : current_scope->decls) {
if (d->varname == decl->varname) {
Error("Variable [%s] is already defined in the scope", decl->varname);
return false;
}
}
current_scope->decls.push_back(decl);
if (!(decl->flags & DECL_FLAG_IS_FUNCTION_ARGUMENT)) {
// argument declarations have their flag set already
if (current_scope->parent == nullptr) {
decl->flags |= DECL_FLAG_IS_GLOBAL_VARIABLE;
} else {
decl->flags |= DECL_FLAG_IS_LOCAL_VARIABLE;
}
}
return true;
}
bool Parser::AddDeclarationToStruct(StructDefinitionAST * struct_def, VariableDeclarationAST * decl)
{
for (auto d : struct_def->struct_type->struct_scope.decls) {
if (d->varname == decl->varname) {
Error("Variable %s is already defined within this struct", decl->varname);
return false;
}
}
struct_def->struct_type->struct_scope.decls.push_back(decl);
decl->scope = &struct_def->struct_type->struct_scope;
decl->flags |= DECL_FLAG_IS_STRUCT_MEMBER;
return true;
}
static bool isIntegerType(BasicType t)
{
return (t == BASIC_TYPE_INTEGER);
}
static bool isFloatType(BasicType t)
{
return (t == BASIC_TYPE_FLOATING);
}
static bool isUnaryPrefixOperator(TOKEN_TYPE type)
{
return (type == TK_PLUS)
|| (type == TK_MINUS)
|| (type == TK_BANG)
|| (type == TK_STAR)
|| (type == TK_LSHIFT);
}
static bool isAssignmentOperator(TOKEN_TYPE type)
{
return (type == TK_ASSIGN)
|| (type == TK_MUL_ASSIGN)
|| (type == TK_DIV_ASSIGN)
|| (type == TK_MOD_ASSIGN)
|| (type == TK_ADD_ASSIGN)
|| (type == TK_SUB_ASSIGN)
|| (type == TK_AND_ASSIGN)
|| (type == TK_XOR_ASSIGN)
|| (type == TK_OR_ASSIGN);
}
static bool isBinOperator(TOKEN_TYPE type)
{
return (type == TK_EQ)
|| (type == TK_LEQ)
|| (type == TK_GEQ)
|| (type == TK_NEQ)
|| (type == TK_LT)
|| (type == TK_GT)
|| (type == TK_STAR)
|| (type == TK_DIV)
|| (type == TK_MOD)
|| (type == TK_PIPE)
|| (type == TK_DOUBLE_PIPE)
|| (type == TK_HAT)
|| (type == TK_AMP)
|| (type == TK_DOUBLE_AMP)
|| (type == TK_PLUS)
|| (type == TK_MINUS);
}
bool isBoolOperator(TOKEN_TYPE type)
{
return (type == TK_EQ)
|| (type == TK_LEQ)
|| (type == TK_GEQ)
|| (type == TK_NEQ)
|| (type == TK_LT)
|| (type == TK_GT);
}
static u32 getPrecedence(TOKEN_TYPE t)
{
switch (t) {
case TK_STAR:
case TK_DIV:
case TK_MOD:
return 1;
case TK_MINUS:
case TK_PLUS:
return 2;
case TK_LT:
case TK_GT:
case TK_LEQ:
case TK_GEQ:
return 4;
case TK_EQ:
case TK_NEQ:
return 5;
case TK_AMP:
return 6;
case TK_HAT:
return 7;
case TK_PIPE:
return 8;
case TK_DOUBLE_AMP:
return 9;
case TK_DOUBLE_PIPE:
return 10;
}
return 0;
}
static bool isBuiltInType(TOKEN_TYPE t)
{
return (t == TK_BOOL)
|| (t == TK_INT)
|| (t == TK_U8)
|| (t == TK_U16)
|| (t == TK_U32)
|| (t == TK_U64)
|| (t == TK_S8)
|| (t == TK_S16)
|| (t == TK_S32)
|| (t == TK_S64)
|| (t == TK_FLOAT)
|| (t == TK_F32)
|| (t == TK_F64)
|| (t == TK_STRING_KEYWORD)
|| (t == TK_VOID);
}
static bool isHexNumber(Token &t)
{
if (t.type == TK_NUMBER) {
return strcmp("0x", t.string) == 0;
}
return false;
}
static f64 computeDecimal(Token &t)
{
assert(t.type == TK_NUMBER);
assert(!isHexNumber(t));
double total = 0;
double divisor = 10;
char *s = t.string;
while (*s != 0) {
float num = (float)(*s - '0');
total += num / divisor;
divisor *= 10;
s++;
}
return total;
}
static struct TypeHelperRec {
TOKEN_TYPE tk;
const char *name;
u64 bytes;
BasicType bt;
bool sign;
DirectTypeAST *ast;
} TypeHelper[] = {
{ TK_VOID, "void", 0, BASIC_TYPE_VOID, false, nullptr },
{ TK_BOOL, "bool", 1, BASIC_TYPE_BOOL, false, nullptr },
{ TK_STRING_KEYWORD, "string", 16, BASIC_TYPE_STRING, false, nullptr },
{ TK_U8, "u8", 1, BASIC_TYPE_INTEGER, false, nullptr },
{ TK_U16, "u16", 2, BASIC_TYPE_INTEGER, false, nullptr },
{ TK_U32, "u32", 4, BASIC_TYPE_INTEGER, false, nullptr },
{ TK_U64, "u64", 8, BASIC_TYPE_INTEGER, false, nullptr },
{ TK_S8, "s8", 1, BASIC_TYPE_INTEGER, true, nullptr },
{ TK_S16, "s16", 2, BASIC_TYPE_INTEGER, true, nullptr },
{ TK_S32, "s32", 4, BASIC_TYPE_INTEGER, true, nullptr },
{ TK_S64, "s64", 8, BASIC_TYPE_INTEGER, true, nullptr },
{ TK_INT, "int", 8, BASIC_TYPE_INTEGER, true, nullptr },
{ TK_F32, "f32", 4, BASIC_TYPE_FLOATING, true, nullptr },
{ TK_F64, "f64", 8, BASIC_TYPE_FLOATING, true, nullptr },
{ TK_FLOAT, "float", 8, BASIC_TYPE_FLOATING, true, nullptr },
{ TK_INVALID, nullptr, 0, BASIC_TYPE_VOID, false, nullptr }
};
DirectTypeAST *getTypeEx(DirectTypeAST *oldtype, u32 newbytes)
{
TypeHelperRec *th;
for (th = TypeHelper; th->name != nullptr; th++) {
if ((th->bt == oldtype->basic_type) && (th->sign == oldtype->isSigned)
&& (th->bytes == newbytes)) {
return th->ast;
}
}
assert(false);
return nullptr;
}
DirectTypeAST *getBuiltInType(TOKEN_TYPE tktype)
{
if ((tktype >= TK_VOID) && (tktype <= TK_FLOAT)) {
return TypeHelper[tktype - TK_VOID].ast;
}
assert(false);
return nullptr;
}
void Parser::defineBuiltInTypes()
{
if (TypeHelper[0].ast != nullptr) return;
TypeHelperRec *th;
for (th = TypeHelper; th->name != nullptr; th++) {
DirectTypeAST *tp;
tp = createType(th->tk, CreateTextType(pool, th->name));
th->ast = tp;
}
assert(TypeHelper[TK_FLOAT - TK_VOID].tk == TK_FLOAT);
}
DirectTypeAST *Parser::createType(TOKEN_TYPE tktype, TextType name)
{
DirectTypeAST *type = (DirectTypeAST *) new(this->pool) DirectTypeAST;
type->s = sequence_id++;
type->name = name;
switch (tktype) {
case TK_VOID:
type->basic_type = BASIC_TYPE_VOID;
type->size_in_bytes = 0; // Basically this can never be a direct type
break;
case TK_BOOL:
type->basic_type = BASIC_TYPE_BOOL;
type->size_in_bytes = 1; // This could change, but enough for now
break;
case TK_STRING_KEYWORD:
type->basic_type = BASIC_TYPE_STRING;
type->size_in_bytes = 8 + 8; // for the pointer to data and the size of the string
break;
case TK_U8:
type->basic_type = BASIC_TYPE_INTEGER;
type->size_in_bytes = 1;
break;
case TK_U16:
type->basic_type = BASIC_TYPE_INTEGER;
type->size_in_bytes = 2;
break;
case TK_U32:
type->basic_type = BASIC_TYPE_INTEGER;
type->size_in_bytes = 4;
break;
case TK_U64:
type->basic_type = BASIC_TYPE_INTEGER;
type->size_in_bytes = 8;
break;
case TK_S8:
type->basic_type = BASIC_TYPE_INTEGER;
type->isSigned = true;
type->size_in_bytes = 1;
break;
case TK_S16:
type->basic_type = BASIC_TYPE_INTEGER;
type->isSigned = true;
type->size_in_bytes = 2;
break;
case TK_S32:
type->basic_type = BASIC_TYPE_INTEGER;
type->isSigned = true;
type->size_in_bytes = 4;
break;
case TK_INT:
case TK_S64:
type->basic_type = BASIC_TYPE_INTEGER;
type->isSigned = true;
type->size_in_bytes = 8;
break;
case TK_F32:
type->basic_type = BASIC_TYPE_FLOATING;
type->size_in_bytes = 4;
type->isSigned = true;
break;
case TK_FLOAT:
case TK_F64:
type->basic_type = BASIC_TYPE_FLOATING;
type->size_in_bytes = 8;
type->isSigned = true;
break;
case TK_IDENTIFIER:
type->basic_type = BASIC_TYPE_CUSTOM;
break;
default:
assert(!"Identifier types, custom types are not implemented");
}
return type;
}
DirectTypeAST *Parser::getType(TOKEN_TYPE tktype, TextType name)
{
if ((tktype >= TK_VOID) && (tktype <= TK_FLOAT)) {
return TypeHelper[tktype - TK_VOID].ast;
}
DirectTypeAST *type = NEW_AST(DirectTypeAST);
type->name = name;
switch (tktype) {
case TK_IDENTIFIER:
type->basic_type = BASIC_TYPE_CUSTOM;
break;
default:
assert(!"Identifier types, custom types are not implemented");
}
return type;
}
TypeAST *Parser::parseDirectType()
{
// @TODO: support pointer, arrays, etc
Token t;
lex->getNextToken(t);
if ((t.type == TK_IDENTIFIER) || isBuiltInType(t.type)) {
return getType(t.type, t.string);
} else if (t.type == TK_STAR) {
// This is a pointer to something
PointerTypeAST *pt = NEW_AST(PointerTypeAST);
pt->points_to_type = parseDirectType();
pt->size_in_bytes = 8;
return pt;
} else if (t.type == TK_OPEN_SQBRACKET) {
// this is an array declaration
// The only supported options are: [] , [..] , [constant number expression]
// option 3 is evaluated at Interpreter time
ArrayTypeAST *at = NEW_AST(ArrayTypeAST);
VariableDeclarationAST *data_decl = NEW_AST(VariableDeclarationAST);
PointerTypeAST *pt = NEW_AST(PointerTypeAST);
pt->points_to_type = nullptr; // will be filled later
pt->size_in_bytes = 8;
data_decl->specified_type = pt;
data_decl->varname = CreateTextType(pool, "data");
at->decls.push_back(data_decl);
VariableDeclarationAST *count_decl = NEW_AST(VariableDeclarationAST);
count_decl->specified_type = getType(TK_U64, nullptr);
count_decl->varname = CreateTextType(pool, "count");
at->decls.push_back(count_decl);
if (lex->checkToken(TK_CLOSE_SQBRACKET)) {
lex->consumeToken();
at->array_type = ArrayTypeAST::SIZED_ARRAY;
} else if (lex->checkToken(TK_DOUBLE_PERIOD)) {
lex->consumeToken();
MustMatchToken(TK_CLOSE_SQBRACKET, "Declaration of array type needs a closed square bracket");
if (!success) {
return nullptr;
}
at->array_type = ArrayTypeAST::DYNAMIC_ARRAY;
VariableDeclarationAST *rsize_decl = NEW_AST(VariableDeclarationAST);
rsize_decl->specified_type = getType(TK_U64, nullptr);
rsize_decl->varname = CreateTextType(pool, "reserved_size");
at->decls.push_back(rsize_decl);
} else {
at->num_expr = parseExpression();
if (!success) {
return nullptr;
}
MustMatchToken(TK_CLOSE_SQBRACKET, "Declaration of array type needs a closed square bracket");
if (!success) {
return nullptr;
}
at->array_type = ArrayTypeAST::STATIC_ARRAY;
}
at->array_of_type = parseType();
if (!success) {
return nullptr;
}
pt->points_to_type = at->array_of_type;
return at;
} else {
if (t.type == TK_STRUCT) {
Error("To declare a struct you need to use the form of <var> := struct { ... }");
} else {
Error("Variable type token could not be found, but we found: %s\n",
TokenTypeToStr(t.type));
}
return nullptr;
}
}
TypeAST * Parser::parseType()
{
if (lex->checkToken(TK_OPEN_PAREN)) {
return parseFunctionDeclaration();
}
return parseDirectType();
}
VariableDeclarationAST *Parser::parseArgumentDeclaration()
{
Token t;
lex->lookaheadToken(t);
VariableDeclarationAST *arg = NEW_AST(VariableDeclarationAST);
MustMatchToken(TK_IDENTIFIER, "Argument declaration needs to start with an identifier");
if (!success) {
return nullptr;
}
arg->varname = t.string;
MustMatchToken(TK_COLON, "Argument declaration needs a colon between identifier and type");
if (!success) {
return nullptr;
}
arg->specified_type = parseType();
if (!success) {
return nullptr;
}
arg->flags |= DECL_FLAG_IS_FUNCTION_ARGUMENT;
return arg;
}
FunctionTypeAST *Parser::parseFunctionDeclaration()
{
MustMatchToken(TK_OPEN_PAREN, "Function declarations need to start with an open parenthesis");
if (!success) {
return nullptr;
}
FunctionTypeAST *fundec = NEW_AST(FunctionTypeAST);
while (!lex->checkToken(TK_CLOSE_PAREN)) {
if (lex->checkToken(TK_DOUBLE_PERIOD)) {
// this is a special argument case, the variable lenght argument
lex->consumeToken();
fundec->hasVariableArguments = true;
if (!lex->checkToken(TK_CLOSE_PAREN)) {
Error("Variable lenght arguments must be the last parameter in a function\n");
return nullptr;
}
continue;
}
VariableDeclarationAST *arg = Parser::parseArgumentDeclaration();
if (!success) {
return nullptr;
}
fundec->arguments.push_back(arg);
if (lex->checkToken(TK_COMMA)) {
lex->consumeToken();
} else if (!lex->checkToken(TK_CLOSE_PAREN)) {
Error("Comma must be used in between parameters in a function\n");
return nullptr;
}
}
lex->consumeToken();
// Now do the return value, which can be empty
if (lex->checkToken(TK_RETURN_ARROW)) {
lex->consumeToken();
fundec->return_type = parseType();
} else {
fundec->return_type = getType(TK_VOID, (char *)"void");
}
if (!success) {
return nullptr;
}
return fundec;
}
ReturnStatementAST *Parser::parseReturnStatement()
{
ReturnStatementAST *ret = NEW_AST(ReturnStatementAST);
MustMatchToken(TK_RETURN);
if (!success) {
return nullptr;
}
ret->ret = parseExpression();
if (!success) {
return nullptr;
}
MustMatchToken(TK_SEMICOLON, "Statement needs to end in semicolon");
if (!success) {
return nullptr;
}
return ret;
}
IfStatementAST * Parser::parseIfStatement()
{
IfStatementAST *ifst = NEW_AST(IfStatementAST);
MustMatchToken(TK_IF);
if (!success) {
return nullptr;
}
ifst->condition = parseExpression();
if (!success) {
return nullptr;
}
ifst->then_branch = parseStatement();
if (!success) {
return nullptr;
}
TOKEN_TYPE cur_type;
cur_type = lex->getTokenType();
if (cur_type == TK_ELSE) {
lex->consumeToken();
ifst->else_branch = parseStatement();
if (!success) {
return nullptr;
}
}
return ifst;
}
static IdentifierAST *checkArrayIterator(ExpressionAST *expr, bool &isPtr)
{
isPtr = false;
if (expr->ast_type == AST_IDENTIFIER) return (IdentifierAST *)expr;
if (expr->ast_type == AST_UNARY_OPERATION) {
auto unop = (UnaryOperationAST *)expr;
if (unop->op != TK_STAR) return nullptr;
if (unop->expr->ast_type == AST_IDENTIFIER) {
isPtr = true;
return (IdentifierAST *)unop->expr;
}
}
return nullptr;
}
ForStatementAST * Parser::parseForStatement()
{
ForStatementAST *forst = NEW_AST(ForStatementAST);
MustMatchToken(TK_FOR);
if (!success) {
return nullptr;
}
forst->is_array = true;
ExpressionAST *expr = parseExpression();
if (!success) {
return nullptr;
}
TOKEN_TYPE cur_type;
cur_type = lex->getTokenType();
switch (cur_type) {
case TK_DOUBLE_PERIOD: {
lex->consumeToken();
// this is the case where we iterate in a range
forst->is_array = false;
forst->start = expr;
forst->end = parseExpression();
if (!success) {
return nullptr;
}
break;
}
case TK_COLON:
case TK_COMMA: {
lex->consumeToken();
// When we see a comma, means we are going to have named iterator and index
forst->it = checkArrayIterator(expr, forst->is_it_ptr);
if (forst->it == nullptr) {
Error("Iterator on the for loop has to be an identifier");
return nullptr;
}
if (forst->it->next) {
Error("Iterator on the for loop has to be a simple identifier");
return nullptr;
}
if (cur_type == TK_COMMA) {
expr = parseExpression();
if (!success) {
return nullptr;
}
if (expr->ast_type != AST_IDENTIFIER) {
Error("Iterator index on the for loop has to be an identifier");
return nullptr;
}
forst->it_index = (IdentifierAST *)expr;
if (forst->it_index->next) {
Error("Iterator index on the for loop has to be a simple identifier");
return nullptr;
}
if (!lex->checkToken(TK_COLON)) {
Error("For loop with iterator and index needs to be followed by \": <array> ");
return nullptr;
}
lex->consumeToken();
}
// Here we parse the range, which can be an array or start .. end
expr = parseExpression();
if (!success) {
return nullptr;
}
if (lex->checkToken(TK_DOUBLE_PERIOD)) {
// we are in a range case
forst->is_array = false;
// first, store the previous expression in start
forst->start = expr;
lex->consumeToken();
forst->end = parseExpression();
if (!success) {
return nullptr;
}
} else {
// the current expression has to refer to an array
if (expr->ast_type != AST_IDENTIFIER) {
Error("For array variable has to be an identifier");
return nullptr;
}
forst->arr = (IdentifierAST *)expr;
}
break;
}
default: {
// We must have seen something that is the for block, so assume expr is the array
if (expr->ast_type != AST_IDENTIFIER) {
Error("For array variable has to be an identifier");
return nullptr;
}
forst->arr = (IdentifierAST *)expr;
if (!success) {
return nullptr;
}
}
}
forst->for_scope.parent = current_scope;
current_scope = &forst->for_scope;
// Assume single array, time to parse a statement
forst->loop_block = parseStatement();
current_scope = current_scope->parent;
if (!success) {
return nullptr;
}
return forst;
}
StatementAST *Parser::parseStatement()
{
TOKEN_TYPE cur_type;
StatementAST *statement = nullptr;
cur_type = lex->getTokenType();
if (cur_type == TK_IDENTIFIER) {
// could be a variable definition or a statement
if (lex->checkAheadToken(TK_COLON,1)
|| lex->checkAheadToken(TK_DOUBLE_COLON, 1)
|| lex->checkAheadToken(TK_IMPLICIT_ASSIGN, 1)) {
statement = parseDeclaration();
} else if (lex->checkAheadToken(TK_OPEN_PAREN, 1)) {
// this is a function call, parse it as such
statement = parseFunctionCall();
if (!success) {
return nullptr;
}
MustMatchToken(TK_SEMICOLON, "Statement needs to end in semicolon");
if (!success) {
return nullptr;
}
} else {
statement = parseAssignmentOrExpression();
if (!success) {
return nullptr;
}
MustMatchToken(TK_SEMICOLON, "Statement needs to end in semicolon");
if (!success) {
return nullptr;
}
}
return statement;
} else if (cur_type == TK_OPEN_BRACKET) {
return parseStatementBlock();
} else if (cur_type == TK_RETURN) {
return parseReturnStatement();
} else if (cur_type == TK_IF) {
return parseIfStatement();
} else if (cur_type == TK_FOR) {
return parseForStatement();
} else if (cur_type == TK_WHILE) {
Error("The `while` statement is not yet supported.\n");
return nullptr;
} else if (cur_type == TK_ELSE) {
Error("Found a mismatched `else`.\n");
return nullptr;
} else {
statement = parseAssignmentOrExpression();
MustMatchToken(TK_SEMICOLON, "Statement needs to end in semicolon");
if (!success) {
return nullptr;
}
return statement;
}
}
StatementBlockAST *Parser::parseStatementBlock(FunctionDefinitionAST *fundef)
{
if (!lex->checkToken(TK_OPEN_BRACKET)) {
Error("We are trying to parse a statement block and it needs to start with an open bracket\n");
return nullptr;
}
lex->consumeToken(); // consume the {
StatementBlockAST *block = NEW_AST(StatementBlockAST);
// push scope
block->block_scope.parent = current_scope;
current_scope = &block->block_scope;
if (fundef) {
current_scope->current_function = fundef;
// if this is the body of a function, register the arguments as variables
for(auto arg:fundef->declaration->arguments) {
AddDeclarationToScope(arg);
arg->scope = current_scope;
}
}
while (!lex->checkToken(TK_CLOSE_BRACKET)) {
StatementAST *statement = nullptr;
statement = parseStatement();
if (!success) {
return nullptr;
}
block->statements.push_back(statement);
if (lex->checkToken(TK_LAST_TOKEN)) {
Error("Failed to find a matching close bracket, open bracket at line %d\n", block->line_num);
if (!success) {
return nullptr;
}
}
}
lex->consumeToken(); // match }
// pop scope
current_scope = current_scope->parent;
return block;
}
FunctionDefinitionAST *Parser::parseFunctionDefinition()
{
FunctionDefinitionAST *fundef = NEW_AST(FunctionDefinitionAST);
fundef->declaration = parseFunctionDeclaration();
if (!success) {
return nullptr;
}
if (isImport && lex->checkToken(TK_FOREIGN)) {
// foreign functions are special, there is no body for them
fundef->declaration->isForeign = true;
lex->consumeToken();
MustMatchToken(TK_SEMICOLON, "Function definitions need to end in semicolon\n");
return fundef;
}
if (!lex->checkToken(TK_OPEN_BRACKET)) {
Error("Function declaration needs to be followed by an implementation {}, found token: %s \n",
TokenTypeToStr(lex->getTokenType()));
return nullptr;
}
// We need to add the declarated variables into the statementBlock
// for the function
fundef->function_body = parseStatementBlock(fundef);
if (!success) {
return nullptr;
}
return fundef;
}
// This is really the declaration...
StructDefinitionAST * Parser::parseStructDefinition()
{
StructDefinitionAST *struct_def = NEW_AST(StructDefinitionAST);
struct_def->struct_type = NEW_AST(StructTypeAST);
Token t;
lex->getNextToken(t);
assert(t.type == TK_STRUCT);
// Add here possible support for SOA or other qualifiers
lex->getNextToken(t);
if (t.type == TK_OPEN_BRACKET) {
while (t.type != TK_CLOSE_BRACKET) {
// now we process the different elements inside the struct, recursively
VariableDeclarationAST *decl = parseDeclaration(true);
if (!success) {
return nullptr;
}
AddDeclarationToStruct(struct_def, decl);
if (!success) {
return nullptr;
}
lex->lookaheadToken(t);
}
// consume the close bracket
lex->consumeToken();
}
return struct_def;
}
FunctionCallAST * Parser::parseFunctionCall()
{
FunctionCallAST *funcall = NEW_AST(FunctionCallAST);
Token t;
lex->getNextToken(t);
assert(t.type == TK_IDENTIFIER);
funcall->function_name = t.string;
MustMatchToken(TK_OPEN_PAREN);
if (!success) {
return nullptr;
}
while (!lex->checkToken(TK_CLOSE_PAREN)) {
ExpressionAST * expr = parseExpression();
if (!success) {
return nullptr;
}
funcall->args.push_back(expr);
if (!lex->checkToken(TK_CLOSE_PAREN)) {
if (lex->checkToken(TK_COMMA)) {
lex->consumeToken();
} else {
Error("Comma must be used to separate function arguments\n");
return nullptr;
}
}
}
MustMatchToken(TK_CLOSE_PAREN);
if (!success) {
return nullptr;
}
return funcall;
}
VarReferenceAST * Parser::parseVarReference()
{
Token t;
lex->getCurrentToken(t);
if (t.type == TK_OPEN_SQBRACKET) {
lex->consumeToken();
// This is an array access
ArrayAccessAST *acc = NEW_AST(ArrayAccessAST);
acc->array_exp = parseExpression();
if (!success) {
return nullptr;
}
MustMatchToken(TK_CLOSE_SQBRACKET, "Cound not find matching close square bracket");
if (!success) {
return nullptr;
}
acc->next = parseVarReference();
if (acc->next) {
acc->next->prev = acc;
}
return acc;
}
if (t.type == TK_PERIOD) {
lex->consumeToken();
// compound statement
StructAccessAST *sac = NEW_AST(StructAccessAST);
lex->getNextToken(t);
if (t.type != TK_IDENTIFIER) {
Error("An identifier must follow after a period access expression");
return nullptr;
}
sac->name = t.string;
sac->next = parseVarReference();
if (sac->next) {
sac->next->prev = sac;
// the scope for a variable reference is that of the enclosing struct
// since we do not yet know it, just null it to be safe
sac->next->scope = nullptr;
}
return sac;
}
// This is not an error, just that the VarReference has ended
return nullptr;
}
ExpressionAST * Parser::parseLiteral()
{
Token t;
lex->getNextToken(t);
if (t.type == TK_IDENTIFIER) {
IdentifierAST *ex = NEW_AST(IdentifierAST);
ex->name = t.string;
ex->next = parseVarReference();
if (ex->next) {
ex->next->prev = ex;
}
return ex;
} else if (t.type == TK_NULL) {
auto nptr = NEW_AST(NullPtrAST);
nptr->expr_type = NEW_AST(NullPtrTypeAST);
nptr->expr_type->size_in_bytes = 8;
return nptr;
} else if ((t.type == TK_NUMBER) || (t.type == TK_TRUE) ||
(t.type == TK_FNUMBER) || (t.type == TK_STRING) || (t.type == TK_FALSE)) {
auto ex = NEW_AST(LiteralAST);
// setASTinfo(this, ex->typeAST);
if (t.type == TK_NUMBER) {
ex->typeAST = getType(TK_U64, nullptr);
//ex->typeAST.basic_type = BASIC_TYPE_INTEGER;
//ex->typeAST.size_in_bytes = 8;
ex->_u64 = t._u64;
} else if (t.type == TK_FNUMBER) {
ex->typeAST = getType(TK_FLOAT, nullptr);
//ex->typeAST.basic_type = BASIC_TYPE_FLOATING;
//ex->typeAST.size_in_bytes = 8;
ex->_f64 = t._f64;
} else if (t.type == TK_STRING) {
ex->typeAST = getType(TK_STRING_KEYWORD, nullptr);
//ex->typeAST.basic_type = BASIC_TYPE_STRING;
//ex->typeAST.size_in_bytes = 8+8;
ex->str = t.string;
} else if (t.type == TK_TRUE) {
ex->typeAST = getType(TK_BOOL, nullptr);
//ex->typeAST.basic_type = BASIC_TYPE_BOOL;
//ex->typeAST.size_in_bytes = 1;
ex->_bool = true;
} else if (t.type == TK_FALSE) {
ex->typeAST = getType(TK_BOOL, nullptr);
//ex->typeAST.basic_type = BASIC_TYPE_BOOL;
//ex->typeAST.size_in_bytes = 1;
ex->_bool = false;
}
return ex;
} else if (t.type == TK_OPEN_PAREN) {
SrcLocation loc;
loc = t.loc;
ExpressionAST *expr = parseExpression();
if (!success) return nullptr;
lex->getNextToken(t);
if (t.type != TK_CLOSE_PAREN) {
Error("Cound not find a matching close parentesis, open parenthesis was at %d:%d\n",
loc.line, loc.col);
if (!success) {
return nullptr;
}
}
return expr;
} else if (t.type == TK_PERIOD) {
// We support period for expressions like `.5`
if (lex->checkAheadToken(TK_NUMBER, 1)) {
lex->getNextToken(t);
if (isHexNumber(t)) {
Error("After a period we need to see normal numbers, not hex numbers");
return nullptr;
}
auto ex = NEW_AST(LiteralAST);
ex->typeAST = getType(TK_FLOAT, nullptr);
ex->_f64 = computeDecimal(t);
return ex;
} else {
Error("Could not parse a literal expression! Unknown token type: %s", TokenTypeToStr(t.type));
return nullptr;
}
}
Error("Could not parse a literal expression! Unknown token type: %s", TokenTypeToStr(t.type));
return nullptr;
}
ExpressionAST * Parser::parseUnaryExpression()
{
Token t;
lex->lookaheadToken(t);
if (t.type == TK_IDENTIFIER) {
if (lex->checkAheadToken(TK_OPEN_PAREN, 1)) {
return parseFunctionCall();
}
} else if (t.type == TK_NEW) {
lex->consumeToken();
NewAllocAST *nast = NEW_AST(NewAllocAST);
nast->type = parseType();
if (!success) return nullptr;
return nast;
} else if (isUnaryPrefixOperator(t.type)) {
lex->consumeToken();
ExpressionAST *expr = parseUnaryExpression();
if (!success) return nullptr;
// optimization, if expr is a real literal, merge the actual value
if (expr->ast_type == AST_LITERAL) {
auto lit = (LiteralAST *)expr;
switch (lit->typeAST->basic_type) {
case BASIC_TYPE_FLOATING:
if (t.type == TK_BANG) {
Error("The bang operator cannot be used with floating point numbers");
return nullptr;
} else if (t.type == TK_MINUS) {
lit->_f64 = -lit->_f64;
return expr;
} else {
assert(t.type == TK_PLUS);
// a plus unary sign can be ignored
return expr;
}
break;
case BASIC_TYPE_BOOL:
if (t.type == TK_BANG) {
lit->_bool = !lit->_bool;
return expr;
} else {
Error("Operator %s cannot be used with boolean types", TokenTypeToStr(t.type));
return nullptr;
}
break;
case BASIC_TYPE_STRING:
Error("The type string does not support unary operators");
return nullptr;
break;
case BASIC_TYPE_INTEGER:
if (t.type == TK_BANG) {
Error("Operator ! cannot be used for integer types");
return nullptr;
//UnaryOperationAST *un = new UnaryOperationAST();
//setASTinfo(this, un);
//un->op = t.type;
//un->expr = expr;
//return un;
} else if (t.type == TK_MINUS) {
if (lit->typeAST->isSigned) {
lit->_s64 = -lit->_s64;
} else {
lit->_s64 = -(s64)lit->_u64;
lit->typeAST = getType(TK_S64, nullptr);
}
return expr;
} else {
assert(t.type == TK_PLUS);
// a plus unary sign can be ignored
return expr;
}
break;
}
}
UnaryOperationAST *un = NEW_AST(UnaryOperationAST);
un->op = t.type;
un->expr = expr;
return un;
} else if (t.type == TK_RUN) {
return parseRunDirective();
}
// @TODO: Handle postfix operators after the parseLiteral
return parseLiteral();
}
ExpressionAST *Parser::parseBinOpExpressionRecursive(u32 oldprec, ExpressionAST *lhs)
{
TOKEN_TYPE cur_type;
while (1) {
cur_type = lex->getTokenType();
if (isBinOperator(cur_type)) {
u32 cur_prec = getPrecedence(cur_type);
if (cur_prec < oldprec) {
return lhs;
} else {
lex->consumeToken();
ExpressionAST *rhs = parseUnaryExpression();
if (isBinOperator(lex->getTokenType())) {
u32 newprec = getPrecedence(lex->getTokenType());
if (cur_prec < newprec) {
rhs = parseBinOpExpressionRecursive(cur_prec + 1, rhs);
}
}
BinaryOperationAST *bin = NEW_AST(BinaryOperationAST);
bin->lhs = lhs;
bin->rhs = rhs;
bin->op = cur_type;
lhs = bin;
}
} else {
break;
}
}
return lhs;
}
ExpressionAST *Parser::parseBinOpExpression()
{
ExpressionAST *lhs = parseUnaryExpression();
return parseBinOpExpressionRecursive( 0, lhs);
}
ExpressionAST * Parser::parseAssignmentOrExpression()
{
ExpressionAST *lhs = parseBinOpExpression();
TOKEN_TYPE type;
type = lex->getTokenType();
if (isAssignmentOperator(type)) {
lex->consumeToken();
AssignmentAST *assign = NEW_AST(AssignmentAST);
assign->lhs = lhs;
assign->op = type;
assign->rhs = parseAssignmentOrExpression();
return assign;
}
return lhs;
}
ExpressionAST * Parser::parseExpression()
{
return parseBinOpExpression();
}
void Parser::parseImportDirective()
{
Token t;
// @TODO: make import be module based with module folders
// and appending extension, as well as figuring out libs to link against
MustMatchToken(TK_IMPORT);
if (!success) return;
lex->getNextToken(t);
if (t.type != TK_STRING) {
Error("When parsing an #import directive, a string needs to follow\n");
return;
}
// import directives can define new functions
// as well as new types, all in global scope / Or the current scope?
// things not allowed on an import
/*
- full function definition? (to be discussed)
- #run directives ?
- #load directive
*/
// things ONLY allowed on an import
/*
- #foreign
-
*/
// this could be done in parallel if needed be
Parser import_parser;
import_parser.isImport = true;
import_parser.interp = interp;
import_parser.current_scope = current_scope;
// All modules are in the modules folder, with the extension
// One day this will be a search path
char fname[64];
sprintf_s(fname, "modules/%s.rad", t.string);
bool val;
// This does the equivalent of pragma once, and also
// records the libraries we opened (#import)
if (!top_level_ast->imports.get(t.string, val)) {
top_level_ast->imports.put(t.string, true);
import_parser.Parse(fname, pool, top_level_ast);
if (!import_parser.success) {
errorString = strcpy(errorString, import_parser.errorStringBuffer);
success = false;
}
}
}
void Parser::parseLoadDirective()
{
Token t;
lex->getNextToken(t);
MustMatchToken(TK_LOAD);
if (!success) return;
lex->getNextToken(t);
if (t.type != TK_STRING) {
Error("When parsing an #load directive, a string needs to follow\n");
return;
}
// load directives can define new functions
// as well as new types, all in global scope / Or the current scope?
// this could be done in parallel if needed be
Parser import_parser;
import_parser.interp = interp;
import_parser.current_scope = current_scope;
import_parser.Parse(t.string, pool, top_level_ast);
if (!import_parser.success) {
errorString = strcpy(errorString, import_parser.errorStringBuffer);
success = false;
}
}
RunDirectiveAST* Parser::parseRunDirective()
{
MustMatchToken(TK_RUN);
// After run, it is an expression in general. Run can appear anywhere, and affect (or not)
// the code and what is parsed.
// if run produces output, it should be inserted (on a separate compilation phase)
ExpressionAST *expr;
expr = parseUnaryExpression();
if (!success) {
return nullptr;
}
RunDirectiveAST *run = NEW_AST(RunDirectiveAST);
run->expr = expr;
// have a list of all run directives to process them later on
// top_level_ast->run_items.push_back(run);
return run;
}
DefinitionAST *Parser::parseDefinition()
{
Token t;
lex->lookaheadToken(t);
if (t.type == TK_OPEN_PAREN) {
bool oneArgument = (lex->checkAheadToken(TK_IDENTIFIER, 1) &&
lex->checkAheadToken(TK_COLON, 2));
bool noArguments = lex->checkAheadToken(TK_CLOSE_PAREN, 1);
if (oneArgument || noArguments) {
// if we encounter a [ ( IDENTIFER : ] sequence, this is
// a function and not an expression, as we do not use the COLON
// for anything else. When functions get more complex, this
// check will be too.
return parseFunctionDefinition();
}
} else if (t.type == TK_STRUCT) {
return parseStructDefinition();
}
return parseExpression();
}
VariableDeclarationAST * Parser::parseDeclaration(bool isStruct)
{
Token t;
lex->getNextToken(t);
VariableDeclarationAST *decl = NEW_AST(VariableDeclarationAST);
if (t.type != TK_IDENTIFIER) {
Error("Identifier expected but not found\n");
return nullptr;
}
decl->varname = t.string;
lex->lookaheadToken(t);
if ((t.type != TK_COLON) &&
(t.type != TK_DOUBLE_COLON) &&
(t.type != TK_IMPLICIT_ASSIGN)) {
Error("Declaration needs a colon, but found token: %s\n", TokenTypeToStr(t.type));
return nullptr;
}
if (t.type == TK_COLON) {
lex->consumeToken();
// we are doing a variable declaration
decl->specified_type = parseType();
if (!success) {
return nullptr;
}
lex->lookaheadToken(t);
}
if (t.type == TK_DOUBLE_COLON) {
decl->flags |= DECL_FLAG_IS_CONSTANT;
}
if ((t.type == TK_ASSIGN) || (t.type == TK_DOUBLE_COLON)
|| (t.type == TK_IMPLICIT_ASSIGN)) {
lex->consumeToken();
// we are doing an assignment or initial value
decl->definition = parseDefinition();
if (!success) {
return nullptr;
}
if (decl->definition->ast_type == AST_FUNCTION_DEFINITION) {
// we want to be able to find the name of the function
auto fundef = (FunctionDefinitionAST *)decl->definition;
fundef->var_decl = decl;
} else if (decl->definition->ast_type == AST_STRUCT_DEFINITION) {
// we need this pointer for C generation ordering
auto sdef = (StructDefinitionAST *)decl->definition;
sdef->struct_type->decl = decl;
}
lex->lookaheadToken(t);
} else if (t.type != TK_SEMICOLON) {
Error("Declaration is malformed, a semicolon was expected");
if (!success) {
return nullptr;
}
}
if (!decl->definition || decl->definition->needsSemiColon) {
// @TODO: support compiler flags and others here
if (t.type != TK_SEMICOLON) {
Error("Declaration needs to end with a semicolon\n");
if (!success) {
return nullptr;
}
}
lex->getNextToken(t);
}
if (!isStruct) {
// struct members do not follow the AddDeclaration to scope
AddDeclarationToScope(decl);
}
return decl;
}
// first version, just return a list of AST
FileAST *Parser::Parse(const char *filename, PoolAllocator *pool, FileAST *fast)
{
Lexer lex;
this->lex = &lex;
this->pool = pool;
CPU_SAMPLE("Parser Main");
lex.setPoolAllocator(pool);
if (errorString == nullptr) {
errorString = errorStringBuffer;
errorString[0] = 0;
}
if (!lex.openFile(filename)) {
errorString += sprintf(errorString, "Error: File [%s] could not be opened to be processed\n", filename);
return nullptr;
}
return ParseInternal(fast);
}
FileAST * Parser::ParseFromString(const char *str, u64 str_size, PoolAllocator *pool, FileAST *fast)
{
Lexer lex;
this->lex = &lex;
this->pool = pool;
CPU_SAMPLE("Parser From String");
lex.setPoolAllocator(pool);
if (errorString == nullptr) {
errorString = errorStringBuffer;
errorString[0] = 0;
}
if (!lex.loadString(str, str_size)) {
errorString += sprintf(errorString, "Error: String could not be loaded to be processed\n");
return nullptr;
}
return ParseInternal(fast);
}
FileAST * Parser::ParseInternal(FileAST *fast)
{
FileAST *file_inst = nullptr;
if (fast != nullptr) {
file_inst = fast;
} else {
file_inst = new (pool) FileAST;
file_inst->global_scope.parent = nullptr;
file_inst->scope = &file_inst->global_scope;
file_inst->filename = CreateTextType(pool, lex->getFileData()->getFilename());
}
top_level_ast = file_inst;
success = true;
if (errorString == nullptr) {
errorString = errorStringBuffer;
}
defineBuiltInTypes();
lex->parseFile();
interp->files.push_back(lex->getFileData());
if (option_printTokens) {
while (!lex->checkToken(TK_LAST_TOKEN)) {
Token t;
lex->getNextToken(t);
t.print();
}
lex->setTokenStreamPosition(0);
}
if (current_scope == nullptr) {
current_scope = &file_inst->global_scope;
}
while (!lex->checkToken(TK_LAST_TOKEN)) {
Token t;
lex->lookaheadToken(t);
if (t.type == TK_IMPORT) {
parseImportDirective();
} else if (t.type == TK_LOAD) {
parseLoadDirective();
} else if (t.type == TK_RUN) {
RunDirectiveAST *r = parseRunDirective();
if (!success) {
return nullptr;
}
// Allow semicolons after a #run directive
lex->lookaheadToken(t);
if (t.type == TK_SEMICOLON) lex->consumeToken();
file_inst->items.push_back(r);
} else {
VariableDeclarationAST *d = parseDeclaration();
if (!success) {
return nullptr;
}
file_inst->items.push_back(d);
}
}
this->lex = nullptr;
return file_inst;
}
| 29.469284 | 112 | 0.572058 | Ibarria |
27d267ead683bc769840aec6e7f7a5acd2b22680 | 1,425 | hpp | C++ | schema_parser/Schema.hpp | josefschmeisser/TardisDB | 0d805c4730533fa37c3668acd592404027b9b0d6 | [
"Apache-2.0"
] | 5 | 2021-01-15T16:59:59.000Z | 2022-02-28T15:41:00.000Z | schema_parser/Schema.hpp | josefschmeisser/TardisDB | 0d805c4730533fa37c3668acd592404027b9b0d6 | [
"Apache-2.0"
] | null | null | null | schema_parser/Schema.hpp | josefschmeisser/TardisDB | 0d805c4730533fa37c3668acd592404027b9b0d6 | [
"Apache-2.0"
] | 1 | 2021-06-22T04:53:38.000Z | 2021-06-22T04:53:38.000Z | #ifndef H_Schema_hpp
#define H_Schema_hpp
#include <vector>
#include <string>
#include <unordered_map>
#include "Types.hpp"
#include <memory>
namespace SchemaParser {
struct Schema {
struct SecondaryIndex {
std::string name;
std::string table;
std::vector<unsigned> attributes;
SecondaryIndex(const std::string & name) : name(name) { }
};
struct Relation {
struct Attribute {
std::string name;
Types::Tag type;
unsigned len;
unsigned len2;
bool notNull;
Attribute() : len(~0), notNull(false) {}
};
std::string name;
std::vector<std::unique_ptr<Schema::Relation::Attribute>> attributes;
std::vector<unsigned> primaryKey;
std::vector<Schema::SecondaryIndex *> secondaryIndices;
Relation(const std::string& name) : name(name) {}
};
std::vector<Schema::Relation> relations;
std::vector<Schema::SecondaryIndex> indices;
std::unordered_multimap<std::string, Relation::Attribute *> attributes;
std::string toString() const;
};
const SchemaParser::Schema & getSchema();
const Schema::Relation & getRelation(const std::string & name);
const Schema::Relation::Attribute * getAttribute(const std::string & name);
const Schema::Relation::Attribute * getAttribute(
const Schema::Relation & rel, const std::string & name);
bool isAttributeName(const std::string & name);
}
#endif
| 25.446429 | 75 | 0.667368 | josefschmeisser |
27d39bfa2b856a1d6bc6d630c33bf409fb69264d | 1,385 | cpp | C++ | DESIRE-Engine/src/Engine/Physics/PhysicsComponent.cpp | nyaki-HUN/DESIRE | dd579bffa77bc6999266c8011bc389bb96dee01d | [
"BSD-2-Clause"
] | 1 | 2020-10-04T18:50:01.000Z | 2020-10-04T18:50:01.000Z | DESIRE-Engine/src/Engine/Physics/PhysicsComponent.cpp | nyaki-HUN/DESIRE | dd579bffa77bc6999266c8011bc389bb96dee01d | [
"BSD-2-Clause"
] | null | null | null | DESIRE-Engine/src/Engine/Physics/PhysicsComponent.cpp | nyaki-HUN/DESIRE | dd579bffa77bc6999266c8011bc389bb96dee01d | [
"BSD-2-Clause"
] | 1 | 2018-09-18T08:03:33.000Z | 2018-09-18T08:03:33.000Z | #include "Engine/stdafx.h"
#include "Engine/Physics/PhysicsComponent.h"
#include "Engine/Physics/ColliderShape.h"
#include "Engine/Physics/Physics.h"
PhysicsComponent::PhysicsComponent(GameObject& object)
: Component(object)
, m_collisionLayer(EPhysicsCollisionLayer::Default)
{
Modules::Physics->OnPhysicsComponentCreated(this);
}
PhysicsComponent::~PhysicsComponent()
{
Modules::Physics->OnPhysicsComponentDestroyed(this);
}
Component& PhysicsComponent::CloneTo(GameObject& otherObject) const
{
PhysicsComponent& newComponent = Modules::Physics->CreatePhysicsComponentOnObject(otherObject);
newComponent.SetCollisionLayer(GetCollisionLayer());
newComponent.SetCollisionDetectionMode(GetCollisionDetectionMode());
newComponent.m_physicsMaterial = GetPhysicsMaterial();
newComponent.SetBodyType(GetBodyType());
newComponent.SetTrigger(IsTrigger());
newComponent.SetMass(GetMass());
newComponent.SetLinearDamping(GetLinearDamping());
newComponent.SetAngularDamping(GetAngularDamping());
newComponent.SetEnabled(IsEnabled());
return newComponent;
}
void PhysicsComponent::SetCollisionLayer(EPhysicsCollisionLayer collisionLayer)
{
m_collisionLayer = collisionLayer;
}
EPhysicsCollisionLayer PhysicsComponent::GetCollisionLayer() const
{
return m_collisionLayer;
}
const PhysicsMaterial& PhysicsComponent::GetPhysicsMaterial() const
{
return m_physicsMaterial;
}
| 28.854167 | 96 | 0.823105 | nyaki-HUN |
27d5c06f468040ac9f7a3fb1a5d1da135cf3b071 | 3,368 | cpp | C++ | Sources/Files/LoadedValue.cpp | hhYanGG/Acid | f5543e9290aee5e25c6ecdafe8a3051054b203c0 | [
"MIT"
] | 1 | 2019-03-13T08:26:38.000Z | 2019-03-13T08:26:38.000Z | Sources/Files/LoadedValue.cpp | hhYanGG/Acid | f5543e9290aee5e25c6ecdafe8a3051054b203c0 | [
"MIT"
] | null | null | null | Sources/Files/LoadedValue.cpp | hhYanGG/Acid | f5543e9290aee5e25c6ecdafe8a3051054b203c0 | [
"MIT"
] | null | null | null | #include "LoadedValue.hpp"
#include <ostream>
namespace acid
{
LoadedValue::LoadedValue(LoadedValue *parent, const std::string &name, const std::string &value, const std::map<std::string, std::string> &attributes) :
m_parent(parent),
m_children(std::vector<LoadedValue *>()),
m_name(FormatString::RemoveAll(name, '\"')),
m_value(value),
m_attributes(attributes)
{
}
LoadedValue::~LoadedValue()
{
for (auto &child : m_children)
{
delete child;
}
}
std::vector<LoadedValue *> LoadedValue::GetChildren(const std::string &name)
{
auto result = std::vector<LoadedValue *>();
for (auto &child : m_children)
{
if (child->m_name == name)
{
result.push_back(child);
}
}
return result;
}
LoadedValue *LoadedValue::GetChild(const std::string &name, const bool &addIfNull, const bool &reportError)
{
std::string nameNoSpaces = FormatString::Replace(name, " ", "_");
for (auto &child : m_children)
{
if (child->m_name == name || child->m_name == nameNoSpaces)
{
return child;
}
}
if (!addIfNull)
{
if (reportError)
{
fprintf(stderr, "Could not find child in loaded value '%s' of name '%s'\n", m_name.c_str(), name.c_str());
}
return nullptr;
}
auto child = new LoadedValue(this, name, "");
m_children.emplace_back(child);
return child;
}
LoadedValue *LoadedValue::GetChild(const uint32_t &index, const bool &addIfNull, const bool &reportError)
{
if (m_children.size() >= index)
{
return m_children.at(index);
}
// TODO
//if (!addIfNull)
//{
if (reportError)
{
fprintf(stderr, "Could not find child in loaded value '%s' at '%i'\n", m_name.c_str(), index);
}
return nullptr;
//}
}
LoadedValue *LoadedValue::GetChildWithAttribute(const std::string &childName, const std::string &attribute, const std::string &value, const bool &reportError)
{
auto children = GetChildren(childName);
if (children.empty())
{
return nullptr;
}
for (auto &child : children)
{
std::string attrib = child->GetAttribute(attribute);
if (attrib == value)
{
return child;
}
}
if (reportError)
{
fprintf(stderr, "Could not find child in loaded value '%s' with '%s'\n", m_name.c_str(), attribute.c_str());
}
return nullptr;
}
void LoadedValue::AddChild(LoadedValue *value)
{
auto child = GetChild(value->m_name);
if (child != nullptr)
{
child->m_value = value->m_value;
return;
}
child = value;
m_children.emplace_back(child);
}
std::string LoadedValue::GetAttribute(const std::string &attribute) const
{
auto it = m_attributes.find(attribute);
if (it == m_attributes.end())
{
return nullptr;
}
return (*it).second;
}
void LoadedValue::AddAttribute(const std::string &attribute, const std::string &value)
{
auto it = m_attributes.find(attribute);
if (it == m_attributes.end())
{
m_attributes.emplace(attribute, value);
}
(*it).second = value;
}
bool LoadedValue::RemoveAttribute(const std::string &attribute)
{
auto it = m_attributes.find(attribute);
if (it != m_attributes.end())
{
m_attributes.erase(it);
return true;
}
return false;
}
std::string LoadedValue::GetString()
{
return FormatString::RemoveAll(m_value, '\"');
}
void LoadedValue::SetString(const std::string &data)
{
m_value = "\"" + data + "\"";
}
}
| 19.468208 | 159 | 0.649644 | hhYanGG |
27d6344871393ba0ea54801376ae49b4ef1f9650 | 5,223 | cc | C++ | daemon/network_interface_description.cc | nawazish-couchbase/kv_engine | 132f1bb04c9212bcac9e401d069aeee5f63ff1cd | [
"MIT",
"BSD-3-Clause"
] | 104 | 2017-05-22T20:41:57.000Z | 2022-03-24T00:18:34.000Z | daemon/network_interface_description.cc | nawazish-couchbase/kv_engine | 132f1bb04c9212bcac9e401d069aeee5f63ff1cd | [
"MIT",
"BSD-3-Clause"
] | 3 | 2017-11-14T08:12:46.000Z | 2022-03-03T11:14:17.000Z | daemon/network_interface_description.cc | nawazish-couchbase/kv_engine | 132f1bb04c9212bcac9e401d069aeee5f63ff1cd | [
"MIT",
"BSD-3-Clause"
] | 71 | 2017-05-22T20:41:59.000Z | 2022-03-29T10:34:32.000Z | /*
* Copyright 2021-Present Couchbase, Inc.
*
* Use of this software is governed by the Business Source License included
* in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
* in that file, in accordance with the Business Source License, use of this
* software will be governed by the Apache License, Version 2.0, included in
* the file licenses/APL2.txt.
*/
#include "network_interface_description.h"
#include <nlohmann/json.hpp>
/// Validate the interface description
static nlohmann::json validateInterfaceDescription(const nlohmann::json& json) {
if (!json.is_object()) {
throw std::invalid_argument("value must be JSON of type object");
}
bool host = false;
bool port = false;
bool family = false;
bool type = false;
for (const auto& kv : json.items()) {
if (kv.key() == "host") {
if (!kv.value().is_string()) {
throw std::invalid_argument("host must be JSON of type string");
}
host = true;
} else if (kv.key() == "port") {
// Yack. One thought one could use is_number_unsigned and it would
// return true for all positive integer values, but it actually
// looks at the _datatype_ so it may return false for lets say
// 0 and 11210. Perform the checks myself
if (!kv.value().is_number_integer()) {
throw std::invalid_argument("port must be JSON of type number");
}
if (kv.value().get<int>() < 0) {
throw std::invalid_argument("port must be a positive number");
}
if (kv.value().get<int>() > std::numeric_limits<in_port_t>::max()) {
throw std::invalid_argument(
"port must be [0," +
std::to_string(std::numeric_limits<in_port_t>::max()) +
"]");
}
port = true;
} else if (kv.key() == "family") {
if (!kv.value().is_string()) {
throw std::invalid_argument(
"family must be JSON of type string");
}
const auto value = kv.value().get<std::string>();
if (value != "inet" && value != "inet6") {
throw std::invalid_argument(R"(family must "inet" or "inet6")");
}
family = true;
} else if (kv.key() == "tls") {
if (!kv.value().is_boolean()) {
throw std::invalid_argument("tls must be JSON of type boolean");
}
} else if (kv.key() == "system") {
if (!kv.value().is_boolean()) {
throw std::invalid_argument(
"system must be JSON of type boolean");
}
} else if (kv.key() == "type") {
if (!kv.value().is_string()) {
throw std::invalid_argument("type must be JSON of type string");
}
const auto value = kv.value().get<std::string>();
if (value != "mcbp" && value != "prometheus") {
throw std::invalid_argument(
R"(type must "mcbp" or "prometheus")");
}
type = true;
} else if (kv.key() == "tag") {
if (!kv.value().is_string()) {
throw std::invalid_argument("tag must be JSON of type string");
}
} else if (kv.key() == "uuid") {
if (!kv.value().is_string()) {
throw std::invalid_argument("uuid must be JSON of type string");
}
} else {
throw std::invalid_argument("Unsupported JSON property " +
kv.key());
}
}
if (!host || !port || !family || !type) {
throw std::invalid_argument(
R"("host", "port", "family" and "type" must all be set)");
}
return json;
}
NetworkInterfaceDescription::NetworkInterfaceDescription(
const nlohmann::json& json)
: NetworkInterfaceDescription(validateInterfaceDescription(json), true) {
}
static sa_family_t toFamily(const std::string& family) {
if (family == "inet") {
return AF_INET;
}
if (family == "inet6") {
return AF_INET6;
}
throw std::invalid_argument(
"toFamily(): family must be 'inet' or 'inet6': " + family);
}
NetworkInterfaceDescription::NetworkInterfaceDescription(
const nlohmann::json& json, bool)
: host(json["host"].get<std::string>()),
port(json["port"].get<in_port_t>()),
family(toFamily(json["family"].get<std::string>())),
system(!(json.find("system") == json.cend()) &&
json["system"].get<bool>()),
type(json["type"].get<std::string>() == "mcbp" ? Type::Mcbp
: Type::Prometheus),
tag(json.find("tag") == json.cend() ? ""
: json["tag"].get<std::string>()),
tls(!(json.find("tls") == json.cend()) && json["tls"].get<bool>()),
uuid(json.find("uuid") == json.cend() ? ""
: json["uuid"].get<std::string>()) {
}
| 39.870229 | 80 | 0.515987 | nawazish-couchbase |
27dac96816d29817f5b26faa1fc7d35519651029 | 422 | hpp | C++ | exceptions/InvalidDataException.hpp | Adrijaned/oglPlaygorund | ce3c31669263545650efcc4b12dd22e6517ccaa7 | [
"MIT"
] | null | null | null | exceptions/InvalidDataException.hpp | Adrijaned/oglPlaygorund | ce3c31669263545650efcc4b12dd22e6517ccaa7 | [
"MIT"
] | null | null | null | exceptions/InvalidDataException.hpp | Adrijaned/oglPlaygorund | ce3c31669263545650efcc4b12dd22e6517ccaa7 | [
"MIT"
] | null | null | null | //
// Created by adrijarch on 5/26/19.
//
#ifndef OGLPLAYGROUND_INVALIDDATAEXCEPTION_HPP
#define OGLPLAYGROUND_INVALIDDATAEXCEPTION_HPP
#include <stdexcept>
/**
* Marks any case where data has not been as expected.
*/
class InvalidDataException : public std::runtime_error {
public:
explicit InvalidDataException(const std::string &arg) : runtime_error(arg) { }
};
#endif //OGLPLAYGROUND_INVALIDDATAEXCEPTION_HPP
| 21.1 | 80 | 0.774882 | Adrijaned |
27dbe03cdcc424e19cf179c200f36afdfb516e5e | 854 | hpp | C++ | Helena/Traits/Constness.hpp | NIKEA-SOFT/HelenaFramework | 4f443710e6a67242ddd4361f9c1a89e9d757c820 | [
"MIT"
] | 24 | 2020-08-17T21:49:38.000Z | 2022-03-31T13:31:46.000Z | Helena/Traits/Constness.hpp | NIKEA-SOFT/HelenaFramework | 4f443710e6a67242ddd4361f9c1a89e9d757c820 | [
"MIT"
] | null | null | null | Helena/Traits/Constness.hpp | NIKEA-SOFT/HelenaFramework | 4f443710e6a67242ddd4361f9c1a89e9d757c820 | [
"MIT"
] | 2 | 2021-04-21T09:27:03.000Z | 2021-08-20T09:44:53.000Z | #ifndef HELENA_TRAITS_CONSTNESS_HPP
#define HELENA_TRAITS_CONSTNESS_HPP
#include <type_traits>
namespace Helena::Traits
{
/**
* @brief Transcribes the constness of a type to another type.
* @tparam To The type to which to transcribe the constness.
* @tparam From The type from which to transcribe the constness.
*/
template<typename To, typename From>
struct Constness {
/*! @brief The type resulting from the transcription of the constness. */
using type = std::remove_const_t<To>;
};
/*! @copydoc constness_as */
template<typename To, typename From>
struct Constness<To, const From> {
/*! @brief The type resulting from the transcription of the constness. */
using type = std::add_const_t<To>;
};
}
#endif // HELENA_TRAITS_CONSTNESS_HPP | 30.5 | 82 | 0.660422 | NIKEA-SOFT |
27e0906939c0c5bb899d69db0c6b1248684703e9 | 10,225 | cc | C++ | Validation/EcalRecHits/src/EcalTBValidation.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | Validation/EcalRecHits/src/EcalTBValidation.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | Validation/EcalRecHits/src/EcalTBValidation.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | // Ecal H4 tesbeam analysis
#include "Validation/EcalRecHits/interface/EcalTBValidation.h"
#include "DataFormats/EcalRecHit/interface/EcalUncalibratedRecHit.h"
#include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h"
#include "DataFormats/EcalDigi/interface/EcalDigiCollections.h"
#include "TBDataFormats/EcalTBObjects/interface/EcalTBHodoscopeRecInfo.h"
#include "TBDataFormats/EcalTBObjects/interface/EcalTBTDCRecInfo.h"
#include "TBDataFormats/EcalTBObjects/interface/EcalTBEventHeader.h"
#include "DQMServices/Core/interface/DQMStore.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include <iostream>
#include <string>
EcalTBValidation::EcalTBValidation( const edm::ParameterSet& config ) {
data_ = config.getUntrackedParameter<int>("data",-1000);
xtalInBeam_ = config.getUntrackedParameter<int>("xtalInBeam",-1000);
digiCollection_ = config.getParameter<std::string>("digiCollection");
digiProducer_ = config.getParameter<std::string>("digiProducer");
hitCollection_ = config.getParameter<std::string>("hitCollection");
hitProducer_ = config.getParameter<std::string>("hitProducer");
hodoRecInfoCollection_ = config.getParameter<std::string>("hodoRecInfoCollection");
hodoRecInfoProducer_ = config.getParameter<std::string>("hodoRecInfoProducer");
tdcRecInfoCollection_ = config.getParameter<std::string>("tdcRecInfoCollection");
tdcRecInfoProducer_ = config.getParameter<std::string>("tdcRecInfoProducer");
eventHeaderCollection_ = config.getParameter<std::string>("eventHeaderCollection");
eventHeaderProducer_ = config.getParameter<std::string>("eventHeaderProducer");
digi_Token_ = consumes<EBDigiCollection>(edm::InputTag(digiProducer_, digiCollection_));
hit_Token_ = consumes<EBUncalibratedRecHitCollection>(edm::InputTag(hitProducer_, hitCollection_));
hodoRec_Token_ = consumes<EcalTBHodoscopeRecInfo>(edm::InputTag(hodoRecInfoProducer_, hodoRecInfoCollection_));
tdcRec_Token_ = consumes<EcalTBTDCRecInfo>(edm::InputTag(tdcRecInfoProducer_, tdcRecInfoCollection_));
eventHeader_Token_ = consumes<EcalTBEventHeader>(edm::InputTag(eventHeaderProducer_));
//rootfile_ = config.getUntrackedParameter<std::string>("rootfile","EcalTBValidation.root");
// verbosity...
verbose_ = config.getUntrackedParameter<bool>("verbose", false);
meETBxib_ = 0;
meETBampltdc_ = 0;
meETBShape_ = 0;
meETBhodoX_ = 0;
meETBhodoY_ = 0;
meETBe1x1_ = 0;
meETBe3x3_ = 0;
meETBe5x5_ = 0;
meETBe1e9_ = 0;
meETBe1e25_ = 0;
meETBe9e25_ = 0;
meETBe1x1_center_ = 0;
meETBe3x3_center_ = 0;
meETBe5x5_center_ = 0;
meETBe1vsX_ = 0;
meETBe1vsY_ = 0;
meETBe1e9vsX_ = 0;
meETBe1e9vsY_ = 0;
meETBe1e25vsX_ = 0;
meETBe1e25vsY_ = 0;
meETBe9e25vsX_ = 0;
meETBe9e25vsY_ = 0;
}
EcalTBValidation::~EcalTBValidation(){}
void EcalTBValidation::bookHistograms(DQMStore::IBooker &ibooker, edm::Run const&, edm::EventSetup const&){
std::string hname;
ibooker.setCurrentFolder( "EcalRecHitsV/EcalTBValidationTask" );
hname = "xtal in beam position";
meETBxib_ = ibooker.book2D( hname, hname, 85, 0., 85., 20,0., 20. );
hname = "Max Amplitude vs TDC offset";
meETBampltdc_ = ibooker.book2D( hname, hname, 100, 0., 1., 1000, 0., 4000. );
hname = "Beam Profile X";
meETBhodoX_ = ibooker.book1D( hname, hname, 100, -20., 20. );
hname = "Beam Profile Y";
meETBhodoY_ = ibooker.book1D( hname, hname, 100, -20., 20. );
hname = "E1x1 energy";
meETBe1x1_ = ibooker.book1D( hname, hname, 1000, 0., 4000. );
hname = "E3x3 energy";
meETBe3x3_ = ibooker.book1D( hname, hname, 1000, 0., 4000. );
hname = "E5x5 energy";
meETBe5x5_ = ibooker.book1D( hname, hname, 1000, 0., 4000. );
hname = "E1x1 energy center";
meETBe1x1_center_ = ibooker.book1D( hname, hname, 1000, 0., 4000. );
hname = "E3x3 energy center";
meETBe3x3_center_ = ibooker.book1D( hname, hname, 1000, 0., 4000. );
hname = "E5x5 energy center";
meETBe5x5_center_ = ibooker.book1D( hname, hname, 1000, 0., 4000. );
hname = "E1 over E9 ratio";
meETBe1e9_ = ibooker.book1D( hname, hname, 600, 0., 1.2 );
hname = "E1 over E25 ratio";
meETBe1e25_ = ibooker.book1D( hname, hname, 600, 0., 1.2 );
hname = "E9 over E25 ratio";
meETBe9e25_ = ibooker.book1D( hname, hname, 600, 0., 1.2 );
hname = "E1 vs X";
meETBe1vsX_ = ibooker.book2D( hname, hname, 80, -20, 20, 1000, 0., 4000. );
hname = "E1 vs Y";
meETBe1vsY_ = ibooker.book2D( hname, hname, 80, -20, 20, 1000, 0., 4000. );
hname = "E1 over E9 vs X";
meETBe1e9vsX_ = ibooker.book2D( hname, hname, 80, -20, 20, 600, 0., 1.2 );
hname = "E1 over E9 vs Y";
meETBe1e9vsY_ = ibooker.book2D( hname, hname, 80, -20, 20, 600, 0., 1.2 );
hname = "E1 over E25 vs X";
meETBe1e25vsX_ = ibooker.book2D( hname, hname, 80, -20, 20, 600, 0., 1.2 );
hname = "E1 over E25 vs Y";
meETBe1e25vsY_ = ibooker.book2D( hname, hname, 80, -20, 20, 600, 0., 1.2 );
hname = "E9 over E25 vs X";
meETBe9e25vsX_ = ibooker.book2D( hname, hname, 80, -20, 20, 600, 0., 1.2 );
hname = "E9 over E25 vs Y";
meETBe9e25vsY_ = ibooker.book2D( hname, hname, 80, -20, 20, 600, 0., 1.2 );
hname = "Xtal in Beam Shape";
meETBShape_ = ibooker.book2D( hname, hname, 250, 0, 10, 350, 0, 3500 );
}
void EcalTBValidation::analyze( const edm::Event& event, const edm::EventSetup& setup ) {
using namespace edm;
using namespace cms;
// digis
const EBDigiCollection* theDigis=0;
Handle<EBDigiCollection> pdigis;
event.getByToken(digi_Token_, pdigis);
if(pdigis.isValid()){
theDigis = pdigis.product();
}
else {
std::cerr << "Error! can't get the product " << digiCollection_.c_str() << std::endl;
return;
}
// rechits
const EBUncalibratedRecHitCollection* theHits=0;
Handle<EBUncalibratedRecHitCollection> phits;
event.getByToken(hit_Token_, phits);
if(phits.isValid()){
theHits = phits.product();
}
else {
std::cerr << "Error! can't get the product " << hitCollection_.c_str() << std::endl;
return;
}
// hodoscopes
const EcalTBHodoscopeRecInfo* theHodo=0;
Handle<EcalTBHodoscopeRecInfo> pHodo;
event.getByToken(hodoRec_Token_, pHodo);
if(pHodo.isValid()){
theHodo = pHodo.product();
}
else{
std::cerr << "Error! can't get the product " << hodoRecInfoCollection_.c_str() << std::endl;
return;
}
// tdc
const EcalTBTDCRecInfo* theTDC=0;
Handle<EcalTBTDCRecInfo> pTDC;
event.getByToken(tdcRec_Token_, pTDC);
if(pTDC.isValid()){
theTDC = pTDC.product();
}
else{
std::cerr << "Error! can't get the product " << tdcRecInfoCollection_.c_str() << std::endl;
return;
}
// event header
const EcalTBEventHeader* evtHeader=0;
Handle<EcalTBEventHeader> pEventHeader;
event.getByToken(eventHeader_Token_ , pEventHeader);
if(pEventHeader.isValid()){
evtHeader = pEventHeader.product();
}
else{
std::cerr << "Error! can't get the product " << eventHeaderProducer_.c_str() << std::endl;
return;
}
// -----------------------------------------------------------------------
// xtal-in-beam
EBDetId xtalInBeamId(1,xtalInBeam_, EBDetId::SMCRYSTALMODE);
if (xtalInBeamId==EBDetId(0)){ return; }
int xibEta = xtalInBeamId.ieta();
int xibPhi = xtalInBeamId.iphi();
// skipping events with moving table (in data)
if (data_ && (evtHeader->tableIsMoving())) return;
// amplitudes
EBDetId Xtals5x5[25];
for (unsigned int icry=0;icry<25;icry++){
unsigned int row = icry/5;
unsigned int column = icry%5;
int ieta = xtalInBeamId.ieta()+column-2;
int iphi = xtalInBeamId.iphi()+row-2;
if(EBDetId::validDetId(ieta, iphi)){
EBDetId tempId(ieta, iphi,EBDetId::ETAPHIMODE);
if (tempId.ism()==1)
Xtals5x5[icry] = tempId;
else
Xtals5x5[icry] = EBDetId(0);
} else {
Xtals5x5[icry] = EBDetId(0);
}
}
// matrices
double ampl1x1 = 0.;
double ampl3x3 = 0.;
double ampl5x5 = 0.;
for (unsigned int icry=0;icry<25;icry++) {
if (!Xtals5x5[icry].null()){
double theAmpl = (theHits->find(Xtals5x5[icry]))->amplitude();
ampl5x5 += theAmpl;
if (icry==12){ampl1x1 = theAmpl;}
if (icry==6 || icry==7 || icry==8 || icry==11 || icry==12 || icry==13 || icry==16 || icry==17 || icry==18){ampl3x3 += theAmpl;}
}}
// pulse shape
double sampleSave[10];
for(int ii=0; ii < 10; ++ii){ sampleSave[ii] = 0.0; }
EBDigiCollection::const_iterator thisDigi = theDigis->find(xtalInBeamId);
// int sMax = -1; // UNUSED
double eMax = 0.;
if (thisDigi != theDigis->end()){
EBDataFrame myDigi = (*thisDigi);
for (int sample=0; sample < myDigi.size(); ++sample){
double analogSample = myDigi.sample(sample).adc();
sampleSave[sample] = analogSample;
if ( eMax < analogSample ) {
eMax = analogSample;
// sMax = sample; // UNUSED
}
}
}
// beam profile
double xBeam = theHodo->posX();
double yBeam = theHodo->posY();
// filling histos
meETBxib_ -> Fill(xibEta, xibPhi);
meETBhodoX_ -> Fill(xBeam);
meETBhodoY_ -> Fill(yBeam);
meETBampltdc_ -> Fill(theTDC->offset(),ampl1x1);
meETBe1x1_ -> Fill(ampl1x1);
meETBe3x3_ -> Fill(ampl3x3);
meETBe5x5_ -> Fill(ampl5x5);
meETBe1e9_ -> Fill(ampl1x1/ampl3x3);
meETBe1e25_ -> Fill(ampl1x1/ampl5x5);
meETBe9e25_ -> Fill(ampl3x3/ampl5x5);
meETBe1vsX_ -> Fill(xBeam,ampl1x1);
meETBe1vsY_ -> Fill(yBeam,ampl1x1);
meETBe1e9vsX_ -> Fill(xBeam,ampl1x1/ampl3x3);
meETBe1e9vsY_ -> Fill(yBeam,ampl1x1/ampl3x3);
meETBe1e25vsX_ -> Fill(xBeam,ampl1x1/ampl5x5);
meETBe1e25vsY_ -> Fill(yBeam,ampl1x1/ampl5x5);
meETBe9e25vsX_ -> Fill(xBeam,ampl3x3/ampl5x5);
meETBe9e25vsY_ -> Fill(yBeam,ampl3x3/ampl5x5);
for(int ii=0; ii < 10; ++ii){ meETBShape_->Fill(double(ii)+theTDC->offset(),sampleSave[ii]); }
if ( (fabs(xBeam)<2.5) && (fabs(yBeam)<2.5) ){
meETBe1x1_center_ -> Fill(ampl1x1);
meETBe3x3_center_ -> Fill(ampl3x3);
meETBe5x5_center_ -> Fill(ampl5x5);
}
}
| 36.258865 | 133 | 0.661809 | pasmuss |
27e39159526886e35b3c2a1dd3f5a8f41ecb930d | 11,945 | cpp | C++ | CoralSDK_Cocos2d-x_DemoV/Classes/Snake/GameLayer.cpp | zoozooll/MyExercise | 1be14e0252babb28e32951fa1e35fc867a6ac070 | [
"Apache-2.0"
] | 2 | 2019-07-03T00:38:50.000Z | 2020-08-06T06:24:06.000Z | CoralSDK_Cocos2d-x_DemoV/Classes/Snake/GameLayer.cpp | zoozooll/MyExercise | 1be14e0252babb28e32951fa1e35fc867a6ac070 | [
"Apache-2.0"
] | null | null | null | CoralSDK_Cocos2d-x_DemoV/Classes/Snake/GameLayer.cpp | zoozooll/MyExercise | 1be14e0252babb28e32951fa1e35fc867a6ac070 | [
"Apache-2.0"
] | null | null | null | #include "GameLayer.h"
#include "GameManager.h"
#include "SnakeNode.h"
#include "GameOver.h"
USING_NS_CC;
int GameLayer::gridwidth = 50;
int GameLayer::gridcount = 12;
int GameLayer::grid[12][12] = {0};
int GameLayer::linewidth = 2;
int GameLayer::startX = 0;
int GameLayer::startY = 0;
int GameLayer::defaultbodynum = 1;
void GameLayer::onKeyReleased(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event)
{
if(keyCode==cocos2d::EventKeyboard::KeyCode::KEY_BACKSPACE)
{
Director::getInstance()->end();
}
}
Scene* GameLayer::createScene()
{
auto scene = Scene::create();
auto layer = GameLayer::create();
scene->addChild(layer);
return scene;
}
GameLayer::GameLayer()
{
score = 0;
}
GameLayer::~GameLayer()
{
AnimationCache::destroyInstance();
}
bool GameLayer::init()
{
if(!Layer::init())
{
return false;
}
this->setKeyboardEnabled(true);
deGameManager->setgameflag(1);
memset(GameLayer::grid,0,sizeof(int)*GameLayer::gridcount*GameLayer::gridcount);
GameLayer::startX = (deGameManager->getVisibleSize().width - GameLayer::gridcount*GameLayer::gridwidth)/2;
GameLayer::startY = deGameManager->getVisibleSize().height - GameLayer::gridcount*GameLayer::gridwidth-80;
//初始化,食物,身体,蛇头
for(int i=0;i<defaultbodynum;i++)
{
SnakeNode* sn = SnakeNode::create(gridcount/2 + i,gridcount/2,GAMEVIEW_SNAKE_BODY);
this->addChild(sn);
body.pushBack(sn);
GameLayer::grid[sn->row][sn->col] = 1;
}
head = SnakeNode::create(gridcount/2 + defaultbodynum,gridcount/2,GAMEVIEW_SNAKE_HEAD);
head->dir = Direction::NONE;
GameLayer::grid[head->row][head->col] = 1;
this->addChild(head);
food = SnakeNode::create(0,0,GAMEVIEW_SNAKE_FOOD);
foodtag = Sprite::create();
foodtag->setPosition(Point(food->sprite->getPositionX()+5,food->sprite->getPositionY()+6));
foodtag->setZOrder(100);
foodtag->setAnchorPoint(Point::ZERO);
foodtag->setScale(0.35);
// With 2 loops and reverse
auto cache = AnimationCache::getInstance();
cache->addAnimationsWithFile(ANIMATIONS_CACHE_PLIST);
auto animation2 = cache->getAnimation("quan_1");
auto *animate = Animate::create(animation2);
foodtag->runAction(CCRepeatForever::create(animate));
this->addChild(foodtag,1);
GameLayer::refreshfood(0.1);
this->addChild(food);
auto score = Sprite::createWithSpriteFrameName(GAMEVIEW_STAGE);
score->setPosition(Point(deGameManager->getWinSize().width-180, deGameManager->getWinSize().height-40));
score->setTag(TAG_GAMELAYER_STAGE);
score->setVisible(true);
this->addChild(score, 1);
scorelabel = Label::createWithTTF("0",FONT_EN, 40);
scorelabel->setPosition(Point(score->getPositionX()+60,score->getPositionY()));
this->addChild(scorelabel);
auto spriteNormal = Sprite::createWithSpriteFrameName(GAMEVIEW_HOME);
auto spriteSelected = Sprite::createWithSpriteFrameName(GAMEVIEW_HOME_1);
auto home = MenuItemSprite::create(spriteNormal,spriteSelected,nullptr,CC_CALLBACK_1(GameLayer::Steering, this));
home->setScale(0.6);
home->setPosition(Point(60, deGameManager->getWinSize().height-40));
home->setTag(TAG_GAMELAYER_HOME);
//网格
DrawNode* drawnode = DrawNode::create();
addChild(drawnode, 0);
for (int i = 0; i<gridcount+1; i++)
{
drawnode->drawSegment(Point(startX+0,i*gridwidth+startY), Point(startX+gridcount*gridwidth,i*gridwidth+startY),linewidth,Color4F(192,192,192,0.1f));
drawnode->drawSegment(Point(startX+i*gridwidth,0+startY), Point(startX+i*gridwidth,gridcount*gridwidth+startY),linewidth,Color4F(192,192,192,0.1f));
}
auto spriteNormal_l = Sprite::createWithSpriteFrameName(DIRECTION);
auto spriteSelected_l = Sprite::createWithSpriteFrameName(DIRECTION_1);
auto LeftItem = MenuItemSprite::create(spriteNormal_l,spriteSelected_l,nullptr,CC_CALLBACK_1(GameLayer::Steering, this));
LeftItem->setPosition(deGameManager->getWinSize().width/2-180 ,100);
LeftItem->setTag(TAG_GAMELAYER_BT_LEFT);
LeftItem->setScale(0.7);
ActionInterval * LeftItem_RT = CCRotateTo::create(0.5, 180);
LeftItem->runAction(LeftItem_RT);
auto spriteNormal_r = Sprite::createWithSpriteFrameName(DIRECTION);
auto spriteSelected_r = Sprite::createWithSpriteFrameName(DIRECTION_1);
auto RightItem = MenuItemSprite::create(spriteNormal_r,spriteSelected_r,nullptr,CC_CALLBACK_1(GameLayer::Steering, this));
RightItem->setPosition(deGameManager->getWinSize().width/2+180 ,100);
RightItem->setTag(TAG_GAMELAYER_BT_RIGHT);
RightItem->setScale(0.7);
//RightItem->setEnabled(false);
ActionInterval * RightItem_RT = CCRotateTo::create(0.5, 0);
RightItem->runAction(RightItem_RT);
auto menu = Menu::create(home,LeftItem,RightItem,NULL);
menu->setPosition(Point::ZERO);
this->addChild(menu, 0);
auto bg = Sprite::createWithSpriteFrameName(GAMEVIEW_BG);
bg->setAnchorPoint(Point::ZERO);
bg->setPosition(Point::ZERO);
this->addChild(bg, -2);
this->schedule(schedule_selector(GameLayer::update), 0.16);
ParticleSnow * ccps = ParticleSnow::create();
ccps->setSpeed(200.0f);
ccps->setAutoRemoveOnFinish(true);
this->addChild(ccps);
return true;
}
void GameLayer::BnFunc(float f)
{
}
void GameLayer::Steering(Ref* pSender)
{
deGameManager->playAudioSound(SOUND_BT);
auto mii = (MenuItemLabel*) pSender;
if(TAG_GAMELAYER_HOME==mii->getTag())
{
deGameManager->changeGameState(EGameState::RANDING);
return;
}
switch (head->dir)
{
case Direction::NONE:
{
if(mii->getTag()==TAG_GAMELAYER_BT_RIGHT)
{
head->dir = Direction::RIGHT;
}
else
{
head->dir = Direction::LEFT;
}
break;
}
case Direction::UP:
{
if(mii->getTag()==TAG_GAMELAYER_BT_RIGHT)
{
head->dir = Direction::RIGHT;
}
else
{
head->dir = Direction::LEFT;
}
break;
}
case Direction::DOWN:
{
if(mii->getTag()==TAG_GAMELAYER_BT_RIGHT)
{
head->dir = Direction::LEFT;
}
else
{
head->dir = Direction::RIGHT;
}
break;
}
case Direction::LEFT:
{
if(mii->getTag()==TAG_GAMELAYER_BT_RIGHT)
{
head->dir = Direction::UP;
}
else
{
head->dir = Direction::DOWN;
}
break;
}
case Direction::RIGHT:
{
if(mii->getTag()==TAG_GAMELAYER_BT_RIGHT)
{
head->dir = Direction::DOWN;
}
else
{
head->dir = Direction::UP;
}
break;
}
default:
break;
}
}
void GameLayer::update(float dt)
{
if(head->dir==Direction::NONE) return;
//蛇身每一段跟随前一段移动
for(int i = body.size() -1 ;i>=0;i--)
{
SnakeNode* sn = body.at(i);
if(i!=0)
{
SnakeNode* pre = body.at(i-1);
sn->dir = pre->dir;
sn->setCol(pre->col);
sn->setRow(pre->row);
}
else
{
sn->dir = head->dir;
sn->setCol(head->col);
sn->setRow(head->row);
}
}
//根据方向来让蛇头移动
switch (head->dir)
{
case UP:
if(head->row+1 >=gridcount)GameLayer::Over();else head->setRow(head->row+1);
break;
case DOWN:
if(head->row-1 <0)GameLayer::Over(); else head->setRow(head->row-1);
break;
case RIGHT:
if(head->col+1>=gridcount) GameLayer::Over(); else head->setCol(head->col+1);
break;
case LEFT:
if(head->col-1 < 0) GameLayer::Over();else head->setCol(head->col-1);
break;
default:
break;
}
//蛇身是否碰到蛇头
for(int i = body.size() -1 ;i>=0;i--)
{
SnakeNode* sn = body.at(i);
if(head->row == sn->row && head->col == sn->col)
{
GameLayer::Over();
break;
}
}
//碰撞检测
if(head->row == food->row && head->col == food->col)
{
ParticleSystemQuad* mSystem = CCParticleSystemQuad::create(PARTICLE_PLIST_1);
mSystem->setBlendAdditive(true);
mSystem->setPosition(food->sprite->getPosition());// + 60
mSystem->setAnchorPoint(Point::ZERO);
mSystem->setScale(1.5);
mSystem->setStartSize(30.0);
this->addChild(mSystem);
mSystem->setAutoRemoveOnFinish(true);
score++;
scorelabel->setString(String::createWithFormat("%d",score)->getCString());
deGameManager->playAudioSound(SOUND_EAT);
//刷新蛋
SnakeNode* sn1 = head;
GameLayer::refreshfood(0.1f);
SnakeNode* sn = SnakeNode::createbody(head->row ,head->col);
sn->dir = head->dir;
switch (sn->dir)
{
case UP:
if(sn->row+1 >=gridcount)GameLayer::Over();else sn->setRow(head->row+1);
break;
case DOWN:
if(sn->row-1 <0)GameLayer::Over(); else sn->setRow(head->row-1);
break;
case RIGHT:
if(sn->col+1>=gridcount) GameLayer::Over(); else sn->setCol(head->col+1);
break;
case LEFT:
if(sn->col-1 < 0) GameLayer::Over();else sn->setCol(head->col-1);
break;
default:
break;
}
head = sn;
this->addChild(sn,1);
body.insert(0, sn1);
}
}
void GameLayer::refreshfood(float f)
{
/*
for(int i=gridcount-1; i>=0;i--)
{
for(int y=0; y<gridcount;y++)
{
grid[i][y] = 0;
}
}
*/
memset(GameLayer::grid,0,sizeof(int)*GameLayer::gridcount*GameLayer::gridcount);
for(int i = body.size() -1 ;i>=0;i--)
{
SnakeNode* sn = body.at(i);
grid[sn->row][sn->col] = 1;
}
grid[food->row][food->col] = 1;
grid[head->row][head->col] = 1;
grid[0][GameLayer::gridcount-1] = 1;
grid[0][0] = 1;
grid[GameLayer::gridcount-1][GameLayer::gridcount-1] = 1;
grid[GameLayer::gridcount-1][0] = 1;
for(int i=gridcount-1; i>=0;i--)
{
for(int y=0; y<gridcount;y++)
{
printf(" %d ",grid[i][y]);
}
printf(" \r\n");
}
printf(" \r\n\r\n");
long bodysize = body.size();
long rand = (gridcount*gridcount-bodysize-2);
rand = (rand<0)?0:rand;
rand = arc4random()% rand;
int st = 0;
for(int i=0; i<gridcount;i++)
{
for(int y=0; y<gridcount;y++)
{
if(grid[i][y]==1)
{
continue;
}
if(st==rand)
{
food->row = i;
food->col = y;
food->rePos(false);
if(foodtag!=NULL)
foodtag->setPosition(Point(food->sprite->getPositionX()+5,food->sprite->getPositionY()+6));
return;
}
st++;
}
}
}
bool GameLayer::Over()
{
if(deGameManager->getgameflag()==1)
{
deGameManager->setgameflag(0);
deGameManager->playAudioSound(SOUND_GAMEOVER);
unschedule(schedule_selector(GameLayer::update));
deGameManager->gameOver(score, "", 0, CCString::createWithFormat(" 基础分值:%d\r\n 属于一般水平!",score)->getCString());
}
return true;
}
| 28.922518 | 156 | 0.566429 | zoozooll |
27e7f84dd56ff1377295227a2b0ede4ee928a7fd | 1,178 | hpp | C++ | src/gui/hud/hud.hpp | louiz/batajelo | 4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e | [
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | 7 | 2015-01-28T09:17:08.000Z | 2020-04-21T13:51:16.000Z | src/gui/hud/hud.hpp | louiz/batajelo | 4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e | [
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | null | null | null | src/gui/hud/hud.hpp | louiz/batajelo | 4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e | [
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | 1 | 2020-07-11T09:20:25.000Z | 2020-07-11T09:20:25.000Z | /** @addtogroup Ui
* @{
*/
/**
* Uniq object owned by the Screen. It is in charge of displaying all
* static information about the game, like the time, the minimap, entities
* attributes, interface buttons, etc.
* @class Hud
*/
#include <SFML/System.hpp>
#ifndef __HUP_HPP__
# define __HUP_HPP__
#define HUD_HEIGHT 323
#include <gui/screen/screen_element.hpp>
#include <gui/hud/info_hud.hpp>
#include <gui/hud/abilities_panel.hpp>
class Screen;
class GameClient;
class Hud: public ScreenElement
{
public:
Hud(GameClient* game, Screen* screen);
~Hud();
void draw() override final;
bool handle_event(const sf::Event&) override final;
void update(const utils::Duration& dt) override final;
bool is_entity_hovered(const Entity*) const;
void add_info_message(std::string&& text);
void activate_ability(const std::size_t nb);
bool handle_keypress(const sf::Event& event);
bool handle_keyrelease(const sf::Event& event);
private:
Hud(const Hud&);
Hud& operator=(const Hud&);
GameClient* game;
sf::Texture hud_texture;
sf::Sprite hud_sprite;
sf::Font font;
AbilitiesPanel abilities_panel;
InfoHud info_hud;
};
#endif // __HUP_HPP__
| 22.226415 | 74 | 0.726655 | louiz |
27e8d30d8d97607b38b9e8a62dc690c7c1e31b2c | 2,697 | cpp | C++ | aoj/CGL/CGL_7_E/solve.cpp | tobyapi/online-judge-solutions | 4088adb97ea592e8e6582ae7d2ecde2f85e2ed9c | [
"MIT"
] | null | null | null | aoj/CGL/CGL_7_E/solve.cpp | tobyapi/online-judge-solutions | 4088adb97ea592e8e6582ae7d2ecde2f85e2ed9c | [
"MIT"
] | null | null | null | aoj/CGL/CGL_7_E/solve.cpp | tobyapi/online-judge-solutions | 4088adb97ea592e8e6582ae7d2ecde2f85e2ed9c | [
"MIT"
] | null | null | null | #include<cmath>
#include<algorithm>
#include<iostream>
#include<vector>
#include<climits>
#include<cfloat>
#include<cstdio>
#define all(c) (c).begin(),(c).end()
#define curr(P,i) P[(i)%P.size()]
#define next(P,i) P[(i+1)%P.size()]
#define prev(P,i) P[(i+P.size()-1)%P.size()]
using namespace std;
typedef double Real;
Real EPS = 1e-8;
const Real PI = acos(-1);
int sgn(Real a, Real b=0){return a<b-EPS?-1:a>b+EPS?1:0;}
Real sqr(Real a){return sqrt(max(a,(Real)0));}
struct Point{
Real add(Real a, Real b){
if(abs(a+b) < EPS*(abs(a)+abs(b)))return 0;
return a+b;
}
Real x, y;
Point(){}
Point(Real x,Real y) : x(x) , y(y){}
Point operator + (Point p){return Point(add(x,p.x), add(y,p.y));}
Point operator - (Point p){return Point(add(x,-p.x), add(y,-p.y));}
Point operator * (Real d){return Point(x*d,y*d);}
Point operator / (Real d){return Point(x/d,y/d);}
bool operator == (Point p){return !sgn(dist(p));}
bool operator < (Point p)const{return (p.x!=x)?x<p.x:y<p.y;}
Real norm(){return sqr(x*x+y*y);}
Real dist(Point a){return (*this-a).norm();}
Real dot(Point a){return x*a.x+y*a.y;}
Real cross(Point a){return x*a.y-y*a.x;}
//点pを中心に角度r(radius)だけ半時計回りに回転する
Point rotate(Real r,Point p = Point(0,0)){
Real ta=cos(r)*(x-p.x)-sin(r)*(y-p.y)+p.x;
Real tb=sin(r)*(x-p.x)+cos(r)*(y-p.y)+p.y;
return Point(ta,tb);
}
Real arg(){
if(sgn(x)>0)return atan(y/x);
if(sgn(x)<0)return atan(y/x)+PI;
if(sgn(y)>0)return PI/2;
if(sgn(y)<0)return 3*PI/2;
return 0;
}
};
//a -> b -> c
int ccw(Point a, Point b, Point c) {
b = b-a; c = c-a;
if (b.cross(c) > 0) return +1; // counter clockwise
if (b.cross(c) < 0) return -1; // clockwise
if (b.dot(c) < 0) return +2; // c--a--b on line
if (b.norm() < c.norm()) return -2; // a--b--c on line
return 0; // a--c--b on line
}
struct Circle{
Point p;
Real r;
Circle(){}
Circle(Point p, Real r) : p(p) , r(r){}
/*
Verified. AOJ 1132
2円の交点を求める
*/
vector<Point> intersectionPoints(Circle b){
vector<Point> res;
Point tmp=p-b.p;
if(tmp.norm()>pow(r+b.r,2))return res;
Real L=p.dist(b.p);
Real C=atan2(b.p.y-p.y,b.p.x-p.x);
Real a=acos((L*L+r*r-b.r*b.r)/(2*L*r));
res.push_back(Point(p.x+r*cos(C+a), p.y+r*sin(C+a)));
res.push_back(Point(p.x+r*cos(C-a), p.y+r*sin(C-a)));
return res;
}
};
int main(void){
Circle a,b;
cin >> a.p.x >> a.p.y >> a.r;
cin >> b.p.x >> b.p.y >> b.r;
vector<Point> res=a.intersectionPoints(b);
sort(all(res));
printf("%.8f %.8f %.8f %.8f",res[0].x,res[0].y,res[1].x,res[1].y);
cout << endl;
return 0;
}
| 24.743119 | 69 | 0.557286 | tobyapi |
27e9f2aa136291997b4f98ad4946faa09e82375f | 1,944 | hpp | C++ | pellets/z_http/mem_write.hpp | wohaaitinciu/zpublic | 0e4896b16e774d2f87e1fa80f1b9c5650b85c57e | [
"Unlicense"
] | 50 | 2015-01-07T01:54:54.000Z | 2021-01-15T00:41:48.000Z | pellets/z_http/mem_write.hpp | sinmx/ZPublic | 0e4896b16e774d2f87e1fa80f1b9c5650b85c57e | [
"Unlicense"
] | 1 | 2015-05-26T07:40:19.000Z | 2015-05-26T07:40:19.000Z | pellets/z_http/mem_write.hpp | sinmx/ZPublic | 0e4896b16e774d2f87e1fa80f1b9c5650b85c57e | [
"Unlicense"
] | 39 | 2015-01-07T02:03:15.000Z | 2021-01-15T00:41:50.000Z | /*************************************************************************
* *
* I|*j^3Cl|a "+!*% qt Nd gW *
* l]{y+l?MM* !#Wla\NNP NW MM I| *
* PW ?E| tWg Wg sC! AW ~@v~ *
* NC ?M! yN| WW MK MW@K1Y%M@ RM #Q QP@tim *
* CM| |WQCljAE| MD Mg RN cM~ NM WQ MQ *
* #M aQ? MW M3 Mg Q( HQ YR IM| *
* Dq {Ql MH iMX Mg MM QP QM Eg *
* !EWNaPRag2$ +M" $WNaHaN% MQE$%EXW QQ CM %M%a$D *
* *
* Website: https://github.com/zpublic/zpublic *
* *
************************************************************************/
#pragma once
#include "stream_writter.hpp"
#include "z_http_interface.h"
namespace zl
{
namespace http
{
class ZLMemWrite : public ICurlWrite
{
public:
ZLMemWrite()
{
}
virtual ~ZLMemWrite()
{
}
virtual int Write(BYTE *pData, int nLength)
{
m_stream.WriteBinary(pData, nLength);
return nLength;
}
virtual const BYTE* GetData()
{
return (const BYTE*)m_stream.GetStream();
}
virtual int GetLength()
{
return m_stream.GetSize();
}
ZLStreamWriter& GetStreamWriter()
{
return m_stream;
}
private:
ZLStreamWriter m_stream;
};
}
}
| 30.857143 | 74 | 0.296811 | wohaaitinciu |
27eee5181ee98dc3d63b1216c64d059f9b5afdba | 5,995 | hpp | C++ | src/math/CartesianToGeodeticFukushima.hpp | JordanMcManus/MBES-lib | 618d64f4e042bf5660015819f89537cdd70e696d | [
"MIT"
] | 13 | 2019-10-29T14:16:13.000Z | 2022-02-24T06:44:37.000Z | src/math/CartesianToGeodeticFukushima.hpp | JordanMcManus/MBES-lib | 618d64f4e042bf5660015819f89537cdd70e696d | [
"MIT"
] | 62 | 2019-04-16T13:53:50.000Z | 2022-03-07T19:44:23.000Z | src/math/CartesianToGeodeticFukushima.hpp | JordanMcManus/MBES-lib | 618d64f4e042bf5660015819f89537cdd70e696d | [
"MIT"
] | 18 | 2019-04-10T19:51:21.000Z | 2022-01-31T21:42:22.000Z | /*
* Copyright 2020 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés
*/
/*
* File: CartesianToGeodeticFukushima.hpp
* Author: jordan
*/
#ifndef CARTESIANTOGEODETICFUKUSHIMA_HPP
#define CARTESIANTOGEODETICFUKUSHIMA_HPP
#ifdef _WIN32
#define _USE_MATH_DEFINES
#include <math.h>
#else
#include <cmath>
#endif
#include <vector>
#include <Eigen/Dense>
#include "../Position.hpp"
#include "../utils/Constants.hpp"
class CartesianToGeodeticFukushima {
/*
* This class implements the method given in Fukushima (2006):
*
* Transformation from Cartesian to geodetic coordinates
* accelerated by Halley's method
* DOI: 10.1007/s00190-006-0023-2
*/
private:
unsigned int numberOfIterations;
// Ellipsoid parameters
double a; // semi-major axis
double e2; // first eccentricity squared
// Derived parameters
double b; // semi-minor axis
double a_inverse; // 1/a
double ec; // sqrt(1 - e*e)
public:
CartesianToGeodeticFukushima(unsigned int numberOfIterations, double a=a_wgs84, double e2=e2_wgs84) :
numberOfIterations(numberOfIterations), a(a), e2(e2) {
ec = std::sqrt(1 - e2);
b = a*ec;
a_inverse = 1 / a;
}
~CartesianToGeodeticFukushima() {};
void ecefToLongitudeLatitudeElevation(Eigen::Vector3d & ecefPosition, Position & positionGeographic) {
double x = ecefPosition(0);
double y = ecefPosition(1);
double z = ecefPosition(2);
// Center of the Earth
if (x == 0.0 && y == 0.0 && z == 0.0) {
positionGeographic.setLatitude(0.0);
positionGeographic.setLongitude(0.0);
positionGeographic.setEllipsoidalHeight(0.0);
return;
}
// Position at Poles
if (x == 0.0 && y == 0.0 && z != 0.0) {
if (z > 0) {
positionGeographic.setLatitude(M_PI_2*R2D);
} else {
positionGeographic.setLatitude(-M_PI_2*R2D);
}
positionGeographic.setLongitude(0.0);
positionGeographic.setEllipsoidalHeight(std::abs(z) - b);
return;
}
double pp = x * x + y * y;
double p = std::sqrt(pp);
// Position at Equator
if (z == 0.0) {
positionGeographic.setLatitude(0.0);
positionGeographic.setLongitude(estimateLongitude(x, y, p)*R2D);
positionGeographic.setEllipsoidalHeight(std::sqrt(x * x + y * y) - a);
return;
}
double P = p*a_inverse;
double Z = a_inverse * ec * std::abs(z);
//double R = std::sqrt(pp + z * z);
std::vector<double> S(numberOfIterations + 1, 0);
std::vector<double> C(numberOfIterations + 1, 0);
std::vector<double> D(numberOfIterations + 1, 0);
std::vector<double> F(numberOfIterations + 1, 0);
std::vector<double> A(numberOfIterations + 1, 0);
std::vector<double> B(numberOfIterations + 1, 0);
S[0] = Z; //starter variables. See (Fukushima, 2006) p.691 equation (17)
C[0] = ec*P; //starter variables. See (Fukushima, 2006) p.691 equation (17)
A[0] = std::sqrt(S[0] * S[0] + C[0] * C[0]);
B[0] = 1.5 * e2 * e2 * P * S[0] * S[0] * C[0] * C[0] * (A[0] - ec); //starter variables. See (Fukushima, 2006) p.691 equation (18)
unsigned int iterationNumber = 1;
while (iterationNumber <= numberOfIterations) {
D[iterationNumber - 1] =
Z * A[iterationNumber - 1] * A[iterationNumber - 1] * A[iterationNumber - 1] +
e2 * S[iterationNumber - 1] * S[iterationNumber - 1] * S[iterationNumber - 1];
F[iterationNumber - 1] =
P * A[iterationNumber - 1] * A[iterationNumber - 1] * A[iterationNumber - 1] -
e2 * C[iterationNumber - 1] * C[iterationNumber - 1] * C[iterationNumber - 1];
S[iterationNumber] =
D[iterationNumber - 1] * F[iterationNumber - 1] -
B[iterationNumber - 1] * S[iterationNumber - 1];
C[iterationNumber] =
F[iterationNumber - 1] * F[iterationNumber - 1] -
B[iterationNumber - 1] * C[iterationNumber - 1];
A[iterationNumber] = std::sqrt(
S[iterationNumber] * S[iterationNumber] +
C[iterationNumber] * C[iterationNumber]);
B[iterationNumber] =
1.5 *
e2 * S[iterationNumber] *
C[iterationNumber] * C[iterationNumber] *
((P * S[iterationNumber] - Z * C[iterationNumber]) * A[iterationNumber] -
e2 * S[iterationNumber] * C[iterationNumber]);
++iterationNumber;
}
double lon = estimateLongitude(x, y, p);
double Cc = ec*C[numberOfIterations];
double lat = estimateLatitude(z, S[numberOfIterations], Cc);
double h = estimateHeight(z, p, A[numberOfIterations], S[numberOfIterations], Cc);
positionGeographic.setLatitude(lat*R2D);
positionGeographic.setLongitude(lon*R2D);
positionGeographic.setEllipsoidalHeight(h);
}
double estimateLongitude(double x, double y, double p) {
// Vermeille (2004), stable longitude calculation
// atan(y/x) suffers when x = 0
if (y < 0) {
return -M_PI_2 + 2*std::atan(x/(p - y));
}
return M_PI_2 - 2*std::atan(x/(p + y));
}
double estimateLatitude(double z, double S, double Cc) {
double lat = std::abs(std::atan(S / Cc));
if (z < 0) {
return -lat;
}
return lat;
}
double estimateHeight(double z, double p, double A, double S, double Cc) {
return (p * Cc + std::abs(z) * S - b * A) / std::sqrt(Cc * Cc + S * S);
}
};
#endif /* CARTESIANTOGEODETICFUKUSHIMA_HPP */
| 32.93956 | 139 | 0.568474 | JordanMcManus |
27f50ee1c6d1bb148b49053e73d852f5ee973bd8 | 2,350 | cpp | C++ | src/framework/GSD3D11Mesh.cpp | 3dhater/miGUI | a086201ce18393d7d00f4018a201635ed5aa63c0 | [
"MIT"
] | 1 | 2021-11-16T23:11:26.000Z | 2021-11-16T23:11:26.000Z | src/framework/GSD3D11Mesh.cpp | 3dhater/miGUI | a086201ce18393d7d00f4018a201635ed5aa63c0 | [
"MIT"
] | null | null | null | src/framework/GSD3D11Mesh.cpp | 3dhater/miGUI | a086201ce18393d7d00f4018a201635ed5aa63c0 | [
"MIT"
] | null | null | null | #include "mgf.h"
#ifdef MGF_GS_D3D11
#include "Log.h"
#include "GSD3D11.h"
#include "GSD3D11Mesh.h"
using namespace mgf;
GSD3D11Mesh::GSD3D11Mesh(GSMeshInfo* mi, ID3D11Device* d, ID3D11DeviceContext* dc)
{
m_d3d11DevCon = dc;
m_meshInfo = *mi;
Mesh* mesh = (Mesh*)m_meshInfo.m_meshPtr;
m_vertexType = mesh->m_vertexType;
D3D11_BUFFER_DESC vbd, ibd;
ZeroMemory(&vbd, sizeof(D3D11_BUFFER_DESC));
ZeroMemory(&ibd, sizeof(D3D11_BUFFER_DESC));
vbd.Usage = D3D11_USAGE_DEFAULT;
//vbd.Usage = D3D11_USAGE_DYNAMIC;
vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER | D3D11_BIND_STREAM_OUTPUT;
ibd.Usage = D3D11_USAGE_DEFAULT;
//ibd.Usage = D3D11_USAGE_DYNAMIC;
ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;
//vbd.CPUAccessFlags = 0;
//ibd.CPUAccessFlags = 0; //D3D11_CPU_ACCESS_WRITE
D3D11_SUBRESOURCE_DATA vData, iData;
ZeroMemory(&vData, sizeof(D3D11_SUBRESOURCE_DATA));
ZeroMemory(&iData, sizeof(D3D11_SUBRESOURCE_DATA));
HRESULT hr = 0;
vbd.ByteWidth = mesh->m_stride * mesh->m_vCount;
vData.pSysMem = &mesh->m_vertices[0];
hr = d->CreateBuffer(&vbd, &vData, &m_vBuffer);
if (FAILED(hr))
LogWriteError("Can't create Direct3D 11 vertex buffer\n");
m_stride = mesh->m_stride;
m_iCount = mesh->m_iCount;
if (mesh->m_indices)
{
uint32_t index_sizeof = sizeof(uint16_t);
m_indexType = DXGI_FORMAT_R16_UINT;
if (mesh->m_indexType == Mesh::MeshIndexType_u32)
{
m_indexType = DXGI_FORMAT_R32_UINT;
index_sizeof = sizeof(uint32_t);
}
ibd.ByteWidth = index_sizeof * mesh->m_iCount;
iData.pSysMem = &mesh->m_indices[0];
hr = d->CreateBuffer(&ibd, &iData, &m_iBuffer);
if (FAILED(hr))
LogWriteError("Can't create Direct3D 11 index buffer\n");
}
}
GSD3D11Mesh::~GSD3D11Mesh()
{
if (m_vBuffer)
{
m_vBuffer->Release();
m_vBuffer = 0;
}
if (m_iBuffer)
{
m_iBuffer->Release();
m_iBuffer = 0;
}
}
void GSD3D11Mesh::MapModelForWriteVerts(uint8_t** v_ptr)
{
static D3D11_MAPPED_SUBRESOURCE mapData;
auto hr = m_d3d11DevCon->Map(
m_vBuffer,
0,
D3D11_MAP_WRITE_DISCARD,
0,
&mapData
);
if (FAILED(hr))
{
printf("Can not lock D3D11 render model buffer. Code : %u\n", hr);
return;
}
*v_ptr = (uint8_t*)mapData.pData;
m_lockedResource = m_vBuffer;
}
void GSD3D11Mesh::UnmapModelForWriteVerts()
{
m_d3d11DevCon->Unmap(m_lockedResource, 0);
m_lockedResource = nullptr;
}
#endif
| 21.363636 | 82 | 0.722979 | 3dhater |
27f56b53bc11e807e51a4ede90f64c85420a85ec | 758 | cpp | C++ | src/scenes/stage.cpp | AgoutiGames/Piper | 160f0c7e8afb8d3ea91dd69ee10c63da60f66a21 | [
"MIT"
] | null | null | null | src/scenes/stage.cpp | AgoutiGames/Piper | 160f0c7e8afb8d3ea91dd69ee10c63da60f66a21 | [
"MIT"
] | 2 | 2020-06-13T11:48:59.000Z | 2020-06-13T11:56:24.000Z | src/scenes/stage.cpp | AgoutiGames/Piper | 160f0c7e8afb8d3ea91dd69ee10c63da60f66a21 | [
"MIT"
] | null | null | null | #include "scenes/stage.hpp"
#include "core/scene_manager.hpp"
const char* Stage::type = "Stage";
const bool Stage::good = GameScene::register_class<Stage>(Stage::type);
Stage::Stage(salmon::MapRef map, SceneManager* scene_manager) :
GameScene(map,scene_manager) {}
void Stage::init() {
m_scene_manager->set_game_resolution(320,320);
m_scene_manager->set_fullscreen(false);
m_scene_manager->set_window_size(640,640);
// Initializes all characters in scene
GameScene::init();
// Setup member vars here | example: put(m_speed, "m_speed");
// Clear data accessed via put
get_data().clear();
}
void Stage::update() {
// Add scene logic here
// Calls update on all characters in scene
GameScene::update();
}
| 25.266667 | 71 | 0.695251 | AgoutiGames |
27f5fe883f7794051f6b849c5c471c04802a8a84 | 1,957 | cxx | C++ | main/sc/source/ui/unoobj/unoreflist.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/sc/source/ui/unoobj/unoreflist.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/sc/source/ui/unoobj/unoreflist.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include "unoreflist.hxx"
#include "document.hxx"
//------------------------------------------------------------------------
ScUnoRefList::ScUnoRefList()
{
}
ScUnoRefList::~ScUnoRefList()
{
}
void ScUnoRefList::Add( sal_Int64 nId, const ScRangeList& rOldRanges )
{
aEntries.push_back( ScUnoRefEntry( nId, rOldRanges ) );
}
void ScUnoRefList::Undo( ScDocument* pDoc )
{
std::list<ScUnoRefEntry>::const_iterator aEnd( aEntries.end() );
for ( std::list<ScUnoRefEntry>::const_iterator aIter( aEntries.begin() );
aIter != aEnd; ++aIter )
{
ScUnoRefUndoHint aHint( *aIter );
pDoc->BroadcastUno( aHint );
}
}
//------------------------------------------------------------------------
TYPEINIT1(ScUnoRefUndoHint, SfxHint);
ScUnoRefUndoHint::ScUnoRefUndoHint( const ScUnoRefEntry& rRefEntry ) :
aEntry( rRefEntry )
{
}
ScUnoRefUndoHint::~ScUnoRefUndoHint()
{
}
| 27.957143 | 77 | 0.618293 | Grosskopf |
27f7d4bfcbb0624d36a6f492fcc93315fc86bbb9 | 1,141 | cxx | C++ | Applications/WorkBench/main.cxx | linson7017/MIPF | adf982ae5de69fca9d6599fbbbd4ca30f4ae9767 | [
"ECL-2.0",
"Apache-2.0"
] | 4 | 2017-04-13T06:01:49.000Z | 2019-12-04T07:23:53.000Z | Applications/WorkBench/main.cxx | linson7017/MIPF | adf982ae5de69fca9d6599fbbbd4ca30f4ae9767 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2017-10-27T02:00:44.000Z | 2017-10-27T02:00:44.000Z | Applications/WorkBench/main.cxx | linson7017/MIPF | adf982ae5de69fca9d6599fbbbd4ca30f4ae9767 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-09-06T01:59:07.000Z | 2019-12-04T07:23:54.000Z | #include <QApplication>
//qfmain
#include "iqf_main.h"
//qtxml
#include "Utils/PluginFactory.h"
#include "UIs/QF_Plugin.h"
#ifdef Q_WS_X11
#include <X11/Xlib.h>
#endif
#include "qf_log.h"
int main(int argc, char *argv[])
{
QApplication qtapplication(argc, argv);
std::cout << "*********************************************Initialize Main Control**************************************************" << std::endl;
//Create IQF_Main object, meanwhile assign application entry and library path
QF::IQF_Main* pMain = QF::QF_CreateMainObject(qApp->applicationFilePath().toLocal8Bit().constData(),
qApp->applicationDirPath().toLocal8Bit().constData(), false);
//Load the launcher plugin
pMain->Init("","init-plugins.cfg");
std::cout << "***************************************************Initialized*********************************************************\n" << std::endl;
//Setup launcher
QF::QF_Plugin* launcher = dynamic_cast<QF::QF_Plugin*>(QF::PluginFactory::Instance()->Create("Launcher"));
launcher->SetMainPtr(pMain);
launcher->SetupResource();
return qtapplication.exec();
} | 33.558824 | 154 | 0.568799 | linson7017 |
27f9371977b9d599d725a7c73671a4ead38ad6b0 | 3,819 | cpp | C++ | src/tracer/src/core/medium/heterogeneous.cpp | AirGuanZ/Atrc | a0c4bc1b7bb96ddffff8bb1350f88b651b94d993 | [
"MIT"
] | 358 | 2018-11-29T08:15:05.000Z | 2022-03-31T07:48:37.000Z | src/tracer/src/core/medium/heterogeneous.cpp | happyfire/Atrc | 74cac111e277be53eddea5638235d97cec96c378 | [
"MIT"
] | 23 | 2019-04-06T17:23:58.000Z | 2022-02-08T14:22:46.000Z | src/tracer/src/core/medium/heterogeneous.cpp | happyfire/Atrc | 74cac111e277be53eddea5638235d97cec96c378 | [
"MIT"
] | 22 | 2019-03-04T01:47:56.000Z | 2022-01-13T06:06:49.000Z | #include <agz/tracer/core/medium.h>
#include <agz/tracer/core/texture3d.h>
#include <agz/tracer/utility/phase_function.h>
#include <agz-utils/misc.h>
#include <agz-utils/texture.h>
AGZ_TRACER_BEGIN
class HeterogeneousMedium : public Medium
{
FTransform3 local_to_world_;
RC<const Texture3D> density_;
RC<const Texture3D> albedo_;
RC<const Texture3D> g_;
real max_density_;
real inv_max_density_;
int max_scattering_count_;
public:
HeterogeneousMedium(
const FTransform3 &local_to_world,
RC<const Texture3D> density,
RC<const Texture3D> albedo,
RC<const Texture3D> g,
int max_scattering_count)
{
local_to_world_ = local_to_world;
density_ = std::move(density);
albedo_ = std::move(albedo);
g_ = std::move(g);
max_density_ = density_->max_real();
max_density_ = (std::max)(max_density_, EPS());
inv_max_density_ = 1 / max_density_;
max_scattering_count_ = max_scattering_count;
}
int get_max_scattering_count() const noexcept override
{
return max_scattering_count_;
}
FSpectrum tr(
const FVec3 &a, const FVec3 &b, Sampler &sampler) const noexcept override
{
real result = 1;
real t = 0;
const real t_max = distance(a, b);
for(;;)
{
const real delta_t = -std::log(1 - sampler.sample1().u)
* inv_max_density_;
t += delta_t;
if(t >= t_max)
break;
const FVec3 pos = lerp(a, b, t / t_max);
const FVec3 unit_pos = local_to_world_.apply_inverse_to_point(pos);
const real density = density_->sample_real(unit_pos);
result *= 1 - density / max_density_;
}
return FSpectrum(result);
}
FSpectrum ab(
const FVec3 &a, const FVec3 &b, Sampler &sampler) const noexcept override
{
// FIXME
return tr(a, b, sampler);
}
SampleOutScatteringResult sample_scattering(
const FVec3 &a, const FVec3 &b,
Sampler &sampler, Arena &arena) const noexcept override
{
const real t_max = distance(a, b);
real t = 0;
for(;;)
{
const real delta_t = -std::log(1 - sampler.sample1().u)
* inv_max_density_;
t += delta_t;
if(t >= t_max)
break;
const FVec3 pos = lerp(a, b, t / t_max);
const FVec3 unit_pos = local_to_world_.apply_inverse_to_point(pos);
const real density = density_->sample_real(unit_pos);
if(sampler.sample1().u < density / max_density_)
{
const FSpectrum albedo = albedo_->sample_spectrum(unit_pos);
const real g = g_->sample_real(unit_pos);
MediumScattering scattering;
scattering.pos = pos;
scattering.medium = this;
scattering.wr = (a - b) / t_max;
auto phase_function =
arena.create<HenyeyGreensteinPhaseFunction>(
g, FSpectrum(albedo));
return SampleOutScatteringResult(
scattering, FSpectrum(albedo), phase_function);
}
}
return SampleOutScatteringResult({}, FSpectrum(1), nullptr);
}
};
RC<Medium> create_heterogeneous_medium(
const FTransform3 &local_to_world,
RC<const Texture3D> density,
RC<const Texture3D> albedo,
RC<const Texture3D> g,
int max_scattering_count)
{
return newRC<HeterogeneousMedium>(
local_to_world, std::move(density),
std::move(albedo), std::move(g), max_scattering_count);
}
AGZ_TRACER_END
| 28.5 | 81 | 0.579733 | AirGuanZ |
27fcfebeff3b27791de0b719cb8ce91194fb2163 | 23,275 | cpp | C++ | src/third_party/VisionWorks-1.6-Demos/nvxio/src/NVX/FrameSource/NvMedia/OV10635/ImageCapture.cpp | reveriel/cuda_scheduling_examiner_mirror | 16d2404c0dc8d72f7a13e4a167d3db4c86128a26 | [
"BSD-2-Clause-FreeBSD"
] | 39 | 2017-05-23T00:27:50.000Z | 2022-02-16T07:56:07.000Z | src/third_party/VisionWorks-1.6-Demos/nvxio/src/NVX/FrameSource/NvMedia/OV10635/ImageCapture.cpp | reveriel/cuda_scheduling_examiner_mirror | 16d2404c0dc8d72f7a13e4a167d3db4c86128a26 | [
"BSD-2-Clause-FreeBSD"
] | 2 | 2019-10-22T13:47:39.000Z | 2020-04-03T16:09:04.000Z | src/third_party/VisionWorks-1.6-Demos/nvxio/src/NVX/FrameSource/NvMedia/OV10635/ImageCapture.cpp | reveriel/cuda_scheduling_examiner_mirror | 16d2404c0dc8d72f7a13e4a167d3db4c86128a26 | [
"BSD-2-Clause-FreeBSD"
] | 14 | 2017-09-11T19:59:19.000Z | 2021-02-03T10:00:22.000Z | /*
# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef USE_CSI_OV10635
#include "FrameSource/NvMedia/OV10635/ImageCapture.hpp"
#include "config_capture.h"
#include <NVX/Application.hpp>
#define IMGCAPTURE_BUFFERPOOL_SIZE 20
#define TIMEOUT 100
using namespace nvidiaio::egl_api;
//
// EGL context and Stream initialization routings
//
static bool InitializeEGLDisplay(nvidiaio::ov10635::ImgCapture & ctx)
{
// Obtain the EGL display
ctx.eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (ctx.eglDisplay == EGL_NO_DISPLAY)
{
printf("EGL failed to obtain display.\n");
return false;
}
// Initialize EGL
EGLBoolean eglStatus = eglInitialize(ctx.eglDisplay, 0, 0);
if (!eglStatus)
{
printf("EGL failed to initialize.\n");
return false;
}
return true;
}
static bool InitializeEGLStream(nvidiaio::ov10635::ImgCapture & ctx)
{
static const EGLint streamAttr[] = { EGL_NONE };
EGLint fifo_length = 4, latency = 0, timeout = 0, error = 0;
if(!setupEGLExtensions())
{
printf("%s: eglSetupExtensions failed\n", __func__);
return false;
}
ctx.eglStream = eglCreateStreamKHR(ctx.eglDisplay, streamAttr);
if(ctx.eglStream == EGL_NO_STREAM_KHR)
{
error = eglGetError();
printf("%s: Failed to create egl stream, error: %d\n", __func__, error);
return false;
}
// Set stream attribute
if(!eglStreamAttribKHR(ctx.eglDisplay, ctx.eglStream, EGL_CONSUMER_LATENCY_USEC_KHR, 16000))
{
printf("Consumer: streamAttribKHR EGL_CONSUMER_LATENCY_USEC_KHR failed\n");
}
if(!eglStreamAttribKHR(ctx.eglDisplay, ctx.eglStream, EGL_CONSUMER_ACQUIRE_TIMEOUT_USEC_KHR, 16000))
{
printf("Consumer: streamAttribKHR EGL_CONSUMER_ACQUIRE_TIMEOUT_USEC_KHR failed\n");
}
// Get stream attributes
if(!eglQueryStreamKHR(ctx.eglDisplay, ctx.eglStream, EGL_STREAM_FIFO_LENGTH_KHR, &fifo_length))
{
printf("Consumer: eglQueryStreamKHR EGL_STREAM_FIFO_LENGTH_KHR failed\n");
}
if(!eglQueryStreamKHR(ctx.eglDisplay, ctx.eglStream, EGL_CONSUMER_LATENCY_USEC_KHR, &latency))
{
printf("Consumer: eglQueryStreamKHR EGL_CONSUMER_LATENCY_USEC_KHR failed\n");
}
if(!eglQueryStreamKHR(ctx.eglDisplay, ctx.eglStream, EGL_CONSUMER_ACQUIRE_TIMEOUT_USEC_KHR, &timeout))
{
printf("Consumer: eglQueryStreamKHR EGL_CONSUMER_ACQUIRE_TIMEOUT_USEC_KHR failed\n");
}
// Create EGL stream consumer
CUresult curesult = cuEGLStreamConsumerConnect(&ctx.cudaConnection, ctx.eglStream);
if (CUDA_SUCCESS != curesult)
{
printf("Connect CUDA EGL stream consumer ERROR %d\n", curesult);
return false;
}
// Create EGL stream producer
ctx.eglProducer = NvMediaEglStreamProducerCreate(ctx.device,
ctx.eglDisplay,
ctx.eglStream,
ctx.outputSurfType,
ctx.outputWidth,
ctx.outputHeight);
if(!ctx.eglProducer)
{
printf("%s: Failed to create EGL stream, producer\n", __func__);
return false;
}
return true;
}
static void FinalizeEglDisplay(nvidiaio::ov10635::ImgCapture & ctx)
{
eglTerminate(ctx.eglDisplay);
ctx.eglDisplay = EGL_NO_DISPLAY;
}
static void FinalizeEglStream(nvidiaio::ov10635::ImgCapture & ctx)
{
if(ctx.eglProducer)
{
NvMediaEglStreamProducerDestroy(ctx.eglProducer);
ctx.eglProducer = NULL;
}
cuEGLStreamConsumerDisconnect(&ctx.cudaConnection);
ctx.cudaConnection = NULL;
if(ctx.eglStream)
{
eglDestroyStreamKHR(ctx.eglDisplay, ctx.eglStream);
ctx.eglStream = EGL_NO_STREAM_KHR;
}
}
static NvU32
ImgCapture_displayThreadFunc(void *data)
{
nvidiaio::ov10635::ImgCapture *ctx = (nvidiaio::ov10635::ImgCapture *)data;
NvMediaStatus status;
NvMediaImage *capturedFrame = NULL;
NvMediaImage *imgOut = NULL;
NvU32 i = 0, numFrames = 0, timeout = TIMEOUT;
while(!ctx->quit)
{
// Wait for captured frames
status = ImageCaptureNumAvailableFrames(ctx->icpCtx, &numFrames);
if(status != NVMEDIA_STATUS_OK)
{
LOG_ERR("%s: ImageCaptureNumAvailableFrames failed\n", __func__);
ctx->quit = NVMEDIA_TRUE;
goto done;
}
if(!numFrames)
{
usleep(100);
continue;
}
// Get frame from capture
status = ImageCaptureGetFrame(ctx->icpCtx, &capturedFrame);
if(status != NVMEDIA_STATUS_OK)
{
LOG_ERR("%s: ImageCaptureGetFrame failed\n", __func__);
ctx->quit = NVMEDIA_TRUE;
goto done;
}
// Convert frame and push to EGLStream
{
NVXIO_ASSERT(ctx->convert);
// Setup image for conversion
status = ImageSurfUtilsConvertImage(ctx->convert, capturedFrame);
if(status != NVMEDIA_STATUS_OK)
{
LOG_ERR("%s: ImageSurfUtilsConvertImage failed\n", __func__);
ctx->quit = NVMEDIA_TRUE;
goto done;
}
#if BOARD_CODE_NAME >= DRIVE_PX_BOARD
capturedFrame = NULL;
#endif
timeout = TIMEOUT;
numFrames = 0;
// Check for converted image
while((!numFrames) && timeout--)
{
status = ImageSurfUtilsNumAvailableFrames(ctx->convert,
&numFrames);
if(status != NVMEDIA_STATUS_OK)
{
LOG_ERR("%s: ImageCaptureNumAvailableFrames failed\n", __func__);
ctx->quit = NVMEDIA_TRUE;
goto done;
}
const timespec time = {0, 50000};
nanosleep(&time, NULL);
}
if(numFrames)
{
// Get image from conversion
status = ImageSurfUtilsGetImage(ctx->convert, &imgOut);
if(status != NVMEDIA_STATUS_OK)
{
LOG_ERR("%s: ImageSurfUtilsGetImage failed\n", __func__);
ctx->quit = NVMEDIA_TRUE;
goto done;
}
// push to EGLStream stuff
{
if (!ctx->quit)
{
NvMediaImage * imageToPass = imgOut, * retImage = NULL;
LOG_DBG("%s: EGL producer: Post image %p\n", __func__, imageToPass);
if(NvMediaEglStreamProducerPostImage(ctx->eglProducer,
imageToPass,
NULL) != NVMEDIA_STATUS_OK)
{
printf("%s: NvMediaEglStreamProducerPostImage failed\n", __func__);
ctx->quit = NVMEDIA_TRUE;
break;
}
LOG_DBG("%s: EGL producer Getting image %p\n", __func__, retImage);
NvMediaEglStreamProducerGetImage(ctx->eglProducer, &retImage, 100);
if(retImage)
{
LOG_DBG("%s: EGL producer: Got image %p\n", __func__, retImage);
// Put post-processed buffer on output queue
ImageSurfUtilsReleaseImage(ctx->convert, retImage);
}
LOG_DBG("capture2d_AggrPostProcessorThreadFunc iteraration finished.\n");
}
goto done;
}
}
}
done:
if(capturedFrame)
ImageCaptureReleaseImage(capturedFrame);
i++;
if(ctx->quit)
break;
}
ctx->displayThread.exitedFlag = NVMEDIA_TRUE;
return 0;
}
static NvMediaStatus
ImgCapture_SetConfigCaptureParameters(nvidiaio::ov10635::ImgCapture *ctx,
NvMediaBool aggregateFlag,
ConfigCaptureParameters *param)
{
if (!ctx || !param)
{
LOG_ERR("%s: Bad parameter passed\n");
return NVMEDIA_STATUS_BAD_PARAMETER;
}
memset(param, 0, sizeof(ConfigCaptureParameters));
param->inputFormat = (char *)ctx->captureParams->inputFormat.c_str();
param->surfaceFormat = (char *)ctx->captureParams->surfaceFormat.c_str();
param->resolution = (char *)ctx->captureParams->resolution.c_str();
param->interface = (char *)ctx->captureParams->interface.c_str();
param->csiLanes= ctx->captureParams->csiLanes;
param->embeddedDataLinesTop = ctx->captureParams->embeddedDataLinesTop;
param->embeddedDataLinesBottom = ctx->captureParams->embeddedDataLinesBottom;
param->device = ctx->device;
param->aggregateFlag = aggregateFlag;
param->imagesNum = ctx->imagesNum;
#if BOARD_CODE_NAME >= DRIVE_PX_BOARD
param->pixelOrder = (ctx->tpgMode) ? NVMEDIA_RAW_PIXEL_ORDER_RGGB :
ctx->extImgDevice->property.pixelOrder;
#endif
if(param->surfaceFormat[0] == '\0')
param->isSurfaceFormatUsed = NVMEDIA_FALSE;
else
param->isSurfaceFormatUsed = NVMEDIA_TRUE;
return NVMEDIA_STATUS_OK;
}
static void
ImgCapture_SetImageCaptureTestConfigSettings(nvidiaio::ov10635::ImgCapture *ctx,
ImageCaptureTestConfig *icpTestConfig)
{
memset(icpTestConfig, 0, sizeof(ImageCaptureTestConfig));
icpTestConfig->numBuffers = IMGCAPTURE_BUFFERPOOL_SIZE;
icpTestConfig->quitFlag = &ctx->quit;
#if BOARD_CODE_NAME >= DRIVE_PX_BOARD
icpTestConfig->numMiniburstFrames = 1;
#endif
}
static void
ImgCapture_SetImageSurfUtilsParameters(nvidiaio::ov10635::ImgCapture *ctx,
NvU32 inputWidth,
NvU32 inputHeight,
ImageSurfUtilsParameters *convertParam)
{
memset(convertParam, 0, sizeof(ImageSurfUtilsParameters));
convertParam->inputFormat = (char *)ctx->captureParams->inputFormat.c_str();
convertParam->inputWidth = inputWidth;
convertParam->inputHeight = inputHeight;
convertParam->rawBytesPerPixel = ctx->rawBytesPerPixel;
#if BOARD_CODE_NAME >= DRIVE_PX_BOARD
convertParam->pixelOrder = ctx->extImgDevice->property.pixelOrder;
#endif
convertParam->quitFlag = &ctx->quit;
#if BOARD_CODE_NAME >= DRIVE_PX2_BOARD
convertParam->bDisplay = NVMEDIA_TRUE;
#endif
}
#if BOARD_CODE_NAME == JETSON_PRO_BOARD
static NvMediaStatus
ImgCapture_SetConfigISCInfoParameters(nvidiaio::ov10635::ImgCapture *ctx)
{
CaptureConfigParams *captureParams = ctx->captureParams;
ConfigISCInfo *iscConfigInfo = &ctx->iscConfigInfo;
iscConfigInfo->max9286_address = captureParams->desAddr;
iscConfigInfo->broadcast_max9271_address = captureParams->brdcstSerAddr;
iscConfigInfo->broadcast_sensor_address = captureParams->brdcstSensorAddr;
for(unsigned int i = 0; i < MAX_AGGREGATE_IMAGES; i++)
{
iscConfigInfo->max9271_address[i] = captureParams->serAddr[i];
iscConfigInfo->sensor_address[i] = captureParams->sensorAddr[i];
}
iscConfigInfo->i2cDevice = captureParams->i2cDevice;
ctx->captureModuleName = (char *)captureParams->inputDevice.c_str();
iscConfigInfo->board = (char *)captureParams->board.c_str();
iscConfigInfo->resolution = (char *)captureParams->resolution.c_str();
iscConfigInfo->sensorsNum = ctx->imagesNum;
if(captureParams->inputFormat == "raw10")
iscConfigInfo->rawCompressionFormat = ISC_RAW10;
else if(captureParams->inputFormat == "raw12")
iscConfigInfo->rawCompressionFormat = ISC_RAW1x12;
else if(captureParams->inputFormat == "raw2x11")
iscConfigInfo->rawCompressionFormat = ISC_RAW2x11;
else if(captureParams->inputFormat == "raw16log")
iscConfigInfo->rawCompressionFormat = ISC_RAW16LOG;
return NVMEDIA_STATUS_OK;
}
#else
static NvMediaStatus
ImgCapture_SetExtImgDevParameters(nvidiaio::ov10635::ImgCapture *ctx, ExtImgDevParam *configParam)
{
unsigned int i;
CaptureConfigParams *captureParams = ctx->captureParams;
configParam->desAddr = captureParams->desAddr;
configParam->brdcstSerAddr = captureParams->brdcstSerAddr;
configParam->brdcstSensorAddr = captureParams->brdcstSensorAddr;
for(i = 0; i < MAX_AGGREGATE_IMAGES; i++)
{
configParam->serAddr[i] = captureParams->serAddr[i];
configParam->sensorAddr[i] = captureParams->sensorAddr[i];
}
configParam->i2cDevice = captureParams->i2cDevice;
configParam->moduleName = (char *)captureParams->inputDevice.c_str();
configParam->board = (char *)captureParams->board.c_str();
configParam->resolution = (char *)captureParams->resolution.c_str();
configParam->camMap = &ctx->camMap;
configParam->sensorsNum = ctx->imagesNum;
configParam->inputFormat = (char *)captureParams->inputFormat.c_str();
configParam->interface = (char *)captureParams->interface.c_str();
configParam->enableEmbLines =
(captureParams->embeddedDataLinesTop || captureParams->embeddedDataLinesBottom) ?
NVMEDIA_TRUE : NVMEDIA_FALSE;
configParam->initialized = NVMEDIA_FALSE;
configParam->enableSimulator = NVMEDIA_FALSE;
return NVMEDIA_STATUS_OK;
}
#endif
namespace nvidiaio { namespace ov10635 {
NvMediaStatus
ImgCapture_Init(ImgCapture **ctx, CaptureConfigParams & captureConfigCollection, NvU32 imagesNum)
{
if (nvxio::Application::get().getVerboseFlag())
SetLogLevel(LEVEL_DBG);
NvMediaStatus status;
ImgCapture *ctxTmp = nullptr;
ImageCaptureTestConfig icpTestConfig;
ImageSurfUtilsParameters convertParam;
ConfigCaptureParameters configParam;
ConfigCaptureSettings configSettings;
NvMediaBool useAggregationFlag = NVMEDIA_TRUE;
#if BOARD_CODE_NAME >= DRIVE_PX_BOARD
ExtImgDevParam extImgDevParam;
#endif
NvU32 inputWidth = 0;
NvU32 inputHeight = 0;
memset(&configSettings, 0, sizeof(ConfigCaptureSettings));
if(!ctx)
{
LOG_ERR("%s: Bad parameter", __func__);
return NVMEDIA_STATUS_BAD_PARAMETER;
}
// Create and initialize ImgCapture context
ctxTmp = (ImgCapture *)calloc(1, sizeof(ImgCapture));
if(!ctxTmp)
{
LOG_ERR("%s: Out of memory", __func__);
return NVMEDIA_STATUS_OUT_OF_MEMORY;
}
if(imagesNum > NVMEDIA_MAX_AGGREGATE_IMAGES)
{
LOG_WARN("Max aggregate images is: %u\n",
NVMEDIA_MAX_AGGREGATE_IMAGES);
imagesNum = NVMEDIA_MAX_AGGREGATE_IMAGES;
}
ctxTmp->imagesNum = imagesNum;
ctxTmp->displayThread.exitedFlag = NVMEDIA_TRUE;
ctxTmp->captureParams = &captureConfigCollection;
ctxTmp->tpgMode = NVMEDIA_FALSE;
#if BOARD_CODE_NAME >= DRIVE_PX_BOARD
ctxTmp->camMap.enable = EXTIMGDEV_MAP_N_TO_ENABLE(imagesNum);
ctxTmp->camMap.mask = CAM_MASK_DEFAULT;
ctxTmp->camMap.csiOut = CSI_OUT_DEFAULT;
#endif
if (sscanf(ctxTmp->captureParams->resolution.c_str(), "%ux%u", &inputWidth, &inputHeight) != 2)
{
LOG_ERR("%s: Invalid input resolution %s\n", __func__, ctxTmp->captureParams->resolution.c_str());
status = NVMEDIA_STATUS_ERROR;
goto failed;
}
if (useAggregationFlag)
inputWidth *= imagesNum;
ctxTmp->outputWidth = inputWidth;
ctxTmp->outputHeight = inputHeight;
ctxTmp->outputSurfType = NvMediaSurfaceType_Image_RGBA;
if (captureConfigCollection.inputFormat == "raw12")
{
ctxTmp->outputWidth >>= 1;
ctxTmp->outputHeight >>= 1;
}
// create EGLDisplay
if (!InitializeEGLDisplay(*ctxTmp))
{
status = NVMEDIA_STATUS_ERROR;
LOG_ERR("%s: Failed to initialize EGLDisplay\n", __func__);
goto failed;
}
// create EGLStream
if (!InitializeEGLStream(*ctxTmp))
{
status = NVMEDIA_STATUS_ERROR;
LOG_ERR("%s: Failed to initialize EGLStream\n", __func__);
goto failed;
}
#if BOARD_CODE_NAME > JETSON_PRO_BOARD
extImgDevParam.slave = NVMEDIA_FALSE;
status = ImgCapture_SetExtImgDevParameters(ctxTmp, &extImgDevParam);
if(status != NVMEDIA_STATUS_OK)
{
LOG_ERR("%s: Failed to set ISC device parameters\n", __func__);
goto failed;
}
ctxTmp->extImgDevice = ExtImgDevInit(&extImgDevParam);
if(!ctxTmp->extImgDevice)
{
LOG_ERR("%s: Failed to initialize ISC devices\n", __func__);
status = NVMEDIA_STATUS_ERROR;
goto failed;
}
#endif
// Create NvMedia Device
ctxTmp->device = NvMediaDeviceCreate();
if(!ctxTmp->device)
{
status = NVMEDIA_STATUS_ERROR;
LOG_ERR("%s: Failed to create NvMedia device\n", __func__);
goto failed;
}
// Configure and set capture settings
status = ImgCapture_SetConfigCaptureParameters(ctxTmp,
useAggregationFlag,
&configParam);
if(status != NVMEDIA_STATUS_OK)
{
LOG_ERR("%s: Failed to set capture parameters\n", __func__);
goto failed;
}
status = ConfigCaptureProcessParameters(&configParam,
&configSettings);
if(status != NVMEDIA_STATUS_OK)
{
LOG_ERR("%s: Failed to process capture parameters\n", __func__);
goto failed;
}
ctxTmp->rawBytesPerPixel = ConfigCaptureGetRawBytesPerPixel(&configSettings);
ImgCapture_SetImageCaptureTestConfigSettings(ctxTmp, &icpTestConfig);
// Initialize and create converter
{
ImgCapture_SetImageSurfUtilsParameters(ctxTmp,
inputWidth,
inputHeight,
&convertParam);
status = ImageSurfUtilsCreate(&ctxTmp->convert, ctxTmp->device,
&convertParam);
if(status != NVMEDIA_STATUS_OK)
{
LOG_ERR("%s: Failed to create ImageSurfUtils context\n", __func__);
goto failed;
}
}
// Configure and create ISC devices
#if BOARD_CODE_NAME == JETSON_PRO_BOARD
status = ImgCapture_SetConfigISCInfoParameters(ctxTmp);
if(status != NVMEDIA_STATUS_OK)
{
LOG_ERR("%s: Failed to set ISC device parameters\n", __func__);
goto failed;
}
ctxTmp->iscConfigInfo.inputSurfType = configSettings.poolConfig.surfType;
ctxTmp->iscConfigInfo.csi_link = configSettings.settings.interfaceType;
status = ConfigISCCreateDevices(&ctxTmp->iscConfigInfo,
&ctxTmp->iscDevices,
NVMEDIA_FALSE,
ctxTmp->captureModuleName);
if(status != NVMEDIA_STATUS_OK)
{
LOG_ERR("%s: Failed to create ISC devices\n", __func__);
goto failed;
}
#endif
// Create capture context and thread
status = ImageCaptureCreate(&ctxTmp->icpCtx,
ConfigCaptureGetICPSettings(&configSettings),
ConfigCaptureGetBufferPoolConfig(&configSettings),
&icpTestConfig);
if(status != NVMEDIA_STATUS_OK)
{
LOG_ERR("%s: Failed to create ImageCapture Context\n", __func__);
goto failed;
}
// Create thread to save and/or display frames
ctxTmp->displayThread.exitedFlag = NVMEDIA_FALSE;
status = NvThreadCreate(&ctxTmp->displayThread.thread,
ImgCapture_displayThreadFunc,
(void *)ctxTmp, NV_THREAD_PRIORITY_NORMAL);
if(status != NVMEDIA_STATUS_OK)
{
LOG_ERR("%s: Failed to create save and display thread\n",
__func__);
ctxTmp->displayThread.exitedFlag = NVMEDIA_TRUE;
goto failed;
}
#if BOARD_CODE_NAME >= DRIVE_PX2_BOARD
// Start ExtImgDevice
if(ctxTmp->extImgDevice)
ExtImgDevStart(ctxTmp->extImgDevice);
#endif
*ctx = ctxTmp;
return NVMEDIA_STATUS_OK;
failed:
LOG_ERR("%s: Failed to initialize ImgCapture\n",__func__);
ImgCapture_Finish(ctxTmp);
return status;
}
void
ImgCapture_Finish(ImgCapture *ctx)
{
NvMediaStatus status;
ctx->quit = NVMEDIA_TRUE;
// Wait for all threads to exit
while(!ctx->displayThread.exitedFlag)
{
LOG_DBG("%s: Waiting for save and display thread to quit\n",
__func__);
usleep(1000);
}
if(ctx->icpCtx)
ImageCaptureDestroy(ctx->icpCtx);
// Dispose converter
if (ctx->convert)
ImageSurfUtilsDestroy(ctx->convert);
// Destroy threads
if(ctx->displayThread.thread)
{
status = NvThreadDestroy(ctx->displayThread.thread);
if(status != NVMEDIA_STATUS_OK)
LOG_ERR("%s: Failed to destroy save and display thread\n", __func__);
}
#if BOARD_CODE_NAME == JETSON_PRO_BOARD
ConfigISCDestroyDevices(&ctx->iscConfigInfo, &ctx->iscDevices);
#else
if (ctx->extImgDevice)
ExtImgDevDeinit(ctx->extImgDevice);
#endif
// Finalize EGL Stuff
FinalizeEglStream(*ctx);
FinalizeEglDisplay(*ctx);
free(ctx);
}
} // namespace ov10635
} // namespace nvidiaio
#endif // USE_CSI_OV10635
| 32.874294 | 106 | 0.630333 | reveriel |
27feaafbd6e5d8ad98ca139ed48012a2e7c4f153 | 4,199 | hpp | C++ | include/cmbml/behavior/reader_state_machine_actions.hpp | osrf/cmbml | 3804228f192db676b3e0b06d040f03bed545df61 | [
"Apache-2.0"
] | 1 | 2020-03-26T20:12:52.000Z | 2020-03-26T20:12:52.000Z | include/cmbml/behavior/reader_state_machine_actions.hpp | osrf/cmbml | 3804228f192db676b3e0b06d040f03bed545df61 | [
"Apache-2.0"
] | null | null | null | include/cmbml/behavior/reader_state_machine_actions.hpp | osrf/cmbml | 3804228f192db676b3e0b06d040f03bed545df61 | [
"Apache-2.0"
] | null | null | null | #ifndef CMBML__READER_STATE_MACHINE_ACTIONS__HPP_
#define CMBML__READER_STATE_MACHINE_ACTIONS__HPP_
#include <cmbml/structure/reader.hpp>
#include <cmbml/types.hpp>
#include <cmbml/structure/history.hpp>
#include <cmbml/message/data.hpp>
namespace cmbml {
auto on_reader_created = [](auto & e) {
WriterProxy writer_proxy(e.remote_writer_guid, e.unicast_locators, e.multicast_locators);
e.reader.add_matched_writer(std::move(writer_proxy));
// TODO WriterProxy is initialized with all past and future samples from the Writer
// as discussed in 8.4.10.4.
};
auto on_reader_deleted = [](auto & e) {
e.reader.remove_matched_writer(e.writer);
};
auto on_data_received_stateless = [](auto & e) {
CacheChange change(e.data);
e.reader.reader_cache.add_change(std::move(change));
};
auto on_heartbeat = [](auto & e) {
assert(e.writer);
e.writer->update_missing_changes(e.heartbeat.last_sn);
e.writer->update_lost_changes(e.heartbeat.first_sn);
};
auto on_data = [](auto & e) {
CacheChange change(e.data);
e.reader.reader_cache.add_change(std::move(change));
// TODO Check that this lookup is correct.
GUID_t writer_guid = {e.receiver.source_guid_prefix, e.data.writer_id};
WriterProxy * proxy = e.reader.matched_writer_lookup(writer_guid);
// TODO: This could be a warning in production.
assert(proxy);
proxy->set_received_change(change.sequence_number);
};
auto on_gap = [](auto & e) {
assert(e.writer);
// Does the spec describe a range or a pair? Look at other impls
// I think it's safe to say it's a pair
for (const auto & seq_num : {e.gap.gap_start.value(), e.gap.gap_list.base.value() - 1}) {
e.writer->set_irrelevant_change(seq_num);
}
for (const auto & seq_num : e.gap.gap_list.set) {
e.writer->set_irrelevant_change(seq_num.value());
}
};
auto on_heartbeat_response_delay = [](auto & e) {
SequenceNumberSet missing_seq_num_set({e.writer.max_available_changes() + 1});
assert(missing_seq_num_set.set.empty());
for (const auto & change : e.writer.missing_changes()) {
missing_seq_num_set.set.push_back(change.sequence_number);
}
// TODO Implement send and maybe a constructor for acknack
// TODO see spec page 127 for capacity handling behavior in sequence set
AckNack acknack;
acknack.reader_id = e.reader_id;
acknack.writer_id = e.writer.get_guid().entity_id;
acknack.reader_sn_state = std::move(missing_seq_num_set);
// Current setting final=1, which means we do not expect a response from the writer
acknack.final_flag = 1;
e.writer.send(std::move(acknack), e.transport_context);
};
auto on_data_received_stateful = [](auto & e) {
CacheChange change(e.data);
GUID_t writer_guid = {e.receiver.source_guid_prefix, e.data.writer_id};
WriterProxy * writer_proxy = e.reader.matched_writer_lookup(writer_guid);
assert(writer_proxy);
// XXX: This is only needed for the assert at the end
const SequenceNumber_t & seq = change.sequence_number;
SequenceNumber_t expected_seq_num = writer_proxy->max_available_changes() + 1;
if (change.sequence_number >= expected_seq_num) {
writer_proxy->set_received_change(change.sequence_number);
if (change.sequence_number > expected_seq_num) {
writer_proxy->update_lost_changes(change.sequence_number);
}
e.reader.reader_cache.add_change(std::move(change));
}
assert(writer_proxy->max_available_changes() >= seq);
};
// Entry functions
// TODO: bind executor: pass to the state machine, pass timer values...
auto on_must_ack_entry = [](auto & e) {
auto on_timer = []() {
// event<heartbeat_response_delay> h;
// state_machine.process_event(h);
};
// executor.add_timed_task(heartbeat_response_delay, on_timer);
};
// Guards
auto not_final_guard = [](auto & e) {
return !e.heartbeat.final_flag;
};
// Small subtlety based on literal interpretation of precedence in spec
auto not_live_guard = [](auto & e) {
return e.heartbeat.final_flag && !e.heartbeat.liveliness_flag;
};
}
#endif // CMBML__READER_STATE_MACHINE_ACTIONS__HPP_
| 37.491071 | 93 | 0.705882 | osrf |
27ff2c22dafd0a4ad0ed52b585bd84ce243fb6b4 | 1,326 | cpp | C++ | example/nulldemo/nullcontroller_main.cpp | byllyfish/oftr | ac1e4ef09388376ea6fa7b460b6abe2ab3471624 | [
"MIT"
] | 1 | 2019-06-14T13:57:28.000Z | 2019-06-14T13:57:28.000Z | example/nulldemo/nullcontroller_main.cpp | byllyfish/oftr | ac1e4ef09388376ea6fa7b460b6abe2ab3471624 | [
"MIT"
] | 20 | 2017-02-20T04:49:10.000Z | 2019-07-09T05:32:54.000Z | example/nulldemo/nullcontroller_main.cpp | byllyfish/oftr | ac1e4ef09388376ea6fa7b460b6abe2ab3471624 | [
"MIT"
] | 1 | 2019-07-16T00:21:42.000Z | 2019-07-16T00:21:42.000Z | // Copyright (c) 2015-2018 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.
#include <iostream>
#include "ofp/ofp.h"
using namespace ofp;
class NullController : public ChannelListener {
public:
void onChannelUp(Channel *channel) override {
log_debug(__PRETTY_FUNCTION__);
}
void onMessage(Message *message) override {}
static ChannelListener *Factory() { return new NullController; }
};
int main(int argc, char **argv) {
log::configure(log::Level::Debug);
std::vector<std::string> args{argv + 1, argv + argc};
IPv6Address addr;
if (!args.empty()) {
addr = IPv6Address{args[0]};
}
Driver driver;
driver.installSignalHandlers();
if (addr.valid()) {
(void)driver.connect(
ChannelOptions::FEATURES_REQ, 0,
IPv6Endpoint{addr, OFPGetDefaultPort()}, ProtocolVersions::All,
NullController::Factory, [](Channel *channel, std::error_code err) {
std::cout << "Result: connId=" << channel->connectionId()
<< " err=" << err << '\n';
});
} else {
std::error_code err;
(void)driver.listen(ChannelOptions::FEATURES_REQ, 0,
IPv6Endpoint{OFPGetDefaultPort()},
ProtocolVersions::All, NullController::Factory, err);
}
driver.run();
}
| 26 | 77 | 0.634238 | byllyfish |
7e061b21f22d9c5e4f585bf7e991810c4974be77 | 554 | cpp | C++ | src/ShowAlwaysOn.cpp | joergkeller/arduino-musicbox | 2fbbfabd77a9daf6fdc73b6212416be7ec7bca22 | [
"MIT"
] | null | null | null | src/ShowAlwaysOn.cpp | joergkeller/arduino-musicbox | 2fbbfabd77a9daf6fdc73b6212416be7ec7bca22 | [
"MIT"
] | 7 | 2019-05-12T22:08:55.000Z | 2021-04-29T12:26:25.000Z | src/ShowAlwaysOn.cpp | joergkeller/arduino-musicbox | 2fbbfabd77a9daf6fdc73b6212416be7ec7bca22 | [
"MIT"
] | null | null | null | /*
* Constantly switch on all lights of the trellis display.
*
* Written by Jörg Keller, Winterthur, Switzerland
* https://github.com/joergkeller/arduino-musicbox
* MIT license, all text above must be included in any redistribution
*/
#include "ShowAlwaysOn.h"
ShowAlwaysOn::ShowAlwaysOn(const Adafruit_Trellis& t)
: trellis(t) {}
void ShowAlwaysOn::initialize() {
trellis.setBrightness(BRIGHTNESS_IDLE);
trellis.blinkRate(HT16K33_BLINK_OFF);
for (byte i = 0; i < NUMKEYS; i++) {
trellis.setLED(i);
}
trellis.writeDisplay();
}
| 25.181818 | 69 | 0.722022 | joergkeller |
7e0632a6b7ea90d7a3fcf349fdf244bc5716bea7 | 53 | cpp | C++ | unit_test/cuda/Test_Cuda_Blas_gesv.cpp | hmaarrfk/kokkos-kernels | d86db111124cea12e23dd3447b6c307f96ef7439 | [
"BSD-3-Clause"
] | null | null | null | unit_test/cuda/Test_Cuda_Blas_gesv.cpp | hmaarrfk/kokkos-kernels | d86db111124cea12e23dd3447b6c307f96ef7439 | [
"BSD-3-Clause"
] | 1 | 2019-07-03T18:02:17.000Z | 2019-07-03T22:54:16.000Z | unit_test/cuda/Test_Cuda_Blas_gesv.cpp | hmaarrfk/kokkos-kernels | d86db111124cea12e23dd3447b6c307f96ef7439 | [
"BSD-3-Clause"
] | null | null | null | #include<Test_Cuda.hpp>
#include<Test_Blas_gesv.hpp>
| 17.666667 | 28 | 0.811321 | hmaarrfk |
7e06ef896353231f4eff47e0e43f4e24ef7d53cf | 1,164 | cpp | C++ | src/drawing/foundation/Colour.cpp | andystanton/lana-tetris | df39d2c157d9f7eb587801315a4c3079a937de72 | [
"MIT"
] | 3 | 2021-05-14T17:56:11.000Z | 2022-01-25T10:00:40.000Z | src/drawing/foundation/Colour.cpp | andystanton/lana-tetris | df39d2c157d9f7eb587801315a4c3079a937de72 | [
"MIT"
] | null | null | null | src/drawing/foundation/Colour.cpp | andystanton/lana-tetris | df39d2c157d9f7eb587801315a4c3079a937de72 | [
"MIT"
] | null | null | null |
#include "Colour.h"
Colour::Colour(const string& name, int r, int g, int b) {
this->r = r;
this->g = g;
this->b = b;
colour = new GLfloat[3];
this->colour[0] = r/255.f;
this->colour[1] = g/255.f;
this->colour[2] = b/255.f;
this->name = name;
}
Colour::Colour(const string& name, float r, float g, float b) {
this->r = r*255;
this->g = g*255;
this->b = b*255;
colour = new GLfloat[3];
this->colour[0] = r;
this->colour[1] = g;
this->colour[2] = b;
this->name = name;
}
Colour::Colour(const string& name, int hexValue) {
r = ((hexValue >> 16) & 0xff);
g = ((hexValue >> 8) & 0xff);
b = (hexValue & 0xff);
colour = new GLfloat[3];
this->colour[0] = r/255.f;
this->colour[1] = g/255.f;
this->colour[2] = b/255.f;
this->name = name;
}
GLfloat* Colour::getColour3fv() {
return colour;
}
Colour::~Colour() {
delete colour;
colour = nullptr;
}
float Colour::getR() {
return r/255.f;
}
float Colour::getG() {
return g/255.f;
}
float Colour::getB() {
return b/255.f;
}
string* Colour::toString() {
return &name;
}
| 17.373134 | 63 | 0.536082 | andystanton |
7e07dac253ac857403e4b9a58e497f2dec093b05 | 1,919 | cc | C++ | NEST-14.0-FPGA/sli/oosupport.cc | OpenHEC/SNN-simulator-on-PYNQcluster | 14f86a76edf4e8763b58f84960876e95d4efc43a | [
"MIT"
] | 45 | 2019-12-09T06:45:53.000Z | 2022-01-29T12:16:41.000Z | NEST-14.0-FPGA/sli/oosupport.cc | zlchai/SNN-simulator-on-PYNQcluster | 14f86a76edf4e8763b58f84960876e95d4efc43a | [
"MIT"
] | 2 | 2020-05-23T05:34:21.000Z | 2021-09-08T02:33:46.000Z | NEST-14.0-FPGA/sli/oosupport.cc | OpenHEC/SNN-simulator-on-PYNQcluster | 14f86a76edf4e8763b58f84960876e95d4efc43a | [
"MIT"
] | 10 | 2019-12-09T06:45:59.000Z | 2021-03-25T09:32:56.000Z | /*
* oosupport.cc
*
* This file is part of NEST.
*
* Copyright (C) 2004 The NEST Initiative
*
* NEST is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* NEST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NEST. If not, see <http://www.gnu.org/licenses/>.
*
*/
/*
SLI's data access functions
*/
#include "oosupport.h"
// Includes from sli:
#include "dictdatum.h"
#include "dictstack.h"
#include "namedatum.h"
void
OOSupportModule::init( SLIInterpreter* i )
{
i->createcommand( "call", &callmemberfunction );
}
const std::string
OOSupportModule::commandstring( void ) const
{
return std::string( "(oosupport.sli) run" );
}
const std::string
OOSupportModule::name( void ) const
{
return std::string( "OOSupport" );
}
void
OOSupportModule::CallMemberFunction::execute( SLIInterpreter* i ) const
{
// call: dict key call -> unknown
DictionaryDatum* dict =
dynamic_cast< DictionaryDatum* >( i->OStack.pick( 1 ).datum() );
assert( dict != NULL );
LiteralDatum* key =
dynamic_cast< LiteralDatum* >( i->OStack.pick( 0 ).datum() );
assert( key != NULL );
Token value = ( *dict )->lookup( *key );
if ( value.datum() != NULL )
{
Token nt( new NameDatum( *key ) );
i->DStack->push( *dict );
i->EStack.pop(); // never forget me
i->EStack.push( i->baselookup( i->end_name ) );
i->EStack.push_move( nt );
i->OStack.pop( 2 );
}
else
{
i->raiseerror( "UnknownMember" );
}
}
| 23.9875 | 72 | 0.663366 | OpenHEC |
7e0d343109dfea3b9c1cc5bb77248222b6979b1d | 1,114 | cpp | C++ | 02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/12_Judge_Assignment_3_(7_July_2018)/03_Teams.cpp | Knightwalker/Knowledgebase | 00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161 | [
"MIT"
] | null | null | null | 02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/12_Judge_Assignment_3_(7_July_2018)/03_Teams.cpp | Knightwalker/Knowledgebase | 00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161 | [
"MIT"
] | null | null | null | 02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/12_Judge_Assignment_3_(7_July_2018)/03_Teams.cpp | Knightwalker/Knowledgebase | 00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161 | [
"MIT"
] | null | null | null | #include <iostream>;
#include <string>;
#include <unordered_set>
#include <unordered_map>
#include <map>;
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::map;
using std::unordered_map;
using std::unordered_set;
int main() {
std::cin.sync_with_stdio(false);
std::cout.sync_with_stdio(false);
map<string, int> playersDict;
unordered_map<string, unordered_set<string>> teamsDict;
int t = 0; cin >> t;
for (int i = 0; i < t; i++) {
string team = ""; cin >> team;
int teamSize = 0; cin >> teamSize;
for (int j = 0; j < teamSize; j++) {
string teamMember = ""; cin >> teamMember;
teamsDict[team].insert(teamMember);
playersDict[teamMember] = 0;
}
}
int g = 0; cin >> g;
for (int i = 0; i < g; i++) {
string team = ""; cin >> team;
std::unordered_map<string, unordered_set<string>>::iterator foundTeam = teamsDict.find(team);
if (foundTeam != teamsDict.end()) {
for (auto const& player : foundTeam->second) {
playersDict[player]++;
}
}
}
// output
for (auto const& player : playersDict) {
cout << player.second << " ";
}
} | 20.62963 | 95 | 0.631957 | Knightwalker |
7e0e20571e65425e820aaa66dbf3d6afa3724856 | 559 | cpp | C++ | Graph/dijkstra.cpp | JanaSabuj/CodingLibrary | 92bc141ae327ce01b480fde7a10ffb0be0ba401d | [
"MIT"
] | 14 | 2020-05-17T18:31:32.000Z | 2021-02-04T03:56:30.000Z | Graph/dijkstra.cpp | JanaSabuj/cppdump | 92bc141ae327ce01b480fde7a10ffb0be0ba401d | [
"MIT"
] | null | null | null | Graph/dijkstra.cpp | JanaSabuj/cppdump | 92bc141ae327ce01b480fde7a10ffb0be0ba401d | [
"MIT"
] | 2 | 2020-05-27T10:42:36.000Z | 2021-02-02T11:59:04.000Z | vector<pii> adj[N];
priority_queue<pii, vector<pii>, greater<pii>> pq;
int dis[N];
void dijkstra(int src) {
for (int i = 0; i < N; ++i) {
dis[i] = LLONG_MAX;
}
pq.push({0, src});
dis[src] = 0;
while (!pq.empty()) {
auto curr = pq.top();
pq.pop();
int v = curr.second;
int d_v = curr.first;
if (d_v != dis[v])
continue;// stale pair
for (auto u : adj[v]) {
int to = u.first;
int len = u.second;
if (dis[v] + len < dis[to]) {
dis[to] = dis[v] + len;
pq.push({dis[to], to});
}
}
}
} | 18.032258 | 51 | 0.495528 | JanaSabuj |
7e0ed2ed9273a7f594c83ab02d157548ca530ace | 1,483 | cpp | C++ | solved/c-e/dynamic-frog/frog.cpp | abuasifkhan/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-09-30T19:18:04.000Z | 2021-06-26T21:11:30.000Z | solved/c-e/dynamic-frog/frog.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | null | null | null | solved/c-e/dynamic-frog/frog.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-01-04T09:49:54.000Z | 2021-06-03T13:18:44.000Z | #include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
#define MAXN 100
#define Zero(v) memset((v), 0, sizeof(v))
int N, D;
int rocks[MAXN + 2];
int n;
bool vis[MAXN + 2];
bool check(int d)
{
Zero(vis);
int from = 0, to = 0;
for (int i = 1; i < n; ++i) {
if (rocks[i] - rocks[from] <= d) { to = i; continue; }
vis[to] = true;
from = to, to = i;
if (rocks[to] - rocks[from] > d) return false;
}
vis[n-1] = false;
from = 0;
for (int i = 1; i < n; ++i) {
if (vis[i]) continue;
if (rocks[i] - rocks[from] > d) return false;
from = i;
}
return true;
}
int shortest()
{
int lo = 0, hi = rocks[n - 1] - rocks[0];
while (lo <= hi) {
int mid = (hi + lo) / 2;
if (check(mid)) hi = mid - 1;
else lo = mid + 1;
}
return lo;
}
int main()
{
int T;
scanf("%d", &T);
int ncase = 0;
while (T--) {
scanf("%d%d", &N, &D);
int ans = 0;
n = 1;
rocks[0] = 0;
for (int i = 0; i < N; ++i) {
char S;
int M;
scanf(" %c-%d", &S, &M);
rocks[n++] = M;
if (S == 'B') {
ans = max(ans, shortest());
n = 1;
rocks[0] = M;
}
}
rocks[n++] = D;
ans = max(ans, shortest());
printf("Case %d: %d\n", ++ncase, ans);
}
return 0;
}
| 16.662921 | 62 | 0.403237 | abuasifkhan |
7e1138342c72fe7393be850a40fe3caadc53f764 | 250 | hh | C++ | User/motor/HBridge.hh | synergia/synermycha-firmware-stm32 | 990bcc057d6cf7a3719524014b8c2babb5d2baf5 | [
"MIT"
] | null | null | null | User/motor/HBridge.hh | synergia/synermycha-firmware-stm32 | 990bcc057d6cf7a3719524014b8c2babb5d2baf5 | [
"MIT"
] | 21 | 2020-03-06T20:11:32.000Z | 2021-02-25T17:15:44.000Z | User/motor/HBridge.hh | synergia/synermycha-firmware-stm32 | 990bcc057d6cf7a3719524014b8c2babb5d2baf5 | [
"MIT"
] | null | null | null | #pragma once
#include "utils/HalUtils.hh"
class HBridge
{
public:
HBridge(GpioPort portEnable, GpioPin pinEnable);
void initialize();
void enable();
void disable();
private:
GpioPort mPortEnable;
GpioPin mPinEnable;
}; | 14.705882 | 52 | 0.676 | synergia |
7e117928c5361185524e258430ca1ae09e6aa5f2 | 1,247 | cpp | C++ | aws-cpp-sdk-datapipeline/source/model/RemoveTagsRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-datapipeline/source/model/RemoveTagsRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-datapipeline/source/model/RemoveTagsRequest.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/datapipeline/model/RemoveTagsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::DataPipeline::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
RemoveTagsRequest::RemoveTagsRequest() :
m_pipelineIdHasBeenSet(false),
m_tagKeysHasBeenSet(false)
{
}
Aws::String RemoveTagsRequest::SerializePayload() const
{
JsonValue payload;
if(m_pipelineIdHasBeenSet)
{
payload.WithString("pipelineId", m_pipelineId);
}
if(m_tagKeysHasBeenSet)
{
Array<JsonValue> tagKeysJsonList(m_tagKeys.size());
for(unsigned tagKeysIndex = 0; tagKeysIndex < tagKeysJsonList.GetLength(); ++tagKeysIndex)
{
tagKeysJsonList[tagKeysIndex].AsString(m_tagKeys[tagKeysIndex]);
}
payload.WithArray("tagKeys", std::move(tagKeysJsonList));
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection RemoveTagsRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "DataPipeline.RemoveTags"));
return headers;
}
| 22.267857 | 93 | 0.744186 | Neusoft-Technology-Solutions |
7e12279f45de48bf733b2984cf350751b11a54a0 | 838 | cpp | C++ | src/util/util.cpp | TijnBertens/light-show | a95c63b96643b9ec5dead495ffc6f45048bfee5f | [
"MIT"
] | 1 | 2020-11-10T22:05:19.000Z | 2020-11-10T22:05:19.000Z | src/util/util.cpp | TijnBertens/light-show | a95c63b96643b9ec5dead495ffc6f45048bfee5f | [
"MIT"
] | null | null | null | src/util/util.cpp | TijnBertens/light-show | a95c63b96643b9ec5dead495ffc6f45048bfee5f | [
"MIT"
] | null | null | null | #include "util.hpp"
int Util::read_file(char **buffer, size_t *size, const char *file_name)
{
FILE *file = fopen(file_name, "rb");
if (!file) {
ls_log::log(LOG_ERROR, "failed to open file \"%s\"\n", file_name);
return EXIT_FAILURE;
}
fseek(file, 0, SEEK_END);
*size = ftell(file);
rewind(file);
*buffer = new char[*size + 1]; // +1 for null terminator
if (!(*buffer)) {
ls_log::log(LOG_ERROR, "failed to allocate %d bytes\n", *size);
fclose(file);
return EXIT_FAILURE;
}
size_t read_size = fread(*buffer, sizeof(char), *size, file);
fclose(file);
if (read_size != *size) {
ls_log::log(LOG_ERROR, "failed to read all bytes in file\n", *size);
return EXIT_FAILURE;
}
(*buffer)[*size] = '\0';
return EXIT_SUCCESS;
} | 23.277778 | 76 | 0.577566 | TijnBertens |
7e14065129dfc400b0987c24236954090dbe741d | 4,811 | cpp | C++ | test_deprecated/testUtil/example_tc_socket.cpp | SuckShit/TarsCpp | 3f42f4e7a7bf43026a782c5d4b033155c27ed0c4 | [
"BSD-3-Clause"
] | 1 | 2019-09-05T07:25:51.000Z | 2019-09-05T07:25:51.000Z | test_deprecated/testUtil/example_tc_socket.cpp | SuckShit/TarsCpp | 3f42f4e7a7bf43026a782c5d4b033155c27ed0c4 | [
"BSD-3-Clause"
] | null | null | null | test_deprecated/testUtil/example_tc_socket.cpp | SuckShit/TarsCpp | 3f42f4e7a7bf43026a782c5d4b033155c27ed0c4 | [
"BSD-3-Clause"
] | 1 | 2021-05-21T09:59:06.000Z | 2021-05-21T09:59:06.000Z | /**
* Tencent is pleased to support the open source community by making Tars available.
*
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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 "util/tc_socket.h"
#include "util/tc_clientsocket.h"
#include "util/tc_http.h"
#include "util/tc_epoller.h"
#include "util/tc_common.h"
#include <iostream>
#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h>
using namespace tars;
string now2str(const string &sFormat = "%Y%m%d%H%M%S")
{
time_t t = time(NULL);
struct tm *pTm = localtime(&t);
if(pTm == NULL)
{
return "";
}
char sTimeString[255] = "\0";
strftime(sTimeString, sizeof(sTimeString), sFormat.c_str(), pTm);
return string(sTimeString);
}
void testTC_Socket()
{
TC_Socket tcSocket;
tcSocket.createSocket();
tcSocket.bind("192.168.128.66", 8765);
tcSocket.listen(5);
}
void testTC_TCPClient()
{
TC_TCPClient tc;
tc.init("172.16.28.79", 8382, 3);
cout << now2str() << endl;
int i = 10000;
while(i>0)
{
string s = "test";
char c[1024] = "\0";
size_t length = 4;
int iRet = tc.sendRecv(s.c_str(), s.length(), c, length);
if(iRet < 0)
{
cout << "send recv error:" << iRet << ":" << c << endl;
}
i--;
// cout << c << endl;
assert(c == s);
}
cout << now2str() << endl;
}
void testShortSock()
{
int i = 1000;
while(i>0)
{
TC_TCPClient tc;
tc.init("127.0.0.1", 8382, 10);
string s = "test";
char c[1024] = "\0";
size_t length = 4;
int iRet = tc.sendRecv(s.c_str(), s.length(), c, length);
if(iRet < 0)
{
cout << "send recv error" << endl;
}
if(i % 1000 == 0)
{
cout << i << endl;
}
usleep(10);
i--;
assert(c == s);
}
}
void testUdp()
{
fork();fork();fork();fork();fork();
int i = 1000;
string s;
for(int j = 0; j < 7192; j++)
{
s += "0";
}
s += "\n";
while(i>0)
{
TC_UDPClient tc;
tc.init("127.0.0.1", 8082, 3000);
char c[10240] = "\0";
size_t length = sizeof(c);
int iRet = tc.sendRecv(s.c_str(), s.length(), c, length);
if(iRet < 0)
{
cout << "send recv error:" << iRet << endl;
}
if(i % 1000 == 0)
{
cout << i << endl;
}
i--;
if(c != s)
{
cout << c << endl;
// break;
}
}
}
void testTimeoutSock()
{
int i = 10;
while(i>0)
{
TC_TCPClient tc;
tc.init("127.0.0.1", 8382, 3);
string s = "test";
char c[1024] = "\0";
size_t length = 4;
int iRet = tc.sendRecv(s.c_str(), s.length(), c, length);
if(iRet < 0)
{
cout << "send recv error" << endl;
}
if(i % 1000 == 0)
{
cout << i << endl;
}
i--;
sleep(3);
assert(c == s);
}
}
void testLocalHost()
{
vector<string> v = TC_Socket::getLocalHosts();
cout << TC_Common::tostr(v.begin(), v.end()) << endl;
}
int main(int argc, char *argv[])
{
try
{
testUdp();
return 0;
TC_Socket t;
t.createSocket();
t.bind("127.0.0.1", 0);
string d;
uint16_t p;
t.getSockName(d, p);
t.close();
cout << d << ":" << p << endl;
return 0;
testLocalHost();
string st;
TC_Socket s;
s.createSocket(SOCK_STREAM, AF_LOCAL);
if(argc > 1)
{
s.bind("/tmp/tmp.udp.sock");
s.listen(5);
s.getSockName(st);
cout << st << endl;
struct sockaddr_un stSockAddr;
socklen_t iSockAddrSize = sizeof(sockaddr_un);
TC_Socket c;
s.accept(c, (struct sockaddr *) &stSockAddr, iSockAddrSize);
}
else
{
s.connect("/tmp/tmp.udp.sock");
s.getPeerName(st);
cout << st << endl;
}
}
catch(exception &ex)
{
cout << ex.what() << endl;
}
return 0;
}
| 21.193833 | 92 | 0.49761 | SuckShit |
7e1a89c99a9a348b915aaa0775bee5202db11528 | 5,943 | cpp | C++ | samples/sample_03_global.cpp | fengjixuchui/protolesshooks | 7cb9aeeef7e36939663b015dfa7977809fbaa566 | [
"MIT"
] | 112 | 2020-05-07T09:54:13.000Z | 2022-03-22T10:01:00.000Z | samples/sample_03_global.cpp | fengjixuchui/protolesshooks | 7cb9aeeef7e36939663b015dfa7977809fbaa566 | [
"MIT"
] | 2 | 2020-05-14T03:39:14.000Z | 2020-05-23T16:00:21.000Z | samples/sample_03_global.cpp | vovkos/protolesshooks | 19145c1e9428d29b35c1e3dcda66309eb72c7c0f | [
"MIT"
] | 28 | 2020-05-09T18:55:26.000Z | 2022-02-18T01:58:56.000Z | #include "plh_ModuleEnumerator.h"
#include "plh_ImportEnumerator.h"
#include "plh_ImportWriteProtection.h"
#include "plh_Hook.h"
#include <stdio.h>
#include <string.h>
#include <cinttypes>
#include <string>
#include <sstream>
#include <list>
#include <unordered_map>
#define _TRACE_HOOKING_MODULE 1
#define _TRACE_HOOKING_FUNCTION 1
//..............................................................................
size_t g_indentSlot;
int
incrementIndent(int delta)
{
int indent = (int)plh::getTlsValue(g_indentSlot);
plh::setTlsValue(g_indentSlot, indent + delta);
return indent;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
plh::HookAction
hookEnter(
void* targetFunc,
void* callbackParam,
size_t frameBase
)
{
int indent = incrementIndent(1);
printf(
"%*sTID %" PRIx64 ": sp: %p +%s\n",
indent * 2,
"",
plh::getCurrentThreadId(),
(void*)frameBase,
(char*)callbackParam
);
return plh::HookAction_Default;
}
void
hookLeave(
void* targetFunc,
void* callbackParam,
size_t frameBase
)
{
int indent = incrementIndent(-1) - 1;
if (!frameBase) // abandoned
{
printf(
"%*sTID %" PRIx64 ": ~%s\n",
indent * 2,
"",
plh::getCurrentThreadId(),
(char*)callbackParam
);
return;
}
plh::RegRetBlock* regRetBlock = (plh::RegRetBlock*)(frameBase + plh::FrameOffset_RegRetBlock);
#if (_PLH_CPU_AMD64)
int returnValue = (int)regRetBlock->m_rax;
#elif (_PLH_CPU_X86)
int returnValue = regRetBlock->m_eax;
#endif
printf(
"%*sTID %" PRIx64 ": sp: %p -%s -> %d/0x%x\n",
indent * 2,
"",
plh::getCurrentThreadId(),
(void*)frameBase,
(char*)callbackParam,
returnValue,
returnValue
);
}
const char*
getFileName(const char* fileName)
{
if (!fileName)
return "?";
for (const char* p = fileName; *p; p++)
#if (_PLH_OS_WIN)
if (*p == '/' || *p == '\\')
#else
if (*p == '/')
#endif
fileName = p + 1;
return fileName;
}
bool
spyModule(
const plh::ModuleIterator& moduleIt,
plh::HookArena* hookArena,
std::list<std::string>* stringCache
)
{
const char* moduleName = moduleIt.getModuleFileName();
#if (_TRACE_HOOKING_MODULE)
printf("Hooking %s...\n", moduleName);
#endif
moduleName = getFileName(moduleName);
#if (_PLH_OS_DARWIN)
std::unordered_map<size_t, bool> hookSet;
#endif
plh::ImportWriteProtectionBackup backup;
bool result = plh::disableImportWriteProtection(moduleIt, &backup);
if (!result)
return false;
plh::ImportIterator it = plh::enumerateImports(moduleIt);
for (; it; it++)
{
stringCache->emplace_back();
std::string& functionName = stringCache->back();
const char* symbolName = it.getSymbolName();
#if (_PLH_OS_WIN)
std::ostringstream sstream;
sstream << moduleName;
sstream << ":";
sstream << it.getModuleName();
sstream << ":";
if (it.getOrdinal() == -1)
{
sstream << symbolName;
}
else
{
sstream << "@";
sstream << it.getOrdinal();
}
functionName = sstream.str();
if (symbolName &&
(strcmp(symbolName, "TlsGetValue") == 0 ||
strcmp(symbolName, "TlsSetValue") == 0))
{
printf(" skipping %s for now...\n", functionName.c_str());
continue;
}
void** slot = it.getSlot();
void* targetFunc = *slot;
plh::Hook* hook = hookArena->allocate(targetFunc, (void*)functionName.c_str(), hookEnter, hookLeave);
# if (_TRACE_HOOKING_FUNCTION)
printf(" hooking [%p] %p -> %p %s...\n", slot, targetFunc, hook, functionName.c_str());
# endif
*slot = hook;
#elif (_PLH_OS_LINUX)
functionName = moduleName;
functionName += ":";
functionName += symbolName;
if (symbolName &&
(strcmp(symbolName, "pthread_getspecific") == 0 ||
strcmp(symbolName, "pthread_setspecific") == 0))
{
printf(" skipping %s for now...\n", functionName.c_str());
continue;
}
void** slot = it.getSlot();
void* targetFunc = *slot;
plh::Hook* hook = hookArena->allocate(targetFunc, (void*)functionName.c_str(), hookEnter, hookLeave);
# if (_TRACE_HOOKING_FUNCTION)
printf(" hooking [%p] %p -> %p %s...\n", slot, targetFunc, hook, functionName.c_str());
# endif
*slot = hook;
#elif (_PLH_OS_DARWIN)
functionName = moduleName;
functionName += ":";
functionName += getFileName(it.getModuleName());
functionName += ":";
functionName += symbolName;
if (symbolName &&
(strcmp(symbolName, "_pthread_getspecific") == 0 ||
strcmp(symbolName, "_pthread_setspecific") == 0))
{
printf(" skipping %s for now...\n", functionName.c_str());
continue;
}
size_t slotVmAddr = it.getSlotVmAddr();
std::unordered_map<size_t, bool>::value_type hookSetValue(slotVmAddr, true);
std::pair<std::unordered_map<size_t, bool>::iterator, bool> insertResult = hookSet.insert(hookSetValue);
if (!insertResult.second)
{
# if (_TRACE_HOOKING_FUNCTION)
printf(" already hooked [%08zx] %s\n", slotVmAddr, functionName.c_str());
# endif
continue;
}
void** slot = it.getSlot();
void* targetFunc = *slot;
plh::Hook* hook = hookArena->allocate(targetFunc, (void*)functionName.c_str(), hookEnter, hookLeave);
# if (_TRACE_HOOKING_FUNCTION)
printf(
" hooking [%08zx] %p -> %p %s...\n",
slotVmAddr,
targetFunc,
hook,
functionName.c_str()
);
# endif
*slot = hook;
#endif
}
result = plh::restoreImportWriteProtection(&backup);
assert(result);
return true;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
int
main()
{
g_indentSlot = plh::createTlsSlot();
plh::HookArena hookArena;
std::list<std::string>* stringCache = new std::list<std::string>; // no free
plh::ModuleIterator it = plh::enumerateModules();
for (; it; it++)
spyModule(it, &hookArena, stringCache);
printf("Hooking done, enabling hooks...\n");
plh::enableHooks();
// puts/printf will mess up the output; let's use something else...
std::string* p = new std::string;
delete p;
return 0;
}
//..............................................................................
| 22.175373 | 106 | 0.62948 | fengjixuchui |
7e1e127e19c3473f9d35587aee2a2f2ef038b05e | 610 | cpp | C++ | Level 4/Exercices de deblocage du Niveau 4/Baguenaudier/main.cpp | Wurlosh/France-ioi | f5fb36003cbfc56a2e7cf64ad43c4452f086f198 | [
"MIT"
] | 31 | 2018-10-30T09:54:23.000Z | 2022-03-02T21:45:51.000Z | Level 4/Exercices de deblocage du Niveau 4/Baguenaudier/main.cpp | Wurlosh/France-ioi | f5fb36003cbfc56a2e7cf64ad43c4452f086f198 | [
"MIT"
] | 2 | 2016-12-24T23:39:20.000Z | 2017-07-02T22:51:28.000Z | Level 4/Exercices de deblocage du Niveau 4/Baguenaudier/main.cpp | Wurlosh/France-ioi | f5fb36003cbfc56a2e7cf64ad43c4452f086f198 | [
"MIT"
] | 30 | 2018-10-25T12:28:36.000Z | 2022-01-31T14:31:02.000Z | #include <bits/stdc++.h>
#define N 20
using namespace std;
int tab[N];
string ans[N];
string v[N];
int n;
int main()
{
ios_base::sync_with_stdio(0);
ans[1]="1";
ans[2]="2\n1";
v[1]="1";
v[2]="1\n2\n1";
cin>>n;
for(int i=3;i<=n;++i)
{
ans[i]="";
ans[i]=ans[i]+ans[i-2]+"\n";
if(i/10!=0)
ans[i]+=('0'+i/10);
ans[i]+=('0'+i%10);
ans[i]+="\n";
ans[i]=ans[i]+v[i-1];
v[i]=v[i-1]+"\n";
if(i/10!=0)
v[i]+=('0'+i/10);
v[i]+=('0'+i%10);
v[i]+="\n";
v[i]=v[i]+v[i-1];
}
cout<<ans[n]<<endl;
return 0;
} | 16.944444 | 34 | 0.406557 | Wurlosh |
7e219e1b2c300ef8b466403ebd01c7ddd29d7c70 | 2,897 | cpp | C++ | CaptureManagerSource/CaptureManager/Main.cpp | luoyingwen/CaptureManagerSDK | e96395a120175a45c56ff4e2b3283b807a42fd75 | [
"MIT"
] | 64 | 2020-07-20T09:35:16.000Z | 2022-03-27T19:13:08.000Z | CaptureManagerSource/CaptureManager/Main.cpp | luoyingwen/CaptureManagerSDK | e96395a120175a45c56ff4e2b3283b807a42fd75 | [
"MIT"
] | 8 | 2020-07-30T09:20:28.000Z | 2022-03-03T22:37:10.000Z | CaptureManagerSource/CaptureManager/Main.cpp | luoyingwen/CaptureManagerSDK | e96395a120175a45c56ff4e2b3283b807a42fd75 | [
"MIT"
] | 28 | 2020-07-20T13:02:42.000Z | 2022-03-18T07:36:05.000Z | /*
MIT License
Copyright(c) 2020 Evgeny Pereguda
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.
*/
#define WIN32_LEAN_AND_MEAN
#include "../Common/Singleton.h"
#include "CommercialConfig.h"
#include "Libraries.h"
#include "../COMServer/RegisterManager.h"
#include "../COMServer/ClassFactory.h"
#include "../LogPrintOut/LogPrintOut.h"
#include "../Common/Macros.h"
using namespace CaptureManager;
using namespace CaptureManager::COMServer;
HINSTANCE gModuleInstance = NULL;
BOOL APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
gModuleInstance = hInstance;
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
STDAPI DllCanUnloadNow()
{
return Singleton<ClassFactory>::getInstance().checkLock();
}
STDAPI DllGetClassObject(
REFCLSID aRefCLSID,
REFIID aRefIID,
void** aPtrPtrVoidObject)
{
return Singleton<ClassFactory>::getInstance().getClassObject(
aRefCLSID,
aRefIID,
aPtrPtrVoidObject);
}
STDAPI DllRegisterServer()
{
return Singleton<RegisterManager>::getInstance().registerServer(gModuleInstance);
}
STDAPI DllUnregisterServer()
{
return Singleton<RegisterManager>::getInstance().unregisterServer(gModuleInstance);
}
void InitLogOut()
{
LogPrintOut::getInstance().printOutln(
LogPrintOut::INFO_LEVEL,
L"***** CAPTUREMANAGER SDK ",
(int)VERSION_MAJOR,
L".",
(int)VERSION_MINOR,
L".",
(int)VERSION_PATCH,
L" ",
WSTRINGIZE(ADDITIONAL_LABEL),
L" - ",
__DATE__,
L" (Author: Evgeny Pereguda) *****\n");
}
void UnInitLogOut()
{
LogPrintOut::getInstance().printOutlnUnlock(
LogPrintOut::INFO_LEVEL,
L"***** CAPTUREMANAGER SDK ",
(int)VERSION_MAJOR,
L".",
(int)VERSION_MINOR,
L".",
(int)VERSION_PATCH,
L" ",
WSTRINGIZE(ADDITIONAL_LABEL),
L" - ",
__DATE__,
L" (Author: Evgeny Pereguda) - is closed *****\n");
} | 24.974138 | 85 | 0.754574 | luoyingwen |
7e28d48a883b09ea6b4fbe126622a7206d5a7d32 | 1,872 | cc | C++ | transformations/legacy/LinearInterpolator.cc | gnafit/gna | c1a58dac11783342c97a2da1b19c97b85bce0394 | [
"MIT"
] | 5 | 2019-10-14T01:06:57.000Z | 2021-02-02T16:33:06.000Z | transformations/legacy/LinearInterpolator.cc | gnafit/gna | c1a58dac11783342c97a2da1b19c97b85bce0394 | [
"MIT"
] | null | null | null | transformations/legacy/LinearInterpolator.cc | gnafit/gna | c1a58dac11783342c97a2da1b19c97b85bce0394 | [
"MIT"
] | null | null | null | #include "LinearInterpolator.hh"
void LinearInterpolator::indexBins() {
if (m_xs.size() < 2) {
return;
}
double minbinsize = std::numeric_limits<double>::infinity();
for (size_t i = 0; i < m_xs.size()-1; ++i) {
minbinsize = std::min(minbinsize, m_xs[i+1] - m_xs[i]);
}
m_index.clear();
m_index.reserve((m_xs.back() - m_xs.front())/minbinsize);
double x = m_xs.front();
size_t i = 0;
for (size_t k = 0; ; ++k) {
x = m_xs.front() + k*minbinsize;
if (x > m_xs[i]) {
if (i+1 == m_xs.size()) {
m_index.push_back(i);
break;
} else {
i += 1;
}
}
m_index.push_back(i);
}
m_minbinsize = minbinsize;
}
void LinearInterpolator::interpolate(FunctionArgs& fargs) {
const auto &xs = fargs.args[0].x;
auto &ys = fargs.rets[0].x;
Eigen::ArrayXi idxes = ((xs - m_xs[0]) / m_minbinsize).cast<int>();
for (int i = 0; i < idxes.size(); ++i) {
if (idxes(i) < 0 || static_cast<size_t>(idxes(i)) >= m_index.size()) {
if (m_status_on_fail == ReturnOnFail::UseZero) {
ys(i) = 0.;
} else {
ys(i) = std::numeric_limits<double>::quiet_NaN();
}
continue;
}
size_t j;
for (j = m_index[idxes(i)]; j < m_xs.size(); ++j) {
if (m_xs[j] <= xs(i) && xs(i) <= m_xs[j+1]) {
break;
}
}
if (j < m_xs.size()) {
size_t j2;
double off = xs(i) - m_xs[j];
if (off == 0) {
ys(i) = m_ys[j];
continue;
} else if ((off > 0 && j+1 < m_xs.size()) || j == 0) {
j2 = j+1;
} else {
j2 = j-1;
}
ys(i) = m_ys[j] + (m_ys[j2]-m_ys[j])/(m_xs[j2]-m_xs[j])*off;
} else if (m_status_on_fail == ReturnOnFail::UseNaN) {
ys(i) = std::numeric_limits<double>::quiet_NaN();
}
else if (m_status_on_fail == ReturnOnFail::UseZero) {
ys(i) = 0.;
}
}
}
| 27.130435 | 74 | 0.514423 | gnafit |
7e2aadb0e396b36365109f16ac9086a5307fcc81 | 990 | cpp | C++ | learn_joy/src/jaws_joy_pub_joint.cpp | iConor/learn-ros | 91343f06c9d0df1c69ff01203a959366b0905953 | [
"BSD-3-Clause"
] | 2 | 2015-10-21T16:37:07.000Z | 2017-09-03T13:54:36.000Z | learn_joy/src/jaws_joy_pub_joint.cpp | iConor/learn-ros | 91343f06c9d0df1c69ff01203a959366b0905953 | [
"BSD-3-Clause"
] | null | null | null | learn_joy/src/jaws_joy_pub_joint.cpp | iConor/learn-ros | 91343f06c9d0df1c69ff01203a959366b0905953 | [
"BSD-3-Clause"
] | null | null | null | #include <ros/ros.h>
#include <sensor_msgs/JointState.h>
#include <sensor_msgs/Joy.h>
class Servos
{
private:
ros::NodeHandle nh;
ros::Subscriber sub;
ros::Publisher pub;
sensor_msgs::JointState js;
public:
Servos();
void callback(const sensor_msgs::Joy::ConstPtr& joy);
void loop();
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "state_publisher");
Servos servos;
servos.loop();
}
Servos::Servos() : nh()
{
sub = nh.subscribe<sensor_msgs::Joy>("joy", 1, &Servos::callback, this);
pub = nh.advertise<sensor_msgs::JointState>("joint_states", 1);
}
void Servos::callback(const sensor_msgs::Joy::ConstPtr& joy)
{
js.header.stamp = ros::Time::now();
js.name.resize(2);
js.position.resize(2);
js.name[0] ="port-base";
js.position[0] = joy->axes[2] * -0.7853975;
js.name[1] ="stbd-base";
js.position[1] = joy->axes[2] * -0.7853975;
pub.publish(js);
}
void Servos::loop()
{
while(ros::ok())
{
ros::spin();
}
}
| 19.411765 | 74 | 0.634343 | iConor |
7e2bab5d6ac4d2e4637bccf49e1b6a47992d715b | 4,664 | cc | C++ | third_party/blink/renderer/modules/service_worker/navigator_service_worker.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/modules/service_worker/navigator_service_worker.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/modules/service_worker/navigator_service_worker.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/service_worker/navigator_service_worker.h"
#include "services/network/public/mojom/web_sandbox_flags.mojom-blink.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/navigator.h"
#include "third_party/blink/renderer/modules/service_worker/service_worker_container.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
NavigatorServiceWorker::NavigatorServiceWorker(Navigator& navigator) {}
NavigatorServiceWorker* NavigatorServiceWorker::From(Document& document) {
LocalFrame* frame = document.GetFrame();
if (!frame)
return nullptr;
// TODO(kouhei): Remove below after M72, since the check is now done in
// RenderFrameImpl::CreateServiceWorkerProvider instead.
//
// Bail-out if we are about to be navigated away.
// We check that DocumentLoader is attached since:
// - This serves as the signal since the DocumentLoader is detached in
// FrameLoader::PrepareForCommit().
// - Creating ServiceWorkerProvider in
// RenderFrameImpl::CreateServiceWorkerProvider() assumes that there is a
// DocumentLoader attached to the frame.
if (!frame->Loader().GetDocumentLoader())
return nullptr;
LocalDOMWindow* dom_window = frame->DomWindow();
if (!dom_window)
return nullptr;
Navigator& navigator = *dom_window->navigator();
return &From(navigator);
}
NavigatorServiceWorker& NavigatorServiceWorker::From(Navigator& navigator) {
NavigatorServiceWorker* supplement = ToNavigatorServiceWorker(navigator);
if (!supplement) {
supplement = MakeGarbageCollected<NavigatorServiceWorker>(navigator);
ProvideTo(navigator, supplement);
}
if (navigator.GetFrame() && navigator.GetFrame()
->GetSecurityContext()
->GetSecurityOrigin()
->CanAccessServiceWorkers()) {
// Ensure ServiceWorkerContainer. It can be cleared regardless of
// |supplement|. See comments in NavigatorServiceWorker::serviceWorker() for
// details.
supplement->GetOrCreateContainer(navigator.GetFrame(), ASSERT_NO_EXCEPTION);
}
return *supplement;
}
NavigatorServiceWorker* NavigatorServiceWorker::ToNavigatorServiceWorker(
Navigator& navigator) {
return Supplement<Navigator>::From<NavigatorServiceWorker>(navigator);
}
const char NavigatorServiceWorker::kSupplementName[] = "NavigatorServiceWorker";
// static
ServiceWorkerContainer* NavigatorServiceWorker::serviceWorker(
ScriptState* script_state,
Navigator& navigator,
ExceptionState& exception_state) {
ExecutionContext* execution_context = ExecutionContext::From(script_state);
DCHECK(!navigator.GetFrame() ||
execution_context->GetSecurityOrigin()->CanAccess(
navigator.GetFrame()->GetSecurityContext()->GetSecurityOrigin()));
return NavigatorServiceWorker::From(navigator).GetOrCreateContainer(
navigator.GetFrame(), exception_state);
}
ServiceWorkerContainer* NavigatorServiceWorker::GetOrCreateContainer(
LocalFrame* frame,
ExceptionState& exception_state) {
if (!frame)
return nullptr;
if (!frame->GetSecurityContext()
->GetSecurityOrigin()
->CanAccessServiceWorkers()) {
String error_message;
if (frame->GetSecurityContext()->IsSandboxed(
network::mojom::blink::WebSandboxFlags::kOrigin)) {
error_message =
"Service worker is disabled because the context is sandboxed and "
"lacks the 'allow-same-origin' flag.";
} else {
error_message =
"Access to service workers is denied in this document origin.";
}
exception_state.ThrowSecurityError(error_message);
return nullptr;
}
if (frame->GetSecurityContext()->GetSecurityOrigin()->IsLocal()) {
UseCounter::Count(frame->GetDocument(),
WebFeature::kFileAccessedServiceWorker);
}
return ServiceWorkerContainer::From(
Document::From(frame->DomWindow()->GetExecutionContext()));
}
void NavigatorServiceWorker::Trace(Visitor* visitor) {
Supplement<Navigator>::Trace(visitor);
}
} // namespace blink
| 38.545455 | 87 | 0.733705 | sarang-apps |
7e2e35a3010afffb4f4882e87cd594fc5d4b5db6 | 1,813 | hpp | C++ | src/FrameWork/Math/Vectors.hpp | kevin20x2/PersistEngine | eeb4e14840d53274aa51fca6ad69f6f44a4e61ab | [
"MIT"
] | null | null | null | src/FrameWork/Math/Vectors.hpp | kevin20x2/PersistEngine | eeb4e14840d53274aa51fca6ad69f6f44a4e61ab | [
"MIT"
] | null | null | null | src/FrameWork/Math/Vectors.hpp | kevin20x2/PersistEngine | eeb4e14840d53274aa51fca6ad69f6f44a4e61ab | [
"MIT"
] | null | null | null | #pragma once
#include <math.h>
namespace Persist
{
#pragma pack(push)
#pragma pack(4)
template <typename T>
struct Vector2
{
Vector2(T _x, T _y) :
x(_x)
{
}
T x,y;
};
using Vector2f = Vector2<float>;
template <typename T>
struct Vector3
{
Vector3(T _x,T _y , T _z) :
x(_x),y(_y),z(_z)
{
}
Vector3(const Vector3 & rhs) :
x(rhs.x) , y(rhs.y),z(rhs.z)
{
}
T dot(const Vector3 & rhs)
{
return x*rhs.x + y * rhs.y + z * rhs.z;
}
T dot(const Vector3 & rhs) const
{
return x* rhs.x + y*rhs.y + z* rhs.z;
}
Vector3 operator *(const Vector3 & rhs)
{
return Vector3(x * rhs.x , y * rhs.y , z * rhs.z);
}
Vector3 operator*(T mul) const
{
return Vector3(x *mul , y * mul , z * mul);
}
// no pram
Vector3 operator-() const
{
return Vector3(-x,-y,-z);
}
T length()
{
return sqrt(x*x + y*y + z*z);
}
Vector3 & normalize()
{
T len = length();
if(len > 1e-6)
{
x/= len;
y/= len;
z/= len;
return *this;
}
else
{
throw Status::Error("normalize vector of length 0");
return *this;
}
}
//T x,y,z;
union { T x , r ;};
union { T y , g ;};
union { T z , b ;};
};
using Vector3f = Vector3<float> ;
template <typename T>
struct Vector4
{
Vector4( T _x , T _y , T _z , T _w) :
x(_x),y(_y),z(_z),w(_w)
{
}
Vector4(const Vector4 & rhs) :
x(rhs.x) , y (rhs.y) , z(rhs.z) ,w(rhs.z)
{
}
union { T x,r; };
union { T y,g; };
union { T z,b; };
union { T w,a; };
};
using Vector4f = Vector4<float>;
#pragma pack(pop)
} | 15.62931 | 64 | 0.453392 | kevin20x2 |
7e2fe949026cf8235f24d233935c8342af9c649a | 2,955 | cpp | C++ | benchmarks/statistical/spawn_threads_analysis.cpp | vamatya/benchmarks | 8a86c6eebac5f9a29a0e37a62bdace45395c8d73 | [
"BSL-1.0"
] | null | null | null | benchmarks/statistical/spawn_threads_analysis.cpp | vamatya/benchmarks | 8a86c6eebac5f9a29a0e37a62bdace45395c8d73 | [
"BSL-1.0"
] | null | null | null | benchmarks/statistical/spawn_threads_analysis.cpp | vamatya/benchmarks | 8a86c6eebac5f9a29a0e37a62bdace45395c8d73 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2012 Daniel Kogler
//
// 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)
/*This benchmark measures how long it takes to spawn new threads directly*/
#include "statstd.hpp"
#include <hpx/include/threadmanager.hpp>
#include <hpx/util/lightweight_test.hpp>
#include <boost/assign/std/vector.hpp>
#include <boost/lexical_cast.hpp>
//just an empty function to assign to the thread
void void_thread(){
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//this runs a series of tests for a packaged_action.apply()
void run_tests(uint64_t);
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//still required to run hpx
int hpx_main(variables_map& vm){
uint64_t num = vm["number-spawned"].as<uint64_t>();
csv = (vm.count("csv") ? true : false);
run_tests(num);
return hpx::finalize();
}
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[]){
// Configure application-specific options.
options_description
desc_commandline("usage: " HPX_APPLICATION_STRING " [options]");
desc_commandline.add_options()
("number-spawned,N",
boost::program_options::value<uint64_t>()
->default_value(50000),
"number of created and joined")
("csv",
"output results as csv "
"(format:count,mean,accurate mean,variance,min,max)");
// Initialize and run HPX
outname = argv[0];
return hpx::init(desc_commandline, argc, argv);
}
///////////////////////////////////////////////////////////////////////////////
//measure how long it takes to spawn threads with a simple argumentless function
void run_tests(uint64_t num){
uint64_t i = 0;
double ot = timer_overhead(num);
double mean1;
string message = "Measuring time required to spawn threads:";
vector<double> time;
vector<hpx::thread> threads;
threads.reserve(2*num);
//first measure the average time it takes to spawn threads
high_resolution_timer t;
for(; i < num; ++i)
threads.push_back(hpx::thread(&void_thread));
mean1 = t.elapsed()/num;
//now retrieve the statistical sampling of this time
time.reserve(num);
for(i = 0; i < num; i++){
high_resolution_timer t1;
threads.push_back(hpx::thread(&void_thread));
time.push_back(t1.elapsed());
}
printout(time, ot, mean1, message);
//ensure all created threads have joined or else we will not be able to safely
//exit the program
for(i = 0; i < num; ++i) threads[i].join();
for(i = num; i < num+num; ++i) threads[i].join();
}
| 33.579545 | 82 | 0.554315 | vamatya |
7e314be72e15b42eb5bf81a4f947791aeed1a9ab | 2,040 | cpp | C++ | src/net/LwipOutputQueue.cpp | jnmeurisse/FortiRDP | 53f48413c8a292304de27468b271847534353c61 | [
"Apache-2.0"
] | null | null | null | src/net/LwipOutputQueue.cpp | jnmeurisse/FortiRDP | 53f48413c8a292304de27468b271847534353c61 | [
"Apache-2.0"
] | null | null | null | src/net/LwipOutputQueue.cpp | jnmeurisse/FortiRDP | 53f48413c8a292304de27468b271847534353c61 | [
"Apache-2.0"
] | 1 | 2022-02-19T19:47:43.000Z | 2022-02-19T19:47:43.000Z | /*!
* This file is part of FortiRDP
*
* Copyright (C) 2022 Jean-Noel Meurisse
* SPDX-License-Identifier: Apache-2.0
*
*/
#include <algorithm>
#include "net/LwipOutputQueue.h"
namespace net {
using namespace tools;
LwipOutputQueue::LwipOutputQueue(int capacity):
OutputQueue(capacity),
_logger(Logger::get_logger())
{
DEBUG_CTOR(_logger, "LwipOutputQueue");
}
LwipOutputQueue::~LwipOutputQueue()
{
DEBUG_DTOR(_logger, "LwipOutputQueue");
}
lwip_err LwipOutputQueue::write(::tcp_pcb* socket, size_t& written)
{
if (_logger->is_trace_enabled())
_logger->trace(
".... %x enter LwipOutputQueue::write tcp=%x",
this,
socket);
int rc = 0;
written = 0;
while (!empty()) {
PBufChain* const pbuf = front();
// Compute the length of the next chunk of data. The length of
// a chunk is always less than 64 Kb, we can cast to an unsigned 16 Bits
// integer.
uint16_t available = static_cast<u16_t>(pbuf->cend() - pbuf->cbegin());
// Determine how many bytes we can effectively send
uint16_t len = min(tcp_sndbuf(socket), available);
// stop writing if no more space available
if (len == 0)
break;
// is this pbuf exhausted ?
u8_t flags = TCP_WRITE_FLAG_COPY | ((available > len) ? TCP_WRITE_FLAG_MORE : 0);
// send
rc = tcp_write(socket, pbuf->cbegin(), len, flags);
if (rc)
goto write_error;
// report the number of sent bytes.
written += len;
// move our pointer into the payload if bytes have been sent
pbuf->move(len);
// unlink the first chain if no more data
if (pbuf->empty()) {
pop_front();
delete pbuf;
}
}
if (written > 0) {
rc = tcp_output(socket);
if (rc)
goto write_error;
}
write_error:
if (_logger->is_trace_enabled())
_logger->trace(
".... %x leave LwipOutputQueue::write tcp=%x rc=%d written=%d",
this,
socket,
rc,
written);
if (rc == ERR_IF)
// The output buffer was full, we will try to send the pbuf chain later
rc = ERR_OK;
return rc;
}
}
| 21.030928 | 84 | 0.647059 | jnmeurisse |
7e31d3a9b404e35f3690f98cd86c7ee04d181cdd | 432 | cpp | C++ | C++/TrainingCode/example_16.cpp | jedrzejpolaczek/code_snippets | 04dd6821840d897a95c2a94d75693072ac3c08eb | [
"MIT"
] | null | null | null | C++/TrainingCode/example_16.cpp | jedrzejpolaczek/code_snippets | 04dd6821840d897a95c2a94d75693072ac3c08eb | [
"MIT"
] | null | null | null | C++/TrainingCode/example_16.cpp | jedrzejpolaczek/code_snippets | 04dd6821840d897a95c2a94d75693072ac3c08eb | [
"MIT"
] | null | null | null | /* kompilator: MinGW 6.3.0 */
/* Czy ta funkcja jest poprawna? */
#include <iostream>
#include <stdio.h>
int foo(int * p){
return 0;
}
int main(int argc, char **argv) {
int tab[] = {0,0,0};
foo(tab);
return 0;
}
//-----------------------------------------------
/* ODPOWIEDŹ:
* Tak. Do funkcji przekazywany jest adres pierwszego elmentu tablicy.
*/
Collapse
white_check_mark
eyes
raised_hands
| 12.342857 | 70 | 0.548611 | jedrzejpolaczek |
cce3401856453e5ad64f0c61acf95e1c3f2e7067 | 1,339 | hpp | C++ | challenges/c0005/challenge.hpp | cdalvaro/project-euler | 7a09b06a0034ab555706214017ac2e6e3f019806 | [
"MIT"
] | null | null | null | challenges/c0005/challenge.hpp | cdalvaro/project-euler | 7a09b06a0034ab555706214017ac2e6e3f019806 | [
"MIT"
] | 18 | 2021-02-27T16:42:33.000Z | 2022-02-12T11:40:40.000Z | challenges/c0005/challenge.hpp | cdalvaro/project-euler | 7a09b06a0034ab555706214017ac2e6e3f019806 | [
"MIT"
] | 1 | 2021-02-22T13:08:13.000Z | 2021-02-22T13:08:13.000Z | //
// challenge.hpp
// Challenges
//
// Created by Carlos David on 11/06/2020.
// Copyright © 2020 cdalvaro. All rights reserved.
//
#ifndef challenges_c0005_challenge_hpp
#define challenges_c0005_challenge_hpp
#include "challenges/ichallenge.hpp"
namespace challenges {
/**
@class Challenge5
@brief This class is intended to solve Challenge 5
@link https://projecteuler.net/problem=5 @endlink
*/
class Challenge5 : virtual public IChallenge {
public:
//! @copydoc IChallenge::Type_t
using Type_t = size_t;
/**
@brief Class constructor
This is the main constructor of Challenge5 class
@param last_number The las number starting from 1 to be divisible
without remainder
*/
Challenge5(const Type_t &last_number);
/**
@brief Default constructor
*/
virtual ~Challenge5() = default;
/**
This method contains the algorithm that solves challenge 5
@return The solution for challenge 5
*/
std::any solve() override final;
private:
Type_t last_number; /**< The las number starting from 1 to be divisible
without remainder */
};
} // namespace challenges
#endif /* challenges_c0005_challenge_hpp */
| 23.910714 | 79 | 0.625093 | cdalvaro |
cce4ba72a191d9307a795629a1381f53b5e47067 | 3,611 | cpp | C++ | SynchronisationServer/src/mainapp.cpp | FilmakademieRnd/v-p-e-t | d7dd8efb6d4aa03784e1bb4f941d2bcef919f28b | [
"MIT"
] | 62 | 2016-10-12T17:29:37.000Z | 2022-02-27T01:24:48.000Z | SynchronisationServer/src/mainapp.cpp | FilmakademieRnd/v-p-e-t | d7dd8efb6d4aa03784e1bb4f941d2bcef919f28b | [
"MIT"
] | 75 | 2017-01-05T12:02:43.000Z | 2021-04-06T19:07:50.000Z | SynchronisationServer/src/mainapp.cpp | FilmakademieRnd/v-p-e-t | d7dd8efb6d4aa03784e1bb4f941d2bcef919f28b | [
"MIT"
] | 16 | 2016-10-12T17:29:42.000Z | 2021-12-01T17:27:33.000Z | /*
-----------------------------------------------------------------------------
This source file is part of VPET - Virtual Production Editing Tool
http://vpet.research.animationsinstitut.de/
http://github.com/FilmakademieRnd/VPET
Copyright (c) 2018 Filmakademie Baden-Wuerttemberg, Animationsinstitut R&D Lab
This project has been initiated in the scope of the EU funded project
Dreamspace under grant agreement no 610005 in the years 2014, 2015 and 2016.
http://dreamspaceproject.eu/
Post Dreamspace the project has been further developed on behalf of the
research and development activities of Animationsinstitut.
The VPET components Scene Distribution and Synchronization Server are intended
for research and development purposes only. Commercial use of any kind is not
permitted.
There is no support by Filmakademie. Since the Scene Distribution and
Synchronization Server are available for free, Filmakademie shall only be
liable for intent and gross negligence; warranty is limited to malice. Scene
Distribution and Synchronization Server may under no circumstances be used for
racist, sexual or any illegal purposes. In all non-commercial productions,
scientific publications, prototypical non-commercial software tools, etc.
using the Scene Distribution and/or Synchronization Server Filmakademie has
to be named as follows: “VPET-Virtual Production Editing Tool by Filmakademie
Baden-Württemberg, Animationsinstitut (http://research.animationsinstitut.de)“.
In case a company or individual would like to use the Scene Distribution and/or
Synchronization Server in a commercial surrounding or for commercial purposes,
software based on these components or any part thereof, the company/individual
will have to contact Filmakademie (research<at>filmakademie.de).
-----------------------------------------------------------------------------
*/
#include "mainapp.h"
MainApp::MainApp(QString ownIP, QString ncamIP, QString ncamPort, bool debug)
{
context_ = new zmq::context_t(1);
ownIP_ = ownIP;
ncamIP_ = ncamIP;
ncamPort_ = ncamPort;
debug_ = debug;
isRecording = false;
}
void MainApp::run()
{
//create Thread to receive zeroMQ messages from tablets
QThread* zeroMQHandlerThread = new QThread();
ZeroMQHandler* zeroMQHandler = new ZeroMQHandler(ownIP_, debug_ , context_);
zeroMQHandler->moveToThread(zeroMQHandlerThread);
QObject::connect( zeroMQHandlerThread, SIGNAL(started()), zeroMQHandler, SLOT(run()));
zeroMQHandlerThread->start();
zeroMQHandler->requestStart();
#ifdef Q_OS_WIN
NcamAdapter* ncamAdapter = new NcamAdapter(ncamIP_, ncamPort_, ownIP_, context_);
if(ncamIP_ != "" && ncamPort_ != "")
{
QThread* ncamThread = new QThread();
ncamAdapter->moveToThread(ncamThread);
QObject::connect( ncamThread, SIGNAL(started()), ncamAdapter, SLOT(run()));
ncamThread->start();
}
#endif
/*
RecordWriter* recordWriter = new RecordWriter( &messagesStorage, &m_mutex );
QThread* writeThread = new QThread();
recordWriter->moveToThread( writeThread );
QObject::connect( writeThread, SIGNAL( started() ), recordWriter, SLOT( run() ) );
writeThread->start();
QThread* recorderThread = new QThread();
TransformationRecorder* transformationRecorder = new TransformationRecorder(ownIP_, context_, &messagesStorage, &m_mutex, ncamAdapter );//, recordWriter);
transformationRecorder->moveToThread(recorderThread);
QObject::connect( recorderThread, SIGNAL(started()), transformationRecorder, SLOT(run()));
recorderThread->start();
*/
}
| 43.506024 | 158 | 0.725561 | FilmakademieRnd |
ccea11ed15950bb342b61ab41dd08d1312f6e1ed | 592 | cpp | C++ | src/app/QVTKOpenGLInit.cpp | edrumwri/director | c82aff0ed2ad0083dc5ac9cf4b90994d2d852be8 | [
"BSD-3-Clause"
] | 18 | 2018-11-05T09:16:11.000Z | 2021-12-21T09:05:50.000Z | src/app/QVTKOpenGLInit.cpp | edrumwri/director | c82aff0ed2ad0083dc5ac9cf4b90994d2d852be8 | [
"BSD-3-Clause"
] | 36 | 2018-10-09T21:33:43.000Z | 2020-12-10T11:22:29.000Z | src/app/QVTKOpenGLInit.cpp | edrumwri/director | c82aff0ed2ad0083dc5ac9cf4b90994d2d852be8 | [
"BSD-3-Clause"
] | 5 | 2017-02-22T17:56:52.000Z | 2019-07-21T09:04:53.000Z | #include "QVTKOpenGLInit.h"
// Qt includes
#include <QtGlobal>
// VTK includes
#include <vtkVersionMacros.h>
#include <vtkRenderingOpenGLConfigure.h>
#if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0) && VTK_MAJOR_VERSION >= 8
# ifdef VTK_OPENGL2
#include <QSurfaceFormat>
#include <QVTKOpenGLWidget.h>
# endif
#endif
QVTKOpenGLInit::QVTKOpenGLInit()
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0) && VTK_MAJOR_VERSION >= 8
# ifdef VTK_OPENGL2
// Set the default surface format for the OpenGL view
QSurfaceFormat::setDefaultFormat(QVTKOpenGLWidget::defaultFormat());
# endif
#endif
}
| 22.769231 | 70 | 0.744932 | edrumwri |
ccea58bdb68c43bd9734b4a77a0afa626e250990 | 614 | hpp | C++ | lab1/1_triangle/triangle/triangle.hpp | zaychenko-sergei/oop-ki13 | 97405077de1f66104ec95c1bb2785bc18445532d | [
"MIT"
] | 2 | 2015-10-08T15:07:07.000Z | 2017-09-17T10:08:36.000Z | lab1/1_triangle/triangle/triangle.hpp | zaychenko-sergei/oop-ki13 | 97405077de1f66104ec95c1bb2785bc18445532d | [
"MIT"
] | null | null | null | lab1/1_triangle/triangle/triangle.hpp | zaychenko-sergei/oop-ki13 | 97405077de1f66104ec95c1bb2785bc18445532d | [
"MIT"
] | null | null | null | // (C) 2013-2014, Sergei Zaychenko, KNURE, Kharkiv, Ukraine
#ifndef _TRIANGLE_HPP_
#define _TRIANGLE_HPP_
/*****************************************************************************/
#include "point.hpp"
/*****************************************************************************/
class Triangle
{
/*-----------------------------------------------------------------*/
// ... TODO ...
/*------------------------------------------------------------------*/
};
/*****************************************************************************/
#endif // _TRIANGLE_HPP_
| 21.928571 | 80 | 0.218241 | zaychenko-sergei |