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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e102464f1c980633d4c3d101eac9f241350a931d | 9,180 | hh | C++ | Files.hh | pirl-lpl/pirlplusplus | d3211b05fc18f11fc66d97d5bcaeabcbd0b8b6e0 | [
"Apache-2.0"
] | null | null | null | Files.hh | pirl-lpl/pirlplusplus | d3211b05fc18f11fc66d97d5bcaeabcbd0b8b6e0 | [
"Apache-2.0"
] | null | null | null | Files.hh | pirl-lpl/pirlplusplus | d3211b05fc18f11fc66d97d5bcaeabcbd0b8b6e0 | [
"Apache-2.0"
] | null | null | null | /* Files
PIRL CVS ID: $Id: Files.hh,v 1.11 2012/07/20 00:25:53 castalia Exp $
Copyright (C) 2006-2010 Arizona Board of Regents on behalf of the
Planetary Image Research Laboratory, Lunar and Planetary Laboratory at
the University of Arizona.
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef _Files_
#define _Files_
#include <string>
#include <sys/types.h> // For off_t.
namespace PIRL
{
/*==============================================================================
Constants
*/
//! Module identification name with source code version and date.
extern const char
*Files_ID;
//! Host filesystem pathname delimiter ('/').
extern const char
FILE_PATHNAME_DELIMITER;
//! Filename extension delimiter ('.').
extern const char
FILE_EXTENSION_DELIMITER;
/*==============================================================================
Functions
*/
/** Test if a file exists at a pathname.
@param pathname The filesystem pathname to test.
@return true if the file exists; false otherwise.
*/
bool file_exists (const std::string& pathname);
/** Test if a file at a pathname is readable.
Readability is determined by the system's access method. The file
must be readable by the real ID of the process.
@param pathname The pathname to test.
@return true if the file is accessable and can be read; false otherwise.
@throws runtime_error If the file attributes can not be obtained
(MS/Windows only).
*/
bool file_is_readable (const std::string& pathname);
/** Test if a file at a pathname is writeable.
Writeability is determined by the system's access method. The file
must be writeable by the real ID of the process.
@param pathname The pathname to test.
@return true if the file is accessable and can be written; false
otherwise.
@throws runtime_error If the file attributes can not be obtained
(MS/Windows only).
*/
bool file_is_writeable (const std::string& pathname);
/** Test if a file at a pathname is a normal file.
@param pathname The pathname to test.
@return true if the file is accessable and is a normal type of file;
false otherwise.
*/
bool file_is_normal (const std::string& pathname);
/** Test if a file at a pathname is a directory.
@param pathname The pathname to test.
@return true if the file is accessable and is a directory; false
otherwise.
*/
bool file_is_directory (const std::string& pathname);
/** Test if a file at a pathname is a link file.
@param pathname The pathname to test.
@return true if the file is accessable and is a link; false
otherwise.
*/
bool file_is_link (const std::string& pathname);
/** Get the size of a file.
<b>N.B.</b>: For MS/Windows a directory always has a file size of
zero.
@param pathname The pathname to the file.
@return The size of the file in bytes. This will be -1 if the file
could not be accessed. The return data type is off_t, the natural
type for a file offset value for the host system.
*/
off_t file_size (const std::string& pathname);
/** Test if a pathname is an absolute pathname.
An absolute pathname begins with the #FILE_PATHNAME_DELIMITER character.
@param pathname The pathname to test.
@return true if the pathname is an absolute pathname; false otherwise.
*/
bool file_is_absolute (const std::string& pathname);
/** Clean a pathname of redundant segments.
All sequences of multiple #FILE_PATHNAME_DELIMITER characters are
replaced with a single delimiter. All sequences of
#FILE_PATHNAME_DELIMITER-'.'-#FILE_PATHNAME_DELIMITER characters are
replaced with a single delimiter. Any trailing #FILE_PATHNAME_DELIMITER
is removed.
@param pathname The pathname from which to obtain the extension.
@return The cleaned pathname. <b>N.B.</b>: The pathname string is
modified in place.
*/
std::string& clean_pathname (std::string& pathname);
/** Get the full pathname for a filename.
If the filename is relative the {@link #CWD() current working directory}
of the process is prepended.
The directory pathname is {@link clean_pathname(std::string&)
cleaned} before it is returned.
@param filename The filename for which to obtain an absolute
pathname.
@return The absolute pathname for the filename.
@throws runtime_error If the current working directory can not
be obtained.
*/
std::string file_pathname (const std::string& filename);
/** Get the full pathname for a filename.
If the filename is relative the directory is prepended. If the
directory is relative the {@link #CWD() current working directory}
of the process is prepended to it.
The directory pathname is {@link clean_pathname(std::string&)
cleaned} before it is returned.
@param directory The directory to prepend to the filename if
it is not an absolute pathname.
@param filename The filename for which to obtain an absolute
pathname.
@return The absolute pathname for the filename.
@throws runtime_error If the current working directory can not
be obtained.
*/
std::string file_pathname
(const std::string& directory, const std::string& filename);
/** Get the current working directory of the process.
This is a convenience function for the system getcwd function.
@return The absolute pathname for the current working directory
of the process.
@throws runtime_error If the current working directory can not
be obtained.
*/
std::string CWD ();
/** Get the leading directory portion of a pathname.
The leading directory portion of a pathname is that substring
preceding the last #FILE_PATHNAME_DELIMITER, or the empty string if
it does not contain the delimiter. <b>N.B.</b>: If the pathname contains
only one delimiter that is the first character, then the leading
directory pathname is the delimiter (i.e. the filesystem root).
@param pathname The pathname from which to obtain the directory
pathname.
@return The directory pathname from the pathname.
*/
std::string file_directory (const std::string& pathname);
/** Get the leading directory pathname portion of a pathname.
The {@link #file_directory(const std::string&) leading directory}
portion of the pathname is obtained. If it is not an {@link
file_is_absolute(const std::string&) absolute pathname} the {@link
#CWD() current working directory} of the process is prepended.
The directory pathname is {@link clean_pathname(std::string&)
cleaned} before it is returned.
@param pathname The pathname from which to obtain the directory
pathname.
@return The directory pathname from the pathname.
@throws runtime_error If the current working directory can not
be obtained.
*/
std::string file_directory_pathname (const std::string& pathname);
/** Get the final name portion of a pathname.
The final name portion of a pathname is that substring following the
last #FILE_PATHNAME_DELIMITER, or the entire string if it does not
contain the delimiter.
@param pathname The pathname from which to obtain the file's name.
@return The name of the file referenced by the pathname.
*/
std::string file_name (const std::string& pathname);
/** Get the basename of a file's pathname.
The basename is that portion of the path preceeding the last
#FILE_EXTENSION_DELIMITER; or the entire string if there
it does not contain the delimiter. <b>N.B.</b>: Any directory
segments of the pathname are retained in the basename; these
can be removed using the file_name method.
@param pathname The pathname from which to obtain the basename.
@return The basename of the pathname.
*/
std::string file_basename (const std::string& pathname);
/** Get a file's extension.
The extension is that portion of the path following the last
#FILE_EXTENSION_DELIMITER. This will be the empty string if no
extension is present or the pathname ends with the delimiter.
@param pathname The pathname from which to obtain the extension.
@return The extension of the file referenced by the pathname.
*/
std::string file_extension (const std::string& pathname);
/** Get the user's home directory pathname.
@return The pathname of the effective user home directory.
@throws runtime_error If the user info can not be obtained.
*/
std::string home_directory_pathname ();
/** Get the effective username.
@return The name of the effective user.
@throws runtime_error If the user info can not be obtained (UNIX
only).
*/
std::string username ();
/** Get the effective user ID.
@return The effective user ID value.
*/
unsigned int UID ();
/** Get the effective group ID.
@return The effective group ID value.
*/
unsigned int GID ();
/** Get the name of the host system.
@return The name of the host system.
*/
std::string hostname ();
} // PIRL namespace
#endif
| 31.875 | 80 | 0.745425 | pirl-lpl |
e105a4dfa600f7ac6b2bdf8315f120d1a39cb769 | 4,184 | cpp | C++ | tester/libtbag/graphic/ImageIOTest.cpp | osom8979/tbag | c31e2d884907d946df0836a70d8d5d69c4bf3c27 | [
"MIT"
] | 21 | 2016-04-05T06:08:41.000Z | 2022-03-28T10:20:22.000Z | tester/libtbag/graphic/ImageIOTest.cpp | osom8979/tbag | c31e2d884907d946df0836a70d8d5d69c4bf3c27 | [
"MIT"
] | null | null | null | tester/libtbag/graphic/ImageIOTest.cpp | osom8979/tbag | c31e2d884907d946df0836a70d8d5d69c4bf3c27 | [
"MIT"
] | 2 | 2019-07-16T00:37:21.000Z | 2021-11-10T06:14:09.000Z | /**
* @file ImageIOTest.cpp
* @brief ImageIO class tester.
* @author zer0
* @date 2017-06-10
* @date 2019-02-20 (Rename: Image -> ImageIO)
*/
#include <gtest/gtest.h>
#include <tester/DemoAsset.hpp>
#include <libtbag/graphic/ImageIO.hpp>
#include <libtbag/filesystem/Path.hpp>
#include <libtbag/filesystem/File.hpp>
using namespace libtbag;
using namespace libtbag::graphic;
TEST(ImageIOTest, ReadImage)
{
auto path = DemoAsset::get_tester_dir_image() / "lena.png";
Box image;
ASSERT_EQ(E_SUCCESS, readImage(path.getString(), image));
ASSERT_EQ(3, image.dim(2));
ASSERT_EQ(512, image.dim(1));
ASSERT_EQ(512, image.dim(0));
// First RGB pixel.
ASSERT_EQ(226, image.offset<uint8_t>(0)); // r
ASSERT_EQ(137, image.offset<uint8_t>(1)); // g
ASSERT_EQ(125, image.offset<uint8_t>(2)); // b
// Last RGB pixel.
ASSERT_EQ(185, image.offset<uint8_t>(image.size() - 3)); // r
ASSERT_EQ( 74, image.offset<uint8_t>(image.size() - 2)); // g
ASSERT_EQ( 81, image.offset<uint8_t>(image.size() - 1)); // b
libtbag::util::Buffer buffer;
ASSERT_EQ(E_SUCCESS, writeImage(buffer, image, ImageFileFormat::IFF_PNG));
ASSERT_FALSE(buffer.empty());
// Save & Load.
tttDir_Automatic();
auto const SAVE_PATH = tttDir_Get() / "save.png";
ASSERT_EQ(E_SUCCESS, writeImage(SAVE_PATH.getString(), image));
ASSERT_EQ(buffer.size(), SAVE_PATH.getState().size);
Box reload;
ASSERT_EQ(E_SUCCESS, readImage(SAVE_PATH.getString(), reload));
ASSERT_EQ(3, image.dim(2));
ASSERT_EQ(512, reload.dim(1));
ASSERT_EQ(512, reload.dim(0));
// First RGB pixel.
ASSERT_EQ(226, reload.offset<uint8_t>(0)); // r
ASSERT_EQ(137, reload.offset<uint8_t>(1)); // g
ASSERT_EQ(125, reload.offset<uint8_t>(2)); // b
// Last RGB pixel.
ASSERT_EQ(185, reload.offset<uint8_t>(reload.size() - 3)); // r
ASSERT_EQ( 74, reload.offset<uint8_t>(reload.size() - 2)); // g
ASSERT_EQ( 81, reload.offset<uint8_t>(reload.size() - 1)); // b
}
TEST(ImageIOTest, ReadRgbaImage)
{
auto path = DemoAsset::get_tester_dir_image() / "lena.png";
Box image;
ASSERT_EQ(E_SUCCESS, readRgbaImage(path.getString(), image));
ASSERT_EQ(4, image.dim(2));
ASSERT_EQ(512, image.dim(1));
ASSERT_EQ(512, image.dim(0));
// First RGB pixel.
ASSERT_EQ(226, image.offset<uint8_t>(0)); // r
ASSERT_EQ(137, image.offset<uint8_t>(1)); // g
ASSERT_EQ(125, image.offset<uint8_t>(2)); // b
ASSERT_EQ(255, image.offset<uint8_t>(3)); // a
// Last RGB pixel.
ASSERT_EQ(185, image.offset<uint8_t>(image.size() - 4)); // r
ASSERT_EQ( 74, image.offset<uint8_t>(image.size() - 3)); // g
ASSERT_EQ( 81, image.offset<uint8_t>(image.size() - 2)); // b
ASSERT_EQ(255, image.offset<uint8_t>(image.size() - 1)); // a
tttDir_Automatic();
auto const SAVE_PATH = tttDir_Get() / "save.png";
ASSERT_EQ(E_SUCCESS, writeImage(SAVE_PATH.getString(), image));
Box reload;
ASSERT_EQ(E_SUCCESS, readImage(SAVE_PATH.getString(), reload));
ASSERT_EQ(4, reload.dim(2));
ASSERT_EQ(512, reload.dim(1));
ASSERT_EQ(512, reload.dim(0));
}
TEST(ImageIOTest, UseJpeg)
{
auto path = DemoAsset::get_tester_dir_image() / "lena.png";
Box image;
ASSERT_EQ(E_SUCCESS, readImage(path.getString(), image));
// Save & Load.
tttDir_Automatic();
auto const JPEG_PATH = tttDir_Get() / "save.jpg";
ASSERT_EQ(E_SUCCESS, writeImage(JPEG_PATH.getString(), image));
ASSERT_TRUE(JPEG_PATH.isRegularFile());
Box reload;
ASSERT_EQ(E_SUCCESS, readImage(JPEG_PATH.getString(), reload));
auto const channels = reload.dim(2);
auto const width = reload.dim(1);
auto const height = reload.dim(0);
ASSERT_EQ(3, channels);
ASSERT_EQ(512, width);
ASSERT_EQ(512, height);
// Write To memory:
libtbag::util::Buffer buffer;
ASSERT_NE(0, writeJpg(width, height, channels, reload.data<char>(), DEFAULT_JPG_QUALITY, buffer));
ASSERT_FALSE(buffer.empty());
auto const JPEG_PATH_02 = tttDir_Get() / "save_02.jpg";
ASSERT_EQ(E_SUCCESS, libtbag::filesystem::writeFile(JPEG_PATH_02, buffer));
}
| 31.223881 | 102 | 0.657983 | osom8979 |
e107816cc441feae31ebcc0b53c8c75dbd2d2510 | 917 | cpp | C++ | MMOCoreORB/src/server/zone/managers/ship/ShipManager.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 18 | 2017-02-09T15:36:05.000Z | 2021-12-21T04:22:15.000Z | MMOCoreORB/src/server/zone/managers/ship/ShipManager.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 61 | 2016-12-30T21:51:10.000Z | 2021-12-10T20:25:56.000Z | MMOCoreORB/src/server/zone/managers/ship/ShipManager.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 71 | 2017-01-01T05:34:38.000Z | 2022-03-29T01:04:00.000Z | /*
* ShipManager.cpp
*
* Created on: 18/10/2013
* Author: victor
*/
#include "ShipManager.h"
#include "templates/manager/DataArchiveStore.h"
#include "templates/datatables/DataTableIff.h"
ShipManager::ShipManager() {
IffStream* iffStream = DataArchiveStore::instance()->openIffFile(
"datatables/space/ship_components.iff");
if (iffStream == nullptr) {
fatal("datatables/space/ship_components.iff could not be found.");
return;
}
DataTableIff dtiff;
dtiff.readObject(iffStream);
for (int i = 0; i < dtiff.getTotalRows(); ++i) {
DataTableRow* row = dtiff.getRow(i);
Reference<ShipComponent*> component = new ShipComponent();
component->readObject(row);
//info("loaded ship component " + component->getName() + " crc:0x" + String::hexvalueOf(int(component->getName().hashCode())), true);
shipComponents.put(component->getName().hashCode(), component);
}
delete iffStream;
}
| 24.131579 | 135 | 0.704471 | V-Fib |
e1098bfa3c4f724f10c806b4df309ef6c31b5892 | 5,176 | cpp | C++ | llbc/src/core/os/OS_Console.cpp | zhouyanlt/llbc | a8cc4662401e9b077be7ee0058350b35fdd86060 | [
"MIT"
] | null | null | null | llbc/src/core/os/OS_Console.cpp | zhouyanlt/llbc | a8cc4662401e9b077be7ee0058350b35fdd86060 | [
"MIT"
] | null | null | null | llbc/src/core/os/OS_Console.cpp | zhouyanlt/llbc | a8cc4662401e9b077be7ee0058350b35fdd86060 | [
"MIT"
] | null | null | null | // The MIT License (MIT)
// Copyright (c) 2013 lailongwei<lailongwei@126.com>
//
// 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 "llbc/common/Export.h"
#include "llbc/common/BeforeIncl.h"
#include "llbc/core/file/File.h"
#if LLBC_TARGET_PLATFORM_WIN32
#include "llbc/core/thread/FastLock.h"
#endif // LLBC_TARGET_PLATFORM_WIN32
#include "llbc/core/os/OS_Console.h"
#if LLBC_TARGET_PLATFORM_WIN32
__LLBC_INTERNAL_NS_BEGIN
static LLBC_NS LLBC_FastLock __g_consoleLock[2];
__LLBC_INTERNAL_NS_END
#endif // LLBC_TARGET_PLATFORM_WIN32
__LLBC_NS_BEGIN
int LLBC_GetConsoleColor(FILE *file)
{
#if LLBC_TARGET_PLATFORM_NON_WIN32
LLBC_SetLastError(LLBC_ERROR_NOT_IMPL);
return LLBC_FAILED;
#else
const int fileNo = LLBC_File::GetFileNo(file);
if (UNLIKELY(fileNo == -1))
{
return LLBC_FAILED;
}
else if (UNLIKELY(fileNo != 1 && fileNo != 2))
{
LLBC_SetLastError(LLBC_ERROR_INVALID);
return LLBC_FAILED;
}
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Lock();
HANDLE handle = (fileNo == 1 ?
::GetStdHandle(STD_OUTPUT_HANDLE) : GetStdHandle(STD_ERROR_HANDLE));
CONSOLE_SCREEN_BUFFER_INFO info;
if (::GetConsoleScreenBufferInfo(handle, &info) == 0)
{
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Unlock();
LLBC_SetLastError(LLBC_ERROR_OSAPI);
return LLBC_FAILED;
}
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Unlock();
return info.wAttributes;
#endif
}
int LLBC_SetConsoleColor(FILE *file, int color)
{
#if LLBC_TARGET_PLATFORM_NON_WIN32
LLBC_SetLastError(LLBC_ERROR_NOT_IMPL);
return LLBC_FAILED;
#else
const int fileNo = LLBC_File::GetFileNo(file);
if (UNLIKELY(fileNo == -1))
{
return LLBC_FAILED;
}
else if (UNLIKELY(fileNo != 1 && fileNo != 2))
{
LLBC_SetLastError(LLBC_ERROR_INVALID);
return LLBC_FAILED;
}
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Lock();
HANDLE handle = (fileNo == 1 ?
::GetStdHandle(STD_OUTPUT_HANDLE) : GetStdHandle(STD_ERROR_HANDLE));
if (::SetConsoleTextAttribute(handle, color) == 0)
{
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Unlock();
LLBC_SetLastError(LLBC_ERROR_OSAPI);
return LLBC_FAILED;
}
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Unlock();
return LLBC_OK;
#endif
}
int __LLBC_FilePrint(bool newline, FILE *file, const char *fmt, ...)
{
const int fileNo = LLBC_File::GetFileNo(file);
if (UNLIKELY(fileNo == -1))
{
return LLBC_FAILED;
}
char *buf; int len;
LLBC_FormatArg(fmt, buf, len);
#if LLBC_TARGET_PLATFORM_NON_WIN32
flockfile(file);
fprintf(file, (newline?"%s\n":"%s"), buf);
fflush(file);
funlockfile(file);
#else
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Lock();
fprintf(file, newline?"%s\n":"%s", buf);
fflush(file);
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Unlock();
#endif
LLBC_Free(buf);
return LLBC_OK;
}
int LLBC_FlushFile(FILE *file)
{
if (UNLIKELY(!file))
{
LLBC_SetLastError(LLBC_ERROR_INVALID);
return LLBC_FAILED;
}
#if LLBC_TARGET_PLATFORM_NON_WIN32
flockfile(file);
if (UNLIKELY(::fflush(file) != 0))
{
funlockfile(file);
LLBC_SetLastError(LLBC_ERROR_CLIB);
return LLBC_FAILED;
}
funlockfile(file);
return LLBC_OK;
#else // Win32
const int fileNo = LLBC_File::GetFileNo(file);
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Lock();
if (UNLIKELY(::fflush(file) != 0))
{
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Unlock();
LLBC_SetLastError(LLBC_ERROR_CLIB);
return LLBC_FAILED;
}
LLBC_INTERNAL_NS __g_consoleLock[(fileNo == 1 || fileNo == 2 ? 0 : 1)].Unlock();
return LLBC_OK;
#endif
}
__LLBC_NS_END
#include "llbc/common/AfterIncl.h"
| 30.093023 | 88 | 0.676584 | zhouyanlt |
e1099f393270d8e22b6138229f7b141a3a5530fa | 519 | cpp | C++ | level_zero/tools/source/pin/pin.cpp | dkjiang2018/compute-runtime | 310947e6ddefc4bb9a7a268fc1ee8639155b730c | [
"MIT"
] | 1 | 2020-04-17T05:46:04.000Z | 2020-04-17T05:46:04.000Z | level_zero/tools/source/pin/pin.cpp | dkjiang2018/compute-runtime | 310947e6ddefc4bb9a7a268fc1ee8639155b730c | [
"MIT"
] | null | null | null | level_zero/tools/source/pin/pin.cpp | dkjiang2018/compute-runtime | 310947e6ddefc4bb9a7a268fc1ee8639155b730c | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "pin.h"
#include "level_zero/core/source/module/module.h"
#include "level_zero/source/inc/ze_intel_gpu.h"
namespace L0 {
static PinContext *PinContextInstance = nullptr;
void PinContext::init(ze_init_flag_t flag) {
if (!getenv_tobool("ZE_ENABLE_PROGRAM_INSTRUMENTATION")) {
return;
}
if (PinContextInstance == nullptr) {
PinContextInstance = new PinContext();
}
}
} // namespace L0
| 19.222222 | 62 | 0.691715 | dkjiang2018 |
e10b18b722ef76256ac93eb0b9699462585af786 | 1,091 | cpp | C++ | _codeforces/448C/448c.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | 11 | 2015-08-29T13:41:22.000Z | 2020-01-08T20:34:06.000Z | _codeforces/448C/448c.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | null | null | null | _codeforces/448C/448c.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | 5 | 2016-01-20T18:17:01.000Z | 2019-10-30T11:57:15.000Z | #include <fstream>
#include <iostream>
using namespace std;
const int maxn = 5005;
const int maxlg = 21;
int rmq[maxlg][maxn], a[maxn], n, lg[maxn];
inline int query(int st, int dr) {
int l = lg[dr - st + 1];
int ans = rmq[l][st];
if(a[ans] > a[rmq[l][dr - (1 << l) + 1]])
ans = rmq[l][dr - (1 << l) + 1];
return ans;
}
inline long long dei(int st, int dr, int h) {
if(st > dr)
return 0;
int minpos = query(st, dr);
return min((long long)(dr - st + 1), dei(st, minpos - 1, a[minpos]) + dei(minpos + 1, dr,a[minpos]) + a[minpos] - h);
}
int main() {
cin.sync_with_stdio(false);
#ifndef ONLINE_JUDGE
freopen("448c.in", "r", stdin);
freopen("448c.out", "w", stdout);
#endif
cin >> n;
for(int i = 1 ; i <= n ; ++ i) {
cin >> a[i];
rmq[0][i] = i;
}
for(int i = 2 ; i <= n ; ++ i)
lg[i] = lg[i >> 1] + 1;
for(int i = 1 ; (1 << i) <= n ; ++ i)
for(int j = 1 ; j + (1 << i) - 1 <= n ; ++ j) {
rmq[i][j] = rmq[i - 1][j];
if(a[rmq[i][j]] > a[rmq[i - 1][j + (1 << (i - 1))]])
rmq[i][j] = rmq[i - 1][j + (1 << (i - 1))];
}
cout << dei(1, n, 0) << '\n';
}
| 23.212766 | 118 | 0.491292 | rusucosmin |
e116b7a2bd41239b474ad1af82c50031b9e728cc | 9,656 | cpp | C++ | samples/gl-320-fbo-blit.cpp | galek/ogl-samples | 38cada7a9458864265e25415ae61586d500ff5fc | [
"MIT"
] | 571 | 2015-01-08T16:29:38.000Z | 2022-03-16T06:45:42.000Z | samples/gl-320-fbo-blit.cpp | galek/ogl-samples | 38cada7a9458864265e25415ae61586d500ff5fc | [
"MIT"
] | 45 | 2015-01-15T12:47:28.000Z | 2022-03-04T09:22:32.000Z | samples/gl-320-fbo-blit.cpp | galek/ogl-samples | 38cada7a9458864265e25415ae61586d500ff5fc | [
"MIT"
] | 136 | 2015-01-31T15:24:57.000Z | 2022-02-17T19:26:24.000Z | #include "test.hpp"
namespace
{
char const* VERT_SHADER_SOURCE("gl-320/fbo-blit.vert");
char const* FRAG_SHADER_SOURCE("gl-320/fbo-blit.frag");
char const* TEXTURE_DIFFUSE("kueken7_rgba8_srgb.dds");
glm::ivec2 const FRAMEBUFFER_SIZE(512, 512);
struct vertex
{
vertex
(
glm::vec2 const & Position,
glm::vec2 const & Texcoord
) :
Position(Position),
Texcoord(Texcoord)
{}
glm::vec2 Position;
glm::vec2 Texcoord;
};
// With DDS textures, v texture coordinate are reversed, from top to bottom
GLsizei const VertexCount(6);
GLsizeiptr const VertexSize = VertexCount * sizeof(vertex);
vertex const VertexData[VertexCount] =
{
vertex(glm::vec2(-1.5f,-1.5f), glm::vec2(0.0f, 0.0f)),
vertex(glm::vec2( 1.5f,-1.5f), glm::vec2(1.0f, 0.0f)),
vertex(glm::vec2( 1.5f, 1.5f), glm::vec2(1.0f, 1.0f)),
vertex(glm::vec2( 1.5f, 1.5f), glm::vec2(1.0f, 1.0f)),
vertex(glm::vec2(-1.5f, 1.5f), glm::vec2(0.0f, 1.0f)),
vertex(glm::vec2(-1.5f,-1.5f), glm::vec2(0.0f, 0.0f))
};
namespace framebuffer
{
enum type
{
RENDER,
RESOLVE,
MAX
};
}//namespace framebuffer
namespace texture
{
enum type
{
DIFFUSE,
COLORBUFFER,
MAX
};
}//namespace texture
}//namespace
class sample : public framework
{
public:
sample(int argc, char* argv[]) :
framework(argc, argv, "gl-320-fbo-blit", framework::CORE, 3, 2),
VertexArrayName(0),
BufferName(0),
ColorRenderbufferName(0),
ProgramName(0),
UniformMVP(-1),
UniformDiffuse(-1)
{}
private:
std::array<GLuint, texture::MAX> TextureName;
std::array<GLuint, framebuffer::MAX> FramebufferName;
GLuint VertexArrayName;
GLuint BufferName;
GLuint ColorRenderbufferName;
GLuint ProgramName;
GLint UniformMVP;
GLint UniformDiffuse;
bool initProgram()
{
bool Validated = true;
compiler Compiler;
// Create program
if(Validated)
{
GLuint VertShaderName = Compiler.create(GL_VERTEX_SHADER, getDataDirectory() + VERT_SHADER_SOURCE, "--version 150 --profile core");
GLuint FragShaderName = Compiler.create(GL_FRAGMENT_SHADER, getDataDirectory() + FRAG_SHADER_SOURCE, "--version 150 --profile core");
ProgramName = glCreateProgram();
glAttachShader(ProgramName, VertShaderName);
glAttachShader(ProgramName, FragShaderName);
glBindAttribLocation(ProgramName, semantic::attr::POSITION, "Position");
glBindAttribLocation(ProgramName, semantic::attr::TEXCOORD, "Texcoord");
glBindFragDataLocation(ProgramName, semantic::frag::COLOR, "Color");
glLinkProgram(ProgramName);
Validated = Validated && Compiler.check();
Validated = Validated && Compiler.check_program(ProgramName);
}
if(Validated)
{
UniformMVP = glGetUniformLocation(ProgramName, "MVP");
UniformDiffuse = glGetUniformLocation(ProgramName, "Diffuse");
}
return this->checkError("initProgram");
}
bool initBuffer()
{
glGenBuffers(1, &BufferName);
glBindBuffer(GL_ARRAY_BUFFER, BufferName);
glBufferData(GL_ARRAY_BUFFER, VertexSize, VertexData, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return this->checkError("initBuffer");;
}
bool initTexture()
{
gli::texture2d Texture(gli::load_dds((getDataDirectory() + TEXTURE_DIFFUSE).c_str()));
gli::gl GL(gli::gl::PROFILE_GL32);
glGenTextures(texture::MAX, &TextureName[0]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, TextureName[texture::DIFFUSE]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, GLint(Texture.levels() - 1));
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
gli::gl::format const Format = GL.translate(Texture.format(), Texture.swizzles());
for(std::size_t Level = 0; Level < Texture.levels(); ++Level)
{
glTexImage2D(GL_TEXTURE_2D, GLint(Level),
Format.Internal,
GLsizei(Texture[Level].extent().x), GLsizei(Texture[Level].extent().y),
0,
Format.External, Format.Type,
Texture[Level].data());
}
glGenerateMipmap(GL_TEXTURE_2D); // Allocate all mipmaps memory
glBindTexture(GL_TEXTURE_2D, TextureName[texture::COLORBUFFER]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glBindTexture(GL_TEXTURE_2D, 0);
return true;
}
bool initFramebuffer()
{
glGenFramebuffers(framebuffer::MAX, &FramebufferName[0]);
glGenRenderbuffers(1, &ColorRenderbufferName);
glBindRenderbuffer(GL_RENDERBUFFER, ColorRenderbufferName);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y);
glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName[framebuffer::RENDER]);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, ColorRenderbufferName);
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
return this->checkError("initFramebuffer");
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName[framebuffer::RESOLVE]);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, TextureName[texture::COLORBUFFER], 0);
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
return this->checkError("initFramebuffer");
glBindFramebuffer(GL_FRAMEBUFFER, 0);
return this->checkError("initFramebuffer");
}
bool initVertexArray()
{
glGenVertexArrays(1, &VertexArrayName);
glBindVertexArray(VertexArrayName);
glBindBuffer(GL_ARRAY_BUFFER, BufferName);
glVertexAttribPointer(semantic::attr::POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(0));
glVertexAttribPointer(semantic::attr::TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(sizeof(glm::vec2)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(semantic::attr::POSITION);
glEnableVertexAttribArray(semantic::attr::TEXCOORD);
glBindVertexArray(0);
return this->checkError("initVertexArray");
}
void renderFBO()
{
glm::mat4 Perspective = glm::perspective(glm::pi<float>() * 0.25f, float(FRAMEBUFFER_SIZE.y) / FRAMEBUFFER_SIZE.x, 0.1f, 100.0f);
glm::mat4 Model = glm::scale(glm::mat4(1.0f), glm::vec3(1.0f,-1.0f, 1.0f));
glm::mat4 MVP = Perspective * this->view() * Model;
glUniformMatrix4fv(UniformMVP, 1, GL_FALSE, &MVP[0][0]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, TextureName[texture::DIFFUSE]);
glBindVertexArray(VertexArrayName);
glDrawArraysInstanced(GL_TRIANGLES, 0, VertexCount, 1);
}
void renderFB()
{
glm::vec2 WindowSize(this->getWindowSize());
glm::mat4 Perspective = glm::perspective(glm::pi<float>() * 0.25f, WindowSize.x / WindowSize.y, 0.1f, 100.0f);
glm::mat4 Model = glm::mat4(1.0f);
glm::mat4 MVP = Perspective * this->view() * Model;
glUniformMatrix4fv(UniformMVP, 1, GL_FALSE, &MVP[0][0]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, TextureName[texture::COLORBUFFER]);
glBindVertexArray(VertexArrayName);
glDrawArraysInstanced(GL_TRIANGLES, 0, VertexCount, 1);
}
bool begin()
{
bool Validated = true;
if(Validated)
Validated = initProgram();
if(Validated)
Validated = initBuffer();
if(Validated)
Validated = initTexture();
if(Validated)
Validated = initFramebuffer();
if(Validated)
Validated = initVertexArray();
return Validated && this->checkError("begin");
}
bool end()
{
glDeleteProgram(ProgramName);
glDeleteBuffers(1, &BufferName);
glDeleteTextures(texture::MAX, &TextureName[0]);
glDeleteRenderbuffers(1, &ColorRenderbufferName);
glDeleteFramebuffers(framebuffer::MAX, &FramebufferName[0]);
glDeleteVertexArrays(1, &VertexArrayName);
return true;
}
bool render()
{
glm::vec2 WindowSize(this->getWindowSize());
glUseProgram(ProgramName);
glUniform1i(UniformDiffuse, 0);
// Pass 1
glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName[framebuffer::RENDER]);
glViewport(0, 0, FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y);
glClearBufferfv(GL_COLOR, 0, &glm::vec4(0.0f, 0.5f, 1.0f, 1.0f)[0]);
renderFBO();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// Generate FBO mipmaps
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, TextureName[texture::COLORBUFFER]);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
// Blit framebuffers
GLint const Border = 2;
int const Tile = 4;
glBindFramebuffer(GL_READ_FRAMEBUFFER, FramebufferName[framebuffer::RENDER]);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, FramebufferName[framebuffer::RESOLVE]);
glClearBufferfv(GL_COLOR, 0, &glm::vec4(1.0f, 0.5f, 0.0f, 1.0f)[0]);
for(int j = 0; j < Tile; ++j)
for(int i = 0; i < Tile; ++i)
{
if((i + j) % 2)
continue;
glBlitFramebuffer(0, 0, FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y,
FRAMEBUFFER_SIZE.x / Tile * (i + 0) + Border,
FRAMEBUFFER_SIZE.x / Tile * (j + 0) + Border,
FRAMEBUFFER_SIZE.y / Tile * (i + 1) - Border,
FRAMEBUFFER_SIZE.y / Tile * (j + 1) - Border,
GL_COLOR_BUFFER_BIT, GL_LINEAR);
}
// Pass 2
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, static_cast<GLsizei>(WindowSize.x), static_cast<GLsizei>(WindowSize.y));
glClearBufferfv(GL_COLOR, 0, &glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)[0]);
renderFB();
return true;
}
};
int main(int argc, char* argv[])
{
int Error = 0;
sample Sample(argc, argv);
Error += Sample();
return Error;
}
| 29.710769 | 136 | 0.727527 | galek |
e11b11ad7daa7984011f9478308fbad2234acda0 | 424 | hpp | C++ | include/skyr/v2/unicode/ranges/sentinel.hpp | BioDataAnalysis/url | 281501b0fdf00b52eeb114f6856a9a83004d204e | [
"BSL-1.0"
] | 47 | 2019-08-24T13:43:45.000Z | 2022-02-21T11:45:19.000Z | include/skyr/v2/unicode/ranges/sentinel.hpp | BioDataAnalysis/url | 281501b0fdf00b52eeb114f6856a9a83004d204e | [
"BSL-1.0"
] | 35 | 2018-10-13T10:35:00.000Z | 2021-06-11T12:23:55.000Z | include/skyr/v2/unicode/ranges/sentinel.hpp | BioDataAnalysis/url | 281501b0fdf00b52eeb114f6856a9a83004d204e | [
"BSL-1.0"
] | 25 | 2019-02-19T02:46:21.000Z | 2021-10-21T14:53:00.000Z | // Copyright 2020 Glyn Matthews.
// 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)
#ifndef SKYR_V2_UNICODE_RANGES_SENTINEL_HPP
#define SKYR_V2_UNICODE_RANGES_SENTINEL_HPP
namespace skyr::inline v2::unicode {
class sentinel {};
} // namespace skyr::inline v2::unicode
#endif // SKYR_V2_UNICODE_RANGES_SENTINEL_HPP
| 30.285714 | 61 | 0.787736 | BioDataAnalysis |
e11b5643056209ff627e1d9744991e3476a518c0 | 614 | cpp | C++ | SourceCode/Chapter 15/GradedActivity Version 1/Pr15-1.cpp | aceiro/poo2019 | 0f93d22296f43a8b024a346f510c00314817d2cf | [
"MIT"
] | 1 | 2019-04-09T18:29:38.000Z | 2019-04-09T18:29:38.000Z | SourceCode/Chapter 15/GradedActivity Version 1/Pr15-1.cpp | aceiro/poo2019 | 0f93d22296f43a8b024a346f510c00314817d2cf | [
"MIT"
] | null | null | null | SourceCode/Chapter 15/GradedActivity Version 1/Pr15-1.cpp | aceiro/poo2019 | 0f93d22296f43a8b024a346f510c00314817d2cf | [
"MIT"
] | null | null | null | // This program demonstrates the GradedActivity class.
#include <iostream>
#include "GradedActivity.h"
using namespace std;
int main()
{
double testScore; // To hold a test score
// Create a GradedActivity object for the test.
GradedActivity test;
// Get a numeric test score from the user.
cout << "Enter your numeric test score: ";
cin >> testScore;
// Store the numeric score in the test object.
test.setScore(testScore);
// Display the letter grade for the test.
cout << "The grade for that test is "
<< test.getLetterGrade() << endl;
return 0;
} | 24.56 | 54 | 0.659609 | aceiro |
e11bc9c21d1f84745870b66488adf6f73c564033 | 1,602 | cc | C++ | chrome/test/chromedriver/devtools_events_logger.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/test/chromedriver/devtools_events_logger.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/test/chromedriver/devtools_events_logger.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/chromedriver/devtools_events_logger.h"
#include "base/json/json_writer.h"
#include "base/memory/ptr_util.h"
#include "base/values.h"
#include "chrome/test/chromedriver/chrome/devtools_client.h"
#include "chrome/test/chromedriver/chrome/devtools_client_impl.h"
DevToolsEventsLogger::DevToolsEventsLogger(Log* log,
const base::ListValue* prefs)
: log_(log),
prefs_(prefs) {}
inline DevToolsEventsLogger::~DevToolsEventsLogger() {}
Status DevToolsEventsLogger::OnConnected(DevToolsClient* client) {
for (base::ListValue::const_iterator it = prefs_->begin();
it != prefs_->end();
++it) {
std::string event;
it->GetAsString(&event);
events_.insert(event);
}
return Status(kOk);
}
Status DevToolsEventsLogger::OnEvent(DevToolsClient* client,
const std::string& method,
const base::DictionaryValue& params) {
std::unordered_set<std::string>::iterator it = events_.find(method);
if (it != events_.end()) {
base::DictionaryValue log_message_dict;
log_message_dict.SetString("method", method);
log_message_dict.Set("params", base::MakeUnique<base::Value>(params));
std::string log_message_json;
base::JSONWriter::Write(log_message_dict, &log_message_json);
log_->AddEntry(Log::kInfo, log_message_json);
}
return Status(kOk);
}
| 34.826087 | 75 | 0.679151 | metux |
e11ef728449d97ccea84ece89679c663fd42c108 | 2,851 | cpp | C++ | lldb/unittests/Process/Linux/ProcfsTests.cpp | ornata/llvm-project | 494913b8b4e4bce0b3525e5569d8e486e82b9a52 | [
"Apache-2.0"
] | null | null | null | lldb/unittests/Process/Linux/ProcfsTests.cpp | ornata/llvm-project | 494913b8b4e4bce0b3525e5569d8e486e82b9a52 | [
"Apache-2.0"
] | null | null | null | lldb/unittests/Process/Linux/ProcfsTests.cpp | ornata/llvm-project | 494913b8b4e4bce0b3525e5569d8e486e82b9a52 | [
"Apache-2.0"
] | null | null | null | //===-- ProcfsTests.cpp ---------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "Procfs.h"
#include "lldb/Host/linux/Support.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using namespace lldb_private;
using namespace process_linux;
using namespace llvm;
TEST(Perf, HardcodedLogicalCoreIDs) {
Expected<std::vector<lldb::core_id_t>> core_ids =
GetAvailableLogicalCoreIDs(R"(processor : 13
vendor_id : GenuineIntel
cpu family : 6
model : 85
model name : Intel(R) Xeon(R) Gold 6138 CPU @ 2.00GHz
stepping : 4
microcode : 0x2000065
cpu MHz : 2886.370
cache size : 28160 KB
physical id : 1
siblings : 40
core id : 19
cpu cores : 20
apicid : 103
initial apicid : 103
fpu : yes
fpu_exception : yes
cpuid level : 22
power management:
processor : 24
vendor_id : GenuineIntel
cpu family : 6
model : 85
model name : Intel(R) Xeon(R) Gold 6138 CPU @ 2.00GHz
stepping : 4
microcode : 0x2000065
cpu MHz : 2768.494
cache size : 28160 KB
physical id : 1
siblings : 40
core id : 20
cpu cores : 20
apicid : 105
power management:
processor : 35
vendor_id : GenuineIntel
cpu family : 6
model : 85
model name : Intel(R) Xeon(R) Gold 6138 CPU @ 2.00GHz
stepping : 4
microcode : 0x2000065
cpu MHz : 2884.703
cache size : 28160 KB
physical id : 1
siblings : 40
core id : 24
cpu cores : 20
apicid : 113
processor : 79
vendor_id : GenuineIntel
cpu family : 6
model : 85
model name : Intel(R) Xeon(R) Gold 6138 CPU @ 2.00GHz
stepping : 4
microcode : 0x2000065
cpu MHz : 3073.955
cache size : 28160 KB
physical id : 1
siblings : 40
core id : 28
cpu cores : 20
apicid : 121
power management:
)");
ASSERT_TRUE((bool)core_ids);
ASSERT_THAT(*core_ids, ::testing::ElementsAre(13, 24, 35, 79));
}
TEST(Perf, RealLogicalCoreIDs) {
// We first check we can read /proc/cpuinfo
auto buffer_or_error = errorOrToExpected(getProcFile("cpuinfo"));
if (!buffer_or_error)
GTEST_SKIP() << toString(buffer_or_error.takeError());
// At this point we shouldn't fail parsing the core ids
Expected<ArrayRef<lldb::core_id_t>> core_ids = GetAvailableLogicalCoreIDs();
ASSERT_TRUE((bool)core_ids);
ASSERT_GT((int)core_ids->size(), 0) << "We must see at least one core";
}
| 27.152381 | 80 | 0.590319 | ornata |
e125f5c785a485c804fce2c96ffe04b7dfd90908 | 1,270 | cpp | C++ | MemoryzeUM/TCPEndpoint.cpp | allewwaly/dementia-forensics | 401423fd8ba4f4d2b6dbec461df2eb18f33ac734 | [
"MIT"
] | 9 | 2018-08-20T03:06:07.000Z | 2021-06-14T14:46:43.000Z | MemoryzeUM/TCPEndpoint.cpp | zignie/dementia-forensics | 201a10faa17f2d406073d29e9cb5385b30c405f8 | [
"MIT"
] | null | null | null | MemoryzeUM/TCPEndpoint.cpp | zignie/dementia-forensics | 201a10faa17f2d406073d29e9cb5385b30c405f8 | [
"MIT"
] | 2 | 2017-08-02T02:33:31.000Z | 2017-09-03T17:56:33.000Z | #include "StdAfx.h"
#include "TCPEndpoint.h"
TCPEndpoint::TCPEndpoint(const DWORD dwPoolHeaderSize)
{
// initialize object name and tag
m_szObjName = "TCP_ENDPOINT";
m_dwTag = 0x45706354;
m_dwPoolHeaderSize = dwPoolHeaderSize;
// initialize default offset
SetDefaultOffsetsAndSizes();
}
TCPEndpoint::~TCPEndpoint(void)
{
}
void TCPEndpoint::SetDefaultOffsetsAndSizes( void )
{
// first obtain OS version
OSVERSIONINFO verInfo;
ZeroMemory(&verInfo, sizeof(OSVERSIONINFO));
verInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&verInfo);
// THE CODE THAT FOLLOWS DOES NOT COVER ALL CASES
// FIX ME!!!
if(verInfo.dwMajorVersion == 5)
{
// using Windows XP x86
m_isPID = true;
m_dwConnectionOwnerOffset = 0x18;
}
else if(verInfo.dwMajorVersion == 6)
{
m_isPID = false;
// Vista/2008 have different offsets than Windows 7
if(verInfo.dwMinorVersion == 0)
{
#ifdef _WIN64
m_dwConnectionOwnerOffset = 0x210;
#else // _WIN32
m_dwConnectionOwnerOffset = 0x160;
#endif // _WIN64
}
else
{
// using Windows 7 x86 defaults
#ifdef _WIN64
m_dwConnectionOwnerOffset = 0x238;
#else // _WIN32
m_dwConnectionOwnerOffset = 0x174;
#endif // _WIN64
}
}
} | 21.166667 | 55 | 0.692913 | allewwaly |
e12663c852c4dc04e585c68031d8e49fe158d4e8 | 651 | hpp | C++ | Axis.Core/services/management/UserModuleProxy.hpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | 2 | 2021-07-23T08:49:54.000Z | 2021-07-29T22:07:30.000Z | Axis.Core/services/management/UserModuleProxy.hpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | null | null | null | Axis.Core/services/management/UserModuleProxy.hpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | null | null | null | #pragma once
#include "ProviderProxy.hpp"
namespace axis { namespace services { namespace management {
class UserModuleProxy : public ProviderProxy
{
public:
UserModuleProxy(Provider& provider, bool isNonVolatile);
virtual ~UserModuleProxy(void);
virtual bool IsBootstrapModule(void) const;
virtual bool IsNonVolatileUserModule(void) const;
virtual bool IsUserModule(void) const;
virtual Provider& GetProvider(void) const;
virtual bool IsCustomSystemModule( void ) const;
virtual bool IsSystemModule( void ) const;
private:
bool _isNonVolatile;
bool _isWeakModule;
Provider& _provider;
};
} } } // namespace axis::services::management
| 27.125 | 60 | 0.786482 | renato-yuzup |
e12861572da521a57beaf8c9ff9fa04342db7888 | 4,761 | cxx | C++ | test/t_widget_registry.cxx | CM4all/beng-proxy | ce5a81f7969bc5cb6c5985cdc98f61ef8b5c6159 | [
"BSD-2-Clause"
] | 35 | 2017-08-16T06:52:26.000Z | 2022-03-27T21:49:01.000Z | test/t_widget_registry.cxx | nn6n/beng-proxy | 2cf351da656de6fbace3048ee90a8a6a72f6165c | [
"BSD-2-Clause"
] | 2 | 2017-12-22T15:34:23.000Z | 2022-03-08T04:15:23.000Z | test/t_widget_registry.cxx | nn6n/beng-proxy | 2cf351da656de6fbace3048ee90a8a6a72f6165c | [
"BSD-2-Clause"
] | 8 | 2017-12-22T15:11:47.000Z | 2022-03-15T22:54:04.000Z | /*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "widget/Registry.hxx"
#include "widget/Widget.hxx"
#include "widget/Class.hxx"
#include "http/Address.hxx"
#include "translation/Service.hxx"
#include "translation/Handler.hxx"
#include "translation/Request.hxx"
#include "translation/Response.hxx"
#include "translation/Transformation.hxx"
#include "AllocatorPtr.hxx"
#include "pool/pool.hxx"
#include "pool/Ptr.hxx"
#include "PInstance.hxx"
#include "util/Cancellable.hxx"
#include "stopwatch.hxx"
#include <gtest/gtest.h>
#include <string.h>
class MyTranslationService final : public TranslationService, Cancellable {
public:
bool aborted = false;
/* virtual methods from class TranslationService */
void SendRequest(AllocatorPtr alloc,
const TranslateRequest &request,
const StopwatchPtr &parent_stopwatch,
TranslateHandler &handler,
CancellablePointer &cancel_ptr) noexcept override;
/* virtual methods from class Cancellable */
void Cancel() noexcept override {
aborted = true;
}
};
struct Context : PInstance {
bool got_class = false;
const WidgetClass *cls = nullptr;
void RegistryCallback(const WidgetClass *_cls) noexcept {
got_class = true;
cls = _cls;
}
};
/*
* tstock.c emulation
*
*/
void
MyTranslationService::SendRequest(AllocatorPtr alloc,
const TranslateRequest &request,
const StopwatchPtr &,
TranslateHandler &handler,
CancellablePointer &cancel_ptr) noexcept
{
assert(request.remote_host == NULL);
assert(request.host == NULL);
assert(request.uri == NULL);
assert(request.widget_type != NULL);
assert(request.session.IsNull());
assert(request.param == NULL);
if (strcmp(request.widget_type, "sync") == 0) {
auto response = alloc.New<TranslateResponse>();
response->address = *http_address_parse(alloc, "http://foo/");
response->views = alloc.New<WidgetView>(nullptr);
response->views->address = {ShallowCopy(), response->address};
handler.OnTranslateResponse(*response);
} else if (strcmp(request.widget_type, "block") == 0) {
cancel_ptr = *this;
} else
assert(0);
}
/*
* tests
*
*/
TEST(WidgetRegistry, Normal)
{
MyTranslationService ts;
Context data;
WidgetRegistry registry(data.root_pool, ts);
CancellablePointer cancel_ptr;
auto pool = pool_new_linear(data.root_pool, "test", 8192);
registry.LookupWidgetClass(pool, pool, "sync",
BIND_METHOD(data, &Context::RegistryCallback),
cancel_ptr);
ASSERT_FALSE(ts.aborted);
ASSERT_TRUE(data.got_class);
ASSERT_NE(data.cls, nullptr);
ASSERT_EQ(data.cls->views.address.type, ResourceAddress::Type::HTTP);
ASSERT_STREQ(data.cls->views.address.GetHttp().host_and_port, "foo");
ASSERT_STREQ(data.cls->views.address.GetHttp().path, "/");
ASSERT_EQ(data.cls->views.next, nullptr);
ASSERT_TRUE(data.cls->views.transformations.empty());
pool.reset();
pool_commit();
}
/** caller aborts */
TEST(WidgetRegistry, Abort)
{
MyTranslationService ts;
Context data;
WidgetRegistry registry(data.root_pool, ts);
CancellablePointer cancel_ptr;
auto pool = pool_new_linear(data.root_pool, "test", 8192);
registry.LookupWidgetClass(pool, pool, "block",
BIND_METHOD(data, &Context::RegistryCallback),
cancel_ptr);
ASSERT_FALSE(data.got_class);
ASSERT_FALSE(ts.aborted);
cancel_ptr.Cancel();
ASSERT_TRUE(ts.aborted);
ASSERT_FALSE(data.got_class);
pool.reset();
pool_commit();
}
| 28.680723 | 75 | 0.741231 | CM4all |
e12d758454e2d43181eb3b6fff5f11a85b4616cd | 3,395 | cpp | C++ | inference-engine/thirdparty/clDNN/src/gpu/upsampling_gpu.cpp | zhoub/dldt | e42c01cf6e1d3aefa55e2c5df91f1054daddc575 | [
"Apache-2.0"
] | null | null | null | inference-engine/thirdparty/clDNN/src/gpu/upsampling_gpu.cpp | zhoub/dldt | e42c01cf6e1d3aefa55e2c5df91f1054daddc575 | [
"Apache-2.0"
] | null | null | null | inference-engine/thirdparty/clDNN/src/gpu/upsampling_gpu.cpp | zhoub/dldt | e42c01cf6e1d3aefa55e2c5df91f1054daddc575 | [
"Apache-2.0"
] | null | null | null | /*
// Copyright (c) 2016 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 "upsampling_inst.h"
#include "primitive_gpu_base.h"
#include "implementation_map.h"
#include "error_handler.h"
#include "kernel_selector_helper.h"
#include "upsampling/upsampling_kernel_selector.h"
#include "upsampling/upsampling_kernel_base.h"
namespace cldnn {
namespace gpu {
namespace {
inline kernel_selector::sample_type convert_to_sample_type(upsampling_sample_type type) {
switch (type) {
case upsampling_sample_type::nearest:
return kernel_selector::sample_type::NEAREST;
case upsampling_sample_type::bilinear:
return kernel_selector::sample_type::BILINEAR;
default:
return kernel_selector::sample_type::NEAREST;
}
}
} // namespace
struct upsampling_gpu : typed_primitive_gpu_impl<upsampling> {
using parent = typed_primitive_gpu_impl<upsampling>;
using parent::parent;
static primitive_impl* create(const upsampling_node& arg) {
auto us_params = get_default_params<kernel_selector::upsampling_params>(arg);
auto us_optional_params =
get_default_optional_params<kernel_selector::upsampling_optional_params>(arg.get_program());
const auto& primitive = arg.get_primitive();
if (primitive->with_activation)
convert_activation_func_params(primitive, us_params.activation);
us_params.num_filter = primitive->num_filter;
us_params.sampleType = convert_to_sample_type(primitive->sample_type);
auto& kernel_selector = kernel_selector::upsampling_kernel_selector::Instance();
auto best_kernels = kernel_selector.GetBestKernels(us_params, us_optional_params);
CLDNN_ERROR_BOOL(arg.id(),
"Best_kernel.empty()",
best_kernels.empty(),
"Cannot find a proper kernel with this arguments");
auto upsampling = new upsampling_gpu(arg, best_kernels[0]);
return upsampling;
}
};
namespace {
struct attach {
attach() {
implementation_map<upsampling>::add(
{{std::make_tuple(engine_types::ocl, data_types::f32, format::yxfb), upsampling_gpu::create},
{std::make_tuple(engine_types::ocl, data_types::f16, format::yxfb), upsampling_gpu::create},
{std::make_tuple(engine_types::ocl, data_types::f32, format::bfyx), upsampling_gpu::create},
{std::make_tuple(engine_types::ocl, data_types::f16, format::bfyx), upsampling_gpu::create},
{std::make_tuple(engine_types::ocl, data_types::f32, format::byxf), upsampling_gpu::create},
{std::make_tuple(engine_types::ocl, data_types::f16, format::byxf), upsampling_gpu::create}});
}
~attach() {}
};
attach attach_impl;
} // namespace
} // namespace gpu
} // namespace cldnn
| 38.579545 | 107 | 0.698969 | zhoub |
e12f8806969adebcb4a575491bc4fb1a3a84fee0 | 49 | hpp | C++ | src/boost_hana_ext_boost_fusion_deque.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_hana_ext_boost_fusion_deque.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_hana_ext_boost_fusion_deque.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/hana/ext/boost/fusion/deque.hpp>
| 24.5 | 48 | 0.77551 | miathedev |
e130e34796b879a2894eb8d721281355a920ed7d | 1,145 | hpp | C++ | include/networkit/generators/StochasticBlockmodel.hpp | kit-parco/networkit | e7cb33df26969e34b17f73ff80dbca982b2a34b9 | [
"MIT"
] | 194 | 2016-10-21T22:56:49.000Z | 2019-06-21T03:04:22.000Z | include/networkit/generators/StochasticBlockmodel.hpp | kit-parco/networkit | e7cb33df26969e34b17f73ff80dbca982b2a34b9 | [
"MIT"
] | 215 | 2017-02-06T09:12:54.000Z | 2019-06-24T10:52:24.000Z | include/networkit/generators/StochasticBlockmodel.hpp | kit-parco/networkit | e7cb33df26969e34b17f73ff80dbca982b2a34b9 | [
"MIT"
] | 93 | 2017-01-10T10:51:01.000Z | 2019-06-20T13:58:57.000Z | /*
* StochasticBlockmodel.hpp
*
* Created on: 13.08.2014
* Author: Christian Staudt
*/
#ifndef NETWORKIT_GENERATORS_STOCHASTIC_BLOCKMODEL_HPP_
#define NETWORKIT_GENERATORS_STOCHASTIC_BLOCKMODEL_HPP_
#include <networkit/generators/StaticGraphGenerator.hpp>
namespace NetworKit {
/**
* @ingroup generators
*/
class StochasticBlockmodel final : public StaticGraphGenerator {
public:
/**
* Construct a undirected regular ring lattice.
*
* @param nNodes number of nodes in target graph
* @param n number of blocks (=k)
* @param membership maps node ids to block ids (consecutive, 0 <= i < nBlocks)
* @param affinity matrix of size k x k with edge probabilities between the blocks
*/
StochasticBlockmodel(count n, count nBlocks, const std::vector<index> &membership,
const std::vector<std::vector<double>> &affinity);
Graph generate() override;
private:
count n;
std::vector<index> membership;
const std::vector<std::vector<double>> &affinity;
};
} /* namespace NetworKit */
#endif // NETWORKIT_GENERATORS_STOCHASTIC_BLOCKMODEL_HPP_
| 27.261905 | 89 | 0.697817 | kit-parco |
e131216988b37083b126bed680cfaa1b401e4336 | 1,030 | cpp | C++ | src/client/Country.cpp | john-fotis/SysPro2 | d403493ddad4c962353ecc8b41a7cf20e3759b09 | [
"MIT"
] | 1 | 2021-08-20T11:19:49.000Z | 2021-08-20T11:19:49.000Z | src/client/Country.cpp | john-fotis/SysPro2 | d403493ddad4c962353ecc8b41a7cf20e3759b09 | [
"MIT"
] | null | null | null | src/client/Country.cpp | john-fotis/SysPro2 | d403493ddad4c962353ecc8b41a7cf20e3759b09 | [
"MIT"
] | null | null | null | #include "include/Country.hpp"
Country::Country(const Country &country) {
if (this == &country) return;
name.clear();
name.assign(country.getName());
}
Country &Country::operator=(const Country &country) {
if (this == &country) return *this;
name.clear();
name.assign(country.getName());
return *this;
}
bool operator==(const Country &c1, const Country &c2) {
return (c1.getName() == c2.getName());
}
bool operator!=(const Country &c1, const Country &c2) {
return !(c1 == c2);
}
bool operator<(const Country &c1, const Country &c2) {
return c1.getName() < c2.getName();
}
bool operator>(const Country &c1, const Country &c2) {
return c1.getName() > c2.getName();
}
bool operator<=(const Country &c1, const Country &c2) {
return c1.getName() <= c2.getName();
}
bool operator>=(const Country &c1, const Country &c2) {
return c1.getName() >= c2.getName();
}
std::ostream &operator<<(std::ostream &os, const Country &country) {
os << country.getName();
return os;
} | 23.953488 | 68 | 0.639806 | john-fotis |
e1314ee536e7cfa437acc31cba31ad4953e63749 | 2,130 | cpp | C++ | configuration/HttpdConf.cpp | Peter408/webServer | 84d7fefd85a3fcbba44c9905d6d1c5c61ff58b61 | [
"MIT"
] | null | null | null | configuration/HttpdConf.cpp | Peter408/webServer | 84d7fefd85a3fcbba44c9905d6d1c5c61ff58b61 | [
"MIT"
] | null | null | null | configuration/HttpdConf.cpp | Peter408/webServer | 84d7fefd85a3fcbba44c9905d6d1c5c61ff58b61 | [
"MIT"
] | null | null | null | #include "HttpdConf.hpp"
#include <iostream>
#include <sstream>
#include <algorithm>
HttpdConf::HttpdConf(std::string fileName) : ConfigurationReader(fileName) {
createDispatch();
}
void HttpdConf::load() {
while(hasMoreLines()) {
std::istringstream iss(nextLine());
std::vector<std::string> tokens((std::istream_iterator<std::string>(iss)),
std::istream_iterator<std::string>());
dispatcher[tokens[0]](tokens);
}
closeFile();
}
std::string HttpdConf::removeQuotes(std::string &str) {
str.erase(remove( str.begin(), str.end(), '\"' ),str.end());
return str;
}
void HttpdConf::createDispatch() {
dispatcher = {
{"ServerRoot", [&](std::vector<std::string> tokens) {
serverRoot = removeQuotes(tokens[1]);
}},
{"DocumentRoot", [&](std::vector<std::string> tokens) {
documentRoot = removeQuotes(tokens[1]);
}},
{"Listen", [&](std::vector<std::string> tokens) {
port = std::stoi(tokens[1]);
}},
{"LogFile", [&](std::vector<std::string> tokens) {
logFile = removeQuotes(tokens[1]);
}},
{"ScriptAlias", [&](std::vector<std::string> tokens) {
scriptAliases [tokens[1]] = removeQuotes(tokens[2]);
}},
{"Alias", [&](std::vector<std::string> tokens) {
aliases [tokens[1]] = removeQuotes(tokens[2]);
}},
{"AccessFile", [&](std::vector<std::string> tokens) {
accessFile = removeQuotes(tokens[1]);
}},
{"DirectoryIndex", [&](std::vector<std::string> tokens) {
directoryIndex = removeQuotes(tokens[1]);
}}
};
}
const std::unordered_map<std::string, std::string>& HttpdConf::getAliases() {
return aliases;
}
const std::unordered_map<std::string, std::string>& HttpdConf::getScriptAliases() {
return scriptAliases;
}
const std::string HttpdConf::getDocumentRoot() {
return documentRoot;
}
const std::string HttpdConf::getLog() {
return logFile;
}
const uint HttpdConf::getPort() {
return port;
}
| 28.783784 | 83 | 0.577465 | Peter408 |
e1349809eb1e25d31982e9c4b985c4543d109a1f | 5,516 | cpp | C++ | pop/src/commands/ScheduleRetryCommand.cpp | webOS-ports/mojomail | 49358ac2878e010f5c6e3bd962f047c476c11fc3 | [
"Apache-2.0"
] | 6 | 2015-01-09T02:20:27.000Z | 2021-01-02T08:14:23.000Z | mojomail/pop/src/commands/ScheduleRetryCommand.cpp | openwebos/app-services | 021d509d609fce0cb41a0e562650bdd1f3bf4e32 | [
"Apache-2.0"
] | 3 | 2019-05-11T19:17:56.000Z | 2021-11-24T16:04:36.000Z | mojomail/pop/src/commands/ScheduleRetryCommand.cpp | openwebos/app-services | 021d509d609fce0cb41a0e562650bdd1f3bf4e32 | [
"Apache-2.0"
] | 6 | 2015-01-09T02:21:13.000Z | 2021-01-02T02:37:10.000Z | // @@@LICENSE
//
// Copyright (c) 2009-2013 LG Electronics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// LICENSE@@@
#include "commands/ScheduleRetryCommand.h"
#include "activity/ActivityBuilder.h"
#include "commands/DeleteActivitiesCommand.h"
#include "data/EmailAccountAdapter.h"
#include "PopClient.h"
#include "PopDefs.h"
int ScheduleRetryCommand::INITIAL_RETRY_SECONDS = 60;
int ScheduleRetryCommand::MAX_RETRY_SECONDS = 30 * 60;
float ScheduleRetryCommand::RETRY_MULTIPLIER = 1.5;
ScheduleRetryCommand::ScheduleRetryCommand(PopClient& client, const MojObject& folderId, EmailAccount::AccountError err)
: PopClientCommand(client, "Schedule Retry"),
m_folderId(folderId),
m_accntErr(err),
m_scheduleRetrySlot(this, &ScheduleRetryCommand::ScheduleRetryResponse),
m_deleteActivitiesSlot(this, &ScheduleRetryCommand::CancelActivitiesDone),
m_updateAccountSlot(this, &ScheduleRetryCommand::UpdateAccountResponse)
{
}
ScheduleRetryCommand::~ScheduleRetryCommand()
{
}
void ScheduleRetryCommand::RunImpl()
{
try {
if (!m_client.GetAccount().get()) {
MojString err;
err.format("Account is not loaded for '%s'", AsJsonString(
m_client.GetAccountId()).c_str());
throw MailException(err.data(), __FILE__, __LINE__);
}
ScheduleRetry();
} catch (const std::exception& ex) {
Failure(ex);
} catch (...) {
Failure(MailException("Unknown exception in scheduling POP account retry", __FILE__, __LINE__));
}
}
void ScheduleRetryCommand::ScheduleRetry()
{
ActivityBuilder ab;
// Get current retry interval from account
EmailAccount::RetryStatus retryStatus = m_client.GetAccount()->GetRetry();
int interval = retryStatus.GetInterval();
if(interval <= INITIAL_RETRY_SECONDS) {
interval = INITIAL_RETRY_SECONDS;
} else if(interval >= MAX_RETRY_SECONDS) {
interval = MAX_RETRY_SECONDS;
} else {
// TODO: only update this on actual retry?
interval *= RETRY_MULTIPLIER;
}
// Update account just in case it wasn't within the limit
retryStatus.SetInterval(interval);
m_client.GetAccount()->SetRetry(retryStatus);
m_client.GetActivityBuilderFactory()->BuildFolderRetrySync(ab, m_folderId, interval);
MojErr err;
MojObject payload;
err = payload.put("activity", ab.GetActivityObject());
ErrorToException(err);
err = payload.put("start", true);
ErrorToException(err);
err = payload.put("replace", true);
MojLogInfo(m_log, "Creating retry activity in activity manager: %s", AsJsonString(payload).c_str());
m_client.SendRequest(m_scheduleRetrySlot, "com.palm.activitymanager", "create", payload);
}
MojErr ScheduleRetryCommand::ScheduleRetryResponse(MojObject& response, MojErr err)
{
try {
MojLogInfo(m_log, "Retry activity creation: %s", AsJsonString(response).c_str());
ErrorToException(err);
CancelActivities();
} catch (const std::exception& e) {
MojLogError(m_log, "Exception in schedule retry response: '%s'", e.what());
Failure(e);
} catch (...) {
MojLogError(m_log, "Unknown exception in schedule retry response");
Failure(MailException("Unknown exception in schedule retry response", __FILE__, __LINE__));
}
return MojErrNone;
}
void ScheduleRetryCommand::CancelActivities()
{
// Delete anything that includes the folderId in the name
MojString folderIdSubstring;
MojErr err = folderIdSubstring.format("folderId=%s", AsJsonString(m_folderId).c_str());
ErrorToException(err);
MojString retryActivityName;
m_client.GetActivityBuilderFactory()->GetFolderRetrySyncActivityName(retryActivityName, m_folderId);
m_deleteActivitiesCommand.reset(new DeleteActivitiesCommand(m_client));
m_deleteActivitiesCommand->SetIncludeNameFilter(folderIdSubstring);
m_deleteActivitiesCommand->SetExcludeNameFilter(retryActivityName);
m_deleteActivitiesCommand->Run(m_deleteActivitiesSlot);
}
MojErr ScheduleRetryCommand::CancelActivitiesDone()
{
try {
m_deleteActivitiesCommand->GetResult()->CheckException();
UpdateAccount();
} catch (const std::exception& e) {
MojLogError(m_log, "Exception in cancel activities done: '%s'", e.what());
Failure(e);
} catch (...) {
MojLogError(m_log, "Unknown exception in cancel activities done");
Failure(MailException("Unknown exception in cancel activities done", __FILE__, __LINE__));
}
return MojErrNone;
}
void ScheduleRetryCommand::UpdateAccount()
{
MojObject accountObj;
EmailAccountAdapter::SerializeAccountRetryStatus(*m_client.GetAccount().get(), accountObj);
m_client.GetDatabaseInterface().UpdateAccountRetry(m_updateAccountSlot, m_client.GetAccountId(), accountObj);
}
MojErr ScheduleRetryCommand::UpdateAccountResponse(MojObject& response, MojErr err)
{
try {
ErrorToException(err);
Complete();
} catch (const std::exception& e) {
MojLogError(m_log, "Exception in update account response: '%s'", e.what());
Failure(e);
} catch (...) {
MojLogError(m_log, "Unknown exception in update account response");
Failure(MailException("Unknown exception in update account response", __FILE__, __LINE__));
}
return MojErrNone;
}
| 31.701149 | 120 | 0.759608 | webOS-ports |
e1380090e5e4c8865b84376be2e656aee9792197 | 935 | hpp | C++ | include/hydro/parser/__ast/ParamDecl.hpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | include/hydro/parser/__ast/ParamDecl.hpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | include/hydro/parser/__ast/ParamDecl.hpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | //
// __ __ __
// / / / /__ __ ____/ /_____ ____
// / /_/ // / / // __ // ___// __ \
// / __ // /_/ // /_/ // / / /_/ /
// /_/ /_/ \__, / \__,_//_/ \____/
// /____/
//
// The Hydro Programming Language
//
#ifndef __h3o_ParamDecl__
#define __h3o_ParamDecl__
#include "Decl.hpp"
#include "TypeSpec.hpp"
#include "Expr.hpp"
#include "ParamSymbol.hpp"
namespace hydro
{
class ParamDecl : public Decl
{
private:
TypeSpec *_type;
Expr *_defaultValue;
public:
ParamDecl(Token *token, Modifier *mod, Name *name, TypeSpec *type, ParamSymbol *symbol, Expr *defaultValue = nullptr);
virtual ~ParamDecl();
TypeSpec *type() const { return _type; }
Expr *defaultValue() const { return _defaultValue; }
};
} // namespace hydro
#endif /* __h3o_ParamDecl__ */
| 23.974359 | 122 | 0.516578 | hydraate |
e13869e260aa5e30185c4fcd0ae77230901e373a | 2,128 | cpp | C++ | Phase 1 Placement Specific/11. Strings/basic_functions.cpp | priyanshd2510/CPP-DSA | 00f5d1018ae2bd4e3d9c20a8b9d06c8ea862190f | [
"Apache-2.0"
] | 42 | 2021-01-03T17:54:59.000Z | 2022-03-26T15:57:01.000Z | Phase 1 Placement Specific/11. Strings/basic_functions.cpp | sauhard2701/CPP-DSA | 1e9202c7b6a15e13aff9edd9220f362e0d84abc6 | [
"Apache-2.0"
] | 26 | 2021-04-05T07:54:21.000Z | 2021-12-10T07:35:39.000Z | Phase 1 Placement Specific/11. Strings/basic_functions.cpp | sauhard2701/CPP-DSA | 1e9202c7b6a15e13aff9edd9220f362e0d84abc6 | [
"Apache-2.0"
] | 56 | 2020-12-24T17:06:33.000Z | 2022-02-06T18:21:33.000Z | #include <bits/stdc++.h>
using namespace std;
int main(){
string str,str1,str2,s; // zero based indexing
string sr (6,'0'); // create a string of "aaaaaa"
cout<<sr<<endl;
getline(cin,s); //input a string with spaces
cout<<s<<endl;
//append or add or concatenate 2 strings
str1 = "worry";
str2 = "about me";
str1.append(str2); // OR str1 = str1 + str2
cout<<str1+str2<<endl;//srt1 already contains worryabout me
//length() or size() is same
for(int i = 0; i<str1.length(); i++){
cout<<str1[i]<<" "; // we can treat string like arrays
}
cout<<endl;
str1.clear(); // empty string
str1 = "lost frequencies";
// cout<<str1<<" "<<str2<<endl;
//compare function -> return 0 if true or string equal
cout<<str1.compare(str2)<<endl;//return +ve number means that str1 is lexicographical greater than str2
cout<<str2.compare(str1)<<endl;// return -ve number means str2 is smaller
str2 = str1;
// self explanatory
if(!str1.compare(str2)){
cout<<"String equals";
}
else{
cout<<"strings not equal";
}
cout<<endl;
if(str.empty()){
cout<<"string is empty"<<endl;
}
str = "greatness";
str.erase(5,4);// it deletes the character starting from index 5 that is n to 5+4=9 ie s
cout<<str<<endl;//output "great" only
cout<<str.find("eat")<<endl;//found "eat" in "great" at index 2
cout<<str.insert(5,"ness")<<endl; // this is not zero based indexing
s = str.substr(2,5); // copy char from index 2 that is 'e' till 5 ie 'e' in word 'greatness'
cout<<s<<endl;
s = "3000";
int x = stoi(s); // convert string to int datatype
cout<<x/10<<endl;
x = 420;
s = to_string(x);
cout<<s + " samaj jao"<<endl; // convert int to string
cout<<endl;
str += str1 + str2 +s + "@#!$%&*($#@1356";
cout<<str<<endl;//adding all the strings or concatenating
cout<<endl;
//sorting string
sort(str.begin(),str.end());
cout<<str<<endl; // 2 spaces are sorted first because in the word "lost frequencies"
return 0;
} | 25.638554 | 107 | 0.590226 | priyanshd2510 |
e1388f6a440d029ab35a4e15c1744e8399d033c3 | 1,761 | cpp | C++ | src/PointVisual.cpp | StevenHong/dwl-rviz-plugin | 61b4f70408873dc67712eb6c3afed2e5e3e024ae | [
"BSD-3-Clause"
] | 10 | 2018-02-07T09:50:25.000Z | 2021-01-24T08:30:03.000Z | src/PointVisual.cpp | StevenHong/dwl-rviz-plugin | 61b4f70408873dc67712eb6c3afed2e5e3e024ae | [
"BSD-3-Clause"
] | 1 | 2022-02-11T10:08:51.000Z | 2022-02-11T10:08:51.000Z | src/PointVisual.cpp | StevenHong/dwl-rviz-plugin | 61b4f70408873dc67712eb6c3afed2e5e3e024ae | [
"BSD-3-Clause"
] | 4 | 2018-03-15T10:28:01.000Z | 2022-02-10T21:38:43.000Z | #include <OgreVector3.h>
#include <OgreSceneNode.h>
#include <OgreSceneManager.h>
#include <rviz/ogre_helpers/shape.h>
#include <dwl_rviz_plugin/PointVisual.h>
namespace dwl_rviz_plugin
{
PointVisual::PointVisual(Ogre::SceneManager* scene_manager,
Ogre::SceneNode* parent_node) : radius_(0.)
{
scene_manager_ = scene_manager;
// Ogre::SceneNode s form a tree, with each node storing the transform (position and
// orientation) of itself relative to its parent. Ogre does the math of combining those
// transforms when it is time to render.
// Here we create a node to store the pose of the Point's header frame relative to the RViz
// fixed frame.
frame_node_ = parent_node->createChildSceneNode();
// We create the point object within the frame node so that we can set its position.
point_ = new rviz::Shape(rviz::Shape::Sphere, scene_manager_, frame_node_);
}
PointVisual::~PointVisual()
{
// Delete the point to make it disappear.
delete point_;
// Destroy the frame node since we don't need it anymore.
scene_manager_->destroySceneNode(frame_node_);
}
void PointVisual::setPoint(const Ogre::Vector3& point)
{
Ogre::Vector3 scale(radius_, radius_, radius_);
point_->setScale(scale);
// Set the orientation of the arrow to match the direction of the acceleration vector.
point_->setPosition(point);
}
void PointVisual::setFramePosition(const Ogre::Vector3& position)
{
frame_node_->setPosition(position);
}
void PointVisual::setFrameOrientation(const Ogre::Quaternion& orientation)
{
frame_node_->setOrientation(orientation);
}
void PointVisual::setColor(float r, float g, float b, float a)
{
point_->setColor(r, g, b, a);
}
void PointVisual::setRadius(float r)
{
radius_ = r;
}
} //@namespace dwl_rviz_plugin
| 24.123288 | 92 | 0.75071 | StevenHong |
e138a542414962863139e1abdaec88cfcdbae984 | 4,038 | cpp | C++ | src/TestMushMesh/TestMushMeshApp.cpp | mushware/adanaxis-core-app | 679ac3e8a122e059bb208e84c73efc19753e87dd | [
"MIT"
] | 9 | 2020-11-02T17:20:40.000Z | 2021-12-25T15:35:36.000Z | src/TestMushMesh/TestMushMeshApp.cpp | mushware/adanaxis-core-app | 679ac3e8a122e059bb208e84c73efc19753e87dd | [
"MIT"
] | 2 | 2020-06-27T23:14:13.000Z | 2020-11-02T17:28:32.000Z | src/TestMushMesh/TestMushMeshApp.cpp | mushware/adanaxis-core-app | 679ac3e8a122e059bb208e84c73efc19753e87dd | [
"MIT"
] | 1 | 2021-05-12T23:05:42.000Z | 2021-05-12T23:05:42.000Z | //%Header {
/*****************************************************************************
*
* File: src/TestMushMesh/TestMushMeshApp.cpp
*
* Copyright: Andy Southgate 2002-2007, 2020
*
* 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.
*
****************************************************************************/
//%Header } fLo4NYe7P7n7p3BjMIvqPA
/*
* $Id: TestMushMeshApp.cpp,v 1.11 2006/06/01 15:40:01 southa Exp $
* $Log: TestMushMeshApp.cpp,v $
* Revision 1.11 2006/06/01 15:40:01 southa
* DrawArray verification and fixes
*
* Revision 1.10 2005/05/19 13:02:22 southa
* Mac release work
*
* Revision 1.9 2004/01/02 21:13:16 southa
* Source conditioning
*
* Revision 1.8 2003/10/24 12:39:09 southa
* Triangular mesh work
*
* Revision 1.7 2003/10/23 20:03:58 southa
* End mesh work
*
* Revision 1.6 2003/10/20 13:02:54 southa
* Patch fixes and testing
*
* Revision 1.5 2003/10/17 12:27:20 southa
* Line end fixes and more mesh work
*
* Revision 1.4 2003/10/15 12:23:10 southa
* MushMeshArray neighbour testing and subdivision work
*
* Revision 1.3 2003/10/15 11:54:54 southa
* MushMeshArray neighbour testing and subdivision
*
* Revision 1.2 2003/10/15 07:08:29 southa
* MushMeshArray creation
*
* Revision 1.1 2003/10/14 13:07:26 southa
* MushMesh vector creation
*
*/
#include "TestMushMeshApp.h"
using namespace Mushware;
using namespace std;
MUSHCORE_SINGLETON_INSTANCE(TestMushMeshApp);
U32 TestMushMeshApp::m_passCount=0;
TestMushMeshApp::tFails TestMushMeshApp::m_fails;
void
TestMushMeshApp::EnterInstance(void)
{
cout << "Starting tests" << endl;
RunTest("testvector", "MushMeshVector");
RunTest("testbox", "MushMeshBox");
RunTest("testarray", "MushMeshArray");
RunTest("testtriangulararray", "MushMeshTriangularArray");
RunTest("testutils", "MushMeshUtils");
RunTest("testpatch", "MushMeshPatch");
RunTest("testsubdivide", "MushMeshSubdivide");
}
void
TestMushMeshApp::RunTest(const string& inCommandStr, const string& inNameStr)
{
cout << "Test " << inNameStr << "... ";
try
{
MushcoreInterpreter::Sgl().Execute(inCommandStr);
PassAdd(inNameStr);
cout << "passed";
}
catch (MushcoreFail& e)
{
cout << "FAILED";
FailureAdd(inNameStr+": "+e.what());
}
cout << endl;
}
void
TestMushMeshApp::Enter(void)
{
Sgl().EnterInstance();
}
void
TestMushMeshApp::FailureAdd(const std::string& inStr)
{
m_fails.push_back(inStr);
}
void
TestMushMeshApp::PassAdd(const std::string& inStr)
{
++m_passCount;
}
void
TestMushMeshApp::FailuresPrint(void)
{
if (m_fails.size() == 0)
{
cout << "All " << m_passCount << " tests passed" << endl;
}
else
{
cout << "****** " << m_fails.size() << " test failures" << endl;
cout << "Failure report:" << endl;
}
for (tFails::const_iterator p = m_fails.begin(); p != m_fails.end(); ++p)
{
cout << *p << endl;
}
}
| 28.237762 | 78 | 0.655275 | mushware |
e139f6f46e16a0fc5424aea8da479effb37d2bf7 | 3,753 | cpp | C++ | old/System/Backends/Scummvm/KeyboardImplementation.cpp | DrItanium/AdventureEngine | abb2f492a9cc085fd95e3674d8af65ea6d8cbb81 | [
"BSD-3-Clause"
] | null | null | null | old/System/Backends/Scummvm/KeyboardImplementation.cpp | DrItanium/AdventureEngine | abb2f492a9cc085fd95e3674d8af65ea6d8cbb81 | [
"BSD-3-Clause"
] | null | null | null | old/System/Backends/Scummvm/KeyboardImplementation.cpp | DrItanium/AdventureEngine | abb2f492a9cc085fd95e3674d8af65ea6d8cbb81 | [
"BSD-3-Clause"
] | null | null | null | /*
The Adventure Engine
Copyright (c) 2013, Joshua Scoggins
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 Joshua Scoggins nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Joshua Scoggins 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.
*/
#define FORBIDDEN_SYMBOL_ALLOW_ALL
#include <System/Backends/Scummvm/AdventureEngine.h>
#include "common/events.h"
#include "common/system.h"
extern "C" {
#include <System/Input/KeyboardInput.h>
#include <System/Core/clips.h>
}
#define PullOutEngine(env) (AdventureEngine::AdventureEngineEngine*)GetEnvironmentContext(env)
#define NullMultifield(env, rVal) EnvSetMultifieldErrorValue(env, rVal)
extern "C" void GetCurrentlyPressedKeys(void* theEnv, DATA_OBJECT_PTR returnValue) {
void* multifield;
AdventureEngine::AdventureEngineEngine* engine = PullOutEngine(theEnv);
Common::EventManager* _eventMan = engine->getEventManager();
Common::Event keyEvent;
//this function does generate side effects if we assert facts
//However, if we return a multifield with all the contents then we need to
//parse it....hmmmmmm, doing the multifield is easier
//only check for a single key at this point
while(_eventMan->pollEvent(keyEvent))
{
//let's do a simple test
switch(keyEvent.type) {
case Common::EVENT_KEYDOWN:
switch(keyEvent.kbd.keycode) {
case Common::KEYCODE_ESCAPE:
multifield = EnvCreateMultifield(theEnv, 1);
SetMFType(multifield, 1, SYMBOL);
SetMFValue(multifield, 1, EnvAddSymbol(theEnv, (char*)"escape"));
SetpType(returnValue, MULTIFIELD);
SetpValue(returnValue, multifield);
SetpDOBegin(returnValue, 1);
SetpDOEnd(returnValue, 1);
return;
default:
multifield = EnvCreateMultifield(theEnv, 1);
SetMFType(multifield, 1, INTEGER);
SetMFValue(multifield, 1, EnvAddLong(theEnv, keyEvent.kbd.keycode));
SetpType(returnValue, MULTIFIELD);
SetpValue(returnValue, multifield);
SetpDOBegin(returnValue, 1);
SetpDOEnd(returnValue, 1);
return;
}
default:
NullMultifield(theEnv, returnValue);
return;
}
}
NullMultifield(theEnv, returnValue);
}
#undef PullOutEngine
#undef NullMultifield
| 45.216867 | 94 | 0.699174 | DrItanium |
e13d8da3b9d667f0a9864ffe394061460cdec758 | 15,499 | cpp | C++ | Code/EMMPMLib/Core/MPMCalculation.cpp | BlueQuartzSoftware/emmpm | edfc6d5840e6d18ad784b763c845356432eae9d6 | [
"libtiff"
] | null | null | null | Code/EMMPMLib/Core/MPMCalculation.cpp | BlueQuartzSoftware/emmpm | edfc6d5840e6d18ad784b763c845356432eae9d6 | [
"libtiff"
] | null | null | null | Code/EMMPMLib/Core/MPMCalculation.cpp | BlueQuartzSoftware/emmpm | edfc6d5840e6d18ad784b763c845356432eae9d6 | [
"libtiff"
] | null | null | null | /*
The Original EM/MPM algorithm was developed by Mary L. Comer and is distributed
under the BSD License.
Copyright (c) <2010>, <Mary L. Comer>
All rights reserved.
[1] Comer, Mary L., and Delp, Edward J., ÒThe EM/MPM Algorithm for Segmentation
of Textured Images: Analysis and Further Experimental Results,Ó IEEE Transactions
on Image Processing, Vol. 9, No. 10, October 2000, pp. 1731-1744.
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 <Mary L. Comer> nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* acvmpm.c */
/* Modified by Joel Dumke on 1/30/09 */
/* Heavily modified from the original by Michael A. Jackson for BlueQuartz Software
* and funded by the Air Force Research Laboratory, Wright-Patterson AFB.
*/
#include "MPMCalculation.h"
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real.hpp>
#include <boost/random/variate_generator.hpp>
#include "EMMPMLib/Core/EMMPM.h"
#include "EMMPMLib/Common/MSVCDefines.h"
#include "EMMPMLib/Common/EMMPM_Math.h"
#include "EMMPMLib/Common/EMTime.h"
#include "EMMPMLib/Core/EMMPMUtilities.h"
#define USE_TBB_TASK_GROUP 0
#if defined (EMMPMLib_USE_PARALLEL_ALGORITHMS)
#include <tbb/task_scheduler_init.h>
#include <tbb/parallel_for.h>
#include <tbb/blocked_range2d.h>
#include <tbb/partitioner.h>
#include <tbb/task_group.h>
#endif
#define COMPUTE_C_CLIQUE( C, x, y, ci, cj)\
if((x) < 0 || (x) >= colEnd || (y) < 0 || (y) >= rowEnd) {\
C[ci][cj] = classes;\
}\
else\
{\
ij = (cols * (y)) + (x);\
C[ci][cj] = xt[ij];\
}
/**
* @class ParallelCalcLoop ParallelCalcLoop.h EMMPM/Curvature/ParallelCalcLoop.h
* @brief This class can calculate the parts of the MPM loop in parallel
* @author Michael A. Jackson for BlueQuartz Software
* @date March 11, 2012
* @version 1.0
*/
class ParallelMPMLoop
{
public:
#if USE_TBB_TASK_GROUP
ParallelCalcLoop(EMMPM_Data* dPtr, real_t* ykPtr, real_t* rnd, int rowStart, int rowEnd,
int colStart, int colEnd) :
m_RowStart(rowStart),
m_RowEnd(rowEnd),
m_ColStart(colStart),
m_ColEnd(colEnd),
#else
ParallelMPMLoop(EMMPM_Data* dPtr, real_t* ykPtr, real_t* rnd) :
#endif
data(dPtr),
yk(ykPtr),
rnd(rnd)
{}
virtual ~ParallelMPMLoop(){}
void calc(int rowStart, int rowEnd,
int colStart, int colEnd) const
{
//uint64_t millis = EMMPM_getMilliSeconds();
// int l;
real_t prior;
int32_t ij, lij;
int rows = data->rows;
int cols = data->columns;
int classes = data->classes;
real_t xrnd, current;
real_t post[EMMPM_MAX_CLASSES], sum, edge;
size_t nsCols = data->columns - 1;
size_t ewCols = data->columns;
size_t swCols = data->columns - 1;
size_t nwCols = data->columns - 1;
unsigned char* xt = data->xt;
real_t* probs = data->probs;
real_t* ccost = data->ccost;
real_t* ns = data->ns;
real_t* ew = data->ew;
real_t* sw = data->sw;
real_t* nw = data->nw;
real_t curvature_value = (real_t)0.0;
int C[3][3]; // This is the Clique for the current Pixel
// --------- X -----
// | | 0 | 1 | 2 |
// -----------------
// Y | 0 | | | |
// -----------------
// | 1 | | P | |
// -----------------
// | 2 | | | |
//
// When we calculate the "C" matrix if the pixel value for the specific index of
// the clique would be off the image then a value = number of classes is
// used for the C[i][j]. That way we can figure out if we are off the image
std::stringstream ss;
unsigned int cSize = classes + 1;
real_t* coupling = data->couplingBeta;
for (int32_t y = rowStart; y < rowEnd; y++)
{
for (int32_t x = colStart; x < colEnd; x++)
{
/* ------------- */
COMPUTE_C_CLIQUE(C, x-1, y-1, 0, 0);
COMPUTE_C_CLIQUE(C, x, y-1, 1, 0);
COMPUTE_C_CLIQUE(C, x+1, y-1, 2, 0);
COMPUTE_C_CLIQUE(C, x-1, y, 0, 1);
COMPUTE_C_CLIQUE(C, x+1, y, 2, 1);
COMPUTE_C_CLIQUE(C, x-1, y+1, 0, 2);
COMPUTE_C_CLIQUE(C, x, y+1, 1, 2);
COMPUTE_C_CLIQUE(C, x+1, y+1, 2, 2);
#if 0
if (y == rowStart + 1 && x == colStart + 1)
{
ss << "------------------------------" << std::endl;
ss << "|" << C[0][0] << "\t" << C[1][0] << "\t" << C[2][0] << std::endl;
ss << "|" << C[0][1] << "\t" << C[1][1] << "\t" << C[2][1] << std::endl;
ss << "|" << C[0][2] << "\t" << C[1][2] << "\t" << C[2][2] << std::endl;
ss << "------------------------------" << std::endl;
std::cout << ss.str() << std::endl;
}
#endif
ij = (cols*y)+x;
sum = 0;
for (int l = 0; l < classes; ++l)
{
prior = 0;
edge = 0;
prior += coupling[(cSize*l)+ C[0][0]];
prior += coupling[(cSize*l)+ C[1][0]];
prior += coupling[(cSize*l)+ C[2][0]];
prior += coupling[(cSize*l)+ C[0][1]];
prior += coupling[(cSize*l)+ C[2][1]];
prior += coupling[(cSize*l)+ C[0][2]];
prior += coupling[(cSize*l)+ C[1][2]];
prior += coupling[(cSize*l)+ C[2][2]];
#if 0
if (y == rowStart + 1 && x == colStart + 1)
{
std::cout << "Class: " << l << "\t prior: " << prior << std::endl;
}
#endif
// now check for the gradient penalty. If our current class is NOT equal
// to the class at index[i][j] AND the value of C[i][j] does NOT equal
// to the Number of Classes then add in the gradient penalty.
if (data->useGradientPenalty)
{
if (C[0][0] != l && C[0][0] != classes) edge += sw[(swCols*(y-1))+x-1];
if (C[1][0] != l && C[1][0] != classes) edge += ew[(ewCols*(y-1))+x];
if (C[2][0] != l && C[2][0] != classes) edge += nw[(nwCols*(y-1))+x];
if (C[0][1] != l && C[0][1] != classes) edge += ns[(nsCols*y)+x-1];
if (C[2][1] != l && C[2][1] != classes) edge += ns[(nsCols*y)+x];
if (C[0][2] != l && C[0][2] != classes) edge += nw[(nwCols*y)+x-1];
if (C[1][2] != l && C[1][2] != classes) edge += ew[(ewCols*y)+x];
if (C[2][2] != l && C[2][2] != classes) edge += sw[(swCols*y)+x];
}
lij = (cols * rows * l) + (cols * y) + x;
curvature_value = 0.0;
if (data->useCurvaturePenalty)
{
curvature_value = data->beta_c * ccost[lij];
}
real_t arg = data->workingKappa * (yk[lij] - (prior) - (edge) - (curvature_value) - data->w_gamma[l]);
post[l] = expf(arg);
sum += post[l];
}
xrnd = rnd[ij];
current = 0.0;
for (int l = 0; l < classes; l++)
{
lij = (cols * rows * l) + ij;
real_t arg = post[l] / sum;
if ((xrnd >= current) && (xrnd <= (current + arg)))
{
xt[ij] = l;
probs[lij] += 1.0;
}
current += arg;
}
#if 0
Dont even THINK about using this code...
This classifys the pixel based on the largest
in magnitude probability
real_t max = 0.0;
int maxClass = 0;
for (int l = 0; l < classes; l++)
{
lij = (cols * rows * l) + ij;
//real_t arg = post[l] / sum;
if (probs[lij] > max)
{
max = probs[lij];
maxClass = l;
}
}
//Assign class based on Maximum probability
xt[ij] = maxClass;
#endif
}
}
// std::cout << " --" << EMMPM_getMilliSeconds() - millis << "--" << std::endl;
}
#if defined (EMMPMLib_USE_PARALLEL_ALGORITHMS)
#if USE_TBB_TASK_GROUP
void operator()() const
{
calc(m_RowStart, m_RowEnd, m_ColStart, m_ColEnd);
}
#else
void operator()(const tbb::blocked_range2d<int> &r) const
{
calc(r.rows().begin(), r.rows().end(), r.cols().begin(), r.cols().end());
}
#endif
#endif
private:
#if USE_TBB_TASK_GROUP
int m_RowStart;
int m_RowEnd;
int m_ColStart;
int m_ColEnd;
#endif
const EMMPM_Data* data;
const real_t* yk;
const real_t* rnd;
};
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
MPMCalculation::MPMCalculation() :
m_StatsDelegate(NULL)
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
MPMCalculation::~MPMCalculation()
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void MPMCalculation::execute()
{
EMMPM_Data* data = m_Data.get();
real_t* yk;
real_t sqrt2pi, con[EMMPM_MAX_CLASSES];
real_t post[EMMPM_MAX_CLASSES];
// int k, l;
// unsigned int i, j, d;
size_t ld, ijd, lij;
unsigned int dims = data->dims;
unsigned int rows = data->rows;
unsigned int cols = data->columns;
unsigned int classes = data->classes;
// int rowEnd = rows/2;
unsigned char* y = data->y;
real_t* probs = data->probs;
real_t* m = data->mean;
real_t* v = data->variance;
char msgbuff[256];
float totalLoops;
int currentLoopCount;
// real_t curvature_value = (real_t)0.0;
memset(post, 0, EMMPM_MAX_CLASSES * sizeof(real_t));
memset(con, 0, EMMPM_MAX_CLASSES * sizeof(real_t));
totalLoops = (float)(data->emIterations * data->mpmIterations + data->mpmIterations);
memset(msgbuff, 0, 256);
data->progress++;
yk = (real_t*)malloc(cols * rows * classes * sizeof(real_t));
sqrt2pi = sqrt(2.0 * M_PI);
for (uint32_t l = 0; l < classes; l++)
{
con[l] = 0;
for (uint32_t d = 0; d < dims; d++)
{
ld = dims * l + d;
con[l] += -log(sqrt2pi * sqrt(v[ld]));
}
}
for (uint32_t i = 0; i < rows; i++)
{
for (uint32_t j = 0; j < cols; j++)
{
for (uint32_t l = 0; l < classes; l++)
{
lij = (cols * rows * l) + (cols * i) + j;
probs[lij] = 0;
yk[lij] = con[l];
for (uint32_t d = 0; d < dims; d++)
{
ld = dims * l + d;
ijd = (dims * cols * i) + (dims * j) + d;
yk[lij] += ((y[ijd] - m[ld]) * (y[ijd] - m[ld]) / (-2.0 * v[ld]));
}
}
}
}
const float rangeMin = 0;
const float rangeMax = 1.0f;
typedef boost::uniform_real<real_t> NumberDistribution;
typedef boost::mt19937 RandomNumberGenerator;
typedef boost::variate_generator<RandomNumberGenerator&,
NumberDistribution> Generator;
NumberDistribution distribution(rangeMin, rangeMax);
RandomNumberGenerator generator;
Generator numberGenerator(generator, distribution);
generator.seed(EMMPM_getMilliSeconds()); // seed with the current time
// Generate all the numbers up front
size_t total = rows * cols;
std::vector<real_t> rndNumbers(total);
real_t* rndNumbersPtr = &(rndNumbers.front());
for(size_t i = 0; i < total; ++i)
{
rndNumbersPtr[i] = numberGenerator(); // Work directly with the pointer for speed.
}
//unsigned long long int millis = EMMPM_getMilliSeconds();
//std::cout << "------------------------------------------------" << std::endl;
/* Perform the MPM loops */
for (int32_t k = 0; k < data->mpmIterations; k++)
{
data->currentMPMLoop = k;
if (data->cancel) { data->progress = 100.0; break; }
data->inside_mpm_loop = 1;
#if defined (EMMPMLib_USE_PARALLEL_ALGORITHMS)
tbb::task_scheduler_init init;
int threads = init.default_num_threads();
#if USE_TBB_TASK_GROUP
tbb::task_group* g = new tbb::task_group;
unsigned int rowIncrement = rows/threads;
unsigned int rowStop = 0 + rowIncrement;
unsigned int rowStart = 0;
for (int t = 0; t < threads; ++t)
{
g->run(ParallelCalcLoop(data, yk, &(rndNumbers.front()), rowStart, rowStop, 0, cols) );
rowStart = rowStop;
rowStop = rowStop + rowIncrement;
if (rowStop >= rows)
{
rowStop = rows;
}
}
g->wait();
delete g;
#else
tbb::parallel_for(tbb::blocked_range2d<int>(0, rows, rows/threads, 0, cols, cols),
ParallelMPMLoop(data, yk, &(rndNumbers.front())),
tbb::simple_partitioner());
#endif
#else
ParallelMPMLoop pcl(data, yk, &(rndNumbers.front()));
pcl.calc(0, rows, 0, cols);
#endif
//std::cout << "Counter: " << counter << std::endl;
EMMPMUtilities::ConvertXtToOutputImage(getData());
data->currentMPMLoop = k;
// snprintf(msgbuff, 256, "MPM Loop %d", data->currentMPMLoop);
// notify(msgbuff, 0, UpdateProgressMessage);
currentLoopCount = data->mpmIterations * data->currentEMLoop + data->currentMPMLoop;
data->progress = currentLoopCount / totalLoops * 100.0;
// notify("", data->progress, UpdateProgressValue);
if (m_StatsDelegate != NULL)
{
m_StatsDelegate->reportProgress(m_Data);
}
}
#if 0
#if defined (EMMPMLib_USE_PARALLEL_ALGORITHMS)
std::cout << "Parrallel MPM Loop Time to Complete:";
#else
std::cout << "Serial MPM Loop Time To Complete: ";
#endif
std::cout << (EMMPM_getMilliSeconds() - millis) << std::endl;
#endif
data->inside_mpm_loop = 0;
if (!data->cancel)
{
/* Normalize probabilities */
for (uint32_t i = 0; i < data->rows; i++)
{
for (uint32_t j = 0; j < data->columns; j++)
{
for (uint32_t l = 0; l < classes; l++)
{
lij = (cols * rows * l) + (cols * i) + j;
data->probs[lij] = data->probs[lij] / (real_t)data->mpmIterations;
}
}
}
}
/* Clean Up Memory */
free(yk);
}
| 30.813121 | 114 | 0.548552 | BlueQuartzSoftware |
e13da52398e3eaa5474ae908429a93b784ce55fd | 4,011 | cpp | C++ | src/Window.cpp | PurpleAzurite/starter_project | 9503bc689ec93bc21797e24bd9abb33bca75c140 | [
"Apache-2.0"
] | null | null | null | src/Window.cpp | PurpleAzurite/starter_project | 9503bc689ec93bc21797e24bd9abb33bca75c140 | [
"Apache-2.0"
] | null | null | null | src/Window.cpp | PurpleAzurite/starter_project | 9503bc689ec93bc21797e24bd9abb33bca75c140 | [
"Apache-2.0"
] | null | null | null | // clang-format off
#include "Window.h"
#include "Events/KeyEvents.h"
#include "Events/WindowEvents.h"
#include "Events/MouseEvents.h"
#include <utility>
// clang-format on
namespace Engine {
Window::Window(WindowProps props)
: m_data(std::move(props))
{
glfwSetErrorCallback(
[](int code, const char* msg) { ENGINE_ERROR("[GLFW] Error {}: {}", code, msg); });
glfwInit();
m_context =
glfwCreateWindow(m_data.width, m_data.height, m_data.title.data(), nullptr, nullptr);
glfwMakeContextCurrent(m_context);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
ENGINE_ERROR("[GLAD] Could not load GLAD!");
glfwSetWindowUserPointer(m_context, reinterpret_cast<void*>(&m_data));
glfwSetWindowCloseCallback(m_context, [](GLFWwindow* window) {
auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window));
WindowClosedEvent event;
data.callback(event);
});
glfwSetWindowPosCallback(m_context, [](GLFWwindow* window, int x, int y) {
auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window));
WindowMovedEvent event(x, y);
data.callback(event);
});
glfwSetWindowSizeCallback(m_context, [](GLFWwindow* window, int width, int height) {
// TODO: Should framebuffer be resized here?
auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window));
WindowResizedEvent event(width, height);
data.callback(event);
});
glfwSetWindowFocusCallback(m_context, [](GLFWwindow* window, int focus) {
auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window));
switch (focus)
{
case 1: {
WindowFocusedEvent event;
data.callback(event);
break;
}
case 0: {
WindowLostFocusEvent event;
data.callback(event);
break;
}
}
});
glfwSetCursorPosCallback(m_context, [](GLFWwindow* window, double x, double y) {
auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window));
MouseMovedEvent event(x, y);
data.callback(event);
});
glfwSetMouseButtonCallback(m_context, [](GLFWwindow* window, int button, int action, int mods) {
(void)mods;
auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window));
switch (action)
{
case GLFW_PRESS: {
MouseButtonPressedEvent event(button);
data.callback(event);
break;
}
case GLFW_RELEASE: {
MouseButtonReleasedEvent event(button);
data.callback(event);
break;
}
}
});
glfwSetScrollCallback(m_context, [](GLFWwindow* window, double xOffset, double yOffset) {
auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window));
MouseScrolledEvent event(xOffset, yOffset);
data.callback(event);
});
glfwSetKeyCallback(m_context, [](GLFWwindow* window, int key, int scancode, int action, int mod) {
(void)scancode;
(void)action;
(void)mod;
auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window));
switch(action) {
case GLFW_PRESS:
{
KeyPressedEvent event(key);
data.callback(event);
break;
}
case GLFW_RELEASE:
{
KeyReleasedEvent event(key);
data.callback(event);
break;
}
}
});
// TODO callbacks: key pressed, key
// released
}
Window::~Window()
{
glfwDestroyWindow(m_context);
glfwTerminate();
}
void Window::update()
{
glfwSwapBuffers(m_context);
glfwPollEvents();
}
void Window::setCallbackFunction(const CallbackFn& fn) { m_data.callback = fn; }
} // namespace Engine
| 28.446809 | 102 | 0.614061 | PurpleAzurite |
e13e9ad8389b56e7927bb757d05b89569268f52a | 1,885 | cpp | C++ | frameworks/cocos2d-x/cocos/scripting/ruby-bindings/manual/CCRubyEngine.cpp | pedrohenriquerls/cocos2d_ruby_binding | 52d929ddcd8e4b7f613c98d73477133952b8a7b0 | [
"MIT"
] | null | null | null | frameworks/cocos2d-x/cocos/scripting/ruby-bindings/manual/CCRubyEngine.cpp | pedrohenriquerls/cocos2d_ruby_binding | 52d929ddcd8e4b7f613c98d73477133952b8a7b0 | [
"MIT"
] | null | null | null | frameworks/cocos2d-x/cocos/scripting/ruby-bindings/manual/CCRubyEngine.cpp | pedrohenriquerls/cocos2d_ruby_binding | 52d929ddcd8e4b7f613c98d73477133952b8a7b0 | [
"MIT"
] | null | null | null | #include "CCRubyEngine.h"
#include "RubyBridge.h"
#include "ruby_cocos2dx_auto.hpp"
#include "ruby_cocos2dx_audioengine_auto.hpp"
#include "ManualImplement.h"
#include "RubyValueMap.h"
NS_CC_BEGIN
RubyEngine* RubyEngine::_defaultEngine = nullptr;
RubyEngine* RubyEngine::getInstance(void)
{
if (!_defaultEngine)
{
_defaultEngine = new (std::nothrow) RubyEngine();
//_defaultEngine->init();
}
return _defaultEngine;
}
RubyEngine::RubyEngine(void)
{
_init_Ruby_VM();
register_all_cocos2dx();
register_all_cocos2dx_audioengine();
manual_implement();
}
RubyEngine::~RubyEngine(void)
{
_defaultEngine=nullptr;
}
int RubyEngine::handleMenuClickedEvent(void* data)
{
if (NULL == data)
return 0;
BasicScriptData* basicScriptData = (BasicScriptData*)data;
if (NULL == basicScriptData->nativeObject)
return 0;
MenuItem* menuItem = static_cast<MenuItem*>(basicScriptData->nativeObject);
RBVAL menuItemValue=rbb_get_or_create_value<cocos2d::MenuItem>(menuItem);
RBVAL onClicked=rb_ivar_get_bridge(menuItemValue,ATID_onClicked());
if (onClicked!=RBNil()){
RBVAL resultVal=rb_proc_call_protected(onClicked);
int result=0;
rb_value_to_int(resultVal,&result);
return result;
}
return 0;
}
int RubyEngine::sendEvent(ScriptEvent* evt){
if (NULL == evt)
return 0;
switch (evt->type)
{
case kMenuClickedEvent:
{
return handleMenuClickedEvent(evt->data);
}
break;
default:
break;
}
return 0;
}
int RubyEngine::executeString(const char* codes) {
return _ruby_executeString(codes);
}
int RubyEngine::executeScriptFile(const char* filename) {
std::string cmd("eval_script \"");
cmd.append(filename);
cmd.append("\"");
return executeString(cmd.c_str());
}
NS_CC_END | 20.944444 | 79 | 0.679045 | pedrohenriquerls |
e13fa352ee2c1942e4a613b79cb77cfca27e2f54 | 747 | cpp | C++ | algorithms/convert-sorted-array-to-binary-search-tree.cpp | jlygit/leetcode-oj | 66718f709b31ef0e7e091638d95418a5543019b4 | [
"Apache-2.0"
] | 1 | 2016-08-10T11:17:16.000Z | 2016-08-10T11:17:16.000Z | algorithms/convert-sorted-array-to-binary-search-tree.cpp | jlygit/leetcode-oj | 66718f709b31ef0e7e091638d95418a5543019b4 | [
"Apache-2.0"
] | null | null | null | algorithms/convert-sorted-array-to-binary-search-tree.cpp | jlygit/leetcode-oj | 66718f709b31ef0e7e091638d95418a5543019b4 | [
"Apache-2.0"
] | null | null | null | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* makeBST(vector<int>& nums,int start,int end) {
if(start>end) return NULL;
TreeNode* t;
if(start==end) {
t=new TreeNode(nums[start]);
} else {
int m=(start+end)/2;
t=new TreeNode(nums[m]);
t->left=makeBST(nums,start,m-1);
t->right=makeBST(nums,m+1,end);
}
return t;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return makeBST(nums,0,nums.size()-1);
}
}; | 26.678571 | 61 | 0.504685 | jlygit |
e1411f576c5b14d6f36e291270c0d059f6a01d3c | 1,332 | cpp | C++ | Modules/QtWidgets/src/QmitkMimeTypes.cpp | maleike/MITK | 83b0c35625dfaed99147f357dbd798b1dc19815b | [
"BSD-3-Clause"
] | 1 | 2020-12-09T06:33:13.000Z | 2020-12-09T06:33:13.000Z | Modules/QtWidgets/src/QmitkMimeTypes.cpp | maleike/MITK | 83b0c35625dfaed99147f357dbd798b1dc19815b | [
"BSD-3-Clause"
] | null | null | null | Modules/QtWidgets/src/QmitkMimeTypes.cpp | maleike/MITK | 83b0c35625dfaed99147f357dbd798b1dc19815b | [
"BSD-3-Clause"
] | 1 | 2020-03-18T02:39:55.000Z | 2020-03-18T02:39:55.000Z | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkMimeTypes.h"
const QString QmitkMimeTypes::DataNodePtrs = "application/x-qmitk-datanode-ptrs";
const QString QmitkMimeTypes::DataStorageTreeItemPtrs = "application/x-qmitk-datastorage-treeitem-ptrs";
#include <iostream>
QList<mitk::DataNode *> QmitkMimeTypes::ToDataNodePtrList(const QByteArray &ba)
{
QDataStream ds(ba);
QList<mitk::DataNode*> result;
while(!ds.atEnd())
{
quintptr dataNodePtr;
ds >> dataNodePtr;
result.push_back(reinterpret_cast<mitk::DataNode*>(dataNodePtr));
}
return result;
}
QList<mitk::DataNode *> QmitkMimeTypes::ToDataNodePtrList(const QMimeData *mimeData)
{
if (mimeData == nullptr || !mimeData->hasFormat(QmitkMimeTypes::DataNodePtrs))
{
return QList<mitk::DataNode*>();
}
return ToDataNodePtrList(mimeData->data(QmitkMimeTypes::DataNodePtrs));
}
| 29.6 | 104 | 0.683934 | maleike |
e141a2b056181f2b295d2f5e54db5529aa7010a6 | 7,595 | cpp | C++ | fboss/agent/hw/bcm/BcmBstStatsMgr.cpp | nathanawmk/fboss | 9f36dbaaae47202f9131598560c65715334a9a83 | [
"BSD-3-Clause"
] | 834 | 2015-03-10T18:12:28.000Z | 2022-03-31T20:16:17.000Z | fboss/agent/hw/bcm/BcmBstStatsMgr.cpp | nathanawmk/fboss | 9f36dbaaae47202f9131598560c65715334a9a83 | [
"BSD-3-Clause"
] | 82 | 2015-04-07T08:48:29.000Z | 2022-03-11T21:56:58.000Z | fboss/agent/hw/bcm/BcmBstStatsMgr.cpp | nathanawmk/fboss | 9f36dbaaae47202f9131598560c65715334a9a83 | [
"BSD-3-Clause"
] | 296 | 2015-03-11T03:45:37.000Z | 2022-03-14T22:54:22.000Z | /*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <folly/logging/xlog.h>
#include "fboss/agent/hw/bcm/BcmBstStatsMgr.h"
#include "fboss/agent/hw/bcm/BcmControlPlane.h"
#include "fboss/agent/hw/bcm/BcmCosManager.h"
#include "fboss/agent/hw/bcm/BcmError.h"
#include "fboss/agent/hw/bcm/BcmPlatform.h"
#include "fboss/agent/hw/bcm/BcmPortTable.h"
#include "fboss/agent/hw/switch_asics/HwAsic.h"
extern "C" {
#include <bcm/field.h>
}
namespace facebook::fboss {
bool BcmBstStatsMgr::startBufferStatCollection() {
if (!isBufferStatCollectionEnabled()) {
hw_->getCosMgr()->enableBst();
bufferStatsEnabled_ = true;
}
return bufferStatsEnabled_;
}
bool BcmBstStatsMgr::stopBufferStatCollection() {
if (isBufferStatCollectionEnabled()) {
hw_->getCosMgr()->disableBst();
bufferStatsEnabled_ = false;
}
return !bufferStatsEnabled_;
}
void BcmBstStatsMgr::syncStats() const {
auto rv = bcm_cosq_bst_stat_sync(
hw_->getUnit(), (bcm_bst_stat_id_t)bcmBstStatIdUcast);
bcmCheckError(rv, "Failed to sync bcmBstStatIdUcast stat");
if (hw_->getPlatform()->getAsic()->isSupported(HwAsic::Feature::PFC)) {
// All the below are PG related and available on platforms supporting PFC
rv = bcm_cosq_bst_stat_sync(
hw_->getUnit(), (bcm_bst_stat_id_t)bcmBstStatIdPriGroupHeadroom);
bcmCheckError(rv, "Failed to sync bcmBstStatIdPriGroupHeadroom stat");
rv = bcm_cosq_bst_stat_sync(
hw_->getUnit(), (bcm_bst_stat_id_t)bcmBstStatIdPriGroupShared);
bcmCheckError(rv, "Failed to sync bcmBstStatIdPriGroupShared stat");
rv = bcm_cosq_bst_stat_sync(
hw_->getUnit(), (bcm_bst_stat_id_t)bcmBstStatIdHeadroomPool);
bcmCheckError(rv, "Failed to sync bcmBstStatIdHeadroomPool stat");
rv = bcm_cosq_bst_stat_sync(
hw_->getUnit(), (bcm_bst_stat_id_t)bcmBstStatIdIngPool);
bcmCheckError(rv, "Failed to sync bcmBstStatIdIngPool stat");
}
}
void BcmBstStatsMgr::getAndPublishDeviceWatermark() {
auto peakUsage = hw_->getCosMgr()->deviceStatGet(bcmBstStatIdDevice);
auto peakBytes = peakUsage * hw_->getMMUCellBytes();
if (peakBytes > hw_->getMMUBufferBytes()) {
// First value read immediately after enabling BST, gives
// a abnormally high usage value (over 1B bytes), which is
// obviously bogus. Warn, but skip writing that value.
XLOG(WARNING)
<< " Got a bogus switch MMU buffer utilization value, peak cells: "
<< peakUsage << " peak bytes: " << peakBytes << " skipping write";
return;
}
deviceWatermarkBytes_.store(peakBytes);
publishDeviceWatermark(peakBytes);
if (isFineGrainedBufferStatLoggingEnabled()) {
bufferStatsLogger_->logDeviceBufferStat(
peakBytes, hw_->getMMUBufferBytes());
}
}
void BcmBstStatsMgr::getAndPublishGlobalWatermarks(
const std::map<int, bcm_port_t>& itmToPortMap) const {
auto cosMgr = hw_->getCosMgr();
for (auto it = itmToPortMap.begin(); it != itmToPortMap.end(); it++) {
int itm = it->first;
bcm_port_t bcmPortId = it->second;
uint64_t maxGlobalHeadroomBytes =
cosMgr->statGet(PortID(bcmPortId), -1, bcmBstStatIdHeadroomPool) *
hw_->getMMUCellBytes();
uint64_t maxGlobalSharedBytes =
cosMgr->statGet(PortID(bcmPortId), -1, bcmBstStatIdIngPool) *
hw_->getMMUCellBytes();
publishGlobalWatermarks(itm, maxGlobalHeadroomBytes, maxGlobalSharedBytes);
}
}
void BcmBstStatsMgr::createItmToPortMap(
std::map<int, bcm_port_t>& itmToPortMap) const {
if (itmToPortMap.size() == 0) {
/*
* ITM to port map not available, need to populate it first!
* Global headroom/shared buffer stats are per ITM, but as
* the counters are to be read per port, we need to keep track
* of one port per ITM for which stats can be read. This mapping
* is static and doesnt change.
*/
for (const auto& entry : *hw_->getPortTable()) {
BcmPort* bcmPort = entry.second;
int itm = hw_->getPlatform()->getPortItm(bcmPort);
if (itmToPortMap.find(itm) == itmToPortMap.end()) {
itmToPortMap[itm] = bcmPort->getBcmPortId();
XLOG(DBG2) << "ITM" << itm << " mapped to bcmport "
<< itmToPortMap[itm];
}
}
}
}
void BcmBstStatsMgr::updateStats() {
syncStats();
// Track if PG is enabled on any port in the system
bool pgEnabled = false;
auto qosSupported =
hw_->getPlatform()->getAsic()->isSupported(HwAsic::Feature::L3_QOS);
for (const auto& entry : *hw_->getPortTable()) {
BcmPort* bcmPort = entry.second;
auto curPortStatsOptional = bcmPort->getPortStats();
if (!curPortStatsOptional) {
// ignore ports with no saved stats
continue;
}
auto cosMgr = hw_->getCosMgr();
std::map<int16_t, int64_t> queueId2WatermarkBytes;
auto maxQueueId = qosSupported
? bcmPort->getQueueManager()->getNumQueues(cfg::StreamType::UNICAST) - 1
: 0;
for (int queue = 0; queue <= maxQueueId; queue++) {
auto peakBytes = 0;
if (bcmPort->isUp()) {
auto peakCells = cosMgr->statGet(
PortID(bcmPort->getBcmPortId()), queue, bcmBstStatIdUcast);
peakBytes = peakCells * hw_->getMMUCellBytes();
}
queueId2WatermarkBytes[queue] = peakBytes;
publishQueueuWatermark(bcmPort->getPortName(), queue, peakBytes);
if (isFineGrainedBufferStatLoggingEnabled()) {
getBufferStatsLogger()->logPortBufferStat(
bcmPort->getPortName(),
BufferStatsLogger::Direction::Egress,
queue,
peakBytes,
curPortStatsOptional->queueOutDiscardBytes__ref()->at(queue),
bcmPort->getPlatformPort()->getEgressXPEs());
}
}
bcmPort->setQueueWaterMarks(std::move(queueId2WatermarkBytes));
// Get PG MAX headroom/shared stats
if (bcmPort->isPortPgConfigured()) {
bcm_port_t bcmPortId = bcmPort->getBcmPortId();
uint64_t maxHeadroomBytes =
cosMgr->statGet(PortID(bcmPortId), -1, bcmBstStatIdPriGroupHeadroom) *
hw_->getMMUCellBytes();
uint64_t maxSharedBytes =
cosMgr->statGet(PortID(bcmPortId), -1, bcmBstStatIdPriGroupShared) *
hw_->getMMUCellBytes();
publishPgWatermarks(
bcmPort->getPortName(), maxHeadroomBytes, maxSharedBytes);
pgEnabled = true;
}
}
if (pgEnabled) {
/*
* Ingress Traffic Manager(ITM) is part of the MMU. The ports in the
* system are split between multiple ITMs and the ITMs has buffers
* shared by all port which are part of the same ITM. The global
* ingress buffer statistics are tracked per ITM and hence needs
* to be fetched only once per ITM. This would mean we first find
* the port->ITM mapping and then read the statistics once per ITM.
*/
static std::map<int, bcm_port_t> itmToPortMap;
createItmToPortMap(itmToPortMap);
getAndPublishGlobalWatermarks(itmToPortMap);
}
// Get watermark stats for CPU queues
if (qosSupported) {
auto controlPlane = hw_->getControlPlane();
HwPortStats cpuStats;
controlPlane->updateQueueWatermarks(&cpuStats);
for (const auto& [cosQ, stats] : *cpuStats.queueWatermarkBytes__ref()) {
publishCpuQueueWatermark(cosQ, stats);
}
}
getAndPublishDeviceWatermark();
}
} // namespace facebook::fboss
| 35.825472 | 80 | 0.687689 | nathanawmk |
e1450facedfc9d2dfc4fe5c3ba4bb4729d0aac79 | 271 | cpp | C++ | GameEngine/src/GE/Events/Mouse/MouseReleasedEvent.cpp | MikeAllport/CE301-Final-Year-Project | da2f3a3d52b955b2f8deca43849273a26b49dda3 | [
"Apache-2.0"
] | null | null | null | GameEngine/src/GE/Events/Mouse/MouseReleasedEvent.cpp | MikeAllport/CE301-Final-Year-Project | da2f3a3d52b955b2f8deca43849273a26b49dda3 | [
"Apache-2.0"
] | null | null | null | GameEngine/src/GE/Events/Mouse/MouseReleasedEvent.cpp | MikeAllport/CE301-Final-Year-Project | da2f3a3d52b955b2f8deca43849273a26b49dda3 | [
"Apache-2.0"
] | null | null | null | #include "gepch.h"
#include "MouseReleasedEvent.h"
namespace GE
{
MouseReleasedEvent::MouseReleasedEvent(int code) :
MouseEvent(code)
{}
std::string MouseReleasedEvent::toString() const
{
return "MouseClickedReleased: button= " + toStringBut(keyPressed());
}
} | 19.357143 | 70 | 0.738007 | MikeAllport |
e145993e59749b8f25846655203facf53034906d | 9,424 | cc | C++ | src/object/format-info.cc | jcbaillie/urbi | fb17359b2838cdf8d3c0858abb141e167a9d4bdb | [
"BSD-3-Clause"
] | 16 | 2016-05-10T05:50:58.000Z | 2021-10-05T22:16:13.000Z | src/object/format-info.cc | jcbaillie/urbi | fb17359b2838cdf8d3c0858abb141e167a9d4bdb | [
"BSD-3-Clause"
] | 7 | 2016-09-05T10:08:33.000Z | 2019-02-13T10:51:07.000Z | src/object/format-info.cc | jcbaillie/urbi | fb17359b2838cdf8d3c0858abb141e167a9d4bdb | [
"BSD-3-Clause"
] | 15 | 2015-01-28T20:27:02.000Z | 2021-09-28T19:26:08.000Z | /*
* Copyright (C) 2009-2012, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <cctype>
#include <libport/lexical-cast.hh>
#include <object/format-info.hh>
#include <urbi/object/global.hh>
#include <urbi/object/symbols.hh>
namespace urbi
{
namespace object
{
FormatInfo::FormatInfo()
: alignment_(Align::RIGHT)
, alt_(false)
, consistent_(true)
, group_("")
, pad_(" ")
, pattern_("%s")
, precision_(6)
, prefix_("")
, rank_(0)
, spec_("s")
, uppercase_(Case::UNDEFINED)
, width_(0)
{
proto_add(proto ? rObject(proto) : Object::proto);
}
FormatInfo::FormatInfo(rFormatInfo model)
: alignment_(model->alignment_)
, alt_(model->alt_)
, consistent_(model->consistent_)
, group_(model->group_)
, pad_(model->pad_)
, pattern_(model->pattern_)
, precision_(model->precision_)
, prefix_(model->prefix_)
, rank_(model->rank_)
, spec_(model->spec_)
, uppercase_(model->uppercase_)
, width_(model->width_)
{
proto_add(model);
}
URBI_CXX_OBJECT_INIT(FormatInfo)
: alignment_(Align::RIGHT)
, alt_(false)
, consistent_(true)
, group_("")
, pad_(" ")
, pattern_("%s")
, precision_(6)
, prefix_("")
, rank_(0)
, spec_("s")
, uppercase_(Case::UNDEFINED)
, width_(0)
{
BIND(init);
BIND(asString, as_string);
BINDG(pattern, pattern_get);
# define DECLARE(Name) \
bind(#Name, &FormatInfo::Name ##_get, &FormatInfo::Name ##_set);
DECLARE(alignment);
DECLARE(alt);
DECLARE(group);
DECLARE(pad);
DECLARE(precision);
DECLARE(prefix);
DECLARE(rank);
DECLARE(spec);
DECLARE(uppercase);
DECLARE(width);
# undef DECLARE
}
void
FormatInfo::init(const std::string& pattern)
{
init_(pattern, true);
}
void
FormatInfo::init_(const std::string& pattern, bool check_end)
{
if (pattern.empty())
RAISE("format: empty pattern");
if (pattern[0] != '%')
FRAISE("format: pattern does not begin with %%: %s", pattern);
if (pattern.size() == 1)
RAISE("format: trailing `%'");
const char* digits = "0123456789";
// Cursor inside pattern.
size_t cursor = 1;
// Whether between `|'.
bool piped = pattern[cursor] == '|';
if (piped)
++cursor;
// Whether a simple positional request: %<rank>%, in which case,
// no flags admitted.
bool percented = false;
// Whether there is a positional argument: <NUM>$, or if
// it's a %<rank>% (but then, no pipe accepted).
{
// First non digit.
size_t sep = pattern.find_first_not_of(digits, cursor);
// If there are digits, and then a $, then we have a
// positional argument.
if (sep != cursor
&& sep < pattern.size()
&& (pattern[sep] == '$'
|| (!piped && pattern[sep] == '%')))
{
percented = pattern[sep] == '%';
rank_ = lexical_cast<size_t>(pattern.substr(cursor, sep - cursor));
if (!rank_)
FRAISE("format: invalid positional argument: %s",
pattern.substr(cursor, sep - cursor));
cursor = sep + 1;
}
else
rank_ = 0;
}
// Parsing flags.
if (!percented)
{
std::string flags("-=+#0 '");
std::string excludes;
char current;
for (;
cursor < pattern.size()
&& libport::has(flags, current = pattern[cursor]);
++cursor)
if (libport::has(excludes, current))
FRAISE("format: '%s' conflicts with one of these flags: \"%s\"",
current, excludes);
else
switch (current)
{
case '-': alignment_ = Align::LEFT; excludes += "-="; break;
case '=': alignment_ = Align::CENTER; excludes += "-="; break;
case '+': prefix_ = "+"; excludes += " +"; break;
case ' ': prefix_ = " "; excludes += " +"; break;
case '0': pad_ = "0"; break;
case '#': alt_ = true; break;
case '\'': group_ = " "; break;
};
}
// Parsing width.
if (!percented)
if (size_t w = pattern.find_first_not_of(digits, cursor) - cursor)
{
width_ = lexical_cast<size_t>(pattern.substr(cursor, w));
cursor += w;
}
// Parsing precision.
if (!percented
&& cursor < pattern.size() && pattern[cursor] == '.')
{
++cursor;
if (size_t w = pattern.find_first_not_of(digits, cursor) - cursor)
{
precision_ = lexical_cast<size_t>(pattern.substr(cursor, w));
cursor += w;
}
else
FRAISE("format: invalid width after `.': %s", pattern[cursor]);
}
// Parsing spec. Optional if piped.
if (!percented
&& cursor < pattern.size()
&& (!piped || pattern[cursor] != '|'))
{
spec_ = tolower(pattern[cursor]);
if (!strchr("sdbxoef", spec_[0]))
FRAISE("format: invalid conversion type character: %s", spec_);
else if (spec_ != "s")
uppercase_ = (islower(pattern[cursor])) ? Case::LOWER : Case::UPPER;
++cursor;
}
if (piped)
{
if (cursor < pattern.size())
++cursor;
else {
RAISE("format: missing closing '|'");
}
}
if (check_end && cursor < pattern.size())
FRAISE("format: spurious characters after format: %s",
pattern.substr(cursor));
pattern_ = pattern.substr(0, cursor);
}
std::string
FormatInfo::as_string() const
{
return pattern_get();
}
const std::string&
FormatInfo::pattern_get() const
{
if (!consistent_)
{
pattern_ = compute_pattern();
consistent_ = true;
}
return pattern_;
}
std::string
FormatInfo::compute_pattern(bool for_float) const
{
// To format floats, we rely on Boost.Format.
size_t rank = rank_;
char spec = spec_[0];
if (for_float)
{
rank = 0;
if (spec == 's' || spec == 'd') spec = 'g';
if (spec == 'D') spec = 'G';
}
return std::string("%|")
+ (rank == 0 ? "" : (string_cast(rank) + "$"))
+ ((alignment_ == Align::RIGHT) ? ""
: (alignment_ == Align::LEFT) ? "-"
: "=")
+ (alt_ ? "#" : "")
+ (group_ == "" ? "" : "'")
+ (pad_ == " " ? "" : "0")
+ prefix_
+ (width_ == 0 ? "" : string_cast(width_))
+ (precision_ == 6 ? "" : "." + string_cast(precision_))
+ (uppercase_ == Case::UPPER ? char(toupper(spec)) : spec)
+ '|';
}
void
FormatInfo::alignment_set(Align::position val)
{
alignment_ = val;
consistent_ = false;
}
void
FormatInfo::group_set(std::string v)
{
if (!v.empty() && v != " ")
FRAISE("expected \" \" or \"\": \"%s\"", v);
group_ = v;
consistent_ = false;
}
void
FormatInfo::pad_set(std::string v)
{
if (v != " " && v != "0")
FRAISE("expected \" \" or \"0\": \"%s\"", v);
pad_ = v;
consistent_ = false;
}
void
FormatInfo::prefix_set(std::string v)
{
if (v != " " && v != "+" && v != "")
FRAISE("expected \"\", \" \" or \"+\": \"%s\"", v);
prefix_ = v;
consistent_ = false;
}
void
FormatInfo::spec_set(std::string val_)
{
if (val_.size() != 1)
RAISE("expected one-character long string: " + val_);
if (!strchr("sdbxoefEDX", val_[0]))
RAISE("expected one character in \"sdbxoefEDX\": \"" + val_ + "\"");
spec_ = val_;
std::transform(spec_.begin(), spec_.end(), spec_.begin(), ::tolower);
uppercase_ = (spec_ == "s" ? Case::UNDEFINED
: islower(val_[0]) ? Case::LOWER
: Case::UPPER);
consistent_ = false;
}
void
FormatInfo::uppercase_set(int v)
{
switch (v)
{
#define CASE(In, Out, Spec) \
case In: uppercase_ = Case::Out; spec_ = Spec; break
CASE(-1, LOWER, "d");
CASE( 0, UNDEFINED, "s");
CASE( 1, UPPER, "D");
#undef CASE
default:
FRAISE("expected integer -1, 0 or 1: %s", v);
}
consistent_ = false;
}
void
FormatInfo::alt_set(bool v)
{
alt_ = v;
consistent_ = false;
}
void
FormatInfo::precision_set(size_t v)
{
precision_ = v;
consistent_ = false;
}
void
FormatInfo::rank_set(size_t v)
{
rank_ = v;
consistent_ = false;
}
void
FormatInfo::width_set(size_t v)
{
width_ = v;
consistent_ = false;
}
} // namespace object
}
| 26.033149 | 78 | 0.497878 | jcbaillie |
e1469b32e8c62fadac53e74a7b2300ede6a67de3 | 332 | cpp | C++ | higan/sfc/slot/sufamiturbo/sufamiturbo.cpp | mp-lee/higan | c38a771f2272c3ee10fcb99f031e982989c08c60 | [
"Intel",
"ISC"
] | 38 | 2018-04-05T05:00:05.000Z | 2022-02-06T00:02:02.000Z | higan/sfc/slot/sufamiturbo/sufamiturbo.cpp | mp-lee/higan | c38a771f2272c3ee10fcb99f031e982989c08c60 | [
"Intel",
"ISC"
] | 1 | 2018-04-29T19:45:14.000Z | 2018-04-29T19:45:14.000Z | higan/sfc/slot/sufamiturbo/sufamiturbo.cpp | libretro-mirrors/higan | 8617711ea2c201a33442266945dc7ed186e9d695 | [
"Intel",
"ISC"
] | 8 | 2018-04-16T22:37:46.000Z | 2021-02-10T07:37:03.000Z | #include <sfc/sfc.hpp>
namespace SuperFamicom {
#include "serialization.cpp"
SufamiTurboCartridge sufamiturboA;
SufamiTurboCartridge sufamiturboB;
auto SufamiTurboCartridge::unload() -> void {
rom.reset();
ram.reset();
}
auto SufamiTurboCartridge::power() -> void {
rom.writeProtect(true);
ram.writeProtect(false);
}
}
| 16.6 | 45 | 0.740964 | mp-lee |
e1481756e08e3a1d063417af62918508e7a6b072 | 4,528 | cpp | C++ | streambox/test/test-common.cpp | wzhao18/StreamBox | 134b7445feca76a44ec3b183a60a270c46e6c067 | [
"BSD-2-Clause"
] | 1 | 2022-03-22T00:01:40.000Z | 2022-03-22T00:01:40.000Z | streambox/test/test-common.cpp | wzhao18/StreamBox | 134b7445feca76a44ec3b183a60a270c46e6c067 | [
"BSD-2-Clause"
] | null | null | null | streambox/test/test-common.cpp | wzhao18/StreamBox | 134b7445feca76a44ec3b183a60a270c46e6c067 | [
"BSD-2-Clause"
] | null | null | null | #include <stdio.h>
#include "log.h"
#include "config.h"
void print_config()
{
printf("config:\n");
#ifdef USE_NUMA_TP
xzl_show_define(USE_NUMA_TP);
#else
xzl_show_undefine(USE_NUMA_TP);
#endif
#ifdef USE_TBB_DS
xzl_show_define(USE_TBB_DS)
#else
xzl_show_undefine(USE_TBB_DS)
#endif
#ifdef USE_FOLLY_VECTOR
xzl_show_define(USE_FOLLY_VECTOR)
#else
xzl_show_undefine(USE_FOLLY_VECTOR)
#endif
#ifdef USE_FOLLY_STRING
xzl_show_define(USE_FOLLY_STRING)
#else
xzl_show_undefine(USE_FOLLY_STRING)
#endif
#ifdef USE_FOLLY_HASHMAP
xzl_show_define(USE_FOLLY_HASHMAP)
#else
xzl_show_undefine(USE_FOLLY_HASHMAP)
#endif
#ifdef USE_CUCKOO_HASHMAP
xzl_show_define(USE_CUCKOO_HASHMAP)
#else
xzl_show_undefine(USE_CUCKOO_HASHMAP)
#endif
#ifdef USE_TBB_HASHMAP
xzl_show_define(USE_TBB_HASHMAP)
#else
xzl_show_undefine(USE_TBB_HASHMAP)
#endif
#ifdef USE_NUMA_ALLOC
xzl_show_define(USE_NUMA_ALLOC)
#else
xzl_show_undefine(USE_NUMA_ALLOC)
#endif
#ifdef INPUT_ALWAYS_ON_NODE0
xzl_show_define(INPUT_ALWAYS_ON_NODE0)
#else
xzl_show_undefine(INPUT_ALWAYS_ON_NODE0)
#endif
#ifdef MEASURE_LATENCY
xzl_show_define(MEASURE_LATENCY)
#else
xzl_show_undefine(MEASURE_LATENCY)
#endif
#ifdef CONFIG_SOURCE_THREADS
xzl_show_define(CONFIG_SOURCE_THREADS)
#else
// xzl_show_undefine(CONFIG_SOURCE_THREADS)
#error
#endif
#ifdef CONFIG_MIN_PERNODE_BUFFER_SIZE_MB
xzl_show_define(CONFIG_MIN_PERNODE_BUFFER_SIZE_MB)
#else
// xzl_show_undefine(CONFIG_MIN_PERNODE_BUFFER_SIZE_MB)
#error
#endif
#ifdef CONFIG_MIN_EPOCHS_PERNODE_BUFFER
xzl_show_define(CONFIG_MIN_EPOCHS_PERNODE_BUFFER)
#else
// xzl_show_undefine(X)
#error
#endif
#ifdef CONFIG_NETMON_HT_PARTITIONS
xzl_show_define(CONFIG_NETMON_HT_PARTITIONS)
#else
#error
#endif
#ifdef CONFIG_JOIN_HT_PARTITIONS
xzl_show_define(CONFIG_JOIN_HT_PARTITIONS)
#else
#error
#endif
/* warn about workarounds */
#ifdef WORKAROUND_JOIN_JDD
EE("warning: WORKAROUND_JOIN_JDD = 1. Sure? (any key to continue)\n");
getchar();
#endif
#ifdef WORKAROUND_WINKEYREDUCER_RECORDBUNDLE
EE("warning: WORKAROUND_WINKEYREDUCER_RECORDBUNDLE = 1. Sure? (any key to continue)\n");
getchar();
#endif
/* todo: add more here */
}
// Copyright Vladimir Prus 2002-2004.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
/* The simplest usage of the library.
*
* http://www.boost.org/doc/libs/1_61_0/libs/program_options/example/first.cpp
* http://www.boost.org/doc/libs/1_61_0/libs/program_options/example/options_description.cpp
*/
#undef _GLIBCXX_DEBUG /* does not get along with program options lib */
#include <iostream>
#include <boost/program_options.hpp>
using namespace std;
namespace po = boost::program_options;
#include <thread>
#include "test-common.h"
void parse_options(int ac, char *av[], pipeline_config* config)
{
po::variables_map vm;
xzl_assert(config);
try {
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("records", po::value<unsigned long>(), "records per wm interval")
("target_tput", po::value<unsigned long>(), "target throughput (krec/s)")
("record_size", po::value<unsigned long>(), "record (string_range) size (bytes)")
("cores", po::value<unsigned long>(), "# cores for worker threads")
("input_file", po::value<vector<string>>(), "input file path") /* must be vector */
;
po::store(po::parse_command_line(ac, av, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
exit(1);
}
if (vm.count("records")) {
config->records_per_interval = vm["records"].as<unsigned long>();
}
if (vm.count("target_tput")) {
config->target_tput = vm["target_tput"].as<unsigned long>() * 1000;
}
if (vm.count("record_size")) {
config->record_size = vm["record_size"].as<unsigned long>();
}
if (vm.count("cores")) {
config->cores = vm["cores"].as<unsigned long>();
} else { /* default value for # cores (save one for source) */
config->cores = std::thread::hardware_concurrency() - 1;
}
if (vm.count("input_file")) {
config->input_file = vm["input_file"].as<vector<string>>()[0];
}
}
catch(exception& e) {
cerr << "error: " << e.what() << "\n";
abort();
}
catch(...) {
cerr << "Exception of unknown type!\n";
abort();
}
}
| 23.706806 | 93 | 0.71091 | wzhao18 |
e1484866d83884575ad92e6132abc875b6471318 | 1,249 | hpp | C++ | Server Lib/Game Server/PANGYA_DB/cmd_add_dolfini_locker_item.hpp | CCasusensa/SuperSS-Dev | 6c6253b0a56bce5dad150c807a9bbf310e8ff61b | [
"MIT"
] | 23 | 2021-10-31T00:20:21.000Z | 2022-03-26T07:24:40.000Z | Server Lib/Game Server/PANGYA_DB/cmd_add_dolfini_locker_item.hpp | CCasusensa/SuperSS-Dev | 6c6253b0a56bce5dad150c807a9bbf310e8ff61b | [
"MIT"
] | 5 | 2021-10-31T18:44:51.000Z | 2022-03-25T18:04:26.000Z | Server Lib/Game Server/PANGYA_DB/cmd_add_dolfini_locker_item.hpp | CCasusensa/SuperSS-Dev | 6c6253b0a56bce5dad150c807a9bbf310e8ff61b | [
"MIT"
] | 18 | 2021-10-20T02:31:56.000Z | 2022-02-01T11:44:36.000Z | // Arquivo cmd_add_dolfini_locker_item.hpp
// Criado em 02/06/2018 as 23:20 por Acrisio
// Defini��o da classe CmdAddDolfiniLockerItem
#pragma once
#ifndef _STDA_CMD_ADD_DOLFINI_LOCKER_ITEM_HPP
#define _STDA_CMD_ADD_DOLFINI_LOCKER_ITEM_HPP
#include "../../Projeto IOCP/PANGYA_DB/pangya_db.h"
#include "../TYPE/pangya_game_st.h"
namespace stdA {
class CmdAddDolfiniLockerItem : public pangya_db {
public:
explicit CmdAddDolfiniLockerItem(bool _waiter = false);
CmdAddDolfiniLockerItem(uint32_t _uid, DolfiniLockerItem& _dli, bool _waiter = false);
virtual ~CmdAddDolfiniLockerItem();
uint32_t getUID();
void setUID(uint32_t _uid);
DolfiniLockerItem& getInfo();
void setInfo(DolfiniLockerItem& _dli);
protected:
void lineResult(result_set::ctx_res* _result, uint32_t _index_result) override;
response* prepareConsulta(database& _db) override;
// get Class name
virtual std::string _getName() override { return "CmdAddDolfiniLockerItem"; };
virtual std::wstring _wgetName() override { return L"CmdAddDolfiniLockerItem"; };
private:
uint32_t m_uid;
DolfiniLockerItem m_dli;
const char* m_szConsulta = "pangya.ProcAddItemDolfiniLocker";
};
}
#endif // !_STDA_CMD_ADD_DOLFINI_LOCKER_ITEM_HPP
| 29.738095 | 89 | 0.767814 | CCasusensa |
e1495da8c7f366f6d71aef71335b52b982ef4647 | 5,704 | hpp | C++ | Lodestar/blocks/std/SwitchBlock.hpp | helkebir/Lodestar | 6b325d3e7a388676ed31d44eac1146630ee4bb2c | [
"BSD-3-Clause"
] | 4 | 2020-06-05T14:08:23.000Z | 2021-06-26T22:15:31.000Z | Lodestar/blocks/std/SwitchBlock.hpp | helkebir/Lodestar | 6b325d3e7a388676ed31d44eac1146630ee4bb2c | [
"BSD-3-Clause"
] | 2 | 2021-06-25T15:14:01.000Z | 2021-07-01T17:43:20.000Z | Lodestar/blocks/std/SwitchBlock.hpp | helkebir/Lodestar | 6b325d3e7a388676ed31d44eac1146630ee4bb2c | [
"BSD-3-Clause"
] | 1 | 2021-06-16T03:15:23.000Z | 2021-06-16T03:15:23.000Z | //
// Created by Hamza El-Kebir on 12/23/21.
//
#ifndef LODESTAR_SWITCHBLOCK_HPP
#define LODESTAR_SWITCHBLOCK_HPP
#include "Lodestar/blocks/Block.hpp"
namespace ls {
namespace blocks {
namespace std {
enum class SwitchBlockParameter {
Parametric,
AdditionalInput
};
template<typename TType,
SwitchBlockParameter TPar = SwitchBlockParameter::Parametric>
class SwitchBlock {
static_assert(::std::is_same<TType, TType>::value,
"SwitchBlock not defined for this type.");
};
template<typename TType>
class SwitchBlock<TType, SwitchBlockParameter::Parametric> :
public Block<
::std::tuple<TType, TType>,
::std::tuple<TType>,
::std::tuple<bool>
> {
public:
using Base =
Block<
::std::tuple<TType, TType>,
::std::tuple<TType>,
::std::tuple<bool>
>;
using type = SwitchBlock<TType, SwitchBlockParameter::Parametric>;
SwitchBlock()
{
state(false);
bindEquation();
}
SwitchBlock(const bool switchState)
{
state(switchState);
bindEquation();
}
bool &state(bool setting)
{
this->template p<0>() = setting;
return this->template p<0>();
}
bool state() const
{
return this->template p<0>();
}
bool &state()
{
return this->template p<0>();
}
void toggle()
{
state(!state());
}
protected:
void bindEquation()
{
this->equation = ::std::bind(
&type::triggerFunction,
this,
::std::placeholders::_1
);
}
void triggerFunction(Base &b)
{
if (state())
this->template o<0>() = this->template i<1>();
else
this->template o<0>() = this->template i<0>();
}
};
template<typename TType>
class SwitchBlock<TType, SwitchBlockParameter::AdditionalInput> :
public Block<
::std::tuple<TType, TType, bool>,
::std::tuple<TType>,
BlockProto::empty
> {
public:
using Base =
Block<
::std::tuple<TType, TType, bool>,
::std::tuple<TType>,
BlockProto::empty
>;
using type = SwitchBlock<TType, SwitchBlockParameter::AdditionalInput>;
SwitchBlock()
{
state(false);
bindEquation();
}
SwitchBlock(const bool switchState)
{
state(switchState);
bindEquation();
}
Signal<bool> &state(bool setting)
{
this->template i<2>() = setting;
return this->template i<2>();
}
Signal<bool> &state(const Signal<bool> &setting)
{
this->template i<2>() = setting;
return this->template i<2>();
}
const Signal<bool> &state() const
{
return this->template i<2>();
}
Signal<bool> &state()
{
return this->template i<2>();
}
void toggle()
{
state(!state().object);
}
protected:
void bindEquation()
{
this->equation = ::std::bind(
&type::triggerFunction,
this,
::std::placeholders::_1
);
}
void triggerFunction(Base &b)
{
if (state().object)
this->template o<0>() = this->template i<1>();
else
this->template o<0>() = this->template i<0>();
}
};
}
template<typename TType, std::SwitchBlockParameter TPar>
class BlockTraits<std::SwitchBlock<TType, TPar>> {
public:
static constexpr const BlockType blockType = BlockType::SwitchBlock;
static constexpr const bool directFeedthrough = true;
using type = std::SwitchBlock<TType, TPar>;
using Base = typename type::Base;
static const constexpr int kIns = type::Base::kIns;
static const constexpr int kOuts = type::Base::kOuts;
static const constexpr int kPars = type::Base::kPars;
};
}
}
#endif //LODESTAR_SWITCHBLOCK_HPP
| 30.179894 | 87 | 0.389376 | helkebir |
e14bc6fe5eda807847d4ff836f4b2fe96fa6c755 | 2,098 | cpp | C++ | VLCPlayer.cpp | gigagenie/sample-client-linux-websocket | 1c0003f543e75441030dfa0e5707820dd7c7ec3f | [
"Apache-2.0"
] | null | null | null | VLCPlayer.cpp | gigagenie/sample-client-linux-websocket | 1c0003f543e75441030dfa0e5707820dd7c7ec3f | [
"Apache-2.0"
] | null | null | null | VLCPlayer.cpp | gigagenie/sample-client-linux-websocket | 1c0003f543e75441030dfa0e5707820dd7c7ec3f | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020 KT AI Lab.
*
* 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 "VLCPlayer.h"
void VLCPlayer::init()
{
/* Load the VLC engine */
inst = libvlc_new (0, NULL);
}
void VLCPlayer::finalize()
{
if(mp!=nullptr)
{
stop();
}
libvlc_release (inst);
}
VLCPlayer::VLCPlayer()
{
init();
}
VLCPlayer::~VLCPlayer()
{
finalize();
}
int VLCPlayer::stop()
{
if(mp==nullptr) return -1;
/* Stop playing */
libvlc_media_player_stop (mp);
/* Free the media_player */
libvlc_media_player_release (mp);
mp=nullptr;
/* No need to keep the media now */
libvlc_media_release (m);
m=nullptr;
play_end_time=std::chrono::steady_clock::now();
return 0;
}
int VLCPlayer::play(const std::string& play_url)
{
/* Create a new item */
m = libvlc_media_new_location (inst,play_url.c_str());
/* Create a media player playing environement */
mp = libvlc_media_player_new_from_media (m);
/* play the media_player */
libvlc_media_player_play (mp);
play_start_time=std::chrono::steady_clock::now();
return 0;
}
int VLCPlayer::pause()
{
if(mp==nullptr) return -1;
libvlc_media_player_set_pause(mp,1);
return 0;
}
int VLCPlayer::resume()
{
if(mp==nullptr) return -1;
libvlc_media_player_set_pause(mp,0);
return 0;
}
long VLCPlayer::getDuration()
{
//if(m==nullptr) return -1;
//return libvlc_media_get_duration (m);
return std::chrono::duration_cast<std::chrono::seconds>(play_end_time-play_start_time).count();
}
| 20.368932 | 99 | 0.662536 | gigagenie |
e14f78db2d2505de8d1a834e9550e18686244508 | 684 | cc | C++ | src/base/b3BaseInclude.cc | stmork/blz3 | 275e24681cb1493319cd0a50e691feb86182f6f0 | [
"BSD-3-Clause"
] | null | null | null | src/base/b3BaseInclude.cc | stmork/blz3 | 275e24681cb1493319cd0a50e691feb86182f6f0 | [
"BSD-3-Clause"
] | null | null | null | src/base/b3BaseInclude.cc | stmork/blz3 | 275e24681cb1493319cd0a50e691feb86182f6f0 | [
"BSD-3-Clause"
] | 1 | 2022-01-07T15:58:38.000Z | 2022-01-07T15:58:38.000Z | /*
**
** $Filename: b3BaseInclude.cc $
** $Release: Dortmund 2006 $
** $Revision$
** $Date$
** $Author$
** $Developer: Steffen A. Mork $
**
** Blizzard III - Precompiled header file for base package
**
** (C) Copyright 2006 Steffen A. Mork
** All Rights Reserved
**
**
**
*/
/*************************************************************************
** **
** Blizzard III includes **
** **
*************************************************************************/
#include "b3BaseInclude.h"
| 26.307692 | 74 | 0.307018 | stmork |
e14fc29fc5053933822bf210b520d3830303d77c | 8,476 | hpp | C++ | include/hermite_multidimensional.hpp | maliasadi/thewalrus | 719cdcc4791579d3f6d45fcc8fb41372989dec85 | [
"Apache-2.0"
] | null | null | null | include/hermite_multidimensional.hpp | maliasadi/thewalrus | 719cdcc4791579d3f6d45fcc8fb41372989dec85 | [
"Apache-2.0"
] | null | null | null | include/hermite_multidimensional.hpp | maliasadi/thewalrus | 719cdcc4791579d3f6d45fcc8fb41372989dec85 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Xanadu Quantum Technologies Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file
* Contains functions for calculating the multidimensional
* Hermite polynomials, used for computation of batched hafnians.
*/
#pragma once
#include <stdafx.h>
#include <assert.h>
#include <algorithm>
#include <cstring>
typedef unsigned long long int ullint;
/**
* Returns the index of the one dimensional flattened vector corresponding to the multidimensional tensor
*
* @param pos
* @param cutoff
*
* @return index on flattened vector
*/
ullint vec2index(std::vector<int> &pos, int cutoff) {
int dim = pos.size();
ullint nextCoordinate = 0;
nextCoordinate = pos[0]-1;
for(int ii = 0; ii < dim-1; ii++) {
nextCoordinate = nextCoordinate*cutoff + (pos[ii+1]-1);
}
return nextCoordinate;
}
/**
* Updates the iterators needed for the calculation of the Hermite multidimensional functions
*
* @param nextPos a vector of integers
* @param jumpFrom a vector of integers
* @param jump integer specifying whether to jump to the next index
* @param cutoff integer specifying the cuotff
* @dim dimension of the R matrix
*
* @k index necessary for knowing which elements are needed from the input vector y and matrix R
*/
int update_iterator(std::vector<int> &nextPos, std::vector<int> &jumpFrom, int &jump, const int &cutoff, const int &dim) {
if (jump > 0) {
jumpFrom[jump] += 1;
jump = 0;
}
for (int ii = 0; ii < dim; ii++) {
if ( nextPos[ii] + 1 > cutoff) {
nextPos[ii] = 1;
jumpFrom[ii] = 1;
jump = ii+1;
}
else {
jumpFrom[ii] = nextPos[ii];
nextPos[ii] = nextPos[ii] + 1;
break;
}
}
int k=0;
for(; k < dim; k++) {
if(nextPos[k] != jumpFrom[k]) break;
}
return k;
}
namespace libwalrus {
/**
* Returns the multidimensional Hermite polynomials \f$H_k^{(R)}(y)\f$.
*
* This implementation is based on the MATLAB code available at
* https://github.com/clementsw/gaussian-optics
*
* @param R a flattened vector of size \f$n^2\f$, representing a
* \f$n\times n\f$ symmetric matrix.
* @param y a flattened vector of size \f$n\f$.
* @param cutoff highest number of photons to be resolved.
*
*/
template <typename T>
inline T* hermite_multidimensional_cpp(const std::vector<T> &R, const std::vector<T> &y, const int &cutoff) {
int dim = std::sqrt(static_cast<double>(R.size()));
ullint Hdim = pow(cutoff, dim);
T *H;
H = (T*) malloc(sizeof(T)*Hdim);
memset(&H[0],0,sizeof(T)*Hdim);
H[0] = 1;
std::vector<int> nextPos(dim, 1);
std::vector<int> jumpFrom(dim, 1);
int jump = 0;
int k;
ullint nextCoordinate, fromCoordinate;
for (ullint jj = 0; jj < Hdim-1; jj++) {
k = update_iterator(nextPos, jumpFrom, jump, cutoff, dim);
nextCoordinate = vec2index(nextPos, cutoff);
fromCoordinate = vec2index(jumpFrom, cutoff);
H[nextCoordinate] = H[fromCoordinate] * y[k];
std::vector<int> tmpjump(dim, 0);
for (int ii = 0; ii < dim; ii++) {
if (jumpFrom[ii] > 1) {
std::vector<int> prevJump(dim, 0);
prevJump[ii] = 1;
std::transform(jumpFrom.begin(), jumpFrom.end(), prevJump.begin(), tmpjump.begin(), std::minus<int>());
ullint prevCoordinate = vec2index(tmpjump, cutoff);
H[nextCoordinate] = H[nextCoordinate] - (static_cast<T>(jumpFrom[ii]-1))*(R[dim*k+ii])*H[prevCoordinate];
}
}
}
return H;
}
/**
* Returns the normalized multidimensional Hermite polynomials \f$\tilde{H}_k^{(R)}(y)\f$.
*
* This implementation is based on the MATLAB code available at
* https://github.com/clementsw/gaussian-optics
*
* @param R a flattened vector of size \f$n^2\f$, representing a
* \f$n\times n\f$ symmetric matrix.
* @param y a flattened vector of size \f$n\f$.
* @param cutoff highest number of photons to be resolved.
*
*/
template <typename T>
inline T* renorm_hermite_multidimensional_cpp(const std::vector<T> &R, const std::vector<T> &y, const int &cutoff) {
int dim = std::sqrt(static_cast<double>(R.size()));
ullint Hdim = pow(cutoff, dim);
T *H;
H = (T*) malloc(sizeof(T)*Hdim);
memset(&H[0],0,sizeof(T)*Hdim);
H[0] = 1;
std::vector<double> intsqrt(cutoff+1, 0);
for (int ii = 0; ii<=cutoff; ii++) {
intsqrt[ii] = std::sqrt((static_cast<double>(ii)));
}
std::vector<int> nextPos(dim, 1);
std::vector<int> jumpFrom(dim, 1);
int jump = 0;
int k;
ullint nextCoordinate, fromCoordinate;
for (ullint jj = 0; jj < Hdim-1; jj++) {
k = update_iterator(nextPos, jumpFrom, jump, cutoff, dim);
nextCoordinate = vec2index(nextPos, cutoff);
fromCoordinate = vec2index(jumpFrom, cutoff);
H[nextCoordinate] = H[fromCoordinate] * y[k];
std::vector<int> tmpjump(dim, 0);
for (int ii = 0; ii < dim; ii++) {
if (jumpFrom[ii] > 1) {
std::vector<int> prevJump(dim, 0);
prevJump[ii] = 1;
std::transform(jumpFrom.begin(), jumpFrom.end(), prevJump.begin(), tmpjump.begin(), std::minus<int>());
ullint prevCoordinate = vec2index(tmpjump, cutoff);
H[nextCoordinate] = H[nextCoordinate] - intsqrt[jumpFrom[ii]-1]*(R[k*dim+ii])*H[prevCoordinate];
}
}
H[nextCoordinate] = H[nextCoordinate]/intsqrt[nextPos[k]-1];
}
return H;
}
/**
* Returns the matrix elements of an interferometer parametrized in terms of its R matrix
*
* @param R a flattened vector of size \f$n^2\f$, representing a
* \f$n\times n\f$ symmetric matrix.
* @param cutoff highest number of photons to be resolved.
*
*/
template <typename T>
inline T* interferometer_cpp(const std::vector<T> &R, const int &cutoff) {
int dim = std::sqrt(static_cast<double>(R.size()));
assert(dim % 2 == 0);
int num_modes = dim/2;
ullint Hdim = pow(cutoff, dim);
T *H;
H = (T*) malloc(sizeof(T)*Hdim);
memset(&H[0],0,sizeof(T)*Hdim);
H[0] = 1;
std::vector<double> intsqrt(cutoff+1, 0);
for (int ii = 0; ii<=cutoff; ii++) {
intsqrt[ii] = std::sqrt((static_cast<double>(ii)));
}
std::vector<int> nextPos(dim, 1);
std::vector<int> jumpFrom(dim, 1);
int jump = 0;
int k;
ullint nextCoordinate, fromCoordinate;
for (ullint jj = 0; jj < Hdim-1; jj++) {
k = update_iterator(nextPos, jumpFrom, jump, cutoff, dim);
int bran = 0;
for (int ii=0; ii < num_modes; ii++) {
bran += nextPos[ii];
}
int ketn = 0;
for (int ii=num_modes; ii < dim; ii++) {
ketn += nextPos[ii];
}
if (bran == ketn) {
nextCoordinate = vec2index(nextPos, cutoff);
fromCoordinate = vec2index(jumpFrom, cutoff);
std::vector<int> tmpjump(dim, 0);
int low_lim;
int high_lim;
if (k > num_modes) {
low_lim = 0;
high_lim = num_modes;
}
else {
low_lim = num_modes;
high_lim = dim;
}
for (int ii = low_lim; ii < high_lim; ii++) {
if (jumpFrom[ii] > 1) {
std::vector<int> prevJump(dim, 0);
prevJump[ii] = 1;
std::transform(jumpFrom.begin(), jumpFrom.end(), prevJump.begin(), tmpjump.begin(), std::minus<int>());
ullint prevCoordinate = vec2index(tmpjump, cutoff);
H[nextCoordinate] = H[nextCoordinate] - (intsqrt[jumpFrom[ii]-1])*(R[k*dim+ii])*H[prevCoordinate];
}
}
H[nextCoordinate] = H[nextCoordinate] /intsqrt[nextPos[k]-1];
}
}
return H;
}
}
| 31.161765 | 123 | 0.591317 | maliasadi |
e150fcc7c4dd87b2dcce117127aeeccf639d7f1b | 242 | cpp | C++ | 556-next-greater-element-iii/556-next-greater-element-iii.cpp | arihantthriwe/CompetitiveProgramming | 0e923ea965cc1b75cb97e766e61345c8b939f41a | [
"MIT"
] | 1 | 2022-02-25T12:22:31.000Z | 2022-02-25T12:22:31.000Z | 556-next-greater-element-iii/556-next-greater-element-iii.cpp | arihantthriwe/CompetitiveProgramming | 0e923ea965cc1b75cb97e766e61345c8b939f41a | [
"MIT"
] | null | null | null | 556-next-greater-element-iii/556-next-greater-element-iii.cpp | arihantthriwe/CompetitiveProgramming | 0e923ea965cc1b75cb97e766e61345c8b939f41a | [
"MIT"
] | null | null | null | class Solution {
public:
int nextGreaterElement(int n) {
auto digits = to_string(n);
next_permutation(digits.begin(), digits.end());
auto x = stoll(digits);
return (x > INT_MAX || x <= n) ? -1 : x;
}
}; | 26.888889 | 55 | 0.553719 | arihantthriwe |
e15153e746078c2bd6ea3c69ad4e68d0701b02e4 | 1,738 | cpp | C++ | cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/fun/welford_covar_estimator_test.cpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/fun/welford_covar_estimator_test.cpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/fun/welford_covar_estimator_test.cpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | #include <stan/math/prim/mat.hpp>
#include <gtest/gtest.h>
TEST(ProbWelfordCovarEstimator, restart) {
const int n = 10;
Eigen::VectorXd q = Eigen::VectorXd::Ones(n);
const int n_learn = 10;
stan::math::welford_covar_estimator estimator(n);
for (int i = 0; i < n_learn; ++i)
estimator.add_sample(q);
estimator.restart();
EXPECT_EQ(0, estimator.num_samples());
Eigen::VectorXd mean(n);
estimator.sample_mean(mean);
for (int i = 0; i < n; ++i)
EXPECT_EQ(0, mean(i));
}
TEST(ProbWelfordCovarEstimator, num_samples) {
const int n = 10;
Eigen::VectorXd q = Eigen::VectorXd::Ones(n);
const int n_learn = 10;
stan::math::welford_covar_estimator estimator(n);
for (int i = 0; i < n_learn; ++i)
estimator.add_sample(q);
EXPECT_EQ(n_learn, estimator.num_samples());
}
TEST(ProbWelfordCovarEstimator, sample_mean) {
const int n = 10;
const int n_learn = 10;
stan::math::welford_covar_estimator estimator(n);
for (int i = 0; i < n_learn; ++i) {
Eigen::VectorXd q = Eigen::VectorXd::Constant(n, i);
estimator.add_sample(q);
}
Eigen::VectorXd mean(n);
estimator.sample_mean(mean);
for (int i = 0; i < n; ++i)
EXPECT_EQ(9.0 / 2.0, mean(i));
}
TEST(ProbWelfordCovarEstimator, sample_covariance) {
const int n = 10;
const int n_learn = 10;
stan::math::welford_covar_estimator estimator(n);
for (int i = 0; i < n_learn; ++i) {
Eigen::VectorXd q = Eigen::VectorXd::Constant(n, i);
estimator.add_sample(q);
}
Eigen::MatrixXd covar(n, n);
estimator.sample_covariance(covar);
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
EXPECT_EQ(55.0 / 6.0, covar(i, j));
}
| 20.690476 | 56 | 0.622555 | yizhang-cae |
e1589aef5d6807d3e1a5a53dabb71021de0e4fa1 | 7,708 | cpp | C++ | src/prod/src/Reliability/Failover/ra/Test.Unit.LocalFailoverUnitMap.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/Reliability/Failover/ra/Test.Unit.LocalFailoverUnitMap.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/Reliability/Failover/ra/Test.Unit.LocalFailoverUnitMap.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace Reliability;
using namespace Reliability::ReconfigurationAgentComponent;
using namespace ReliabilityUnitTest;
using namespace Infrastructure;
using namespace Common;
using namespace std;
class TestLocalFailoverUnitMap
{
protected:
TestLocalFailoverUnitMap() { BOOST_REQUIRE(TestSetup()); }
TEST_METHOD_SETUP(TestSetup);
~TestLocalFailoverUnitMap() { BOOST_REQUIRE(TestCleanup()); }
TEST_METHOD_CLEANUP(TestCleanup);
struct AddEntriesResult
{
LocalFailoverUnitMapEntrySPtr FMEntry;
LocalFailoverUnitMapEntrySPtr OtherFTEntry;
vector<EntityEntryBase*> CreateExpectation(bool fmEntry, bool otherEntry) const
{
vector<EntityEntryBase*> rv;
if (fmEntry)
{
rv.push_back(FMEntry.get());
}
if (otherEntry)
{
rv.push_back(OtherFTEntry.get());
}
return rv;
}
};
class EntryState
{
public:
enum Enum
{
NotExisting = 0,
NullFT = 1,
HasFTInitial = 2,
HasFTUpdated = 3,
Deleted = 4,
};
};
class PersistenceResult
{
public:
enum Enum
{
Success,
Failure
};
};
AddEntriesResult AddEntries(bool addFMEntry, bool addOtherEntry);
void ExecuteGetAllAndVerifyResult(bool excludeFM, bool fmExpected, bool otherExpected, AddEntriesResult const & addEntryResult);
void ExecuteGetFMEntriesAndVerifyResult(bool expected, AddEntriesResult const & addEntryResult);
LocalFailoverUnitMapEntrySPtr GetOrCreate(bool createFlag);
LocalFailoverUnitMapEntrySPtr GetOrCreate(bool createFlag, std::wstring const & ftShortName);
InMemoryLocalStore & GetStore();
static FailoverUnitId GetFTId();
static FailoverUnitId GetFTId(std::wstring const & ftShortName);
static wstring GetFTShortName();
UnitTestContextUPtr utContext_;
};
bool TestLocalFailoverUnitMap::TestSetup()
{
utContext_ = UnitTestContext::Create(UnitTestContext::Option::None);
return true;
}
bool TestLocalFailoverUnitMap::TestCleanup()
{
return utContext_->Cleanup();
}
TestLocalFailoverUnitMap::AddEntriesResult TestLocalFailoverUnitMap::AddEntries(bool addFMEntry, bool addOtherEntry)
{
AddEntriesResult result;
if (addFMEntry)
{
result.FMEntry = GetOrCreate(true, L"FM");
}
if (addOtherEntry)
{
result.OtherFTEntry = GetOrCreate(true, L"SP1");
}
return result;
}
template<typename T>
vector<T*> ConvertVectorOfSharedPtrToVectorOfPtr(vector<std::shared_ptr<T>> const & result)
{
vector<T*> rv;
for (auto const & it : result)
{
rv.push_back(it.get());
}
return rv;
}
void TestLocalFailoverUnitMap::ExecuteGetAllAndVerifyResult(bool excludeFM, bool fmExpected, bool otherExpected, AddEntriesResult const & addEntryResult)
{
auto expectedEntities = addEntryResult.CreateExpectation(fmExpected, otherExpected);
auto entryResultSPtr = utContext_->LFUM.GetAllFailoverUnitEntries(excludeFM);
// Do this to not define write to text writer for entity entry
auto entryResult = ConvertVectorOfSharedPtrToVectorOfPtr(entryResultSPtr);
Verify::Vector<EntityEntryBase*>(entryResult, entryResult);
}
void TestLocalFailoverUnitMap::ExecuteGetFMEntriesAndVerifyResult(bool expected, AddEntriesResult const & addEntryResult)
{
vector<EntityEntryBase*> expectedEntities = addEntryResult.CreateExpectation(expected, false);
auto result = utContext_->LFUM.GetFMFailoverUnitEntries();
auto casted = ConvertVectorOfSharedPtrToVectorOfPtr(result);
Verify::Vector(casted, expectedEntities);
}
FailoverUnitId TestLocalFailoverUnitMap::GetFTId()
{
return GetFTId(GetFTShortName());
}
FailoverUnitId TestLocalFailoverUnitMap::GetFTId(std::wstring const & shortName)
{
return StateManagement::Default::GetInstance().LookupFTContext(shortName).FUID;
}
wstring TestLocalFailoverUnitMap::GetFTShortName()
{
return L"SP1";
}
LocalFailoverUnitMapEntrySPtr TestLocalFailoverUnitMap::GetOrCreate(bool createFlag)
{
return GetOrCreate(createFlag, GetFTShortName());
}
LocalFailoverUnitMapEntrySPtr TestLocalFailoverUnitMap::GetOrCreate(bool createFlag, std::wstring const & ftShortName)
{
return dynamic_pointer_cast<LocalFailoverUnitMapEntry>(utContext_->LFUM.GetOrCreateEntityMapEntry(GetFTId(ftShortName), createFlag));
}
BOOST_AUTO_TEST_SUITE(Unit)
BOOST_FIXTURE_TEST_SUITE(TestLocalFailoverUnitMapSuite,TestLocalFailoverUnitMap)
BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMTrue_OnlyFMEntries)
{
auto addResult = AddEntries(true, false);
ExecuteGetAllAndVerifyResult(true, false, false, addResult);
}
BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMTrue_NoEntries)
{
auto addResult = AddEntries(false, false);
ExecuteGetAllAndVerifyResult(true, false, false, addResult);
}
BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMTrue_BothEntries)
{
auto addResult = AddEntries(true, true);
ExecuteGetAllAndVerifyResult(true, false, true, addResult);
}
BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMTrue_OnlyNonFMEntries)
{
auto addResult = AddEntries(false, true);
ExecuteGetAllAndVerifyResult(true, false, true, addResult);
}
BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMFalse_OnlyFMEntries)
{
auto addResult = AddEntries(true, false);
ExecuteGetAllAndVerifyResult(false, true, false, addResult);
}
BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMFalse_NoEntries)
{
auto addResult = AddEntries(false, false);
ExecuteGetAllAndVerifyResult(false, false, false, addResult);
}
BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMFalse_BothEntries)
{
auto addResult = AddEntries(true, true);
ExecuteGetAllAndVerifyResult(false, true, true, addResult);
}
BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMFalse_OnlyNonFMEntries)
{
auto addResult = AddEntries(false, true);
ExecuteGetAllAndVerifyResult(false, false, true, addResult);
}
BOOST_AUTO_TEST_CASE(GetFMEntries_OnlyFM)
{
auto addResult = AddEntries(true, false);
ExecuteGetFMEntriesAndVerifyResult(true, addResult);
}
BOOST_AUTO_TEST_CASE(GetFMEntries_Both)
{
auto addResult = AddEntries(true, true);
ExecuteGetFMEntriesAndVerifyResult(true, addResult);
}
BOOST_AUTO_TEST_CASE(GetFMEntries_None)
{
auto addResult = AddEntries(false, false);
ExecuteGetFMEntriesAndVerifyResult(false, addResult);
}
BOOST_AUTO_TEST_CASE(GetFMEntries_OnlyOtherEntries)
{
auto addResult = AddEntries(false, true);
ExecuteGetFMEntriesAndVerifyResult(false, addResult);
}
BOOST_AUTO_TEST_CASE(GetByOwner_Fmm)
{
auto addResult = AddEntries(true, true);
auto entries = utContext_->LFUM.GetFailoverUnitEntries(*FailoverManagerId::Fmm);
auto casted = ConvertVectorOfSharedPtrToVectorOfPtr(entries);
auto expected = addResult.CreateExpectation(true, false);
Verify::Vector(expected, casted);
}
BOOST_AUTO_TEST_CASE(GetByOwner_Fm)
{
auto addResult = AddEntries(true, true);
auto entries = utContext_->LFUM.GetFailoverUnitEntries(*FailoverManagerId::Fm);
auto casted = ConvertVectorOfSharedPtrToVectorOfPtr(entries);
auto expected = addResult.CreateExpectation(false, true);
Verify::Vector(expected, casted);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
| 26.763889 | 153 | 0.730929 | AnthonyM |
e15aae3934814b00d9afe2a4b4786b82c12d7eac | 620 | cpp | C++ | Archivos/Estado_archivo.cpp | memo0p2/Programas-cpp | f78f283886e478be12b3636992dbf922199ae5f1 | [
"MIT"
] | null | null | null | Archivos/Estado_archivo.cpp | memo0p2/Programas-cpp | f78f283886e478be12b3636992dbf922199ae5f1 | [
"MIT"
] | null | null | null | Archivos/Estado_archivo.cpp | memo0p2/Programas-cpp | f78f283886e478be12b3636992dbf922199ae5f1 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
using namespace std;
int main(){
/***** ESTADO DEl ARCHIVO *****/
/**
bad() -> Cuando no tenemos permiso. Cuando no hay espacio. Cuando no existe el archivo
fail() -> Error de formato (tratas de leer int y solo encuentras un char).
eof() -> Fin de archivo End Of File
good() ->
**/
ifstream entrada;
char linea[80];
entrada.open("archivo.txt");
if(entrada.good()){
cout<<"Archivo en buen estado"<<endl;
}
else{
cout<<"Archivo en mal estado"<<endl;
}
return 0;
}
| 25.833333 | 96 | 0.55 | memo0p2 |
e15bba1dfdedc6d7b7780a2031950d8e5876bfc8 | 4,000 | cpp | C++ | src/picotorrent/ui/dialogs/addmagnetlinkdialog.cpp | theRealBaccata/picotorrent | 5baad13e44d15cc5e79da9e947b0e91781cd9e76 | [
"MIT"
] | 2,015 | 2015-07-05T23:00:19.000Z | 2022-03-30T12:42:27.000Z | src/picotorrent/ui/dialogs/addmagnetlinkdialog.cpp | ryahpalma/picotorrent | 68526dcbb9a84fe8155185b0cf4fd43f4cc196a2 | [
"MIT"
] | 740 | 2015-08-14T22:03:55.000Z | 2022-03-24T22:06:55.000Z | src/picotorrent/ui/dialogs/addmagnetlinkdialog.cpp | ryahpalma/picotorrent | 68526dcbb9a84fe8155185b0cf4fd43f4cc196a2 | [
"MIT"
] | 282 | 2015-07-02T21:47:13.000Z | 2022-03-11T15:43:26.000Z | #include "addmagnetlinkdialog.hpp"
#include <regex>
#include <boost/log/trivial.hpp>
#include <libtorrent/magnet_uri.hpp>
#include <wx/clipbrd.h>
#include <wx/tokenzr.h>
#include "../translator.hpp"
namespace lt = libtorrent;
using pt::UI::Dialogs::AddMagnetLinkDialog;
AddMagnetLinkDialog::AddMagnetLinkDialog(wxWindow* parent, wxWindowID id)
: wxDialog(parent, id, i18n("add_magnet_link_s"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER),
m_links(new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHSCROLL | wxTE_MULTILINE))
{
auto buttonsSizer = new wxBoxSizer(wxHORIZONTAL);
wxButton* ok = new wxButton(this, wxID_OK);
ok->SetDefault();
buttonsSizer->Add(ok);
buttonsSizer->Add(new wxButton(this, wxID_CANCEL, i18n("cancel")), 0, wxLEFT, FromDIP(7));
auto mainSizer = new wxBoxSizer(wxVERTICAL);
mainSizer->AddSpacer(FromDIP(11));
mainSizer->Add(new wxStaticText(this, wxID_ANY, i18n("add_magnet_link_s_description")), 0, wxLEFT | wxRIGHT, FromDIP(11));
mainSizer->AddSpacer(FromDIP(5));
mainSizer->Add(m_links, 1, wxLEFT | wxRIGHT | wxEXPAND, FromDIP(11));
mainSizer->AddSpacer(FromDIP(7));
mainSizer->Add(buttonsSizer, 0, wxLEFT | wxRIGHT | wxBOTTOM | wxALIGN_RIGHT, FromDIP(11));
this->SetSizerAndFit(mainSizer);
this->SetSize(FromDIP(wxSize(400, 250)));
m_links->SetFocus();
m_links->SetFont(
wxFont(9, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Consolas")));
if (auto clipboard = wxClipboard::Get())
{
if (clipboard->Open())
{
wxTextDataObject data;
if (clipboard->GetData(data))
{
wxString d = data.GetText();
if (IsMagnetLinkOrInfoHash(d))
{
if (!d.EndsWith("\n"))
{
d = d + "\n";
}
m_links->SetValue(d);
m_links->SetInsertionPointEnd();
}
}
clipboard->Close();
}
}
}
AddMagnetLinkDialog::~AddMagnetLinkDialog()
{
}
std::vector<libtorrent::add_torrent_params> AddMagnetLinkDialog::GetParams()
{
std::vector<lt::add_torrent_params> result;
wxStringTokenizer tokenizer(m_links->GetValue());
while (tokenizer.HasMoreTokens())
{
std::string token = tokenizer.GetNextToken();
if (!IsMagnetLinkOrInfoHash(token)) { continue; }
switch (token.size())
{
case 40:
if (token.substr(0, 20) != "magnet:?xt=urn:btih:")
{
BOOST_LOG_TRIVIAL(info) << "Prepending magnet URI to v1 info hash: " << token;
token = "magnet:?xt=urn:btih:" + token;
}
break;
case 68:
if (token.substr(0, 20) != "magnet:?xt=urn:btmh:")
{
BOOST_LOG_TRIVIAL(info) << "Prepending magnet URI to v2 info hash: " << token;
token = "magnet:?xt=urn:btmh:" + token;
}
break;
}
lt::error_code ec;
lt::add_torrent_params params = lt::parse_magnet_uri(token, ec);
if (ec)
{
BOOST_LOG_TRIVIAL(warning) << "Failed to parse magnet uri: " << token << ", error: " << ec;
continue;
}
result.push_back(params);
}
return result;
}
bool AddMagnetLinkDialog::IsMagnetLinkOrInfoHash(wxString const& str)
{
std::regex infoHashV1("[a-fA-F\\d]{40}", std::regex_constants::icase);
std::regex infoHashV2("[a-fA-F\\d]{68}", std::regex_constants::icase);
if (std::regex_match(str.ToStdString(), infoHashV1)
|| std::regex_match(str.ToStdString(), infoHashV2))
{
return true;
}
if (str.StartsWith("magnet:?xt=urn:btih:")
|| str.StartsWith("magnet:?xt=urn:btmh:"))
{
return true;
}
return false;
}
| 29.62963 | 130 | 0.59275 | theRealBaccata |
e15ce6e309eb930a32ff04e8bedd311012de8dd0 | 80 | hpp | C++ | src/Arrays/Arrays_macros.hpp | jaimedelacruz/depthOptimizer | 4845cc2d2c81c98c5d905da3fcb057c4e76ee8e9 | [
"MIT"
] | 1 | 2019-01-27T14:54:10.000Z | 2019-01-27T14:54:10.000Z | Arrays/Arrays_macros.hpp | jaimedelacruz/Arrays | 83175d8a412962a0321cb58a74707c43b11ff5b3 | [
"MIT"
] | null | null | null | Arrays/Arrays_macros.hpp | jaimedelacruz/Arrays | 83175d8a412962a0321cb58a74707c43b11ff5b3 | [
"MIT"
] | null | null | null | #ifndef ARRAYS_MACRO_H
#define ARRAYS_MACRO_H
#define M_INLINE inline
#endif
| 10 | 23 | 0.8125 | jaimedelacruz |
e15d5b35691e8502febb5bfa388ae2b36c8a3cc0 | 557 | cpp | C++ | src/sources/AWLdict.cpp | Amuwa/TeXpen | d0d7ae74463f88980beb8ceb2958182ac2df021e | [
"MIT"
] | 5 | 2019-03-04T08:47:52.000Z | 2022-01-28T12:53:55.000Z | src/sources/AWLdict.cpp | Amuwa/TeXpen | d0d7ae74463f88980beb8ceb2958182ac2df021e | [
"MIT"
] | 3 | 2019-02-22T05:41:49.000Z | 2020-03-16T13:37:23.000Z | src/sources/AWLdict.cpp | Amuwa/TeXpen | d0d7ae74463f88980beb8ceb2958182ac2df021e | [
"MIT"
] | 7 | 2019-02-22T06:04:13.000Z | 2022-01-28T12:54:15.000Z | #include "headers/mainwindow.h"
#include "headers/qtexedit.h"
#include <QString>
#include <QFile>
QStringList AWL;
void setupAWL(){
if(AWL.isEmpty()){
QFile file (":/AWL/awl.txt");
file.open(QIODevice::ReadOnly);
QString word = QString::fromUtf8(file.readLine());
while((!word.isEmpty())&& word !=" "){
if(word.contains("\n")){
word.replace("\n","");
}
AWL.append(word);
word = QString::fromUtf8(file.readLine());
}
file.close();
}
}
| 23.208333 | 58 | 0.526032 | Amuwa |
ff150290b708a3924ca3f60eebacf1d51cf58974 | 2,742 | cpp | C++ | Source/Engine/ImageBasedLightingTechnique.cpp | glowing-chemist/Bell | 0cf4d0ac925940869077779700c1d3bd45ff841f | [
"MIT"
] | 14 | 2020-02-12T19:13:46.000Z | 2022-03-05T02:26:06.000Z | Source/Engine/ImageBasedLightingTechnique.cpp | glowing-chemist/Bell | 0cf4d0ac925940869077779700c1d3bd45ff841f | [
"MIT"
] | 5 | 2020-08-06T07:19:47.000Z | 2021-01-05T21:20:51.000Z | Source/Engine/ImageBasedLightingTechnique.cpp | glowing-chemist/Bell | 0cf4d0ac925940869077779700c1d3bd45ff841f | [
"MIT"
] | 2 | 2021-09-18T13:36:47.000Z | 2021-12-04T15:08:53.000Z | #include "Engine/ImageBasedLightingTechnique.hpp"
#include "Engine/Engine.hpp"
#include "Engine/DefaultResourceSlots.hpp"
#include "Core/Executor.hpp"
#include "Core/Profiling.hpp"
DeferredImageBasedLightingTechnique::DeferredImageBasedLightingTechnique(RenderEngine* eng, RenderGraph& graph) :
Technique("GlobalIBL", eng->getDevice()),
mPipelineDesc{Rect{getDevice()->getSwapChain()->getSwapChainImageWidth(),
getDevice()->getSwapChain()->getSwapChainImageHeight()},
Rect{getDevice()->getSwapChain()->getSwapChainImageWidth(),
getDevice()->getSwapChain()->getSwapChainImageHeight()} },
mIBLVertexShader(eng->getShader("./Shaders/FullScreenTriangle.vert")),
mIBLFragmentShader(eng->getShader("./Shaders/DeferredDFGIBL.frag"))
{
GraphicsTask task{ "GlobalIBL", mPipelineDesc };
task.addInput(kCameraBuffer, AttachmentType::UniformBuffer);
task.addInput(kDFGLUT, AttachmentType::Texture2D);
task.addInput(kGBufferDepth, AttachmentType::Texture2D);
task.addInput(kGBufferNormals, AttachmentType::Texture2D);
task.addInput(kGBufferDiffuse, AttachmentType::Texture2D);
task.addInput(kGBufferSpecularRoughness, AttachmentType::Texture2D);
task.addInput(kGBufferEmissiveOcclusion, AttachmentType::Texture2D);
task.addInput(kConvolvedSpecularSkyBox, AttachmentType::CubeMap);
task.addInput(kConvolvedDiffuseSkyBox, AttachmentType::CubeMap);
task.addInput(kDefaultSampler, AttachmentType::Sampler);
if (eng->isPassRegistered(PassType::Shadow) || eng->isPassRegistered(PassType::CascadingShadow) || eng->isPassRegistered(PassType::RayTracedShadows))
task.addInput(kShadowMap, AttachmentType::Texture2D);
if(eng->isPassRegistered(PassType::SSR) || eng->isPassRegistered(PassType::RayTracedReflections))
task.addInput(kReflectionMap, AttachmentType::Texture2D);
task.addManagedOutput(kGlobalLighting, AttachmentType::RenderTarget2D, Format::RGBA16Float,
SizeClass::Swapchain, LoadOp::Clear_Black, StoreOp::Store, ImageUsage::ColourAttachment | ImageUsage::Sampled | ImageUsage::TransferSrc);
task.setRecordCommandsCallback(
[this](const RenderGraph& graph, const uint32_t taskIndex, Executor* exec, RenderEngine*, const std::vector<const MeshInstance*>&)
{
PROFILER_EVENT("Defered IBL");
PROFILER_GPU_TASK(exec);
PROFILER_GPU_EVENT("Defered IBL");
const RenderTask& task = graph.getTask(taskIndex);
exec->setGraphicsShaders(static_cast<const GraphicsTask&>(task), graph, mIBLVertexShader, nullptr, nullptr, nullptr, mIBLFragmentShader);
exec->draw(0, 3);
}
);
mTaskID = graph.addTask(task);
}
| 50.777778 | 153 | 0.736689 | glowing-chemist |
ff1bc95a9befd8c02e3b5f8bb5a65ccfeeb4cca6 | 5,636 | cpp | C++ | src/plugins/azoth/importmanager.cpp | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 120 | 2015-01-22T14:10:39.000Z | 2021-11-25T12:57:16.000Z | src/plugins/azoth/importmanager.cpp | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 8 | 2015-02-07T19:38:19.000Z | 2017-11-30T20:18:28.000Z | src/plugins/azoth/importmanager.cpp | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 33 | 2015-02-07T16:59:55.000Z | 2021-10-12T00:36:40.000Z | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
**********************************************************************/
#include "importmanager.h"
#include <util/sll/qtutil.h>
#include <interfaces/core/icoreproxy.h>
#include <interfaces/core/ipluginsmanager.h>
#include "interfaces/azoth/iaccount.h"
#include "interfaces/azoth/isupportimport.h"
#include "interfaces/azoth/ihistoryplugin.h"
#include "core.h"
#include "accounthandlerchooserdialog.h"
namespace LC
{
namespace Azoth
{
ImportManager::ImportManager (QObject *parent)
: QObject (parent)
{
}
void ImportManager::HandleAccountImport (Entity e)
{
const auto& map = e.Additional_ ["AccountData"].toMap ();
const auto& protoId = map ["Protocol"].toString ();
if (protoId.isEmpty ())
{
qWarning () << Q_FUNC_INFO
<< "empty protocol id"
<< map;
return;
}
for (const auto proto : Core::Instance ().GetProtocols ())
{
const auto isi = qobject_cast<ISupportImport*> (proto->GetQObject ());
if (!isi || isi->GetImportProtocolID () != protoId)
continue;
isi->ImportAccount (map);
break;
}
}
namespace
{
IMessage::Direction GetDirection (const QByteArray& dirStr)
{
if (dirStr == "out")
return IMessage::Direction::Out;
else if (dirStr == "in")
return IMessage::Direction::In;
qWarning () << Q_FUNC_INFO
<< "unknown direction"
<< dirStr;
return IMessage::Direction::In;
}
IMessage::Type GetMessageType (const QByteArray& typeStr)
{
if (typeStr == "chat")
return IMessage::Type::ChatMessage;
else if (typeStr == "muc")
return IMessage::Type::MUCMessage;
else if (typeStr == "event")
return IMessage::Type::EventMessage;
qWarning () << Q_FUNC_INFO
<< "unknown type"
<< typeStr;
return IMessage::Type::ChatMessage;
}
IMessage::EscapePolicy GetEscapePolicy (const QByteArray& polStr)
{
if (polStr.isEmpty ())
return IMessage::EscapePolicy::Escape;
else if (polStr == "escape")
return IMessage::EscapePolicy::Escape;
else if (polStr == "noEscape")
return IMessage::EscapePolicy::NoEscape;
qWarning () << Q_FUNC_INFO
<< "unknown escape policy"
<< polStr;
return IMessage::EscapePolicy::Escape;
}
}
void ImportManager::HandleHistoryImport (Entity e)
{
qDebug () << Q_FUNC_INFO;
const auto& histories = Core::Instance ().GetProxy ()->
GetPluginsManager ()->GetAllCastableTo<IHistoryPlugin*> ();
if (histories.isEmpty ())
{
qWarning () << Q_FUNC_INFO
<< "no history plugin is present, aborting";
return;
}
const auto acc = GetAccountID (e);
if (!acc)
return;
const auto isi = qobject_cast<ISupportImport*> (acc->GetParentProtocol ());
QHash<QString, QString> entryIDcache;
QVariantList history;
for (const auto& qe : EntityQueues_.take (e.Additional_ ["AccountID"].toString ()))
history.append (qe.Additional_ ["History"].toList ());
qDebug () << history.size ();
struct EntryInfo
{
QString VisibleName_;
QList<HistoryItem> Items_;
};
QHash<QString, QHash<QString, EntryInfo>> items;
for (const auto& lineVar : history)
{
const auto& histMap = lineVar.toMap ();
const auto& origId = histMap ["EntryID"].toString ();
QString entryId;
if (entryIDcache.contains (origId))
entryId = entryIDcache [origId];
else
{
const auto& realId = isi->GetEntryID (origId, acc->GetQObject ());
entryIDcache [origId] = realId;
entryId = realId;
}
auto visibleName = histMap ["VisibleName"].toString ();
if (visibleName.isEmpty ())
visibleName = origId;
const auto& accId = acc->GetAccountID ();
const HistoryItem item
{
histMap ["DateTime"].toDateTime (),
GetDirection (histMap ["Direction"].toByteArray ()),
histMap ["Body"].toString (),
histMap ["OtherVariant"].toString (),
GetMessageType (histMap ["Type"].toByteArray ()),
histMap ["RichBody"].toString (),
GetEscapePolicy (histMap ["EscapePolicy"].toByteArray ())
};
auto& info = items [accId] [entryId];
info.VisibleName_ = visibleName;
info.Items_ << item;
}
for (const auto& accPair : Util::Stlize (items))
for (const auto& entryPair : Util::Stlize (accPair.second))
{
const auto& info = entryPair.second;
for (const auto plugin : histories)
plugin->AddRawMessages (accPair.first,
entryPair.first, info.VisibleName_, info.Items_);
}
}
IAccount* ImportManager::GetAccountID (Entity e)
{
const auto& accName = e.Additional_ ["AccountName"].toString ();
const auto& accs = Core::Instance ().GetAccounts ([] (IProtocol *proto)
{ return qobject_cast<ISupportImport*> (proto->GetQObject ()); });
const auto pos = std::find_if (accs.begin (), accs.end (),
[&accName] (IAccount *acc) { return acc->GetAccountName () == accName; });
if (pos != accs.end ())
return *pos;
const auto& impId = e.Additional_ ["AccountID"].toString ();
EntityQueues_ [impId] << e;
if (EntityQueues_ [impId].size () > 1)
return nullptr;
if (AccID2OurID_.contains (impId))
return AccID2OurID_ [impId];
AccountHandlerChooserDialog dia (accs,
tr ("Select account to import history from %1 into:").arg (accName));
if (dia.exec () != QDialog::Accepted)
return 0;
const auto acc = dia.GetSelectedAccount ();
AccID2OurID_ [impId] = acc;
return acc;
}
}
}
| 27.227053 | 85 | 0.648155 | Maledictus |
ff1fc5df7f4b9f9b140ff2e8a484776cb0e3a6bc | 5,382 | cpp | C++ | examples/lapack-like/SkewHermitianEig.cpp | ahmadia/Elemental-1 | f9a82c76a06728e9e04a4316e41803efbadb5a19 | [
"BSD-3-Clause"
] | null | null | null | examples/lapack-like/SkewHermitianEig.cpp | ahmadia/Elemental-1 | f9a82c76a06728e9e04a4316e41803efbadb5a19 | [
"BSD-3-Clause"
] | null | null | null | examples/lapack-like/SkewHermitianEig.cpp | ahmadia/Elemental-1 | f9a82c76a06728e9e04a4316e41803efbadb5a19 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2009-2013, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
// NOTE: It is possible to simply include "elemental.hpp" instead
#include "elemental-lite.hpp"
#include "elemental/blas-like/level1/DiagonalScale.hpp"
#include "elemental/blas-like/level1/Scale.hpp"
#include "elemental/blas-like/level3/Gemm.hpp"
#include "elemental/blas-like/level3/Herk.hpp"
#include "elemental/lapack-like/SkewHermitianEig.hpp"
#include "elemental/lapack-like/Norm/Frobenius.hpp"
#include "elemental/lapack-like/HermitianEig/Sort.hpp"
#include "elemental/matrices/Identity.hpp"
using namespace std;
using namespace elem;
// Typedef our real and complex types to 'R' and 'C' for convenience
typedef double R;
typedef Complex<R> C;
int
main( int argc, char* argv[] )
{
// This detects whether or not you have already initialized MPI and
// does so if necessary. The full routine is elem::Initialize.
Initialize( argc, argv );
// Extract our MPI rank
mpi::Comm comm = mpi::COMM_WORLD;
const int commRank = mpi::CommRank( comm );
// Surround the Elemental calls with try/catch statements in order to
// safely handle any exceptions that were thrown during execution.
try
{
const int n = Input("--size","size of matrix",100);
const bool print = Input("--print","print matrices?",false);
ProcessInput();
PrintInputReport();
// Create a 2d process grid from a communicator. In our case, it is
// MPI_COMM_WORLD. There is another constructor that allows you to
// specify the grid dimensions, Grid g( comm, r, c ), which creates an
// r x c grid.
Grid g( comm );
// Create an n x n complex distributed matrix,
// We distribute the matrix using grid 'g'.
//
// There are quite a few available constructors, including ones that
// allow you to pass in your own local buffer and to specify the
// distribution alignments (i.e., which process row and column owns the
// top-left element)
DistMatrix<C> S( n, n, g );
// Fill the matrix since we did not pass in a buffer.
//
// We will fill entry (i,j) with the complex value (i-j,i+j) so that
// the global matrix is skew-Hermitian. However, only one triangle of
// the matrix actually needs to be filled, the symmetry can be implicit.
//
const int colShift = S.ColShift(); // first row we own
const int rowShift = S.RowShift(); // first col we own
const int colStride = S.ColStride();
const int rowStride = S.RowStride();
const int localHeight = S.LocalHeight();
const int localWidth = S.LocalWidth();
for( int jLocal=0; jLocal<localWidth; ++jLocal )
{
for( int iLocal=0; iLocal<localHeight; ++iLocal )
{
// Our process owns the rows colShift:colStride:n,
// and the columns rowShift:rowStride:n
const int i = colShift + iLocal*colStride;
const int j = rowShift + jLocal*rowStride;
S.SetLocal( iLocal, jLocal, C(i-j,i+j) );
}
}
// Make a backup of S before we overwrite it within the eigensolver
DistMatrix<C> SCopy( S );
// Call the eigensolver. We first create an empty complex eigenvector
// matrix, X[MC,MR], and an eigenvalue column vector, w[VR,* ]
//
// Optional: set blocksizes and algorithmic choices here. See the
// 'Tuning' section of the README for details.
DistMatrix<R,VR,STAR> wImag( g );
DistMatrix<C> X( g );
SkewHermitianEig( LOWER, S, wImag, X ); // only use lower half of S
// Optional: sort the eigenpairs
hermitian_eig::Sort( wImag, X );
if( print )
{
SCopy.Print("S");
X.Print("X");
wImag.Print("wImag");
}
// Check the residual, || S X - Omega X ||_F
const R frobS = HermitianFrobeniusNorm( LOWER, SCopy );
DistMatrix<C> E( X );
Scale( C(0,1), E );
DiagonalScale( RIGHT, NORMAL, wImag, E );
Gemm( NORMAL, NORMAL, C(-1), SCopy, X, C(1), E );
const R frobResid = FrobeniusNorm( E );
// Check the orthogonality of X
Identity( E, n, n );
Herk( LOWER, NORMAL, C(-1), X, C(1), E );
const R frobOrthog = HermitianFrobeniusNorm( LOWER, E );
if( g.Rank() == 0 )
{
std::cout << "|| H ||_F = " << frobS << "\n"
<< "|| H X - X Omega ||_F / || A ||_F = "
<< frobResid / frobS << "\n"
<< "|| X X^H - I ||_F = " << frobOrthog / frobS
<< "\n" << std::endl;
}
}
catch( ArgException& e )
{
// There is nothing to do
}
catch( exception& e )
{
ostringstream os;
os << "Process " << commRank << " caught exception with message: "
<< e.what() << endl;
cerr << os.str();
#ifndef RELEASE
DumpCallStack();
#endif
}
Finalize();
return 0;
}
| 36.612245 | 80 | 0.580639 | ahmadia |
ff2006889cc49c36f90713986754b6fa67ef925e | 1,699 | hh | C++ | plugins/SonarPlugin.hh | traversaro/gazebo | 6fd426b3949c4ca73fa126cde68f5cc4a59522eb | [
"ECL-2.0",
"Apache-2.0"
] | 887 | 2020-04-18T08:43:06.000Z | 2022-03-31T11:58:50.000Z | plugins/SonarPlugin.hh | traversaro/gazebo | 6fd426b3949c4ca73fa126cde68f5cc4a59522eb | [
"ECL-2.0",
"Apache-2.0"
] | 462 | 2020-04-21T21:59:19.000Z | 2022-03-31T23:23:21.000Z | plugins/SonarPlugin.hh | traversaro/gazebo | 6fd426b3949c4ca73fa126cde68f5cc4a59522eb | [
"ECL-2.0",
"Apache-2.0"
] | 421 | 2020-04-21T09:13:03.000Z | 2022-03-30T02:22:01.000Z | /*
* Copyright (C) 2012 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef GAZEBO_PLUGINS_SONARPLUGIN_HH_
#define GAZEBO_PLUGINS_SONARPLUGIN_HH_
#include "gazebo/common/Plugin.hh"
#include "gazebo/sensors/SensorTypes.hh"
#include "gazebo/sensors/SonarSensor.hh"
#include "gazebo/util/system.hh"
namespace gazebo
{
/// \brief A sonar sensor plugin
class GZ_PLUGIN_VISIBLE SonarPlugin : public SensorPlugin
{
/// \brief Constructor
public: SonarPlugin();
/// \brief Destructor
public: virtual ~SonarPlugin();
/// \brief Load the plugin
/// \param[in] _parent Pointer to the parent sensor.
/// \param[in] _sdf SDF element for the plugin.
public: void Load(sensors::SensorPtr _parent, sdf::ElementPtr _sdf);
/// \brief Update callback. Overload this function in a child class.
/// \param[in] _msg The sonar ping message.
protected: virtual void OnUpdate(msgs::SonarStamped _msg);
/// \brief The parent sensor
protected: sensors::SonarSensorPtr parentSensor;
/// \brief The connection tied to SonarSensor's update event
private: event::ConnectionPtr connection;
};
}
#endif
| 31.462963 | 75 | 0.724544 | traversaro |
ff20f8da8e0bb40b1dd071d3e8f550fd4dd2335d | 18,857 | cpp | C++ | src/orm/query/grammars/grammar.cpp | MrAhmedSayedAli/TinyORM | f185e76cfa955475df9b807c3e7ecaa4c20989c0 | [
"MIT"
] | 4 | 2021-07-07T01:21:34.000Z | 2022-02-01T01:38:24.000Z | src/orm/query/grammars/grammar.cpp | MrAhmedSayedAli/TinyORM | f185e76cfa955475df9b807c3e7ecaa4c20989c0 | [
"MIT"
] | 2 | 2022-03-04T10:57:15.000Z | 2022-03-26T17:10:28.000Z | src/orm/query/grammars/grammar.cpp | MrAhmedSayedAli/TinyORM | f185e76cfa955475df9b807c3e7ecaa4c20989c0 | [
"MIT"
] | 2 | 2021-08-10T01:31:31.000Z | 2022-03-04T10:37:42.000Z | #include "orm/query/grammars/grammar.hpp"
#include "orm/databaseconnection.hpp"
#include "orm/macros/likely.hpp"
#include "orm/query/joinclause.hpp"
TINYORM_BEGIN_COMMON_NAMESPACE
namespace Orm::Query::Grammars
{
QString Grammar::compileSelect(QueryBuilder &query) const
{
/* If the query does not have any columns set, we'll set the columns to the
* character to just get all of the columns from the database. Then we
can build the query and concatenate all the pieces together as one. */
const auto original = query.getColumns();
if (original.isEmpty())
query.setColumns({ASTERISK});
/* To compile the query, we'll spin through each component of the query and
see if that component exists. If it does we'll just call the compiler
function for the component which is responsible for making the SQL. */
auto sql = concatenate(compileComponents(query));
// Restore original columns value
query.setColumns(original);
return sql;
}
QString Grammar::compileInsert(const QueryBuilder &query,
const QVector<QVariantMap> &values) const
{
const auto table = wrapTable(query.getFrom());
// FEATURE insert with empty values, this code will never be triggered, because check in the QueryBuilder::insert, even all other code works correctly and support empty values silverqx
if (values.isEmpty())
return QStringLiteral("insert into %1 default values").arg(table);
return QStringLiteral("insert into %1 (%2) values %3").arg(
table,
// Columns are obtained only from a first QMap
columnize(values.at(0).keys()),
compileInsertToVector(values).join(COMMA));
}
QString Grammar::compileInsertOrIgnore(const QueryBuilder &/*unused*/,
const QVector<QVariantMap> &/*unused*/) const
{
throw Exceptions::RuntimeError(
"This database engine does not support inserting while ignoring "
"errors.");
}
QString Grammar::compileUpdate(QueryBuilder &query,
const QVector<UpdateItem> &values) const
{
const auto table = wrapTable(query.getFrom());
const auto columns = compileUpdateColumns(values);
const auto wheres = compileWheres(query);
return query.getJoins().isEmpty()
? compileUpdateWithoutJoins(query, table, columns, wheres)
: compileUpdateWithJoins(query, table, columns, wheres);
}
QVector<QVariant>
Grammar::prepareBindingsForUpdate(const BindingsMap &bindings,
const QVector<UpdateItem> &values) const
{
QVector<QVariant> preparedBindings(bindings.find(BindingType::JOIN).value());
// Merge update values bindings
std::transform(values.cbegin(), values.cend(), std::back_inserter(preparedBindings),
[](const auto &updateItem)
{
return updateItem.value;
});
/* Flatten bindings map and exclude select and join bindings and than merge
all remaining bindings from flatten bindings map. */
const auto flatten = flatBindingsForUpdateDelete(bindings, {BindingType::SELECT,
BindingType::JOIN});
// std::copy() is ok, 'flatten' contains vector of references
std::copy(flatten.cbegin(), flatten.cend(), std::back_inserter(preparedBindings));
return preparedBindings;
}
QString Grammar::compileDelete(QueryBuilder &query) const
{
const auto table = wrapTable(query.getFrom());
const auto wheres = compileWheres(query);
return query.getJoins().isEmpty() ? compileDeleteWithoutJoins(query, table, wheres)
: compileDeleteWithJoins(query, table, wheres);
}
QVector<QVariant> Grammar::prepareBindingsForDelete(const BindingsMap &bindings) const
{
QVector<QVariant> preparedBindings;
/* Flatten bindings map and exclude select bindings and than merge all remaining
bindings from flatten bindings map. */
const auto flatten = flatBindingsForUpdateDelete(bindings, {BindingType::SELECT});
// std::copy() is ok, 'flatten' contains vector of references
std::copy(flatten.cbegin(), flatten.cend(), std::back_inserter(preparedBindings));
return preparedBindings;
}
std::unordered_map<QString, QVector<QVariant>>
Grammar::compileTruncate(const QueryBuilder &query) const
{
return {{QStringLiteral("truncate table %1").arg(wrapTable(query.getFrom())), {}}};
}
const QVector<QString> &Grammar::getOperators() const
{
/* I make it this way, I don't declare it as pure virtual intentionally, this gives
me oportunity to instantiate the Grammar class eg. in tests. */
static const QVector<QString> cachedOperators;
return cachedOperators;
}
bool Grammar::shouldCompileAggregate(const std::optional<AggregateItem> &aggregate) const
{
return aggregate.has_value() && !aggregate->function.isEmpty();
}
bool Grammar::shouldCompileColumns(const QueryBuilder &query) const
{
/* If the query is actually performing an aggregating select, we will let
compileAggregate() to handle the building of the select clauses, as it will need
some more syntax that is best handled by that function to keep things neat. */
return !query.getAggregate() && !query.getColumns().isEmpty();
}
bool Grammar::shouldCompileFrom(const FromClause &from) const
{
return !std::holds_alternative<std::monostate>(from) ||
(std::holds_alternative<QString>(from) &&
!std::get<QString>(from).isEmpty());
}
QStringList Grammar::compileComponents(const QueryBuilder &query) const
{
QStringList sql;
const auto &compileMap = getCompileMap();
for (const auto &component : compileMap)
if (component.isset)
if (component.isset(query))
sql.append(std::invoke(component.compileMethod, query));
return sql;
}
QString Grammar::compileAggregate(const QueryBuilder &query) const
{
const auto &aggregate = query.getAggregate();
const auto &distinct = query.getDistinct();
auto column = columnize(aggregate->columns);
/* If the query has a "distinct" constraint and we're not asking for all columns
we need to prepend "distinct" onto the column name so that the query takes
it into account when it performs the aggregating operations on the data. */
if (std::holds_alternative<bool>(distinct) && query.getDistinct<bool>() &&
column != ASTERISK
) T_LIKELY
column = QStringLiteral("distinct %1").arg(column);
else if (std::holds_alternative<QStringList>(distinct)) T_UNLIKELY
column = QStringLiteral("distinct %1")
.arg(columnize(std::get<QStringList>(distinct)));
return QStringLiteral("select %1(%2) as %3").arg(aggregate->function, column,
wrap(QStringLiteral("aggregate")));
}
QString Grammar::compileColumns(const QueryBuilder &query) const
{
QString select;
const auto &distinct = query.getDistinct();
if (!std::holds_alternative<bool>(distinct))
throw Exceptions::RuntimeError(
QStringLiteral("Connection '%1' doesn't support defining more distinct "
"columns.")
.arg(query.getConnection().getName()));
if (std::get<bool>(distinct))
select = QStringLiteral("select distinct %1");
else
select = QStringLiteral("select %1");
return select.arg(columnize(query.getColumns()));
}
QString Grammar::compileFrom(const QueryBuilder &query) const
{
return QStringLiteral("from %1").arg(wrapTable(query.getFrom()));
}
QString Grammar::compileWheres(const QueryBuilder &query) const
{
const auto sql = compileWheresToVector(query);
if (!sql.isEmpty())
return concatenateWhereClauses(query, sql);
return {};
}
QStringList Grammar::compileWheresToVector(const QueryBuilder &query) const
{
const auto &wheres = query.getWheres();
QStringList compiledWheres;
compiledWheres.reserve(wheres.size());
for (const auto &where : wheres)
compiledWheres << QStringLiteral("%1 %2")
.arg(where.condition,
std::invoke(getWhereMethod(where.type), where));
return compiledWheres;
}
QString Grammar::concatenateWhereClauses(const QueryBuilder &query,
const QStringList &sql) const
{
// Is it a query instance of the JoinClause?
const auto conjunction = dynamic_cast<const JoinClause *>(&query) == nullptr
? QStringLiteral("where")
: QStringLiteral("on");
return QStringLiteral("%1 %2").arg(conjunction,
removeLeadingBoolean(sql.join(SPACE)));
}
QString Grammar::compileJoins(const QueryBuilder &query) const
{
const auto &joins = query.getJoins();
QStringList sql;
sql.reserve(joins.size());
for (const auto &join : joins)
sql << QStringLiteral("%1 join %2 %3").arg(join->getType(),
wrapTable(join->getTable()),
compileWheres(*join));
return sql.join(SPACE);
}
QString Grammar::compileGroups(const QueryBuilder &query) const
{
return QStringLiteral("group by %1").arg(columnize(query.getGroups()));
}
QString Grammar::compileHavings(const QueryBuilder &query) const
{
const auto &havings = query.getHavings();
QStringList compiledHavings;
compiledHavings.reserve(havings.size());
for (const auto &having : havings)
compiledHavings << compileHaving(having);
return QStringLiteral("having %1").arg(
removeLeadingBoolean(compiledHavings.join(SPACE)));
}
QString Grammar::compileHaving(const HavingConditionItem &having) const
{
/* If the having clause is "raw", we can just return the clause straight away
without doing any more processing on it. Otherwise, we will compile the
clause into SQL based on the components that make it up from builder. */
switch (having.type) {
T_LIKELY
case HavingType::BASIC:
return compileBasicHaving(having);
T_UNLIKELY
case HavingType::RAW:
return QStringLiteral("%1 %2").arg(having.condition, having.sql);
T_UNLIKELY
default:
throw Exceptions::RuntimeError(QStringLiteral("Unknown HavingType (%1).")
.arg(static_cast<int>(having.type)));
}
}
QString Grammar::compileBasicHaving(const HavingConditionItem &having) const
{
return QStringLiteral("%1 %2 %3 %4").arg(having.condition, wrap(having.column),
having.comparison, parameter(having.value));
}
QString Grammar::compileOrders(const QueryBuilder &query) const
{
if (query.getOrders().isEmpty())
return QLatin1String("");
return QStringLiteral("order by %1").arg(compileOrdersToVector(query).join(COMMA));
}
QStringList Grammar::compileOrdersToVector(const QueryBuilder &query) const
{
const auto &orders = query.getOrders();
QStringList compiledOrders;
compiledOrders.reserve(orders.size());
for (const auto &order : orders)
if (order.sql.isEmpty()) T_LIKELY
compiledOrders << QStringLiteral("%1 %2")
.arg(wrap(order.column), order.direction.toLower());
else T_UNLIKELY
compiledOrders << order.sql;
return compiledOrders;
}
QString Grammar::compileLimit(const QueryBuilder &query) const
{
return QStringLiteral("limit %1").arg(query.getLimit());
}
QString Grammar::compileOffset(const QueryBuilder &query) const
{
return QStringLiteral("offset %1").arg(query.getOffset());
}
QString Grammar::compileLock(const QueryBuilder &query) const
{
const auto &lock = query.getLock();
if (std::holds_alternative<QString>(lock))
return std::get<QString>(lock);
return QLatin1String("");
}
QString Grammar::whereBasic(const WhereConditionItem &where) const
{
// FEATURE postgres, try operators with ? vs pdo str_replace(?, ??) https://wiki.php.net/rfc/pdo_escape_placeholders silverqx
return QStringLiteral("%1 %2 %3").arg(wrap(where.column),
where.comparison,
parameter(where.value));
}
QString Grammar::whereNested(const WhereConditionItem &where) const
{
/* Here we will calculate what portion of the string we need to remove. If this
is a join clause query, we need to remove the "on" portion of the SQL and
if it is a normal query we need to take the leading "where" of queries. */
auto compiled = compileWheres(*where.nestedQuery);
const auto offset = compiled.indexOf(SPACE) + 1;
return PARENTH_ONE.arg(compiled.remove(0, offset));
}
QString Grammar::whereColumn(const WhereConditionItem &where) const
{
/* In this where type where.column contains first column and where,value contains
second column. */
return QStringLiteral("%1 %2 %3").arg(wrap(where.column),
where.comparison,
wrap(where.columnTwo));
}
QString Grammar::whereIn(const WhereConditionItem &where) const
{
if (where.values.isEmpty())
return QStringLiteral("0 = 1");
return QStringLiteral("%1 in (%2)").arg(wrap(where.column),
parametrize(where.values));
}
QString Grammar::whereNotIn(const WhereConditionItem &where) const
{
if (where.values.isEmpty())
return QStringLiteral("1 = 1");
return QStringLiteral("%1 not in (%2)").arg(wrap(where.column),
parametrize(where.values));
}
QString Grammar::whereNull(const WhereConditionItem &where) const
{
return QStringLiteral("%1 is null").arg(wrap(where.column));
}
QString Grammar::whereNotNull(const WhereConditionItem &where) const
{
return QStringLiteral("%1 is not null").arg(wrap(where.column));
}
QString Grammar::whereRaw(const WhereConditionItem &where) const
{
return where.sql;
}
QString Grammar::whereExists(const WhereConditionItem &where) const
{
return QStringLiteral("exists (%1)").arg(compileSelect(*where.nestedQuery));
}
QString Grammar::whereNotExists(const WhereConditionItem &where) const
{
return QStringLiteral("not exists (%1)").arg(compileSelect(*where.nestedQuery));
}
QStringList
Grammar::compileInsertToVector(const QVector<QVariantMap> &values) const
{
/* We need to build a list of parameter place-holders of values that are bound
to the query. Each insert should have the exact same amount of parameter
bindings so we will loop through the record and parameterize them all. */
QStringList compiledParameters;
compiledParameters.reserve(values.size());
for (const auto &valuesMap : values)
compiledParameters << PARENTH_ONE.arg(parametrize(valuesMap));
return compiledParameters;
}
QString
Grammar::compileUpdateColumns(const QVector<UpdateItem> &values) const
{
QStringList compiledAssignments;
compiledAssignments.reserve(values.size());
for (const auto &assignment : values)
compiledAssignments << QStringLiteral("%1 = %2").arg(
wrap(assignment.column),
parameter(assignment.value));
return compiledAssignments.join(COMMA);
}
QString
Grammar::compileUpdateWithoutJoins(const QueryBuilder &/*unused*/, const QString &table,
const QString &columns, const QString &wheres) const
{
// The table argument is already wrapped
return QStringLiteral("update %1 set %2 %3").arg(table, columns, wheres);
}
QString
Grammar::compileUpdateWithJoins(const QueryBuilder &query, const QString &table,
const QString &columns, const QString &wheres) const
{
const auto joins = compileJoins(query);
// The table argument is already wrapped
return QStringLiteral("update %1 %2 set %3 %4").arg(table, joins, columns, wheres);
}
QString
Grammar::compileDeleteWithoutJoins(const QueryBuilder &/*unused*/, const QString &table,
const QString &wheres) const
{
// The table argument is already wrapped
return QStringLiteral("delete from %1 %2").arg(table, wheres);
}
QString Grammar::compileDeleteWithJoins(const QueryBuilder &query, const QString &table,
const QString &wheres) const
{
const auto alias = getAliasFromFrom(table);
const auto joins = compileJoins(query);
/* Alias has to be after the delete keyword and aliased table definition after the
from keyword. */
return QStringLiteral("delete %1 from %2 %3 %4").arg(alias, table, joins, wheres);
}
QString Grammar::concatenate(const QStringList &segments) const
{
QString result;
for (const auto &segment : segments) {
if (segment.isEmpty())
continue;
result += QStringLiteral("%1 ").arg(segment);
}
return result.trimmed();
}
QString Grammar::removeLeadingBoolean(QString statement) const
{
// Skip all whitespaces after and/or, to avoid trimmed() for performance reasons
const auto firstChar = [&statement](const auto from)
{
for (auto i = from; i < statement.size(); ++i)
if (statement.at(i) != SPACE)
return i;
// Return initial value if space has not been found, should never happen :/
return from;
};
// RegExp not used for performance reasons
/* Before and/or could not be whitespace, current implementation doesn't include
whitespaces before. */
if (statement.startsWith(QLatin1String("and ")))
return statement.mid(firstChar(4));
if (statement.startsWith(QLatin1String("or ")))
return statement.mid(firstChar(3));
return statement;
}
QVector<std::reference_wrapper<const QVariant>>
Grammar::flatBindingsForUpdateDelete(const BindingsMap &bindings,
const QVector<BindingType> &exclude) const
{
QVector<std::reference_wrapper<const QVariant>> cleanBindingsFlatten;
for (auto itBindingVector = bindings.constBegin();
itBindingVector != bindings.constEnd(); ++itBindingVector)
if (exclude.contains(itBindingVector.key()))
continue;
else
for (const auto &binding : itBindingVector.value())
cleanBindingsFlatten.append(std::cref(binding));
return cleanBindingsFlatten;
}
} // namespace Orm::Query::Grammars
TINYORM_END_COMMON_NAMESPACE
| 34.099458 | 188 | 0.659808 | MrAhmedSayedAli |
ff2124babab6b9c1c6734feb66c531de585a0f08 | 3,082 | cpp | C++ | src/vsg/vk/Sampler.cpp | XenonofArcticus/VulkanSceneGraphPrototype | 2118ff8deb1078625bd09d4435757fdf346dffb7 | [
"MIT"
] | null | null | null | src/vsg/vk/Sampler.cpp | XenonofArcticus/VulkanSceneGraphPrototype | 2118ff8deb1078625bd09d4435757fdf346dffb7 | [
"MIT"
] | null | null | null | src/vsg/vk/Sampler.cpp | XenonofArcticus/VulkanSceneGraphPrototype | 2118ff8deb1078625bd09d4435757fdf346dffb7 | [
"MIT"
] | null | null | null | /* <editor-fold desc="MIT License">
Copyright(c) 2018 Robert Osfield
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.
</editor-fold> */
#include <vsg/vk/Sampler.h>
using namespace vsg;
Sampler::Sampler(VkSampler sampler, Device* device, AllocationCallbacks* allocator) :
_sampler(sampler),
_device(device),
_allocator(allocator)
{
}
Sampler::~Sampler()
{
if (_sampler)
{
vkDestroySampler(*_device, _sampler, _allocator);
}
}
Sampler::Result Sampler::create(Device* device, const VkSamplerCreateInfo& createSamplerInfo, AllocationCallbacks* allocator)
{
if (!device)
{
return Result("Error: vsg::Sampler::create(...) failed to create vkSampler, undefined Device.", VK_ERROR_INVALID_EXTERNAL_HANDLE);
}
VkSampler sampler;
VkResult result = vkCreateSampler(*device, &createSamplerInfo, allocator, &sampler);
if (result == VK_SUCCESS)
{
return Result(new Sampler(sampler, device, allocator));
}
else
{
return Result("Error: Failed to create vkSampler.", result);
}
}
Sampler::Result Sampler::create(Device* device, AllocationCallbacks* allocator)
{
VkSamplerCreateInfo samplerInfo = {};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.minFilter = VK_FILTER_LINEAR;
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
#if 1
// requres Logical device to have deviceFeatures.samplerAnisotropy = VK_TRUE; set when creating the vsg::Deivce
samplerInfo.anisotropyEnable = VK_TRUE;
samplerInfo.maxAnisotropy = 16;
#else
samplerInfo.anisotropyEnable = VK_FALSE;
samplerInfo.maxAnisotropy = 1;
#endif
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
return create(device, samplerInfo, allocator);
}
| 41.093333 | 460 | 0.758923 | XenonofArcticus |
ff25a359fb700b9ce74f7c40d051283646c5d0ef | 16,430 | hpp | C++ | include/eve/module/proba/regular/impl/normal_distribution.hpp | the-moisrex/eve | 80b52663eefee11460abb0aedf4158a5067cf7dc | [
"MIT"
] | 340 | 2020-09-16T21:12:48.000Z | 2022-03-28T15:40:33.000Z | include/eve/module/proba/regular/impl/normal_distribution.hpp | the-moisrex/eve | 80b52663eefee11460abb0aedf4158a5067cf7dc | [
"MIT"
] | 383 | 2020-09-17T06:56:35.000Z | 2022-03-13T15:58:53.000Z | include/eve/module/proba/regular/impl/normal_distribution.hpp | the-moisrex/eve | 80b52663eefee11460abb0aedf4158a5067cf7dc | [
"MIT"
] | 28 | 2021-02-27T23:11:23.000Z | 2022-03-25T12:31:29.000Z | //==================================================================================================
/*
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
*/
//==================================================================================================
#pragma once
#include <eve/concept/value.hpp>
#include <eve/constant/half.hpp>
#include <eve/constant/mhalf.hpp>
#include <eve/constant/one.hpp>
#include <eve/constant/sqrt_2.hpp>
#include <eve/constant/sqrt_2o_2.hpp>
#include <eve/constant/zero.hpp>
#include <eve/detail/apply_over.hpp>
#include <eve/detail/kumi.hpp>
#include <eve/detail/implementation.hpp>
#include <eve/detail/skeleton_calls.hpp>
#include <eve/function/abs.hpp>
#include <eve/function/all.hpp>
#include <eve/function/cospi.hpp>
#include <eve/function/erfc.hpp>
#include <eve/function/erfc_inv.hpp>
#include <eve/function/exp.hpp>
#include <eve/function/fma.hpp>
#include <eve/function/is_finite.hpp>
#include <eve/function/is_gtz.hpp>
#include <eve/function/log.hpp>
#include <eve/function/log1p.hpp>
#include <eve/function/raw.hpp>
#include <eve/function/rec.hpp>
#include <eve/function/sqr.hpp>
#include <eve/function/sqrt.hpp>
#include <eve/module/real/core/detail/generic/horn.hpp>
#include <eve/module/proba/detail/attributes.hpp>
#include <eve/module/proba/detail/urg01.hpp>
#include <eve/platform.hpp>
#include <concepts>
#include <type_traits>
namespace eve
{
namespace detail
{
template < typename G, typename R> EVE_FORCEINLINE
auto box_muller(G & gen, as<R> const & ) noexcept
{
auto x1 = detail::urg01(gen, as<R>());
auto x2 = detail::urg01(gen, as<R>());
auto rho = eve::sqrt(-2*eve::log1p(-x1));
return rho*half_circle(cospi)(2*x2);
}
}
template < typename T, typename U, typename Internal = T>
struct normal_distribution{};
template < floating_real_value T, floating_real_value U>
requires compatible_values<T, U>
struct normal_distribution<T, U>
{
using is_distribution_t = void;
using m_type = T;
using s_type = U;
using value_type = common_compatible_t<T, U>;
using parameters = struct { value_type m; value_type s; };
normal_distribution(T m_, U s_)
: m(m_), s(s_)
{
EVE_ASSERT(all(is_gtz(s) && is_finite(s)), "s must be strictly positive and finite");
EVE_ASSERT(all(is_finite(m)), "m must be finite");
}
normal_distribution(parameters const & p)
: m(p.m), s(p.s)
{
EVE_ASSERT(all(is_gtz(s) && is_finite(s)), "s must be strictly positive and finite");
EVE_ASSERT(all(is_finite(m)), "m must be finite");
}
template < typename G, typename R = value_type> auto operator()(G & gen, as<R> const & )
requires scalar_value<value_type>
{
return fma(m, detail::box_muller(gen, as<R>()), s);
}
parameters params() const noexcept
{
return { .m = m, .s = s };
}
m_type m;
s_type s;
};
template < floating_real_value U>
struct normal_distribution<callable_zero_, U>
{
using is_distribution_t = void;
using m_type = callable_zero_;
using s_type = U;
using value_type = U;
using parameters = struct { callable_zero_ m; value_type s;};
normal_distribution(callable_zero_ const&, U s_)
: s(s_)
{
EVE_ASSERT(all(is_gtz(s) && is_finite(s)), "s must be strictly positive and finite");
}
normal_distribution(parameters const & p)
: s(p.s)
{
EVE_ASSERT(all(is_gtz(s) && is_finite(s)), "s must be strictly positive and finite");
}
template < typename G, typename R = value_type> auto operator()(G & gen, as<R> const & )
requires scalar_value<value_type>
{
return detail::box_muller(gen, as<R>())*s;
}
parameters params() noexcept
{
return { .m = zero, .s = s };
}
s_type s;
};
template < floating_real_value T>
struct normal_distribution<T, callable_one_>
{
using is_distribution_t = void;
using m_type = T;
using s_type = decltype(eve::one);
using value_type = T;
using parameters = struct { value_type m; callable_one_ s;};
normal_distribution(T m_, callable_one_ const &)
: m(m_)
{
EVE_ASSERT(all(is_finite(m)), "m must be finite");
}
normal_distribution(parameters const & p)
: m(p.m)
{
EVE_ASSERT(all(is_finite(m)), "m must be finite");
}
template < typename G, typename R = value_type> auto operator()(G & gen, as<R> const & )
requires scalar_value<value_type>
{
return detail::box_muller(gen, as<R>())+m;
}
parameters params() noexcept
{
return { .m = m, .s = one };
}
m_type m;
};
template<typename T, typename U> normal_distribution(T,U) -> normal_distribution<T,U>;
template < floating_real_value T>
struct normal_distribution<callable_zero_, callable_one_, T>
{
using is_distribution_t = void;
using m_type = callable_zero_;
using s_type = callable_one_;
using value_type = T;
using parameters = struct { callable_zero_ m; callable_one_ s;};
normal_distribution(parameters const & ) { }
template < typename G, typename R = value_type> auto operator()(G & gen, as<R> const & )
requires scalar_value<value_type>
{
return detail::box_muller(gen, as<R>());
}
parameters params() noexcept
{
return { .m = zero, .s = one };
}
constexpr normal_distribution( as<T> const&) {}
};
template<typename T> normal_distribution(as<T> const&) -> normal_distribution<callable_zero_, callable_one_, T>;
template<floating_real_value T>
inline constexpr auto normal_distribution_01 = normal_distribution<callable_zero_, callable_one_, T>(as<T>{});
namespace detail
{
//////////////////////////////////////////////////////
/// cdf
template<typename T, typename U, floating_value V
, typename I = T>
EVE_FORCEINLINE auto cdf_(EVE_SUPPORTS(cpu_)
, normal_distribution<T, U, I> const & d
, V const &x ) noexcept
{
if constexpr(floating_value<T> && floating_value<U>)
return half(as(x))*erfc(sqrt_2o_2(as(x))*((d.m-x)/d.s));
else if constexpr(std::same_as<T, callable_zero_> && floating_value<U>)
return half(as(x))*erfc(sqrt_2o_2(as(x))*(-x/d.s));
else if constexpr(std::same_as<U, callable_one_> && floating_value<T>)
return half(as(x))*erfc(sqrt_2o_2(as(x))*((d.m-x)));
else
return half(as(x))*erfc(sqrt_2o_2(as(x))*(-x));
}
template<typename T, typename U, floating_value V
, typename I = T>
EVE_FORCEINLINE auto cdf_(EVE_SUPPORTS(cpu_)
, raw_type const &
, normal_distribution<T, U, I> const &d
, V const &x ) noexcept
{
using elt_t = element_type_t<T>;
if constexpr(std::same_as<elt_t, float>)
{
auto eval = [](auto l)
{
auto al = eve::abs(l);
auto k = rec(fma(T(0.2316419f),al,one(as(l))));
auto w = horn<T
, 0x3ea385fa // 0.31938153f
, 0xbeb68f87 // -0.356563782f,
, 0x3fe40778 // 1.781477937f,
, 0xbfe91eea // -1.821255978f,
, 0x3faa466f // 1.330274429f,
>(k);
auto invsqrt_2pi = T(0.39894228040143267793994605993438186847585863116493);
w*=k*invsqrt_2pi*eve::exp(-sqr(l)*half(as(l)));
return if_else(is_gtz(l),oneminus(w),w);
};
if constexpr(floating_value<T> && floating_value<U>)
return eval((x-d.m)/d.s);
else if constexpr(std::same_as<T, callable_zero_> && floating_value<U>)
return eval(x/d.s);
else if constexpr(std::same_as<U, callable_one_> && floating_value<T>)
return eval(x-d.m);
else
return eval(x);
}
else return cdf(d, x);
}
//////////////////////////////////////////////////////
/// pdf
template<typename T, typename U, floating_value V
, typename I = T>
EVE_FORCEINLINE auto pdf_(EVE_SUPPORTS(cpu_)
, normal_distribution<T, U, I> const & d
, V const &x ) noexcept
{
auto invsqrt_2pi = V(0.39894228040143267793994605993438186847585863116493);
if constexpr(floating_value<T> && floating_value<U>)
{
auto invsig = rec(d.s);
return eve::exp(mhalf(as(x))*sqr((x-d.m)*invsig))*invsqrt_2pi*invsig;
}
else if constexpr(std::same_as<T, callable_zero_> && floating_value<U>)
{
auto invsig = rec(d.s);
return eve::exp(mhalf(as(x))*sqr(x*invsig))*invsqrt_2pi*invsig;
}
else if constexpr(std::same_as<U, callable_one_> && floating_value<T>)
{
return eve::exp(mhalf(as(x))*sqr((x-d.m)))*invsqrt_2pi;
}
else
return eve::exp(mhalf(as(x))*sqr(x))*invsqrt_2pi;
}
//////////////////////////////////////////////////////
/// mgf
template<typename T, typename U, floating_value V
, typename I = T>
EVE_FORCEINLINE auto mgf_(EVE_SUPPORTS(cpu_)
, normal_distribution<T, U, I> const & d
, V const &x ) noexcept
{
auto invsqrt_2pi = V(0.39894228040143267793994605993438186847585863116493);
if constexpr(floating_value<T> && floating_value<U>)
{
return eve::exp(d.m*x+sqr(d.s*x)*half(as(x)));
}
else if constexpr(std::same_as<T, callable_zero_> && floating_value<U>)
{
return eve::exp(sqr(d.s*x)*half(as(x)));
}
else if constexpr(std::same_as<U, callable_one_> && floating_value<T>)
{
return eve::exp(d.m*x+sqr(x)*half(as(x)));
}
else
return eve::exp(sqr(d)*half(as(x)));
}
//////////////////////////////////////////////////////
/// invcdf
template<typename T, typename U, floating_value V
, typename I = T>
EVE_FORCEINLINE auto invcdf_(EVE_SUPPORTS(cpu_)
, normal_distribution<T, U, I> const & d
, V const &x ) noexcept
{
if constexpr(floating_value<T> && floating_value<U>)
{
return fma(-sqrt_2(as(x))*erfc_inv( T(2)*x), d.s, d.m);
}
else if constexpr(std::same_as<T, callable_zero_> && floating_value<U>)
{
return -sqrt_2(as(x))*erfc_inv(2*x)*d.s;
}
else if constexpr(std::same_as<U, callable_one_> && floating_value<T>)
{
return -sqrt_2(as(x))*erfc_inv(2*x)+d.m;
}
else
return -sqrt_2(as(x))*erfc_inv(2*x);
}
//////////////////////////////////////////////////////
/// median
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto median_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & d) noexcept
{
if constexpr (floating_value<T>)
return d.m;
else if constexpr (floating_value<U>)
return zero(as<U>());
else
return zero(as<I>());
}
//////////////////////////////////////////////////////
/// mean
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto mean_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const &d) noexcept
{
return median(d);
}
//////////////////////////////////////////////////////
/// mode
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto mode_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & d) noexcept
{
return median(d);
}
//////////////////////////////////////////////////////
/// entropy
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto entropy_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & d) noexcept
{
auto twopie = T(17.0794684453471341309271017390931489900697770715304);
if constexpr (floating_value<U>)
return half(as<T>())*log(twopie*sqr(d.s));
else
return half(as<T>())*log(twopie);
}
//////////////////////////////////////////////////////
/// skewness
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto skewness_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & ) noexcept
{
return I(0);
}
//////////////////////////////////////////////////////
/// kurtosis
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto kurtosis_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & ) noexcept
{
return I(0);
}
//////////////////////////////////////////////////////
/// mad
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto mad_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & d) noexcept
{
auto sqrt_2o_pi = T(0.79788456080286535587989211986876373695171726232986);
if constexpr (floating_value<U>)
return d.s*sqrt_2o_pi;
else
return sqrt_2o_pi;
}
//////////////////////////////////////////////////////
/// var
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto var_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & d) noexcept
{
if constexpr (floating_value<U>)
return sqr(d.s);
else
return one(as<I>());
}
//////////////////////////////////////////////////////
/// stdev
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto stdev_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & d) noexcept
{
if constexpr (floating_value<U>)
return d.s;
else
return one(as<I>());
}
//////////////////////////////////////////////////////
/// kullback
template<typename T, typename U, typename I = T>
EVE_FORCEINLINE auto kullback_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & d1
, normal_distribution<T,U,I> const & d2 ) noexcept
{
if constexpr (floating_value<T> && floating_value<U>)
{
auto srap = d1.s/d2.s;
return half(as<T>())*(dec(sqr(srap)+sqr((d1.m-d2.m)/d2.s))+T(2)*eve::log(srap));
}
else if constexpr(std::same_as<T, callable_zero_> && floating_value<U>)
{
auto srap = d1.s/d2.s;
return half(as<T>())*(dec(sqr(srap))+T(2)*eve::log(srap));
}
else if constexpr(std::same_as<U, callable_one_> && floating_value<T>)
{
return half(as<T>())*dec(oneminus(sqr((d1.m-d2.m)/d2.s)));
}
else
return zero(as<I>());
}
//////////////////////////////////////////////////////
/// confidence
template<typename T, typename U, floating_real_value R
, floating_real_value V, floating_real_value A, typename I = T>
EVE_FORCEINLINE auto confidence_(EVE_SUPPORTS(cpu_)
, normal_distribution<T,U,I> const & d
, R const & x
, std::array<V, 4> const & cov
, A const & alpha ) noexcept
{
using v_t = typename normal_distribution<T,U,I>::value_type;
R z = x;
auto normz = -invcdf(normal_distribution_01<I>, alpha*v_t(0.5));
auto halfwidth = normz;
if constexpr(floating_real_value<T> && floating_real_value<U>)
z = (z-d.m)/d.s;
else if constexpr(floating_real_value<T>)
z -= d.m;
else if constexpr(floating_real_value<U>)
z /= d.s;
auto zvar = fma(fma(cov[3], z, 2*cov[1]), z, cov[0]);
halfwidth *= eve::sqrt(zvar);
if constexpr(floating_real_value<U>)
halfwidth /= d.s;
auto d01 = normal_distribution_01<I>;
return kumi::make_tuple(cdf(d01, z), cdf(d01, z-halfwidth), cdf(d01, z+halfwidth));
}
}
}
| 33.125 | 115 | 0.545344 | the-moisrex |
ff2bdd4d08a602a6a1b92713e4e5f35d635e477f | 546 | cpp | C++ | person.cpp | vpoulailleau/cpp_game | 371bbd7352a380b5f5cf8ee5767f0e797e7e0362 | [
"BSD-3-Clause"
] | 1 | 2020-02-23T13:14:46.000Z | 2020-02-23T13:14:46.000Z | person.cpp | vpoulailleau/cpp_game | 371bbd7352a380b5f5cf8ee5767f0e797e7e0362 | [
"BSD-3-Clause"
] | null | null | null | person.cpp | vpoulailleau/cpp_game | 371bbd7352a380b5f5cf8ee5767f0e797e7e0362 | [
"BSD-3-Clause"
] | 1 | 2020-10-12T06:53:26.000Z | 2020-10-12T06:53:26.000Z | #include "person.h"
void Person::fight(Person &other)
{
_fight_once(other);
other._fight_once(*this);
}
void Person::_fight_once(Person &other)
{
cout << " - " << get_name() << " launching the attack: ";
shout();
cout << endl;
int dice = rand() % 6 + 1;
cout << " - dice: " << dice << endl;
if (dice <= get_skill())
{
cout << " - ATTACK" << endl;
other.loose_health(get_force());
}
else
{
cout << " - missed attack" << endl;
}
} | 21.84 | 68 | 0.474359 | vpoulailleau |
ff2d911365728144b1b467351756589a24b77e8f | 15,224 | cpp | C++ | cdb/src/v20170320/model/CreateCloneInstanceRequest.cpp | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | 1 | 2022-01-27T09:27:34.000Z | 2022-01-27T09:27:34.000Z | cdb/src/v20170320/model/CreateCloneInstanceRequest.cpp | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | null | null | null | cdb/src/v20170320/model/CreateCloneInstanceRequest.cpp | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/cdb/v20170320/model/CreateCloneInstanceRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Cdb::V20170320::Model;
using namespace std;
CreateCloneInstanceRequest::CreateCloneInstanceRequest() :
m_instanceIdHasBeenSet(false),
m_specifiedRollbackTimeHasBeenSet(false),
m_specifiedBackupIdHasBeenSet(false),
m_uniqVpcIdHasBeenSet(false),
m_uniqSubnetIdHasBeenSet(false),
m_memoryHasBeenSet(false),
m_volumeHasBeenSet(false),
m_instanceNameHasBeenSet(false),
m_securityGroupHasBeenSet(false),
m_resourceTagsHasBeenSet(false),
m_cpuHasBeenSet(false),
m_protectModeHasBeenSet(false),
m_deployModeHasBeenSet(false),
m_slaveZoneHasBeenSet(false),
m_backupZoneHasBeenSet(false),
m_deviceTypeHasBeenSet(false),
m_instanceNodesHasBeenSet(false),
m_deployGroupIdHasBeenSet(false),
m_dryRunHasBeenSet(false),
m_cageIdHasBeenSet(false),
m_projectIdHasBeenSet(false)
{
}
string CreateCloneInstanceRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_instanceIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InstanceId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_instanceId.c_str(), allocator).Move(), allocator);
}
if (m_specifiedRollbackTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SpecifiedRollbackTime";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_specifiedRollbackTime.c_str(), allocator).Move(), allocator);
}
if (m_specifiedBackupIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SpecifiedBackupId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_specifiedBackupId, allocator);
}
if (m_uniqVpcIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "UniqVpcId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_uniqVpcId.c_str(), allocator).Move(), allocator);
}
if (m_uniqSubnetIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "UniqSubnetId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_uniqSubnetId.c_str(), allocator).Move(), allocator);
}
if (m_memoryHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Memory";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_memory, allocator);
}
if (m_volumeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Volume";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_volume, allocator);
}
if (m_instanceNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InstanceName";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_instanceName.c_str(), allocator).Move(), allocator);
}
if (m_securityGroupHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SecurityGroup";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_securityGroup.begin(); itr != m_securityGroup.end(); ++itr)
{
d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_resourceTagsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ResourceTags";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_resourceTags.begin(); itr != m_resourceTags.end(); ++itr, ++i)
{
d[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(d[key.c_str()][i], allocator);
}
}
if (m_cpuHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Cpu";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_cpu, allocator);
}
if (m_protectModeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ProtectMode";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_protectMode, allocator);
}
if (m_deployModeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DeployMode";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_deployMode, allocator);
}
if (m_slaveZoneHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SlaveZone";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_slaveZone.c_str(), allocator).Move(), allocator);
}
if (m_backupZoneHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "BackupZone";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_backupZone.c_str(), allocator).Move(), allocator);
}
if (m_deviceTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DeviceType";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_deviceType.c_str(), allocator).Move(), allocator);
}
if (m_instanceNodesHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InstanceNodes";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_instanceNodes, allocator);
}
if (m_deployGroupIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DeployGroupId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_deployGroupId.c_str(), allocator).Move(), allocator);
}
if (m_dryRunHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DryRun";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_dryRun, allocator);
}
if (m_cageIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "CageId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_cageId.c_str(), allocator).Move(), allocator);
}
if (m_projectIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ProjectId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_projectId, allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string CreateCloneInstanceRequest::GetInstanceId() const
{
return m_instanceId;
}
void CreateCloneInstanceRequest::SetInstanceId(const string& _instanceId)
{
m_instanceId = _instanceId;
m_instanceIdHasBeenSet = true;
}
bool CreateCloneInstanceRequest::InstanceIdHasBeenSet() const
{
return m_instanceIdHasBeenSet;
}
string CreateCloneInstanceRequest::GetSpecifiedRollbackTime() const
{
return m_specifiedRollbackTime;
}
void CreateCloneInstanceRequest::SetSpecifiedRollbackTime(const string& _specifiedRollbackTime)
{
m_specifiedRollbackTime = _specifiedRollbackTime;
m_specifiedRollbackTimeHasBeenSet = true;
}
bool CreateCloneInstanceRequest::SpecifiedRollbackTimeHasBeenSet() const
{
return m_specifiedRollbackTimeHasBeenSet;
}
int64_t CreateCloneInstanceRequest::GetSpecifiedBackupId() const
{
return m_specifiedBackupId;
}
void CreateCloneInstanceRequest::SetSpecifiedBackupId(const int64_t& _specifiedBackupId)
{
m_specifiedBackupId = _specifiedBackupId;
m_specifiedBackupIdHasBeenSet = true;
}
bool CreateCloneInstanceRequest::SpecifiedBackupIdHasBeenSet() const
{
return m_specifiedBackupIdHasBeenSet;
}
string CreateCloneInstanceRequest::GetUniqVpcId() const
{
return m_uniqVpcId;
}
void CreateCloneInstanceRequest::SetUniqVpcId(const string& _uniqVpcId)
{
m_uniqVpcId = _uniqVpcId;
m_uniqVpcIdHasBeenSet = true;
}
bool CreateCloneInstanceRequest::UniqVpcIdHasBeenSet() const
{
return m_uniqVpcIdHasBeenSet;
}
string CreateCloneInstanceRequest::GetUniqSubnetId() const
{
return m_uniqSubnetId;
}
void CreateCloneInstanceRequest::SetUniqSubnetId(const string& _uniqSubnetId)
{
m_uniqSubnetId = _uniqSubnetId;
m_uniqSubnetIdHasBeenSet = true;
}
bool CreateCloneInstanceRequest::UniqSubnetIdHasBeenSet() const
{
return m_uniqSubnetIdHasBeenSet;
}
int64_t CreateCloneInstanceRequest::GetMemory() const
{
return m_memory;
}
void CreateCloneInstanceRequest::SetMemory(const int64_t& _memory)
{
m_memory = _memory;
m_memoryHasBeenSet = true;
}
bool CreateCloneInstanceRequest::MemoryHasBeenSet() const
{
return m_memoryHasBeenSet;
}
int64_t CreateCloneInstanceRequest::GetVolume() const
{
return m_volume;
}
void CreateCloneInstanceRequest::SetVolume(const int64_t& _volume)
{
m_volume = _volume;
m_volumeHasBeenSet = true;
}
bool CreateCloneInstanceRequest::VolumeHasBeenSet() const
{
return m_volumeHasBeenSet;
}
string CreateCloneInstanceRequest::GetInstanceName() const
{
return m_instanceName;
}
void CreateCloneInstanceRequest::SetInstanceName(const string& _instanceName)
{
m_instanceName = _instanceName;
m_instanceNameHasBeenSet = true;
}
bool CreateCloneInstanceRequest::InstanceNameHasBeenSet() const
{
return m_instanceNameHasBeenSet;
}
vector<string> CreateCloneInstanceRequest::GetSecurityGroup() const
{
return m_securityGroup;
}
void CreateCloneInstanceRequest::SetSecurityGroup(const vector<string>& _securityGroup)
{
m_securityGroup = _securityGroup;
m_securityGroupHasBeenSet = true;
}
bool CreateCloneInstanceRequest::SecurityGroupHasBeenSet() const
{
return m_securityGroupHasBeenSet;
}
vector<TagInfo> CreateCloneInstanceRequest::GetResourceTags() const
{
return m_resourceTags;
}
void CreateCloneInstanceRequest::SetResourceTags(const vector<TagInfo>& _resourceTags)
{
m_resourceTags = _resourceTags;
m_resourceTagsHasBeenSet = true;
}
bool CreateCloneInstanceRequest::ResourceTagsHasBeenSet() const
{
return m_resourceTagsHasBeenSet;
}
int64_t CreateCloneInstanceRequest::GetCpu() const
{
return m_cpu;
}
void CreateCloneInstanceRequest::SetCpu(const int64_t& _cpu)
{
m_cpu = _cpu;
m_cpuHasBeenSet = true;
}
bool CreateCloneInstanceRequest::CpuHasBeenSet() const
{
return m_cpuHasBeenSet;
}
int64_t CreateCloneInstanceRequest::GetProtectMode() const
{
return m_protectMode;
}
void CreateCloneInstanceRequest::SetProtectMode(const int64_t& _protectMode)
{
m_protectMode = _protectMode;
m_protectModeHasBeenSet = true;
}
bool CreateCloneInstanceRequest::ProtectModeHasBeenSet() const
{
return m_protectModeHasBeenSet;
}
int64_t CreateCloneInstanceRequest::GetDeployMode() const
{
return m_deployMode;
}
void CreateCloneInstanceRequest::SetDeployMode(const int64_t& _deployMode)
{
m_deployMode = _deployMode;
m_deployModeHasBeenSet = true;
}
bool CreateCloneInstanceRequest::DeployModeHasBeenSet() const
{
return m_deployModeHasBeenSet;
}
string CreateCloneInstanceRequest::GetSlaveZone() const
{
return m_slaveZone;
}
void CreateCloneInstanceRequest::SetSlaveZone(const string& _slaveZone)
{
m_slaveZone = _slaveZone;
m_slaveZoneHasBeenSet = true;
}
bool CreateCloneInstanceRequest::SlaveZoneHasBeenSet() const
{
return m_slaveZoneHasBeenSet;
}
string CreateCloneInstanceRequest::GetBackupZone() const
{
return m_backupZone;
}
void CreateCloneInstanceRequest::SetBackupZone(const string& _backupZone)
{
m_backupZone = _backupZone;
m_backupZoneHasBeenSet = true;
}
bool CreateCloneInstanceRequest::BackupZoneHasBeenSet() const
{
return m_backupZoneHasBeenSet;
}
string CreateCloneInstanceRequest::GetDeviceType() const
{
return m_deviceType;
}
void CreateCloneInstanceRequest::SetDeviceType(const string& _deviceType)
{
m_deviceType = _deviceType;
m_deviceTypeHasBeenSet = true;
}
bool CreateCloneInstanceRequest::DeviceTypeHasBeenSet() const
{
return m_deviceTypeHasBeenSet;
}
int64_t CreateCloneInstanceRequest::GetInstanceNodes() const
{
return m_instanceNodes;
}
void CreateCloneInstanceRequest::SetInstanceNodes(const int64_t& _instanceNodes)
{
m_instanceNodes = _instanceNodes;
m_instanceNodesHasBeenSet = true;
}
bool CreateCloneInstanceRequest::InstanceNodesHasBeenSet() const
{
return m_instanceNodesHasBeenSet;
}
string CreateCloneInstanceRequest::GetDeployGroupId() const
{
return m_deployGroupId;
}
void CreateCloneInstanceRequest::SetDeployGroupId(const string& _deployGroupId)
{
m_deployGroupId = _deployGroupId;
m_deployGroupIdHasBeenSet = true;
}
bool CreateCloneInstanceRequest::DeployGroupIdHasBeenSet() const
{
return m_deployGroupIdHasBeenSet;
}
bool CreateCloneInstanceRequest::GetDryRun() const
{
return m_dryRun;
}
void CreateCloneInstanceRequest::SetDryRun(const bool& _dryRun)
{
m_dryRun = _dryRun;
m_dryRunHasBeenSet = true;
}
bool CreateCloneInstanceRequest::DryRunHasBeenSet() const
{
return m_dryRunHasBeenSet;
}
string CreateCloneInstanceRequest::GetCageId() const
{
return m_cageId;
}
void CreateCloneInstanceRequest::SetCageId(const string& _cageId)
{
m_cageId = _cageId;
m_cageIdHasBeenSet = true;
}
bool CreateCloneInstanceRequest::CageIdHasBeenSet() const
{
return m_cageIdHasBeenSet;
}
uint64_t CreateCloneInstanceRequest::GetProjectId() const
{
return m_projectId;
}
void CreateCloneInstanceRequest::SetProjectId(const uint64_t& _projectId)
{
m_projectId = _projectId;
m_projectIdHasBeenSet = true;
}
bool CreateCloneInstanceRequest::ProjectIdHasBeenSet() const
{
return m_projectIdHasBeenSet;
}
| 26.158076 | 106 | 0.723529 | TencentCloud |
ff2e166cc6cad8ca49e2c417ff5b2136393d7f41 | 86,479 | cc | C++ | components/sync/engine_impl/sync_encryption_handler_impl.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/sync/engine_impl/sync_encryption_handler_impl.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/sync/engine_impl/sync_encryption_handler_impl.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2012 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 "components/sync/engine_impl/sync_encryption_handler_impl.h"
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include "base/base64.h"
#include "base/bind.h"
#include "base/containers/queue.h"
#include "base/feature_list.h"
#include "base/json/json_string_value_serializer.h"
#include "base/location.h"
#include "base/metrics/histogram_macros.h"
#include "base/sequenced_task_runner.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "components/sync/base/encryptor.h"
#include "components/sync/base/passphrase_enums.h"
#include "components/sync/base/sync_base_switches.h"
#include "components/sync/base/time.h"
#include "components/sync/engine/sync_engine_switches.h"
#include "components/sync/engine/sync_string_conversions.h"
#include "components/sync/protocol/encryption.pb.h"
#include "components/sync/protocol/nigori_specifics.pb.h"
#include "components/sync/protocol/sync.pb.h"
#include "components/sync/syncable/directory.h"
#include "components/sync/syncable/entry.h"
#include "components/sync/syncable/mutable_entry.h"
#include "components/sync/syncable/nigori_util.h"
#include "components/sync/syncable/read_node.h"
#include "components/sync/syncable/read_transaction.h"
#include "components/sync/syncable/syncable_base_transaction.h"
#include "components/sync/syncable/syncable_model_neutral_write_transaction.h"
#include "components/sync/syncable/syncable_read_transaction.h"
#include "components/sync/syncable/syncable_write_transaction.h"
#include "components/sync/syncable/user_share.h"
#include "components/sync/syncable/write_node.h"
#include "components/sync/syncable/write_transaction.h"
namespace syncer {
namespace {
// The maximum number of times we will automatically overwrite the nigori node
// because the encryption keys don't match (per chrome instantiation).
// We protect ourselves against nigori rollbacks, but it's possible two
// different clients might have contrasting view of what the nigori node state
// should be, in which case they might ping pong (see crbug.com/119207).
static const int kNigoriOverwriteLimit = 10;
// Enumeration of nigori keystore migration results (for use in UMA stats).
enum NigoriMigrationResult {
FAILED_TO_SET_DEFAULT_KEYSTORE,
FAILED_TO_SET_NONDEFAULT_KEYSTORE,
FAILED_TO_EXTRACT_DECRYPTOR,
FAILED_TO_EXTRACT_KEYBAG,
MIGRATION_SUCCESS_KEYSTORE_NONDEFAULT,
MIGRATION_SUCCESS_KEYSTORE_DEFAULT,
MIGRATION_SUCCESS_FROZEN_IMPLICIT,
MIGRATION_SUCCESS_CUSTOM,
MIGRATION_RESULT_SIZE,
};
enum NigoriMigrationState {
MIGRATED,
NOT_MIGRATED_CRYPTO_NOT_READY,
NOT_MIGRATED_NO_KEYSTORE_KEY,
NOT_MIGRATED_UNKNOWN_REASON,
MIGRATION_STATE_SIZE,
};
// The new passphrase state is sufficient to determine whether a nigori node
// is migrated to support keystore encryption. In addition though, we also
// want to verify the conditions for proper keystore encryption functionality.
// 1. Passphrase type is set.
// 2. Frozen keybag is true
// 3. If passphrase state is keystore, keystore_decryptor_token is set.
bool IsNigoriMigratedToKeystore(const sync_pb::NigoriSpecifics& nigori) {
// |passphrase_type| is always populated by modern clients, but may be missing
// in coming from an ancient client, from data that was never upgraded, or
// from the uninitialized NigoriSpecifics (e.g. sync was just enabled for this
// account).
if (!nigori.has_passphrase_type())
return false;
if (!nigori.keybag_is_frozen())
return false;
if (nigori.passphrase_type() == sync_pb::NigoriSpecifics::IMPLICIT_PASSPHRASE)
return false;
if (nigori.passphrase_type() ==
sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE &&
nigori.keystore_decryptor_token().blob().empty())
return false;
return true;
}
// Keystore Bootstrap Token helper methods.
// The bootstrap is a base64 encoded, encrypted, ListValue of keystore key
// strings, with the current keystore key as the last value in the list.
std::string PackKeystoreBootstrapToken(
const std::vector<std::string>& old_keystore_keys,
const std::string& current_keystore_key,
const Encryptor& encryptor) {
if (current_keystore_key.empty())
return std::string();
base::ListValue keystore_key_values;
for (size_t i = 0; i < old_keystore_keys.size(); ++i)
keystore_key_values.AppendString(old_keystore_keys[i]);
keystore_key_values.AppendString(current_keystore_key);
// Update the bootstrap token.
// The bootstrap is a base64 encoded, encrypted, ListValue of keystore key
// strings, with the current keystore key as the last value in the list.
std::string serialized_keystores;
JSONStringValueSerializer json(&serialized_keystores);
json.Serialize(keystore_key_values);
std::string encrypted_keystores;
encryptor.EncryptString(serialized_keystores, &encrypted_keystores);
std::string keystore_bootstrap;
base::Base64Encode(encrypted_keystores, &keystore_bootstrap);
return keystore_bootstrap;
}
bool UnpackKeystoreBootstrapToken(const std::string& keystore_bootstrap_token,
const Encryptor& encryptor,
std::vector<std::string>* old_keystore_keys,
std::string* current_keystore_key) {
if (keystore_bootstrap_token.empty())
return false;
std::string base64_decoded_keystore_bootstrap;
if (!base::Base64Decode(keystore_bootstrap_token,
&base64_decoded_keystore_bootstrap)) {
return false;
}
std::string decrypted_keystore_bootstrap;
if (!encryptor.DecryptString(base64_decoded_keystore_bootstrap,
&decrypted_keystore_bootstrap)) {
return false;
}
JSONStringValueDeserializer json(decrypted_keystore_bootstrap);
std::unique_ptr<base::Value> deserialized_keystore_keys(
json.Deserialize(nullptr, nullptr));
if (!deserialized_keystore_keys)
return false;
base::ListValue* internal_list_value = nullptr;
if (!deserialized_keystore_keys->GetAsList(&internal_list_value))
return false;
int number_of_keystore_keys = internal_list_value->GetSize();
if (!internal_list_value->GetString(number_of_keystore_keys - 1,
current_keystore_key)) {
return false;
}
old_keystore_keys->resize(number_of_keystore_keys - 1);
for (int i = 0; i < number_of_keystore_keys - 1; ++i)
internal_list_value->GetString(i, &(*old_keystore_keys)[i]);
return true;
}
// Returns the key derivation method to be used when a user sets a new
// custom passphrase.
KeyDerivationMethod GetDefaultKeyDerivationMethodForCustomPassphrase() {
if (base::FeatureList::IsEnabled(
switches::kSyncUseScryptForNewCustomPassphrases) &&
!base::FeatureList::IsEnabled(
switches::kSyncForceDisableScryptForCustomPassphrase)) {
return KeyDerivationMethod::SCRYPT_8192_8_11;
}
return KeyDerivationMethod::PBKDF2_HMAC_SHA1_1003;
}
KeyDerivationParams CreateKeyDerivationParamsForCustomPassphrase(
const base::RepeatingCallback<std::string()>& random_salt_generator) {
KeyDerivationMethod method =
GetDefaultKeyDerivationMethodForCustomPassphrase();
switch (method) {
case KeyDerivationMethod::PBKDF2_HMAC_SHA1_1003:
return KeyDerivationParams::CreateForPbkdf2();
case KeyDerivationMethod::SCRYPT_8192_8_11:
return KeyDerivationParams::CreateForScrypt(random_salt_generator.Run());
case KeyDerivationMethod::UNSUPPORTED:
break;
}
NOTREACHED();
return KeyDerivationParams::CreateWithUnsupportedMethod();
}
KeyDerivationMethod GetKeyDerivationMethodFromNigori(
const sync_pb::NigoriSpecifics& nigori) {
::google::protobuf::int32 proto_key_derivation_method =
nigori.custom_passphrase_key_derivation_method();
KeyDerivationMethod key_derivation_method =
ProtoKeyDerivationMethodToEnum(proto_key_derivation_method);
if (key_derivation_method == KeyDerivationMethod::SCRYPT_8192_8_11 &&
base::FeatureList::IsEnabled(
switches::kSyncForceDisableScryptForCustomPassphrase)) {
// Because scrypt is explicitly disabled, just behave as if it is an
// unsupported method.
key_derivation_method = KeyDerivationMethod::UNSUPPORTED;
}
if (key_derivation_method == KeyDerivationMethod::UNSUPPORTED) {
DLOG(WARNING) << "Unsupported key derivation method encountered: "
<< proto_key_derivation_method;
}
return key_derivation_method;
}
std::string GetScryptSaltFromNigori(const sync_pb::NigoriSpecifics& nigori) {
DCHECK_EQ(nigori.custom_passphrase_key_derivation_method(),
sync_pb::NigoriSpecifics::SCRYPT_8192_8_11);
std::string decoded_salt;
bool result = base::Base64Decode(
nigori.custom_passphrase_key_derivation_salt(), &decoded_salt);
DCHECK(result);
return decoded_salt;
}
KeyDerivationParams GetKeyDerivationParamsFromNigori(
const sync_pb::NigoriSpecifics& nigori) {
KeyDerivationMethod method = GetKeyDerivationMethodFromNigori(nigori);
switch (method) {
case KeyDerivationMethod::PBKDF2_HMAC_SHA1_1003:
return KeyDerivationParams::CreateForPbkdf2();
case KeyDerivationMethod::SCRYPT_8192_8_11:
return KeyDerivationParams::CreateForScrypt(
GetScryptSaltFromNigori(nigori));
case KeyDerivationMethod::UNSUPPORTED:
break;
}
return KeyDerivationParams::CreateWithUnsupportedMethod();
}
void UpdateNigoriSpecificsKeyDerivationParams(
const KeyDerivationParams& params,
sync_pb::NigoriSpecifics* nigori) {
DCHECK_EQ(nigori->passphrase_type(),
sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE);
DCHECK_NE(params.method(), KeyDerivationMethod::UNSUPPORTED);
nigori->set_custom_passphrase_key_derivation_method(
EnumKeyDerivationMethodToProto(params.method()));
if (params.method() == KeyDerivationMethod::SCRYPT_8192_8_11) {
// Persist the salt used for key derivation in Nigori if we're using scrypt.
std::string encoded_salt;
base::Base64Encode(params.scrypt_salt(), &encoded_salt);
nigori->set_custom_passphrase_key_derivation_salt(encoded_salt);
}
}
KeyDerivationMethodStateForMetrics GetKeyDerivationMethodStateForMetrics(
const base::Optional<KeyDerivationParams>& key_derivation_params) {
if (!key_derivation_params.has_value()) {
return KeyDerivationMethodStateForMetrics::NOT_SET;
}
switch (key_derivation_params.value().method()) {
case KeyDerivationMethod::PBKDF2_HMAC_SHA1_1003:
return KeyDerivationMethodStateForMetrics::PBKDF2_HMAC_SHA1_1003;
case KeyDerivationMethod::SCRYPT_8192_8_11:
return KeyDerivationMethodStateForMetrics::SCRYPT_8192_8_11;
case KeyDerivationMethod::UNSUPPORTED:
return KeyDerivationMethodStateForMetrics::UNSUPPORTED;
}
NOTREACHED();
return KeyDerivationMethodStateForMetrics::UNSUPPORTED;
}
// The custom passphrase key derivation method in Nigori can be unspecified
// (which means that PBKDF2 was implicitly used). In those cases, we want to set
// it explicitly to PBKDF2. This function checks whether this needs to be done.
bool ShouldSetExplicitCustomPassphraseKeyDerivationMethod(
const sync_pb::NigoriSpecifics& nigori) {
return nigori.passphrase_type() ==
sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE &&
nigori.custom_passphrase_key_derivation_method() ==
sync_pb::NigoriSpecifics::UNSPECIFIED;
}
} // namespace
SyncEncryptionHandlerImpl::Vault::Vault(ModelTypeSet encrypted_types,
PassphraseType passphrase_type)
: encrypted_types(encrypted_types), passphrase_type(passphrase_type) {}
SyncEncryptionHandlerImpl::Vault::~Vault() {}
SyncEncryptionHandlerImpl::SyncEncryptionHandlerImpl(
UserShare* user_share,
const Encryptor* encryptor,
const std::string& restored_key_for_bootstrapping,
const std::string& restored_keystore_key_for_bootstrapping,
const base::RepeatingCallback<std::string()>& random_salt_generator)
: user_share_(user_share),
encryptor_(encryptor),
vault_unsafe_(AlwaysEncryptedUserTypes(), kInitialPassphraseType),
encrypt_everything_(false),
nigori_overwrite_count_(0),
random_salt_generator_(random_salt_generator),
migration_attempted_(false) {
DCHECK(encryptor);
// Restore the cryptographer's previous keys. Note that we don't add the
// keystore keys into the cryptographer here, in case a migration was pending.
vault_unsafe_.cryptographer.Bootstrap(*encryptor,
restored_key_for_bootstrapping);
// If this fails, we won't have a valid keystore key, and will simply request
// new ones from the server on the next DownloadUpdates.
UnpackKeystoreBootstrapToken(restored_keystore_key_for_bootstrapping,
*encryptor, &old_keystore_keys_, &keystore_key_);
}
SyncEncryptionHandlerImpl::~SyncEncryptionHandlerImpl() {}
void SyncEncryptionHandlerImpl::AddObserver(Observer* observer) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(!observers_.HasObserver(observer));
observers_.AddObserver(observer);
}
void SyncEncryptionHandlerImpl::RemoveObserver(Observer* observer) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(observers_.HasObserver(observer));
observers_.RemoveObserver(observer);
}
bool SyncEncryptionHandlerImpl::Init() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
WriteTransaction trans(FROM_HERE, user_share_);
WriteNode node(&trans);
if (node.InitTypeRoot(NIGORI) != BaseNode::INIT_OK) {
// TODO(mastiz): This should be treated as error because it's a protocol
// violation if the server doesn't return the NIGORI root.
return true;
}
switch (ApplyNigoriUpdateImpl(node.GetNigoriSpecifics(),
trans.GetWrappedTrans())) {
case ApplyNigoriUpdateResult::kSuccess:
// If we have successfully updated, we also need to replace an UNSPECIFIED
// key derivation method in Nigori with PBKDF2. (If the update fails,
// WriteEncryptionStateToNigori will do this for us.)
ReplaceImplicitKeyDerivationMethodInNigori(&trans);
break;
case ApplyNigoriUpdateResult::kUnsupportedRemoteState:
return false;
case ApplyNigoriUpdateResult::kRemoteMustBeCorrected:
WriteEncryptionStateToNigori(&trans, NigoriMigrationTrigger::kInit);
break;
}
PassphraseType passphrase_type = GetPassphraseType(trans.GetWrappedTrans());
UMA_HISTOGRAM_ENUMERATION("Sync.PassphraseType", passphrase_type);
if (passphrase_type == PassphraseType::kCustomPassphrase) {
UMA_HISTOGRAM_ENUMERATION(
"Sync.Crypto.CustomPassphraseKeyDerivationMethodStateOnStartup",
GetKeyDerivationMethodStateForMetrics(
custom_passphrase_key_derivation_params_));
}
bool has_pending_keys =
UnlockVault(trans.GetWrappedTrans()).cryptographer.has_pending_keys();
bool is_ready =
UnlockVault(trans.GetWrappedTrans()).cryptographer.CanEncrypt();
// Log the state of the cryptographer regardless of migration state.
UMA_HISTOGRAM_BOOLEAN("Sync.CryptographerReady", is_ready);
UMA_HISTOGRAM_BOOLEAN("Sync.CryptographerPendingKeys", has_pending_keys);
if (IsNigoriMigratedToKeystore(node.GetNigoriSpecifics())) {
// This account has a nigori node that has been migrated to support
// keystore.
UMA_HISTOGRAM_ENUMERATION("Sync.NigoriMigrationState", MIGRATED,
MIGRATION_STATE_SIZE);
if (has_pending_keys && GetPassphraseType(trans.GetWrappedTrans()) ==
PassphraseType::kKeystorePassphrase) {
// If this is happening, it means the keystore decryptor is either
// undecryptable with the available keystore keys or does not match the
// nigori keybag's encryption key. Otherwise we're simply missing the
// keystore key.
UMA_HISTOGRAM_BOOLEAN("Sync.KeystoreDecryptionFailed",
!keystore_key_.empty());
}
} else if (!is_ready) {
// Migration cannot occur until the cryptographer is ready (initialized
// with GAIA password and any pending keys resolved).
UMA_HISTOGRAM_ENUMERATION("Sync.NigoriMigrationState",
NOT_MIGRATED_CRYPTO_NOT_READY,
MIGRATION_STATE_SIZE);
} else if (keystore_key_.empty()) {
// The client has no keystore key, either because it is not yet enabled or
// the server is not sending a valid keystore key.
UMA_HISTOGRAM_ENUMERATION("Sync.NigoriMigrationState",
NOT_MIGRATED_NO_KEYSTORE_KEY,
MIGRATION_STATE_SIZE);
} else {
// If the above conditions have been met and the nigori node is still not
// migrated, something failed in the migration process.
UMA_HISTOGRAM_ENUMERATION("Sync.NigoriMigrationState",
NOT_MIGRATED_UNKNOWN_REASON,
MIGRATION_STATE_SIZE);
}
// Always trigger an encrypted types and cryptographer state change event at
// init time so observers get the initial values.
for (auto& observer : observers_) {
observer.OnEncryptedTypesChanged(
UnlockVault(trans.GetWrappedTrans()).encrypted_types,
encrypt_everything_);
}
for (auto& observer : observers_) {
observer.OnCryptographerStateChanged(
&UnlockVaultMutable(trans.GetWrappedTrans())->cryptographer,
UnlockVault(trans.GetWrappedTrans()).cryptographer.has_pending_keys());
}
// If the cryptographer is not ready (either it has pending keys or we
// failed to initialize it), we don't want to try and re-encrypt the data.
// If we had encrypted types, the DataTypeManager will block, preventing
// sync from happening until the the passphrase is provided.
if (UnlockVault(trans.GetWrappedTrans()).cryptographer.CanEncrypt())
ReEncryptEverything(&trans);
return true;
}
void SyncEncryptionHandlerImpl::SetEncryptionPassphrase(
const std::string& passphrase) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// We do not accept empty passphrases.
if (passphrase.empty()) {
NOTREACHED() << "Cannot encrypt with an empty passphrase.";
return;
}
// All accesses to the cryptographer are protected by a transaction.
WriteTransaction trans(FROM_HERE, user_share_);
WriteNode node(&trans);
if (node.InitTypeRoot(NIGORI) != BaseNode::INIT_OK) {
NOTREACHED();
return;
}
DirectoryCryptographer* cryptographer =
&UnlockVaultMutable(trans.GetWrappedTrans())->cryptographer;
// Once we've migrated to keystore, the only way to set a passphrase for
// encryption is to set a custom passphrase.
if (IsNigoriMigratedToKeystore(node.GetNigoriSpecifics())) {
// Will fail if we already have an explicit passphrase or we have pending
// keys.
SetCustomPassphrase(passphrase, &trans, &node);
// When keystore migration occurs, the "CustomEncryption" UMA stat must be
// logged as true.
UMA_HISTOGRAM_BOOLEAN("Sync.CustomEncryption", true);
return;
}
std::string bootstrap_token;
sync_pb::EncryptedData pending_keys;
if (cryptographer->has_pending_keys())
pending_keys = cryptographer->GetPendingKeys();
bool success = false;
PassphraseType* passphrase_type =
&UnlockVaultMutable(trans.GetWrappedTrans())->passphrase_type;
// There are six cases to handle here:
// 1. The user has no pending keys and is setting their current GAIA password
// as the encryption passphrase. This happens either during first time sync
// with a clean profile, or after re-authenticating on a profile that was
// already signed in with the cryptographer ready.
// 2. The user has no pending keys, and is overwriting an (already provided)
// implicit passphrase with an explicit (custom) passphrase.
// 3. The user has pending keys for an explicit passphrase that is somehow set
// to their current GAIA passphrase.
// 4. The user has pending keys encrypted with their current GAIA passphrase
// and the caller passes in the current GAIA passphrase.
// 5. The user has pending keys encrypted with an older GAIA passphrase
// and the caller passes in the current GAIA passphrase.
// 6. The user has previously done encryption with an explicit passphrase.
// Furthermore, we enforce the fact that the bootstrap encryption token will
// always be derived from the newest GAIA password if the account is using
// an implicit passphrase (even if the data is encrypted with an old GAIA
// password). If the account is using an explicit (custom) passphrase, the
// bootstrap token will be derived from the most recently provided explicit
// passphrase (that was able to decrypt the data).
if (!IsExplicitPassphrase(*passphrase_type)) {
if (!cryptographer->has_pending_keys()) {
KeyParams key_params = {KeyDerivationParams::CreateForPbkdf2(),
passphrase};
if (cryptographer->AddKey(key_params)) {
// Case 1 and 2. We set a new GAIA passphrase when there are no pending
// keys (1), or overwriting an implicit passphrase with a new explicit
// one (2) when there are no pending keys.
DVLOG(1) << "Setting explicit passphrase for encryption.";
*passphrase_type = PassphraseType::kCustomPassphrase;
custom_passphrase_time_ = base::Time::Now();
for (auto& observer : observers_) {
observer.OnPassphraseTypeChanged(
*passphrase_type, GetExplicitPassphraseTime(*passphrase_type));
}
cryptographer->GetBootstrapToken(*encryptor_, &bootstrap_token);
UMA_HISTOGRAM_BOOLEAN("Sync.CustomEncryption", true);
success = true;
} else {
NOTREACHED() << "Failed to add key to cryptographer.";
success = false;
}
} else { // cryptographer->has_pending_keys() == true
// This can only happen if the nigori node is updated with a new
// implicit passphrase while a client is attempting to set a new custom
// passphrase (race condition).
DVLOG(1) << "Failing because an implicit passphrase is already set.";
success = false;
} // cryptographer->has_pending_keys()
} else { // IsExplicitPassphrase(passphrase_type) == true.
// Case 6. We do not want to override a previously set explicit passphrase,
// so we return a failure.
DVLOG(1) << "Failing because an explicit passphrase is already set.";
success = false;
}
DVLOG_IF(1, !success)
<< "Failure in SetEncryptionPassphrase; notifying and returning.";
DVLOG_IF(1, success)
<< "Successfully set encryption passphrase; updating nigori and "
"reencrypting.";
FinishSetPassphrase(success, bootstrap_token, &trans, &node);
}
void SyncEncryptionHandlerImpl::SetDecryptionPassphrase(
const std::string& passphrase) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// We do not accept empty passphrases.
if (passphrase.empty()) {
NOTREACHED() << "Cannot decrypt with an empty passphrase.";
return;
}
// All accesses to the cryptographer are protected by a transaction.
WriteTransaction trans(FROM_HERE, user_share_);
WriteNode node(&trans);
if (node.InitTypeRoot(NIGORI) != BaseNode::INIT_OK) {
NOTREACHED();
return;
}
// Once we've migrated to keystore, we're only ever decrypting keys derived
// from an explicit passphrase. But, for clients without a keystore key yet
// (either not on by default or failed to download one), we still support
// decrypting with a gaia passphrase, and therefore bypass the
// DecryptPendingKeysWithExplicitPassphrase logic.
if (IsNigoriMigratedToKeystore(node.GetNigoriSpecifics()) &&
IsExplicitPassphrase(GetPassphraseType(trans.GetWrappedTrans()))) {
// We have completely migrated and are using an explicit passphrase (either
// FROZEN_IMPLICIT_PASSPHRASE or CUSTOM_PASSPHRASE). In the
// CUSTOM_PASSPHRASE case, custom_passphrase_key_derivation_method_ was set
// previously (when reading the Nigori node), and we will use it for key
// derivation in DecryptPendingKeysWithExplicitPassphrase.
PassphraseType passphrase_type = GetPassphraseType(trans.GetWrappedTrans());
if (passphrase_type == PassphraseType::kCustomPassphrase) {
DCHECK(custom_passphrase_key_derivation_params_.has_value());
if (custom_passphrase_key_derivation_params_.value().method() ==
KeyDerivationMethod::UNSUPPORTED) {
// For now we will just refuse the passphrase. In the future, we may
// notify the user about the reason and ask them to update Chrome.
DLOG(ERROR) << "Setting decryption passphrase failed because the key "
"derivation method is unsupported.";
FinishSetPassphrase(/*success=*/false,
/*bootstrap_token=*/std::string(), &trans, &node);
return;
}
DVLOG(1)
<< "Setting passphrase of type "
<< PassphraseTypeToString(PassphraseType::kCustomPassphrase)
<< " for decryption with key derivation method "
<< KeyDerivationMethodToString(
custom_passphrase_key_derivation_params_.value().method());
} else {
DVLOG(1) << "Setting passphrase of type "
<< PassphraseTypeToString(passphrase_type)
<< " for decryption, implicitly using old key derivation method";
}
DecryptPendingKeysWithExplicitPassphrase(passphrase, &trans, &node);
return;
}
DirectoryCryptographer* cryptographer =
&UnlockVaultMutable(trans.GetWrappedTrans())->cryptographer;
if (!cryptographer->has_pending_keys()) {
// Note that this *can* happen in a rare situation where data is
// re-encrypted on another client while a SetDecryptionPassphrase() call is
// in-flight on this client. It is rare enough that we choose to do nothing.
NOTREACHED() << "Attempt to set decryption passphrase failed because there "
<< "were no pending keys.";
return;
}
std::string bootstrap_token;
sync_pb::EncryptedData pending_keys;
pending_keys = cryptographer->GetPendingKeys();
bool success = false;
// There are three cases to handle here:
// 7. We're using the current GAIA password to decrypt the pending keys. This
// happens when signing in to an account with a previously set implicit
// passphrase, where the data is already encrypted with the newest GAIA
// password.
// 8. The user is providing an old GAIA password to decrypt the pending keys.
// In this case, the user is using an implicit passphrase, but has changed
// their password since they last encrypted their data, and therefore
// their current GAIA password was unable to decrypt the data. This will
// happen when the user is setting up a new profile with a previously
// encrypted account (after changing passwords).
// 9. The user is providing a previously set explicit passphrase to decrypt
// the pending keys.
KeyParams key_params = {KeyDerivationParams::CreateForPbkdf2(), passphrase};
if (!IsExplicitPassphrase(GetPassphraseType(trans.GetWrappedTrans()))) {
if (cryptographer->is_initialized()) {
// We only want to change the default encryption key to the pending
// one if the pending keybag already contains the current default.
// This covers the case where a different client re-encrypted
// everything with a newer gaia passphrase (and hence the keybag
// contains keys from all previously used gaia passphrases).
// Otherwise, we're in a situation where the pending keys are
// encrypted with an old gaia passphrase, while the default is the
// current gaia passphrase. In that case, we preserve the default.
DirectoryCryptographer temp_cryptographer;
temp_cryptographer.SetPendingKeys(cryptographer->GetPendingKeys());
if (temp_cryptographer.DecryptPendingKeys(key_params)) {
// Check to see if the pending bag of keys contains the current
// default key.
sync_pb::EncryptedData encrypted;
cryptographer->GetKeys(&encrypted);
if (temp_cryptographer.CanDecrypt(encrypted)) {
DVLOG(1) << "Implicit user provided passphrase accepted for "
<< "decryption, overwriting default.";
// Case 7. The pending keybag contains the current default. Go ahead
// and update the cryptographer, letting the default change.
cryptographer->DecryptPendingKeys(key_params);
cryptographer->GetBootstrapToken(*encryptor_, &bootstrap_token);
success = true;
} else {
// Case 8. The pending keybag does not contain the current default
// encryption key. We decrypt the pending keys here, and in
// FinishSetPassphrase, re-encrypt everything with the current GAIA
// passphrase instead of the passphrase just provided by the user.
DVLOG(1) << "Implicit user provided passphrase accepted for "
<< "decryption, restoring implicit internal passphrase "
<< "as default.";
std::string bootstrap_token_from_current_key;
cryptographer->GetBootstrapToken(*encryptor_,
&bootstrap_token_from_current_key);
cryptographer->DecryptPendingKeys(key_params);
// Overwrite the default from the pending keys.
cryptographer->AddKeyFromBootstrapToken(
*encryptor_, bootstrap_token_from_current_key);
success = true;
}
} else { // !temp_cryptographer.DecryptPendingKeys(..)
DVLOG(1) << "Implicit user provided passphrase failed to decrypt.";
success = false;
} // temp_cryptographer.DecryptPendingKeys(...)
} else { // cryptographer->is_initialized() == false
if (cryptographer->DecryptPendingKeys(key_params)) {
// This can happpen in two cases:
// - First time sync on android, where we'll never have a
// !user_provided passphrase.
// - This is a restart for a client that lost their bootstrap token.
// In both cases, we should go ahead and initialize the cryptographer
// and persist the new bootstrap token.
//
// Note: at this point, we cannot distinguish between cases 7 and 8
// above. This user provided passphrase could be the current or the
// old. But, as long as we persist the token, there's nothing more
// we can do.
cryptographer->GetBootstrapToken(*encryptor_, &bootstrap_token);
DVLOG(1) << "Implicit user provided passphrase accepted, initializing"
<< " cryptographer.";
success = true;
} else {
DVLOG(1) << "Implicit user provided passphrase failed to decrypt.";
success = false;
}
} // cryptographer->is_initialized()
} else { // nigori_has_explicit_passphrase == true
// Case 9. Encryption was done with an explicit passphrase, and we decrypt
// with the passphrase provided by the user.
if (cryptographer->DecryptPendingKeys(key_params)) {
DVLOG(1) << "Explicit passphrase accepted for decryption.";
cryptographer->GetBootstrapToken(*encryptor_, &bootstrap_token);
success = true;
} else {
DVLOG(1) << "Explicit passphrase failed to decrypt.";
success = false;
}
} // nigori_has_explicit_passphrase
DVLOG_IF(1, !success)
<< "Failure in SetDecryptionPassphrase; notifying and returning.";
DVLOG_IF(1, success)
<< "Successfully set decryption passphrase; updating nigori and "
"reencrypting.";
FinishSetPassphrase(success, bootstrap_token, &trans, &node);
}
void SyncEncryptionHandlerImpl::AddTrustedVaultDecryptionKeys(
const std::vector<std::vector<uint8_t>>& keys) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
NOTIMPLEMENTED();
}
void SyncEncryptionHandlerImpl::EnableEncryptEverything() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
WriteTransaction trans(FROM_HERE, user_share_);
DVLOG(1) << "Enabling encrypt everything.";
if (encrypt_everything_)
return;
EnableEncryptEverythingImpl(trans.GetWrappedTrans());
WriteEncryptionStateToNigori(
&trans, NigoriMigrationTrigger::kEnableEncryptEverything);
if (UnlockVault(trans.GetWrappedTrans()).cryptographer.CanEncrypt())
ReEncryptEverything(&trans);
}
bool SyncEncryptionHandlerImpl::IsEncryptEverythingEnabled() const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return encrypt_everything_;
}
base::Time SyncEncryptionHandlerImpl::GetKeystoreMigrationTime() const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return keystore_migration_time_;
}
KeystoreKeysHandler* SyncEncryptionHandlerImpl::GetKeystoreKeysHandler() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return this;
}
std::string SyncEncryptionHandlerImpl::GetLastKeystoreKey() const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
syncable::ReadTransaction trans(FROM_HERE, user_share_->directory.get());
return keystore_key_;
}
// Note: this is called from within a syncable transaction, so we need to post
// tasks if we want to do any work that creates a new sync_api transaction.
bool SyncEncryptionHandlerImpl::ApplyNigoriUpdate(
const sync_pb::NigoriSpecifics& nigori,
syncable::BaseTransaction* const trans) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(trans);
switch (ApplyNigoriUpdateImpl(nigori, trans)) {
case ApplyNigoriUpdateResult::kSuccess:
// If we have successfully updated, we also need to replace an UNSPECIFIED
// key derivation method in Nigori with PBKDF2, for which we post a task.
// (If the update fails, RewriteNigori will do this for us.) Note that
// this check is redundant, but it is used to avoid the overhead of
// posting a task which will just do nothing.
if (ShouldSetExplicitCustomPassphraseKeyDerivationMethod(nigori)) {
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(
&SyncEncryptionHandlerImpl::
ReplaceImplicitKeyDerivationMethodInNigoriWithTransaction,
weak_ptr_factory_.GetWeakPtr()));
}
break;
case ApplyNigoriUpdateResult::kUnsupportedRemoteState:
return false;
case ApplyNigoriUpdateResult::kRemoteMustBeCorrected:
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&SyncEncryptionHandlerImpl::RewriteNigori,
weak_ptr_factory_.GetWeakPtr(),
NigoriMigrationTrigger::kApplyNigoriUpdate));
break;
}
for (auto& observer : observers_) {
observer.OnCryptographerStateChanged(
&UnlockVaultMutable(trans)->cryptographer,
UnlockVault(trans).cryptographer.has_pending_keys());
}
return true;
}
void SyncEncryptionHandlerImpl::UpdateNigoriFromEncryptedTypes(
sync_pb::NigoriSpecifics* nigori,
const syncable::BaseTransaction* const trans) const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
syncable::UpdateNigoriFromEncryptedTypes(UnlockVault(trans).encrypted_types,
encrypt_everything_, nigori);
}
bool SyncEncryptionHandlerImpl::NeedKeystoreKey() const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
syncable::ReadTransaction trans(FROM_HERE, user_share_->directory.get());
return keystore_key_.empty();
}
bool SyncEncryptionHandlerImpl::SetKeystoreKeys(
const std::vector<std::vector<uint8_t>>& keys) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
syncable::ReadTransaction trans(FROM_HERE, user_share_->directory.get());
if (keys.empty())
return false;
// The last key in the vector is the current keystore key. The others are kept
// around for decryption only.
const std::vector<uint8_t>& raw_keystore_key = keys.back();
if (raw_keystore_key.empty())
return false;
// Note: in order to Pack the keys, they must all be base64 encoded (else
// JSON serialization fails).
keystore_key_ = base::Base64Encode(raw_keystore_key);
// Go through and save the old keystore keys. We always persist all keystore
// keys the server sends us.
old_keystore_keys_.resize(keys.size() - 1);
for (size_t i = 0; i < keys.size() - 1; ++i)
old_keystore_keys_[i] = base::Base64Encode(keys[i]);
DirectoryCryptographer* cryptographer =
&UnlockVaultMutable(&trans)->cryptographer;
// Update the bootstrap token. If this fails, we persist an empty string,
// which will force us to download the keystore keys again on the next
// restart.
std::string keystore_bootstrap = PackKeystoreBootstrapToken(
old_keystore_keys_, keystore_key_, *encryptor_);
for (auto& observer : observers_) {
observer.OnBootstrapTokenUpdated(keystore_bootstrap,
KEYSTORE_BOOTSTRAP_TOKEN);
}
DVLOG(1) << "Keystore bootstrap token updated.";
// If this is a first time sync, we get the encryption keys before we process
// the nigori node. Just return for now, ApplyNigoriUpdate will be invoked
// once we have the nigori node.
syncable::Entry entry(&trans, syncable::GET_TYPE_ROOT, NIGORI);
if (!entry.good())
return true;
const sync_pb::NigoriSpecifics& nigori = entry.GetSpecifics().nigori();
if (cryptographer->has_pending_keys() && IsNigoriMigratedToKeystore(nigori) &&
!nigori.keystore_decryptor_token().blob().empty()) {
// If the nigori is already migrated and we have pending keys, we might
// be able to decrypt them using either the keystore decryptor token
// or the existing keystore keys.
DecryptPendingKeysWithKeystoreKey(nigori.keystore_decryptor_token(),
cryptographer);
}
// Note that triggering migration will have no effect if we're already
// properly migrated with the newest keystore keys.
if (GetMigrationReason(nigori, *cryptographer, GetPassphraseType(&trans)) !=
NigoriMigrationReason::kNoReason) {
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&SyncEncryptionHandlerImpl::RewriteNigori,
weak_ptr_factory_.GetWeakPtr(),
NigoriMigrationTrigger::kSetKeystoreKeys));
}
return true;
}
const Cryptographer* SyncEncryptionHandlerImpl::GetCryptographer(
const syncable::BaseTransaction* const trans) const {
return &UnlockVault(trans).cryptographer;
}
const DirectoryCryptographer*
SyncEncryptionHandlerImpl::GetDirectoryCryptographer(
const syncable::BaseTransaction* const trans) const {
return &UnlockVault(trans).cryptographer;
}
ModelTypeSet SyncEncryptionHandlerImpl::GetEncryptedTypes(
const syncable::BaseTransaction* const trans) const {
return UnlockVault(trans).encrypted_types;
}
PassphraseType SyncEncryptionHandlerImpl::GetPassphraseType(
const syncable::BaseTransaction* const trans) const {
return UnlockVault(trans).passphrase_type;
}
ModelTypeSet SyncEncryptionHandlerImpl::GetEncryptedTypesUnsafe() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return vault_unsafe_.encrypted_types;
}
bool SyncEncryptionHandlerImpl::MigratedToKeystore() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
ReadTransaction trans(FROM_HERE, user_share_);
ReadNode nigori_node(&trans);
if (nigori_node.InitTypeRoot(NIGORI) != BaseNode::INIT_OK)
return false;
return IsNigoriMigratedToKeystore(nigori_node.GetNigoriSpecifics());
}
base::Time SyncEncryptionHandlerImpl::custom_passphrase_time() const {
return custom_passphrase_time_;
}
void SyncEncryptionHandlerImpl::RestoreNigoriForTesting(
const sync_pb::NigoriSpecifics& nigori_specifics) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
WriteTransaction trans(FROM_HERE, user_share_);
// Verify we don't already have a nigori node.
WriteNode nigori_node(&trans);
BaseNode::InitByLookupResult init_result = nigori_node.InitTypeRoot(NIGORI);
DCHECK(init_result == BaseNode::INIT_FAILED_ENTRY_NOT_GOOD);
// Create one.
syncable::ModelNeutralMutableEntry model_neutral_mutable_entry(
trans.GetWrappedWriteTrans(), syncable::CREATE_NEW_TYPE_ROOT, NIGORI);
DCHECK(model_neutral_mutable_entry.good());
model_neutral_mutable_entry.PutServerIsDir(true);
model_neutral_mutable_entry.PutUniqueServerTag(ModelTypeToRootTag(NIGORI));
model_neutral_mutable_entry.PutIsUnsynced(true);
// Update it with the saved nigori specifics.
syncable::MutableEntry mutable_entry(trans.GetWrappedWriteTrans(),
syncable::GET_TYPE_ROOT, NIGORI);
DCHECK(mutable_entry.good());
sync_pb::EntitySpecifics specifics;
*specifics.mutable_nigori() = nigori_specifics;
mutable_entry.PutSpecifics(specifics);
// Update our state based on the saved nigori node.
ApplyNigoriUpdate(nigori_specifics, trans.GetWrappedTrans());
}
DirectoryCryptographer*
SyncEncryptionHandlerImpl::GetMutableCryptographerForTesting() {
return &vault_unsafe_.cryptographer;
}
// This function iterates over all encrypted types. There are many scenarios in
// which data for some or all types is not currently available. In that case,
// the lookup of the root node will fail and we will skip encryption for that
// type.
void SyncEncryptionHandlerImpl::ReEncryptEverything(WriteTransaction* trans) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(UnlockVault(trans->GetWrappedTrans()).cryptographer.CanEncrypt());
for (ModelType type : UnlockVault(trans->GetWrappedTrans()).encrypted_types) {
if (type == PASSWORDS || IsControlType(type))
continue; // These types handle encryption differently.
ReadNode type_root(trans);
if (type_root.InitTypeRoot(type) != BaseNode::INIT_OK)
continue; // Don't try to reencrypt if the type's data is unavailable.
// Iterate through all children of this datatype.
base::queue<int64_t> to_visit;
int64_t child_id = type_root.GetFirstChildId();
to_visit.push(child_id);
while (!to_visit.empty()) {
child_id = to_visit.front();
to_visit.pop();
if (child_id == kInvalidId)
continue;
WriteNode child(trans);
if (child.InitByIdLookup(child_id) != BaseNode::INIT_OK)
continue; // Possible for locally deleted items.
if (child.GetIsFolder()) {
to_visit.push(child.GetFirstChildId());
}
if (!child.GetIsPermanentFolder()) {
// Rewrite the specifics of the node with encrypted data if necessary
// (only rewrite the non-unique folders).
child.ResetFromSpecifics();
}
to_visit.push(child.GetSuccessorId());
}
}
// Passwords are encrypted with their own legacy scheme. Passwords are always
// encrypted so we don't need to check GetEncryptedTypes() here.
ReadNode passwords_root(trans);
if (passwords_root.InitTypeRoot(PASSWORDS) == BaseNode::INIT_OK) {
int64_t child_id = passwords_root.GetFirstChildId();
while (child_id != kInvalidId) {
WriteNode child(trans);
if (child.InitByIdLookup(child_id) != BaseNode::INIT_OK)
break; // Possible if we failed to decrypt the data for some reason.
child.SetPasswordSpecifics(child.GetPasswordSpecifics());
child_id = child.GetSuccessorId();
}
}
DVLOG(1) << "Re-encrypt everything complete.";
// NOTE: We notify from within a transaction.
for (auto& observer : observers_) {
observer.OnEncryptionComplete();
}
}
SyncEncryptionHandlerImpl::ApplyNigoriUpdateResult
SyncEncryptionHandlerImpl::ApplyNigoriUpdateImpl(
const sync_pb::NigoriSpecifics& nigori,
syncable::BaseTransaction* const trans) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
const base::Optional<PassphraseType> nigori_passphrase_type_optional =
ProtoPassphraseInt32ToEnum(nigori.passphrase_type());
if (!nigori_passphrase_type_optional) {
DVLOG(1) << "Ignoring nigori node update with unknown passphrase type.";
return ApplyNigoriUpdateResult::kUnsupportedRemoteState;
}
const PassphraseType nigori_passphrase_type =
*nigori_passphrase_type_optional;
if (nigori_passphrase_type == PassphraseType::kTrustedVaultPassphrase) {
NOTIMPLEMENTED();
return ApplyNigoriUpdateResult::kUnsupportedRemoteState;
}
DVLOG(1) << "Applying nigori node update.";
bool nigori_types_need_update =
!UpdateEncryptedTypesFromNigori(nigori, trans);
if (nigori.custom_passphrase_time() != 0) {
custom_passphrase_time_ = ProtoTimeToTime(nigori.custom_passphrase_time());
}
bool is_nigori_migrated = IsNigoriMigratedToKeystore(nigori);
PassphraseType* passphrase_type = &UnlockVaultMutable(trans)->passphrase_type;
if (is_nigori_migrated) {
keystore_migration_time_ =
ProtoTimeToTime(nigori.keystore_migration_time());
// Only update the local passphrase state if it's a valid transition:
// - implicit -> keystore
// - implicit -> frozen implicit
// - implicit -> custom
// - keystore -> custom
// Note: frozen implicit -> custom is not technically a valid transition,
// but we let it through here as well in case future versions do add support
// for this transition.
if (*passphrase_type != nigori_passphrase_type &&
nigori_passphrase_type != PassphraseType::kImplicitPassphrase &&
(*passphrase_type == PassphraseType::kImplicitPassphrase ||
nigori_passphrase_type == PassphraseType::kCustomPassphrase)) {
DVLOG(1) << "Changing passphrase state from "
<< PassphraseTypeToString(*passphrase_type) << " to "
<< PassphraseTypeToString(nigori_passphrase_type);
*passphrase_type = nigori_passphrase_type;
for (auto& observer : observers_) {
observer.OnPassphraseTypeChanged(
*passphrase_type, GetExplicitPassphraseTime(*passphrase_type));
}
}
if (*passphrase_type == PassphraseType::kKeystorePassphrase &&
encrypt_everything_) {
// This is the case where another client that didn't support keystore
// encryption attempted to enable full encryption. We detect it
// and switch the passphrase type to frozen implicit passphrase instead
// due to full encryption not being compatible with keystore passphrase.
// Because the local passphrase type will not match the nigori passphrase
// type, we will trigger a rewrite and subsequently a re-migration.
DVLOG(1) << "Changing passphrase state to FROZEN_IMPLICIT_PASSPHRASE "
<< "due to full encryption.";
*passphrase_type = PassphraseType::kFrozenImplicitPassphrase;
for (auto& observer : observers_) {
observer.OnPassphraseTypeChanged(
*passphrase_type, GetExplicitPassphraseTime(*passphrase_type));
}
}
} else {
// It's possible that while we're waiting for migration a client that does
// not have keystore encryption enabled switches to a custom passphrase.
if (nigori.keybag_is_frozen() &&
*passphrase_type != PassphraseType::kCustomPassphrase) {
*passphrase_type = PassphraseType::kCustomPassphrase;
for (auto& observer : observers_) {
observer.OnPassphraseTypeChanged(
*passphrase_type, GetExplicitPassphraseTime(*passphrase_type));
}
}
}
DirectoryCryptographer* cryptographer =
&UnlockVaultMutable(trans)->cryptographer;
bool nigori_needs_new_keys = false;
if (!nigori.encryption_keybag().blob().empty()) {
// We only update the default key if this was a new explicit passphrase.
// Else, since it was decryptable, it must not have been a new key.
bool need_new_default_key = false;
if (is_nigori_migrated) {
need_new_default_key = IsExplicitPassphrase(nigori_passphrase_type);
} else {
need_new_default_key = nigori.keybag_is_frozen();
}
if (!AttemptToInstallKeybag(nigori.encryption_keybag(),
need_new_default_key, cryptographer)) {
// Check to see if we can decrypt the keybag using the keystore decryptor
// token.
cryptographer->SetPendingKeys(nigori.encryption_keybag());
if (!nigori.keystore_decryptor_token().blob().empty() &&
!keystore_key_.empty()) {
if (DecryptPendingKeysWithKeystoreKey(nigori.keystore_decryptor_token(),
cryptographer)) {
nigori_needs_new_keys =
cryptographer->KeybagIsStale(nigori.encryption_keybag());
} else {
LOG(ERROR) << "Failed to decrypt pending keys using keystore "
<< "bootstrap key.";
}
}
} else {
// Keybag was installed. We write back our local keybag into the nigori
// node if the nigori node's keybag either contains less keys or
// has a different default key.
nigori_needs_new_keys =
cryptographer->KeybagIsStale(nigori.encryption_keybag());
}
} else {
// The nigori node has an empty encryption keybag. Attempt to write our
// local encryption keys into it.
LOG(WARNING) << "Nigori had empty encryption keybag.";
nigori_needs_new_keys = true;
}
// If the method is not CUSTOM_PASSPHRASE, we will fall back to PBKDF2 to be
// backwards compatible.
KeyDerivationParams key_derivation_params =
KeyDerivationParams::CreateForPbkdf2();
if (*passphrase_type == PassphraseType::kCustomPassphrase) {
key_derivation_params = GetKeyDerivationParamsFromNigori(nigori);
if (key_derivation_params.method() == KeyDerivationMethod::UNSUPPORTED) {
DLOG(WARNING) << "Updating from a Nigori node with an unsupported key "
"derivation method.";
}
custom_passphrase_key_derivation_params_ = key_derivation_params;
}
// If we've completed a sync cycle and the cryptographer isn't ready
// yet or has pending keys, prompt the user for a passphrase.
if (cryptographer->has_pending_keys()) {
DVLOG(1) << "OnPassphraseRequired Sent";
sync_pb::EncryptedData pending_keys = cryptographer->GetPendingKeys();
for (auto& observer : observers_) {
observer.OnPassphraseRequired(REASON_DECRYPTION, key_derivation_params,
pending_keys);
}
} else if (!cryptographer->CanEncrypt()) {
DVLOG(1) << "OnPassphraseRequired sent because cryptographer is not "
<< "ready";
for (auto& observer : observers_) {
observer.OnPassphraseRequired(REASON_ENCRYPTION, key_derivation_params,
sync_pb::EncryptedData());
}
}
// Check if the current local encryption state is stricter/newer than the
// nigori state. If so, we need to overwrite the nigori node with the local
// state.
bool passphrase_type_matches = true;
if (!is_nigori_migrated) {
DCHECK(*passphrase_type == PassphraseType::kCustomPassphrase ||
*passphrase_type == PassphraseType::kImplicitPassphrase);
passphrase_type_matches =
nigori.keybag_is_frozen() == IsExplicitPassphrase(*passphrase_type);
} else {
passphrase_type_matches = (nigori_passphrase_type == *passphrase_type);
}
if (!passphrase_type_matches ||
nigori.encrypt_everything() != encrypt_everything_ ||
nigori_types_need_update || nigori_needs_new_keys) {
DVLOG(1) << "Triggering nigori rewrite.";
return ApplyNigoriUpdateResult::kRemoteMustBeCorrected;
}
return ApplyNigoriUpdateResult::kSuccess;
}
void SyncEncryptionHandlerImpl::RewriteNigori(
NigoriMigrationTrigger migration_trigger) {
DVLOG(1) << "Writing local encryption state into nigori.";
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
WriteTransaction trans(FROM_HERE, user_share_);
WriteEncryptionStateToNigori(&trans, migration_trigger);
}
void SyncEncryptionHandlerImpl::WriteEncryptionStateToNigori(
WriteTransaction* trans,
NigoriMigrationTrigger migration_trigger) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
WriteNode nigori_node(trans);
// This can happen in tests that don't have nigori nodes.
if (nigori_node.InitTypeRoot(NIGORI) != BaseNode::INIT_OK)
return;
sync_pb::NigoriSpecifics nigori = nigori_node.GetNigoriSpecifics();
const DirectoryCryptographer& cryptographer =
UnlockVault(trans->GetWrappedTrans()).cryptographer;
// Will not do anything if we shouldn't or can't migrate. Otherwise
// migrates, writing the full encryption state as it does.
if (!AttemptToMigrateNigoriToKeystore(trans, &nigori_node,
migration_trigger)) {
if (cryptographer.CanEncrypt() &&
nigori_overwrite_count_ < kNigoriOverwriteLimit) {
// Does not modify the encrypted blob if the unencrypted data already
// matches what is about to be written.
sync_pb::EncryptedData original_keys = nigori.encryption_keybag();
if (!cryptographer.GetKeys(nigori.mutable_encryption_keybag()))
NOTREACHED();
if (nigori.encryption_keybag().SerializeAsString() !=
original_keys.SerializeAsString()) {
// We've updated the nigori node's encryption keys. In order to prevent
// a possible looping of two clients constantly overwriting each other,
// we limit the absolute number of overwrites per client instantiation.
nigori_overwrite_count_++;
UMA_HISTOGRAM_COUNTS_1M("Sync.AutoNigoriOverwrites",
nigori_overwrite_count_);
}
// Note: we don't try to set keybag_is_frozen here since if that
// is lost the user can always set it again (and we don't want to clobber
// any migration state). The main goal at this point is to preserve
// the encryption keys so all data remains decryptable.
}
syncable::UpdateNigoriFromEncryptedTypes(
UnlockVault(trans->GetWrappedTrans()).encrypted_types,
encrypt_everything_, &nigori);
if (!custom_passphrase_time_.is_null()) {
nigori.set_custom_passphrase_time(
TimeToProtoTime(custom_passphrase_time_));
}
// If nothing has changed, this is a no-op.
nigori_node.SetNigoriSpecifics(nigori);
}
}
bool SyncEncryptionHandlerImpl::UpdateEncryptedTypesFromNigori(
const sync_pb::NigoriSpecifics& nigori,
syncable::BaseTransaction* const trans) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
ModelTypeSet* encrypted_types = &UnlockVaultMutable(trans)->encrypted_types;
if (nigori.encrypt_everything()) {
EnableEncryptEverythingImpl(trans);
DCHECK(*encrypted_types == EncryptableUserTypes());
return true;
} else if (encrypt_everything_) {
DCHECK(*encrypted_types == EncryptableUserTypes());
return false;
}
ModelTypeSet nigori_encrypted_types;
nigori_encrypted_types = syncable::GetEncryptedTypesFromNigori(nigori);
nigori_encrypted_types.PutAll(AlwaysEncryptedUserTypes());
// If anything more than the sensitive types were encrypted, and
// encrypt_everything is not explicitly set to false, we assume it means
// a client intended to enable encrypt everything.
if (!nigori.has_encrypt_everything() &&
!Difference(nigori_encrypted_types, AlwaysEncryptedUserTypes()).Empty()) {
if (!encrypt_everything_) {
encrypt_everything_ = true;
*encrypted_types = EncryptableUserTypes();
for (auto& observer : observers_) {
observer.OnEncryptedTypesChanged(*encrypted_types, encrypt_everything_);
}
}
DCHECK(*encrypted_types == EncryptableUserTypes());
return false;
}
MergeEncryptedTypes(nigori_encrypted_types, trans);
return *encrypted_types == nigori_encrypted_types;
}
void SyncEncryptionHandlerImpl::
ReplaceImplicitKeyDerivationMethodInNigoriWithTransaction() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
WriteTransaction trans(FROM_HERE, user_share_);
ReplaceImplicitKeyDerivationMethodInNigori(&trans);
}
void SyncEncryptionHandlerImpl::ReplaceImplicitKeyDerivationMethodInNigori(
WriteTransaction* trans) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(trans);
WriteNode nigori_node(trans);
// This can happen in tests that don't have nigori nodes.
if (nigori_node.InitTypeRoot(NIGORI) != BaseNode::INIT_OK)
return;
if (!ShouldSetExplicitCustomPassphraseKeyDerivationMethod(
nigori_node.GetNigoriSpecifics())) {
// Nothing to do; an explicit method is already set.
return;
}
DVLOG(1) << "Writing explicit custom passphrase key derivation method to "
"Nigori node, since none was set.";
// UNSPECIFIED as custom_passphrase_key_derivation_method in Nigori implies
// PBKDF2.
sync_pb::NigoriSpecifics specifics = nigori_node.GetNigoriSpecifics();
UpdateNigoriSpecificsKeyDerivationParams(
KeyDerivationParams::CreateForPbkdf2(), &specifics);
nigori_node.SetNigoriSpecifics(specifics);
}
void SyncEncryptionHandlerImpl::SetCustomPassphrase(
const std::string& passphrase,
WriteTransaction* trans,
WriteNode* nigori_node) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(IsNigoriMigratedToKeystore(nigori_node->GetNigoriSpecifics()));
KeyDerivationParams key_derivation_params =
CreateKeyDerivationParamsForCustomPassphrase(random_salt_generator_);
UMA_HISTOGRAM_ENUMERATION(
"Sync.Crypto.CustomPassphraseKeyDerivationMethodOnNewPassphrase",
GetKeyDerivationMethodStateForMetrics(key_derivation_params));
KeyParams key_params = {key_derivation_params, passphrase};
if (GetPassphraseType(trans->GetWrappedTrans()) !=
PassphraseType::kKeystorePassphrase) {
DVLOG(1) << "Failing to set a custom passphrase because one has already "
<< "been set.";
FinishSetPassphrase(false, std::string(), trans, nigori_node);
return;
}
DirectoryCryptographer* cryptographer =
&UnlockVaultMutable(trans->GetWrappedTrans())->cryptographer;
if (cryptographer->has_pending_keys()) {
// This theoretically shouldn't happen, because the only way to have pending
// keys after migrating to keystore support is if a custom passphrase was
// set, which should update passpshrase_state_ and should be caught by the
// if statement above. For the sake of safety though, we check for it in
// case a client is misbehaving.
LOG(ERROR) << "Failing to set custom passphrase because of pending keys.";
FinishSetPassphrase(false, std::string(), trans, nigori_node);
return;
}
std::string bootstrap_token;
if (!cryptographer->AddKey(key_params)) {
NOTREACHED() << "Failed to add key to cryptographer.";
return;
}
DVLOG(1) << "Setting custom passphrase with key derivation method "
<< KeyDerivationMethodToString(key_derivation_params.method());
cryptographer->GetBootstrapToken(*encryptor_, &bootstrap_token);
PassphraseType* passphrase_type =
&UnlockVaultMutable(trans->GetWrappedTrans())->passphrase_type;
*passphrase_type = PassphraseType::kCustomPassphrase;
custom_passphrase_key_derivation_params_ = key_derivation_params;
custom_passphrase_time_ = base::Time::Now();
for (auto& observer : observers_) {
observer.OnPassphraseTypeChanged(
*passphrase_type, GetExplicitPassphraseTime(*passphrase_type));
}
FinishSetPassphrase(true, bootstrap_token, trans, nigori_node);
}
void SyncEncryptionHandlerImpl::NotifyObserversOfLocalCustomPassphrase(
WriteTransaction* trans) {
WriteNode nigori_node(trans);
BaseNode::InitByLookupResult init_result = nigori_node.InitTypeRoot(NIGORI);
DCHECK_EQ(init_result, BaseNode::INIT_OK);
sync_pb::NigoriSpecifics nigori_specifics = nigori_node.GetNigoriSpecifics();
DCHECK(nigori_specifics.passphrase_type() ==
sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE ||
nigori_specifics.passphrase_type() ==
sync_pb::NigoriSpecifics::FROZEN_IMPLICIT_PASSPHRASE);
for (auto& observer : observers_) {
observer.OnLocalSetPassphraseEncryption(nigori_specifics);
}
}
void SyncEncryptionHandlerImpl::DecryptPendingKeysWithExplicitPassphrase(
const std::string& passphrase,
WriteTransaction* trans,
WriteNode* nigori_node) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
PassphraseType passphrase_type = GetPassphraseType(trans->GetWrappedTrans());
DCHECK(IsExplicitPassphrase(passphrase_type));
// If the method is not CUSTOM_PASSPHRASE, we will fall back to PBKDF2 to be
// backwards compatible.
KeyDerivationParams key_derivation_params =
KeyDerivationParams::CreateForPbkdf2();
if (passphrase_type == PassphraseType::kCustomPassphrase) {
DCHECK(custom_passphrase_key_derivation_params_.has_value());
DCHECK_NE(custom_passphrase_key_derivation_params_->method(),
KeyDerivationMethod::UNSUPPORTED);
key_derivation_params = custom_passphrase_key_derivation_params_.value();
}
KeyParams key_params = {key_derivation_params, passphrase};
DirectoryCryptographer* cryptographer =
&UnlockVaultMutable(trans->GetWrappedTrans())->cryptographer;
if (!cryptographer->has_pending_keys()) {
// Note that this *can* happen in a rare situation where data is
// re-encrypted on another client while a SetDecryptionPassphrase() call is
// in-flight on this client. It is rare enough that we choose to do nothing.
NOTREACHED() << "Attempt to set decryption passphrase failed because there "
<< "were no pending keys.";
return;
}
bool success = false;
std::string bootstrap_token;
if (cryptographer->DecryptPendingKeys(key_params)) {
DVLOG(1) << "Explicit passphrase accepted for decryption.";
cryptographer->GetBootstrapToken(*encryptor_, &bootstrap_token);
success = true;
if (passphrase_type == PassphraseType::kCustomPassphrase) {
DCHECK(custom_passphrase_key_derivation_params_.has_value());
UMA_HISTOGRAM_ENUMERATION(
"Sync.Crypto."
"CustomPassphraseKeyDerivationMethodOnSuccessfulDecryption",
GetKeyDerivationMethodStateForMetrics(
custom_passphrase_key_derivation_params_));
}
} else {
DVLOG(1) << "Explicit passphrase failed to decrypt.";
success = false;
}
if (success && !keystore_key_.empty()) {
// Should already be part of the encryption keybag, but we add it just
// in case. Note that, since this is a keystore key, we always use PBKDF2
// for key derivation.
KeyParams key_params = {KeyDerivationParams::CreateForPbkdf2(),
keystore_key_};
cryptographer->AddNonDefaultKey(key_params);
}
FinishSetPassphrase(success, bootstrap_token, trans, nigori_node);
}
void SyncEncryptionHandlerImpl::FinishSetPassphrase(
bool success,
const std::string& bootstrap_token,
WriteTransaction* trans,
WriteNode* nigori_node) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
for (auto& observer : observers_) {
observer.OnCryptographerStateChanged(
&UnlockVaultMutable(trans->GetWrappedTrans())->cryptographer,
UnlockVault(trans->GetWrappedTrans()).cryptographer.has_pending_keys());
}
// It's possible we need to change the bootstrap token even if we failed to
// set the passphrase (for example if we need to preserve the new GAIA
// passphrase).
if (!bootstrap_token.empty()) {
DVLOG(1) << "Passphrase bootstrap token updated.";
for (auto& observer : observers_) {
observer.OnBootstrapTokenUpdated(bootstrap_token,
PASSPHRASE_BOOTSTRAP_TOKEN);
}
}
const DirectoryCryptographer& cryptographer =
UnlockVault(trans->GetWrappedTrans()).cryptographer;
if (!success) {
// If we have not set an explicit method, fall back to PBKDF2 to ensure
// backwards compatibility.
KeyDerivationParams key_derivation_params =
KeyDerivationParams::CreateForPbkdf2();
if (custom_passphrase_key_derivation_params_.has_value()) {
DCHECK_EQ(GetPassphraseType(trans->GetWrappedTrans()),
PassphraseType::kCustomPassphrase);
key_derivation_params = custom_passphrase_key_derivation_params_.value();
}
if (cryptographer.CanEncrypt()) {
LOG(ERROR) << "Attempt to change passphrase failed while cryptographer "
<< "was ready.";
} else if (cryptographer.has_pending_keys()) {
for (auto& observer : observers_) {
observer.OnPassphraseRequired(REASON_DECRYPTION, key_derivation_params,
cryptographer.GetPendingKeys());
}
} else {
for (auto& observer : observers_) {
observer.OnPassphraseRequired(REASON_ENCRYPTION, key_derivation_params,
sync_pb::EncryptedData());
}
}
return;
}
DCHECK(success);
DCHECK(cryptographer.CanEncrypt());
// Will do nothing if we're already properly migrated or unable to migrate
// (in otherwords, if GetMigrationReason returns kNoReason).
// Otherwise will update the nigori node with the current migrated state,
// writing all encryption state as it does.
if (!AttemptToMigrateNigoriToKeystore(
trans, nigori_node, NigoriMigrationTrigger::kFinishSetPassphrase)) {
sync_pb::NigoriSpecifics nigori(nigori_node->GetNigoriSpecifics());
// Does not modify nigori.encryption_keybag() if the original decrypted
// data was the same.
if (!cryptographer.GetKeys(nigori.mutable_encryption_keybag()))
NOTREACHED();
if (IsNigoriMigratedToKeystore(nigori)) {
DCHECK(keystore_key_.empty() ||
IsExplicitPassphrase(GetPassphraseType(trans->GetWrappedTrans())));
DVLOG(1) << "Leaving nigori migration state untouched after setting"
<< " passphrase.";
} else {
nigori.set_keybag_is_frozen(
IsExplicitPassphrase(GetPassphraseType(trans->GetWrappedTrans())));
}
// If we set a new custom passphrase, store the timestamp.
if (!custom_passphrase_time_.is_null()) {
nigori.set_custom_passphrase_time(
TimeToProtoTime(custom_passphrase_time_));
}
nigori_node->SetNigoriSpecifics(nigori);
}
PassphraseType passphrase_type = GetPassphraseType(trans->GetWrappedTrans());
if (passphrase_type == PassphraseType::kCustomPassphrase) {
DVLOG(1) << "Successfully set passphrase of type "
<< PassphraseTypeToString(passphrase_type)
<< " with key derivation method "
<< KeyDerivationMethodToString(
custom_passphrase_key_derivation_params_.value().method())
<< ".";
} else {
DVLOG(1) << "Successfully set passphrase of type "
<< PassphraseTypeToString(passphrase_type)
<< " implicitly using old key derivation method.";
}
// Must do this after OnPassphraseTypeChanged, in order to ensure the PSS
// checks the passphrase state after it has been set.
for (auto& observer : observers_) {
observer.OnPassphraseAccepted();
}
// Does nothing if everything is already encrypted.
// TODO(zea): If we just migrated and enabled encryption, this will be
// redundant. Figure out a way to not do this unnecessarily.
ReEncryptEverything(trans);
}
void SyncEncryptionHandlerImpl::MergeEncryptedTypes(
ModelTypeSet new_encrypted_types,
syncable::BaseTransaction* const trans) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Only UserTypes may be encrypted.
DCHECK(EncryptableUserTypes().HasAll(new_encrypted_types));
ModelTypeSet* encrypted_types = &UnlockVaultMutable(trans)->encrypted_types;
if (!encrypted_types->HasAll(new_encrypted_types)) {
*encrypted_types = new_encrypted_types;
for (auto& observer : observers_) {
observer.OnEncryptedTypesChanged(*encrypted_types, encrypt_everything_);
}
}
}
SyncEncryptionHandlerImpl::Vault* SyncEncryptionHandlerImpl::UnlockVaultMutable(
const syncable::BaseTransaction* const trans) {
DCHECK_EQ(user_share_->directory.get(), trans->directory());
return &vault_unsafe_;
}
const SyncEncryptionHandlerImpl::Vault& SyncEncryptionHandlerImpl::UnlockVault(
const syncable::BaseTransaction* const trans) const {
DCHECK_EQ(user_share_->directory.get(), trans->directory());
return vault_unsafe_;
}
SyncEncryptionHandlerImpl::NigoriMigrationReason
SyncEncryptionHandlerImpl::GetMigrationReason(
const sync_pb::NigoriSpecifics& nigori,
const DirectoryCryptographer& cryptographer,
PassphraseType passphrase_type) const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Don't migrate if there are pending encryption keys (because data
// encrypted with the pending keys will not be decryptable).
if (cryptographer.has_pending_keys())
return NigoriMigrationReason::kNoReason;
if (!IsNigoriMigratedToKeystore(nigori)) {
if (keystore_key_.empty()) {
// If we haven't already migrated, we don't want to do anything unless
// a keystore key is available (so that those clients without keystore
// encryption enabled aren't forced into new states, e.g. frozen implicit
// passphrase).
return NigoriMigrationReason::kNoReason;
}
if (nigori.encryption_keybag().blob().empty()) {
return NigoriMigrationReason::kInitialization;
}
return NigoriMigrationReason::KNigoriNotMigrated;
}
// If the nigori is already migrated but does not reflect the explicit
// passphrase state, remigrate. Similarly, if the nigori has an explicit
// passphrase but does not have full encryption, or the nigori has an
// implicit passphrase but does have full encryption, re-migrate.
// Note that this is to defend against other clients without keystore
// encryption enabled transitioning to states that are no longer valid.
if (passphrase_type != PassphraseType::kKeystorePassphrase &&
nigori.passphrase_type() ==
sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE) {
return NigoriMigrationReason::kOldPassphraseType;
}
if (IsExplicitPassphrase(passphrase_type) && !encrypt_everything_) {
return NigoriMigrationReason::kNotEncryptEverythingWithExplicitPassphrase;
}
if (passphrase_type == PassphraseType::kKeystorePassphrase &&
encrypt_everything_) {
return NigoriMigrationReason::kEncryptEverythingWithKeystorePassphrase;
}
if (cryptographer.CanEncrypt() &&
!cryptographer.CanDecryptUsingDefaultKey(nigori.encryption_keybag())) {
// We need to overwrite the keybag. This might involve overwriting the
// keystore decryptor too.
return NigoriMigrationReason::kCannotDecryptUsingDefaultKey;
}
if (old_keystore_keys_.size() > 0 && !keystore_key_.empty()) {
// Check to see if a server key rotation has happened, but the nigori
// node's keys haven't been rotated yet, and hence we should re-migrate.
// Note that once a key rotation has been performed, we no longer
// preserve backwards compatibility, and the keybag will therefore be
// encrypted with the current keystore key.
DirectoryCryptographer temp_cryptographer;
KeyParams keystore_params = {KeyDerivationParams::CreateForPbkdf2(),
keystore_key_};
temp_cryptographer.AddKey(keystore_params);
if (!temp_cryptographer.CanDecryptUsingDefaultKey(
nigori.encryption_keybag())) {
return NigoriMigrationReason::kServerKeyRotation;
}
}
return NigoriMigrationReason::kNoReason;
}
bool SyncEncryptionHandlerImpl::AttemptToMigrateNigoriToKeystore(
WriteTransaction* trans,
WriteNode* nigori_node,
NigoriMigrationTrigger migration_trigger) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
const sync_pb::NigoriSpecifics& old_nigori =
nigori_node->GetNigoriSpecifics();
DirectoryCryptographer* cryptographer =
&UnlockVaultMutable(trans->GetWrappedTrans())->cryptographer;
PassphraseType* passphrase_type =
&UnlockVaultMutable(trans->GetWrappedTrans())->passphrase_type;
NigoriMigrationReason migration_reason =
GetMigrationReason(old_nigori, *cryptographer, *passphrase_type);
if (migration_reason == NigoriMigrationReason::kNoReason)
return false;
migration_attempted_ = true;
DVLOG(1) << "Starting nigori migration to keystore support.";
sync_pb::NigoriSpecifics migrated_nigori(old_nigori);
PassphraseType new_passphrase_type =
GetPassphraseType(trans->GetWrappedTrans());
bool new_encrypt_everything = encrypt_everything_;
if (encrypt_everything_ && !IsExplicitPassphrase(*passphrase_type)) {
DVLOG(1) << "Switching to frozen implicit passphrase due to already having "
<< "full encryption.";
new_passphrase_type = PassphraseType::kFrozenImplicitPassphrase;
migrated_nigori.clear_keystore_decryptor_token();
} else if (IsExplicitPassphrase(*passphrase_type)) {
DVLOG_IF(1, !encrypt_everything_) << "Enabling encrypt everything due to "
<< "explicit passphrase";
new_encrypt_everything = true;
migrated_nigori.clear_keystore_decryptor_token();
} else {
DCHECK(!encrypt_everything_);
new_passphrase_type = PassphraseType::kKeystorePassphrase;
DVLOG(1) << "Switching to keystore passphrase state.";
}
migrated_nigori.set_encrypt_everything(new_encrypt_everything);
migrated_nigori.set_passphrase_type(
EnumPassphraseTypeToProto(new_passphrase_type));
if (new_passphrase_type == PassphraseType::kCustomPassphrase) {
if (!custom_passphrase_key_derivation_params_.has_value()) {
// We ended up in a CUSTOM_PASSPHRASE state, but we went through neither
// SetCustomPassphrase() nor SetDecryptionPassphrase()'s
// "already-migrated" path, which are the only places where
// custom_passphrase_key_derivation_params_ is set. Therefore, we must
// have reached this state by, for example, being updated to
// CUSTOM_PASSPHRASE because the keybag was frozen. In these cases, we
// will fall back to PBKDF2 to ensure backwards compatibility.
custom_passphrase_key_derivation_params_ =
KeyDerivationParams::CreateForPbkdf2();
}
UpdateNigoriSpecificsKeyDerivationParams(
custom_passphrase_key_derivation_params_.value(), &migrated_nigori);
}
migrated_nigori.set_keybag_is_frozen(true);
if (!keystore_key_.empty()) {
KeyParams key_params = {KeyDerivationParams::CreateForPbkdf2(),
keystore_key_};
if ((old_keystore_keys_.size() > 0 &&
new_passphrase_type == PassphraseType::kKeystorePassphrase) ||
!cryptographer->is_initialized()) {
// Either at least one key rotation has been performed, so we no longer
// care about backwards compatibility, or we're generating keystore-based
// encryption keys without knowing the GAIA password (and therefore the
// cryptographer is not initialized), so we can't support backwards
// compatibility. Ensure the keystore key is the default key.
DVLOG(1) << "Migrating keybag to keystore key.";
bool cryptographer_was_ready = cryptographer->CanEncrypt();
if (!cryptographer->AddKey(key_params)) {
LOG(ERROR) << "Failed to add keystore key as default key";
UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
FAILED_TO_SET_DEFAULT_KEYSTORE,
MIGRATION_RESULT_SIZE);
return false;
}
if (!cryptographer_was_ready && cryptographer->CanEncrypt()) {
for (auto& observer : observers_) {
observer.OnPassphraseAccepted();
}
}
} else {
// We're in backwards compatible mode -- either the account has an
// explicit passphrase, or we want to preserve the current GAIA-based key
// as the default because we can (there have been no key rotations since
// the migration).
DVLOG(1) << "Migrating keybag while preserving old key";
if (!cryptographer->AddNonDefaultKey(key_params)) {
LOG(ERROR) << "Failed to add keystore key as non-default key.";
UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
FAILED_TO_SET_NONDEFAULT_KEYSTORE,
MIGRATION_RESULT_SIZE);
return false;
}
}
}
if (!old_keystore_keys_.empty()) {
// Go through and add all the old keystore keys as non default keys, so
// they'll be preserved in the encryption_keybag when we next write the
// nigori node.
for (std::vector<std::string>::const_iterator iter =
old_keystore_keys_.begin();
iter != old_keystore_keys_.end(); ++iter) {
KeyParams key_params = {KeyDerivationParams::CreateForPbkdf2(), *iter};
cryptographer->AddNonDefaultKey(key_params);
}
}
if (new_passphrase_type == PassphraseType::kKeystorePassphrase &&
!GetKeystoreDecryptor(
*cryptographer, keystore_key_,
migrated_nigori.mutable_keystore_decryptor_token())) {
LOG(ERROR) << "Failed to extract keystore decryptor token.";
UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
FAILED_TO_EXTRACT_DECRYPTOR,
MIGRATION_RESULT_SIZE);
return false;
}
if (!cryptographer->GetKeys(migrated_nigori.mutable_encryption_keybag())) {
LOG(ERROR) << "Failed to extract encryption keybag.";
UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
FAILED_TO_EXTRACT_KEYBAG, MIGRATION_RESULT_SIZE);
return false;
}
if (keystore_migration_time_.is_null()) {
keystore_migration_time_ = base::Time::Now();
}
migrated_nigori.set_keystore_migration_time(
TimeToProtoTime(keystore_migration_time_));
if (!custom_passphrase_time_.is_null()) {
migrated_nigori.set_custom_passphrase_time(
TimeToProtoTime(custom_passphrase_time_));
}
for (auto& observer : observers_) {
observer.OnCryptographerStateChanged(cryptographer,
cryptographer->has_pending_keys());
}
if (*passphrase_type != new_passphrase_type) {
*passphrase_type = new_passphrase_type;
for (auto& observer : observers_) {
observer.OnPassphraseTypeChanged(
*passphrase_type, GetExplicitPassphraseTime(*passphrase_type));
}
}
if (new_encrypt_everything && !encrypt_everything_) {
EnableEncryptEverythingImpl(trans->GetWrappedTrans());
ReEncryptEverything(trans);
} else if (!cryptographer->CanDecryptUsingDefaultKey(
old_nigori.encryption_keybag())) {
DVLOG(1) << "Rencrypting everything due to key rotation.";
ReEncryptEverything(trans);
}
DVLOG(1) << "Completing nigori migration to keystore support.";
nigori_node->SetNigoriSpecifics(migrated_nigori);
if (new_encrypt_everything &&
(new_passphrase_type == PassphraseType::kFrozenImplicitPassphrase ||
new_passphrase_type == PassphraseType::kCustomPassphrase)) {
NotifyObserversOfLocalCustomPassphrase(trans);
}
switch (new_passphrase_type) {
case PassphraseType::kKeystorePassphrase:
if (old_keystore_keys_.size() > 0) {
UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
MIGRATION_SUCCESS_KEYSTORE_NONDEFAULT,
MIGRATION_RESULT_SIZE);
} else {
UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
MIGRATION_SUCCESS_KEYSTORE_DEFAULT,
MIGRATION_RESULT_SIZE);
}
break;
case PassphraseType::kFrozenImplicitPassphrase:
UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
MIGRATION_SUCCESS_FROZEN_IMPLICIT,
MIGRATION_RESULT_SIZE);
break;
case PassphraseType::kCustomPassphrase:
UMA_HISTOGRAM_ENUMERATION("Sync.AttemptNigoriMigration",
MIGRATION_SUCCESS_CUSTOM,
MIGRATION_RESULT_SIZE);
break;
default:
NOTREACHED();
break;
}
return true;
}
bool SyncEncryptionHandlerImpl::GetKeystoreDecryptor(
const DirectoryCryptographer& cryptographer,
const std::string& keystore_key,
sync_pb::EncryptedData* encrypted_blob) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(!keystore_key.empty());
DCHECK(cryptographer.CanEncrypt());
std::string serialized_nigori;
serialized_nigori = cryptographer.GetDefaultNigoriKeyData();
if (serialized_nigori.empty()) {
LOG(ERROR) << "Failed to get cryptographer bootstrap token.";
return false;
}
DirectoryCryptographer temp_cryptographer;
KeyParams key_params = {KeyDerivationParams::CreateForPbkdf2(), keystore_key};
if (!temp_cryptographer.AddKey(key_params))
return false;
if (!temp_cryptographer.EncryptString(serialized_nigori, encrypted_blob))
return false;
return true;
}
bool SyncEncryptionHandlerImpl::AttemptToInstallKeybag(
const sync_pb::EncryptedData& keybag,
bool update_default,
DirectoryCryptographer* cryptographer) {
if (!cryptographer->CanDecrypt(keybag))
return false;
cryptographer->InstallKeys(keybag);
if (update_default)
cryptographer->SetDefaultKey(keybag.key_name());
return true;
}
void SyncEncryptionHandlerImpl::EnableEncryptEverythingImpl(
syncable::BaseTransaction* const trans) {
ModelTypeSet* encrypted_types = &UnlockVaultMutable(trans)->encrypted_types;
if (encrypt_everything_) {
DCHECK_EQ(EncryptableUserTypes(), *encrypted_types);
return;
}
encrypt_everything_ = true;
*encrypted_types = EncryptableUserTypes();
for (auto& observer : observers_) {
observer.OnEncryptedTypesChanged(*encrypted_types, encrypt_everything_);
}
}
bool SyncEncryptionHandlerImpl::DecryptPendingKeysWithKeystoreKey(
const sync_pb::EncryptedData& keystore_decryptor_token,
DirectoryCryptographer* cryptographer) {
DCHECK(cryptographer->has_pending_keys());
if (keystore_decryptor_token.blob().empty())
return false;
DirectoryCryptographer temp_cryptographer;
// First, go through and all all the old keystore keys to the temporary
// cryptographer.
for (size_t i = 0; i < old_keystore_keys_.size(); ++i) {
KeyParams old_key_params = {KeyDerivationParams::CreateForPbkdf2(),
old_keystore_keys_[i]};
temp_cryptographer.AddKey(old_key_params);
}
// Then add the current keystore key as the default key and see if we can
// decrypt.
KeyParams keystore_params = {KeyDerivationParams::CreateForPbkdf2(),
keystore_key_};
if (temp_cryptographer.AddKey(keystore_params) &&
temp_cryptographer.CanDecrypt(keystore_decryptor_token)) {
// Someone else migrated the nigori for us! How generous! Go ahead and
// install both the keystore key and the new default encryption key
// (i.e. the one provided by the keystore decryptor token) into the
// cryptographer.
// The keystore decryptor token is a keystore key encrypted blob containing
// the current serialized default encryption key (and as such should be
// able to decrypt the nigori node's encryption keybag).
// Note: it's possible a key rotation has happened since the migration, and
// we're decrypting using an old keystore key. In that case we need to
// ensure we re-encrypt using the newest key.
DVLOG(1) << "Attempting to decrypt pending keys using "
<< "keystore decryptor token.";
std::string serialized_nigori;
// TODO(crbug.com/908391): what if the decryption below fails?
temp_cryptographer.DecryptToString(keystore_decryptor_token,
&serialized_nigori);
// This will decrypt the pending keys and add them if possible. The key
// within |serialized_nigori| will be the default after.
cryptographer->ImportNigoriKey(serialized_nigori);
if (!temp_cryptographer.CanDecryptUsingDefaultKey(
keystore_decryptor_token)) {
// The keystore decryptor token was derived from an old keystore key.
// A key rotation is necessary, so set the current keystore key as the
// default key (which will trigger a re-migration).
DVLOG(1) << "Pending keys based on old keystore key. Setting newest "
<< "keystore key as default.";
cryptographer->AddKey(keystore_params);
} else {
// Theoretically the encryption keybag should already contain the keystore
// key. We explicitly add it as a safety measure.
DVLOG(1) << "Pending keys based on newest keystore key.";
cryptographer->AddNonDefaultKey(keystore_params);
}
if (cryptographer->CanEncrypt()) {
std::string bootstrap_token;
cryptographer->GetBootstrapToken(*encryptor_, &bootstrap_token);
DVLOG(1) << "Keystore decryptor token decrypted pending keys.";
// Note: These are separate loops to match previous functionality and not
// out of explicit knowledge that they must be.
for (auto& observer : observers_) {
observer.OnPassphraseAccepted();
}
for (auto& observer : observers_) {
observer.OnBootstrapTokenUpdated(bootstrap_token,
PASSPHRASE_BOOTSTRAP_TOKEN);
}
for (auto& observer : observers_) {
observer.OnCryptographerStateChanged(cryptographer,
cryptographer->has_pending_keys());
}
return true;
}
}
return false;
}
base::Time SyncEncryptionHandlerImpl::GetExplicitPassphraseTime(
PassphraseType passphrase_type) const {
if (passphrase_type == PassphraseType::kFrozenImplicitPassphrase)
return GetKeystoreMigrationTime();
else if (passphrase_type == PassphraseType::kCustomPassphrase)
return custom_passphrase_time();
return base::Time();
}
} // namespace syncer
| 43.067231 | 80 | 0.720984 | sarang-apps |
ff302bbf2a850a3ce0dbf52c2459a4f000214bec | 34,114 | cpp | C++ | Sources/Internationalizator.cpp | Petititi/imGraph | 068890ffe2f8fa1fb51bc95b8d9296cc79737fac | [
"BSD-3-Clause"
] | 2 | 2015-01-12T11:27:45.000Z | 2015-03-25T18:24:38.000Z | Sources/Internationalizator.cpp | Petititi/imGraph | 068890ffe2f8fa1fb51bc95b8d9296cc79737fac | [
"BSD-3-Clause"
] | 30 | 2015-01-07T11:59:07.000Z | 2015-04-24T13:02:01.000Z | Sources/Internationalizator.cpp | Petititi/imGraph | 068890ffe2f8fa1fb51bc95b8d9296cc79737fac | [
"BSD-3-Clause"
] | 1 | 2018-12-20T12:18:18.000Z | 2018-12-20T12:18:18.000Z |
#include "Internationalizator.h"
#ifdef _WIN32
#pragma warning(disable:4503)
#pragma warning(push)
#pragma warning(disable:4996 4251 4275 4800)
#endif
#include <boost/thread/recursive_mutex.hpp>
#include <boost/thread/lock_guard.hpp>
#ifdef _WIN32
#pragma warning(pop)
#endif
using namespace std;
using boost::recursive_mutex;
using boost::lock_guard;
namespace charliesoft
{
recursive_mutex _internationalizatorMutex;
Internationalizator *Internationalizator::ptr = NULL;
boost::format my_format(const std::string & f_string) {
using namespace boost::io;
boost::format fmter(f_string);
fmter.exceptions(no_error_bits);//no exceptions wanted!
return fmter;
}
Internationalizator::Internationalizator()
{
initTranslations();
}
Internationalizator* Internationalizator::getInstance()
{
lock_guard<recursive_mutex> guard(_internationalizatorMutex);
if (ptr == NULL)
ptr = new Internationalizator();
return ptr;
};
void Internationalizator::releaseInstance()
{
lock_guard<recursive_mutex> guard(_internationalizatorMutex);
if (ptr != NULL)
delete ptr;
ptr = NULL;
};
void Internationalizator::setLang(std::string resourceFile)
{
///\todo
};
std::string Internationalizator::getTranslation(std::string key){
if (translations.find(key) != translations.end())
return translations[key];
else
return key;
};
std::string _STR(std::string key)
{
return Internationalizator::getInstance()->getTranslation(key).c_str();
};
QString _QT(std::string key)
{
QString output = Internationalizator::getInstance()->getTranslation(key).c_str();
return output;
};
void Internationalizator::initTranslations()
{
translations["TRUE"] = "True";
translations["FALSE"] = "False";
translations["ALL_TYPES"] = "All types";
translations["BUTTON_OK"] = "OK";
translations["BUTTON_CANCEL"] = "Cancel";
translations["BUTTON_DELETE"] = "Delete";
translations["BUTTON_BROWSE"] = "Browse...";
translations["BUTTON_UPDATE"] = "Update";
translations["BUTTON_COLOR"] = "Color editor";
translations["BUTTON_MATRIX"] = "Matrix editor";
translations["BUTTON_ADD_INPUT"] = "Add input...";
translations["BUTTON_ADD_OUTPUT"] = "Add output...";
translations["BUTTON_SWITCH_SYNC"] = "Change block rendering type<br/>(currently synchrone)";
translations["BUTTON_SWITCH_ASYNC"] = "Change block rendering type<br/>(currently asyncrone)";
translations["BUTTON_SWITCH_ONESHOT"] = "Change block rendering type<br/>(currently one shot)";
translations["TYPE_DATAS_BOOL"] = "Boolean";
translations["TYPE_DATAS_INT"] = "Int";
translations["TYPE_DATAS_FLOAT"] = "Float";
translations["TYPE_DATAS_COLOR"] = "Color";
translations["TYPE_DATAS_MATRIX"] = "Matrix";
translations["TYPE_DATAS_STRING"] = "String";
translations["TYPE_DATAS_FILE"] = "FilePath";
translations["TYPE_DATAS_LISTBOX"] = "ListBox";
translations["TYPE_DATAS_ERROR"] = "typeError";
translations["CONDITION_EDITOR"] = "Condition editor...";
translations["CONDITION_EDITOR_HELP"] = "You can define here which conditions are needed for block rendering!";
translations["CONDITION_BLOCK_ERROR_INPUT"] = "Condition can't be input of block...";
translations["CONDITION_BLOCK_LEFT"] = "left";
translations["CONDITION_BLOCK_HELP"] = "link to the output's block<br/>whose value will be used in condition";
translations["CONDITION_BLOCK_RIGHT"] = "right";
translations["CONDITION_CARDINAL"] = "#rendering";
translations["CONDITION_IS_EMPTY"] = "is empty";
translations["NOT_INITIALIZED"] = "Not initialized...";
translations["PROCESSING_TIME"] = "Mean processing time: ";
translations["BLOCK_OUTPUT"] = "output";
translations["BLOCK_INPUT"] = "input";
translations["BLOCK_TITLE_INPUT"] = "Input";
translations["BLOCK_TITLE_IMG_PROCESS"] = "2D processing";
translations["BLOCK_TITLE_SIGNAL"] = "Video processing";
translations["BLOCK_TITLE_MATH"] = "Math op.";
translations["BLOCK_TITLE_OUTPUT"] = "Output";
translations["BLOCK_TITLE_INFOS"] = "Infos";
translations["BLOCK_INFOS"] =
"<h1>Statistics</h1>"
"<table><tr><td>Mean processing time:</td><td>%1$s ms</td></tr>"
"<tr><td>Max processing time:</td><td>%2$s ms</td></tr>"
"<tr><td>Min processing time:</td><td>%3$s ms</td></tr>"
"<tr><td>Nb rendering:</td><td>%4$s</td></tr></table>"
"<h1>Errors</h1>"
"<p>%5$s</p>";
translations["ERROR_GENERIC"] = "Error undefined!";
translations["ERROR_GENERIC_TITLE"] = "Error!";
translations["ERROR_CONFIRM_SET_VALUE"] = "Wrong input, are you sure you want to set this value?";
translations["ERROR_TYPE"] = "The type of \"%1$s.%2$s\" (%3$s) doesn't correspond to \"%4$s.%5$s\" (%6$s)";
translations["ERROR_LINK_WRONG_INPUT_OUTPUT"] = "You can't link %1$s to %2$s : same type (%3$s)!";
translations["ERROR_LINK_SAME_BLOCK"] = "You can't link the same block!";
translations["ERROR_PARAM_EXCLUSIF"] = "Params \"%1$s\" and \"%2$s\" are mutually exclusive...";
translations["ERROR_PARAM_NEEDED"] = "Param \"%1$s\" is required...";
translations["ERROR_PARAM_ONLY_POSITIF"] = "Param \"%1$s\":<br/>only positive value are authorized!";
translations["ERROR_PARAM_ONLY_POSITIF_STRICT"] = "Param \"%1$s\":<br/>only strict positive value are authorized!";
translations["ERROR_PARAM_ONLY_NEGATIF"] = "Param \"%1$s\":<br/>only negative value are authorized!";
translations["ERROR_PARAM_ONLY_NEGATIF_STRICT"] = "Param \"%1$s\":<br/>only strict negative value are authorized!";
translations["ERROR_PARAM__valueBETWEEN"] = "Param \"%1$s\" (%2$f):<br/>should be between %3$f and %4$f";
translations["ERROR_PARAM_FOUND"] = "Error! Could not find property of \"%1$s\"";
translations["MENU_FILE"] = "File";
translations["MENU_FILE_OPEN"] = "Open";
translations["MENU_FILE_OPEN_TIP"] = "Open a previous project";
translations["MENU_FILE_CREATE"] = "New";
translations["MENU_FILE_CREATE_TIP"] = "Create a new project";
translations["MENU_FILE_SAVE"] = "Save";
translations["MENU_FILE_SAVE_TIP"] = "Save current project";
translations["MENU_FILE_SAVEAS"] = "Save as...";
translations["MENU_FILE_SAVEAS_TIP"] = "Choose file where to save current project";
translations["MENU_FILE_QUIT"] = "Quit";
translations["MENU_FILE_QUIT_TIP"] = "Quit application";
translations["MENU_EDIT"] = "Edit";
translations["MENU_EDIT_SUBGRAPH"] = "Create subprocess";
translations["MENU_EDIT_SUBGRAPH_TIP"] = "Create a subprocess using every selected widgets";
translations["CREATE_PARAM_TITLE"] = "Parameter creation";
translations["CREATE_PARAM_TYPE"] = "Type of the parameter: ";
translations["CREATE_PARAM_NAME"] = "Short name of the parameter: ";
translations["CREATE_PARAM_NAME_HELP"] = "Short description of the parameter: ";
translations["CREATE_PARAM_INIT_VAL"] = "Initial value of the parameter: ";
translations["MATRIX_EDITOR_TOOLS"] = "Tools";
translations["MATRIX_EDITOR_BLOCKS"] = "Blocks";
translations["MATRIX_EDITOR_DATA_CHOICES"] = "Matrix data type:";
translations["MATRIX_EDITOR_DATA_SIZE"] = "Size (rows, cols, channels):";
translations["MATRIX_EDITOR_DATA_INITIAL_VAL"] = "Initial values:";
translations["MATRIX_EDITOR_DATA_INITIAL_VAL_0"] = "zeros";
translations["MATRIX_EDITOR_DATA_INITIAL_VAL_1"] = "constant";
translations["MATRIX_EDITOR_DATA_INITIAL_VAL_2"] = "eye";
translations["MATRIX_EDITOR_DATA_INITIAL_VAL_3"] = "ellipse";
translations["MATRIX_EDITOR_DATA_INITIAL_VAL_4"] = "rect";
translations["MATRIX_EDITOR_DATA_INITIAL_VAL_5"] = "cross";
translations["MATRIX_EDITOR_DATA_INITIAL_VAL_6"] = "random";
translations["MATRIX_EDITOR_SECTION_PEN_COLOR"] = "Color:";
translations["MATRIX_EDITOR_SECTION_PEN_SIZE"] = "Pencil size:";
translations["MATRIX_EDITOR_HELP_LEFT"] = "Panning left (CTRL+arrowLEFT)";
translations["MATRIX_EDITOR_HELP_RIGHT"] = "Panning right (CTRL+arrowRIGHT)";
translations["MATRIX_EDITOR_HELP_UP"] = "Panning up (CTRL+arrowUP)";
translations["MATRIX_EDITOR_HELP_DOWN"] = "Panning down (CTRL+arrowDOWN)";
translations["MATRIX_EDITOR_HELP_ZOOM_X1"] = "Zoom x1 (CTRL+P)";
translations["MATRIX_EDITOR_HELP_ZOOM_IN"] = "Zoom in (CTRL++)";
translations["MATRIX_EDITOR_HELP_ZOOM_OUT"] = "Zoom out (CTRL+-)";
translations["MATRIX_EDITOR_HELP_SAVE"] = "Save current matrix (CTRL+S)";
translations["MATRIX_EDITOR_HELP_LOAD"] = "Load new matrix (CTRL+O)";
translations["MATRIX_EDITOR_HELP_EDIT"] = "Edit matrix (CTRL+E)";
translations["MATRIX_EDITOR_HELP_ONTOP"] = "Always on top (CTRL+T)";
translations["MATRIX_EDITOR_HELP_START"] = "Run graph (Enter)";
translations["MATRIX_EDITOR_HELP_STOP"] = "Stop graph (End)";
translations["MATRIX_EDITOR_HELP_PAUSE"] = "Pause graph (Space)";
translations["MENU_HELP_INFO"] = "Info";
translations["MENU_HELP_HELP"] = "Help";
translations["CONF_FILE_TYPE"] = "imGraph project (*.igp)";
translations["PROJ_LOAD_FILE"] = "Open project file";
translations["PROJ_CREATE_FILE"] = "Create project file";
translations["DOCK_TITLE"] = "Toolbox";
translations["DOCK_PROPERTY_TITLE"] = "Properties";
translations["SUBBLOCK__"] = "Sub graph";
translations["FOR_BLOCK_"] = "for";
translations["FOR_BLOCK_INITVAL"] = "start";
translations["FOR_BLOCK_INITVAL_HELP"] = "Initial value of counter";
translations["FOR_BLOCK_ENDVAL"] = "end";
translations["FOR_BLOCK_ENDVAL_HELP"] = "Final value of counter";
translations["FOR_BLOCK_STEPVAL"] = "step";
translations["FOR_BLOCK_STEPVAL_HELP"] = "Step value of counter";
translations["BLOCK__INPUT_NAME"] = "File Loader";
translations["BLOCK__INPUT_IN_INPUT_TYPE"] = "input";
translations["BLOCK__INPUT_IN_INPUT_TYPE_HELP"] = "Input type|Webcam^Video file^Folder";
translations["BLOCK__INPUT_IN_FILE_HELP"] = "File to load.";
translations["BLOCK__INPUT_IN_FILE_FILTER"] = "media files";
translations["BLOCK__INPUT_IN_FILE_NOT_FOUND"] = "File \"%1$s\" not found!";
translations["BLOCK__INPUT_IN_FILE_NOT_FOLDER"] = "File \"%1$s\" is not a folder!";
translations["BLOCK__INPUT_IN_FILE_PROBLEM"] = "File \"%1$s\" can't be loaded!";
translations["BLOCK__INPUT_IN_LOOP"] = "loop";
translations["BLOCK__INPUT_IN_LOOP_HELP"] = "Loop video file (if <=0, infinite loop)";
translations["BLOCK__INPUT_IN_GREY"] = "grey";
translations["BLOCK__INPUT_IN_GREY_HELP"] = "Convert image to a grayscale one";
translations["BLOCK__INPUT_IN_COLOR"] = "color";
translations["BLOCK__INPUT_IN_COLOR_HELP"] = "Convert image to a color one";
translations["BLOCK__INPUT_OUT_IMAGE"] = "image";
translations["BLOCK__INPUT_OUT_IMAGE_HELP"] = "Output image";
translations["BLOCK__INPUT_OUT_FRAMERATE"] = "framerate";
translations["BLOCK__INPUT_OUT_FRAMERATE_HELP"] = "Number of frames per second";
translations["BLOCK__INPUT_INOUT_WIDTH"] = "width";
translations["BLOCK__INPUT_INOUT_WIDTH_HELP"] = "Wanted width of images (in pixels)";
translations["BLOCK__INPUT_INOUT_HEIGHT"] = "height";
translations["BLOCK__INPUT_INOUT_HEIGHT_HELP"] = "Wanted height of images (in pixels)";
translations["BLOCK__INPUT_INOUT_POS_FRAMES"] = "position";
translations["BLOCK__INPUT_INOUT_POS_FRAMES_HELP"] = "0-based index of the frame to be decoded/captured";
translations["BLOCK__INPUT_INOUT_POS_RATIO"] = "pos. ratio";
translations["BLOCK__INPUT_INOUT_POS_RATIO_HELP"] = "Relative position in the video file (0-begining, 1-end)";
translations["BLOCK__INPUT_OUT_FORMAT"] = "out format";
translations["BLOCK__INPUT_OUT_FORMAT_HELP"] = "The format of the Mat objects";
translations["BLOCK__OUTPUT_NAME"] = "Display image";
translations["BLOCK__OUTPUT_IN_IMAGE"] = "image";
translations["BLOCK__OUTPUT_IN_IMAGE_HELP"] = "Image to show";
translations["BLOCK__OUTPUT_IN_WIN_NAME"] = "win. title";
translations["BLOCK__OUTPUT_IN_WIN_NAME_HELP"] = "Windows title";
translations["BLOCK__OUTPUT_IN_NORMALIZE"] = "normalize";
translations["BLOCK__OUTPUT_IN_NORMALIZE_HELP"] = "Normalize image before show";
translations["BLOCK__SHOWGRAPH_NAME"] = "Show graph";
translations["BLOCK__SHOWGRAPH_IN_VALUES"] = "values";
translations["BLOCK__SHOWGRAPH_IN_VALUES_HELP"] = "Vector of values to show";
translations["BLOCK__SHOWGRAPH_IN_TITLE"] = "title";
translations["BLOCK__SHOWGRAPH_IN_TITLE_HELP"] = "Graph title";
translations["BLOCK__STRING_CREATION_NAME"] = "String creation";
translations["BLOCK__STRING_CREATION_IN_REGEX"] = "pattern";
translations["BLOCK__STRING_CREATION_IN_REGEX_HELP"] = "Pattern name <br/>(use %i% for input i : <br/>\"img%1%.jpg\"<br/> will concatenate first input<br/> with the pattern...)<br/>%n% can also be used:<br/>it's the number of current frame";
translations["BLOCK__STRING_CREATION_OUT"] = "output";
translations["BLOCK__STRING_CREATION_OUT_HELP"] = "Constructed string";
translations["BLOCK__WRITE_NAME"] = "Write video";
translations["BLOCK__WRITE_IN_IMAGE"] = "image";
translations["BLOCK__WRITE_IN_IMAGE_HELP"] = "Image to add to video file";
translations["BLOCK__WRITE_IN_FILENAME"] = "Filename";
translations["BLOCK__WRITE_IN_FILENAME_HELP"] = "Filename of the video file";
translations["BLOCK__WRITE_IN_FPS"] = "FPS";
translations["BLOCK__WRITE_IN_FPS_HELP"] = "Frames per second";
translations["BLOCK__WRITE_IN_CODEC"] = "codec";
translations["BLOCK__WRITE_IN_CODEC_HELP"] = "FOURCC wanted (XVID, X264...).<br/>Empty if you want no compression,<br/>-1 if you want to choose using IHM!";
translations["BLOCK__IMWRITE_NAME"] = "Write image";
translations["BLOCK__IMWRITE_IN_IMAGE"] = "image";
translations["BLOCK__IMWRITE_IN_IMAGE_HELP"] = "Image to save";
translations["BLOCK__IMWRITE_IN_FILENAME"] = "Filename";
translations["BLOCK__IMWRITE_IN_FILENAME_HELP"] = "Filename of the file";
translations["BLOCK__IMWRITE_IN_QUALITY"] = "Quality";
translations["BLOCK__IMWRITE_IN_QUALITY_HELP"] = "Quality of the output img (0->highest compression, 100->highest quality)";
translations["BLOCK__LINEDRAWER_NAME"] = "Draw lines";
translations["BLOCK__LINEDRAWER_IN_LINES"] = "lines list";
translations["BLOCK__LINEDRAWER_IN_LINES_HELP"] = "Input of lines (4 values per row)";
translations["BLOCK__LINEDRAWER_IN_IMAGE"] = "image";
translations["BLOCK__LINEDRAWER_IN_IMAGE_HELP"] = "Input image to draw on";
translations["BLOCK__LINEDRAWER_IN_COLOR"] = "color";
translations["BLOCK__LINEDRAWER_IN_COLOR_HELP"] = "Color of lines";
translations["BLOCK__LINEDRAWER_IN_SIZE"] = "size";
translations["BLOCK__LINEDRAWER_IN_SIZE_HELP"] = "Size of lines";
translations["BLOCK__LINEDRAWER_OUT_IMAGE"] = "image";
translations["BLOCK__LINEDRAWER_OUT_IMAGE_HELP"] = "Binary output image";
translations["BLOCK__POINTDRAWER_NAME"] = "Draw points";
translations["BLOCK__POINTDRAWER_IN_POINTS"] = "point list";
translations["BLOCK__POINTDRAWER_IN_POINTS_HELP"] = "Input of points (2 values per row)";
translations["BLOCK__POINTDRAWER_IN_IMAGE"] = "image";
translations["BLOCK__POINTDRAWER_IN_IMAGE_HELP"] = "Input image to draw on";
translations["BLOCK__POINTDRAWER_IN_COLOR"] = "color";
translations["BLOCK__POINTDRAWER_IN_COLOR_HELP"] = "Color of points";
translations["BLOCK__POINTDRAWER_IN_SIZE"] = "size";
translations["BLOCK__POINTDRAWER_IN_SIZE_HELP"] = "Size of points";
translations["BLOCK__POINTDRAWER_OUT_IMAGE"] = "image";
translations["BLOCK__POINTDRAWER_OUT_IMAGE_HELP"] = "Binary output image";
translations["BLOCK__POINTDRAWER_ERROR_POINT_SIZE"] = "Image and points have different sizes";
translations["BLOCK__CREATEMATRIX_NAME"] = "Create new matrix";
translations["BLOCK__CREATEMATRIX_IN_TYPE"] = "type";
translations["BLOCK__CREATEMATRIX_IN_TYPE_HELP"] = "Wanted type|CV_8U^CV_8S^CV_16U^CV_16S^CV_32S^CV_32F^CV_64F";
translations["BLOCK__CREATEMATRIX_IN_NBCHANNEL"] = "channels";
translations["BLOCK__CREATEMATRIX_IN_NBCHANNEL_HELP"] = "Numbers of channels";
translations["BLOCK__CREATEMATRIX_IN_WIDTH"] = translations["BLOCK__INPUT_INOUT_WIDTH"];
translations["BLOCK__CREATEMATRIX_IN_WIDTH_HELP"] = translations["BLOCK__INPUT_INOUT_WIDTH_HELP"];
translations["BLOCK__CREATEMATRIX_IN_HEIGHT"] = translations["BLOCK__INPUT_INOUT_HEIGHT"];
translations["BLOCK__CREATEMATRIX_IN_HEIGHT_HELP"] = translations["BLOCK__INPUT_INOUT_HEIGHT_HELP"];
translations["BLOCK__CREATEMATRIX_IN_INIT"] = "intialisation";
translations["BLOCK__CREATEMATRIX_IN_INIT_HELP"] = "Initial values of matrix|zeros^ones^eye^ellipse^rect^cross^random uniform^random gaussian";
translations["BLOCK__CREATEMATRIX_OUT_IMAGE"] = "image";
translations["BLOCK__CREATEMATRIX_OUT_IMAGE_HELP"] = "Binary output image";
translations["BLOCK__NORMALIZ_NAME"] = "Normalize image";
translations["BLOCK__NORMALIZ_IN_IMAGE"] = "image";
translations["BLOCK__NORMALIZ_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__NORMALIZ_OUT_IMAGE"] = "image";
translations["BLOCK__NORMALIZ_OUT_IMAGE_HELP"] = "Normalized image";
translations["BLOCK__OPTICFLOW_NAME"] = "Compute Optical flow";
translations["BLOCK__OPTICFLOW_IN_IMAGE1"] = "image1";
translations["BLOCK__OPTICFLOW_IN_IMAGE1_HELP"] = "First image";
translations["BLOCK__OPTICFLOW_IN_IMAGE2"] = "image2";
translations["BLOCK__OPTICFLOW_IN_IMAGE2_HELP"] = "Second image";
translations["BLOCK__OPTICFLOW_IN_METHOD"] = "method";
translations["BLOCK__OPTICFLOW_IN_METHOD_HELP"] = "Method|LK^Farneback^DualTVL1^DeepFlow";
translations["BLOCK__OPTICFLOW_OUT_IMAGE"] = "flow";
translations["BLOCK__OPTICFLOW_OUT_IMAGE_HELP"] = "Optical flow";
translations["BLOCK__LINE_FINDER_NAME"] = "Find lines";
translations["BLOCK__LINE_FINDER_IN_IMAGE"] = "image";
translations["BLOCK__LINE_FINDER_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__LINE_FINDER_OUT_IMAGE"] = "lines";
translations["BLOCK__LINE_FINDER_OUT_IMAGE_HELP"] = "List of detected lines";
translations["BLOCK__POINT_FINDER_NAME"] = "Find points";
translations["BLOCK__POINT_FINDER_IN_IMAGE"] = "image";
translations["BLOCK__POINT_FINDER_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__POINT_FINDER_IN_DETECTOR"] = "detector";
translations["BLOCK__POINT_FINDER_IN_DETECTOR_HELP"] = "Method used to detect points|BRISK^FAST^GFTT^HARRIS^MSER^ORB^SIFT^STAR^SURF^KAZE^AKAZE^SimpleBlob"; //^Grid^Dense
translations["BLOCK__POINT_FINDER_IN_EXTRACTOR"] = "extractor";
translations["BLOCK__POINT_FINDER_IN_EXTRACTOR_HELP"] = "Method used to compute descriptor|SIFT^SURF^ORB^BRIEF^BRISK^MSER^FREAK^KAZE^AKAZE";
translations["BLOCK__POINT_FINDER_OUT_DESC"] = "descriptors";
translations["BLOCK__POINT_FINDER_OUT_DESC_HELP"] = "List of corresponding descriptors";
translations["BLOCK__POINT_FINDER_OUT_POINTS"] = "points";
translations["BLOCK__POINT_FINDER_OUT_POINTS_HELP"] = "List of detected points";
translations["BLOCK__POINT_MATCHER_NAME"] = "Match points";
translations["BLOCK__POINT_MATCHER_IN_PT_DESC1"] = "desc1";
translations["BLOCK__POINT_MATCHER_IN_PT_DESC1_HELP"] = "List of first points descriptors";
translations["BLOCK__POINT_MATCHER_IN_PT_DESC2"] = "desc2";
translations["BLOCK__POINT_MATCHER_IN_PT_DESC2_HELP"] = "List of second points descriptors";
translations["BLOCK__POINT_MATCHER_IN_ALGO"] = "method";
translations["BLOCK__POINT_MATCHER_IN_ALGO_HELP"] = "Method used to match feature vector|Brute force^FLANN";
translations["BLOCK__POINT_MATCHER_OUT_MATCHES"] = "matches";
translations["BLOCK__POINT_MATCHER_OUT_MATCHES_HELP"] = "List of matched points";
translations["BLOCK__POINT_MATCHER_OUT_MATCHES_MASK"] = "mask";
translations["BLOCK__POINT_MATCHER_OUT_MATCHES_MASK_HELP"] = "List of correct matched points";
translations["BLOCK__DEINTERLACE_NAME"] = "Deinterlace";
translations["BLOCK__DEINTERLACE_IN_IMAGE"] = "image";
translations["BLOCK__DEINTERLACE_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__DEINTERLACE_IN_TYPE"] = "Deinterlacing";
translations["BLOCK__DEINTERLACE_IN_TYPE_HELP"] = "Deinterlacing type wanted|Blend^Bob^Discard^Unfold";
translations["BLOCK__DEINTERLACE_OUT_IMAGE"] = "image";
translations["BLOCK__DEINTERLACE_OUT_IMAGE_HELP"] = "Deinterlaced image";
translations["BLOCK__HISTOGRAM_NAME"] = "Histogram";
translations["BLOCK__HISTOGRAM_IN_IMAGE"] = "image";
translations["BLOCK__HISTOGRAM_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__HISTOGRAM_IN_BINS"] = "#bins";
translations["BLOCK__HISTOGRAM_IN_BINS_HELP"] = "number of bins";
translations["BLOCK__HISTOGRAM_IN_ACCUMULATE"] = "accumulate";
translations["BLOCK__HISTOGRAM_IN_ACCUMULATE_HELP"] = "This feature enables you to compute a single histogram from several sets of arrays, or to update the histogram in time";
translations["BLOCK__HISTOGRAM_OUT_HISTO"] = "histo";
translations["BLOCK__HISTOGRAM_OUT_HISTO_HELP"] = "Histogram of the input image";
translations["BLOCK__SKIP_FRAME_NAME"] = "Keep only 1 frame every N frame";
translations["BLOCK__SKIP_FRAME_IN_IMAGE"] = "image";
translations["BLOCK__SKIP_FRAME_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__SKIP_FRAME_IN_TYPE"] = "nb skip";
translations["BLOCK__SKIP_FRAME_IN_TYPE_HELP"] = "Number of frames to skip";
translations["BLOCK__SKIP_FRAME_OUT_IMAGE"] = "image";
translations["BLOCK__SKIP_FRAME_OUT_IMAGE_HELP"] = "Interlaced image";
translations["BLOCK__DELAY_VIDEO_NAME"] = "Delay the video of N frame";
translations["BLOCK__DELAY_VIDEO_IN_IMAGE"] = "image";
translations["BLOCK__DELAY_VIDEO_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__DELAY_VIDEO_IN_DELAY"] = "delay";
translations["BLOCK__DELAY_VIDEO_IN_DELAY_HELP"] = "Number of frames to delay";
translations["BLOCK__DELAY_VIDEO_OUT_IMAGE"] = "image";
translations["BLOCK__DELAY_VIDEO_OUT_IMAGE_HELP"] = "N-th old image";
translations["BLOCK__ADD_NAME"] = "Add";
translations["BLOCK__ADD_IN_PARAM1"] = "input1";
translations["BLOCK__ADD_IN_PARAM1_HELP"] = "First input (Matrix, number...)";
translations["BLOCK__ADD_IN_PARAM2"] = "input2";
translations["BLOCK__ADD_IN_PARAM2_HELP"] = "Second input (Matrix, number...)";
translations["BLOCK__ADD_OUTPUT"] = "sum";
translations["BLOCK__ADD_OUTPUT_HELP"] = "Output sum of the two input (concatenate in case of string)";
translations["BLOCK__CROP_NAME"] = "Crop image";
translations["BLOCK__CROP_IN_IMAGE"] = "image";
translations["BLOCK__CROP_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__CROP_WIDTH"] = translations["BLOCK__INPUT_INOUT_WIDTH"];
translations["BLOCK__CROP_WIDTH_HELP"] = translations["BLOCK__INPUT_INOUT_WIDTH_HELP"];
translations["BLOCK__CROP_HEIGHT"] = translations["BLOCK__INPUT_INOUT_HEIGHT"];
translations["BLOCK__CROP_HEIGHT_HELP"] = translations["BLOCK__INPUT_INOUT_HEIGHT_HELP"];
translations["BLOCK__CROP_IN_X"] = "X";
translations["BLOCK__CROP_IN_X_HELP"] = "Position of top-left corner (X)";
translations["BLOCK__CROP_IN_Y"] = "Y";
translations["BLOCK__CROP_IN_Y_HELP"] = "Position of top-left corner (Y)";
translations["BLOCK__CROP_OUT_IMAGE"] = "image";
translations["BLOCK__CROP_OUT_IMAGE_HELP"] = "Croped image";
translations["BLOCK__ACCUMULATOR_NAME"] = "Accumulator";
translations["BLOCK__ACCUMULATOR_IN_IMAGE"] = "image";
translations["BLOCK__ACCUMULATOR_IN_IMAGE_HELP"] = "Input image to accumulate";
translations["BLOCK__ACCUMULATOR_IN_NB_HISTORY"] = "history";
translations["BLOCK__ACCUMULATOR_IN_NB_HISTORY_HELP"] = "Size of accumulation history";
translations["BLOCK__ACCUMULATOR_OUT_IMAGE"] = "image";
translations["BLOCK__ACCUMULATOR_OUT_IMAGE_HELP"] = "Accumulated image";
translations["BLOCK__MORPHOLOGIC_NAME"] = "Morpho math";
translations["BLOCK__MORPHOLOGIC_IN_IMAGE"] = "image";
translations["BLOCK__MORPHOLOGIC_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__MORPHOLOGIC_ELEMENT"] = "element";
translations["BLOCK__MORPHOLOGIC_ELEMENT_HELP"] = "Structuring element.";
translations["BLOCK__MORPHOLOGIC_OPERATOR"] = "op";
translations["BLOCK__MORPHOLOGIC_OPERATOR_HELP"] = "Operator|open^close^gradient^tophat^blackhat";
translations["BLOCK__MORPHOLOGIC_ITERATIONS"] = "iterations";
translations["BLOCK__MORPHOLOGIC_ITERATIONS_HELP"] = "Number of times erosion and dilation are applied.";
translations["BLOCK__MORPHOLOGIC_OUT_IMAGE"] = "image";
translations["BLOCK__MORPHOLOGIC_OUT_IMAGE_HELP"] = "Filtered image";
translations["BLOCK__CANNY_NAME"] = "Canny";
translations["BLOCK__CANNY_IN_IMAGE"] = "image";
translations["BLOCK__CANNY_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__CANNY_OUT_IMAGE"] = "output";
translations["BLOCK__CANNY_OUT_IMAGE_HELP"] = "Canny image";
translations["BLOCK__CANNY_IN_THRESHOLD_1"] = "Threshold 1";
translations["BLOCK__CANNY_IN_THRESHOLD_1_HELP"] = "1er threshold for the hysteresis procedure";
translations["BLOCK__CANNY_IN_THRESHOLD_2"] = "Threshold 2";
translations["BLOCK__CANNY_IN_THRESHOLD_2_HELP"] = "2nd threshold for the hysteresis procedure";
translations["BLOCK__CANNY_IN_APERTURE_SIZE"] = "Aperture Size";
translations["BLOCK__CANNY_IN_APERTURE_SIZE_HELP"] = "aperture size for the Sobel operator";
translations["BLOCK__CANNY_IN_L2_GRADIENT"] = "L2 Gradient";
translations["BLOCK__CANNY_IN_L2_GRADIENT_HELP"] = "Use more accurate L2 gradient";
translations["BLOCK__INPUT_IN_INPUT_FILE"] = "Input";
translations["BLOCK__INPUT_IN_INPUT_FILE_HELP"] = "File Path";
translations["BLOCK__INPUT_RAW_VIDEO_NAME"] = "YUV reader";
translations["BLOCK__OUTPUT_RAW_VIDEO_NAME"] = "YUV writer";
translations["BLOCK__CASCADECLASSIFIER_NAME"] = "Cascade Classifier";
translations["BLOCK__CASCADECLASSIFIER_IN_IMAGE"] = "image";
translations["BLOCK__CASCADECLASSIFIER_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__CASCADECLASSIFIER_OUT_IMAGE"] = "mask";
translations["BLOCK__CASCADECLASSIFIER_OUT_IMAGE_HELP"] = "Output mask";
translations["BLOCK__CASCADECLASSIFIER_IN_CASCADE_FILE"] = "classifier";
translations["BLOCK__CASCADECLASSIFIER_IN_CASCADE_FILE_HELP"] = "Loads a classifier from a file.";
translations["BLOCK__CASCADECLASSIFIER_IN_SCALE_FACTOR"] = "scaleFactor";
translations["BLOCK__CASCADECLASSIFIER_IN_SCALE_FACTOR_HELP"] = "Parameter specifying how much the image size is reduced at each image scale.";
translations["BLOCK__CASCADECLASSIFIER_IN_MIN_NEIGHBORS"] = "minNeighbors";
translations["BLOCK__CASCADECLASSIFIER_IN_MIN_NEIGHBORS_HELP"] = "Parameter specifying how many neighbors each candidate rectangle should have to retain it.";
translations["BLOCK__CASCADECLASSIFIER_IN_MIN_WIDTH"] = "minWidth";
translations["BLOCK__CASCADECLASSIFIER_IN_MIN_WIDTH_HELP"] = "Minimum possible object width. Objects smaller than that are ignored.";
translations["BLOCK__CASCADECLASSIFIER_IN_MIN_HEIGHT"] = "minHeight";
translations["BLOCK__CASCADECLASSIFIER_IN_MIN_HEIGHT_HELP"] = "Minimum possible object height. Objects smaller than that are ignored.";
translations["BLOCK__CASCADECLASSIFIER_IN_MAX_WIDTH"] = "maxWidth";
translations["BLOCK__CASCADECLASSIFIER_IN_MAX_WIDTH_HELP"] = "Maximum possible object width. Objects larger than that are ignored.";
translations["BLOCK__CASCADECLASSIFIER_IN_MAX_HEIGHT"] = "maxHeight";
translations["BLOCK__CASCADECLASSIFIER_IN_MAX_HEIGHT_HELP"] = "Maximum possible object height. Objects larger than that are ignored.";
translations["BLOCK__CASCADECLASSIFIER_OUT_OBJECTS"] = "#objects";
translations["BLOCK__CASCADECLASSIFIER_OUT_OBJECTS_HELP"] = "Number of detected objects";
translations["BLOCK__BLUR_NAME"] = "Blurring";
translations["BLOCK__BLUR_IN_METHOD"] = "method";
translations["BLOCK__BLUR_IN_METHOD_HELP"] = "Blurring method|Mean^Gaussian^Median^Bilateral";
translations["BLOCK__BLUR_IN_IMG"] = "image";
translations["BLOCK__BLUR_IN_IMG_HELP"] = "Input image";
translations["BLOCK__BLUR_OUT_IMAGE"] = "image";
translations["BLOCK__BLUR_OUT_IMAGE_HELP"] = "Filtered image";
translations["BLOCK__CONVERTMATRIX_NAME"] = "Convert matrix";
translations["BLOCK__CONVERTMATRIX_IN_IMG"] = "image";
translations["BLOCK__CONVERTMATRIX_IN_IMG_HELP"] = "Input image to convert";
translations["BLOCK__CONVERTMATRIX_IN_TYPE"] = "type";
translations["BLOCK__CONVERTMATRIX_IN_TYPE_HELP"] = "Wanted type|CV_8U^CV_8S^CV_16U^CV_16S^CV_32S^CV_32F^CV_64F";
translations["BLOCK__CONVERTMATRIX_IN_NBCHANNEL"] = "channels";
translations["BLOCK__CONVERTMATRIX_IN_NBCHANNEL_HELP"] = "Numbers of channels";
translations["BLOCK__CONVERTMATRIX_OUT_IMAGE"] = "image";
translations["BLOCK__CONVERTMATRIX_OUT_IMAGE_HELP"] = "Binary output image";
translations["BLOCK__RESIZEMATRIX_NAME"] = "Resize matrix";
translations["BLOCK__RESIZEMATRIX_IN_IMG"] = "image";
translations["BLOCK__RESIZEMATRIX_IN_IMG_HELP"] = "Input image to resize";
translations["BLOCK__RESIZEMATRIX_IN_WIDTH"] = translations["BLOCK__INPUT_INOUT_WIDTH"];
translations["BLOCK__RESIZEMATRIX_IN_WIDTH_HELP"] = translations["BLOCK__INPUT_INOUT_WIDTH_HELP"];
translations["BLOCK__RESIZEMATRIX_IN_HEIGHT"] = translations["BLOCK__INPUT_INOUT_HEIGHT"];
translations["BLOCK__RESIZEMATRIX_IN_HEIGHT_HELP"] = translations["BLOCK__INPUT_INOUT_HEIGHT_HELP"];
translations["BLOCK__RESIZEMATRIX_OUT_IMAGE"] = "image";
translations["BLOCK__RESIZEMATRIX_OUT_IMAGE_HELP"] = "Binary output image";
translations["BLOCK__CORE_NAME"] = "CORE filter";
translations["BLOCK__CORE_IN_POINTS"] = "points";
translations["BLOCK__CORE_IN_POINTS_HELP"] = "Input points to filter";
translations["BLOCK__CORE_IN_DESC"] = "descriptors";
translations["BLOCK__CORE_IN_DESC_HELP"] = "Input descriptors to filter";
translations["BLOCK__CORE_IN_THRESHOLD"] = "threshold";
translations["BLOCK__CORE_IN_THRESHOLD_HELP"] = "Threshold value (percent)";
translations["BLOCK__CORE_IN_OPTIM_THRESHOLD"] = "optimization";
translations["BLOCK__CORE_IN_OPTIM_THRESHOLD_HELP"] = "Threshold value of optimization (0->1, 1 for no optimization)";
translations["BLOCK__CORE_OUT_POINTS"] = "points";
translations["BLOCK__CORE_OUT_POINTS_HELP"] = "Filtered points";
translations["BLOCK__CORE_OUT_DESC"] = "descriptors";
translations["BLOCK__CORE_OUT_DESC_HELP"] = "Filtered descriptors";
translations["BLOCK__FILTER2D_NAME"] = "Filter2D";
translations["BLOCK__FILTER2D_IN_IMAGE"] = "image";
translations["BLOCK__FILTER2D_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__FILTER2D_IN_KERNEL"] = "kernel";
translations["BLOCK__FILTER2D_IN_KERNEL_HELP"] = "Convolution kernel ";
translations["BLOCK__FILTER2D_OUT_IMAGE"] = "image";
translations["BLOCK__FILTER2D_OUT_IMAGE_HELP"] = "Output image";
translations["BLOCK__LAPLACIAN_NAME"] = "Laplacian";
translations["BLOCK__LAPLACIAN_IN_IMAGE"] = "image";
translations["BLOCK__LAPLACIAN_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__LAPLACIAN_OUT_IMAGE"] = "image";
translations["BLOCK__LAPLACIAN_OUT_IMAGE_HELP"] = "Output image";
translations["BLOCK__MASKDRAWER_NAME"] = "Draw mask";
translations["BLOCK__MASKDRAWER_IN_IMAGE"] = "image";
translations["BLOCK__MASKDRAWER_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__MASKDRAWER_IN_MASK"] = "mask";
translations["BLOCK__MASKDRAWER_IN_MASK_HELP"] = "Input mask";
translations["BLOCK__MASKDRAWER_IN_PRINTMASK"] = "Masking type";
translations["BLOCK__MASKDRAWER_IN_PRINTMASK_HELP"] = "How to use the mask?|Draw mask^Keep only mask";
translations["BLOCK__MASKDRAWER_OUT_IMAGE"] = "image";
translations["BLOCK__MASKDRAWER_OUT_IMAGE_HELP"] = "Output image";
translations["BLOCK__MASKDRAWER_ERROR_MASK_TYPE"] = "Expected mask of type CV_8UC1";
translations["BLOCK__MASKDRAWER_ERROR_DIFF_SIZE"] = "Image and mask have different sizes";
translations["BLOCK__THINNING_NAME"] = "Thinning img";
translations["BLOCK__THINNING_IN_IMAGE"] = "image";
translations["BLOCK__THINNING_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__THINNING_OUT_IMAGE"] = "image";
translations["BLOCK__THINNING_OUT_IMAGE_HELP"] = "Output image";
translations["BLOCK__DISTANCE_NAME"] = "Distance transform";
translations["BLOCK__DISTANCE_IN_IMAGE"] = "image";
translations["BLOCK__DISTANCE_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__DISTANCE_IN_DISTANCETYPE"] = "distance";
translations["BLOCK__DISTANCE_IN_DISTANCETYPE_HELP"] = "distance type|DIST_C^DIST_L1^DIST_L2^DIST_PRECISE";
translations["BLOCK__DISTANCE_OUT_IMAGE"] = "image";
translations["BLOCK__DISTANCE_OUT_IMAGE_HELP"] = "Output image";
translations["BLOCK__BINARIZE_NAME"] = "Binarize img";
translations["BLOCK__BINARIZE_IN_IMAGE"] = "image";
translations["BLOCK__BINARIZE_IN_IMAGE_HELP"] = "Input image";
translations["BLOCK__BINARIZE_IN_INVERSE"] = "inverse";
translations["BLOCK__BINARIZE_IN_INVERSE_HELP"] = "Use inverse of binary image";
translations["BLOCK__BINARIZE_IN_METHOD"] = "Method";
translations["BLOCK__BINARIZE_IN_METHOD_HELP"] = "Binarization method|Simple threshold^Otsu^Adaptative^Sauvola";
translations["BLOCK__BINARIZE_IN_THRESHOLD"] = "threshold";
translations["BLOCK__BINARIZE_IN_THRESHOLD_HELP"] = "Threshold value";
translations["BLOCK__BINARIZE_OUT_IMAGE"] = "image";
translations["BLOCK__BINARIZE_OUT_IMAGE_HELP"] = "Output image";
}
}
| 58.017007 | 245 | 0.745442 | Petititi |
ff323a68ce6dfe1ce83fa9c3e888758d49e30c7d | 644 | cpp | C++ | data-structures/trees/trie/main.cpp | stoimenoff/OOP-Cpp | 5bd60f2ad1bd8c433c786bb9716853946b37b875 | [
"MIT"
] | 3 | 2017-01-07T23:37:14.000Z | 2017-02-23T06:00:56.000Z | data-structures/trees/trie/main.cpp | stoimenoff/OOP-Cpp | 5bd60f2ad1bd8c433c786bb9716853946b37b875 | [
"MIT"
] | null | null | null | data-structures/trees/trie/main.cpp | stoimenoff/OOP-Cpp | 5bd60f2ad1bd8c433c786bb9716853946b37b875 | [
"MIT"
] | null | null | null | #include <iostream>
#include "trie.h"
using std::cout;
using std::endl;
void testBasicsTrie()
{
Trie<int> map;
map.set("babati", 1);
map.set("babati2", 2);
map.set("babati3", 3);
map.set("babati2dyadoti", 4);
map.set("babati2dyadoti", 5);
cout << map.get("babati2dyadoti") << endl;
assert(map.contains("babati2dyadoti"));
assert(map.contains("babati"));
assert(map.contains("babati2"));
assert(!map.contains("baba"));
assert(!map.contains(""));
map.remove("babati");
map.remove("babati2dyadoti");
assert(!map.contains("babati"));
assert(!map.contains("babati2dyadoti"));
}
int main()
{
testBasicsTrie();
return 0;
}
| 16.512821 | 43 | 0.661491 | stoimenoff |
ff339c084727ed58728297a87a590bdb02575d6f | 6,745 | cpp | C++ | src/hranol.cpp | romeritto/hranol | 71e37d254c7c9ea0f61a0b6ddce3261483dc1809 | [
"MIT"
] | null | null | null | src/hranol.cpp | romeritto/hranol | 71e37d254c7c9ea0f61a0b6ddce3261483dc1809 | [
"MIT"
] | null | null | null | src/hranol.cpp | romeritto/hranol | 71e37d254c7c9ea0f61a0b6ddce3261483dc1809 | [
"MIT"
] | null | null | null | //
// Copyright © 2018 Roman Sobkuliak <r.sobkuliak@gmail.com>
// This code is released under the license described in the LICENSE file
//
#include "../thirdparty/args/args.hxx"
#include "Filter.h"
#include "FolderCrawler.h"
#include "ImageProcessor.h"
#include "ImageStore.h"
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
#include <memory>
class Hranol
{
std::vector< std::string> folders_;
bool recursive_;
bool ram_friendly_;
std::string fname_regex_;
std::string output_folder_;
// Prefix of filtered folders
std::string folder_prefix_;
// Indicates whether folders starting with folder_prefix_ should be included
bool incl_folder_prefix_;
ImageProcessor img_processor_;
public:
// Defaults
Hranol() :
recursive_(false),
ram_friendly_(false),
fname_regex_(".*\\.(jpe?g|gif|tif|tiff|png|bmp)"),
output_folder_(""),
folder_prefix_("fltrd"),
incl_folder_prefix_(false) { }
void parse_from_cli(int argc, char **argv);
void process();
};
void Hranol::parse_from_cli(int argc, char **argv)
{
args::ArgumentParser parser(
"Hranol -- batch image processing utility. By default only images in given folders are processed "
"and the output is saved to a subfolder with prefix \"" + folder_prefix_ + "\". Writing to subfolders "
"can be overridden with option -o which specifies output folder. Supported filters: static background "
"subtraction, contrast filter (normalization) and mask filter. Each filter is used when a corresponding filter-specific "
"option is set. Only grayscale images are supported.",
"Visit the project page for further information: https://github.com/romeritto/hranol");
parser.Prog(argv[0]);
args::ValueFlag<std::string> mask_file(parser, "file",
"Apply mask to every image. The mask size must match the sizes of all images.",
{ 'm', "mask" });
args::ValueFlag<double> subtraction_factor(parser, "subtraction factor",
"Static background subtraction factor. Computes an average of all images (from single folder) and "
"subtracts this average from each image with given factor. You may use positive floating point "
"values for the factor.",
{ 's', "static-noise" });
args::Group rescale(parser, "Rescaling range [b, e] for contrast filter. Pixel values in range [b, e] will be mapped to [0, 255]:");
args::ValueFlag<int> rescale_beg(rescale, "range begin",
"",
{ 'b', "rescale-begin" });
args::ValueFlag<int> rescale_end(rescale, "range end",
"",
{ 'e', "rescale-end" });
args::ValueFlag<std::string> fname_regex(parser, "filename regex",
"If specified, only files matching given regex will be processed. Default value is \"" + fname_regex_ + "\" "
"(matches common image files). Use ECMAScript regex syntax.",
{'f', "fname-regex"});
args::ValueFlag<std::string> output_folder(parser, "output folder",
"Specifies output folder for filtered images. If used together with recursive option original folder structure "
"will be preserved (folders won't be flattened).",
{ 'o', "output-folder" });
args::ValueFlag<std::string> folder_prefix(parser, "filtered folder prefix",
"Specifies prefix of subfolder that will hold filtered images. Default value is \"" + folder_prefix_ + "\"",
{ 'p', "folder-prefix" });
args::Flag incl_folder_prefix(parser, "include filtered folders",
"If set folders found during recursive traversal starting with folder-prefix (specified with "
"option -p) will be processed. By default these folders are ignored so that they don't "
"get filtered twice.",
{ 'i', "incl-fltrd" });
args::Flag recursive(parser, "recursive",
"Process input folders recursively.",
{ 'r', "recursive" });
args::Flag ram_friendly(parser, "ram friendly",
"By default all images from a single folder are stored in memory when the folder is being processed. If that is not possible "
"due to small RAM space, use this flag.",
{ "ram-friendly" });
args::PositionalList<std::string> folders(parser, "folders", "List of folders to process.");
args::HelpFlag help(parser, "help", "Display this help menu", { 'h', "help" });
try {
parser.ParseCLI(argc, argv);
}
catch (const args::Help & e) {
std::cout << parser;
throw;
}
folders_ = std::vector<std::string>(args::get(folders));
if (recursive)
recursive_ = true;
if (ram_friendly)
ram_friendly_ = true;
if (fname_regex)
fname_regex_ = args::get(fname_regex);
if (output_folder)
output_folder_ = args::get(output_folder);
if (folder_prefix)
folder_prefix_ = args::get(folder_prefix);
if (incl_folder_prefix)
incl_folder_prefix_ = true;
if (mask_file)
img_processor_.add_filter(std::move(MaskFilter::create(args::get(mask_file))));
if (subtraction_factor)
img_processor_.add_filter(std::move(BckgSubFilter::create(args::get(subtraction_factor))));
if (rescale_beg || rescale_end)
{
if (rescale_beg && rescale_end)
img_processor_.add_filter(std::move(ContrastFilter::create(
args::get(rescale_beg),
args::get(rescale_end)
)));
else
throw HranolRuntimeException("Both range begin and end must be specified for rescale filter.");
}
}
void Hranol::process()
{
FolderCrawler crawler(
folders_,
output_folder_,
folder_prefix_,
fname_regex_,
incl_folder_prefix_,
recursive_,
ram_friendly_
);
while (crawler.has_next_run())
{
try {
auto store = crawler.get_next_run();
img_processor_.apply_filters(store.get());
}
catch (const std::exception &e) {
std::cout << "\nError (skipping run):\n" << e.what() << std::endl;
}
}
}
int main(int argc, char **argv)
{
Hranol hranol;
try {
hranol.parse_from_cli(argc, argv);
hranol.process();
}
catch (const args::Help & e) {
// Help page was requested
return 0;
}
catch (const args::Error & e) {
// An exception was thrown while processing arguments
std::cerr << e.what() << std::endl;
return 1;
}
catch (std::exception &e) {
std::cerr << e.what() << std::endl;
return 1;
}
catch (...) {
std::cerr << "Unknown error" << std::endl;
return 1;
}
}
| 34.768041 | 136 | 0.630245 | romeritto |
ff373d53a925e6fe2282752ddc1ba9fce00f5b12 | 6,836 | cc | C++ | src/statistics/FactoredMarkovChain.cc | litlpoet/beliefbox | 6b303e49017f8054f43c6c840686fcc632205e4e | [
"OLDAP-2.3"
] | null | null | null | src/statistics/FactoredMarkovChain.cc | litlpoet/beliefbox | 6b303e49017f8054f43c6c840686fcc632205e4e | [
"OLDAP-2.3"
] | null | null | null | src/statistics/FactoredMarkovChain.cc | litlpoet/beliefbox | 6b303e49017f8054f43c6c840686fcc632205e4e | [
"OLDAP-2.3"
] | null | null | null | /* -*- Mode: c++; -*- */
// copyright (c) 2009 by Christos Dimitrakakis <christos.dimitrakakis@gmail.com>
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "FactoredMarkovChain.h"
#include "Random.h"
FactoredMarkovChain::FactoredMarkovChain(int n_actions_, int n_obs_,
int mem_size_)
: T(0),
n_actions(n_actions_),
n_obs(n_obs_),
n_states(n_obs * n_actions),
mem_size(mem_size_),
n_contexts((Context)pow((double)n_states, (double)mem_size)),
transitions(n_contexts, n_obs),
act_history(mem_size),
obs_history(mem_size),
history(mem_size),
threshold(0.5) {
printf(
"# Making FMC with %d actions, %d obs, %d states, %d history, %lld "
"contexts\n",
n_actions, n_obs, n_states, mem_size, n_contexts);
for (int i = 0; i < mem_size; ++i) {
act_history[i] = 0;
obs_history[i] = 0;
history[i] = 0;
}
}
FactoredMarkovChain::~FactoredMarkovChain() {}
/** Calculate the current context.
Calculates the current contexts up to the time the
last action was taken.
*/
FactoredMarkovChain::Context FactoredMarkovChain::CalculateContext() {
#if 0
Context context = 0;
Context n = 1;
for (Context i=0; i<mem_size; i++, n*=n_states) {
context += history[i]*n;
}
#else
Context context = history.get_id(n_states);
#endif
return context;
}
/** Calculate the current context taking into account that there is an extra
observation.
Calculates the current contexts up to the time the
last action was taken.
*/
FactoredMarkovChain::Context FactoredMarkovChain::getContext(int act) {
assert((obs_history.size() == 1 + act_history.size()) &&
(act_history.size() == history.size()));
// first set up the context component due to the most recent observation
// and postulated next action
if (mem_size == 0) {
return 0;
}
Context context = CalculateState(act, obs_history.back());
Context n = n_states;
// continue with the remaining context
for (Context i = 0; i < mem_size - 1; i++, n *= n_states) {
context += history[i] * n;
}
return context;
}
/** Obtain an observation.
This should only be used at the first time step, before any actions are
taken.
@return Probability of having observed the next state.
*/
real FactoredMarkovChain::Observe(int prd) {
PushObservation(prd);
return 1.0 / (real)n_obs;
}
/** Train the chain with a new observation
A side-effect is that it updates the current_context.
@return Probability of having observed the next state.
*/
real FactoredMarkovChain::Observe(int act, int prd) {
PushAction(act);
current_context = CalculateContext();
real Pr = getProbability(current_context, prd);
// printf("%d %d %d %f # act obx ctx P\n", act, prd, current_context, Pr);
transitions.observe(current_context, prd);
PushObservation(prd);
return Pr;
}
/** Probability of a next observation
\return The probability of observing x
*/
real FactoredMarkovChain::ObservationProbability(int x) {
return getProbability(current_context, x);
}
/** Probability of an observation given a particular action.
\return The probability of observing prd given act.
*/
real FactoredMarkovChain::ObservationProbability(int a, int x) {
assert((a >= 0) && (a < n_actions));
return getProbability(getContext(a), x);
}
#if 0
void FactoredMarkovChain::getNextStateProbabilities(int act, std::vector<real>& p)
{
curr_state = CalculateStateID();
return getProbabilities(curr_state, p);
}
#endif
/// Get the number of transitions from \c context to \c prd
real FactoredMarkovChain::getTransition(Context context, int prd) {
assert((context >= 0) && (context < n_contexts));
assert((prd >= 0) && (prd < n_states));
return transitions.get_weight(context, prd);
}
/// Get the transition probability from \c context to \c prd
///
/// Takes into account the threshold.
real FactoredMarkovChain::getProbability(Context context, int prd) {
assert((context >= 0) && (context < n_contexts));
assert((prd >= 0) && (prd < n_obs));
real sum = 0.0;
int N = transitions.nof_destinations();
for (int i = 0; i < N; ++i) {
sum += transitions.get_weight(context, i);
}
return (transitions.get_weight(context, prd) + threshold) /
(sum + threshold * ((real)N));
}
/// Get the transition probabilities
///
/// Takes into account the threshold.
void FactoredMarkovChain::getProbabilities(Context context,
std::vector<real>& p) {
assert((context >= 0) && (context < n_contexts));
assert((int)p.size() == n_states);
real sum = 0.0;
int N = transitions.nof_destinations();
for (int i = 0; i < N; ++i) {
p[i] = threshold + transitions.get_weight(context, i);
sum += p[i];
}
real invsum = 1.0 / sum;
for (int i = 0; i < N; ++i) {
p[i] *= invsum;
}
}
/**
\brief Reset the chain
Sets the state (and history) to 0. Call before training for
distinct sequences and before generating a new
sequence. (Otherwise training and generation will depend on past
sequences).
*/
void FactoredMarkovChain::Reset() {
int i;
for (i = 0; i < mem_size; i++) {
history[i] = 0;
act_history[i] = 0;
obs_history[i] = 0;
}
current_context = 0;
}
/**
\brief Generate values from the chain.
Generates a new observation based on the current state history,
according to the transition tables. Note that you might generate as
many new states as you wish. The state history must be explicitly
updated by calling MarkovChainPushState() with the generated value
(or one of the generated values, if you have called this multiple
times, or if you are selecting a generated value from a number of
different markov chains).
\arg \c chain: A pointer to the chain
\return The ID of the next state, as generated by the MC. Returns -1 if
nothing could be generated.
*/
int FactoredMarkovChain::GenerateStatic() {
real tot = 0.0f;
// int curr = CalculateStateID ();
real sel = urandom();
for (int j = 0; j < n_states; j++) {
real P = 0.0; // Pr[curr + j*tot_states];
tot += P;
if (sel <= tot && P > 0.0f) {
return j;
}
}
return -1;
}
| 29.593074 | 82 | 0.628877 | litlpoet |
ff40f54d6ec76897d60f928773241dfc493e7dd4 | 3,328 | cpp | C++ | Programming/Sem2/Lab4/lab4.cpp | NazarPonochevnyi/Programming-Labs | 30afedcdf79f1b7e91be62a34d4bb3a399eb3c9f | [
"MIT"
] | 1 | 2020-10-17T13:18:29.000Z | 2020-10-17T13:18:29.000Z | Programming/Sem2/Lab4/lab4.cpp | NazarPonochevnyi/Programming-Labs | 30afedcdf79f1b7e91be62a34d4bb3a399eb3c9f | [
"MIT"
] | null | null | null | Programming/Sem2/Lab4/lab4.cpp | NazarPonochevnyi/Programming-Labs | 30afedcdf79f1b7e91be62a34d4bb3a399eb3c9f | [
"MIT"
] | 1 | 2021-11-08T00:35:35.000Z | 2021-11-08T00:35:35.000Z | #include <iostream>
using namespace std;
/*
10. Перевантажити оператори потокового введення-виведення (>>,<<).
*/
class Fraction
{
protected:
int numerator, denominator;
int nod(int a, int b);
int nok(int a, int b);
public:
Fraction();
Fraction(int num, int den);
Fraction(const Fraction& f);
void addition(const Fraction& f);
void subtraction(const Fraction& f);
void multiplication(const Fraction& f);
void print();
~Fraction();
friend Fraction operator +(const Fraction& a, const Fraction& b);
Fraction& operator =(const Fraction& d);
friend istream& operator >>(istream& s, Fraction& f);
friend ostream& operator <<(ostream& s, const Fraction& f);
};
Fraction::Fraction() {
numerator = 1;
denominator = 2;
}
Fraction::Fraction(int num, int den) {
if (den == 0) {
cout << "Error: division by zero!\n";
cout << 1/0;
}
if (num >= den) {
cout << "Error: fraction must be < 1! Use Any_Fraction fraction.\n";
cout << 1/0;
}
numerator = num;
denominator = den;
}
Fraction::Fraction(const Fraction& f) {
numerator = f.numerator;
denominator = f.denominator;
}
int Fraction::nod(int a, int b) {
while (a != 0 && b != 0) {
if (a > b) {
a = a % b;
}
else b = b % a;
}
return a + b;
}
int Fraction::nok(int a, int b) {
return a * b / Fraction::nod(a, b);
}
void Fraction::addition(const Fraction& f) {
int cd = nok(denominator, f.denominator);
numerator = (numerator * (cd / denominator)) + (f.numerator * (cd / f.denominator));
denominator = cd;
}
void Fraction::subtraction(const Fraction& f) {
Fraction f1 = Fraction(f);
f1.numerator *= -1;
Fraction::addition(f1);
}
void Fraction::multiplication(const Fraction& f) {
numerator *= f.numerator;
denominator *= f.denominator;
}
void Fraction::print() {
cout << numerator << "/" << denominator;
}
Fraction::~Fraction() {
numerator = 0;
denominator = 0;
}
Fraction operator +(const Fraction& a, const Fraction& b) {
Fraction c = Fraction(a);
c.addition(b);
return c;
}
Fraction& Fraction::operator =(const Fraction& f) {
numerator = f.numerator;
denominator = f.denominator;
return *this;
}
istream& operator >>(istream& s, Fraction& f) {
cout << "Enter fraction:\n";
s >> f.numerator;
cout << "--\n";
s >> f.denominator;
return s;
}
ostream& operator <<(ostream& s, const Fraction& f) {
s << f.numerator << "/" << f.denominator;
return s;
}
class Any_Fraction : public Fraction
{
public:
Any_Fraction();
Any_Fraction(int num, int den);
Any_Fraction(const Any_Fraction& f);
};
Any_Fraction::Any_Fraction() {
numerator = 1;
denominator = 2;
}
Any_Fraction::Any_Fraction(int num, int den) {
if (den == 0) {
cout << "Error: division by zero!\n";
cout << 1/0;
}
numerator = num;
denominator = den;
}
Any_Fraction::Any_Fraction(const Any_Fraction& f) {
numerator = f.numerator;
denominator = f.denominator;
}
int main()
{
Fraction f1, f2, f3;
cin >> f1;
cin >> f2;
f3 = f1 + f2;
cout << "f1 + f2: " << f3;
return 0;
}
| 21.063291 | 88 | 0.577524 | NazarPonochevnyi |
ff4285ba2020e89c392910195bfb7d1eb946b892 | 1,916 | cc | C++ | csrc/vectorizedJNIwrapper.cc | SoftwareStartups/vectorization | 93a27569876aa4a9b3798ed658002508a12a31ff | [
"MIT"
] | null | null | null | csrc/vectorizedJNIwrapper.cc | SoftwareStartups/vectorization | 93a27569876aa4a9b3798ed658002508a12a31ff | [
"MIT"
] | null | null | null | csrc/vectorizedJNIwrapper.cc | SoftwareStartups/vectorization | 93a27569876aa4a9b3798ed658002508a12a31ff | [
"MIT"
] | null | null | null | /*
* Jos van Eijndhoven, Vector Fabrics
* The 'com_vectorfabrics_vectorizeLib.h' was generated by 'javah' from the java class interface
*/
#include "com_vectorfabrics_vectorizeLib.h"
#include "Vectorized.h"
extern "C" {
//const char * __stdcall vectorizedVersionName() {
// Vectorized& veclib = VectorizedFactory::get();
//
// return veclib.versionName();
//}
JNIEXPORT jstring JNICALL Java_com_vectorfabrics_vectorizeLib_vectorizedVersionName
(JNIEnv *env, jobject obj) {
Vectorized& veclib = VectorizedFactory::get();
const char *name = veclib.versionName();
return env->NewStringUTF(name);
}
//float __stdcall vectorizedInproduct( unsigned int n, const float *a, const float *b) {
// Vectorized& veclib = VectorizedFactory::get();
//
// return veclib.inproduct(n, a, a);
//}
JNIEXPORT jfloat JNICALL Java_com_vectorfabrics_vectorizeLib_vectorizedInproduct
(JNIEnv *env, jobject obj, jint n, jfloatArray a, jfloatArray b) {
Vectorized& veclib = VectorizedFactory::get();
float *a_body = env->GetFloatArrayElements( a, 0);
float *b_body = env->GetFloatArrayElements( b, 0);
float r = veclib.inproduct(n, a_body, b_body);
env->ReleaseFloatArrayElements( a, a_body, 0);
env->ReleaseFloatArrayElements( b, b_body, 0);
return (jfloat)r;
}
//float __stdcall vectorizedAverage( unsigned int n, const float *a) {
// Vectorized& veclib = VectorizedFactory::get();
//
// return veclib.average(n, a);
//}
JNIEXPORT jfloat JNICALL Java_com_vectorfabrics_vectorizeLib_vectorizedAverage
(JNIEnv *env, jobject obj, jint n, jfloatArray a) {
Vectorized& veclib = VectorizedFactory::get();
float *a_body = env->GetFloatArrayElements( a, 0);
float r = veclib.average(n, a_body);
env->ReleaseFloatArrayElements( a, a_body, 0);
return (jfloat)r;
}
}
| 31.409836 | 97 | 0.683194 | SoftwareStartups |
ff434d0fd0e5b68931982659497b3c4ce24c6e1b | 1,186 | cpp | C++ | reve/reve/lib/SplitEntryBlockPass.cpp | mattulbrich/llreve | 68cb958c1c02177fa0db1965a8afd879a97c2fc4 | [
"BSD-3-Clause"
] | 20 | 2016-08-11T19:51:13.000Z | 2021-09-02T13:10:58.000Z | reve/reve/lib/SplitEntryBlockPass.cpp | mattulbrich/llreve | 68cb958c1c02177fa0db1965a8afd879a97c2fc4 | [
"BSD-3-Clause"
] | 9 | 2016-08-11T11:59:24.000Z | 2021-07-16T09:44:28.000Z | reve/reve/lib/SplitEntryBlockPass.cpp | mattulbrich/llreve | 68cb958c1c02177fa0db1965a8afd879a97c2fc4 | [
"BSD-3-Clause"
] | 7 | 2017-08-19T14:42:27.000Z | 2020-05-20T16:14:13.000Z | /*
* This file is part of
* llreve - Automatic regression verification for LLVM programs
*
* Copyright (C) 2016 Karlsruhe Institute of Technology
*
* The system is published under a BSD license.
* See LICENSE (distributed with this file) for details.
*/
#include "SplitEntryBlockPass.h"
#include "llvm/IR/Instructions.h"
llvm::PreservedAnalyses
SplitBlockPass::run(llvm::Function &Fun, llvm::FunctionAnalysisManager &fam) {
auto &Entry = Fun.getEntryBlock();
Entry.splitBasicBlock(Entry.begin());
std::vector<llvm::Instruction *> splitAt;
for (auto &BB : Fun) {
for (auto &Inst : BB) {
if (const auto CallInst = llvm::dyn_cast<llvm::CallInst>(&Inst)) {
if ((CallInst->getCalledFunction() != nullptr) &&
CallInst->getCalledFunction()->getName() == "__splitmark") {
splitAt.push_back(CallInst);
}
}
}
}
for (auto instr : splitAt) {
llvm::BasicBlock::iterator i(instr);
++i;
i->getParent()->splitBasicBlock(i);
instr->getParent()->splitBasicBlock(instr);
}
return llvm::PreservedAnalyses::none();
}
| 31.210526 | 80 | 0.611298 | mattulbrich |
ff458f2db095189a0cbb3b2cf0497bee16c6a515 | 810 | cpp | C++ | src/Game Engine/Material.cpp | JKneedler/JK-Game-Engine | 00a3a3c4833d12c4a93ae98b2508419700450e66 | [
"Apache-2.0"
] | 1 | 2021-05-10T17:29:30.000Z | 2021-05-10T17:29:30.000Z | src/Game Engine/Material.cpp | JKneedler/JK-Game-Engine | 00a3a3c4833d12c4a93ae98b2508419700450e66 | [
"Apache-2.0"
] | null | null | null | src/Game Engine/Material.cpp | JKneedler/JK-Game-Engine | 00a3a3c4833d12c4a93ae98b2508419700450e66 | [
"Apache-2.0"
] | null | null | null | #include "Material.h"
Material::Material() {
specularIntensity = 0.0f;
shininess = 0.0f;
}
Material::Material(GLfloat sIntensity, GLfloat shine) {
specularIntensity = sIntensity;
shininess = shine;
}
Material::Material(Shader* myShader, Texture* myTexture, GLfloat sIntensity, GLfloat shine) {
shader = myShader;
texture = myTexture;
specularIntensity = sIntensity;
shininess = shine;
}
void Material::UseMaterial() {
glUniform1f(shader->GetSpecularIntensityLocation(), specularIntensity);
glUniform1f(shader->GetShininessLocation(), shininess);
texture->UseTexture();
}
void Material::UseMaterial(GLuint specularIntensityLocation, GLuint shininessLocation) {
glUniform1f(specularIntensityLocation, specularIntensity);
glUniform1f(shininessLocation, shininess);
}
Material::~Material() {
}
| 23.823529 | 93 | 0.774074 | JKneedler |
ff4644aac0d4c7e8cf9dbe074c6ca22148fe09f3 | 5,013 | hpp | C++ | include/Zenject/MethodMultipleProviderUntyped.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/Zenject/MethodMultipleProviderUntyped.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/Zenject/MethodMultipleProviderUntyped.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: Zenject.IProvider
#include "Zenject/IProvider.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Zenject
namespace Zenject {
// Forward declaring type: DiContainer
class DiContainer;
// Forward declaring type: InjectContext
class InjectContext;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Func`2<T, TResult>
template<typename T, typename TResult>
class Func_2;
// Forward declaring type: Type
class Type;
// Forward declaring type: Action
class Action;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: IEnumerable`1<T>
template<typename T>
class IEnumerable_1;
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Size: 0x20
#pragma pack(push, 1)
// Autogenerated type: Zenject.MethodMultipleProviderUntyped
// [NoReflectionBakingAttribute] Offset: DDD0C0
class MethodMultipleProviderUntyped : public ::Il2CppObject/*, public Zenject::IProvider*/ {
public:
// private readonly Zenject.DiContainer _container
// Size: 0x8
// Offset: 0x10
Zenject::DiContainer* container;
// Field size check
static_assert(sizeof(Zenject::DiContainer*) == 0x8);
// private readonly System.Func`2<Zenject.InjectContext,System.Collections.Generic.IEnumerable`1<System.Object>> _method
// Size: 0x8
// Offset: 0x18
System::Func_2<Zenject::InjectContext*, System::Collections::Generic::IEnumerable_1<::Il2CppObject*>*>* method;
// Field size check
static_assert(sizeof(System::Func_2<Zenject::InjectContext*, System::Collections::Generic::IEnumerable_1<::Il2CppObject*>*>*) == 0x8);
// Creating value type constructor for type: MethodMultipleProviderUntyped
MethodMultipleProviderUntyped(Zenject::DiContainer* container_ = {}, System::Func_2<Zenject::InjectContext*, System::Collections::Generic::IEnumerable_1<::Il2CppObject*>*>* method_ = {}) noexcept : container{container_}, method{method_} {}
// Creating interface conversion operator: operator Zenject::IProvider
operator Zenject::IProvider() noexcept {
return *reinterpret_cast<Zenject::IProvider*>(this);
}
// public System.Void .ctor(System.Func`2<Zenject.InjectContext,System.Collections.Generic.IEnumerable`1<System.Object>> method, Zenject.DiContainer container)
// Offset: 0x16C5BA8
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static MethodMultipleProviderUntyped* New_ctor(System::Func_2<Zenject::InjectContext*, System::Collections::Generic::IEnumerable_1<::Il2CppObject*>*>* method, Zenject::DiContainer* container) {
static auto ___internal__logger = ::Logger::get().WithContext("Zenject::MethodMultipleProviderUntyped::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<MethodMultipleProviderUntyped*, creationType>(method, container)));
}
// public System.Boolean get_IsCached()
// Offset: 0x16C5BE0
bool get_IsCached();
// public System.Boolean get_TypeVariesBasedOnMemberType()
// Offset: 0x16C5BE8
bool get_TypeVariesBasedOnMemberType();
// public System.Type GetInstanceType(Zenject.InjectContext context)
// Offset: 0x16C5BF0
System::Type* GetInstanceType(Zenject::InjectContext* context);
// public System.Void GetAllInstancesWithInjectSplit(Zenject.InjectContext context, System.Collections.Generic.List`1<Zenject.TypeValuePair> args, out System.Action injectAction, System.Collections.Generic.List`1<System.Object> buffer)
// Offset: 0x16C5C0C
void GetAllInstancesWithInjectSplit(Zenject::InjectContext* context, System::Collections::Generic::List_1<Zenject::TypeValuePair>* args, System::Action*& injectAction, System::Collections::Generic::List_1<::Il2CppObject*>* buffer);
}; // Zenject.MethodMultipleProviderUntyped
#pragma pack(pop)
static check_size<sizeof(MethodMultipleProviderUntyped), 24 + sizeof(System::Func_2<Zenject::InjectContext*, System::Collections::Generic::IEnumerable_1<::Il2CppObject*>*>*)> __Zenject_MethodMultipleProviderUntypedSizeCheck;
static_assert(sizeof(MethodMultipleProviderUntyped) == 0x20);
}
DEFINE_IL2CPP_ARG_TYPE(Zenject::MethodMultipleProviderUntyped*, "Zenject", "MethodMultipleProviderUntyped");
| 53.903226 | 244 | 0.738081 | darknight1050 |
ff4a04e5c02452aa59ddc8c7d2fc73ce9b308c2e | 10,961 | cpp | C++ | src/pqclean.cpp | Cryptario/tidecoin | 550b726eb7f39730086522676a9c74e40d672a81 | [
"MIT"
] | 30 | 2021-01-05T02:08:40.000Z | 2022-01-21T09:32:10.000Z | src/pqclean.cpp | Cryptario/tidecoin | 550b726eb7f39730086522676a9c74e40d672a81 | [
"MIT"
] | 8 | 2021-03-15T08:14:30.000Z | 2022-02-02T11:37:14.000Z | src/pqclean.cpp | Cryptario/tidecoin | 550b726eb7f39730086522676a9c74e40d672a81 | [
"MIT"
] | 20 | 2021-01-09T00:03:48.000Z | 2022-03-07T11:58:35.000Z | #include "api.h"
#include "inner.h"
#include "randombytes.h"
#include <stddef.h>
#include <string.h>
/*
* Wrapper for implementing the PQClean API.
*/
#define NONCELEN 40
#define SEEDLEN 48
/*
* Encoding formats (nnnn = log of degree, 9 for Falcon-512, 10 for Falcon-1024)
*
* private key:
* header byte: 0101nnnn
* private f (6 or 5 bits by element, depending on degree)
* private g (6 or 5 bits by element, depending on degree)
* private F (8 bits by element)
*
* public key:
* header byte: 0000nnnn
* public h (14 bits by element)
*
* signature:
* header byte: 0011nnnn
* nonce 40 bytes
* value (12 bits by element)
*
* message + signature:
* signature length (2 bytes, big-endian)
* nonce 40 bytes
* message
* header byte: 0010nnnn
* value (12 bits by element)
* (signature length is 1+len(value), not counting the nonce)
*/
/* see api.h */
int
PQCLEAN_FALCON512_CLEAN_crypto_sign_keypair(unsigned char *pk, unsigned char *sk) {
union {
uint8_t b[FALCON_KEYGEN_TEMP_9];
uint64_t dummy_u64;
fpr dummy_fpr;
} tmp;
int8_t f[512], g[512], F[512];
uint16_t h[512];
unsigned char seed[SEEDLEN];
inner_shake256_context rng;
size_t u, v;
/*
* Generate key pair.
*/
randombytes(seed, sizeof seed);
inner_shake256_init(&rng);
inner_shake256_inject(&rng, seed, sizeof seed);
inner_shake256_flip(&rng);
PQCLEAN_FALCON512_CLEAN_keygen(&rng, f, g, F, NULL, h, 9, tmp.b);
inner_shake256_ctx_release(&rng);
/*
* Encode private key.
*/
sk[0] = 0x50 + 9;
u = 1;
v = PQCLEAN_FALCON512_CLEAN_trim_i8_encode(
sk + u, PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES - u,
f, 9, PQCLEAN_FALCON512_CLEAN_max_fg_bits[9]);
if (v == 0) {
return -1;
}
u += v;
v = PQCLEAN_FALCON512_CLEAN_trim_i8_encode(
sk + u, PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES - u,
g, 9, PQCLEAN_FALCON512_CLEAN_max_fg_bits[9]);
if (v == 0) {
return -1;
}
u += v;
v = PQCLEAN_FALCON512_CLEAN_trim_i8_encode(
sk + u, PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES - u,
F, 9, PQCLEAN_FALCON512_CLEAN_max_FG_bits[9]);
if (v == 0) {
return -1;
}
u += v;
if (u != PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES) {
return -1;
}
/*
* Encode public key.
*/
pk[0] = 0x00 + 9;
v = PQCLEAN_FALCON512_CLEAN_modq_encode(
pk + 1, PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES - 1,
h, 9);
if (v != PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES - 1) {
return -1;
}
return 0;
}
/*
* Compute the signature. nonce[] receives the nonce and must have length
* NONCELEN bytes. sigbuf[] receives the signature value (without nonce
* or header byte), with *sigbuflen providing the maximum value length and
* receiving the actual value length.
*
* If a signature could be computed but not encoded because it would
* exceed the output buffer size, then a new signature is computed. If
* the provided buffer size is too low, this could loop indefinitely, so
* the caller must provide a size that can accommodate signatures with a
* large enough probability.
*
* Return value: 0 on success, -1 on error.
*/
static int
do_sign(uint8_t *nonce, uint8_t *sigbuf, size_t *sigbuflen,
const uint8_t *m, size_t mlen, const uint8_t *sk) {
union {
uint8_t b[72 * 512];
uint64_t dummy_u64;
fpr dummy_fpr;
} tmp;
int8_t f[512], g[512], F[512], G[512];
union {
int16_t sig[512];
uint16_t hm[512];
} r;
unsigned char seed[SEEDLEN];
inner_shake256_context sc;
size_t u, v;
/*
* Decode the private key.
*/
if (sk[0] != 0x50 + 9) {
return -1;
}
u = 1;
v = PQCLEAN_FALCON512_CLEAN_trim_i8_decode(
f, 9, PQCLEAN_FALCON512_CLEAN_max_fg_bits[9],
sk + u, PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES - u);
if (v == 0) {
return -1;
}
u += v;
v = PQCLEAN_FALCON512_CLEAN_trim_i8_decode(
g, 9, PQCLEAN_FALCON512_CLEAN_max_fg_bits[9],
sk + u, PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES - u);
if (v == 0) {
return -1;
}
u += v;
v = PQCLEAN_FALCON512_CLEAN_trim_i8_decode(
F, 9, PQCLEAN_FALCON512_CLEAN_max_FG_bits[9],
sk + u, PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES - u);
if (v == 0) {
return -1;
}
u += v;
if (u != PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES) {
return -1;
}
if (!PQCLEAN_FALCON512_CLEAN_complete_private(G, f, g, F, 9, tmp.b)) {
return -1;
}
/*
* Create a random nonce (40 bytes).
*/
randombytes(nonce, NONCELEN);
/*
* Hash message nonce + message into a vector.
*/
inner_shake256_init(&sc);
inner_shake256_inject(&sc, nonce, NONCELEN);
inner_shake256_inject(&sc, m, mlen);
inner_shake256_flip(&sc);
PQCLEAN_FALCON512_CLEAN_hash_to_point_ct(&sc, r.hm, 9, tmp.b);
inner_shake256_ctx_release(&sc);
/*
* Initialize a RNG.
*/
randombytes(seed, sizeof seed);
inner_shake256_init(&sc);
inner_shake256_inject(&sc, seed, sizeof seed);
inner_shake256_flip(&sc);
/*
* Compute and return the signature. This loops until a signature
* value is found that fits in the provided buffer.
*/
for (;;) {
PQCLEAN_FALCON512_CLEAN_sign_dyn(r.sig, &sc, f, g, F, G, r.hm, 9, tmp.b);
v = PQCLEAN_FALCON512_CLEAN_comp_encode(sigbuf, *sigbuflen, r.sig, 9);
if (v != 0) {
inner_shake256_ctx_release(&sc);
*sigbuflen = v;
return 0;
}
}
}
/*
* Verify a sigature. The nonce has size NONCELEN bytes. sigbuf[]
* (of size sigbuflen) contains the signature value, not including the
* header byte or nonce. Return value is 0 on success, -1 on error.
*/
static int
do_verify(
const uint8_t *nonce, const uint8_t *sigbuf, size_t sigbuflen,
const uint8_t *m, size_t mlen, const uint8_t *pk) {
union {
uint8_t b[2 * 512];
uint64_t dummy_u64;
fpr dummy_fpr;
} tmp;
uint16_t h[512], hm[512];
int16_t sig[512];
inner_shake256_context sc;
/*
* Decode public key.
*/
if (pk[0] != 0x00 + 9) {
return -1;
}
if (PQCLEAN_FALCON512_CLEAN_modq_decode(h, 9,
pk + 1, PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES - 1)
!= PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES - 1) {
return -1;
}
PQCLEAN_FALCON512_CLEAN_to_ntt_monty(h, 9);
/*
* Decode signature.
*/
if (sigbuflen == 0) {
return -1;
}
if (PQCLEAN_FALCON512_CLEAN_comp_decode(sig, 9, sigbuf, sigbuflen) != sigbuflen) {
return -1;
}
/*
* Hash nonce + message into a vector.
*/
inner_shake256_init(&sc);
inner_shake256_inject(&sc, nonce, NONCELEN);
inner_shake256_inject(&sc, m, mlen);
inner_shake256_flip(&sc);
PQCLEAN_FALCON512_CLEAN_hash_to_point_ct(&sc, hm, 9, tmp.b);
inner_shake256_ctx_release(&sc);
/*
* Verify signature.
*/
if (!PQCLEAN_FALCON512_CLEAN_verify_raw(hm, sig, h, 9, tmp.b)) {
return -1;
}
return 0;
}
/* see api.h */
int
PQCLEAN_FALCON512_CLEAN_crypto_sign_signature(
uint8_t *sig, size_t *siglen,
const uint8_t *m, size_t mlen, const uint8_t *sk) {
/*
* The PQCLEAN_FALCON512_CLEAN_CRYPTO_BYTES constant is used for
* the signed message object (as produced by PQCLEAN_FALCON512_CLEAN_crypto_sign())
* and includes a two-byte length value, so we take care here
* to only generate signatures that are two bytes shorter than
* the maximum. This is done to ensure that PQCLEAN_FALCON512_CLEAN_crypto_sign()
* and PQCLEAN_FALCON512_CLEAN_crypto_sign_signature() produce the exact same signature
* value, if used on the same message, with the same private key,
* and using the same output from randombytes() (this is for
* reproducibility of tests).
*/
size_t vlen;
vlen = PQCLEAN_FALCON512_CLEAN_CRYPTO_BYTES - NONCELEN - 3;
if (do_sign(sig + 1, sig + 1 + NONCELEN, &vlen, m, mlen, sk) < 0) {
return -1;
}
sig[0] = 0x30 + 9;
*siglen = 1 + NONCELEN + vlen;
return 0;
}
/* see api.h */
int
PQCLEAN_FALCON512_CLEAN_crypto_sign_verify(
const uint8_t *sig, size_t siglen,
const uint8_t *m, size_t mlen, const uint8_t *pk) {
if (siglen < 1 + NONCELEN) {
return -1;
}
if (sig[0] != 0x30 + 9) {
return -1;
}
return do_verify(sig + 1,
sig + 1 + NONCELEN, siglen - 1 - NONCELEN, m, mlen, pk);
}
/* see api.h */
int
PQCLEAN_FALCON512_CLEAN_crypto_sign(
uint8_t *sm, size_t *smlen,
const uint8_t *m, size_t mlen, const uint8_t *sk) {
uint8_t *pm, *sigbuf;
size_t sigbuflen;
/*
* Move the message to its final location; this is a memmove() so
* it handles overlaps properly.
*/
memmove(sm + 2 + NONCELEN, m, mlen);
pm = sm + 2 + NONCELEN;
sigbuf = pm + 1 + mlen;
sigbuflen = PQCLEAN_FALCON512_CLEAN_CRYPTO_BYTES - NONCELEN - 3;
if (do_sign(sm + 2, sigbuf, &sigbuflen, pm, mlen, sk) < 0) {
return -1;
}
pm[mlen] = 0x20 + 9;
sigbuflen ++;
sm[0] = (uint8_t)(sigbuflen >> 8);
sm[1] = (uint8_t)sigbuflen;
*smlen = mlen + 2 + NONCELEN + sigbuflen;
return 0;
}
/* see api.h */
int
PQCLEAN_FALCON512_CLEAN_crypto_sign_open(
uint8_t *m, size_t *mlen,
const uint8_t *sm, size_t smlen, const uint8_t *pk) {
const uint8_t *sigbuf;
size_t pmlen, sigbuflen;
if (smlen < 3 + NONCELEN) {
return -1;
}
sigbuflen = ((size_t)sm[0] << 8) | (size_t)sm[1];
if (sigbuflen < 2 || sigbuflen > (smlen - NONCELEN - 2)) {
return -1;
}
sigbuflen --;
pmlen = smlen - NONCELEN - 3 - sigbuflen;
if (sm[2 + NONCELEN + pmlen] != 0x20 + 9) {
return -1;
}
sigbuf = sm + 2 + NONCELEN + pmlen + 1;
/*
* The 2-byte length header and the one-byte signature header
* have been verified. Nonce is at sm+2, followed by the message
* itself. Message length is in pmlen. sigbuf/sigbuflen point to
* the signature value (excluding the header byte).
*/
if (do_verify(sm + 2, sigbuf, sigbuflen,
sm + 2 + NONCELEN, pmlen, pk) < 0) {
return -1;
}
/*
* Signature is correct, we just have to copy/move the message
* to its final destination. The memmove() properly handles
* overlaps.
*/
memmove(m, sm + 2 + NONCELEN, pmlen);
*mlen = pmlen;
return 0;
}
| 28.396373 | 102 | 0.608612 | Cryptario |
ff4b38a4728f42c4ae1c9496caf88c4fa657ce83 | 833 | cpp | C++ | C++/questions/reverse_string.cpp | nihilesh/sharpner | bb74a20cebb5de284b50b1b81dc5b4b7fca34b7c | [
"Apache-2.0"
] | null | null | null | C++/questions/reverse_string.cpp | nihilesh/sharpner | bb74a20cebb5de284b50b1b81dc5b4b7fca34b7c | [
"Apache-2.0"
] | null | null | null | C++/questions/reverse_string.cpp | nihilesh/sharpner | bb74a20cebb5de284b50b1b81dc5b4b7fca34b7c | [
"Apache-2.0"
] | null | null | null | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
// Routines
char* rstrdup(const char* str);
void reverse_string(char* str);
int
main() {
char str[] = "Atul Patil";
char* rstr = rstrdup(str);
reverse_string(str);
printf("%s ==> %s\n", str, rstr);
return 0;
}
char *
rstrdup(const char *str) {
if (!str) return NULL;
char* rstr = strdup(str);
reverse_string(rstr);
return rstr;
}
void
reverse_string(char *str) {
if (!str) return;
int len = strlen(str);
char* start = str;
char* end = str + len - 1;
while(start < end) {
char tmp = *start;
*start = *end;
*end = tmp;
start++; end--;
}
return;
}
class String {
private:
Array<char, 10> str;
public:
String(): str(""){}
String(const char* str) str(str){}
String(const String s) str(s.str){}
~String(){}
}
| 16.019231 | 37 | 0.591837 | nihilesh |
ff540ed7fe00ca0cf59e4ab4d3a0bc8afce4a42d | 19,429 | cpp | C++ | incoming/BitBucket-INDI1/trunk186/INDI2/plugins/vigilPlugin/VigilBehavior.cpp | eirTony/INDI1 | 42642d8c632da53f60f2610b056547137793021b | [
"MIT"
] | null | null | null | incoming/BitBucket-INDI1/trunk186/INDI2/plugins/vigilPlugin/VigilBehavior.cpp | eirTony/INDI1 | 42642d8c632da53f60f2610b056547137793021b | [
"MIT"
] | 14 | 2016-11-24T10:46:39.000Z | 2016-12-10T07:24:15.000Z | incoming/BitBucket-INDI1/trunk186/INDI2/plugins/vigilPlugin/VigilBehavior.cpp | eirTony/INDI1 | 42642d8c632da53f60f2610b056547137793021b | [
"MIT"
] | null | null | null | #include "VigilBehavior.h"
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QUrl>
#include <QtNetwork/QHostAddress>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QTcpSocket>
#include <eirExe/Log.h>
#include <eirExe/ResultId.h>
#include <eirNetwork/HttpManager.h>
#include <eirFrameSource/FrameSourceState.h>
#include <eirFrameSource/FrameSourceResult.h>
#include "VigilPlugin.h"
VigilBehavior::VigilBehavior(void)
: _manager(0)
, _reply(0)
, currentGet_mst(MillisecondTime::current())
{
}
FrameSourceBehavior * VigilBehavior::brother(void)
{
return new VigilBehavior();
}
QString VigilBehavior::name(void) const
{
return "vigil";
}
QStringList VigilBehavior::schemeList(void)
{
FUNCTION();
FNRETURN("vigilLive vigilPlay" );
return QStringList() << "vigilLive" << "vigilPlay";
}
bool VigilBehavior::supports(const QUrl & url)
{
FUNCTION();
bool b = ("vigilLive" == url.scheme() || "vigilPlay" == url.scheme());
FNRETURN(b);
return b;
}
bool VigilBehavior::supportsScheme(const QString & scheme)
{
FUNCTION();
bool b = ("vigilLive" == scheme || "vigilPlay" == scheme);
FNRETURN(b);
return b;
}
/*--- common ---*/
void VigilBehavior::getResult(MillisecondTime mst,
bool isError,
ResultSet rset)
{
FUNCTION(qint64(mst), isError, rset.size());
RESULTS(rset);
FSPPOINTER(FrameSourcePlugin, _plugin);
if (FrameSourceState::Grabbing == _plugin->state()
&& "vigilLive" == _plugin->url().scheme())
handleLiveGrab(mst, isError, rset);
else if (FrameSourceState::Grabbing == _plugin->state()
&& "vigilPlay" == _plugin->url().scheme())
handlePlayGrab(mst, isError, rset);
else if (FrameSourceState::Starting == _plugin->state()
&& "vigilPlay" == _plugin->url().scheme())
handlePlayStarting(mst, isError, rset);
else
WATCH("Unhandled getResult()");
}
/*===== Construct =====*/
void VigilBehavior::enterConstruct(void)
{
FUNCTION();
FSPPOINTER(FrameSourcePlugin, _plugin);
_socket = new QTcpSocket(_plugin);
_manager = new HttpManager(_plugin);
OBJPOINTER(QTcpSocket, _socket);
OBJPOINTER(HttpManager, _manager);
CONNECT(_socket, SIGNAL(connected()),
_plugin, SLOT(connectResult()));
CONNECT(_socket, SIGNAL(error(QAbstractSocket::SocketError)),
_plugin, SLOT(connectResult()));
ResultSet rset;
rset << Result(FrameSourceResult::Initialized, name());
_plugin->emitInitialized(rset);
}
/*===== Connect =====*/
void VigilBehavior::enterConnecting(void)
{
FUNCTION();
OBJPOINTER(QTcpSocket, _socket);
FSPPOINTER(FrameSourcePlugin, _plugin);
_socket->connectToHost(_plugin->url().host(),
_plugin->url().port(80));
TRACE("connectToHost(%1, %2)", _plugin->url().host(),
_plugin->url().port(80));
}
void VigilBehavior::connectResult(void)
{
FUNCTION();
if (EXPECTNE(0, _socket)) return;
OBJPOINTER(QTcpSocket, _socket);
FSPPOINTER(FrameSourcePlugin, _plugin);
ResultSet rset;
if (EXPECTEQ(QAbstractSocket::ConnectedState, _socket->state()))
{
rset.add(Result(FrameSourceResult::HttpConnectSuccess,
_plugin->url().toString()));
_plugin->emitConnected(rset);
_socket->disconnectFromHost();
}
else
{
rset.add(Result(FrameSourceResult::HttpConnectFailure,
_plugin->url(),
_socket->state(),
_socket->error(),
_socket->errorString()));
_plugin->emitConnectError(rset);
}
RESULTS(rset);
}
void VigilBehavior::exitConnecting(void)
{
FUNCTION();
currentGet_mst = MillisecondTime::null();
if ( ! EXPECTNE(0, _socket)) return;
OBJPOINTER(QTcpSocket, _socket);
_socket->close();
_socket->deleteLater();
_socket = 0;
TODO("GET(xml) if enumeration needed")
}
/*===== Configure =====*/
void VigilBehavior::enterConfiguring(void)
{
FUNCTION();
FSPPOINTER(FrameSourcePlugin, _plugin);
VariableSet config = _plugin->configuration();
connect_msec = config.value("ConnectMsec").toInt();
start_msec = config.value("StartMsec").toInt();
get_msec = config.value("GetMsec").toInt();
maxRetry_i = config.value("MaxRetry").toInt();
if ( ! connect_msec) connect_msec = 5000;
if ( ! start_msec) start_msec = 20000;
if ( ! get_msec) get_msec = 5000;
if ( ! maxRetry_i) maxRetry_i = 5;
TODO("Collect configuration: Resolution");
_plugin->emitConfigured(ResultSet());
}
/*===== Start =====*/
void VigilBehavior::enterStarted(void)
{
FUNCTION();
OBJPOINTER(HttpManager, _manager);
FSPPOINTER(FrameSourcePlugin, _plugin);
QUrl url(_plugin->url());
if ("vigilPlay" == url.scheme())
{
url.setScheme("http");
url.setPath("playback");
url.addQueryItem("cmd", "startsession");
url.addQueryItem("camera", QString::number(_plugin->channel()));
if ( ! _plugin->beginMst().isNull())
url.addQueryItem("from", _plugin->beginMst().toString("yyyy-MM-dd hh:mm"));
if ( ! _plugin->endMst().isNull())
url.addQueryItem("to", _plugin->endMst().toString("yyyy-MM-dd hh:mm"));
currentGet_mst = _manager->get(url, start_msec);
TRACE("Start GET done");
session_i = session_n = 0;
}
else if ("vigilLive" == url.scheme())
{
ResultSet rset;
rset << Result(FrameSourceResult::Started, _plugin->url());
_plugin->emitStarted(rset);
}
retry_k = 0;
CONNECT(_manager, SIGNAL(got(MillisecondTime,bool,ResultSet)),
_plugin, SLOT(getResult(MillisecondTime,bool,ResultSet)));
}
void VigilBehavior::handlePlayStarting(MillisecondTime mst,
bool isError,
ResultSet rset)
{
FUNCTION(qint64(mst), isError, rset.size());
RESULTS(rset);
FSPPOINTER(FrameSourcePlugin, _plugin);
OBJPOINTER(HttpManager, _manager);
ResultSet ourResult;
if (isError)
{
if (rset.is(Severity::Error))
{
Result errRes = rset.find(HttpManager::HttpGetFailure);
ourResult << errRes;
_plugin->emitGrabError(ourResult);
}
else if (rset.is(Severity::Warning))
{
Result errRes = rset.find(HttpManager::HttpGetTimeout);
ourResult << errRes;
_plugin->emitGrabTimeout(ourResult);
}
else
_plugin->emitGrabError(rset);
}
else
{
EXPECTNOT(session_i);
EXPECTNOT(session_n);
QString sResult;
Result dataRes = rset.find(HttpManager::HttpGotData);
DUMPVAR(dataRes.value("MimeType").toString());
if ( ! dataRes.isNull())
{
sResult = dataRes.value("ByteArray").toByteArray();
if (dataRes.value("MimeType").toString().contains("text/plain"))
{
QUrl url(dataRes.value("RequestURL").toUrl());
TRACE("%1 from %2", sResult, url.toString());
EXPECTNOT(sResult.isEmpty());
EXPECTEQ(sResult.size(), dataRes.value("ExpectedBytes").toInt());
EXPECT("playback" == url.path());
EXPECT("startsession" == url.queryItemValue("cmd"));
QStringList qsl(sResult.split(','));
if (EXPECTEQ(3, qsl.size())
&& EXPECTEQ("result:ok", qsl.at(2)))
{
if (EXPECT(qsl.at(0).startsWith("session:")))
session_i = qsl.at(0).mid(QString("session:").size()).toInt();
if (EXPECT(qsl.at(1).startsWith("totalframes:")))
session_n = qsl.at(1).mid(QString("totalframes:").size()).toInt();
}
}
else if (dataRes.value("MimeType").toString().contains("text/html"))
{
int x = sResult.indexOf("<body");
sResult = sResult.mid(x + QString("<body").length());
DUMPVAR(sResult);
x = sResult.indexOf('>');
sResult = sResult.mid(x + QString(">").length());
DUMPVAR(sResult);
x = sResult.indexOf("</body>");
sResult.truncate(x);
DUMPVAR(sResult);
}
else
{
WARNING("Unhandled MimeType: %1", dataRes.value("MimeType"));
}
}
if (session_i && session_n)
{
currentFrame_i = 1;
ourResult << Result(FrameSourceResult::Started,
_plugin->url(),
session_n);
_plugin->emitStarted(ourResult);
}
else
{
ourResult << Result(FrameSourceResult::StartError,
_plugin->url(), sResult);
_plugin->emitStartError(ourResult);
}
}
EXPECTEQ(currentGet_mst, mst);
currentGet_mst = MillisecondTime::null();
RESULTS(ourResult);
}
void VigilBehavior::exitRunning(void)
{
FUNCTION();
OBJPOINTER(HttpManager, _manager);
FSPPOINTER(FrameSourcePlugin, _plugin);
DISCONNECT(_manager, SIGNAL(got(MillisecondTime,bool,ResultSet)),
_plugin, SLOT(getResult(MillisecondTime,bool,ResultSet)));
_manager->abort();
QUrl url(_plugin->url());
if ("vigilPlay" == url.scheme())
{
url.setScheme("http");
url.setPath("playback");
url.addQueryItem("cmd", "stopsession");
url.addQueryItem("session", QString::number(session_i));
_manager->get(url);
TRACE("Stop GET done");
currentFrame_i = session_i = session_n = 0;
}
}
void VigilBehavior::enterFinished(void)
{
FUNCTION();
}
/*===== Grab =====*/
bool VigilBehavior::canGrab(void)
{
FUNCTION();
bool b = true;
if ( ! currentGet_mst.isNull())
b = false;
else if ("vigilPlay" == _plugin->url().scheme())
{
if (session_n < currentFrame_i)
{
ResultSet rset;
rset << Result(FrameSourceResult::PlaybackComplete,
session_n,
_plugin->url(),
_plugin->beginMst().toString(),
_plugin->endMst().toString());
_plugin->emitComplete(rset);
b = false;
}
}
FNRETURN(b);
return b;
}
void VigilBehavior::enterGrabbing(void)
{
FUNCTION();
OBJPOINTER(HttpManager, _manager);
FSPPOINTER(FrameSourcePlugin, _plugin);
QUrl url(_plugin->url());
if ("vigilLive" == url.scheme())
{
url.setScheme("http");
url.setPath("live");
url.addQueryItem("camera", QString::number(_plugin->channel()));
url.addQueryItem("resolution", "VGA");
url.addQueryItem("quality", "90");
currentGet_mst = _manager->get(url, get_msec);
TRACE("Grab GET done");
}
else if ("vigilPlay" == url.scheme())
{
url.setScheme("http");
url.setPath("playback");
url.addQueryItem("cmd", "getimage");
url.addQueryItem("frame", QString::number(currentFrame_i));
url.addQueryItem("session", QString::number(session_i));
url.addQueryItem("resolution", "VGA");
currentGet_mst = _manager->get(url, get_msec);
TRACE("Grab GET done");
}
else
{
WARNING("Unhandled scheme: %1", url.scheme());
}
}
void VigilBehavior::handlePlayGrab(MillisecondTime mst,
bool isError,
ResultSet rset)
{
FUNCTION(qint64(mst), isError, rset.toStringList());
RESULTS(rset);
FSPPOINTER(FrameSourcePlugin, _plugin);
OBJPOINTER(HttpManager, _manager);
ResultSet ourResult;
if (isError)
{
if (rset.is(Severity::Error))
{
Result errRes = rset.find(HttpManager::HttpGetFailure);
ourResult << errRes;
_plugin->emitGrabError(ourResult);
}
else if (rset.is(Severity::Warning))
{
Result errRes = rset.find(HttpManager::HttpGetTimeout);
ourResult << errRes;
_plugin->emitGrabTimeout(ourResult);
}
else
_plugin->emitGrabError(rset);
}
else
{
Result dataRes = rset.find(HttpManager::HttpGotData);
if ( ! dataRes.isNull())
{
QByteArray ba(dataRes.value("ByteArray").toByteArray());
EXPECTNOT(ba.isEmpty());
EXPECTEQ(ba.size(), dataRes.value("ExpectedBytes").toInt());
DUMPVAR(dataRes.value("MimeType").toString());
if (EXPECT(dataRes.value("MimeType").toString().contains("image/jpeg")))
{
QString FrameId = QString("F%1").arg(currentFrame_i, 7, 10, QChar('0'));
ImageEntity frameEntity
= ImageEntity::fromByteArray(ba,
currentGet_mst,
FrameId);
_plugin->enqueueGrab(frameEntity);
Result goodRes = rset.find(HttpManager::HttpGetSuccess);
EXPECTNOT(goodRes.isNull());
ourResult << goodRes;
_plugin->emitGrabbed(ourResult);
++currentFrame_i;
if (retry_k > 0) --retry_k;
}
else if (dataRes.value("MimeType").toString().contains("text/plain"))
{
QString sResult = dataRes.value("ByteArray").toString();
QUrl url(dataRes.value("RequestURL").toUrl());
TRACE("%1 from %2", sResult, url.toString());
EXPECTEQ(sResult.size(), dataRes.value("ExpectedBytes").toInt());
ourResult << Result(HttpManager::HttpGetFailure, -1, sResult);
_plugin->emitGrabError(ourResult);
}
else if (dataRes.value("MimeType").toString().contains("text/html"))
{
QString sResult = dataRes.value("ByteArray").toString();
int x = sResult.indexOf("<body");
sResult = sResult.mid(x + QString("<body").length());
DUMPVAR(sResult);
x = sResult.indexOf('>');
sResult = sResult.mid(x + QString(">").length());
DUMPVAR(sResult);
x = sResult.indexOf("</body>");
sResult.truncate(x);
DUMPVAR(sResult);
ourResult << Result(HttpManager::HttpGetFailure, -2, sResult);
_plugin->emitGrabError(ourResult);
}
else
{
WARNING("Unhandled MimeType: %1", dataRes.value("MimeType"));
}
}
}
RESULTS(ourResult);
EXPECTEQ(currentGet_mst, mst);
currentGet_mst = MillisecondTime::null();
}
void VigilBehavior::handleLiveGrab(MillisecondTime mst,
bool isError,
ResultSet rset)
{
FUNCTION(qint64(mst), isError, rset.toStringList());
RESULTS(rset);
FSPPOINTER(FrameSourcePlugin, _plugin);
OBJPOINTER(HttpManager, _manager);
ResultSet ourResult;
if (isError)
{
if (rset.is(Severity::Error))
{
Result errRes = rset.find(HttpManager::HttpGetFailure);
ourResult << errRes;
_plugin->emitGrabError(ourResult);
}
else if (rset.is(Severity::Warning))
{
Result errRes = rset.find(HttpManager::HttpGetTimeout);
ourResult << errRes;
_plugin->emitGrabTimeout(ourResult);
}
else
_plugin->emitGrabError(rset);
}
else
{
Result dataRes = rset.find(HttpManager::HttpGotData);
if ( ! dataRes.isNull())
{
QByteArray ba(dataRes.value("ByteArray").toByteArray());
EXPECTNOT(ba.isEmpty());
EXPECTEQ(ba.size(), dataRes.value("ExpectedBytes").toInt());
DUMPVAR(dataRes.value("MimeType").toString());
if (EXPECT(dataRes.value("MimeType").toString().contains("image/jpeg")))
{
ImageEntity frameEntity
= ImageEntity::fromByteArray(ba, currentGet_mst);
_plugin->enqueueGrab(frameEntity);
Result goodRes = rset.find(HttpManager::HttpGetSuccess);
EXPECTNOT(goodRes.isNull());
ourResult << goodRes;
RESULTS(ourResult);
_plugin->emitGrabbed(ourResult);
if (retry_k > 0) --retry_k;
}
else if (dataRes.value("MimeType").toString().contains("text/plain"))
{
QString sResult = dataRes.value("ByteArray").toString();
QUrl url(dataRes.value("RequestURL").toUrl());
TRACE("%1 from %2", sResult, url.toString());
EXPECTEQ(sResult.size(), dataRes.value("ExpectedBytes").toInt());
ourResult << Result(HttpManager::HttpGetFailure, -1, sResult);
_plugin->emitGrabError(ourResult);
}
else if (dataRes.value("MimeType").toString().contains("text/html"))
{
QString sResult = dataRes.value("ByteArray").toString();
int x = sResult.indexOf("<body");
sResult = sResult.mid(x + QString("<body").length());
DUMPVAR(sResult);
x = sResult.indexOf('>');
sResult = sResult.mid(x + QString(">").length());
DUMPVAR(sResult);
x = sResult.indexOf("</body>");
sResult.truncate(x);
DUMPVAR(sResult);
ourResult << Result(HttpManager::HttpGetFailure, -2, sResult);
_plugin->emitGrabError(ourResult);
}
else
{
WARNING("Unhandled MimeType: %1", dataRes.value("MimeType"));
}
}
}
RESULTS(ourResult);
EXPECTEQ(currentGet_mst, mst);
currentGet_mst = MillisecondTime::null();
}
void VigilBehavior::enterRetry(void)
{
FUNCTION();
FSPPOINTER(FrameSourcePlugin, _plugin);
if (++retry_k > maxRetry_i)
{
ResultSet rset;
rset << Result(HttpManager::HttpGetFailure,
-retry_k, "Excessive Timeout");
_plugin->emitGrabError(rset);
}
DUMPVAR(retry_k);
}
| 33.672444 | 91 | 0.538628 | eirTony |
ff54c9d4d7b7d0696bd05648edbab9e85b613522 | 2,555 | cc | C++ | oos/src/model/ValidateTemplateContentResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | oos/src/model/ValidateTemplateContentResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | oos/src/model/ValidateTemplateContentResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/oos/model/ValidateTemplateContentResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Oos;
using namespace AlibabaCloud::Oos::Model;
ValidateTemplateContentResult::ValidateTemplateContentResult() :
ServiceResult()
{}
ValidateTemplateContentResult::ValidateTemplateContentResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ValidateTemplateContentResult::~ValidateTemplateContentResult()
{}
void ValidateTemplateContentResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allTasksNode = value["Tasks"]["Task"];
for (auto valueTasksTask : allTasksNode)
{
Task tasksObject;
if(!valueTasksTask["Name"].isNull())
tasksObject.name = valueTasksTask["Name"].asString();
if(!valueTasksTask["Type"].isNull())
tasksObject.type = valueTasksTask["Type"].asString();
if(!valueTasksTask["Description"].isNull())
tasksObject.description = valueTasksTask["Description"].asString();
if(!valueTasksTask["Properties"].isNull())
tasksObject.properties = valueTasksTask["Properties"].asString();
if(!valueTasksTask["Outputs"].isNull())
tasksObject.outputs = valueTasksTask["Outputs"].asString();
tasks_.push_back(tasksObject);
}
if(!value["Parameters"].isNull())
parameters_ = value["Parameters"].asString();
if(!value["RamRole"].isNull())
ramRole_ = value["RamRole"].asString();
if(!value["Outputs"].isNull())
outputs_ = value["Outputs"].asString();
}
std::vector<ValidateTemplateContentResult::Task> ValidateTemplateContentResult::getTasks()const
{
return tasks_;
}
std::string ValidateTemplateContentResult::getParameters()const
{
return parameters_;
}
std::string ValidateTemplateContentResult::getRamRole()const
{
return ramRole_;
}
std::string ValidateTemplateContentResult::getOutputs()const
{
return outputs_;
}
| 29.367816 | 95 | 0.751468 | iamzken |
ff564dbfe66e096e358331bd69b90c2d9ea14bf8 | 9,796 | cpp | C++ | McEngine/src/GUI/CBaseUISlider.cpp | musikowskipawel/McEngine | fcd96ecf1d04a6b44545ea06b7531e8816e61368 | [
"MIT"
] | 73 | 2016-09-12T09:55:53.000Z | 2022-03-26T22:18:35.000Z | McEngine/src/GUI/CBaseUISlider.cpp | musikowskipawel/McEngine | fcd96ecf1d04a6b44545ea06b7531e8816e61368 | [
"MIT"
] | 31 | 2016-08-08T18:05:33.000Z | 2022-03-10T09:27:33.000Z | McEngine/src/GUI/CBaseUISlider.cpp | musikowskipawel/McEngine | fcd96ecf1d04a6b44545ea06b7531e8816e61368 | [
"MIT"
] | 17 | 2016-11-19T15:15:11.000Z | 2022-02-24T11:07:22.000Z | //================ Copyright (c) 2012, PG, All rights reserved. =================//
//
// Purpose: a simple slider
//
// $NoKeywords: $
//===============================================================================//
#include "CBaseUISlider.h"
#include "Engine.h"
#include "Mouse.h"
#include "AnimationHandler.h"
#include "Keyboard.h"
CBaseUISlider::CBaseUISlider(float xPos, float yPos, float xSize, float ySize, UString name) : CBaseUIElement(xPos,yPos,xSize,ySize,name)
{
m_bDrawFrame = true;
m_bDrawBackground = true;
m_bHorizontal = false;
m_bHasChanged = false;
m_bAnimated = true;
m_bLiveUpdate = false;
m_bAllowMouseWheel = true;
m_backgroundColor = COLOR(255, 0, 0, 0);
m_frameColor = COLOR(255,255,255,255);
m_fCurValue = 0.0f;
m_fCurPercent = 0.0f;
m_fMinValue = 0.0f;
m_fMaxValue = 1.0f;
m_fKeyDelta = 0.1f;
m_vBlockSize = Vector2(xSize < ySize ? xSize : ySize, xSize < ySize ? xSize : ySize);
m_sliderChangeCallback = NULL;
setOrientation(xSize > ySize);
}
void CBaseUISlider::draw(Graphics *g)
{
if (!m_bVisible) return;
// draw background
if (m_bDrawBackground)
{
g->setColor(m_backgroundColor);
g->fillRect(m_vPos.x, m_vPos.y, m_vSize.x, m_vSize.y + 1);
}
// draw frame
g->setColor(m_frameColor);
if (m_bDrawFrame)
g->drawRect(m_vPos.x, m_vPos.y, m_vSize.x, m_vSize.y + 1);
// draw sliding line
if (!m_bHorizontal)
g->drawLine(m_vPos.x + m_vSize.x/2.0f, m_vPos.y + m_vBlockSize.y/2.0, m_vPos.x + m_vSize.x/2.0f, m_vPos.y + m_vSize.y - m_vBlockSize.y/2.0f);
else
g->drawLine(m_vPos.x + (m_vBlockSize.x-1)/2 + 1, m_vPos.y + m_vSize.y/2.0f + 1, m_vPos.x + m_vSize.x - (m_vBlockSize.x-1)/2, m_vPos.y + m_vSize.y/2.0f + 1);
drawBlock(g);
}
void CBaseUISlider::drawBlock(Graphics *g)
{
// draw block
Vector2 center = m_vPos + Vector2(m_vBlockSize.x/2 + (m_vSize.x-m_vBlockSize.x)*getPercent(), m_vSize.y/2);
Vector2 topLeft = center - m_vBlockSize/2;
Vector2 topRight = center + Vector2(m_vBlockSize.x/2 + 1, -m_vBlockSize.y/2);
Vector2 halfLeft = center + Vector2(-m_vBlockSize.x/2, 1);
Vector2 halfRight = center + Vector2(m_vBlockSize.x/2 + 1, 1);
Vector2 bottomLeft = center + Vector2(-m_vBlockSize.x/2, m_vBlockSize.y/2 + 1);
Vector2 bottomRight = center + Vector2(m_vBlockSize.x/2 + 1, m_vBlockSize.y/2 + 1);
g->drawQuad(topLeft,
topRight,
halfRight + Vector2(0,1),
halfLeft + Vector2(0,1),
COLOR(255,255,255,255),
COLOR(255,255,255,255),
COLOR(255,241,241,241),
COLOR(255,241,241,241));
g->drawQuad(halfLeft,
halfRight,
bottomRight,
bottomLeft,
COLOR(255,225,225,225),
COLOR(255,225,225,225),
COLOR(255,255,255,255),
COLOR(255,255,255,255));
/*
g->drawQuad(Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1, m_vPos.y+std::round(m_vBlockPos.y)+1),
Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1 + m_vBlockSize.x-1, m_vPos.y+std::round(m_vBlockPos.y)+1),
Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1 + m_vBlockSize.x-1, m_vPos.y+std::round(m_vBlockPos.y)+1 + m_vBlockSize.y/2),
Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1, m_vPos.y+std::round(m_vBlockPos.y)+1 + m_vBlockSize.y/2),
COLOR(255,255,255,255),
COLOR(255,255,255,255),
COLOR(255,241,241,241),
COLOR(255,241,241,241));
g->drawQuad(Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1, m_vPos.y+std::round(m_vBlockPos.y)+1+std::round(m_vBlockSize.y/2.0f)),
Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1 + m_vBlockSize.x-1, m_vPos.y+std::round(m_vBlockPos.y)+1+std::round(m_vBlockSize.y/2.0f)),
Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1 + m_vBlockSize.x-1, m_vPos.y+std::round(m_vBlockPos.y)+1+std::round(m_vBlockSize.y/2.0f) + m_vBlockSize.y-(std::round(m_vBlockSize.y/2.0f))),
Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1, m_vPos.y+std::round(m_vBlockPos.y)+1+std::round(m_vBlockSize.y/2.0f) + m_vBlockSize.y-(std::round(m_vBlockSize.y/2.0f))),
COLOR(255,225,225,225),
COLOR(255,225,225,225),
COLOR(255,255,255,255),
COLOR(255,255,255,255));
*/
/*
g->setColor(0xff00ff00);
g->fillRect(m_vPos.x+m_vBlockPos.x+1, m_vPos.y+m_vBlockPos.y+1, m_vBlockSize.x-1, m_vBlockSize.y);
*/
}
void CBaseUISlider::update()
{
CBaseUIElement::update();
if (!m_bVisible) return;
Vector2 mousepos = engine->getMouse()->getPos();
// handle moving
if (m_bActive)
{
// calculate new values
if (!m_bHorizontal)
{
if (m_bAnimated)
anim->moveQuadOut( &m_vBlockPos.y, clamp<float>( mousepos.y - m_vGrabBackup.y, 0.0f, m_vSize.y-m_vBlockSize.y ), 0.10f, 0, true );
else
m_vBlockPos.y = clamp<float>( mousepos.y - m_vGrabBackup.y, 0.0f, m_vSize.y-m_vBlockSize.y );
m_fCurPercent = clamp<float>(1.0f - (std::round(m_vBlockPos.y) / (m_vSize.y-m_vBlockSize.y)), 0.0f, 1.0f);
}
else
{
if (m_bAnimated)
anim->moveQuadOut( &m_vBlockPos.x, clamp<float>( mousepos.x - m_vGrabBackup.x, 0.0f, m_vSize.x-m_vBlockSize.x ), 0.10f, 0, true );
else
m_vBlockPos.x = clamp<float>( mousepos.x - m_vGrabBackup.x, 0.0f, m_vSize.x-m_vBlockSize.x );
m_fCurPercent = clamp<float>(std::round(m_vBlockPos.x) / (m_vSize.x-m_vBlockSize.x), 0.0f, 1.0f);
}
// set new value
if (m_bAnimated)
{
if (m_bLiveUpdate)
setValue(lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent), false);
else
m_fCurValue = lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent);
}
else
setValue(lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent), false);
m_bHasChanged = true;
}
else
{
// handle mouse wheel
if (m_bMouseInside && m_bAllowMouseWheel)
{
int wheelDelta = engine->getMouse()->getWheelDeltaVertical();
if (wheelDelta != 0)
{
const int multiplier = std::max(1, std::abs(wheelDelta) / 120);
if (wheelDelta > 0)
setValue(m_fCurValue + m_fKeyDelta*multiplier, m_bAnimated);
else
setValue(m_fCurValue - m_fKeyDelta*multiplier, m_bAnimated);
}
}
}
// handle animation value settings after mouse release
if (!m_bActive)
{
if (anim->isAnimating( &m_vBlockPos.x ))
{
m_fCurPercent = clamp<float>(std::round(m_vBlockPos.x) / (m_vSize.x-m_vBlockSize.x), 0.0f, 1.0f);
if (m_bLiveUpdate)
setValue(lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent), false);
else
m_fCurValue = lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent);
}
if (anim->isAnimating( &m_vBlockPos.y ))
{
m_fCurPercent = clamp<float>(1.0f - (std::round(m_vBlockPos.y) / (m_vSize.y-m_vBlockSize.y)), 0.0f, 1.0f);
if (m_bLiveUpdate)
setValue(lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent), false);
else
m_fCurValue = lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent);
}
}
}
void CBaseUISlider::onKeyDown(KeyboardEvent &e)
{
if (!m_bVisible) return;
if (isMouseInside())
{
if (e == KEY_LEFT)
{
setValue(getFloat() - m_fKeyDelta, false);
e.consume();
}
else if (e == KEY_RIGHT)
{
setValue(getFloat() + m_fKeyDelta, false);
e.consume();
}
}
}
void CBaseUISlider::fireChangeCallback()
{
if (m_sliderChangeCallback != NULL)
m_sliderChangeCallback(this);
}
void CBaseUISlider::updateBlockPos()
{
if (!m_bHorizontal)
m_vBlockPos.x = m_vSize.x/2.0f - m_vBlockSize.x/2.0f;
else
m_vBlockPos.y = m_vSize.y/2.0f - m_vBlockSize.y/2.0f;
}
CBaseUISlider *CBaseUISlider::setBounds(float minValue, float maxValue)
{
m_fMinValue = minValue;
m_fMaxValue = maxValue;
m_fKeyDelta = (m_fMaxValue - m_fMinValue) / 10.0f;
return this;
}
CBaseUISlider *CBaseUISlider::setValue(float value, bool animate)
{
bool changeCallbackCheck = false;
if (value != m_fCurValue)
{
changeCallbackCheck = true;
m_bHasChanged = true;
}
m_fCurValue = clamp<float>(value, m_fMinValue, m_fMaxValue);
float percent = getPercent();
if (!m_bHorizontal)
{
if (animate)
anim->moveQuadOut( &m_vBlockPos.y, (m_vSize.y-m_vBlockSize.y)*(1.0f-percent), 0.2f, 0, true );
else
m_vBlockPos.y = (m_vSize.y-m_vBlockSize.y)*(1.0f-percent);
}
else
{
if (animate)
anim->moveQuadOut( &m_vBlockPos.x, (m_vSize.x-m_vBlockSize.x)*percent, 0.2f, 0, true );
else
m_vBlockPos.x = (m_vSize.x-m_vBlockSize.x)*percent;
}
if (changeCallbackCheck && m_sliderChangeCallback != NULL)
m_sliderChangeCallback(this);
updateBlockPos();
return this;
}
CBaseUISlider *CBaseUISlider::setInitialValue(float value)
{
m_fCurValue = clamp<float>(value, m_fMinValue, m_fMaxValue);
float percent = getPercent();
if (m_fCurValue == m_fMaxValue)
percent = 1.0f;
if (!m_bHorizontal)
m_vBlockPos.y = (m_vSize.y-m_vBlockSize.y)*(1.0f-percent);
else
m_vBlockPos.x = (m_vSize.x-m_vBlockSize.x)*percent;
updateBlockPos();
return this;
}
void CBaseUISlider::setBlockSize(float xSize, float ySize)
{
m_vBlockSize = Vector2(xSize, ySize);
}
float CBaseUISlider::getPercent()
{
return clamp<float>((m_fCurValue-m_fMinValue) / (std::abs(m_fMaxValue-m_fMinValue)), 0.0f, 1.0f);
}
bool CBaseUISlider::hasChanged()
{
if (anim->isAnimating(&m_vBlockPos.x))
return true;
if (m_bHasChanged)
{
m_bHasChanged = false;
return true;
}
return false;
}
void CBaseUISlider::onFocusStolen()
{
m_bBusy = false;
}
void CBaseUISlider::onMouseUpInside()
{
m_bBusy = false;
if (m_fCurValue != m_fPrevValue && m_sliderChangeCallback != NULL)
m_sliderChangeCallback(this);
}
void CBaseUISlider::onMouseUpOutside()
{
m_bBusy = false;
if (m_fCurValue != m_fPrevValue && m_sliderChangeCallback != NULL)
m_sliderChangeCallback(this);
}
void CBaseUISlider::onMouseDownInside()
{
m_fPrevValue = m_fCurValue;
if (McRect(m_vPos.x+m_vBlockPos.x,m_vPos.y+m_vBlockPos.y,m_vBlockSize.x,m_vBlockSize.y).contains(engine->getMouse()->getPos()))
m_vGrabBackup = engine->getMouse()->getPos()-m_vBlockPos;
else
m_vGrabBackup = m_vPos + m_vBlockSize/2;
m_bBusy = true;
}
void CBaseUISlider::onResized()
{
setValue(getFloat(), false);
}
| 26.986226 | 190 | 0.686607 | musikowskipawel |
ff59c1a8f1690e09839ef3ba85690fad6ee64446 | 1,673 | cpp | C++ | src/authgeneratorbtns.cpp | OpenIKEv2/libopenikev2_impl | 3c620ca479b20814fe42325cffcfd1d18dbf041c | [
"Apache-2.0"
] | 3 | 2017-03-03T17:05:37.000Z | 2020-06-16T04:50:40.000Z | src/authgeneratorbtns.cpp | OpenIKEv2/libopenikev2_impl | 3c620ca479b20814fe42325cffcfd1d18dbf041c | [
"Apache-2.0"
] | 11 | 2017-02-27T09:31:17.000Z | 2020-03-20T16:31:05.000Z | src/authgeneratorbtns.cpp | OpenIKEv2/libopenikev2_impl | 3c620ca479b20814fe42325cffcfd1d18dbf041c | [
"Apache-2.0"
] | null | null | null | /***************************************************************************
* Copyright (C) 2005 by *
* Alejandro Perez Mendez alex@um.es *
* Pedro J. Fernandez Ruiz pedroj@um.es *
* *
* This software may be modified and distributed under the terms *
* of the Apache license. See the LICENSE file for details. *
***************************************************************************/
#include "authgeneratorbtns.h"
namespace openikev2 {
AuthGeneratorBtns::AuthGeneratorBtns( ) {}
AuthGeneratorBtns::~AuthGeneratorBtns( ) {}
auto_ptr< AuthGenerator > AuthGeneratorBtns::clone() const {
return auto_ptr<AuthGenerator> ( new AuthGeneratorBtns( ) );
}
auto_ptr< Payload_AUTH > AuthGeneratorBtns::generateAuthPayload( const IkeSa& ike_sa ) {
auto_ptr<ByteArray> auth_field (new ByteArray ("BTNS", 4) );
return auto_ptr<Payload_AUTH> ( new Payload_AUTH( (Enums::AUTH_METHOD) 201, auth_field ) );
}
AutoVector<Payload_CERT> AuthGeneratorBtns::generateCertificatePayloads( const IkeSa& ike_sa, const vector< Payload_CERT_REQ * > payload_cert_req_r ) {
AutoVector<Payload_CERT> result;
return result;
}
string AuthGeneratorBtns::toStringTab( uint8_t tabs ) const {
ostringstream oss;
oss << Printable::generateTabs( tabs ) << "<AUTH_GENERATOR_BTNS> {\n";
oss << Printable::generateTabs( tabs ) << "}\n";
return oss.str();
}
}
| 39.833333 | 155 | 0.528392 | OpenIKEv2 |
ff5b7908f992d93dddef5743d47248d55e6f19f8 | 1,515 | cpp | C++ | vulkan/ShaderStorageBuffer.cpp | enjiushi/VulkanLearn | 29fb429a3fb526f8de7406404a983685a7e87117 | [
"MIT"
] | 272 | 2019-06-27T12:21:49.000Z | 2022-03-23T07:18:33.000Z | vulkan/ShaderStorageBuffer.cpp | enjiushi/VulkanLearn | 29fb429a3fb526f8de7406404a983685a7e87117 | [
"MIT"
] | 9 | 2019-08-11T13:07:01.000Z | 2022-01-26T12:30:24.000Z | vulkan/ShaderStorageBuffer.cpp | enjiushi/VulkanLearn | 29fb429a3fb526f8de7406404a983685a7e87117 | [
"MIT"
] | 16 | 2019-09-29T01:41:02.000Z | 2022-03-29T15:51:35.000Z | #include "ShaderStorageBuffer.h"
#include "GlobalDeviceObjects.h"
bool ShaderStorageBuffer::Init(const std::shared_ptr<Device>& pDevice, const std::shared_ptr<ShaderStorageBuffer>& pSelf, uint32_t numBytes)
{
VkBufferCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
uint32_t minAlign = (uint32_t)GetPhysicalDevice()->GetPhysicalDeviceProperties().limits.minStorageBufferOffsetAlignment;
uint32_t totalUniformBytes = numBytes / minAlign * minAlign + (numBytes % minAlign > 0 ? minAlign : 0);
info.size = totalUniformBytes;
if (!SharedBuffer::Init(pDevice, pSelf, info))
return false;
// FIXME: add them back when necessary
m_accessStages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT |
//VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT |
//VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT |
//VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT |
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
m_accessFlags = VK_ACCESS_SHADER_READ_BIT;
return true;
}
std::shared_ptr<ShaderStorageBuffer> ShaderStorageBuffer::Create(const std::shared_ptr<Device>& pDevice, uint32_t numBytes)
{
std::shared_ptr<ShaderStorageBuffer> pSSBO = std::make_shared<ShaderStorageBuffer>();
if (pSSBO.get() && pSSBO->Init(pDevice, pSSBO, numBytes))
return pSSBO;
return nullptr;
}
std::shared_ptr<BufferKey> ShaderStorageBuffer::AcquireBuffer(uint32_t numBytes)
{
return ShaderStorageBufferMgr()->AllocateBuffer(numBytes);
} | 37.875 | 140 | 0.805281 | enjiushi |
ff5c69604d7ce9871ec67cee2388c68b1f740a3e | 5,531 | cpp | C++ | x265/source/output/reconplay.cpp | xu5343/ffmpegtoolkit_CentOS7 | 974496c709a1c8c69034e46ae5ce7101cf03716f | [
"Apache-2.0"
] | 14 | 2019-02-26T22:22:32.000Z | 2022-03-03T07:06:58.000Z | x265/source/output/reconplay.cpp | xu5343/ffmpegtoolkit_CentOS7 | 974496c709a1c8c69034e46ae5ce7101cf03716f | [
"Apache-2.0"
] | null | null | null | x265/source/output/reconplay.cpp | xu5343/ffmpegtoolkit_CentOS7 | 974496c709a1c8c69034e46ae5ce7101cf03716f | [
"Apache-2.0"
] | 7 | 2019-05-17T19:14:10.000Z | 2021-08-31T01:54:40.000Z | /*****************************************************************************
* Copyright (C) 2013-2017 MulticoreWare, Inc
*
* Authors: Peixuan Zhang <zhangpeixuancn@gmail.com>
* Chunli Zhang <chunli@multicorewareinc.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
*
* This program is also available under a commercial proprietary license.
* For more information, contact us at license @ x265.com.
*****************************************************************************/
#include "common.h"
#include "reconplay.h"
#include <signal.h>
using namespace X265_NS;
#if _WIN32
#define popen _popen
#define pclose _pclose
#define pipemode "wb"
#else
#define pipemode "w"
#endif
bool ReconPlay::pipeValid;
#ifndef _WIN32
static void sigpipe_handler(int)
{
if (ReconPlay::pipeValid)
general_log(NULL, "exec", X265_LOG_ERROR, "pipe closed\n");
ReconPlay::pipeValid = false;
}
#endif
ReconPlay::ReconPlay(const char* commandLine, x265_param& param)
{
#ifndef _WIN32
if (signal(SIGPIPE, sigpipe_handler) == SIG_ERR)
general_log(¶m, "exec", X265_LOG_ERROR, "Unable to register SIGPIPE handler: %s\n", strerror(errno));
#endif
width = param.sourceWidth;
height = param.sourceHeight;
colorSpace = param.internalCsp;
frameSize = 0;
for (int i = 0; i < x265_cli_csps[colorSpace].planes; i++)
frameSize += (uint32_t)((width >> x265_cli_csps[colorSpace].width[i]) * (height >> x265_cli_csps[colorSpace].height[i]));
for (int i = 0; i < RECON_BUF_SIZE; i++)
{
poc[i] = -1;
CHECKED_MALLOC(frameData[i], pixel, frameSize);
}
outputPipe = popen(commandLine, pipemode);
if (outputPipe)
{
const char* csp = (colorSpace >= X265_CSP_I444) ? "444" : (colorSpace >= X265_CSP_I422) ? "422" : "420";
const char* depth = (param.internalBitDepth == 10) ? "p10" : "";
fprintf(outputPipe, "YUV4MPEG2 W%d H%d F%d:%d Ip C%s%s\n", width, height, param.fpsNum, param.fpsDenom, csp, depth);
pipeValid = true;
threadActive = true;
start();
return;
}
else
general_log(¶m, "exec", X265_LOG_ERROR, "popen(%s) failed\n", commandLine);
fail:
threadActive = false;
}
ReconPlay::~ReconPlay()
{
if (threadActive)
{
threadActive = false;
writeCount.poke();
stop();
}
if (outputPipe)
pclose(outputPipe);
for (int i = 0; i < RECON_BUF_SIZE; i++)
X265_FREE(frameData[i]);
}
bool ReconPlay::writePicture(const x265_picture& pic)
{
if (!threadActive || !pipeValid)
return false;
int written = writeCount.get();
int read = readCount.get();
int currentCursor = pic.poc % RECON_BUF_SIZE;
/* TODO: it's probably better to drop recon pictures when the ring buffer is
* backed up on the display app */
while (written - read > RECON_BUF_SIZE - 2 || poc[currentCursor] != -1)
{
read = readCount.waitForChange(read);
if (!threadActive)
return false;
}
X265_CHECK(pic.colorSpace == colorSpace, "invalid color space\n");
X265_CHECK(pic.bitDepth == X265_DEPTH, "invalid bit depth\n");
pixel* buf = frameData[currentCursor];
for (int i = 0; i < x265_cli_csps[colorSpace].planes; i++)
{
char* src = (char*)pic.planes[i];
int pwidth = width >> x265_cli_csps[colorSpace].width[i];
for (int h = 0; h < height >> x265_cli_csps[colorSpace].height[i]; h++)
{
memcpy(buf, src, pwidth * sizeof(pixel));
src += pic.stride[i];
buf += pwidth;
}
}
poc[currentCursor] = pic.poc;
writeCount.incr();
return true;
}
void ReconPlay::threadMain()
{
THREAD_NAME("ReconPlayOutput", 0);
do
{
/* extract the next output picture in display order and write to pipe */
if (!outputFrame())
break;
}
while (threadActive);
threadActive = false;
readCount.poke();
}
bool ReconPlay::outputFrame()
{
int written = writeCount.get();
int read = readCount.get();
int currentCursor = read % RECON_BUF_SIZE;
while (poc[currentCursor] != read)
{
written = writeCount.waitForChange(written);
if (!threadActive)
return false;
}
char* buf = (char*)frameData[currentCursor];
intptr_t remainSize = frameSize * sizeof(pixel);
fprintf(outputPipe, "FRAME\n");
while (remainSize > 0)
{
intptr_t retCount = (intptr_t)fwrite(buf, sizeof(char), remainSize, outputPipe);
if (retCount < 0 || !pipeValid)
/* pipe failure, stop writing and start dropping recon pictures */
return false;
buf += retCount;
remainSize -= retCount;
}
poc[currentCursor] = -1;
readCount.incr();
return true;
}
| 27.934343 | 129 | 0.616706 | xu5343 |
ff5d87a1588b20ec0a0941d46bec5cc0ac729072 | 7,201 | cpp | C++ | src/dgraph/pool.cpp | Rascof/dynamic-graph | 4bb6fed1e36d125357e790dacded1da148143677 | [
"BSD-2-Clause"
] | 17 | 2016-05-28T11:34:25.000Z | 2021-12-23T12:59:09.000Z | src/dgraph/pool.cpp | Rascof/dynamic-graph | 4bb6fed1e36d125357e790dacded1da148143677 | [
"BSD-2-Clause"
] | 58 | 2015-02-10T15:17:52.000Z | 2022-01-10T10:58:05.000Z | src/dgraph/pool.cpp | Rascof/dynamic-graph | 4bb6fed1e36d125357e790dacded1da148143677 | [
"BSD-2-Clause"
] | 22 | 2015-02-09T16:38:59.000Z | 2020-09-23T12:42:48.000Z | /*
* Copyright 2010,
* François Bleibel,
* Olivier Stasse,
*
* CNRS/AIST
*
*/
/* --------------------------------------------------------------------- */
/* --- INCLUDE --------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* --- DYNAMIC-GRAPH --- */
#include "dynamic-graph/pool.h"
#include "dynamic-graph/debug.h"
#include "dynamic-graph/entity.h"
#include <list>
#include <sstream>
#include <string>
#include <typeinfo>
using namespace dynamicgraph;
/* --------------------------------------------------------------------- */
/* --- CLASS ----------------------------------------------------------- */
/* --------------------------------------------------------------------- */
PoolStorage *PoolStorage::getInstance() {
if (instance_ == 0) {
instance_ = new PoolStorage;
}
return instance_;
}
void PoolStorage::destroy() {
delete instance_;
instance_ = NULL;
}
PoolStorage::~PoolStorage() {
dgDEBUGIN(15);
for (Entities::iterator iter = entityMap.begin(); iter != entityMap.end();
// Here, this is normal that the next iteration is at the beginning
// of the map as deregisterEntity remove the element iter from the map.
iter = entityMap.begin()) {
dgDEBUG(15) << "Delete \"" << (iter->first) << "\"" << std::endl;
Entity *entity = iter->second;
deregisterEntity(iter);
delete (entity);
}
instance_ = 0;
dgDEBUGOUT(15);
}
/* --------------------------------------------------------------------- */
void PoolStorage::registerEntity(const std::string &entname, Entity *ent) {
Entities::iterator entkey = entityMap.find(entname);
if (entkey != entityMap.end()) // key does exist
{
throw ExceptionFactory(
ExceptionFactory::OBJECT_CONFLICT,
"Another entity already defined with the same name. ",
"Entity name is <%s>.", entname.c_str());
} else {
dgDEBUG(10) << "Register entity <" << entname << "> in the pool."
<< std::endl;
entityMap[entname] = ent;
}
}
void PoolStorage::deregisterEntity(const std::string &entname) {
Entities::iterator entkey = entityMap.find(entname);
if (entkey == entityMap.end()) // key doesnot exist
{
throw ExceptionFactory(ExceptionFactory::OBJECT_CONFLICT,
"Entity not defined yet. ", "Entity name is <%s>.",
entname.c_str());
} else {
dgDEBUG(10) << "Deregister entity <" << entname << "> from the pool."
<< std::endl;
deregisterEntity(entkey);
}
}
void PoolStorage::deregisterEntity(const Entities::iterator &entity) {
entityMap.erase(entity);
}
Entity &PoolStorage::getEntity(const std::string &name) {
dgDEBUG(25) << "Get <" << name << ">" << std::endl;
Entities::iterator entPtr = entityMap.find(name);
if (entPtr == entityMap.end()) {
DG_THROW ExceptionFactory(ExceptionFactory::UNREFERED_OBJECT,
"Unknown entity.", " (while calling <%s>)",
name.c_str());
} else
return *entPtr->second;
}
const PoolStorage::Entities &PoolStorage::getEntityMap() const {
return entityMap;
}
bool PoolStorage::existEntity(const std::string &name) {
return entityMap.find(name) != entityMap.end();
}
bool PoolStorage::existEntity(const std::string &name, Entity *&ptr) {
Entities::iterator entPtr = entityMap.find(name);
if (entPtr == entityMap.end())
return false;
else {
ptr = entPtr->second;
return true;
}
}
void PoolStorage::clearPlugin(const std::string &name) {
dgDEBUGIN(5);
std::list<Entity *> toDelete;
for (Entities::iterator entPtr = entityMap.begin(); entPtr != entityMap.end();
++entPtr)
if (entPtr->second->getClassName() == name)
toDelete.push_back(entPtr->second);
for (std::list<Entity *>::iterator iter = toDelete.begin();
iter != toDelete.end(); ++iter)
delete (Entity *)*iter;
dgDEBUGOUT(5);
}
/* --------------------------------------------------------------------- */
#include <dynamic-graph/entity.h>
#ifdef WIN32
#include <time.h>
#endif /*WIN32*/
void PoolStorage::writeGraph(const std::string &aFileName) {
size_t IdxPointFound = aFileName.rfind(".");
std::string tmp1 = aFileName.substr(0, IdxPointFound);
size_t IdxSeparatorFound = aFileName.rfind("/");
std::string GenericName;
if (IdxSeparatorFound != std::string::npos)
GenericName = tmp1.substr(IdxSeparatorFound, tmp1.length());
else
GenericName = tmp1;
/* Reading local time */
time_t ltime;
ltime = time(NULL);
struct tm ltimeformatted;
#ifdef WIN32
localtime_s(<imeformatted, <ime);
#else
localtime_r(<ime, <imeformatted);
#endif /*WIN32*/
/* Opening the file and writing the first comment. */
std::ofstream GraphFile(aFileName.c_str(), std::ofstream::out);
GraphFile << "/* This graph has been automatically generated. " << std::endl;
GraphFile << " " << 1900 + ltimeformatted.tm_year
<< " Month: " << 1 + ltimeformatted.tm_mon
<< " Day: " << ltimeformatted.tm_mday
<< " Time: " << ltimeformatted.tm_hour << ":"
<< ltimeformatted.tm_min;
GraphFile << " */" << std::endl;
GraphFile << "digraph \"" << GenericName << "\" { ";
GraphFile << "\t graph [ label=\"" << GenericName
<< "\" bgcolor = white rankdir=LR ]" << std::endl
<< "\t node [ fontcolor = black, color = black,"
<< "fillcolor = gold1, style=filled, shape=box ] ; " << std::endl;
GraphFile << "\tsubgraph cluster_Entities { " << std::endl;
GraphFile << "\t} " << std::endl;
for (Entities::iterator iter = entityMap.begin(); iter != entityMap.end();
++iter) {
Entity *ent = iter->second;
GraphFile << "\"" << ent->getName() << "\""
<< " [ label = \"" << ent->getName() << "\" ," << std::endl
<< " fontcolor = black, color = black, fillcolor=cyan,"
<< " style=filled, shape=box ]" << std::endl;
ent->writeGraph(GraphFile);
}
GraphFile << "}" << std::endl;
GraphFile.close();
}
void PoolStorage::writeCompletionList(std::ostream &os) {
for (Entities::iterator iter = entityMap.begin(); iter != entityMap.end();
++iter) {
Entity *ent = iter->second;
ent->writeCompletionList(os);
}
}
static bool objectNameParser(std::istringstream &cmdparse, std::string &objName,
std::string &funName) {
const int SIZE = 128;
char buffer[SIZE];
cmdparse >> std::ws;
cmdparse.getline(buffer, SIZE, '.');
if (!cmdparse.good()) // The callback is not an object method
return false;
objName = buffer;
// cmdparse.getline( buffer,SIZE );
// funName = buffer;
cmdparse >> funName;
return true;
}
SignalBase<int> &PoolStorage::getSignal(std::istringstream &sigpath) {
std::string objname, signame;
if (!objectNameParser(sigpath, objname, signame)) {
DG_THROW ExceptionFactory(ExceptionFactory::UNREFERED_SIGNAL,
"Parse error in signal name");
}
Entity &ent = getEntity(objname);
return ent.getSignal(signame);
}
PoolStorage *PoolStorage::instance_ = 0;
| 31.038793 | 80 | 0.571865 | Rascof |
ff60de0ac0520b62f5f68e07b1ee4b29728e0af1 | 6,500 | cc | C++ | mmap/testing/node_page_test.cc | datacratic/DasDB | 5ccc1fc7c6c69c97e3dae0e02bb4009f95908d3b | [
"Apache-2.0"
] | 3 | 2017-12-06T00:25:52.000Z | 2021-08-24T20:46:54.000Z | mmap/testing/node_page_test.cc | datacratic/DasDB | 5ccc1fc7c6c69c97e3dae0e02bb4009f95908d3b | [
"Apache-2.0"
] | null | null | null | mmap/testing/node_page_test.cc | datacratic/DasDB | 5ccc1fc7c6c69c97e3dae0e02bb4009f95908d3b | [
"Apache-2.0"
] | 1 | 2016-11-24T17:14:16.000Z | 2016-11-24T17:14:16.000Z | /* node_page_test.cc
Rémi Attab, 20 January 2012
Copyright (c) 2012 Datacratic. All rights reserved.
Tests for node_page.h
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include "mmap/node_page.h"
#include "soa/utils/threaded_test.h"
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <thread>
#include <future>
#include <stack>
#include <array>
using namespace std;
using namespace boost;
using namespace Datacratic;
using namespace Datacratic::MMap;
using namespace ML;
// Testing utilities used in both para and seq tests.
template <uint32_t size> struct TestUtil {
typedef GenericNodePage<size> NodeT;
static void checkEmpty (NodeT& nodes) {
BOOST_REQUIRE_EQUAL(nodes.metadata.magic, NodeT::magicNum);
BOOST_REQUIRE_EQUAL(
nodes.metadata.full.numFull(), NodeT::metadataNodes);
}
static void checkSize () {
//Not all NodePages uses the full Page
if (sizeof(NodeT) >= page_size-size && sizeof(NodeT) <= page_size)
return;
cerr << "sizeof(GenericNodePage<" << size << ">)="
<< sizeof(NodeT) << endl;
cerr << "{ numNodes = " << NodeT::numNodes
<< ", sizeof(FullBitmap) = " << sizeof(FullBitmap<NodeT::numNodes>)
<< ", metadataSize = " << NodeT::metadataSize
<< ", metadataNodes = " << NodeT::metadataNodes
<< ", metadataPadding = " << NodeT::metadataPadding
<< "}" << endl;
BOOST_REQUIRE(sizeof(NodeT) == page_size);
}
};
// Test various behaviours when allocating and deallocating in a sequential test
template<uint32_t size> struct SequentialTest {
static void exec () {
typedef GenericNodePage<size> NodeT;
NodeT nodes;
nodes.init();
int64_t offset;
bool needUpdate;
TestUtil<size>::checkSize();
for (int k = 0; k < 3; ++k) {
// Exceptions are thrown but it pollutes the console output so disable it.
#if 0
// Try deallocating metadata nodes
for (int i = 0; i < NodeT::metadataNodes; ++i) {
BOOST_CHECK_THROW(
nodes.deallocate(i*size), ML::Assertion_Failure);
}
#endif
// Fully allocate the page.
for (int i = NodeT::metadataNodes; i < NodeT::numNodes; ++i) {
tie(offset, needUpdate) = nodes.allocate();
BOOST_REQUIRE_EQUAL(needUpdate, i == NodeT::numNodes-1);
BOOST_REQUIRE_EQUAL(offset, i*size);
}
// Over allocate the page.
for(int i = 0; i < 3; ++i) {
tie(offset, needUpdate) = nodes.allocate();
BOOST_REQUIRE_LE(offset, -1);
}
// De-allocate and reallocate a random node.
int64_t newOffset = (NodeT::numNodes/2) * size;
needUpdate = nodes.deallocate(newOffset);
BOOST_REQUIRE_EQUAL(needUpdate, true);
tie(offset, needUpdate) = nodes.allocate();
BOOST_REQUIRE_EQUAL(needUpdate, true);
BOOST_REQUIRE_EQUAL(offset, newOffset);
// Fully de-allocate the page.
for (int i = NodeT::metadataNodes; i < NodeT::numNodes; ++i) {
bool needUpdate = nodes.deallocate(i*size);
BOOST_REQUIRE_EQUAL(needUpdate, i == NodeT::metadataNodes);
}
// Exceptions are thrown but it pollutes the console output so disable it.
#if 0
// Over de-allocate the page
for (int i = NodeT::metadataNodes; i < NodeT::numNodes; ++i) {
BOOST_CHECK_THROW(nodes.deallocate(i*size), ML::Exception);
}
#endif
// Make sure everything is properly deallocated.
TestUtil<size>::checkEmpty(nodes);
}
}
};
BOOST_AUTO_TEST_CASE(test_seq) {
SequentialTest<8>::exec();
SequentialTest<12>::exec();
SequentialTest<32>::exec();
SequentialTest<64>::exec();
SequentialTest<96>::exec();
SequentialTest<192>::exec();
SequentialTest<256>::exec();
}
// Starts a truck load of tests that randomly allocates and frees nodes.
template<uint32_t size>
struct ParallelTest
{
enum {
threadCount = 4,
iterationCount = 10000
};
typedef GenericNodePage<size> NodeT;
NodeT nodes;
bool allocateNode (stack<int64_t>& s) {
int64_t offset = nodes.allocate().first;
if (offset >= 0) {
s.push(offset);
return true;
}
return false;
}
void deallocateHead(stack<int64_t>& s) {
nodes.deallocate(s.top());
s.pop();
}
void runThread (int id) {
mt19937 engine(id);
uniform_int_distribution<int> opDist(0, 1);
uniform_int_distribution<int> numDist(0, size);
stack<int64_t> allocatedOffsets;
for (int i = 0; i < iterationCount; ++i) {
if (allocatedOffsets.empty()) {
if (!allocateNode(allocatedOffsets)) {
// nothing to allocate or deallocate,
// take a nap and try again.
std::this_thread::yield();
}
continue;
}
else if (opDist(engine) && allocateNode(allocatedOffsets)) {
for (int j = numDist(engine); j > 0; --j) {
if (!allocateNode(allocatedOffsets)) {
break;
}
}
continue;
}
// De-allocate if space is full or we're randomly chosen.
for (int j = numDist(engine);
!allocatedOffsets.empty() && j > 0;
--j)
{
deallocateHead(allocatedOffsets);
}
}
// We're done, cleanup.
while (!allocatedOffsets.empty()) {
deallocateHead(allocatedOffsets);
}
}
void exec() {
nodes.init();
auto runFn = [&] (int id) {
this->runThread(id);
return 0;
};
ThreadedTest test;
test.start(runFn, threadCount);
test.joinAll(10000);
// Make sure everything is properly deallocated.
TestUtil<size>::checkEmpty(nodes);
}
};
BOOST_AUTO_TEST_CASE(test_para) {
ParallelTest<8>().exec();
ParallelTest<48>().exec();
ParallelTest<64>().exec();
ParallelTest<192>().exec();
ParallelTest<256>().exec();
}
| 28.508772 | 80 | 0.560308 | datacratic |
ff64b5db8c46c9154066d0808fae5094566deab9 | 335 | cpp | C++ | Backtrack/recur/AddN.cpp | Twinkle0799/Competitive_Programming_Rocks | fb71021e02019004bef59ee1df86687234e36f5a | [
"MIT"
] | 2 | 2021-05-06T17:59:44.000Z | 2021-08-04T12:50:38.000Z | Backtrack/recur/AddN.cpp | Twinkle0799/Competitive_Programming_Rocks | fb71021e02019004bef59ee1df86687234e36f5a | [
"MIT"
] | 1 | 2022-01-14T19:58:34.000Z | 2022-01-14T19:58:34.000Z | Backtrack/recur/AddN.cpp | Twinkle0799/Competitive_Programming_Rocks | fb71021e02019004bef59ee1df86687234e36f5a | [
"MIT"
] | 1 | 2021-02-17T09:48:06.000Z | 2021-02-17T09:48:06.000Z | #include<bits/stdc++.h>
using namespace std;
int AddN(int n)
{
if(n==0)
{
return 0;
}
int presum = AddN(n-1);
return n + presum;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n;
cin>>n;
cout<<AddN(n);
return 0;
} | 12.884615 | 39 | 0.540299 | Twinkle0799 |
ff6570c93f920c109bc9439affe2022813b971c9 | 80,944 | cxx | C++ | PWGHF/vertexingHF/AliAnalysisTaskSEDStarEMCALProductionCheck.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 2 | 2017-08-01T11:53:34.000Z | 2018-12-19T13:20:54.000Z | PWGHF/vertexingHF/AliAnalysisTaskSEDStarEMCALProductionCheck.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | null | null | null | PWGHF/vertexingHF/AliAnalysisTaskSEDStarEMCALProductionCheck.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 1 | 2019-05-21T08:47:05.000Z | 2019-05-21T08:47:05.000Z | /**************************************************************************
* Copyright(c) 1998-2009, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appeuear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//
//
// Base class for DStar Analysis
//
//
// The D* spectra study is done in pt bins:
// [0,0.5] [0.5,1] [1,2] [2,3] [3,4] [4,5] [5,6] [6,7] [7,8],
// [8,10],[10,12], [12,16], [16,20] and [20,24]
//
// Cuts arew centralized in AliRDHFCutsDStartoKpipi
// Side Band and like sign background are implemented in the macro
//
//-----------------------------------------------------------------------
//
// Author A.Grelli
// ERC-QGP Utrecht University - a.grelli@uu.nl,
// Author Y.Wang
// University of Heidelberg - yifei@physi.uni-heidelberg.de
// Author C.Ivan
// ERC-QGP Utrecht University - c.ivan@uu.nl,
//
// modified for EMCAL production check
//-----------------------------------------------------------------------
#include <TSystem.h>
#include <TParticle.h>
#include <TH1I.h>
#include "TROOT.h"
#include <TDatabasePDG.h>
#include <AliAnalysisDataSlot.h>
#include <AliAnalysisDataContainer.h>
#include "AliRDHFCutsDStartoKpipi.h"
#include "AliMCEvent.h"
#include "AliAnalysisManager.h"
#include "AliAODMCHeader.h"
#include "AliAODHandler.h"
#include "AliLog.h"
#include "AliAODVertex.h"
#include "AliAODRecoDecay.h"
#include "AliAODRecoDecayHF.h"
#include "AliAODRecoCascadeHF.h"
#include "AliAODRecoDecayHF2Prong.h"
#include "AliAnalysisVertexingHF.h"
#include "AliESDtrack.h"
#include "AliAODMCParticle.h"
#include "AliNormalizationCounter.h"
#include "AliAODEvent.h"
#include "AliAnalysisTaskSEDStarEMCALProductionCheck.h"
#include "AliEmcalTriggerDecisionContainer.h"
#include "AliInputEventHandler.h"
#include "AliTrackerBase.h"
#include "AliGenPythiaEventHeader.h"
/// \cond CLASSIMP
ClassImp(AliAnalysisTaskSEDStarEMCALProductionCheck);
/// \endcond
//__________________________________________________________________________
AliAnalysisTaskSEDStarEMCALProductionCheck::AliAnalysisTaskSEDStarEMCALProductionCheck():
AliAnalysisTaskSE(),
fEvents(0),
fAnalysis(0),
fD0Window(0),
fPeakWindow(0),
fUseMCInfo(kFALSE),
fDoSearch(kFALSE),
fOutput(0),
fOutputAll(0),
fOutputPID(0),
fOutputProductionCheck(0),
fNSigma(3),
fCuts(0),
fCEvents(0),
fTrueDiff2(0),
fDeltaMassD1(0),
fCounter(0),
fAODProtection(1),
fDoImpParDstar(kFALSE),
fNImpParBins(400),
fLowerImpPar(-2000.),
fHigherImpPar(2000.),
fNPtBins(0),
fAllhist(0x0),
fPIDhist(0x0),
fDoDStarVsY(kFALSE),
fUseEMCalTrigger(kFALSE),
fTriggerSelectionString(0),
fCheckEMCALAcceptance(kFALSE),
fCheckEMCALAcceptanceNumber(0),
fApplyEMCALClusterEventCut(kFALSE)
{
//
/// Default ctor
//
for (Int_t i = 0; i < 5; i++) fHistMassPtImpParTCDs[i] = 0;
}
//___________________________________________________________________________
AliAnalysisTaskSEDStarEMCALProductionCheck::AliAnalysisTaskSEDStarEMCALProductionCheck(const Char_t* name, AliRDHFCutsDStartoKpipi* cuts) :
AliAnalysisTaskSE(name),
fEvents(0),
fAnalysis(0),
fD0Window(0),
fPeakWindow(0),
fUseMCInfo(kFALSE),
fDoSearch(kFALSE),
fOutput(0),
fOutputAll(0),
fOutputPID(0),
fOutputProductionCheck(0),
fNSigma(3),
fCuts(0),
fCEvents(0),
fTrueDiff2(0),
fDeltaMassD1(0),
fCounter(0),
fAODProtection(1),
fDoImpParDstar(kFALSE),
fNImpParBins(400),
fLowerImpPar(-2000.),
fHigherImpPar(2000.),
fNPtBins(0),
fAllhist(0x0),
fPIDhist(0x0),
fDoDStarVsY(kFALSE),
fUseEMCalTrigger(kFALSE),
fTriggerSelectionString(0),
fCheckEMCALAcceptance(kFALSE),
fCheckEMCALAcceptanceNumber(0),
fApplyEMCALClusterEventCut(kFALSE)
{
//
/// Constructor. Initialization of Inputs and Outputs
//
Info("AliAnalysisTaskSEDStarEMCALProductionCheck", "Calling Constructor");
fCuts = cuts;
for (Int_t i = 0; i < 5; i++) fHistMassPtImpParTCDs[i] = 0;
DefineOutput(1, TList::Class()); //counters
DefineOutput(2, TList::Class()); //All Entries output
DefineOutput(3, TList::Class()); //3sigma PID output
DefineOutput(4, AliRDHFCutsDStartoKpipi::Class()); //My private output
DefineOutput(5, AliNormalizationCounter::Class()); // normalization
DefineOutput(6, TList::Class()); //production check
}
//___________________________________________________________________________
AliAnalysisTaskSEDStarEMCALProductionCheck::~AliAnalysisTaskSEDStarEMCALProductionCheck() {
//
/// destructor
//
Info("~AliAnalysisTaskSEDStarEMCALProductionCheck", "Calling Destructor");
delete fOutput;
delete fOutputAll;
delete fOutputPID;
delete fOutputProductionCheck;
delete fCuts;
delete fCEvents;
delete fDeltaMassD1;
for (Int_t i = 0; i < 5; i++) {
delete fHistMassPtImpParTCDs[i];
}
for (Int_t i = 0; i < ((fNPtBins + 2) * 18); i++) {
delete fAllhist[i];
delete fPIDhist[i];
}
delete [] fAllhist;
delete [] fPIDhist;
}
//_________________________________________________
void AliAnalysisTaskSEDStarEMCALProductionCheck::Init() {
//
/// Initialization
//
if (fDebug > 1) printf("AnalysisTaskSEDStarSpectra::Init() \n");
AliRDHFCutsDStartoKpipi* copyfCuts = new AliRDHFCutsDStartoKpipi(*fCuts);
fNPtBins = fCuts->GetNPtBins();
// Post the data
PostData(4, copyfCuts);
return;
}
//_________________________________________________
void AliAnalysisTaskSEDStarEMCALProductionCheck::UserExec(Option_t *)
{
/// user exec
if (!fInputEvent) {
Error("UserExec", "NO EVENT FOUND!");
return;
}
fCEvents->Fill(0);//all events
if (fAODProtection >= 0) {
// Protection against different number of events in the AOD and deltaAOD
// In case of discrepancy the event is rejected.
Int_t matchingAODdeltaAODlevel = AliRDHFCuts::CheckMatchingAODdeltaAODevents();
if (matchingAODdeltaAODlevel < 0 || (matchingAODdeltaAODlevel == 0 && fAODProtection == 1)) {
// AOD/deltaAOD trees have different number of entries || TProcessID do not match while it was required
fCEvents->Fill(8);
return;
}
fCEvents->Fill(1);
}
fEvents++;
AliAODEvent* aodEvent = dynamic_cast<AliAODEvent*>(fInputEvent);
TClonesArray *arrayDStartoD0pi = 0;
TClonesArray *arrayD0toKpi = 0;
if (!aodEvent && AODEvent() && IsStandardAOD()) {
// In case there is an AOD handler writing a standard AOD, use the AOD
// event in memory rather than the input (ESD) event.
aodEvent = dynamic_cast<AliAODEvent*> (AODEvent());
// in this case the braches in the deltaAOD (AliAOD.VertexingHF.root)
// have to taken from the AOD event hold by the AliAODExtension
AliAODHandler* aodHandler = (AliAODHandler*)
((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler());
if (aodHandler->GetExtensions()) {
AliAODExtension *ext = (AliAODExtension*)aodHandler->GetExtensions()->FindObject("AliAOD.VertexingHF.root");
AliAODEvent *aodFromExt = ext->GetAOD();
arrayDStartoD0pi = (TClonesArray*)aodFromExt->GetList()->FindObject("Dstar");
arrayD0toKpi = (TClonesArray*)aodFromExt->GetList()->FindObject("D0toKpi");
}
} else {
arrayDStartoD0pi = (TClonesArray*)aodEvent->GetList()->FindObject("Dstar");
arrayD0toKpi = (TClonesArray*)aodEvent->GetList()->FindObject("D0toKpi");
}
//objects for production check
AliAODMCHeader *mcHeader = nullptr;
AliGenPythiaEventHeader * pythiaHeader = nullptr;
TClonesArray *mcTrackArray = nullptr;
Double_t crossSection = 0.0;
Double_t ptHard = 0.0;
Int_t nTrials = 0;
// Int_t nPtBins = fCuts->GetNPtBins();
// const Int_t nPtBinLimits = nPtBins + 1;
// Int_t PtBinLimits[nPtBinLimits] = fCuts->GetPtBinLimits();
if (fUseMCInfo) {
// load MC header
mcHeader = (AliAODMCHeader*)aodEvent->GetList()->FindObject(AliAODMCHeader::StdBranchName());
if (!mcHeader) {
printf("AliAnalysisTaskSEDStarEMCALProductionCheck::UserExec: MC header branch not found!\n");
return;
}
AliGenPythiaEventHeader * pythiaHeader = (AliGenPythiaEventHeader*)mcHeader->GetCocktailHeader(0);
if (!pythiaHeader) {
printf("AliAnalysisTaskSEDStarEMCALProductionCheck::UserExec: AliGenPythiaEventHeader not found!\n");
return;
}
crossSection = pythiaHeader->GetXsection();
ptHard = pythiaHeader->GetPtHard();
nTrials = pythiaHeader->Trials();
mcTrackArray = dynamic_cast<TClonesArray*>(aodEvent->FindListObject(AliAODMCParticle::StdBranchName()));
if (!mcTrackArray) {std::cout << "no track array" << std::endl; return;};
}
// check before event cut
if (fUseMCInfo) {
for (Int_t j = 0; j < mcTrackArray->GetEntriesFast(); j++) {
AliAODMCParticle *mcTrackParticle = dynamic_cast< AliAODMCParticle*>(mcTrackArray->At(j));
if (!mcTrackParticle) {std::cout << "no particle" << std::endl; continue;}
Int_t pdgCodeMC = TMath::Abs(mcTrackParticle->GetPdgCode());
if (pdgCodeMC == 413)
{ //if the track is a DStar we check if it comes from charm
Double_t ptMC = mcTrackParticle->Pt();
Bool_t fromCharm = kFALSE;
Int_t mother = mcTrackParticle->GetMother();
Int_t istep = 0;
while (mother >= 0 ) {
istep++;
AliAODMCParticle* mcGranma = dynamic_cast<AliAODMCParticle*>(mcTrackArray->At(mother));
if (mcGranma) {
Int_t abspdgGranma = TMath::Abs(mcGranma->GetPdgCode());
if ((abspdgGranma == 4) || (abspdgGranma > 400 && abspdgGranma < 500) || (abspdgGranma > 4000 && abspdgGranma < 5000)) fromCharm = kTRUE;
mother = mcGranma->GetMother();
} else {
printf("AliVertexingHFUtils::IsTrackFromCharm: Failed casting the mother particle!");
break;
}
}
if (fromCharm)
{
Bool_t mcPionDStarPresent = kFALSE;
Bool_t mcPionD0Present = kFALSE;
Bool_t mcKaonPresent = kFALSE;
Int_t nDaughterDStar = mcTrackParticle->GetNDaughters();
if (nDaughterDStar == 2) {
for (Int_t iDaughterDStar = 0; iDaughterDStar < 2; iDaughterDStar++) {
AliAODMCParticle* daughterDStar = (AliAODMCParticle*)mcTrackArray->At(mcTrackParticle->GetDaughterLabel(iDaughterDStar));
if (!daughterDStar) break;
Int_t pdgCodeDaughterDStar = TMath::Abs(daughterDStar->GetPdgCode());
if (pdgCodeDaughterDStar == 211) { //if the track is a pion we save its monte carlo label
mcPionDStarPresent = kTRUE;
} else if (pdgCodeDaughterDStar == 421) { //if the track is a D0 we look at its daughters
Int_t mcLabelD0 = mcTrackParticle->GetDaughterLabel(iDaughterDStar);
Int_t nDaughterD0 = daughterDStar->GetNDaughters();
if (nDaughterD0 == 2) {
for (Int_t iDaughterD0 = 0; iDaughterD0 < 2; iDaughterD0++) {
AliAODMCParticle* daughterD0 = (AliAODMCParticle*)mcTrackArray->At(daughterDStar->GetDaughterLabel(iDaughterD0));
if (!daughterD0) break;
Int_t pdgCodeDaughterD0 = TMath::Abs(daughterD0->GetPdgCode());
if (pdgCodeDaughterD0 == 211) {
mcPionD0Present = kTRUE;
} else if (pdgCodeDaughterD0 == 321) {
mcKaonPresent = kTRUE;
} else break;
}
}
} else break;
}
}
if (mcPionDStarPresent && mcPionD0Present && mcKaonPresent)
{
TString fillthis = "";
fillthis = "DStarPtTruePreEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC);
fillthis = "DStarPtTruePreEventSelectionWeighted";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC, crossSection);
// fillthis = "PtHardPreEventSelection";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptHard);
// fillthis = "PtHardWeightedPreEventSelection";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptHard, crossSection);
// fillthis = "WeightsPreEventSelection";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(crossSection);
// fillthis = "TrialsPreEventSelection";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->AddBinContent(1,nTrials);
fillthis = "DStar_per_bin_true_PreEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC);
fillthis = "DStar_per_bin_true_PreEventSelection_weighted";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC, crossSection);
}
}
}
}
}
TString fillthishist = "";
fillthishist = "PtHardPreEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->Fill(ptHard);
fillthishist = "PtHardWeightedPreEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->Fill(ptHard, crossSection);
fillthishist = "WeightsPreEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->Fill(crossSection);
fillthishist = "TrialsPreEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->AddBinContent(1,nTrials);
// fix for temporary bug in ESDfilter
// the AODs with null vertex pointer didn't pass the PhysSel
if (!aodEvent->GetPrimaryVertex() || TMath::Abs(aodEvent->GetMagneticField()) < 0.001) return;
fCEvents->Fill(2);
fCounter->StoreEvent(aodEvent, fCuts, fUseMCInfo);
// trigger class for PbPb C0SMH-B-NOPF-ALLNOTRD
TString trigclass = aodEvent->GetFiredTriggerClasses();
if (trigclass.Contains("C0SMH-B-NOPF-ALLNOTRD") || trigclass.Contains("C0SMH-B-NOPF-ALL")) fCEvents->Fill(5);
if (!fCuts->IsEventSelected(aodEvent)) {
if (fCuts->GetWhyRejection() == 6) // rejected for Z vertex
fCEvents->Fill(6);
return;
}
// Use simulated EMCal trigger for MC. AliEmcalTriggerMakerTask needs to be run first.
if (fUseEMCalTrigger)
{
auto triggercont = static_cast<PWG::EMCAL::AliEmcalTriggerDecisionContainer*>(fInputEvent->FindListObject("EmcalTriggerDecision"));
if (!triggercont)
{
AliErrorStream() << "Trigger decision container not found in event - not possible to select EMCAL triggers" << std::endl;
return;
}
if (fTriggerSelectionString == "EG1DG1")
{
if (!triggercont->IsEventSelected("EG1") && !triggercont->IsEventSelected("DG1")) return;
} else if (!triggercont->IsEventSelected(fTriggerSelectionString)) return;
}
// Get field for EMCAL acceptance and cut events
AliAnalysisManager *man = AliAnalysisManager::GetAnalysisManager();
AliInputEventHandler* inputHandler = (AliInputEventHandler*) (man->GetInputEventHandler());
inputHandler->SetNeedField();
if (fApplyEMCALClusterEventCut)
{
Int_t numberOfCaloClustersEvent = aodEvent->GetNumberOfCaloClusters();
if (numberOfCaloClustersEvent >= 0)
{
Bool_t passClusterCuts = kFALSE;
for (Int_t iCluster = 0; iCluster < numberOfCaloClustersEvent; ++iCluster)
{
AliAODCaloCluster * trackEMCALCluster = (AliAODCaloCluster*)aodEvent->GetCaloCluster(iCluster);
if (trackEMCALCluster->GetNonLinCorrEnergy() < 9.0) continue;
if (trackEMCALCluster->GetTOF() > 15e-9) continue;
if (trackEMCALCluster->GetTOF() < -20e-9) continue;
if (trackEMCALCluster->GetIsExotic()) continue;
passClusterCuts = kTRUE;
}
if (!passClusterCuts) return;
} else return;
}
Bool_t isEvSel = fCuts->IsEventSelected(aodEvent);
fCEvents->Fill(3);
if (!isEvSel) return;
// Load the event
// AliInfo(Form("Event %d",fEvents));
//if (fEvents%10000 ==0) AliInfo(Form("Event %d",fEvents));
// counters for efficiencies
Int_t icountReco = 0;
//D* and D0 prongs needed to MatchToMC method
Int_t pdgDgDStartoD0pi[2] = {421, 211};
Int_t pdgDgD0toKpi[2] = {321, 211};
// AOD primary vertex
AliAODVertex *vtx1 = (AliAODVertex*)aodEvent->GetPrimaryVertex();
if (!vtx1) return;
if (vtx1->GetNContributors() < 1) return;
fCEvents->Fill(4);
//save cluster information for EMCal trigger selection check
Int_t numberOfCaloClustersEvent = aodEvent->GetNumberOfCaloClusters();
if (numberOfCaloClustersEvent >= 0)
{
for (Int_t iCluster = 0; iCluster < numberOfCaloClustersEvent; ++iCluster)
{
AliAODCaloCluster * trackEMCALCluster = (AliAODCaloCluster*)aodEvent->GetCaloCluster(iCluster);
//save cluster information
Float_t pos[3]={0};
trackEMCALCluster->GetPosition(pos);
TString fillthis = "";
fillthis = "fHistClusPosition";
((TH3F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(pos[0], pos[1], pos[2]);
}
}
if (!arrayDStartoD0pi || !arrayD0toKpi) {
AliInfo("Could not find array of HF vertices, skipping the event");
return;
} else AliDebug(2, Form("Found %d vertices", arrayDStartoD0pi->GetEntriesFast()));
Int_t nSelectedAna = 0;
Int_t nSelectedProd = 0;
// check after event cut
if (fUseMCInfo) {
for (Int_t j = 0; j < mcTrackArray->GetEntriesFast(); j++) {
AliAODMCParticle *mcTrackParticle = dynamic_cast< AliAODMCParticle*>(mcTrackArray->At(j));
if (!mcTrackParticle) {std::cout << "no particle" << std::endl; continue;}
Int_t pdgCodeMC = TMath::Abs(mcTrackParticle->GetPdgCode());
if (pdgCodeMC == 413)
{ //if the track is a DStar we check if it comes from charm
Double_t ptMC = mcTrackParticle->Pt();
Bool_t fromCharm = kFALSE;
Int_t mother = mcTrackParticle->GetMother();
Int_t istep = 0;
while (mother >= 0 ) {
istep++;
AliAODMCParticle* mcGranma = dynamic_cast<AliAODMCParticle*>(mcTrackArray->At(mother));
if (mcGranma) {
Int_t abspdgGranma = TMath::Abs(mcGranma->GetPdgCode());
if ((abspdgGranma == 4) || (abspdgGranma > 400 && abspdgGranma < 500) || (abspdgGranma > 4000 && abspdgGranma < 5000)) fromCharm = kTRUE;
mother = mcGranma->GetMother();
} else {
printf("AliVertexingHFUtils::IsTrackFromCharm: Failed casting the mother particle!");
break;
}
}
if (fromCharm)
{
Bool_t mcPionDStarPresent = kFALSE;
Bool_t mcPionD0Present = kFALSE;
Bool_t mcKaonPresent = kFALSE;
Int_t nDaughterDStar = mcTrackParticle->GetNDaughters();
if (nDaughterDStar == 2) {
for (Int_t iDaughterDStar = 0; iDaughterDStar < 2; iDaughterDStar++) {
AliAODMCParticle* daughterDStar = (AliAODMCParticle*)mcTrackArray->At(mcTrackParticle->GetDaughterLabel(iDaughterDStar));
if (!daughterDStar) break;
Int_t pdgCodeDaughterDStar = TMath::Abs(daughterDStar->GetPdgCode());
if (pdgCodeDaughterDStar == 211) { //if the track is a pion we save its monte carlo label
mcPionDStarPresent = kTRUE;
} else if (pdgCodeDaughterDStar == 421) { //if the track is a D0 we look at its daughters
Int_t mcLabelD0 = mcTrackParticle->GetDaughterLabel(iDaughterDStar);
Int_t nDaughterD0 = daughterDStar->GetNDaughters();
if (nDaughterD0 == 2) {
for (Int_t iDaughterD0 = 0; iDaughterD0 < 2; iDaughterD0++) {
AliAODMCParticle* daughterD0 = (AliAODMCParticle*)mcTrackArray->At(daughterDStar->GetDaughterLabel(iDaughterD0));
if (!daughterD0) break;
Int_t pdgCodeDaughterD0 = TMath::Abs(daughterD0->GetPdgCode());
if (pdgCodeDaughterD0 == 211) {
mcPionD0Present = kTRUE;
} else if (pdgCodeDaughterD0 == 321) {
mcKaonPresent = kTRUE;
} else break;
}
}
} else break;
}
}
if (mcPionDStarPresent && mcPionD0Present && mcKaonPresent)
{
TString fillthis = "";
fillthis = "DStarPtTruePostEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC);
fillthis = "DStarPtTruePostEventSelectionWeighted";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC, crossSection);
// fillthis = "PtHardPostEventSelection";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptHard);
// fillthis = "PtHardWeightedPostEventSelection";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptHard, crossSection);
// fillthis = "WeightsPostEventSelection";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(crossSection);
// fillthis = "TrialsPostEventSelection";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->AddBinContent(1,nTrials);
fillthis = "DStar_per_bin_true_PostEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC);
fillthis = "DStar_per_bin_true_PostEventSelection_weighted";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC, crossSection);
}
}
}
}
}
fillthishist = "";
fillthishist = "PtHardPostEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->Fill(ptHard);
fillthishist = "PtHardWeightedPostEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->Fill(ptHard, crossSection);
fillthishist = "WeightsPostEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->Fill(crossSection);
fillthishist = "TrialsPostEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->AddBinContent(1,nTrials);
// vHF object is needed to call the method that refills the missing info of the candidates
// if they have been deleted in dAOD reconstruction phase
// in order to reduce the size of the file
AliAnalysisVertexingHF *vHF = new AliAnalysisVertexingHF();
// loop over the tracks to search for candidates soft pion
for (Int_t iDStartoD0pi = 0; iDStartoD0pi < arrayDStartoD0pi->GetEntriesFast(); iDStartoD0pi++) {
// D* candidates and D0 from D*
AliAODRecoCascadeHF* dstarD0pi = (AliAODRecoCascadeHF*)arrayDStartoD0pi->At(iDStartoD0pi);
AliAODRecoDecayHF2Prong *trackD0;
if (dstarD0pi->GetIsFilled() < 1) {
trackD0 = (AliAODRecoDecayHF2Prong*)arrayD0toKpi->At(dstarD0pi->GetProngID(1));
} else {
trackD0 = (AliAODRecoDecayHF2Prong*)dstarD0pi->Get2Prong();
}
fCEvents->Fill(10);
TObjArray arrTracks(3);
for (Int_t ipr = 0; ipr < 3; ipr++) {
AliAODTrack *tr;
if (ipr == 0) tr = vHF->GetProng(aodEvent, dstarD0pi, ipr); //soft pion
else tr = vHF->GetProng(aodEvent, trackD0, ipr - 1); //D0 daughters
arrTracks.AddAt(tr, ipr);
}
if (!fCuts->PreSelect(arrTracks)) {
fCEvents->Fill(13);
continue;
}
Bool_t isDStarCand = kTRUE;
if (!(vHF->FillRecoCasc(aodEvent, dstarD0pi, isDStarCand))) { //Fill the data members of the candidate only if they are empty.
fCEvents->Fill(12); //monitor how often this fails
continue;
}
if (!dstarD0pi->GetSecondaryVtx()) continue;
AliAODRecoDecayHF2Prong* theD0particle = (AliAODRecoDecayHF2Prong*)dstarD0pi->Get2Prong();
if (!theD0particle) continue;
Int_t isDStar = 0;
TClonesArray *mcArray = 0;
// AliAODMCHeader *mcHeader = 0;
Bool_t isPrimary = kTRUE;
Float_t pdgCode = -2;
Float_t trueImpParXY = 0.;
// mc analysis
if (fUseMCInfo) {
//MC array need for maching
mcArray = dynamic_cast<TClonesArray*>(aodEvent->FindListObject(AliAODMCParticle::StdBranchName()));
if (!mcArray) {
AliError("Could not find Monte-Carlo in AOD");
return;
}
// load MC header
// mcHeader = (AliAODMCHeader*)aodEvent->GetList()->FindObject(AliAODMCHeader::StdBranchName());
// if (!mcHeader) {
// printf("AliAnalysisTaskSEDplus::UserExec: MC header branch not found!\n");
// return;
// }
// find associated MC particle for D* ->D0toKpi
Int_t mcLabel = dstarD0pi->MatchToMC(413, 421, pdgDgDStartoD0pi, pdgDgD0toKpi, mcArray);
if (mcLabel >= 0) {
AliAODMCParticle *partDSt = (AliAODMCParticle*)mcArray->At(mcLabel);
Int_t checkOrigin = CheckOrigin(mcArray, partDSt);
if (checkOrigin == 5) isPrimary = kFALSE;
AliAODMCParticle *dg0 = (AliAODMCParticle*)mcArray->At(partDSt->GetDaughterLabel(0));
// AliAODMCParticle *dg01 = (AliAODMCParticle*)mcArray->At(dg0->GetDaughterLabel(0));
pdgCode = TMath::Abs(partDSt->GetPdgCode());
if (!isPrimary) {
trueImpParXY = GetTrueImpactParameterD0(mcHeader, mcArray, dg0) * 1000.;
}
isDStar = 1;
} else {
pdgCode = -1;
}
}
if (pdgCode == -1) AliDebug(2, "No particle assigned! check\n");
Double_t Dstarpt = dstarD0pi->Pt();
// quality selction on tracks and region of interest
Int_t isTkSelected = fCuts->IsSelected(dstarD0pi, AliRDHFCuts::kTracks); // quality cuts on tracks
if (!isTkSelected) continue;
if (!fCuts->IsInFiducialAcceptance(dstarD0pi->Pt(), dstarD0pi->YDstar())) continue;
// EMCAL acceptance check
if (fCheckEMCALAcceptance)
{
Int_t numberInAcc = 0;
AliAODTrack *track[3];
for (Int_t iDaught = 0; iDaught < 3; iDaught++) {
track[iDaught] = (AliAODTrack*)arrTracks.At(iDaught);
Int_t numberOfCaloClusters = aodEvent->GetNumberOfCaloClusters();
if (numberOfCaloClusters >= 0)
{
Int_t trackEMCALClusterNumber = track[iDaught]->GetEMCALcluster();
if (!(trackEMCALClusterNumber < 0))
{
AliAODCaloCluster * trackEMCALCluster = (AliAODCaloCluster*)aodEvent->GetCaloCluster(trackEMCALClusterNumber);
if (!trackEMCALCluster) continue;
if (trackEMCALCluster->GetNonLinCorrEnergy() < 9.0) continue;
if (trackEMCALCluster->GetTOF() > 15e-9) continue;
if (trackEMCALCluster->GetTOF() < -20e-9) continue;
if (trackEMCALCluster->GetIsExotic()) continue;
numberInAcc++;
}
}
}
// Cut on number of events in EMCAL acceptance
if (numberInAcc < fCheckEMCALAcceptanceNumber) continue;
}
//histos for impact par studies - D0!!!
Double_t ptCand = dstarD0pi->Get2Prong()->Pt();
Double_t invMass = dstarD0pi->InvMassD0();
Double_t impparXY = dstarD0pi->Get2Prong()->ImpParXY() * 10000.;
Double_t arrayForSparse[3] = {invMass, ptCand, impparXY};
Double_t arrayForSparseTrue[3] = {invMass, ptCand, trueImpParXY};
// set the D0 and D* search window bin by bin - D* window useful to speed up the reconstruction and D0 window used *ONLY* to calculate side band bkg for the background subtraction methods, for the standard analysis the value in the cut file is considered
if (0 <= Dstarpt && Dstarpt < 0.5) {
if (fAnalysis == 1) {
fD0Window = 0.035;
fPeakWindow = 0.03;
} else {
fD0Window = 0.020;
fPeakWindow = 0.0018;
}
}
if (0.5 <= Dstarpt && Dstarpt < 1.0) {
if (fAnalysis == 1) {
fD0Window = 0.035;
fPeakWindow = 0.03;
} else {
fD0Window = 0.020;
fPeakWindow = 0.0018;
}
}
if (1.0 <= Dstarpt && Dstarpt < 2.0) {
if (fAnalysis == 1) {
fD0Window = 0.035;
fPeakWindow = 0.03;
} else {
fD0Window = 0.020;
fPeakWindow = 0.0018;
}
}
if (2.0 <= Dstarpt && Dstarpt < 3.0) {
if (fAnalysis == 1) {
fD0Window = 0.035;
fPeakWindow = 0.03;
} else {
fD0Window = 0.022;
fPeakWindow = 0.0016;
}
}
if (3.0 <= Dstarpt && Dstarpt < 4.0) {
if (fAnalysis == 1) {
fD0Window = 0.035;
fPeakWindow = 0.03;
} else {
fD0Window = 0.026;
fPeakWindow = 0.0014;
}
}
if (4.0 <= Dstarpt && Dstarpt < 5.0) {
if (fAnalysis == 1) {
fD0Window = 0.045;
fPeakWindow = 0.03;
} else {
fD0Window = 0.026;
fPeakWindow = 0.0014;
}
}
if (5.0 <= Dstarpt && Dstarpt < 6.0) {
if (fAnalysis == 1) {
fD0Window = 0.045;
fPeakWindow = 0.03;
} else {
fD0Window = 0.026;
fPeakWindow = 0.006;
}
}
if (6.0 <= Dstarpt && Dstarpt < 7.0) {
if (fAnalysis == 1) {
fD0Window = 0.055;
fPeakWindow = 0.03;
} else {
fD0Window = 0.026;
fPeakWindow = 0.006;
}
}
if (Dstarpt >= 7.0) {
if (fAnalysis == 1) {
fD0Window = 0.074;
fPeakWindow = 0.03;
} else {
fD0Window = 0.026;
fPeakWindow = 0.006;
}
}
nSelectedProd++;
nSelectedAna++;
// check that we are close to signal in the DeltaM - here to save time for PbPb
Double_t mPDGD0 = TDatabasePDG::Instance()->GetParticle(421)->Mass();
Double_t mPDGDstar = TDatabasePDG::Instance()->GetParticle(413)->Mass();
Double_t invmassDelta = dstarD0pi->DeltaInvMass();
if (TMath::Abs(invmassDelta - (mPDGDstar - mPDGD0)) > fPeakWindow) continue;
Int_t isSelected = fCuts->IsSelected(dstarD0pi, AliRDHFCuts::kCandidate, aodEvent); //selected
if (isSelected > 0) fCEvents->Fill(11);
// after cuts
if (fDoImpParDstar && isSelected) {
fHistMassPtImpParTCDs[0]->Fill(arrayForSparse);
if (isPrimary) fHistMassPtImpParTCDs[1]->Fill(arrayForSparse);
else {
fHistMassPtImpParTCDs[2]->Fill(arrayForSparse);
fHistMassPtImpParTCDs[3]->Fill(arrayForSparseTrue);
}
}
if (fDoDStarVsY && isSelected) {
((TH3F*) (fOutputPID->FindObject("deltamassVsyVsPt")))->Fill(dstarD0pi->DeltaInvMass(), dstarD0pi->YDstar(), dstarD0pi->Pt() );
}
// check after cuts
if (fUseMCInfo) {
Int_t mcLabel = dstarD0pi->MatchToMC(413, 421, pdgDgDStartoD0pi, pdgDgD0toKpi, mcTrackArray);
if (mcLabel >= 0) {
AliAODMCParticle *mcTrackParticle = dynamic_cast< AliAODMCParticle*>(mcTrackArray->At(mcLabel));
if (!mcTrackParticle) {std::cout << "no particle" << std::endl; continue;}
Int_t pdgCodeMC = TMath::Abs(mcTrackParticle->GetPdgCode());
if (pdgCodeMC == 413)
{ //if the track is a DStar we check if it comes from charm
Double_t ptMC = mcTrackParticle->Pt();
Bool_t fromCharm = kFALSE;
Int_t mother = mcTrackParticle->GetMother();
Int_t istep = 0;
while (mother >= 0 ) {
istep++;
AliAODMCParticle* mcGranma = dynamic_cast<AliAODMCParticle*>(mcTrackArray->At(mother));
if (mcGranma) {
Int_t abspdgGranma = TMath::Abs(mcGranma->GetPdgCode());
if ((abspdgGranma == 4) || (abspdgGranma > 400 && abspdgGranma < 500) || (abspdgGranma > 4000 && abspdgGranma < 5000)) fromCharm = kTRUE;
mother = mcGranma->GetMother();
} else {
printf("AliVertexingHFUtils::IsTrackFromCharm: Failed casting the mother particle!");
break;
}
}
if (fromCharm)
{
Bool_t mcPionDStarPresent = kFALSE;
Bool_t mcPionD0Present = kFALSE;
Bool_t mcKaonPresent = kFALSE;
Int_t nDaughterDStar = mcTrackParticle->GetNDaughters();
if (nDaughterDStar == 2) {
for (Int_t iDaughterDStar = 0; iDaughterDStar < 2; iDaughterDStar++) {
AliAODMCParticle* daughterDStar = (AliAODMCParticle*)mcTrackArray->At(mcTrackParticle->GetDaughterLabel(iDaughterDStar));
if (!daughterDStar) break;
Int_t pdgCodeDaughterDStar = TMath::Abs(daughterDStar->GetPdgCode());
if (pdgCodeDaughterDStar == 211) { //if the track is a pion we save its monte carlo label
mcPionDStarPresent = kTRUE;
} else if (pdgCodeDaughterDStar == 421) { //if the track is a D0 we look at its daughters
Int_t mcLabelD0 = mcTrackParticle->GetDaughterLabel(iDaughterDStar);
Int_t nDaughterD0 = daughterDStar->GetNDaughters();
if (nDaughterD0 == 2) {
for (Int_t iDaughterD0 = 0; iDaughterD0 < 2; iDaughterD0++) {
AliAODMCParticle* daughterD0 = (AliAODMCParticle*)mcTrackArray->At(daughterDStar->GetDaughterLabel(iDaughterD0));
if (!daughterD0) break;
Int_t pdgCodeDaughterD0 = TMath::Abs(daughterD0->GetPdgCode());
if (pdgCodeDaughterD0 == 211) {
mcPionD0Present = kTRUE;
} else if (pdgCodeDaughterD0 == 321) {
mcKaonPresent = kTRUE;
} else break;
}
}
} else break;
}
}
if (mcPionDStarPresent && mcPionD0Present && mcKaonPresent)
{
TString fillthis = "";
fillthis = "DStarPtTruePostCuts";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC);
fillthis = "DStarPtTruePostCutsWeighted";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC, crossSection);
// fillthis = "PtHardPostCuts";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptHard);
// fillthis = "PtHardWeightedPostCuts";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptHard, crossSection);
// fillthis = "WeightsPostCuts";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(crossSection);
// fillthis = "TrialsPostCuts";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->AddBinContent(1,nTrials);
fillthis = "DStarPtPostCuts";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(Dstarpt);
fillthis = "DStarPtPostCutsWeighted";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(Dstarpt, crossSection);
fillthis = "DStar_per_bin_true_PostCuts";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC);
fillthis = "DStar_per_bin_true_PostCuts_weighted";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC, crossSection);
fillthis = "DStar_per_bin_PostCuts";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(Dstarpt);
fillthis = "DStar_per_bin_PostCuts_weighted";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(Dstarpt, crossSection);
}
}
}
}
}
fillthishist = "";
fillthishist = "PtHardPostCuts";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->Fill(ptHard);
fillthishist = "PtHardWeightedPostCuts";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->Fill(ptHard, crossSection);
fillthishist = "WeightsPostCuts";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->Fill(crossSection);
fillthishist = "TrialsPostCuts";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->AddBinContent(1,nTrials);
// fill PID
FillSpectrum(dstarD0pi, isDStar, fCuts, isSelected, fOutputPID, fPIDhist);
SideBandBackground(dstarD0pi, fCuts, isSelected, fOutputPID, fPIDhist);
//WrongSignForDStar(dstarD0pi,fCuts,fOutputPID);
//swich off the PID selection
fCuts->SetUsePID(kFALSE);
Int_t isSelectedNoPID = fCuts->IsSelected(dstarD0pi, AliRDHFCuts::kCandidate, aodEvent); //selected
fCuts->SetUsePID(kTRUE);
FillSpectrum(dstarD0pi, isDStar, fCuts, isSelectedNoPID, fOutputAll, fAllhist);
// SideBandBackground(dstarD0pi,fCuts,isSelectedNoPID, fOutputAll);
// rare D search ------
if (fDoSearch) {
TLorentzVector lorentzTrack1(0, 0, 0, 0); // lorentz 4 vector
TLorentzVector lorentzTrack2(0, 0, 0, 0); // lorentz 4 vector
for (Int_t i = 0; i < aodEvent->GetNumberOfTracks(); i++) {
AliAODTrack* aodTrack = dynamic_cast<AliAODTrack*>(aodEvent->GetTrack(i));
if (!aodTrack) AliFatal("Not a standard AOD");
if (dstarD0pi->Charge() == aodTrack->Charge()) continue;
if ((!(aodTrack->GetStatus()&AliESDtrack::kITSrefit) || (!(aodTrack->GetStatus()&AliESDtrack::kTPCrefit)))) continue;
if (TMath::Abs(invmassDelta - (mPDGDstar - mPDGD0)) > 0.02) continue;
//build the D1 mass
Double_t mass = TDatabasePDG::Instance()->GetParticle(211)->Mass();
lorentzTrack1.SetPxPyPzE( dstarD0pi->Px(), dstarD0pi->Py(), dstarD0pi->Pz(), dstarD0pi->E(413) );
lorentzTrack2.SetPxPyPzE( aodTrack->Px(), aodTrack->Py(), aodTrack->Pz(), aodTrack->E(mass) );
//D1 mass
Double_t d1mass = ((lorentzTrack1 + lorentzTrack2).M());
//mass difference - at 0.4117 and 0.4566
fDeltaMassD1->Fill(d1mass - dstarD0pi->InvMassDstarKpipi());
}
}
if (isDStar == 1) {
fTrueDiff2->Fill(dstarD0pi->Pt(), dstarD0pi->DeltaInvMass());
}
}
fCounter->StoreCandidates(aodEvent, nSelectedProd, kTRUE);
fCounter->StoreCandidates(aodEvent, nSelectedAna, kFALSE);
delete vHF;
AliDebug(2, Form("Found %i Reco particles that are D*!!", icountReco));
PostData(1, fOutput);
PostData(2, fOutputAll);
PostData(3, fOutputPID);
PostData(5, fCounter);
PostData(6, fOutputProductionCheck);
}
//________________________________________ terminate ___________________________
void AliAnalysisTaskSEDStarEMCALProductionCheck::Terminate(Option_t*)
{
/// The Terminate() function is the last function to be called during
/// a query. It always runs on the client, it can be used to present
/// the results graphically or save the results to file.
//Info("Terminate","");
AliAnalysisTaskSE::Terminate();
fOutput = dynamic_cast<TList*> (GetOutputData(1));
if (!fOutput) {
printf("ERROR: fOutput not available\n");
return;
}
fCEvents = dynamic_cast<TH1F*>(fOutput->FindObject("fCEvents"));
fDeltaMassD1 = dynamic_cast<TH1F*>(fOutput->FindObject("fDeltaMassD1"));
fTrueDiff2 = dynamic_cast<TH2F*>(fOutput->FindObject("fTrueDiff2"));
fOutputAll = dynamic_cast<TList*> (GetOutputData(1));
if (!fOutputAll) {
printf("ERROR: fOutputAll not available\n");
return;
}
fOutputPID = dynamic_cast<TList*> (GetOutputData(2));
if (!fOutputPID) {
printf("ERROR: fOutputPID not available\n");
return;
}
fOutputProductionCheck = dynamic_cast<TList*> (GetOutputData(6));
if (!fOutputProductionCheck) {
printf("ERROR: fOutputProductionCheck not available\n");
return;
}
return;
}
//___________________________________________________________________________
void AliAnalysisTaskSEDStarEMCALProductionCheck::UserCreateOutputObjects() {
/// output
Info("UserCreateOutputObjects", "CreateOutputObjects of task %s\n", GetName());
//slot #1
//OpenFile(1);
fOutput = new TList();
fOutput->SetOwner();
fOutput->SetName("chist0");
fOutputAll = new TList();
fOutputAll->SetOwner();
fOutputAll->SetName("listAll");
fOutputPID = new TList();
fOutputPID->SetOwner();
fOutputPID->SetName("listPID");
fOutputProductionCheck = new TList();
fOutputProductionCheck->SetOwner();
fOutputProductionCheck->SetName("listPID");
// define histograms
DefineHistograms();
//Counter for Normalization
fCounter = new AliNormalizationCounter(Form("%s", GetOutputSlot(5)->GetContainer()->GetName()));
fCounter->Init();
if (fDoImpParDstar) CreateImpactParameterHistos();
PostData(1, fOutput);
PostData(2, fOutputAll);
PostData(3, fOutputPID);
PostData(5, fCounter);
PostData(6, fOutputProductionCheck);
return;
}
//___________________________________ hiostograms _______________________________________
void AliAnalysisTaskSEDStarEMCALProductionCheck::DefineHistograms() {
/// Create histograms
fCEvents = new TH1F("fCEvents", "counter", 14, 0, 14);
fCEvents->SetStats(kTRUE);
fCEvents->GetXaxis()->SetTitle("1");
fCEvents->GetYaxis()->SetTitle("counts");
fCEvents->GetXaxis()->SetBinLabel(1, "nEventsRead");
fCEvents->GetXaxis()->SetBinLabel(2, "nEvents Matched dAOD");
fCEvents->GetXaxis()->SetBinLabel(3, "good prim vtx and B field");
fCEvents->GetXaxis()->SetBinLabel(4, "no event selected");
fCEvents->GetXaxis()->SetBinLabel(5, "no vtx contributors");
fCEvents->GetXaxis()->SetBinLabel(6, "trigger for PbPb");
fCEvents->GetXaxis()->SetBinLabel(7, "no z vtx");
fCEvents->GetXaxis()->SetBinLabel(9, "nEvents Mismatched dAOD");
fCEvents->GetXaxis()->SetBinLabel(11, "no. of cascade candidates");
fCEvents->GetXaxis()->SetBinLabel(12, "no. of Dstar after selection cuts");
fCEvents->GetXaxis()->SetBinLabel(13, "no. of not on-the-fly rec Dstar");
fCEvents->GetXaxis()->SetBinLabel(14, "no. of Dstar rejected by preselect"); //toadd
fOutput->Add(fCEvents);
fTrueDiff2 = new TH2F("DiffDstar_pt", "True Reco diff vs pt", 200, 0, 15, 900, 0, 0.3);
fOutput->Add(fTrueDiff2);
fDeltaMassD1 = new TH1F("DeltaMassD1", "delta mass d1", 600, 0, 0.8);
fOutput->Add(fDeltaMassD1);
//temp a
fAllhist = new TH1F*[(fNPtBins + 2) * 18];
fPIDhist = new TH1F*[(fNPtBins + 2) * 18];
TString nameMass = " ", nameSgn = " ", nameBkg = " ";
for (Int_t i = -2; i < fNPtBins; i++) {
nameMass = "histDeltaMass_";
nameMass += i + 1;
nameSgn = "histDeltaSgn_";
nameSgn += i + 1;
nameBkg = "histDeltaBkg_";
nameBkg += i + 1;
if (i == -2) {
nameMass = "histDeltaMass";
nameSgn = "histDeltaSgn";
nameBkg = "histDeltaBkg";
}
TH1F* spectrumMass = new TH1F(nameMass.Data(), "D^{*}-D^{0} invariant mass; #DeltaM [GeV/c^{2}]; Entries", 700, 0.13, 0.2);
TH1F* spectrumSgn = new TH1F(nameSgn.Data(), "D^{*}-D^{0} Signal invariant mass - MC; #DeltaM [GeV/c^{2}]; Entries", 700, 0.13, 0.2);
TH1F* spectrumBkg = new TH1F(nameBkg.Data(), "D^{*}-D^{0} Background invariant mass - MC; #DeltaM [GeV/c^{2}]; Entries", 700, 0.13, 0.2);
nameMass = "histD0Mass_";
nameMass += i + 1;
nameSgn = "histD0Sgn_";
nameSgn += i + 1;
nameBkg = "histD0Bkg_";
nameBkg += i + 1;
if (i == -2) {
nameMass = "histD0Mass";
nameSgn = "histD0Sgn";
nameBkg = "histD0Bkg";
}
TH1F* spectrumD0Mass = new TH1F(nameMass.Data(), "D^{0} invariant mass; M(D^{0}) [GeV/c^{2}]; Entries", 200, 1.75, 1.95);
TH1F* spectrumD0Sgn = new TH1F(nameSgn.Data(), "D^{0} Signal invariant mass - MC; M(D^{0}) [GeV/c^{2}]; Entries", 200, 1.75, 1.95);
TH1F* spectrumD0Bkg = new TH1F(nameBkg.Data(), "D^{0} Background invariant mass - MC; M(D^{0}) [GeV/c^{2}]; Entries", 200, 1.75, 1.95);
nameMass = "histDstarMass_";
nameMass += i + 1;
nameSgn = "histDstarSgn_";
nameSgn += i + 1;
nameBkg = "histDstarBkg_";
nameBkg += i + 1;
if (i == -2) {
nameMass = "histDstarMass";
nameSgn = "histDstarSgn";
nameBkg = "histDstarBkg";
}
TH1F* spectrumDstarMass = new TH1F(nameMass.Data(), "D^{*} invariant mass; M(D^{*}) [GeV/c^{2}]; Entries", 200, 1.9, 2.1);
TH1F* spectrumDstarSgn = new TH1F(nameSgn.Data(), "D^{*} Signal invariant mass - MC; M(D^{*}) [GeV/c^{2}]; Entries", 200, 1.9, 2.1);
TH1F* spectrumDstarBkg = new TH1F(nameBkg.Data(), "D^{*} Background invariant mass - MC; M(D^{*}) [GeV/c^{2}]; Entries", 200, 1.9, 2.1);
nameMass = "histSideBandMass_";
nameMass += i + 1;
if (i == -2) {
nameMass = "histSideBandMass";
}
TH1F* spectrumSideBandMass = new TH1F(nameMass.Data(), "D^{*}-D^{0} sideband mass; M(D^{*}) [GeV/c^{2}]; Entries", 200, 0.1, 0.2);
nameMass = "histWrongSignMass_";
nameMass += i + 1;
if (i == -2) {
nameMass = "histWrongSignMass";
}
TH1F* spectrumWrongSignMass = new TH1F(nameMass.Data(), "D^{*}-D^{0} wrongsign mass; M(D^{*}) [GeV/c^{2}]; Entries", 200, 0.1, 0.2);
spectrumMass->Sumw2();
spectrumSgn->Sumw2();
spectrumBkg->Sumw2();
spectrumMass->SetLineColor(6);
spectrumSgn->SetLineColor(2);
spectrumBkg->SetLineColor(4);
spectrumMass->SetMarkerStyle(20);
spectrumSgn->SetMarkerStyle(20);
spectrumBkg->SetMarkerStyle(20);
spectrumMass->SetMarkerSize(0.6);
spectrumSgn->SetMarkerSize(0.6);
spectrumBkg->SetMarkerSize(0.6);
spectrumMass->SetMarkerColor(6);
spectrumSgn->SetMarkerColor(2);
spectrumBkg->SetMarkerColor(4);
spectrumD0Mass->Sumw2();
spectrumD0Sgn->Sumw2();
spectrumD0Bkg->Sumw2();
spectrumD0Mass->SetLineColor(6);
spectrumD0Sgn->SetLineColor(2);
spectrumD0Bkg->SetLineColor(4);
spectrumD0Mass->SetMarkerStyle(20);
spectrumD0Sgn->SetMarkerStyle(20);
spectrumD0Bkg->SetMarkerStyle(20);
spectrumD0Mass->SetMarkerSize(0.6);
spectrumD0Sgn->SetMarkerSize(0.6);
spectrumD0Bkg->SetMarkerSize(0.6);
spectrumD0Mass->SetMarkerColor(6);
spectrumD0Sgn->SetMarkerColor(2);
spectrumD0Bkg->SetMarkerColor(4);
spectrumDstarMass->Sumw2();
spectrumDstarSgn->Sumw2();
spectrumDstarBkg->Sumw2();
spectrumDstarMass->SetLineColor(6);
spectrumDstarSgn->SetLineColor(2);
spectrumDstarBkg->SetLineColor(4);
spectrumDstarMass->SetMarkerStyle(20);
spectrumDstarSgn->SetMarkerStyle(20);
spectrumDstarBkg->SetMarkerStyle(20);
spectrumDstarMass->SetMarkerSize(0.6);
spectrumDstarSgn->SetMarkerSize(0.6);
spectrumDstarBkg->SetMarkerSize(0.6);
spectrumDstarMass->SetMarkerColor(6);
spectrumDstarSgn->SetMarkerColor(2);
spectrumDstarBkg->SetMarkerColor(4);
spectrumSideBandMass->Sumw2();
spectrumSideBandMass->SetLineColor(4);
spectrumSideBandMass->SetMarkerStyle(20);
spectrumSideBandMass->SetMarkerSize(0.6);
spectrumSideBandMass->SetMarkerColor(4);
spectrumWrongSignMass->Sumw2();
spectrumWrongSignMass->SetLineColor(4);
spectrumWrongSignMass->SetMarkerStyle(20);
spectrumWrongSignMass->SetMarkerSize(0.6);
spectrumWrongSignMass->SetMarkerColor(4);
TH1F* allMass = (TH1F*)spectrumMass->Clone();
TH1F* allSgn = (TH1F*)spectrumSgn->Clone();
TH1F* allBkg = (TH1F*)spectrumBkg->Clone();
TH1F* pidMass = (TH1F*)spectrumMass->Clone();
TH1F* pidSgn = (TH1F*)spectrumSgn->Clone();
TH1F* pidBkg = (TH1F*)spectrumBkg->Clone();
fOutputAll->Add(allMass);
fOutputAll->Add(allSgn);
fOutputAll->Add(allBkg);
fAllhist[i + 2 + ((fNPtBins + 2)*kDeltaMass)] = allMass;
fAllhist[i + 2 + ((fNPtBins + 2)*kDeltaSgn)] = allSgn;
fAllhist[i + 2 + ((fNPtBins + 2)*kDeltaBkg)] = allBkg;
fOutputPID->Add(pidMass);
fOutputPID->Add(pidSgn);
fOutputPID->Add(pidBkg);
fPIDhist[i + 2 + ((fNPtBins + 2)*kDeltaMass)] = pidMass;
fPIDhist[i + 2 + ((fNPtBins + 2)*kDeltaSgn)] = pidSgn;
fPIDhist[i + 2 + ((fNPtBins + 2)*kDeltaBkg)] = pidBkg;
TH1F* allD0Mass = (TH1F*)spectrumD0Mass->Clone();
TH1F* allD0Sgn = (TH1F*)spectrumD0Sgn->Clone();
TH1F* allD0Bkg = (TH1F*)spectrumD0Bkg->Clone();
TH1F* pidD0Mass = (TH1F*)spectrumD0Mass->Clone();
TH1F* pidD0Sgn = (TH1F*)spectrumD0Sgn->Clone();
TH1F* pidD0Bkg = (TH1F*)spectrumD0Bkg->Clone();
fOutputAll->Add(allD0Mass);
fOutputAll->Add(allD0Sgn);
fOutputAll->Add(allD0Bkg);
fAllhist[i + 2 + ((fNPtBins + 2)*kDzMass)] = allD0Mass;
fAllhist[i + 2 + ((fNPtBins + 2)*kDzSgn)] = allD0Sgn;
fAllhist[i + 2 + ((fNPtBins + 2)*kDzBkg)] = allD0Bkg;
fOutputPID->Add(pidD0Mass);
fOutputPID->Add(pidD0Sgn);
fOutputPID->Add(pidD0Bkg);
fPIDhist[i + 2 + ((fNPtBins + 2)*kDzMass)] = pidD0Mass;
fPIDhist[i + 2 + ((fNPtBins + 2)*kDzSgn)] = pidD0Sgn;
fPIDhist[i + 2 + ((fNPtBins + 2)*kDzBkg)] = pidD0Bkg;
TH1F* allDstarMass = (TH1F*)spectrumDstarMass->Clone();
TH1F* allDstarSgn = (TH1F*)spectrumDstarSgn->Clone();
TH1F* allDstarBkg = (TH1F*)spectrumDstarBkg->Clone();
TH1F* pidDstarMass = (TH1F*)spectrumDstarMass->Clone();
TH1F* pidDstarSgn = (TH1F*)spectrumDstarSgn->Clone();
TH1F* pidDstarBkg = (TH1F*)spectrumDstarBkg->Clone();
fOutputAll->Add(allDstarMass);
fOutputAll->Add(allDstarSgn);
fOutputAll->Add(allDstarBkg);
fAllhist[i + 2 + ((fNPtBins + 2)*kDstarMass)] = allDstarMass;
fAllhist[i + 2 + ((fNPtBins + 2)*kDstarSgn)] = allDstarSgn;
fAllhist[i + 2 + ((fNPtBins + 2)*kDstarBkg)] = allDstarBkg;
fOutputPID->Add(pidDstarMass);
fOutputPID->Add(pidDstarSgn);
fOutputPID->Add(pidDstarBkg);
fPIDhist[i + 2 + ((fNPtBins + 2)*kDstarMass)] = pidDstarMass;
fPIDhist[i + 2 + ((fNPtBins + 2)*kDstarSgn)] = pidDstarSgn;
fPIDhist[i + 2 + ((fNPtBins + 2)*kDstarBkg)] = pidDstarBkg;
TH1F* allSideBandMass = (TH1F*)spectrumSideBandMass->Clone();
TH1F* pidSideBandMass = (TH1F*)spectrumSideBandMass->Clone();
fOutputAll->Add(allSideBandMass);
fOutputPID->Add(pidSideBandMass);
fAllhist[i + 2 + ((fNPtBins + 2)*kSideBandMass)] = allSideBandMass;
fPIDhist[i + 2 + ((fNPtBins + 2)*kSideBandMass)] = pidSideBandMass;
TH1F* allWrongSignMass = (TH1F*)spectrumWrongSignMass->Clone();
TH1F* pidWrongSignMass = (TH1F*)spectrumWrongSignMass->Clone();
fOutputAll->Add(allWrongSignMass);
fOutputPID->Add(pidWrongSignMass);
fAllhist[i + 2 + ((fNPtBins + 2)*kWrongSignMass)] = allWrongSignMass;
fPIDhist[i + 2 + ((fNPtBins + 2)*kWrongSignMass)] = pidWrongSignMass;
}
// pt spectra
nameMass = "ptMass";
nameSgn = "ptSgn";
nameBkg = "ptBkg";
TH1F* ptspectrumMass = new TH1F(nameMass.Data(), "D^{*} p_{T}; p_{T} [GeV]; Entries", 400, 0, 50);
TH1F* ptspectrumSgn = new TH1F(nameSgn.Data(), "D^{*} Signal p_{T} - MC; p_{T} [GeV]; Entries", 400, 0, 50);
TH1F* ptspectrumBkg = new TH1F(nameBkg.Data(), "D^{*} Background p_{T} - MC; p_{T} [GeV]; Entries", 400, 0, 50);
ptspectrumMass->Sumw2();
ptspectrumSgn->Sumw2();
ptspectrumBkg->Sumw2();
ptspectrumMass->SetLineColor(6);
ptspectrumSgn->SetLineColor(2);
ptspectrumBkg->SetLineColor(4);
ptspectrumMass->SetMarkerStyle(20);
ptspectrumSgn->SetMarkerStyle(20);
ptspectrumBkg->SetMarkerStyle(20);
ptspectrumMass->SetMarkerSize(0.6);
ptspectrumSgn->SetMarkerSize(0.6);
ptspectrumBkg->SetMarkerSize(0.6);
ptspectrumMass->SetMarkerColor(6);
ptspectrumSgn->SetMarkerColor(2);
ptspectrumBkg->SetMarkerColor(4);
TH1F* ptallMass = (TH1F*)ptspectrumMass->Clone();
TH1F* ptallSgn = (TH1F*)ptspectrumSgn->Clone();
TH1F* ptallBkg = (TH1F*)ptspectrumBkg->Clone();
TH1F* ptpidMass = (TH1F*)ptspectrumMass->Clone();
TH1F* ptpidSgn = (TH1F*)ptspectrumSgn->Clone();
TH1F* ptpidBkg = (TH1F*)ptspectrumBkg->Clone();
fOutputAll->Add(ptallMass);
fOutputAll->Add(ptallSgn);
fOutputAll->Add(ptallBkg);
fAllhist[((fNPtBins + 2)*kptMass)] = ptallMass;
fAllhist[((fNPtBins + 2)*kptSgn)] = ptallSgn;
fAllhist[((fNPtBins + 2)*kptBkg)] = ptallBkg;
fOutputPID->Add(ptpidMass);
fOutputPID->Add(ptpidSgn);
fOutputPID->Add(ptpidBkg);
fPIDhist[(fNPtBins + 2)*kptMass] = ptpidMass;
fPIDhist[(fNPtBins + 2)*kptSgn] = ptpidSgn;
fPIDhist[(fNPtBins + 2)*kptBkg] = ptpidBkg;
// eta spectra
nameMass = "etaMass";
nameSgn = "etaSgn";
nameBkg = "etaBkg";
TH1F* etaspectrumMass = new TH1F(nameMass.Data(), "D^{*} #eta; #eta; Entries", 200, -1, 1);
TH1F* etaspectrumSgn = new TH1F(nameSgn.Data(), "D^{*} Signal #eta - MC; #eta; Entries", 200, -1, 1);
TH1F* etaspectrumBkg = new TH1F(nameBkg.Data(), "D^{*} Background #eta - MC; #eta; Entries", 200, -1, 1);
etaspectrumMass->Sumw2();
etaspectrumSgn->Sumw2();
etaspectrumBkg->Sumw2();
etaspectrumMass->SetLineColor(6);
etaspectrumSgn->SetLineColor(2);
etaspectrumBkg->SetLineColor(4);
etaspectrumMass->SetMarkerStyle(20);
etaspectrumSgn->SetMarkerStyle(20);
etaspectrumBkg->SetMarkerStyle(20);
etaspectrumMass->SetMarkerSize(0.6);
etaspectrumSgn->SetMarkerSize(0.6);
etaspectrumBkg->SetMarkerSize(0.6);
etaspectrumMass->SetMarkerColor(6);
etaspectrumSgn->SetMarkerColor(2);
etaspectrumBkg->SetMarkerColor(4);
TH1F* etaallMass = (TH1F*)etaspectrumMass->Clone();
TH1F* etaallSgn = (TH1F*)etaspectrumSgn->Clone();
TH1F* etaallBkg = (TH1F*)etaspectrumBkg->Clone();
TH1F* etapidMass = (TH1F*)etaspectrumMass->Clone();
TH1F* etapidSgn = (TH1F*)etaspectrumSgn->Clone();
TH1F* etapidBkg = (TH1F*)etaspectrumBkg->Clone();
fOutputAll->Add(etaallMass);
fOutputAll->Add(etaallSgn);
fOutputAll->Add(etaallBkg);
fAllhist[(fNPtBins + 2)*ketaMass] = etaallMass;
fAllhist[(fNPtBins + 2)*ketaSgn] = etaallSgn;
fAllhist[(fNPtBins + 2)*ketaBkg] = etaallBkg;
fOutputPID->Add(etapidMass);
fOutputPID->Add(etapidSgn);
fOutputPID->Add(etapidBkg);
fPIDhist[(fNPtBins + 2)*ketaMass] = etapidMass;
fPIDhist[(fNPtBins + 2)*ketaSgn] = etapidSgn;
fPIDhist[(fNPtBins + 2)*ketaBkg] = etapidBkg;
if (fDoDStarVsY) {
TH3F* deltamassVsyVsPtPID = new TH3F("deltamassVsyVsPt", "delta mass Vs y Vs pT; #DeltaM [GeV/c^{2}]; y; p_{T} [GeV/c]", 700, 0.13, 0.2, 40, -1, 1, 36, 0., 36.);
fOutputPID->Add(deltamassVsyVsPtPID);
}
TString name_DStarPtTruePreEventSelection = "DStarPtTruePreEventSelection";
TH1F* hist_DStarPtTruePreEventSelection = new TH1F(name_DStarPtTruePreEventSelection.Data(), "DStarPtTruePreEventSelection; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_DStarPtTruePreEventSelection->Sumw2();
hist_DStarPtTruePreEventSelection->SetLineColor(6);
hist_DStarPtTruePreEventSelection->SetMarkerStyle(20);
hist_DStarPtTruePreEventSelection->SetMarkerSize(0.6);
hist_DStarPtTruePreEventSelection->SetMarkerColor(6);
TH1F* histogram_DStarPtTruePreEventSelection = (TH1F*)hist_DStarPtTruePreEventSelection->Clone();
fOutputProductionCheck->Add(histogram_DStarPtTruePreEventSelection);
TString name_DStarPtTruePreEventSelectionWeighted = "DStarPtTruePreEventSelectionWeighted";
TH1F* hist_DStarPtTruePreEventSelectionWeighted = new TH1F(name_DStarPtTruePreEventSelectionWeighted.Data(), "DStarPtTruePreEventSelectionWeighted; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_DStarPtTruePreEventSelectionWeighted->Sumw2();
hist_DStarPtTruePreEventSelectionWeighted->SetLineColor(6);
hist_DStarPtTruePreEventSelectionWeighted->SetMarkerStyle(20);
hist_DStarPtTruePreEventSelectionWeighted->SetMarkerSize(0.6);
hist_DStarPtTruePreEventSelectionWeighted->SetMarkerColor(6);
TH1F* histogram_DStarPtTruePreEventSelectionWeighted = (TH1F*)hist_DStarPtTruePreEventSelectionWeighted->Clone();
fOutputProductionCheck->Add(histogram_DStarPtTruePreEventSelectionWeighted);
TString name_DStarPtTruePostEventSelection = "DStarPtTruePostEventSelection";
TH1F* hist_DStarPtTruePostEventSelection = new TH1F(name_DStarPtTruePostEventSelection.Data(), "DStarPtTruePostEventSelection; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_DStarPtTruePostEventSelection->Sumw2();
hist_DStarPtTruePostEventSelection->SetLineColor(6);
hist_DStarPtTruePostEventSelection->SetMarkerStyle(20);
hist_DStarPtTruePostEventSelection->SetMarkerSize(0.6);
hist_DStarPtTruePostEventSelection->SetMarkerColor(6);
TH1F* histogram_DStarPtTruePostEventSelection = (TH1F*)hist_DStarPtTruePostEventSelection->Clone();
fOutputProductionCheck->Add(histogram_DStarPtTruePostEventSelection);
TString name_DStarPtTruePostEventSelectionWeighted = "DStarPtTruePostEventSelectionWeighted";
TH1F* hist_DStarPtTruePostEventSelectionWeighted = new TH1F(name_DStarPtTruePostEventSelectionWeighted.Data(), "DStarPtTruePostEventSelectionWeighted; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_DStarPtTruePostEventSelectionWeighted->Sumw2();
hist_DStarPtTruePostEventSelectionWeighted->SetLineColor(6);
hist_DStarPtTruePostEventSelectionWeighted->SetMarkerStyle(20);
hist_DStarPtTruePostEventSelectionWeighted->SetMarkerSize(0.6);
hist_DStarPtTruePostEventSelectionWeighted->SetMarkerColor(6);
TH1F* histogram_DStarPtTruePostEventSelectionWeighted = (TH1F*)hist_DStarPtTruePostEventSelectionWeighted->Clone();
fOutputProductionCheck->Add(histogram_DStarPtTruePostEventSelectionWeighted);
TString name_DStarPtTruePostCuts = "DStarPtTruePostCuts";
TH1F* hist_DStarPtTruePostCuts = new TH1F(name_DStarPtTruePostCuts.Data(), "DStarPtTruePostCuts; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_DStarPtTruePostCuts->Sumw2();
hist_DStarPtTruePostCuts->SetLineColor(6);
hist_DStarPtTruePostCuts->SetMarkerStyle(20);
hist_DStarPtTruePostCuts->SetMarkerSize(0.6);
hist_DStarPtTruePostCuts->SetMarkerColor(6);
TH1F* histogram_DStarPtTruePostCuts = (TH1F*)hist_DStarPtTruePostCuts->Clone();
fOutputProductionCheck->Add(histogram_DStarPtTruePostCuts);
TString name_DStarPtTruePostCutsWeighted = "DStarPtTruePostCutsWeighted";
TH1F* hist_DStarPtTruePostCutsWeighted = new TH1F(name_DStarPtTruePostCutsWeighted.Data(), "DStarPtTruePostCutsWeighted; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_DStarPtTruePostCutsWeighted->Sumw2();
hist_DStarPtTruePostCutsWeighted->SetLineColor(6);
hist_DStarPtTruePostCutsWeighted->SetMarkerStyle(20);
hist_DStarPtTruePostCutsWeighted->SetMarkerSize(0.6);
hist_DStarPtTruePostCutsWeighted->SetMarkerColor(6);
TH1F* histogram_DStarPtTruePostCutsWeighted = (TH1F*)hist_DStarPtTruePostCutsWeighted->Clone();
fOutputProductionCheck->Add(histogram_DStarPtTruePostCutsWeighted);
TString name_DStarPtPostCuts = "DStarPtPostCuts";
TH1F* hist_DStarPtPostCuts = new TH1F(name_DStarPtPostCuts.Data(), "DStarPtPostCuts; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_DStarPtPostCuts->Sumw2();
hist_DStarPtPostCuts->SetLineColor(6);
hist_DStarPtPostCuts->SetMarkerStyle(20);
hist_DStarPtPostCuts->SetMarkerSize(0.6);
hist_DStarPtPostCuts->SetMarkerColor(6);
TH1F* histogram_DStarPtPostCuts = (TH1F*)hist_DStarPtPostCuts->Clone();
fOutputProductionCheck->Add(histogram_DStarPtPostCuts);
TString name_DStarPtPostCutsWeighted = "DStarPtPostCutsWeighted";
TH1F* hist_DStarPtPostCutsWeighted = new TH1F(name_DStarPtPostCutsWeighted.Data(), "DStarPtPostCutsWeighted; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_DStarPtPostCutsWeighted->Sumw2();
hist_DStarPtPostCutsWeighted->SetLineColor(6);
hist_DStarPtPostCutsWeighted->SetMarkerStyle(20);
hist_DStarPtPostCutsWeighted->SetMarkerSize(0.6);
hist_DStarPtPostCutsWeighted->SetMarkerColor(6);
TH1F* histogram_DStarPtPostCutsWeighted = (TH1F*)hist_DStarPtPostCutsWeighted->Clone();
fOutputProductionCheck->Add(histogram_DStarPtPostCutsWeighted);
TString name_PtHardPreEventSelection = "PtHardPreEventSelection";
TH1F* hist_PtHardPreEventSelection = new TH1F(name_PtHardPreEventSelection.Data(), "PtHardPreEventSelection; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_PtHardPreEventSelection->Sumw2();
hist_PtHardPreEventSelection->SetLineColor(6);
hist_PtHardPreEventSelection->SetMarkerStyle(20);
hist_PtHardPreEventSelection->SetMarkerSize(0.6);
hist_PtHardPreEventSelection->SetMarkerColor(6);
TH1F* histogram_PtHardPreEventSelection = (TH1F*)hist_PtHardPreEventSelection->Clone();
fOutputProductionCheck->Add(histogram_PtHardPreEventSelection);
TString name_PtHardPostEventSelection = "PtHardPostEventSelection";
TH1F* hist_PtHardPostEventSelection = new TH1F(name_PtHardPostEventSelection.Data(), "PtHardPostEventSelection; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_PtHardPostEventSelection->Sumw2();
hist_PtHardPostEventSelection->SetLineColor(6);
hist_PtHardPostEventSelection->SetMarkerStyle(20);
hist_PtHardPostEventSelection->SetMarkerSize(0.6);
hist_PtHardPostEventSelection->SetMarkerColor(6);
TH1F* histogram_PtHardPostEventSelection = (TH1F*)hist_PtHardPostEventSelection->Clone();
fOutputProductionCheck->Add(histogram_PtHardPostEventSelection);
TString name_PtHardPostCuts = "PtHardPostCuts";
TH1F* hist_PtHardPostCuts = new TH1F(name_PtHardPostCuts.Data(), "PtHardPostCuts; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_PtHardPostCuts->Sumw2();
hist_PtHardPostCuts->SetLineColor(6);
hist_PtHardPostCuts->SetMarkerStyle(20);
hist_PtHardPostCuts->SetMarkerSize(0.6);
hist_PtHardPostCuts->SetMarkerColor(6);
TH1F* histogram_PtHardPostCuts = (TH1F*)hist_PtHardPostCuts->Clone();
fOutputProductionCheck->Add(histogram_PtHardPostCuts);
TString name_PtHardWeightedPreEventSelection = "PtHardWeightedPreEventSelection";
TH1F* hist_PtHardWeightedPreEventSelection = new TH1F(name_PtHardWeightedPreEventSelection.Data(), "PtHardWeightedPreEventSelection; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_PtHardWeightedPreEventSelection->Sumw2();
hist_PtHardWeightedPreEventSelection->SetLineColor(6);
hist_PtHardWeightedPreEventSelection->SetMarkerStyle(20);
hist_PtHardWeightedPreEventSelection->SetMarkerSize(0.6);
hist_PtHardWeightedPreEventSelection->SetMarkerColor(6);
TH1F* histogram_PtHardWeightedPreEventSelection = (TH1F*)hist_PtHardWeightedPreEventSelection->Clone();
fOutputProductionCheck->Add(histogram_PtHardWeightedPreEventSelection);
TString name_PtHardWeightedPostEventSelection = "PtHardWeightedPostEventSelection";
TH1F* hist_PtHardWeightedPostEventSelection = new TH1F(name_PtHardWeightedPostEventSelection.Data(), "PtHardWeightedPostEventSelection; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_PtHardWeightedPostEventSelection->Sumw2();
hist_PtHardWeightedPostEventSelection->SetLineColor(6);
hist_PtHardWeightedPostEventSelection->SetMarkerStyle(20);
hist_PtHardWeightedPostEventSelection->SetMarkerSize(0.6);
hist_PtHardWeightedPostEventSelection->SetMarkerColor(6);
TH1F* histogram_PtHardWeightedPostEventSelection = (TH1F*)hist_PtHardWeightedPostEventSelection->Clone();
fOutputProductionCheck->Add(histogram_PtHardWeightedPostEventSelection);
TString name_PtHardWeightedPostCuts = "PtHardWeightedPostCuts";
TH1F* hist_PtHardWeightedPostCuts = new TH1F(name_PtHardWeightedPostCuts.Data(), "PtHardWeightedPostCuts; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_PtHardWeightedPostCuts->Sumw2();
hist_PtHardWeightedPostCuts->SetLineColor(6);
hist_PtHardWeightedPostCuts->SetMarkerStyle(20);
hist_PtHardWeightedPostCuts->SetMarkerSize(0.6);
hist_PtHardWeightedPostCuts->SetMarkerColor(6);
TH1F* histogram_PtHardWeightedPostCuts = (TH1F*)hist_PtHardWeightedPostCuts->Clone();
fOutputProductionCheck->Add(histogram_PtHardWeightedPostCuts);
TString name_WeightsPreEventSelection = "WeightsPreEventSelection";
TH1F* hist_WeightsPreEventSelection = new TH1F(name_WeightsPreEventSelection.Data(), "WeightsPreEventSelection; p_{T} [GeV/c]; Entries", 50000, 0, 1000);
hist_WeightsPreEventSelection->Sumw2();
hist_WeightsPreEventSelection->SetLineColor(6);
hist_WeightsPreEventSelection->SetMarkerStyle(20);
hist_WeightsPreEventSelection->SetMarkerSize(0.6);
hist_WeightsPreEventSelection->SetMarkerColor(6);
TH1F* histogram_WeightsPreEventSelection = (TH1F*)hist_WeightsPreEventSelection->Clone();
fOutputProductionCheck->Add(histogram_WeightsPreEventSelection);
TString name_WeightsPostEventSelection = "WeightsPostEventSelection";
TH1F* hist_WeightsPostEventSelection = new TH1F(name_WeightsPostEventSelection.Data(), "WeightsPostEventSelection; p_{T} [GeV/c]; Entries", 50000, 0, 1000);
hist_WeightsPostEventSelection->Sumw2();
hist_WeightsPostEventSelection->SetLineColor(6);
hist_WeightsPostEventSelection->SetMarkerStyle(20);
hist_WeightsPostEventSelection->SetMarkerSize(0.6);
hist_WeightsPostEventSelection->SetMarkerColor(6);
TH1F* histogram_WeightsPostEventSelection = (TH1F*)hist_WeightsPostEventSelection->Clone();
fOutputProductionCheck->Add(histogram_WeightsPostEventSelection);
TString name_WeightsPostCuts = "WeightsPostCuts";
TH1F* hist_WeightsPostCuts = new TH1F(name_WeightsPostCuts.Data(), "WeightsPostCuts; p_{T} [GeV/c]; Entries", 50000, 0, 1000);
hist_WeightsPostCuts->Sumw2();
hist_WeightsPostCuts->SetLineColor(6);
hist_WeightsPostCuts->SetMarkerStyle(20);
hist_WeightsPostCuts->SetMarkerSize(0.6);
hist_WeightsPostCuts->SetMarkerColor(6);
TH1F* histogram_WeightsPostCuts = (TH1F*)hist_WeightsPostCuts->Clone();
fOutputProductionCheck->Add(histogram_WeightsPostCuts);
TString name_TrialsPreEventSelection = "TrialsPreEventSelection";
TH1F* hist_TrialsPreEventSelection = new TH1F(name_TrialsPreEventSelection.Data(), "TrialsPreEventSelection; p_{T} [GeV/c]; Entries", 1, 0, 1);
hist_TrialsPreEventSelection->Sumw2();
hist_TrialsPreEventSelection->SetLineColor(6);
hist_TrialsPreEventSelection->SetMarkerStyle(20);
hist_TrialsPreEventSelection->SetMarkerSize(0.6);
hist_TrialsPreEventSelection->SetMarkerColor(6);
TH1F* histogram_TrialsPreEventSelection = (TH1F*)hist_TrialsPreEventSelection->Clone();
fOutputProductionCheck->Add(histogram_TrialsPreEventSelection);
TString name_TrialsPostEventSelection = "TrialsPostEventSelection";
TH1F* hist_TrialsPostEventSelection = new TH1F(name_TrialsPostEventSelection.Data(), "TrialsPostEventSelection; p_{T} [GeV/c]; Entries", 1, 0, 1);
hist_TrialsPostEventSelection->Sumw2();
hist_TrialsPostEventSelection->SetLineColor(6);
hist_TrialsPostEventSelection->SetMarkerStyle(20);
hist_TrialsPostEventSelection->SetMarkerSize(0.6);
hist_TrialsPostEventSelection->SetMarkerColor(6);
TH1F* histogram_TrialsPostEventSelection = (TH1F*)hist_TrialsPostEventSelection->Clone();
fOutputProductionCheck->Add(histogram_TrialsPostEventSelection);
TString name_TrialsPostCuts = "TrialsPostCuts";
TH1F* hist_TrialsPostCuts = new TH1F(name_TrialsPostCuts.Data(), "TrialsPostCuts; p_{T} [GeV/c]; Entries", 1, 0, 1);
hist_TrialsPostCuts->Sumw2();
hist_TrialsPostCuts->SetLineColor(6);
hist_TrialsPostCuts->SetMarkerStyle(20);
hist_TrialsPostCuts->SetMarkerSize(0.6);
hist_TrialsPostCuts->SetMarkerColor(6);
TH1F* histogram_TrialsPostCuts = (TH1F*)hist_TrialsPostCuts->Clone();
fOutputProductionCheck->Add(histogram_TrialsPostCuts);
Int_t nPtBins = fCuts->GetNPtBins();
// const Int_t nPtBinLimits = nPtBins + 1;
Float_t * PtBinLimits = fCuts->GetPtBinLimits();
TString name_DStar_per_bin_true_PreEventSelection ="DStar_per_bin_true_PreEventSelection";
TH1F* hist_DStar_per_bin_true_PreEventSelection = new TH1F(name_DStar_per_bin_true_PreEventSelection.Data(),"DStar_per_bin_true_PreEventSelection; Entries",nPtBins,PtBinLimits);
TH1F* histogram_DStar_per_bin_true_PreEventSelection = (TH1F*)hist_DStar_per_bin_true_PreEventSelection->Clone();
fOutputProductionCheck->Add(histogram_DStar_per_bin_true_PreEventSelection);
TString name_DStar_per_bin_true_PreEventSelection_weighted ="DStar_per_bin_true_PreEventSelection_weighted";
TH1F* hist_DStar_per_bin_true_PreEventSelection_weighted = new TH1F(name_DStar_per_bin_true_PreEventSelection_weighted.Data(),"DStar_per_bin_true_PreEventSelection_weighted; Entries",nPtBins,PtBinLimits);
TH1F* histogram_DStar_per_bin_true_PreEventSelection_weighted = (TH1F*)hist_DStar_per_bin_true_PreEventSelection_weighted->Clone();
fOutputProductionCheck->Add(histogram_DStar_per_bin_true_PreEventSelection_weighted);
TString name_DStar_per_bin_true_PostEventSelection ="DStar_per_bin_true_PostEventSelection";
TH1F* hist_DStar_per_bin_true_PostEventSelection = new TH1F(name_DStar_per_bin_true_PostEventSelection.Data(),"DStar_per_bin_true_PostEventSelection; Entries",nPtBins,PtBinLimits);
TH1F* histogram_DStar_per_bin_true_PostEventSelection = (TH1F*)hist_DStar_per_bin_true_PostEventSelection->Clone();
fOutputProductionCheck->Add(histogram_DStar_per_bin_true_PostEventSelection);
TString name_DStar_per_bin_true_PostEventSelection_weighted ="DStar_per_bin_true_PostEventSelection_weighted";
TH1F* hist_DStar_per_bin_true_PostEventSelection_weighted = new TH1F(name_DStar_per_bin_true_PostEventSelection_weighted.Data(),"DStar_per_bin_true_PostEventSelection_weighted; Entries",nPtBins,PtBinLimits);
TH1F* histogram_DStar_per_bin_true_PostEventSelection_weighted = (TH1F*)hist_DStar_per_bin_true_PostEventSelection_weighted->Clone();
fOutputProductionCheck->Add(histogram_DStar_per_bin_true_PostEventSelection_weighted);
TString name_DStar_per_bin_true_PostCuts ="DStar_per_bin_true_PostCuts";
TH1F* hist_DStar_per_bin_true_PostCuts = new TH1F(name_DStar_per_bin_true_PostCuts.Data(),"DStar_per_bin_true_PostCuts; Entries",nPtBins,PtBinLimits);
TH1F* histogram_DStar_per_bin_true_PostCuts = (TH1F*)hist_DStar_per_bin_true_PostCuts->Clone();
fOutputProductionCheck->Add(histogram_DStar_per_bin_true_PostCuts);
TString name_DStar_per_bin_true_PostCuts_weighted ="DStar_per_bin_true_PostCuts_weighted";
TH1F* hist_DStar_per_bin_true_PostCuts_weighted = new TH1F(name_DStar_per_bin_true_PostCuts_weighted.Data(),"DStar_per_bin_true_PostCuts_weighted; Entries",nPtBins,PtBinLimits);
TH1F* histogram_DStar_per_bin_true_PostCuts_weighted = (TH1F*)hist_DStar_per_bin_true_PostCuts_weighted->Clone();
fOutputProductionCheck->Add(histogram_DStar_per_bin_true_PostCuts_weighted);
TString name_DStar_per_bin_PostCuts ="DStar_per_bin_PostCuts";
TH1F* hist_DStar_per_bin_PostCuts = new TH1F(name_DStar_per_bin_PostCuts.Data(),"DStar_per_bin_PostCuts; Entries",nPtBins,PtBinLimits);
TH1F* histogram_DStar_per_bin_PostCuts = (TH1F*)hist_DStar_per_bin_PostCuts->Clone();
fOutputProductionCheck->Add(histogram_DStar_per_bin_PostCuts);
TString name_DStar_per_bin_PostCuts_weighted ="DStar_per_bin_PostCuts_weighted";
TH1F* hist_DStar_per_bin_PostCuts_weighted = new TH1F(name_DStar_per_bin_PostCuts_weighted.Data(),"DStar_per_bin_PostCuts_weighted; Entries",nPtBins,PtBinLimits);
TH1F* histogram_DStar_per_bin_PostCuts_weighted = (TH1F*)hist_DStar_per_bin_PostCuts_weighted->Clone();
fOutputProductionCheck->Add(histogram_DStar_per_bin_PostCuts_weighted);
TString name_fHistClusPosition ="fHistClusPosition";
TH3F* hist_fHistClusPosition = new TH3F(name_fHistClusPosition.Data(),";#it{x} (cm);#it{y} (cm);#it{z} (cm)", 50, -500, 500, 50, -500, 500, 50, -500, 500);
TH3F* histogram_fHistClusPosition = (TH3F*)hist_fHistClusPosition->Clone();
fOutputProductionCheck->Add(histogram_fHistClusPosition);
return;
}
//________________________________________________________________________
void AliAnalysisTaskSEDStarEMCALProductionCheck::FillSpectrum(AliAODRecoCascadeHF *part, Int_t isDStar, AliRDHFCutsDStartoKpipi *cuts, Int_t isSel, TList *listout, TH1F** histlist) {
//
/// Fill histos for D* spectrum
//
if (!isSel) return;
// D0 window
Double_t mPDGD0 = TDatabasePDG::Instance()->GetParticle(421)->Mass();
Double_t invmassD0 = part->InvMassD0();
Int_t ptbin = cuts->PtBin(part->Pt());
Double_t pt = part->Pt();
Double_t eta = part->Eta();
Double_t invmassDelta = part->DeltaInvMass();
Double_t invmassDstar = part->InvMassDstarKpipi();
TString fillthis = "";
Bool_t massInRange = kFALSE;
Double_t mPDGDstar = TDatabasePDG::Instance()->GetParticle(413)->Mass();
// delta M(Kpipi)-M(Kpi)
if (TMath::Abs(invmassDelta - (mPDGDstar - mPDGD0)) < fPeakWindow) massInRange = kTRUE;
if (fUseMCInfo) {
if (isDStar == 1) {
histlist[ptbin + 1 + ((fNPtBins + 2)*kDzSgn)]->Fill(invmassD0);
histlist[(fNPtBins + 2)*kDzSgn]->Fill(invmassD0);
histlist[ptbin + 1 + ((fNPtBins + 2)*kDstarSgn)]->Fill(invmassDstar);
histlist[(fNPtBins + 2)*kDstarSgn]->Fill(invmassDstar);
histlist[ptbin + 1 + ((fNPtBins + 2)*kDeltaSgn)]->Fill(invmassDelta);
histlist[(fNPtBins + 2)*kDeltaSgn]->Fill(invmassDelta);
if (massInRange) {
histlist[(fNPtBins + 2)*kptSgn]->Fill(pt);
histlist[(fNPtBins + 2)*ketaSgn]->Fill(eta);
}
}
else {//background
histlist[ptbin + 1 + ((fNPtBins + 2)*kDzBkg)]->Fill(invmassD0);
histlist[(fNPtBins + 2)*kDzBkg]->Fill(invmassD0);
histlist[ptbin + 1 + ((fNPtBins + 2)*kDstarBkg)]->Fill(invmassDstar);
histlist[(fNPtBins + 2)*kDstarBkg]->Fill(invmassDstar);
histlist[ptbin + 1 + ((fNPtBins + 2)*kDeltaBkg)]->Fill(invmassDelta);
histlist[(fNPtBins + 2)*kDeltaBkg]->Fill(invmassDelta);
if (massInRange) {
histlist[(fNPtBins + 2)*kptBkg]->Fill(pt);
histlist[(fNPtBins + 2)*ketaBkg]->Fill(eta);
}
}
}
//no MC info, just cut selection
histlist[ptbin + 1 + ((fNPtBins + 2)*kDzMass)]->Fill(invmassD0);
histlist[(fNPtBins + 2)*kDzMass]->Fill(invmassD0);
histlist[ptbin + 1 + ((fNPtBins + 2)*kDstarMass)]->Fill(invmassDstar);
histlist[(fNPtBins + 2)*kDstarMass]->Fill(invmassDstar);
histlist[ptbin + 1 + ((fNPtBins + 2)*kDeltaMass)]->Fill(invmassDelta);
histlist[(fNPtBins + 2)*kDeltaMass]->Fill(invmassDelta);
if (massInRange) {
histlist[(fNPtBins + 2)*kptMass]->Fill(pt);
histlist[(fNPtBins + 2)*ketaMass]->Fill(eta);
}
return;
}
//______________________________ side band background for D*___________________________________
void AliAnalysisTaskSEDStarEMCALProductionCheck::SideBandBackground(AliAODRecoCascadeHF *part, AliRDHFCutsDStartoKpipi *cuts, Int_t isSel, TList *listout, TH1F** histlist) {
/// D* side band background method. Two side bands, in M(Kpi) are taken at ~6 sigmas
/// (expected detector resolution) on the left and right frm the D0 mass. Each band
/// has a width of ~5 sigmas. Two band needed for opening angle considerations
if (!isSel) return;
Int_t ptbin = cuts->PtBin(part->Pt());
// select the side bands intervall
Double_t invmassD0 = part->InvMassD0();
if (TMath::Abs(invmassD0 - 1.865) > 4 * fD0Window && TMath::Abs(invmassD0 - 1.865) < 8 * fD0Window) {
// for pt and eta
Double_t invmassDelta = part->DeltaInvMass();
histlist[ptbin + 1 + ((fNPtBins + 2)*kSideBandMass)]->Fill(invmassDelta);
histlist[(fNPtBins + 2)*kSideBandMass]->Fill(invmassDelta);
}
}
//________________________________________________________________________________________________________________
void AliAnalysisTaskSEDStarEMCALProductionCheck::WrongSignForDStar(AliAODRecoCascadeHF *part, AliRDHFCutsDStartoKpipi *cuts, TList *listout) {
//
/// assign the wrong charge to the soft pion to create background
//
Int_t ptbin = cuts->PtBin(part->Pt());
Double_t mPDGD0 = TDatabasePDG::Instance()->GetParticle(421)->Mass();
Double_t invmassD0 = part->InvMassD0();
if (TMath::Abs(invmassD0 - mPDGD0) > fD0Window) return;
AliAODRecoDecayHF2Prong* theD0particle = (AliAODRecoDecayHF2Prong*)part->Get2Prong();
Int_t okDzWrongSign;
Double_t wrongMassD0 = 0.;
Int_t isSelected = cuts->IsSelected(part, AliRDHFCuts::kCandidate); //selected
if (!isSelected) {
return;
}
okDzWrongSign = 1;
//if is D*+ than assume D0bar
if (part->Charge() > 0 && (isSelected == 1)) {
okDzWrongSign = 0;
}
// assign the wrong mass in case the cuts return both D0 and D0bar
if (part->Charge() > 0 && (isSelected == 3)) {
okDzWrongSign = 0;
}
//wrong D0 inv mass
if (okDzWrongSign != 0) {
wrongMassD0 = theD0particle->InvMassD0();
} else if (okDzWrongSign == 0) {
wrongMassD0 = theD0particle->InvMassD0bar();
}
if (TMath::Abs(wrongMassD0 - 1.865) < fD0Window) {
// wrong D* inv mass
Double_t e[3];
if (part->Charge() > 0) {
e[0] = theD0particle->EProng(0, 321);
e[1] = theD0particle->EProng(1, 211);
} else {
e[0] = theD0particle->EProng(0, 211);
e[1] = theD0particle->EProng(1, 321);
}
e[2] = part->EProng(0, 211);
Double_t esum = e[0] + e[1] + e[2];
Double_t pds = part->P();
Double_t wrongMassDstar = TMath::Sqrt(esum * esum - pds * pds);
TString fillthis = "";
fillthis = "histWrongSignMass_";
fillthis += ptbin;
((TH1F*)(listout->FindObject(fillthis)))->Fill(wrongMassDstar - wrongMassD0);
fillthis = "histWrongSignMass";
((TH1F*)(listout->FindObject(fillthis)))->Fill(wrongMassDstar - wrongMassD0);
}
}
//-------------------------------------------------------------------------------
Int_t AliAnalysisTaskSEDStarEMCALProductionCheck::CheckOrigin(TClonesArray* arrayMC, const AliAODMCParticle *mcPartCandidate) const {
//
// checking whether the mother of the particles come from a charm or a bottom quark
//
Int_t pdgGranma = 0;
Int_t mother = 0;
mother = mcPartCandidate->GetMother();
Int_t istep = 0;
Int_t abspdgGranma = 0;
Bool_t isFromB = kFALSE;
while (mother > 0 ) {
istep++;
AliAODMCParticle* mcGranma = dynamic_cast<AliAODMCParticle*>(arrayMC->At(mother));
if (mcGranma) {
pdgGranma = mcGranma->GetPdgCode();
abspdgGranma = TMath::Abs(pdgGranma);
if ((abspdgGranma > 500 && abspdgGranma < 600) || (abspdgGranma > 5000 && abspdgGranma < 6000)) {
isFromB = kTRUE;
}
mother = mcGranma->GetMother();
} else {
AliError("Failed casting the mother particle!");
break;
}
}
if (isFromB) return 5;
else return 4;
}
//-------------------------------------------------------------------------------------
Float_t AliAnalysisTaskSEDStarEMCALProductionCheck::GetTrueImpactParameterD0(const AliAODMCHeader *mcHeader, TClonesArray* arrayMC, const AliAODMCParticle *partDp) const {
/// true impact parameter calculation
Double_t vtxTrue[3];
mcHeader->GetVertex(vtxTrue);
Double_t origD[3];
partDp->XvYvZv(origD);
Short_t charge = partDp->Charge();
Double_t pXdauTrue[3], pYdauTrue[3], pZdauTrue[3];
Int_t labelFirstDau = partDp->GetDaughterLabel(0);
Int_t nDau = partDp->GetNDaughters();
Int_t theDau = 0;
if (nDau == 2) {
for (Int_t iDau = 0; iDau < 2; iDau++) {
Int_t ind = labelFirstDau + iDau;
AliAODMCParticle* part = dynamic_cast<AliAODMCParticle*>(arrayMC->At(ind));
if (!part) {
AliError("Daughter particle not found in MC array");
return 99999.;
}
Int_t pdgCode = TMath::Abs(part->GetPdgCode());
if (pdgCode == 211 || pdgCode == 321) {
pXdauTrue[theDau] = part->Px();
pYdauTrue[theDau] = part->Py();
pZdauTrue[theDau] = part->Pz();
++theDau;
}
}
}
if (theDau != 2) {
AliError("Wrong number of decay prongs");
return 99999.;
}
Double_t d0dummy[3] = {0., 0., 0.};
AliAODRecoDecayHF aodD0MC(vtxTrue, origD, 3, charge, pXdauTrue, pYdauTrue, pZdauTrue, d0dummy);
return aodD0MC.ImpParXY();
}
//______________________________________________________-
void AliAnalysisTaskSEDStarEMCALProductionCheck::CreateImpactParameterHistos() {
/// Histos for impact paramter study
Int_t nbins[3] = {400, 200, fNImpParBins};
Double_t xmin[3] = {1.75, 0., fLowerImpPar};
Double_t xmax[3] = {1.98, 20., fHigherImpPar};
fHistMassPtImpParTCDs[0] = new THnSparseF("hMassPtImpParAll",
"Mass vs. pt vs.imppar - All",
3, nbins, xmin, xmax);
fHistMassPtImpParTCDs[1] = new THnSparseF("hMassPtImpParPrompt",
"Mass vs. pt vs.imppar - promptD",
3, nbins, xmin, xmax);
fHistMassPtImpParTCDs[2] = new THnSparseF("hMassPtImpParBfeed",
"Mass vs. pt vs.imppar - DfromB",
3, nbins, xmin, xmax);
fHistMassPtImpParTCDs[3] = new THnSparseF("hMassPtImpParTrueBfeed",
"Mass vs. pt vs.true imppar -DfromB",
3, nbins, xmin, xmax);
fHistMassPtImpParTCDs[4] = new THnSparseF("hMassPtImpParBkg",
"Mass vs. pt vs.imppar - backgr.",
3, nbins, xmin, xmax);
for (Int_t i = 0; i < 5; i++) {
fOutput->Add(fHistMassPtImpParTCDs[i]);
}
}
| 41.109192 | 259 | 0.683806 | maroozm |
ff65e6f12c981871c143635bc4f2658d4463410b | 1,338 | cpp | C++ | src/kindyn/src/controller/cardsflow_command_interface.cpp | NexusReflex/VRpuppet | 0b6a14e13951ceaf849b09da1f8dd797a4a1125d | [
"BSD-3-Clause"
] | 3 | 2018-11-12T09:58:35.000Z | 2019-03-31T02:52:54.000Z | src/kindyn/src/controller/cardsflow_command_interface.cpp | NexusReflex/VRpuppet | 0b6a14e13951ceaf849b09da1f8dd797a4a1125d | [
"BSD-3-Clause"
] | 5 | 2018-12-02T14:31:10.000Z | 2021-05-06T12:10:06.000Z | src/kindyn/src/controller/cardsflow_command_interface.cpp | NexusReflex/VRpuppet | 0b6a14e13951ceaf849b09da1f8dd797a4a1125d | [
"BSD-3-Clause"
] | 3 | 2018-12-02T09:55:49.000Z | 2021-09-08T11:54:30.000Z | #include "kindyn/controller/cardsflow_command_interface.hpp"
namespace hardware_interface
{
CardsflowHandle::CardsflowHandle() : CardsflowStateHandle(){}
/**
* @param js This joint's state handle
* @param cmd A pointer to the storage for this joint's output command
*/
CardsflowHandle::CardsflowHandle(const CardsflowStateHandle& js, double* joint_position_cmd,
double* joint_velocity_cmd, double* joint_torque_cmd, VectorXd *motor_cmd)
: CardsflowStateHandle(js), joint_position_cmd_(joint_position_cmd), joint_velocity_cmd_(joint_velocity_cmd),
joint_torque_cmd_(joint_torque_cmd), motor_cmd_(motor_cmd)
{
}
void CardsflowHandle::setMotorCommand(VectorXd command) {*motor_cmd_ = command;}
double CardsflowHandle::getJointPositionCommand() const {return *joint_position_cmd_;}
double CardsflowHandle::getJointVelocityCommand() const {return *joint_velocity_cmd_;}
double CardsflowHandle::getJointTorqueCommand() const {return *joint_torque_cmd_;}
void CardsflowHandle::setJointPositionCommand(double cmd){*joint_position_cmd_ = cmd;}
void CardsflowHandle::setJointVelocityCommand(double cmd){*joint_velocity_cmd_ = cmd;}
void CardsflowHandle::setJointTorqueCommand(double cmd){*joint_torque_cmd_ = cmd;}
}
| 47.785714 | 121 | 0.749626 | NexusReflex |
ff67462b7104a38bb840c5d5c2e40b0760dd4d99 | 3,046 | cc | C++ | mindspore/lite/tools/converter/adapter/dpico/common/format_utils.cc | httpsgithu/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | 1 | 2022-02-23T09:13:43.000Z | 2022-02-23T09:13:43.000Z | mindspore/lite/tools/converter/adapter/dpico/common/format_utils.cc | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/tools/converter/adapter/dpico/common/format_utils.cc | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* 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 "common/format_utils.h"
#include <set>
#include <string>
#include "ops/tuple_get_item.h"
#include "ops/depend.h"
#include "ops/make_tuple.h"
#include "ops/return.h"
#include "ops/batch_norm.h"
#include "ops/batch_to_space.h"
#include "ops/bias_add.h"
#include "ops/depth_to_space.h"
#include "ops/fused_batch_norm.h"
#include "ops/fusion/avg_pool_fusion.h"
#include "ops/fusion/conv2d_fusion.h"
#include "ops/fusion/conv2d_transpose_fusion.h"
#include "ops/fusion/max_pool_fusion.h"
#include "ops/fusion/prelu_fusion.h"
#include "ops/fusion/topk_fusion.h"
#include "ops/instance_norm.h"
#include "ops/lrn.h"
#include "ops/resize.h"
#include "ops/roi_pooling.h"
#include "ops/space_to_batch.h"
#include "ops/space_to_batch_nd.h"
#include "ops/space_to_depth.h"
#include "common/anf_util.h"
namespace mindspore {
namespace dpico {
namespace {
const std::set<std::string> kAssignedFormatOpSet = {
mindspore::ops::kNameAvgPoolFusion, mindspore::ops::kNameBatchNorm,
mindspore::ops::kNameBatchToSpace, mindspore::ops::kNameBiasAdd,
mindspore::ops::kNameConv2DFusion, mindspore::ops::kNameConv2dTransposeFusion,
mindspore::ops::kNameDepthToSpace, mindspore::ops::kNameFusedBatchNorm,
mindspore::ops::kNameInstanceNorm, mindspore::ops::kNameLRN,
mindspore::ops::kNameMaxPoolFusion, mindspore::ops::kNamePReLUFusion,
mindspore::ops::kNameResize, mindspore::ops::kNameROIPooling,
mindspore::ops::kNameSpaceToBatch, mindspore::ops::kNameSpaceToBatchND,
mindspore::ops::kNameSpaceToDepth, mindspore::ops::kNameTopKFusion};
} // namespace
const std::set<std::string> &GetAssignedFormatOpSet() { return kAssignedFormatOpSet; }
bool IsSpecialType(const api::CNodePtr &cnode) {
return CheckPrimitiveType(cnode, api::MakeShared<ops::TupleGetItem>()) ||
CheckPrimitiveType(cnode, api::MakeShared<ops::Depend>()) ||
CheckPrimitiveType(cnode, api::MakeShared<ops::MakeTuple>()) ||
CheckPrimitiveType(cnode, api::MakeShared<ops::Return>());
}
std::string FormatEnumToString(mindspore::Format format) {
static std::vector<std::string> names = {
"NCHW", "NHWC", "NHWC4", "HWKC", "HWCK", "KCHW", "CKHW", "KHWC", "CHWK",
"HW", "HW4", "NC", "NC4", "NC4HW4", "NUM_OF_FORMAT", "NCDHW", "NWC", "NCW",
};
if (format < mindspore::NCHW || format > mindspore::NCW) {
return "";
}
return names[format];
}
} // namespace dpico
} // namespace mindspore
| 38.075 | 88 | 0.726855 | httpsgithu |
ff680e13711b50a084ee738f5d9da55346de63cb | 3,320 | cc | C++ | ishxiao/1462/13648790_RE.cc | ishx/poj | b4e5498117d7c8fc3d96eca2fa7f71f2dfa13c2d | [
"MIT"
] | null | null | null | ishxiao/1462/13648790_RE.cc | ishx/poj | b4e5498117d7c8fc3d96eca2fa7f71f2dfa13c2d | [
"MIT"
] | null | null | null | ishxiao/1462/13648790_RE.cc | ishx/poj | b4e5498117d7c8fc3d96eca2fa7f71f2dfa13c2d | [
"MIT"
] | null | null | null | //1462
#include <iostream>
#include <fstream>
#include <cmath>
#include <cctype>
#include <stdlib.h>
#include <string.h>
#define zero 1e-8
#define MAXN 110
using namespace std;
double t[MAXN];
char code[MAXN][MAXN][MAXN], name[100][100], del[300], *tok;
int m[MAXN], N, n;
double state[MAXN][MAXN], A[MAXN][MAXN + 1], r;
void Gauss()
{
int i, j, k;
for (j = 1; j <= n; j++)
{
for (i = j; i <= n; i++)
if (!(fabs(A[i][j]) < zero))
break;
if (i != j)
for (k = 1; k <= n + 1; k++)
swap(A[i][k], A[j][k]);
r = A[j][j];
for (k = j; k <= n + 1; k++)
A[j][k] /= r;
for (i = j + 1; i <= n; i++)
{
r = A[i][j];
for (k = j; k <= n + 1; k++)
A[i][k] -= r * A[j][k];
}
}
for (j = n; j >= 1; j--)
{
for (i = j - 1; i >= 1; i--)
{
r = A[i][j];
for (k = 1; k <= n + 1; k++)
A[i][k] -= A[j][k] * r;
}
}
}
void IntoA(int x)
{
int i;
for (i = 1; i <= n; i++)
A[x][i] = state[x][i];
A[x][n + 1] = - state[x][0];
A[x][x]--;
}
bool calc(int x)
{
double case1, case2;
int i, j, k;
char s[100];
n = m[x];
for (i = 0; i <= n; i++)
state[n][i] = 0;
IntoA(n);
for (k = n - 1; k >= 1; k--)
{
for (i = 0; i <= n; i++)
state[k][i] = state[k + 1][i];
if (strstr(code[x][k], "NOP;") != 0)
state[k][0]++;
else
{
strcpy(s, code[x][k]);
tok = strtok(s, del);
tok = strtok(NULL, del);
tok = strtok(NULL, del);
case1 = atof(tok);
case2 = 1 - case1;
if (strstr(code[x][k], ">") != 0)
swap(case1, case2);
tok = strtok(NULL, del);
tok = strtok(NULL, del);
if (strstr(code[x][k], "PROC") != 0)
{
for (i = 1; i <= N; i++)
if (strcmp(name[i], tok) == 0)
break;
if (fabs(t[i]) < zero)
return false;
state[k][0] += case1 * t[i];
state[k][0]++;
}
else
{
j = atoi(tok);
for (i = 0; i <= n; i++)
state[k][i] *= case2;
if (j > k)
for (i = 0; i <= n; i++)
state[k][i] += case1 * state[j][i];
else
state[k][j] += case1;
state[k][0]++;
}
}
IntoA(k);
}
return true;
}
int main()
{
int i, j, ndel;
char s[100];
ndel = 0;
for (i = 255; i >= 0; i--)
if (! (isalpha(char(i)) || isdigit(char(i)) || char(i) == '.'))
del[++ndel - 1] = char(i);
del[ndel] = '\0';
ifstream cin("random.dat", ios::in);
cin.getline(s, 200, '\n');
N = 0;
while (1)
{
cin.getline(s, 100, '\n');
if (strcmp(s, "PROG_END") == 0)
break;
N++;
m[N] = 0;
tok = strtok(s, del);
tok = strtok(NULL, del);
strcpy(name[N], tok);
while (1)
{
cin.getline(s, 100, '\n');
++m[N];
strcpy(code[N][m[N]], s);
if (strcmp(s, "END;") == 0)
break;
}
}
for (i = 1; i <= N; i++)
t[i] = 0;
i = N;
while (i > 0)
{
for (j = 1; j <= N; j++)
if (fabs(t[j]) < zero)
if (calc(j))
{
i--;
Gauss();
t[j] = A[1][n + 1];
}
}
while (1)
{
cin.getline(s, 100, '\n');
if (strcmp(s, "REQUEST_END") == 0)
break;
for (i = 1; i <= N; i++)
if (strcmp(s, name[i]) == 0)
{
printf("%.3Lf\n", t[i]);
break;
}
}
cin.close();
//system("pause");
return 0;
} | 17.659574 | 65 | 0.403313 | ishx |
ff686f28f5f10d347265bafa78b8228312d0974d | 151 | cpp | C++ | test.cpp | yusukeOteki/pxt-test1 | a5bb45d48c8c4a8096579d39c2134b953a773846 | [
"MIT"
] | null | null | null | test.cpp | yusukeOteki/pxt-test1 | a5bb45d48c8c4a8096579d39c2134b953a773846 | [
"MIT"
] | null | null | null | test.cpp | yusukeOteki/pxt-test1 | a5bb45d48c8c4a8096579d39c2134b953a773846 | [
"MIT"
] | null | null | null | #include "pxt.h"
using namespace pxt;
namespace test {
//%
void dammy(int32_t x, int32_t y){
uBit.display.image.setPixelValue(0, 0, 255);
}
} | 11.615385 | 46 | 0.662252 | yusukeOteki |
ff6ace1c0415f19b1777f3b561a5501b5f51b9f8 | 2,204 | cpp | C++ | 00-Keypoint_in_WangDao/Chapter_02-List/01-LinkList/00-Basic_LinkList/01-LinkList_Examples/02-LinkList_Seprate_by_Char_Type.cpp | ysl970629/kaoyan_data_structure | d0a469bf0e9e7040de21eca38dc19961aa7e9a53 | [
"MIT"
] | 2 | 2021-03-24T03:29:16.000Z | 2022-03-29T16:34:30.000Z | 00-Keypoint_in_WangDao/Chapter_02-List/01-LinkList/00-Basic_LinkList/01-LinkList_Examples/02-LinkList_Seprate_by_Char_Type.cpp | ysl2/kaoyan-data-structure | d0a469bf0e9e7040de21eca38dc19961aa7e9a53 | [
"MIT"
] | null | null | null | 00-Keypoint_in_WangDao/Chapter_02-List/01-LinkList/00-Basic_LinkList/01-LinkList_Examples/02-LinkList_Seprate_by_Char_Type.cpp | ysl2/kaoyan-data-structure | d0a469bf0e9e7040de21eca38dc19961aa7e9a53 | [
"MIT"
] | null | null | null | #include <cstdlib>
#include <iostream>
typedef int ElemType;
typedef struct LinkNode {
ElemType data;
struct LinkNode *next;
} LinkNode, *LinkList;
void outPut(LinkList L) {
LinkNode *p = L->next;
while (p != NULL) {
std::cout << p->data << " ";
p = p->next;
}
std::cout << std::endl;
}
void rearInsert(LinkList &L, ElemType x) {
LinkNode *s = new LinkNode;
s->data = x;
L->next = s;
L = s;
}
void rearInsertCreate(LinkList &L, ElemType arr[], int length) {
L = new LinkNode;
LinkNode *p = L;
for (int i = 0; i < length; i++) {
rearInsert(p, arr[i]);
}
p->next = NULL;
}
// 题目要求根据大写、小写和数字分类,这样我还得重新定义char类型的链表,太麻烦了
// 所以我按照大写、小写、数字的ASCII码范围来分类,这样都能保证是int型
// 数字:48 ~ 57,放在A里
// 大写:65 ~ 90,放在B里
// 小写:97 ~ 122,放在C里
void SeprateByCharType(LinkList &A, LinkList &B, LinkList &C) {
LinkNode *pre = A;
LinkNode *p = A->next;
B = new LinkNode;
LinkNode *q = B;
C = new LinkNode;
LinkNode *r = C;
while (p != NULL) {
// 放在A里
if (p->data >= 48 && p->data <= 57) {
p = p->next;
pre = pre->next;
continue; //终止当前这次循环,直接进入下一次循环
}
// 放在B里
if (p->data >= 65 && p->data <= 90) {
rearInsert(q, p->data);
// 在A中删除p所指的位置,然后把p定位到下一个位置
pre->next = p->next;
delete p;
p = pre->next;
continue;
}
// 放在C里
if (p->data >= 97 && p->data <= 122) {
rearInsert(r, p->data);
pre->next = p->next;
delete p;
p = pre->next;
// 这里就不用加continue了,因为下面已经没有语句了,肯定会执行下一次循环
}
}
q->next = NULL;
r->next = NULL;
}
int main() {
ElemType arr[] = {49, 66, 98, 50, 67, 99, 51, 68, 100, 52, 69, 101};
int length = sizeof(arr) / sizeof(int);
LinkList L1 = NULL;
LinkList L2 = NULL;
LinkList L3 = NULL;
rearInsertCreate(L1, arr, length);
outPut(L1);
SeprateByCharType(L1, L2, L3);
outPut(L1);
outPut(L2);
outPut(L3);
return 0;
}
// 输出结果:
// 49 66 98 50 67 99 51 68 100 52 69 101
// 49 50 51 52
// 66 67 68 69
// 98 99 100 101
| 22.04 | 72 | 0.511343 | ysl970629 |
ff6ae562d9a9ad053d94d30afdd64d831b21ab02 | 197 | cpp | C++ | engine/src/platform/android/pixelboost/network/networkHelpers.cpp | pixelballoon/pixelboost | 085873310050ce62493df61142b7d4393795bdc2 | [
"MIT"
] | 6 | 2015-04-21T11:30:52.000Z | 2020-04-29T00:10:04.000Z | engine/src/platform/android/pixelboost/network/networkHelpers.cpp | pixelballoon/pixelboost | 085873310050ce62493df61142b7d4393795bdc2 | [
"MIT"
] | null | null | null | engine/src/platform/android/pixelboost/network/networkHelpers.cpp | pixelballoon/pixelboost | 085873310050ce62493df61142b7d4393795bdc2 | [
"MIT"
] | null | null | null | #ifdef PIXELBOOST_PLATFORM_ANDROID
#include "pixelboost/network/networkHelpers.h"
namespace pb
{
namespace NetworkHelpers
{
std::string GetWifiAddress()
{
return "";
}
}
}
#endif | 9.85 | 46 | 0.705584 | pixelballoon |
ff70a2c6cf2d50a878c75ea640c5edd064cebb67 | 19,215 | cpp | C++ | framework/decode/compression_converter.cpp | xooiamd/gfxreconstruct | 18a13b510baa0d9a84b1219f62149fe1abc8101e | [
"Apache-2.0"
] | null | null | null | framework/decode/compression_converter.cpp | xooiamd/gfxreconstruct | 18a13b510baa0d9a84b1219f62149fe1abc8101e | [
"Apache-2.0"
] | null | null | null | framework/decode/compression_converter.cpp | xooiamd/gfxreconstruct | 18a13b510baa0d9a84b1219f62149fe1abc8101e | [
"Apache-2.0"
] | null | null | null | /*
** Copyright (c) 2018-2019 Valve Corporation
** Copyright (c) 2018-2019 LunarG, Inc.
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#include "decode/compression_converter.h"
#include "format/format_util.h"
#include "util/logging.h"
#include <cassert>
GFXRECON_BEGIN_NAMESPACE(gfxrecon)
GFXRECON_BEGIN_NAMESPACE(decode)
CompressionConverter::CompressionConverter() : bytes_written_(0), compressor_(nullptr), decompressing_(false) {}
CompressionConverter::~CompressionConverter()
{
Destroy();
}
bool CompressionConverter::Initialize(std::string filename,
const format::FileHeader& file_header,
const std::vector<format::FileOptionPair>& option_list,
format::CompressionType target_compression_type)
{
bool success = false;
// Modify compression setting and write file header to a new file.
filename_ = filename;
file_stream_ = std::make_unique<util::FileOutputStream>(filename_);
if (format::CompressionType::kNone == target_compression_type)
{
decompressing_ = true;
compressor_ = nullptr;
}
else
{
decompressing_ = false;
compressor_ = format::CreateCompressor(target_compression_type);
if (nullptr == compressor_)
{
GFXRECON_LOG_WARNING("Failed to initialized file compression module (type = %u)", target_compression_type);
return false;
}
}
std::vector<format::FileOptionPair> new_option_list = option_list;
for (auto& option : new_option_list)
{
switch (option.key)
{
case format::FileOption::kCompressionType:
// Change the file option to the new compression type
option.value = static_cast<uint32_t>(target_compression_type);
break;
default:
GFXRECON_LOG_WARNING("Ignoring unrecognized file header option %u", option.key);
break;
}
}
if (file_stream_->IsValid())
{
bytes_written_ = 0;
bytes_written_ += file_stream_->Write(&file_header, sizeof(file_header));
bytes_written_ +=
file_stream_->Write(new_option_list.data(), new_option_list.size() * sizeof(format::FileOptionPair));
success = true;
}
else
{
GFXRECON_LOG_ERROR("Failed to open file %s", filename_.c_str());
}
return success;
}
void CompressionConverter::Destroy()
{
if (nullptr != compressor_)
{
delete compressor_;
compressor_ = nullptr;
}
}
void CompressionConverter::DecodeFunctionCall(format::ApiCallId call_id,
const ApiCallInfo& call_info,
const uint8_t* buffer,
size_t buffer_size)
{
bool write_uncompressed = decompressing_;
if (!decompressing_)
{
// Compress the buffer with the new compression format and write to the new file.
format::CompressedFunctionCallHeader compressed_func_call_header = {};
size_t packet_size = 0;
size_t compressed_size = compressor_->Compress(buffer_size, buffer, &compressed_buffer_);
if (0 < compressed_size && compressed_size < buffer_size)
{
compressed_func_call_header.block_header.type = format::BlockType::kCompressedFunctionCallBlock;
compressed_func_call_header.api_call_id = call_id;
compressed_func_call_header.thread_id = call_info.thread_id;
compressed_func_call_header.uncompressed_size = buffer_size;
packet_size += sizeof(compressed_func_call_header.api_call_id) +
sizeof(compressed_func_call_header.thread_id) +
sizeof(compressed_func_call_header.uncompressed_size) + compressed_size;
compressed_func_call_header.block_header.size = packet_size;
// Write compressed function call block header.
bytes_written_ += file_stream_->Write(&compressed_func_call_header, sizeof(compressed_func_call_header));
// Write parameter data.
bytes_written_ += file_stream_->Write(compressed_buffer_.data(), compressed_size);
}
else
{
// It's bigger compressed than uncompressed, so only write the uncompressed data.
write_uncompressed = true;
}
}
if (write_uncompressed)
{
// Buffer is currently not compressed; it was decompressed prior to this call.
format::FunctionCallHeader func_call_header = {};
size_t packet_size = 0;
func_call_header.block_header.type = format::BlockType::kFunctionCallBlock;
func_call_header.api_call_id = call_id;
func_call_header.thread_id = call_info.thread_id;
packet_size += sizeof(func_call_header.api_call_id) + sizeof(func_call_header.thread_id) + buffer_size;
func_call_header.block_header.size = packet_size;
// Write compressed function call block header.
bytes_written_ += file_stream_->Write(&func_call_header, sizeof(func_call_header));
// Write parameter data.
bytes_written_ += file_stream_->Write(buffer, buffer_size);
}
}
void CompressionConverter::DispatchStateBeginMarker(uint64_t frame_number)
{
format::Marker marker;
marker.header.size = sizeof(marker.marker_type) + sizeof(marker.frame_number);
marker.header.type = format::kStateMarkerBlock;
marker.marker_type = format::kBeginMarker;
marker.frame_number = frame_number;
bytes_written_ += file_stream_->Write(&marker, sizeof(marker));
}
void CompressionConverter::DispatchStateEndMarker(uint64_t frame_number)
{
format::Marker marker;
marker.header.size = sizeof(marker.marker_type) + sizeof(marker.frame_number);
marker.header.type = format::kStateMarkerBlock;
marker.marker_type = format::kEndMarker;
marker.frame_number = frame_number;
bytes_written_ += file_stream_->Write(&marker, sizeof(marker));
}
void CompressionConverter::DispatchDisplayMessageCommand(format::ThreadId thread_id, const std::string& message)
{
size_t message_length = message.size();
format::DisplayMessageCommandHeader message_cmd;
message_cmd.meta_header.block_header.type = format::BlockType::kMetaDataBlock;
message_cmd.meta_header.block_header.size =
sizeof(message_cmd.meta_header.meta_data_type) + sizeof(message_cmd.thread_id) + message_length;
message_cmd.meta_header.meta_data_type = format::MetaDataType::kDisplayMessageCommand;
message_cmd.thread_id = thread_id;
bytes_written_ += file_stream_->Write(&message_cmd, sizeof(message_cmd));
bytes_written_ += file_stream_->Write(message.c_str(), message_length);
}
void CompressionConverter::DispatchFillMemoryCommand(
format::ThreadId thread_id, uint64_t memory_id, uint64_t offset, uint64_t size, const uint8_t* data)
{
// NOTE: Don't apply the offset to the write_address here since it's coming from the file_processor
// at the start of the stream. We only need to record the writing offset for future info.
format::FillMemoryCommandHeader fill_cmd;
const uint8_t* write_address = data;
GFXRECON_CHECK_CONVERSION_DATA_LOSS(size_t, size);
size_t write_size = static_cast<size_t>(size);
fill_cmd.meta_header.block_header.type = format::BlockType::kMetaDataBlock;
fill_cmd.meta_header.meta_data_type = format::MetaDataType::kFillMemoryCommand;
fill_cmd.thread_id = thread_id;
fill_cmd.memory_id = memory_id;
fill_cmd.memory_offset = offset;
fill_cmd.memory_size = write_size;
if ((!decompressing_) && (compressor_ != nullptr))
{
size_t compressed_size = compressor_->Compress(write_size, write_address, &compressed_buffer_);
if ((compressed_size > 0) && (compressed_size < write_size))
{
// We don't have a special header for compressed fill commands because the header always includes
// the uncompressed size, so we just change the type to indicate the data is compressed.
fill_cmd.meta_header.block_header.type = format::BlockType::kCompressedMetaDataBlock;
write_address = compressed_buffer_.data();
write_size = compressed_size;
}
}
// Calculate size of packet with compressed or uncompressed data size.
fill_cmd.meta_header.block_header.size = sizeof(fill_cmd.meta_header.meta_data_type) + sizeof(fill_cmd.thread_id) +
sizeof(fill_cmd.memory_id) + sizeof(fill_cmd.memory_offset) +
sizeof(fill_cmd.memory_size) + write_size;
bytes_written_ += file_stream_->Write(&fill_cmd, sizeof(fill_cmd));
bytes_written_ += file_stream_->Write(write_address, write_size);
}
void CompressionConverter::DispatchResizeWindowCommand(format::ThreadId thread_id,
format::HandleId surface_id,
uint32_t width,
uint32_t height)
{
format::ResizeWindowCommand resize_cmd;
resize_cmd.meta_header.block_header.type = format::BlockType::kMetaDataBlock;
resize_cmd.meta_header.block_header.size = sizeof(resize_cmd.meta_header.meta_data_type) +
sizeof(resize_cmd.thread_id) + sizeof(resize_cmd.surface_id) +
sizeof(resize_cmd.width) + sizeof(resize_cmd.height);
resize_cmd.meta_header.meta_data_type = format::MetaDataType::kResizeWindowCommand;
resize_cmd.thread_id = thread_id;
resize_cmd.surface_id = surface_id;
resize_cmd.width = width;
resize_cmd.height = height;
bytes_written_ += file_stream_->Write(&resize_cmd, sizeof(resize_cmd));
}
void CompressionConverter::DispatchSetSwapchainImageStateCommand(
format::ThreadId thread_id,
format::HandleId device_id,
format::HandleId swapchain_id,
uint32_t last_presented_image,
const std::vector<format::SwapchainImageStateInfo>& image_state)
{
format::SetSwapchainImageStateCommandHeader header;
size_t image_count = image_state.size();
size_t image_state_size = 0;
// Initialize standard block header.
header.meta_header.block_header.size = sizeof(header.meta_header.meta_data_type) + sizeof(header.thread_id) +
sizeof(header.device_id) + sizeof(header.swapchain_id) +
sizeof(header.last_presented_image) + sizeof(header.image_info_count);
header.meta_header.block_header.type = format::kMetaDataBlock;
if (image_count > 0)
{
image_state_size = image_count * sizeof(image_state[0]);
header.meta_header.block_header.size += image_state_size;
}
// Initialize block data for set-swapchain-image-state meta-data command.
header.meta_header.meta_data_type = format::kSetSwapchainImageStateCommand;
header.thread_id = thread_id;
header.device_id = device_id;
header.swapchain_id = swapchain_id;
header.last_presented_image = last_presented_image;
header.image_info_count = static_cast<uint32_t>(image_count);
bytes_written_ += file_stream_->Write(&header, sizeof(header));
bytes_written_ += file_stream_->Write(image_state.data(), image_state_size);
}
void CompressionConverter::DispatchBeginResourceInitCommand(format::ThreadId thread_id,
format::HandleId device_id,
uint64_t max_resource_size,
uint64_t max_copy_size)
{
format::BeginResourceInitCommand begin_cmd;
begin_cmd.meta_header.block_header.size = sizeof(begin_cmd) - sizeof(begin_cmd.meta_header.block_header);
begin_cmd.meta_header.block_header.type = format::kMetaDataBlock;
begin_cmd.meta_header.meta_data_type = format::kBeginResourceInitCommand;
begin_cmd.thread_id = thread_id;
begin_cmd.device_id = device_id;
begin_cmd.max_resource_size = max_resource_size;
begin_cmd.max_copy_size = max_copy_size;
bytes_written_ += file_stream_->Write(&begin_cmd, sizeof(begin_cmd));
}
void CompressionConverter::DispatchEndResourceInitCommand(format::ThreadId thread_id, format::HandleId device_id)
{
format::EndResourceInitCommand end_cmd;
end_cmd.meta_header.block_header.size = sizeof(end_cmd) - sizeof(end_cmd.meta_header.block_header);
end_cmd.meta_header.block_header.type = format::kMetaDataBlock;
end_cmd.meta_header.meta_data_type = format::kEndResourceInitCommand;
end_cmd.thread_id = thread_id;
end_cmd.device_id = device_id;
bytes_written_ += file_stream_->Write(&end_cmd, sizeof(end_cmd));
}
void CompressionConverter::DispatchInitBufferCommand(format::ThreadId thread_id,
format::HandleId device_id,
format::HandleId buffer_id,
uint64_t data_size,
const uint8_t* data)
{
const uint8_t* write_address = data;
GFXRECON_CHECK_CONVERSION_DATA_LOSS(size_t, data_size);
size_t write_size = static_cast<size_t>(data_size);
format::InitBufferCommandHeader init_cmd;
init_cmd.meta_header.block_header.type = format::kMetaDataBlock;
init_cmd.meta_header.meta_data_type = format::kInitBufferCommand;
init_cmd.thread_id = thread_id;
init_cmd.device_id = device_id;
init_cmd.buffer_id = buffer_id;
init_cmd.data_size = write_size; // Uncompressed data size.
if (compressor_ != nullptr)
{
size_t compressed_size = compressor_->Compress(write_size, write_address, &compressed_buffer_);
if ((compressed_size > 0) && (compressed_size < write_size))
{
init_cmd.meta_header.block_header.type = format::BlockType::kCompressedMetaDataBlock;
write_address = compressed_buffer_.data();
write_size = compressed_size;
}
}
// Calculate size of packet with compressed or uncompressed data size.
init_cmd.meta_header.block_header.size =
(sizeof(init_cmd) - sizeof(init_cmd.meta_header.block_header)) + write_size;
bytes_written_ += file_stream_->Write(&init_cmd, sizeof(init_cmd));
bytes_written_ += file_stream_->Write(write_address, write_size);
}
void CompressionConverter::DispatchInitImageCommand(format::ThreadId thread_id,
format::HandleId device_id,
format::HandleId image_id,
uint64_t data_size,
uint32_t aspect,
uint32_t layout,
const std::vector<uint64_t>& level_sizes,
const uint8_t* data)
{
format::InitImageCommandHeader init_cmd;
// Packet size without the resource data.
init_cmd.meta_header.block_header.size = sizeof(init_cmd) - sizeof(init_cmd.meta_header.block_header);
init_cmd.meta_header.block_header.type = format::kMetaDataBlock;
init_cmd.meta_header.meta_data_type = format::kInitImageCommand;
init_cmd.thread_id = thread_id;
init_cmd.device_id = device_id;
init_cmd.image_id = image_id;
init_cmd.aspect = aspect;
init_cmd.layout = layout;
if (data_size > 0)
{
assert(!level_sizes.empty());
const uint8_t* write_address = data;
GFXRECON_CHECK_CONVERSION_DATA_LOSS(size_t, data_size);
size_t write_size = static_cast<size_t>(data_size);
// Store uncompressed data size in packet.
init_cmd.data_size = write_size;
init_cmd.level_count = static_cast<uint32_t>(level_sizes.size());
if (compressor_ != nullptr)
{
size_t compressed_size = compressor_->Compress(write_size, write_address, &compressed_buffer_);
if ((compressed_size > 0) && (compressed_size < write_size))
{
init_cmd.meta_header.block_header.type = format::BlockType::kCompressedMetaDataBlock;
write_address = compressed_buffer_.data();
write_size = compressed_size;
}
}
// Calculate size of packet with compressed or uncompressed data size.
size_t levels_size = level_sizes.size() * sizeof(level_sizes[0]);
init_cmd.meta_header.block_header.size += levels_size + write_size;
bytes_written_ += file_stream_->Write(&init_cmd, sizeof(init_cmd));
bytes_written_ += file_stream_->Write(level_sizes.data(), levels_size);
bytes_written_ += file_stream_->Write(write_address, write_size);
}
else
{
// Write a packet without resource data; replay must still perform a layout transition at image
// initialization.
init_cmd.data_size = 0;
init_cmd.level_count = 0;
bytes_written_ += file_stream_->Write(&init_cmd, sizeof(init_cmd));
}
}
GFXRECON_END_NAMESPACE(decode)
GFXRECON_END_NAMESPACE(gfxrecon)
| 44.274194 | 119 | 0.62472 | xooiamd |
ff74b57f3d608596dc87107d22efe349443c8f7a | 1,450 | cpp | C++ | pawno/include/YSI 2.0/Source/Utils.cpp | gebo96/samp-gamemode | b54b1961d13ce1d21e37f8b63f00c809c76c34e2 | [
"blessing"
] | 2 | 2019-08-05T04:04:34.000Z | 2021-11-15T11:03:39.000Z | pawno/include/YSI 2.0/Source/Utils.cpp | gebo96/samp-gamemode | b54b1961d13ce1d21e37f8b63f00c809c76c34e2 | [
"blessing"
] | 2 | 2020-12-09T03:40:28.000Z | 2021-03-17T13:03:50.000Z | pawno/include/YSI 2.0/Source/Utils.cpp | gebo96/samp-gamemode | b54b1961d13ce1d21e37f8b63f00c809c76c34e2 | [
"blessing"
] | 2 | 2020-10-31T19:01:00.000Z | 2021-08-14T23:09:51.000Z | /*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the YSI 2.0 SA:MP plugin.
*
* The Initial Developer of the Original Code is Alex "Y_Less" Cole.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Peter Beverloo
* Marcus Bauer
*/
#include "utils.h"
bool IsPointInRange(float x1, float y1, float z1, float x2, float y2, float z2, float distance)
{
return (GetRangeSquared(x1, y1, z1, x2, y2, z2) < (float)(distance * distance));
}
bool IsPointInRangeSq(float x1, float y1, float z1, float x2, float y2, float z2, float distance)
{
return (GetRangeSquared(x1, y1, z1, x2, y2, z2) < distance);
}
float GetRangeSquared(float x1, float y1, float z1, float x2, float y2, float z2)
{
x1 -= x2;
y1 -= y2;
z1 -= z2;
return ((float)((float)(x1 * x1) + (float)(y1 * y1) + (float)(z1 * z1)));
}
| 32.954545 | 98 | 0.658621 | gebo96 |
ff75814687c293d16997d55913b65347b2f5d54b | 2,291 | cc | C++ | modules/kernel/src/debugger/DebugVars.cc | eryjus/century-os | 6e6bef8cbc0f9c5ff6a943b44aa87a7e89fdfbd7 | [
"BSD-3-Clause"
] | 12 | 2018-12-03T15:16:52.000Z | 2022-03-16T21:07:13.000Z | modules/kernel/src/debugger/DebugVars.cc | eryjus/century-os | 6e6bef8cbc0f9c5ff6a943b44aa87a7e89fdfbd7 | [
"BSD-3-Clause"
] | null | null | null | modules/kernel/src/debugger/DebugVars.cc | eryjus/century-os | 6e6bef8cbc0f9c5ff6a943b44aa87a7e89fdfbd7 | [
"BSD-3-Clause"
] | 2 | 2018-11-13T01:30:41.000Z | 2021-08-12T18:22:26.000Z | //===================================================================================================================
//
// DebugVars.cc -- Variables used by the debugger
//
// Copyright (c) 2017-2020 -- Adam Clark
// Licensed under "THE BEER-WARE LICENSE"
// See License.md for details.
//
// ------------------------------------------------------------------------------------------------------------------
//
// Date Tracker Version Pgmr Description
// ----------- ------- ------- ---- ---------------------------------------------------------------------------
// 2020-Apr-02 Initial v0.6.0a ADCL Initial version
//
//===================================================================================================================
#include "types.h"
#include "debugger.h"
//
// -- This is the current variable that identifies the current state
// --------------------------------------------------------------
EXPORT KERNEL_BSS
DebuggerState_t debugState;
//
// -- This is the buffer for the command being entered
// ------------------------------------------------
EXPORT KERNEL_BSS
char debugCommand[DEBUG_COMMAND_LEN];
//
// -- For each state, this is the visual representation where on the command tree the user is and what the
// valid commands are (indexed by state).
// ----------------------------------------------------------------------------------------------------
EXPORT KERNEL_DATA
DebugPrompt_t dbgPrompts[] {
// -- location allowed
{"-", "scheduler,timer,msgq"}, // -- DBG_HOME
{"sched", "show,status,run,ready,list,exit"}, // -- DBG_SCHED
{"sched:ready", "all,os,high,normal,low,idle,exit"}, // -- DBG_SCHED_RDY
{"sched:list", "blocked,sleeping,zombie,exit"}, // -- DBG_SCHED_LIST
{"timer", "counts,config,exit"}, // -- DBG_TIMER
{"msgq", "status,show,exit"}, // -- DBG_MSGQ
};
//
// -- This is the actual debug communication structure
// ------------------------------------------------
EXPORT KERNEL_BSS
DebugComm_t debugCommunication = {0};
| 40.192982 | 117 | 0.381493 | eryjus |
ff75c15711eef496b065b8469eb5ee91e8ca69bf | 2,519 | hpp | C++ | inference-engine/include/builders/ie_crop_layer.hpp | fujunwei/dldt | 09497b7724de4be92629f7799b8538b483d809a2 | [
"Apache-2.0"
] | null | null | null | inference-engine/include/builders/ie_crop_layer.hpp | fujunwei/dldt | 09497b7724de4be92629f7799b8538b483d809a2 | [
"Apache-2.0"
] | null | null | null | inference-engine/include/builders/ie_crop_layer.hpp | fujunwei/dldt | 09497b7724de4be92629f7799b8538b483d809a2 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
/**
* @file
*/
#pragma once
#include <builders/ie_layer_decorator.hpp>
#include <ie_network.hpp>
#include <string>
#include <vector>
namespace InferenceEngine {
namespace Builder {
/**
* @deprecated Use ngraph API instead.
* @brief The class represents a builder for Crop layer
*/
IE_SUPPRESS_DEPRECATED_START
class INFERENCE_ENGINE_NN_BUILDER_API_CLASS(CropLayer): public LayerDecorator {
public:
/**
* @brief The constructor creates a builder with the name
* @param name Layer name
*/
explicit CropLayer(const std::string& name = "");
/**
* @brief The constructor creates a builder from generic builder
* @param layer pointer to generic builder
*/
explicit CropLayer(const Layer::Ptr& layer);
/**
* @brief The constructor creates a builder from generic builder
* @param layer constant pointer to generic builder
*/
explicit CropLayer(const Layer::CPtr& layer);
/**
* @brief Sets the name for the layer
* @param name Layer name
* @return reference to layer builder
*/
CropLayer& setName(const std::string& name);
/**
* @brief Returns input ports
* @return Vector of input ports
*/
const std::vector<Port>& getInputPorts() const;
/**
* @brief Sets input ports
* @param ports Vector of input ports
* @return reference to layer builder
*/
CropLayer& setInputPorts(const std::vector<Port>& ports);
/**
* @brief Return output port
* @return Output port
*/
const Port& getOutputPort() const;
/**
* @brief Sets output port
* @param port Output port
* @return reference to layer builder
*/
CropLayer& setOutputPort(const Port& port);
/**
* @brief Returns axis
* @return Vector of axis
*/
const std::vector<size_t> getAxis() const;
/**
* @brief Sets axis
* @param axis Vector of axis
* @return reference to layer builder
*/
CropLayer& setAxis(const std::vector<size_t>& axis);
/**
* @brief Returns offsets
* @return Vector of offsets
*/
const std::vector<size_t> getOffset() const;
/**
* @brief Sets offsets
* @param offsets Vector of offsets
* @return reference to layer builder
*/
CropLayer& setOffset(const std::vector<size_t>& offsets);
};
IE_SUPPRESS_DEPRECATED_END
} // namespace Builder
} // namespace InferenceEngine
| 25.969072 | 79 | 0.645494 | fujunwei |
ff7657f22c869097789d1df79e3e103829b7f0e0 | 1,715 | cpp | C++ | test_6114.cpp | kc9jud/UNtoU3 | 999d12d73909c483a9dc92842badee515e814997 | [
"BSD-2-Clause"
] | 1 | 2021-02-24T22:53:11.000Z | 2021-02-24T22:53:11.000Z | test_6114.cpp | kc9jud/UNtoU3 | 999d12d73909c483a9dc92842badee515e814997 | [
"BSD-2-Clause"
] | null | null | null | test_6114.cpp | kc9jud/UNtoU3 | 999d12d73909c483a9dc92842badee515e814997 | [
"BSD-2-Clause"
] | 1 | 2021-02-25T04:34:59.000Z | 2021-02-25T04:34:59.000Z | // test_6414.cpp - a test driver for UNtoU3 class.
//
// License: BSD 2-Clause (https://opensource.org/licenses/BSD-2-Clause)
//
// Copyright (c) 2019, Daniel Langr
// All rights reserved.
//
// Program implements the U(N) to U(3) reduction where n=5 (N=21) for the input irrep
// [f] = [2,2,2,2,2,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
// which is represented by a number of twos n2=6, number of ones n1=1, and number of zeros n0=14.
// Its dimension is dim[f] = 2168999910.
//
// After reduction, the program iterates over generated U(3) weights and calculates the sum of
// dimensions of resulting U(3) irrpes multiplied by their level dimensionalities. This sum
// should be equal to dim[f].
#include <iostream>
// #define UNTOU3_DISABLE_TCO
// #define UNTOU3_DISABLE_UNORDERED
// #define UNTOU3_DISABLE_PRECALC
#define UNTOU3_ENABLE_OPENMP
#include "UNtoU3.h"
unsigned long dim(const UNtoU3<>::U3Weight & irrep) {
return (irrep[0] - irrep[1] + 1) * (irrep[0] - irrep[2] + 2) * (irrep[1] - irrep[2] + 1) / 2;
}
int main() {
UNtoU3<> gen;
// n=5 - a given HO level, N = (n+1)*(n+2)/2 = 21
gen.generateXYZ(5);
// generation of U(3) irreps in the input U(21) irrep [f]
gen.generateU3Weights(6, 1, 14);
// calculated sum
unsigned long sum = 0;
// iteration over generated U(3) weights
for (const auto & pair : gen.multMap()) {
// get U(3) weight lables
const auto & weight = pair.first;
// get its level dimensionality if its nonzero and the U(3) weight is a U(3) irrep
if (auto D_l = gen.getLevelDimensionality(weight))
// add contribution of this U(3) irrep to the sum
sum += D_l * dim(weight);
}
std::cout << sum << std::endl;
}
| 35.729167 | 97 | 0.651312 | kc9jud |
ff76903cbbaa7b49bdc58a3b47a45cea1c4e45d4 | 5,491 | cpp | C++ | frameworks/bridge/test/unittest/jsfrontend/dompopup/dom_popup_test.cpp | openharmony-gitee-mirror/ace_ace_engine | 78013960cdce81348d1910e466a3292605442a5e | [
"Apache-2.0"
] | null | null | null | frameworks/bridge/test/unittest/jsfrontend/dompopup/dom_popup_test.cpp | openharmony-gitee-mirror/ace_ace_engine | 78013960cdce81348d1910e466a3292605442a5e | [
"Apache-2.0"
] | null | null | null | frameworks/bridge/test/unittest/jsfrontend/dompopup/dom_popup_test.cpp | openharmony-gitee-mirror/ace_ace_engine | 78013960cdce81348d1910e466a3292605442a5e | [
"Apache-2.0"
] | 1 | 2021-09-13T12:07:42.000Z | 2021-09-13T12:07:42.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 "gtest/gtest.h"
#include "core/components/common/layout/constants.h"
#include "core/components/popup/popup_component.h"
#include "frameworks/bridge/common/dom/dom_document.h"
#include "frameworks/bridge/common/dom/dom_popup.h"
#include "frameworks/bridge/test/unittest/jsfrontend/dom_node_factory.h"
using namespace testing;
using namespace testing::ext;
namespace OHOS::Ace::Framework {
namespace {
const Placement PLACEMENT_VALUE = Placement::LEFT;
const std::string MASK_COLOR_DEFAULT = "#0x0000ff";
} // namespace
class DomPopupTest : public testing::Test {
public:
static void SetUpTestCase();
static void TearDownTestCase();
void SetUp() override;
void TearDown() override;
};
void DomPopupTest::SetUpTestCase() {}
void DomPopupTest::TearDownTestCase() {}
void DomPopupTest::SetUp() {}
void DomPopupTest::TearDown() {}
/**
* @tc.name: DomPopupCreatorTest001
* @tc.desc: Test create popup node successfully and popupcomponent create as desire.
* @tc.type: FUNC
* @tc.require: AR000DD66M
* @tc.author: chenbenzhi
*/
HWTEST_F(DomPopupTest, DomPopupCreatorTest001, TestSize.Level1)
{
/**
* @tc.steps: step1. construct the json string of popup component with tag only.
*/
const std::string jsonPopupStr = ""
"{ "
" \"tag\": \"popup\" "
"}";
/**
* @tc.steps: step2. Verify whether the DomPopup.
* @tc.expected: step3. DomPopup is not null.
*/
auto popup = DOMNodeFactory::GetInstance().CreateDOMNodeFromDsl(jsonPopupStr);
EXPECT_TRUE(popup);
}
/**
* @tc.name: DomPopupTest002
* @tc.desc: Verify that DomPopup can be set attributes and styles.
* @tc.type: FUNC
* @tc.require: AR000DD66M
* @tc.author: chenbenzhi
*/
HWTEST_F(DomPopupTest, DomPopupTest002, TestSize.Level1)
{
/**
* @tc.steps: step1. construct the json string of DomPopup with attributes and styles.
*/
const std::string jsonPopupStr = ""
"{ "
" \"tag\": \"popup\", "
" \"attr\": [ "
" {"
" \"placement\" : \"left\" "
" }], "
" \"style\": [{ "
" \"maskColor\" : \"#0x0000ff\" "
" }]"
"}";
/**
* @tc.steps: step2. call jsonPopupStr interface, create DomPopup and set its style.
*/
auto domNodeRoot = DOMNodeFactory::GetInstance().CreateDOMNodeFromDsl(jsonPopupStr);
auto popupChild = AceType::DynamicCast<PopupComponent>(domNodeRoot->GetSpecializedComponent());
ACE_DCHECK(popupChild);
/**
* @tc.steps: step3. Check all the attributes and styles matched.
* @tc.expected: step3. All the attributes and styles are matched.
*/
EXPECT_TRUE(popupChild);
EXPECT_EQ(popupChild->GetPopupParam()->GetPlacement(), PLACEMENT_VALUE);
EXPECT_EQ(popupChild->GetPopupParam()->GetMaskColor(), Color::FromString(MASK_COLOR_DEFAULT));
}
/**
* @tc.name: DomPopupTest003
* @tc.desc: Test add event to popup component successfully.
* @tc.type: FUNC
* @tc.require: AR000DD66M
* @tc.author: chenbenzhi
*/
HWTEST_F(DomPopupTest, DomPopupTest003, TestSize.Level1)
{
/**
* @tc.steps: step1. Construct string with right fields, then create popup node with it.
* @tc.expected: step1. Popup node and is created successfully.
*/
const std::string jsonPopupStr = ""
"{ "
" \"tag\": \"popup\", "
" \"event\": [ \"visibilitychange\" ] "
"}";
auto domNodeRoot = DOMNodeFactory::GetInstance().CreateDOMNodeFromDsl(jsonPopupStr);
auto popupChild = AceType::DynamicCast<PopupComponent>(domNodeRoot->GetSpecializedComponent());
ACE_DCHECK(popupChild);
/**
* @tc.steps: step2. Check eventId of created popup component.
* @tc.expected: step2. The eventId value of popup component is as expected.
*/
EXPECT_TRUE(popupChild);
EXPECT_EQ(popupChild->GetPopupParam()->GetOnVisibilityChange(), std::to_string(domNodeRoot->GetNodeId()));
}
} // namespace OHOS::Ace::Framework
| 38.131944 | 110 | 0.562193 | openharmony-gitee-mirror |
ff775d6947292d8ed8448c5cacd7b351f45b67e5 | 2,911 | cpp | C++ | src/procx.cpp | michalwidera/jeton | 587665ad904f3dd4dea709a4f4e43b3b5d34a67d | [
"MIT"
] | 1 | 2015-09-24T17:42:49.000Z | 2015-09-24T17:42:49.000Z | src/procx.cpp | michalwidera/jeton | 587665ad904f3dd4dea709a4f4e43b3b5d34a67d | [
"MIT"
] | 3 | 2015-04-16T16:18:32.000Z | 2019-01-17T11:57:19.000Z | src/procx.cpp | michalwidera/jeton | 587665ad904f3dd4dea709a4f4e43b3b5d34a67d | [
"MIT"
] | 2 | 2016-09-02T16:08:44.000Z | 2019-01-16T22:51:57.000Z | #include "procx.h"
#include <assert.h>
ProcessClass::ProcessClass(void)
{
State = STATE_ON;
RodzajWej = '.';
RodzajWyj = '.';
PrevProcess = NULL;
NextProcess = NULL;
}
void ProcessClass::LocalDestructor(void)
{
if(NextProcess != NULL)
{
NextProcess->LocalDestructor();
delete NextProcess;
NextProcess = NULL;
}
}
ProcessClass::~ProcessClass(void)
{
LocalDestructor();
}
int ProcessClass::Init(int, char *[])
{
SygError("To nie powinno być wywoływane");
return RESULT_OFF;
}
int ProcessClass::Work(int, Byte *, int)
{
SygError("To nie powinno być wywoływane");
return 0;
}
ProcessClass * ProcessClass::FindUnusedPointer(void)
{
ProcessClass * tmp;
tmp = NULL;
if(NextProcess != NULL)
{
tmp = NextProcess->FindUnusedPointer();
}
else
{
if(RodzajWyj == 'M' || RodzajWyj == 'B')
{
tmp = this;
}
}
return tmp;
}
/* Podłącza w wolne miejsce wskaźnik następnego procesu. Wartość zwracana:
1 - OK, 0 - błąd */
int ProcessClass::ConnectPointer(ProcessClass * proc)
{
int status;
status = 0;
if(NextProcess == NULL)
{
NextProcess = proc;
proc->PrevProcess = this;
status = 1;
}
else
{
SygError("Proces twierdził, że ma miejsce na podłączenie następnego?");
}
return status;
}
/* Sprawdza, czy do aktualnego obiektu można podłączyć następny obiekt.
Dozwolone są tylko połączenia "B->M" i "M->B". Wartość zwrotna: 1 - typy
są zgodne, 0 - typy są niezgodne, co zabrania tworzenia takiego połączenia */
int ProcessClass::ZgodnyTyp(ProcessClass *proc)
{
int status;
status = 0;
if(RodzajWyj == 'B')
{
if(proc->RodzajWej == 'M')
{
status = 1;
}
}
else
{
if(RodzajWyj == 'M')
{
if(proc->RodzajWej == 'B')
{
status = 1;
}
}
}
return status;
}
/* Funkcja sprawdza, czy podany proces może pracować jako proces wejściowy.
Wartość zwrotna: 1 - tak, 0 - nie */
int ProcessClass::ProcesWejsciowy(void)
{
int status;
status = 0;
if(RodzajWej == '-')
{
status = 1;
}
return status;
}
/* Zmienia stan obiektu na podany. Jeśli to jest zmiana na STATE_OFF,
to od razu powiadamia sąsiadów z obu stron. */
void ProcessClass::ZmienStan(int nowy, int kier)
{
assert(nowy == STATE_OFF || nowy == STATE_EOF);
assert(kier == KIER_PROSTO || kier == KIER_WSTECZ || kier == KIER_INNY);
if(nowy == STATE_OFF)
{
if(State != nowy)
{
State = nowy;
if(kier != KIER_WSTECZ)
{
if(NextProcess != NULL)
{
NextProcess->Work(SAND_OFF, NULL, KIER_PROSTO);
}
}
}
}
else
{
State = nowy;
}
}
/* Tworzenie nowych wątków dla obsługi systemu i budzenie ich.
Wartość zwrotna: 1 - OK (udało się pomyślnie utworzyć nowe wątki),
0 - błąd (możemy kończyć pracę systemu, bo się nie udał przydział wątków */
int ProcessClass::Rozszczepianie(void)
{
int status;
status = 1; /* Tak ogólnie niczego nie trzeba rozszczepiać */
if(NextProcess != NULL)
{
status = NextProcess->Rozszczepianie();
}
return status;
}
| 18.424051 | 77 | 0.665751 | michalwidera |
ff7778c52ada84ac5349b0b126d952eb2d91777b | 535 | cpp | C++ | src/componentMask.cpp | taurheim/NomadECS | 0546833bf18d261cd7eb764279da1d17ce80954e | [
"MIT"
] | 136 | 2018-10-04T17:21:52.000Z | 2022-03-19T11:00:52.000Z | src/componentMask.cpp | taurheim/NomadECS | 0546833bf18d261cd7eb764279da1d17ce80954e | [
"MIT"
] | 1 | 2019-02-05T02:32:57.000Z | 2019-02-05T02:32:57.000Z | src/componentMask.cpp | taurheim/NomadECS | 0546833bf18d261cd7eb764279da1d17ce80954e | [
"MIT"
] | 23 | 2018-10-05T15:17:56.000Z | 2022-03-09T02:05:49.000Z | #include "componentMask.h"
#include "nomad.h"
namespace nomad {
bool ComponentMask::isNewMatch(nomad::ComponentMask oldMask, nomad::ComponentMask systemMask) {
return matches(systemMask) && !oldMask.matches(systemMask);
}
bool ComponentMask::isNoLongerMatched(nomad::ComponentMask oldMask, nomad::ComponentMask systemMask) {
return oldMask.matches(systemMask) && !matches(systemMask);
}
bool ComponentMask::matches(nomad::ComponentMask systemMask) { return ((mask & systemMask.mask) == systemMask.mask); }
} // namespace nomad
| 35.666667 | 118 | 0.771963 | taurheim |
ff799d4db5351022ca910a1a150aafdbab1a72a5 | 5,152 | cxx | C++ | Qt/ApplicationComponents/pqImportCinemaReaction.cxx | trickyMan/paraview_view | 3b38670e8259b688093e0d7ba2fe2edd7c5d57a7 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Qt/ApplicationComponents/pqImportCinemaReaction.cxx | trickyMan/paraview_view | 3b38670e8259b688093e0d7ba2fe2edd7c5d57a7 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Qt/ApplicationComponents/pqImportCinemaReaction.cxx | trickyMan/paraview_view | 3b38670e8259b688093e0d7ba2fe2edd7c5d57a7 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: ParaView
Module: pqImportCinemaReaction.cxx
Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
========================================================================*/
#include "pqImportCinemaReaction.h"
#include "vtkPVConfig.h"
#include "pqActiveObjects.h"
#include "pqCoreUtilities.h"
#include "pqFileDialog.h"
#include "pqServer.h"
#include "pqStandardRecentlyUsedResourceLoaderImplementation.h"
#include "pqUndoStack.h"
#include "pqView.h"
#include "vtkNew.h"
#if defined(VTKGL2) && defined(PARAVIEW_ENABLE_PYTHON)
#include "vtkSMCinemaDatabaseImporter.h"
#endif
#include <sstream>
//-----------------------------------------------------------------------------
pqImportCinemaReaction::pqImportCinemaReaction(QAction* parentObject)
: Superclass(parentObject)
{
pqActiveObjects* activeObjects = &pqActiveObjects::instance();
QObject::connect(
activeObjects, SIGNAL(serverChanged(pqServer*)), this, SLOT(updateEnableState()));
this->updateEnableState();
}
//-----------------------------------------------------------------------------
pqImportCinemaReaction::~pqImportCinemaReaction()
{
}
//-----------------------------------------------------------------------------
void pqImportCinemaReaction::updateEnableState()
{
#if defined(VTKGL2) && defined(PARAVIEW_ENABLE_PYTHON)
bool enable_state = false;
pqActiveObjects& activeObjects = pqActiveObjects::instance();
vtkSMSession* session =
activeObjects.activeServer() ? activeObjects.activeServer()->session() : NULL;
if (session)
{
vtkNew<vtkSMCinemaDatabaseImporter> importer;
enable_state = importer->SupportsCinema(session);
}
this->parentAction()->setEnabled(enable_state);
#else
this->parentAction()->setEnabled(true);
#endif
}
//-----------------------------------------------------------------------------
bool pqImportCinemaReaction::loadCinemaDatabase()
{
#if !defined(VTKGL2)
pqCoreUtilities::promptUser("pqImportCinemaReaction::NoOpenGL2", QMessageBox::Critical,
tr("Incompatible rendering backend"),
tr("'OpenGL2' rendering backend is required to load a Cinema database, "
"but is not available in this build."),
QMessageBox::Ok | QMessageBox::Save);
return false;
#elif !defined(PARAVIEW_ENABLE_PYTHON)
pqCoreUtilities::promptUser("pqImportCinemaReaction::NoPython", QMessageBox::Critical,
tr("Python support not enabled"), tr("Python support is required to load a Cinema database, "
"but is not available in this build."),
QMessageBox::Ok | QMessageBox::Save);
return false;
#else
pqServer* server = pqActiveObjects::instance().activeServer();
pqFileDialog fileDialog(server, pqCoreUtilities::mainWidget(), tr("Open Cinema Database:"),
QString(), "Cinema Database Files (info.json);;All files(*)");
fileDialog.setObjectName("FileOpenDialog");
fileDialog.setFileMode(pqFileDialog::ExistingFiles);
if (fileDialog.exec() == QDialog::Accepted)
{
return pqImportCinemaReaction::loadCinemaDatabase(fileDialog.getSelectedFiles(0)[0]);
}
return false;
#endif
}
//-----------------------------------------------------------------------------
bool pqImportCinemaReaction::loadCinemaDatabase(const QString& dbase, pqServer* server)
{
#if defined(VTKGL2) && defined(PARAVIEW_ENABLE_PYTHON)
CLEAR_UNDO_STACK();
server = (server != NULL) ? server : pqActiveObjects::instance().activeServer();
pqView* view = pqActiveObjects::instance().activeView();
vtkNew<vtkSMCinemaDatabaseImporter> importer;
if (!importer->ImportCinema(
dbase.toLatin1().data(), server->session(), (view ? view->getViewProxy() : NULL)))
{
qCritical("Failed to import Cinema database.");
return false;
}
pqStandardRecentlyUsedResourceLoaderImplementation::addCinemaDatabaseToRecentResources(
server, dbase);
if (view)
{
view->render();
}
CLEAR_UNDO_STACK();
return true;
#else
(void)dbase;
(void)server;
return false;
#endif
}
| 35.047619 | 97 | 0.668672 | trickyMan |
ff7c9635fa8d65737a8da4b201f35871c604abe3 | 8,050 | cpp | C++ | test/qupzilla-master/src/lib/webengine/webscrollbarmanager.cpp | JamesMBallard/qmake-unity | cf5006a83e7fb1bbd173a9506771693a673d387f | [
"MIT"
] | 16 | 2019-05-23T08:10:39.000Z | 2021-12-21T11:20:37.000Z | test/qupzilla-master/src/lib/webengine/webscrollbarmanager.cpp | JamesMBallard/qmake-unity | cf5006a83e7fb1bbd173a9506771693a673d387f | [
"MIT"
] | null | null | null | test/qupzilla-master/src/lib/webengine/webscrollbarmanager.cpp | JamesMBallard/qmake-unity | cf5006a83e7fb1bbd173a9506771693a673d387f | [
"MIT"
] | 2 | 2019-05-23T18:37:43.000Z | 2021-08-24T21:29:40.000Z | /* ============================================================
* QupZilla - Qt web browser
* Copyright (C) 2016-2017 David Rosca <nowrep@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* ============================================================ */
#include "webscrollbarmanager.h"
#include "webscrollbar.h"
#include "webview.h"
#include "webpage.h"
#include "mainapplication.h"
#include "scripts.h"
#include "settings.h"
#include <QPointer>
#include <QPaintEvent>
#include <QWebEngineProfile>
#include <QWebEngineScriptCollection>
#include <QStyle>
#include <QStyleOption>
Q_GLOBAL_STATIC(WebScrollBarManager, qz_web_scrollbar_manager)
class WebScrollBarCornerWidget : public QWidget
{
public:
explicit WebScrollBarCornerWidget(WebView *view)
: QWidget()
, m_view(view)
{
setAutoFillBackground(true);
}
void updateVisibility(bool visible, int thickness)
{
if (visible) {
setParent(m_view->overlayWidget());
resize(thickness, thickness);
move(m_view->width() - width(), m_view->height() - height());
show();
} else {
hide();
}
}
private:
void paintEvent(QPaintEvent *ev) override
{
Q_UNUSED(ev)
QStyleOption option;
option.initFrom(this);
option.rect = rect();
QPainter p(this);
if (mApp->styleName() == QL1S("breeze")) {
p.fillRect(ev->rect(), option.palette.background());
} else {
style()->drawPrimitive(QStyle::PE_PanelScrollAreaCorner, &option, &p, this);
}
}
WebView *m_view;
};
struct ScrollBarData {
~ScrollBarData() {
delete vscrollbar;
delete hscrollbar;
delete corner;
}
WebScrollBar *vscrollbar;
WebScrollBar *hscrollbar;
bool vscrollbarVisible = false;
bool hscrollbarVisible = false;
WebScrollBarCornerWidget *corner;
};
WebScrollBarManager::WebScrollBarManager(QObject *parent)
: QObject(parent)
{
m_scrollbarJs = QL1S("(function() {"
"var head = document.getElementsByTagName('head')[0];"
"if (!head) return;"
"var css = document.createElement('style');"
"css.setAttribute('type', 'text/css');"
"var size = %1 / window.devicePixelRatio + 'px';"
"css.appendChild(document.createTextNode('"
" body::-webkit-scrollbar{width:'+size+';height:'+size+';}"
"'));"
"head.appendChild(css);"
"})()");
loadSettings();
}
void WebScrollBarManager::loadSettings()
{
m_enabled = Settings().value(QSL("Web-Browser-Settings/UseNativeScrollbars"), false).toBool();
if (!m_enabled) {
for (WebView *view : m_scrollbars.keys()) {
removeWebView(view);
}
}
}
void WebScrollBarManager::addWebView(WebView *view)
{
if (!m_enabled) {
return;
}
delete m_scrollbars.value(view);
ScrollBarData *data = new ScrollBarData;
data->vscrollbar = new WebScrollBar(Qt::Vertical, view);
data->hscrollbar = new WebScrollBar(Qt::Horizontal, view);
data->corner = new WebScrollBarCornerWidget(view);
m_scrollbars[view] = data;
const int thickness = data->vscrollbar->thickness();
auto updateValues = [=]() {
const QSize viewport = viewportSize(view, thickness);
data->vscrollbar->updateValues(viewport);
data->vscrollbar->setVisible(data->vscrollbarVisible);
data->hscrollbar->updateValues(viewport);
data->hscrollbar->setVisible(data->hscrollbarVisible);
data->corner->updateVisibility(data->vscrollbarVisible && data->hscrollbarVisible, thickness);
};
connect(view, &WebView::viewportResized, data->vscrollbar, updateValues);
connect(view->page(), &WebPage::scrollPositionChanged, data->vscrollbar, updateValues);
connect(view->page(), &WebPage::contentsSizeChanged, data->vscrollbar, [=]() {
const QString source = QL1S("var out = {"
"vertical: document.documentElement && window.innerWidth > document.documentElement.clientWidth,"
"horizontal: document.documentElement && window.innerHeight > document.documentElement.clientHeight"
"};out;");
QPointer<WebView> p(view);
view->page()->runJavaScript(source, WebPage::SafeJsWorld, [=](const QVariant &res) {
if (!p || !m_scrollbars.contains(view)) {
return;
}
const QVariantMap map = res.toMap();
data->vscrollbarVisible = map.value(QSL("vertical")).toBool();
data->hscrollbarVisible = map.value(QSL("horizontal")).toBool();
updateValues();
});
});
connect(view, &WebView::zoomLevelChanged, data->vscrollbar, [=]() {
view->page()->runJavaScript(m_scrollbarJs.arg(thickness));
});
if (m_scrollbars.size() == 1) {
createUserScript(thickness);
}
}
void WebScrollBarManager::removeWebView(WebView *view)
{
if (!m_scrollbars.contains(view)) {
return;
}
if (m_scrollbars.size() == 1) {
removeUserScript();
}
delete m_scrollbars.take(view);
}
QScrollBar *WebScrollBarManager::scrollBar(Qt::Orientation orientation, WebView *view) const
{
ScrollBarData *d = m_scrollbars.value(view);
if (!d) {
return nullptr;
}
return orientation == Qt::Vertical ? d->vscrollbar : d->hscrollbar;
}
WebScrollBarManager *WebScrollBarManager::instance()
{
return qz_web_scrollbar_manager();
}
void WebScrollBarManager::createUserScript(int thickness)
{
QWebEngineScript script;
script.setName(QSL("_qupzilla_scrollbar"));
script.setInjectionPoint(QWebEngineScript::DocumentReady);
script.setWorldId(WebPage::SafeJsWorld);
script.setSourceCode(m_scrollbarJs.arg(thickness));
mApp->webProfile()->scripts()->insert(script);
}
void WebScrollBarManager::removeUserScript()
{
QWebEngineScript script = mApp->webProfile()->scripts()->findScript(QSL("_qupzilla_scrollbar"));
mApp->webProfile()->scripts()->remove(script);
}
QSize WebScrollBarManager::viewportSize(WebView *view, int thickness) const
{
QSize viewport = view->size();
thickness /= view->devicePixelRatioF();
ScrollBarData *data = m_scrollbars.value(view);
Q_ASSERT(data);
if (data->vscrollbarVisible) {
viewport.setWidth(viewport.width() - thickness);
}
if (data->hscrollbarVisible) {
viewport.setHeight(viewport.height() - thickness);
}
#if 0
const QSize content = view->page()->contentsSize().toSize();
// Check both axis
if (content.width() - viewport.width() > 0) {
viewport.setHeight(viewport.height() - thickness);
}
if (content.height() - viewport.height() > 0) {
viewport.setWidth(viewport.width() - thickness);
}
// Check again against adjusted size
if (viewport.height() == view->height() && content.width() - viewport.width() > 0) {
viewport.setHeight(viewport.height() - thickness);
}
if (viewport.width() == view->width() && content.height() - viewport.height() > 0) {
viewport.setWidth(viewport.width() - thickness);
}
#endif
return viewport;
}
| 31.081081 | 136 | 0.62087 | JamesMBallard |
ff7db42a070a5a14ae2622638c3344623ccac321 | 1,021 | cpp | C++ | src/ui/text/font.cpp | Yanick-Salzmann/grower-controller-rpi | 30f279e960a3cc8125f112c76ee943b1fa766191 | [
"MIT"
] | null | null | null | src/ui/text/font.cpp | Yanick-Salzmann/grower-controller-rpi | 30f279e960a3cc8125f112c76ee943b1fa766191 | [
"MIT"
] | null | null | null | src/ui/text/font.cpp | Yanick-Salzmann/grower-controller-rpi | 30f279e960a3cc8125f112c76ee943b1fa766191 | [
"MIT"
] | null | null | null | #include "font.hpp"
namespace grower::ui::text {
LOGGER_IMPL(font);
void font::add_font(const std::string &file_name) {
if(!FcConfigAppFontAddFile(FcConfigGetCurrent(), (FcChar8 *) file_name.c_str())) {
log->warn("Error adding font: {}", file_name);
}
}
void font::load_default_fonts() {
std::string fonts[]{
"TitilliumWeb-Black.ttf",
"TitilliumWeb-Bold.ttf",
"TitilliumWeb-BoldItalic.ttf",
"TitilliumWeb-ExtraLight.ttf",
"TitilliumWeb-ExtraLightItalic.ttf",
"TitilliumWeb-Italic.ttf",
"TitilliumWeb-Light.ttf",
"TitilliumWeb-LightItalic.ttf",
"TitilliumWeb-Regular.ttf",
"TitilliumWeb-SemiBold.ttf",
"TitilliumWeb-SemiBoldItalic.ttf",
"Font Awesome 5 Free-Solid-900.otf"
};
for(const auto& font : fonts) {
log->info("Adding font: {}", font);
add_font(fmt::format("resources/{}", font));
}
}
} | 30.939394 | 90 | 0.571009 | Yanick-Salzmann |
ff81c7d58e4771631e9ba43adb6902567bbe89ce | 2,921 | cc | C++ | src/subsetsum.cc | Kingsford-Group/catfish | acef05cfb1077d613e0f742a31b58e196ce3db29 | [
"BSD-3-Clause"
] | 3 | 2016-11-16T19:08:35.000Z | 2018-02-04T22:08:26.000Z | src/subsetsum.cc | Kingsford-Group/catfish | acef05cfb1077d613e0f742a31b58e196ce3db29 | [
"BSD-3-Clause"
] | null | null | null | src/subsetsum.cc | Kingsford-Group/catfish | acef05cfb1077d613e0f742a31b58e196ce3db29 | [
"BSD-3-Clause"
] | 2 | 2017-12-08T23:42:34.000Z | 2018-06-05T21:42:48.000Z | /*
Part of Catfish
(c) 2017 by Mingfu Shao, Carl Kingsford, and Carnegie Mellon University.
See LICENSE for licensing.
*/
#include "subsetsum.h"
#include "config.h"
#include <cstdio>
#include <cmath>
#include <climits>
#include <algorithm>
#include <cassert>
subsetsum::subsetsum(const vector<PI> &s, const vector<PI> &t)
: source(s), target(t)
{
eqns.clear();
}
int subsetsum::solve()
{
init();
fill();
optimize();
return 0;
}
int subsetsum::init()
{
sort(source.begin(), source.end());
sort(target.begin(), target.end());
ubound = target[target.size() - 1].first;
table1.resize(source.size() + 1);
table2.resize(source.size() + 1);
for(int i = 0; i < table1.size(); i++)
{
table1[i].assign(ubound + 1, false);
table2[i].assign(ubound + 1, -1);
}
for(int i = 0; i <= source.size(); i++)
{
table1[i][0] = false;
table2[i][0] = 0;
}
for(int j = 1; j <= ubound; j++)
{
table1[0][j] = false;
table2[0][j] = -1;
}
return 0;
}
int subsetsum::fill()
{
for(int j = 1; j <= ubound; j++)
{
for(int i = 1; i <= source.size(); i++)
{
int s = source[i - 1].first;
if(j >= s && table2[i - 1][j - s] >= 0)
{
table1[i][j] = true;
table2[i][j] = i;
}
if(table2[i - 1][j] >= 0)
{
table2[i][j] = table2[i - 1][j];
}
}
}
return 0;
}
int subsetsum::optimize()
{
eqns.clear();
for(int i = 0; i < target.size(); i++)
{
equation eqn(0);
backtrace(i, eqn);
if(eqn.s.size() == 0) continue;
eqns.push_back(eqn);
}
return 0;
}
int subsetsum::backtrace(int ti, equation &eqn)
{
int t = target[ti].first;
int n = source.size();
if(table2[n][t] == -1) return 0;
eqn.s.push_back(target[ti].second);
int x = t;
int s = table2[n][t];
while(x >= 1 && s >= 1)
{
assert(table2[s][x] >= 0);
eqn.t.push_back(source[s - 1].second);
x -= source[s - 1].first;
s = table2[s - 1][x];
}
return 0;
}
int subsetsum::print()
{
printf("table 1\n");
printf(" ");
for(int i = 0; i < table1[0].size(); i++) printf("%3d", i);
printf("\n");
for(int i = 0; i < table1.size(); i++)
{
printf("%3d", i);
for(int j = 0; j < table1[i].size(); j++)
{
printf("%3d", table1[i][j] ? 1 : 0);
}
printf("\n");
}
printf("table 2\n");
printf(" ");
for(int i = 0; i < table2[0].size(); i++) printf("%3d", i);
printf("\n");
for(int i = 0; i < table2.size(); i++)
{
printf("%3d", i);
for(int j = 0; j < table2[i].size(); j++)
{
printf("%3d", table2[i][j]);
}
printf("\n");
}
for(int i = 0; i < eqns.size(); i++)
{
eqns[i].print(i);
}
return 0;
}
int subsetsum::test()
{
vector<PI> v;
v.push_back(PI(5, 1));
v.push_back(PI(6, 2));
v.push_back(PI(8, 3));
v.push_back(PI(3, 5));
v.push_back(PI(10,8));
vector<PI> t;
t.push_back(PI(20, 2));
t.push_back(PI(8, 4));
t.push_back(PI(11, 5));
t.push_back(PI(18, 3));
t.push_back(PI(10, 1));
subsetsum sss(v, t);
sss.solve();
sss.print();
return 0;
}
| 16.691429 | 73 | 0.544334 | Kingsford-Group |
ff839702e524b288f5c640431e1a0282882b616c | 8,100 | cpp | C++ | project/src/treewalk_interpreter/scanner.cpp | Jeff-Mott-OR/cpplox | 6b2b771c50fd3d0121283d1f2e54860e1d263bca | [
"MIT"
] | 57 | 2018-04-18T11:06:31.000Z | 2022-01-26T22:15:01.000Z | project/src/treewalk_interpreter/scanner.cpp | Jeff-Mott-OR/cpplox | 6b2b771c50fd3d0121283d1f2e54860e1d263bca | [
"MIT"
] | 24 | 2018-04-20T04:24:39.000Z | 2018-11-13T06:11:37.000Z | project/src/treewalk_interpreter/scanner.cpp | Jeff-Mott-OR/cpplox | 6b2b771c50fd3d0121283d1f2e54860e1d263bca | [
"MIT"
] | 6 | 2018-04-19T03:25:35.000Z | 2020-02-20T03:22:52.000Z | #include "scanner.hpp"
#include <cctype>
#include <algorithm>
#include <array>
#include <iterator>
#include <utility>
#include <boost/lexical_cast.hpp>
using std::isalnum;
using std::isalpha;
using std::isdigit;
using std::array;
using std::back_inserter;
using std::copy_if;
using std::find_if;
using std::move;
using std::pair;
using std::string;
using std::to_string;
using boost::lexical_cast;
// Allow the internal linkage section to access names
using namespace motts::lox;
// Not exported (internal linkage)
namespace {
const array<pair<const char*, Token_type>, 18> reserved_words {{
{"and", Token_type::and_},
{"class", Token_type::class_},
{"else", Token_type::else_},
{"false", Token_type::false_},
{"for", Token_type::for_},
{"fun", Token_type::fun_},
{"if", Token_type::if_},
{"nil", Token_type::nil_},
{"or", Token_type::or_},
{"print", Token_type::print_},
{"return", Token_type::return_},
{"super", Token_type::super_},
{"this", Token_type::this_},
{"true", Token_type::true_},
{"var", Token_type::var_},
{"while", Token_type::while_},
{"break", Token_type::break_},
{"continue", Token_type::continue_}
}};
}
// Exported (external linkage)
namespace motts { namespace lox {
Token_iterator::Token_iterator(const string& source) :
source_ {&source},
token_begin_ {source_->cbegin()},
token_end_ {source_->cbegin()},
token_ {consume_token()}
{}
Token_iterator::Token_iterator() = default;
Token_iterator& Token_iterator::operator++() {
if (token_begin_ != source_->end()) {
// We are at the beginning of the next lexeme
token_begin_ = token_end_;
token_ = consume_token();
} else {
source_ = nullptr;
}
return *this;
}
Token_iterator Token_iterator::operator++(int) {
Token_iterator copy {*this};
operator++();
return copy;
}
bool Token_iterator::operator==(const Token_iterator& rhs) const {
return (
(!source_ && !rhs.source_) ||
(source_ == rhs.source_ && token_begin_ == rhs.token_begin_)
);
}
bool Token_iterator::operator!=(const Token_iterator& rhs) const {
return !(*this == rhs);
}
const Token& Token_iterator::operator*() const & {
return token_;
}
Token&& Token_iterator::operator*() && {
return move(token_);
}
const Token* Token_iterator::operator->() const {
return &token_;
}
Token Token_iterator::make_token(Token_type token_type) {
return Token{token_type, string{token_begin_, token_end_}, {}, line_};
}
Token Token_iterator::make_token(Token_type token_type, Literal&& literal_value) {
return Token{token_type, string{token_begin_, token_end_}, move(literal_value), line_};
}
bool Token_iterator::advance_if_match(char expected) {
if (token_end_ != source_->end() && *token_end_ == expected) {
++token_end_;
return true;
}
return false;
}
Token Token_iterator::consume_string() {
while (token_end_ != source_->end() && *token_end_ != '"') {
if (*token_end_ == '\n') {
++line_;
}
++token_end_;
}
// Check unterminated string
if (token_end_ == source_->end()) {
throw Scanner_error{"Unterminated string.", line_};
}
// The closing "
++token_end_;
// Trim surrounding quotes and normalize line endings for literal value
string literal_value;
copy_if(token_begin_ + 1, token_end_ - 1, back_inserter(literal_value), [] (auto c) {
return c != '\r';
});
return make_token(Token_type::string, Literal{move(literal_value)});
}
Token Token_iterator::consume_number() {
while (token_end_ != source_->end() && isdigit(*token_end_)) {
++token_end_;
}
// Look for a fractional part
if (
token_end_ != source_->end() && *token_end_ == '.' &&
(token_end_ + 1) != source_->end() && isdigit(*(token_end_ + 1))
) {
// Consume the "." and one digit
token_end_ += 2;
while (token_end_ != source_->end() && isdigit(*token_end_)) {
++token_end_;
}
}
return make_token(Token_type::number, Literal{lexical_cast<double>(string{token_begin_, token_end_})});
}
Token Token_iterator::consume_identifier() {
while (token_end_ != source_->end() && (isalnum(*token_end_) || *token_end_ == '_')) {
++token_end_;
}
const string identifier {token_begin_, token_end_};
const auto found = find_if(reserved_words.cbegin(), reserved_words.cend(), [&] (const auto& pair) {
return pair.first == identifier;
});
return make_token(found != reserved_words.cend() ? found->second : Token_type::identifier);
}
Token Token_iterator::consume_token() {
// Loop because we might skip some tokens
for (; token_end_ != source_->end(); token_begin_ = token_end_) {
auto c = *token_end_;
++token_end_;
switch (c) {
// Single char tokens
case '(': return make_token(Token_type::left_paren);
case ')': return make_token(Token_type::right_paren);
case '{': return make_token(Token_type::left_brace);
case '}': return make_token(Token_type::right_brace);
case ',': return make_token(Token_type::comma);
case '.': return make_token(Token_type::dot);
case '-': return make_token(Token_type::minus);
case '+': return make_token(Token_type::plus);
case ';': return make_token(Token_type::semicolon);
case '*': return make_token(Token_type::star);
// One or two char tokens
case '/':
if (advance_if_match('/')) {
// A comment goes until the end of the line
while (token_end_ != source_->end() && *token_end_ != '\n') {
++token_end_;
}
continue;
} else {
return make_token(Token_type::slash);
}
case '!':
return make_token(advance_if_match('=') ? Token_type::bang_equal : Token_type::bang);
case '=':
return make_token(advance_if_match('=') ? Token_type::equal_equal : Token_type::equal);
case '>':
return make_token(advance_if_match('=') ? Token_type::greater_equal : Token_type::greater);
case '<':
return make_token(advance_if_match('=') ? Token_type::less_equal : Token_type::less);
// Whitespace
case '\n':
++line_;
continue;
case ' ':
case '\r':
case '\t':
continue;
// Literals and Keywords
case '"': return consume_string();
default:
if (isdigit(c)) {
return consume_number();
} else if (isalpha(c) || c == '_') {
return consume_identifier();
} else {
throw Scanner_error{"Unexpected character.", line_};
}
}
}
// The final token is always EOF
return Token{Token_type::eof, "", {}, line_};
}
Scanner_error::Scanner_error(const string& what, int line) :
Runtime_error {"[Line " + to_string(line) + "] Error: " + what}
{}
}}
| 31.395349 | 111 | 0.534815 | Jeff-Mott-OR |
ff8569555ece5c7cf7ea227a9e981e6cfda0efd4 | 4,915 | hpp | C++ | ndn-cxx/encoding/estimator.hpp | AsteriosPar/ndn-cxx | 778ad714f0d6dff8f5e75bdfea2658002b95bbd1 | [
"OpenSSL"
] | null | null | null | ndn-cxx/encoding/estimator.hpp | AsteriosPar/ndn-cxx | 778ad714f0d6dff8f5e75bdfea2658002b95bbd1 | [
"OpenSSL"
] | null | null | null | ndn-cxx/encoding/estimator.hpp | AsteriosPar/ndn-cxx | 778ad714f0d6dff8f5e75bdfea2658002b95bbd1 | [
"OpenSSL"
] | null | null | null | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2013-2022 Regents of the University of California.
*
* This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
*
* ndn-cxx library is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* ndn-cxx 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 GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of ndn-cxx authors and contributors.
*/
#ifndef NDN_CXX_ENCODING_ESTIMATOR_HPP
#define NDN_CXX_ENCODING_ESTIMATOR_HPP
#include "ndn-cxx/encoding/block.hpp"
namespace ndn {
namespace encoding {
/**
* @brief Helper class to estimate size of TLV encoding.
*
* The interface of this class (mostly) matches that of the Encoder class.
*
* @sa Encoder
*/
class Estimator : noncopyable
{
public: // common interface between Encoder and Estimator
/**
* @brief Prepend a sequence of bytes
*/
constexpr size_t
prependBytes(span<const uint8_t> bytes) const noexcept
{
return bytes.size();
}
/**
* @brief Append a sequence of bytes
*/
constexpr size_t
appendBytes(span<const uint8_t> bytes) const noexcept
{
return bytes.size();
}
/**
* @brief Prepend a single byte
* @deprecated
*/
[[deprecated("use prependBytes()")]]
constexpr size_t
prependByte(uint8_t) const noexcept
{
return 1;
}
/**
* @brief Append a single byte
* @deprecated
*/
[[deprecated("use appendBytes()")]]
constexpr size_t
appendByte(uint8_t) const noexcept
{
return 1;
}
/**
* @brief Prepend a byte array @p array of length @p length
* @deprecated
*/
[[deprecated("use prependBytes()")]]
constexpr size_t
prependByteArray(const uint8_t*, size_t length) const noexcept
{
return length;
}
/**
* @brief Append a byte array @p array of length @p length
* @deprecated
*/
[[deprecated("use appendBytes()")]]
constexpr size_t
appendByteArray(const uint8_t*, size_t length) const noexcept
{
return length;
}
/**
* @brief Prepend bytes from the range [@p first, @p last)
*/
template<class Iterator>
constexpr size_t
prependRange(Iterator first, Iterator last) const noexcept
{
return std::distance(first, last);
}
/**
* @brief Append bytes from the range [@p first, @p last)
*/
template<class Iterator>
constexpr size_t
appendRange(Iterator first, Iterator last) const noexcept
{
return std::distance(first, last);
}
/**
* @brief Prepend @p n in VarNumber encoding
*/
constexpr size_t
prependVarNumber(uint64_t n) const noexcept
{
return tlv::sizeOfVarNumber(n);
}
/**
* @brief Append @p n in VarNumber encoding
*/
constexpr size_t
appendVarNumber(uint64_t n) const noexcept
{
return tlv::sizeOfVarNumber(n);
}
/**
* @brief Prepend @p n in NonNegativeInteger encoding
*/
constexpr size_t
prependNonNegativeInteger(uint64_t n) const noexcept
{
return tlv::sizeOfNonNegativeInteger(n);
}
/**
* @brief Append @p n in NonNegativeInteger encoding
*/
constexpr size_t
appendNonNegativeInteger(uint64_t n) const noexcept
{
return tlv::sizeOfNonNegativeInteger(n);
}
/**
* @brief Prepend TLV block of type @p type and value from buffer @p array of size @p arraySize
* @deprecated
*/
[[deprecated("use encoding::prependBinaryBlock()")]]
constexpr size_t
prependByteArrayBlock(uint32_t type, const uint8_t* array, size_t arraySize) const noexcept
{
return tlv::sizeOfVarNumber(type) + tlv::sizeOfVarNumber(arraySize) + arraySize;
}
/**
* @brief Append TLV block of type @p type and value from buffer @p array of size @p arraySize
* @deprecated
*/
[[deprecated]]
constexpr size_t
appendByteArrayBlock(uint32_t type, const uint8_t* array, size_t arraySize) const noexcept
{
return tlv::sizeOfVarNumber(type) + tlv::sizeOfVarNumber(arraySize) + arraySize;
}
/**
* @brief Prepend TLV block @p block
* @deprecated
*/
[[deprecated("use encoding::prependBlock()")]]
size_t
prependBlock(const Block& block) const;
/**
* @brief Append TLV block @p block
* @deprecated
*/
[[deprecated]]
size_t
appendBlock(const Block& block) const;
};
} // namespace encoding
} // namespace ndn
#endif // NDN_CXX_ENCODING_ESTIMATOR_HPP
| 24.452736 | 97 | 0.687284 | AsteriosPar |
ff86cc6e6d5cde82a5369865a56a3e333ea45ff8 | 5,788 | cpp | C++ | tests/garbage_collection/gc_delete_test_coop.cpp | saurabhkadekodi/peloton-p3 | e0d84cdf59c0724850ad2d6b187fdb2ef1730369 | [
"Apache-2.0"
] | 1 | 2021-02-28T19:37:04.000Z | 2021-02-28T19:37:04.000Z | tests/garbage_collection/gc_delete_test_coop.cpp | saurabhkadekodi/peloton-p3 | e0d84cdf59c0724850ad2d6b187fdb2ef1730369 | [
"Apache-2.0"
] | 1 | 2016-05-06T05:07:37.000Z | 2016-05-09T23:40:50.000Z | tests/garbage_collection/gc_delete_test_coop.cpp | saurabhkadekodi/peloton-p3 | e0d84cdf59c0724850ad2d6b187fdb2ef1730369 | [
"Apache-2.0"
] | null | null | null | //===----------------------------------------------------------------------===//
//
// Peloton
//
// gc_delete_test_coop.cpp
//
// Identification: tests/executor/gc_delete_test_coop.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <atomic>
#include "harness.h"
#include "backend/catalog/schema.h"
#include "backend/common/value_factory.h"
#include "backend/common/types.h"
#include "backend/common/pool.h"
#include "backend/executor/executor_context.h"
#include "backend/executor/delete_executor.h"
#include "backend/executor/insert_executor.h"
#include "backend/executor/seq_scan_executor.h"
#include "backend/executor/update_executor.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/expression/expression_util.h"
#include "backend/expression/tuple_value_expression.h"
#include "backend/expression/comparison_expression.h"
#include "backend/expression/abstract_expression.h"
#include "backend/storage/tile.h"
#include "backend/storage/tile_group.h"
#include "backend/storage/table_factory.h"
#include "backend/concurrency/transaction_manager_factory.h"
#include "executor/executor_tests_util.h"
#include "executor/mock_executor.h"
#include "backend/planner/delete_plan.h"
#include "backend/planner/insert_plan.h"
#include "backend/planner/seq_scan_plan.h"
#include "backend/planner/update_plan.h"
using ::testing::NotNull;
using ::testing::Return;
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// GC Tests
//===--------------------------------------------------------------------===//
class GCDeleteTestCoop : public PelotonTest {};
std::atomic<int> tuple_id;
std::atomic<int> delete_tuple_id;
enum GCType type = GC_TYPE_COOPERATIVE;
void InsertTuple(storage::DataTable *table, VarlenPool *pool) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
for (oid_t tuple_itr = 0; tuple_itr < 10; tuple_itr++) {
auto tuple = ExecutorTestsUtil::GetTuple(table, ++tuple_id, pool);
planner::InsertPlan node(table, std::move(tuple));
executor::InsertExecutor executor(&node, context.get());
executor.Execute();
}
txn_manager.CommitTransaction();
}
void DeleteTuple(storage::DataTable *table) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
std::vector<storage::Tuple *> tuples;
// Delete
planner::DeletePlan delete_node(table, false);
executor::DeleteExecutor delete_executor(&delete_node, context.get());
// Predicate
// WHERE ATTR_0 > 60
expression::TupleValueExpression *tup_val_exp =
new expression::TupleValueExpression(VALUE_TYPE_INTEGER, 0, 0);
expression::ConstantValueExpression *const_val_exp =
new expression::ConstantValueExpression(
ValueFactory::GetIntegerValue(60));
auto predicate = new expression::ComparisonExpression<expression::CmpGt>(
EXPRESSION_TYPE_COMPARE_GREATERTHAN, tup_val_exp, const_val_exp);
// Seq scan
std::vector<oid_t> column_ids = {0};
std::unique_ptr<planner::SeqScanPlan> seq_scan_node(
new planner::SeqScanPlan(table, predicate, column_ids));
executor::SeqScanExecutor seq_scan_executor(seq_scan_node.get(),
context.get());
// Parent-Child relationship
delete_node.AddChild(std::move(seq_scan_node));
delete_executor.AddChild(&seq_scan_executor);
EXPECT_TRUE(delete_executor.Init());
EXPECT_TRUE(delete_executor.Execute());
// EXPECT_TRUE(delete_executor.Execute());
txn_manager.CommitTransaction();
}
TEST_F(GCDeleteTestCoop, DeleteTest) {
peloton::gc::GCManagerFactory::Configure(type);
peloton::gc::GCManagerFactory::GetInstance().StartGC();
auto *table = ExecutorTestsUtil::CreateTable(1024);
auto &manager = catalog::Manager::GetInstance();
storage::Database db(DEFAULT_DB_ID);
manager.AddDatabase(&db);
db.AddTable(table);
// We are going to insert a tile group into a table in this test
auto testing_pool = TestingHarness::GetInstance().GetTestingPool();
auto before_insert = catalog::Manager::GetInstance().GetMemoryFootprint();
LaunchParallelTest(1, InsertTuple, table, testing_pool);
auto after_insert = catalog::Manager::GetInstance().GetMemoryFootprint();
EXPECT_GT(after_insert, before_insert);
LaunchParallelTest(1, DeleteTuple, table);
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
LOG_INFO("new transaction");
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
// Seq scan
std::vector<oid_t> column_ids = {0};
planner::SeqScanPlan seq_scan_node(table, nullptr, column_ids);
executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get());
EXPECT_TRUE(seq_scan_executor.Init());
auto tuple_cnt = 0;
while (seq_scan_executor.Execute()) {
std::unique_ptr<executor::LogicalTile> result_logical_tile(
seq_scan_executor.GetOutput());
tuple_cnt += result_logical_tile->GetTupleCount();
}
txn_manager.CommitTransaction();
EXPECT_EQ(tuple_cnt, 6);
auto after_delete = catalog::Manager::GetInstance().GetMemoryFootprint();
EXPECT_EQ(after_insert, after_delete);
tuple_id = 0;
}
} // namespace test
} // namespace peloton
| 34.047059 | 80 | 0.708189 | saurabhkadekodi |
ff890b6b971421fee391cde01067e0b42d7c1210 | 2,264 | cxx | C++ | retro/cores/atari2600/stella/src/debugger/PackedBitArray.cxx | MatPoliquin/retro | c70c174a9818d1e97bc36e61abb4694d28fc68e1 | [
"MIT-0",
"MIT"
] | 2,706 | 2018-04-05T18:28:50.000Z | 2022-03-29T16:56:59.000Z | retro/cores/atari2600/stella/src/debugger/PackedBitArray.cxx | MatPoliquin/retro | c70c174a9818d1e97bc36e61abb4694d28fc68e1 | [
"MIT-0",
"MIT"
] | 242 | 2018-04-05T22:30:42.000Z | 2022-03-19T01:55:11.000Z | retro/cores/atari2600/stella/src/debugger/PackedBitArray.cxx | MatPoliquin/retro | c70c174a9818d1e97bc36e61abb4694d28fc68e1 | [
"MIT-0",
"MIT"
] | 464 | 2018-04-05T19:10:34.000Z | 2022-03-28T13:33:32.000Z | //============================================================================
//
// SSSS tt lll lll
// SS SS tt ll ll
// SS tttttt eeee ll ll aaaa
// SSSS tt ee ee ll ll aa
// SS tt eeeeee ll ll aaaaa -- "An Atari 2600 VCS Emulator"
// SS SS tt ee ll ll aa aa
// SSSS ttt eeeee llll llll aaaaa
//
// Copyright (c) 1995-2014 by Bradford W. Mott, Stephen Anthony
// and the Stella Team
//
// See the file "License.txt" for information on usage and redistribution of
// this file, and for a DISCLAIMER OF ALL WARRANTIES.
//
// $Id: PackedBitArray.cxx 2838 2014-01-17 23:34:03Z stephena $
//============================================================================
#include "bspf.hxx"
#include "PackedBitArray.hxx"
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PackedBitArray::PackedBitArray(uInt32 length)
: words(length / wordSize + 1)
{
bits = new uInt32[ words ];
for(uInt32 i = 0; i < words; ++i)
bits[i] = 0;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PackedBitArray::~PackedBitArray()
{
delete[] bits;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
uInt32 PackedBitArray::isSet(uInt32 bit) const
{
uInt32 word = bit / wordSize;
bit %= wordSize;
return (bits[word] & (1 << bit));
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
uInt32 PackedBitArray::isClear(uInt32 bit) const
{
uInt32 word = bit / wordSize;
bit %= wordSize;
return !(bits[word] & (1 << bit));
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void PackedBitArray::toggle(uInt32 bit)
{
uInt32 word = bit / wordSize;
bit %= wordSize;
bits[word] ^= (1 << bit);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void PackedBitArray::set(uInt32 bit)
{
uInt32 word = bit / wordSize;
bit %= wordSize;
bits[word] |= (1 << bit);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void PackedBitArray::clear(uInt32 bit)
{
uInt32 word = bit / wordSize;
bit %= wordSize;
bits[word] &= (~(1 << bit));
}
| 27.277108 | 78 | 0.412544 | MatPoliquin |