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 float64 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 float64 1 77k ⌀ | 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 float64 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 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d8c04a13313137cf5a7cf0c58c970a13042dcce3 | 376 | cpp | C++ | patterns/adapter/main.cpp | PotatoMaster101/pats | 7429125a4b34fa1ba4ad6710a1753a547909f73c | [
"MIT"
] | null | null | null | patterns/adapter/main.cpp | PotatoMaster101/pats | 7429125a4b34fa1ba4ad6710a1753a547909f73c | [
"MIT"
] | null | null | null | patterns/adapter/main.cpp | PotatoMaster101/pats | 7429125a4b34fa1ba4ad6710a1753a547909f73c | [
"MIT"
] | null | null | null | #include <iostream>
#include <memory>
#include "adapter.hpp"
int main(int argc, const char *argv[]) {
auto legacy = std::make_unique<legacy_rect>(1, 2, 3, 4); // x1 x2 y1 y2
auto modern = std::make_unique<rect_adapter>(1, 2, 3, 4); // x y w h
legacy->legacy_print(); // prints 1 3 2 4
modern->print(); // prints 1 4 2 6
return 0;
}
| 31.333333 | 78 | 0.582447 |
d8c07138e588daf79752f92dbe2f0522ae53bc14 | 887 | cpp | C++ | ExemploExcecoesTryCatchThrow/ClasseHerdeiraException.cpp | lucaslgr/LearningCplusplus | 579e4ddc8a55605af9b46e24bfb91897d3be0274 | [
"MIT"
] | 1 | 2020-07-14T16:49:52.000Z | 2020-07-14T16:49:52.000Z | ExemploExcecoesTryCatchThrow/ClasseHerdeiraException.cpp | lucaslgr/LearningCplusplus | 579e4ddc8a55605af9b46e24bfb91897d3be0274 | [
"MIT"
] | null | null | null | ExemploExcecoesTryCatchThrow/ClasseHerdeiraException.cpp | lucaslgr/LearningCplusplus | 579e4ddc8a55605af9b46e24bfb91897d3be0274 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string.h>
#include <exception>
using namespace std;
class ExcecaoCustomizada : public exception
{
protected:
char msg[100];
public:
ExcecaoCustomizada(const char* e)
{
strcpy(msg, e);
}
virtual const char* what()
{
return msg;
}
};
int fat (int n)
{
if (n < 0) {
throw ExcecaoCustomizada("Numero negativo!!");
}
if (n == 0 || n == 1) {
return 1;
}
return (n * fat(n - 1));
}
int main (int agrc, const char *agrv[])
{
try
{
cout << "Fatorial de 5: " << fat(5) << endl;
cout << "Fatorial de -5: " << fat(-5) << endl;
}
catch(ExcecaoCustomizada e)
{
std::cerr << "Erro:" << e.what() << '\n';
}
catch(...)
{
cerr << "Qualquer erro!" << endl;
}
return 0;
} | 17.392157 | 54 | 0.470124 |
d8cd55713bb6d0e47bcf9a195ec14a4b22825b20 | 765 | cpp | C++ | lib/Dialect/XTen/IR/XTenDialect.cpp | jcamacho1234/mlir-xten | 721f97fc01dd39a2f54ef3b409ceb5a9528c61f4 | [
"Apache-2.0"
] | 10 | 2021-11-05T00:08:47.000Z | 2022-02-09T20:12:56.000Z | lib/Dialect/XTen/IR/XTenDialect.cpp | jcamacho1234/mlir-xten | 721f97fc01dd39a2f54ef3b409ceb5a9528c61f4 | [
"Apache-2.0"
] | 1 | 2022-01-27T17:21:14.000Z | 2022-01-27T17:22:41.000Z | lib/Dialect/XTen/IR/XTenDialect.cpp | jcamacho1234/mlir-xten | 721f97fc01dd39a2f54ef3b409ceb5a9528c61f4 | [
"Apache-2.0"
] | 6 | 2021-11-10T06:49:47.000Z | 2021-12-22T19:02:48.000Z | //===- XTenDialect.cpp ------------------------------------------*- C++ -*-===//
//
// This file is licensed 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
//
// (c) Copyright 2021 Xilinx Inc.
//
//===----------------------------------------------------------------------===//
#include "xten/Dialect/XTen/XTenDialect.h"
#include "xten/Dialect/XTen/XTenOps.h"
#include "mlir/IR/DialectImplementation.h"
#include "xten/Dialect/XTen/XTenOpsDialect.cpp.inc"
using namespace mlir;
using namespace xilinx::xten;
void XTenDialect::initialize() {
addOperations<
#define GET_OP_LIST
#include "xten/Dialect/XTen/XTenOps.cpp.inc"
>();
}
| 27.321429 | 80 | 0.605229 |
d8d336b7d950ba8da6e2731acc03269305ba9c66 | 3,136 | cpp | C++ | Misc/foobarnowplayingannouncer.cpp | exscape/lyricusqt | 69c9fc3c38833459493f136f65c9ede8940f0d77 | [
"MIT"
] | null | null | null | Misc/foobarnowplayingannouncer.cpp | exscape/lyricusqt | 69c9fc3c38833459493f136f65c9ede8940f0d77 | [
"MIT"
] | null | null | null | Misc/foobarnowplayingannouncer.cpp | exscape/lyricusqt | 69c9fc3c38833459493f136f65c9ede8940f0d77 | [
"MIT"
] | null | null | null | #include "foobarnowplayingannouncer.h"
#include <QDebug>
#include <QThread>
#include <QFile>
// This should be more than enough, since the struct is smaller
#define BUFSIZE 2048
struct songInfo {
// These are in UTF-8; use QString::fromUtf8() to create a QString
char artist[512];
char title[512];
char path[512];
};
FoobarNowPlayingAnnouncer::FoobarNowPlayingAnnouncer(QObject *parent) : QObject(parent) {
}
void FoobarNowPlayingAnnouncer::run() {
char *responseData = (char *)HeapAlloc(GetProcessHeap(), 0, BUFSIZE);
if (!responseData) {
qWarning() << "Unable to allocate memory for foo_simpleserver_announce response data";
return;
}
bool initial_run = true;
// Loop retrying to connect to the pipe, in case it fails (or disconnects after initially succeeding)
while (true) {
restart_loop:
if (!initial_run) {
QThread::sleep(5);
}
else
initial_run = false;
HANDLE hPipe = CreateFile(TEXT("\\\\.\\pipe\\foo_simpleserver_announce"), GENERIC_READ | FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hPipe == INVALID_HANDLE_VALUE) {
// qWarning() << "Unable to connect to foo_simpleserver_announce pipe";
continue;
}
DWORD mode = PIPE_READMODE_MESSAGE;
if (!SetNamedPipeHandleState(hPipe, &mode, NULL, NULL)) {
qWarning() << "Unable to set PIPE_READMODE_MESSAGE for foo_simpleserver_announce pipe";
CloseHandle(hPipe);
continue;
}
// Loop while connected to this pipe
while (true) {
DWORD bytes_read = 0;
bool success = ReadFile(hPipe, responseData, BUFSIZE, &bytes_read, NULL);
if (!success) {
qWarning() << "foo_simpleserver_announce ReadFile failed; GetLastError() ==" << GetLastError();
CloseHandle(hPipe);
goto restart_loop; // Weee!
}
if (bytes_read != sizeof(struct songInfo)) {
qWarning() << "foo_simpleserver_announce read failed: unexpected data size" << bytes_read << "bytes";
CloseHandle(hPipe);
goto restart_loop; // Weee!
}
struct songInfo *info = reinterpret_cast<struct songInfo *>(responseData);
QString artist = QString::fromUtf8(info->artist);
QString title = QString::fromUtf8(info->title);
QString path = QString::fromUtf8(info->path);
if (path.startsWith("file://"))
path = path.right(path.length() - 7);
if (artist.length() > 0 && title.length() > 0) {
lastArtist = artist;
lastTitle = title;
lastPath = path;
emit newTrack(artist, title, path); // Note that path may be 0-length -- though it should never be
}
}
}
// This won't ever be reached... oh well.
HeapFree(GetProcessHeap(), 0, responseData);
}
void FoobarNowPlayingAnnouncer::reEmitLastTrack() {
emit newTrack(lastArtist, lastTitle, lastPath);
}
| 34.461538 | 153 | 0.601403 |
d8d41db745f162d061bcb56fdf849608ac910537 | 1,179 | cpp | C++ | Shoot/src/Color.cpp | franticsoftware/vlad-heavy-strike | a4da4df617e9ccd6ebd9819ad166d892924638ce | [
"MIT"
] | 3 | 2019-10-04T19:44:44.000Z | 2021-07-27T15:59:39.000Z | Shoot/src/Color.cpp | franticsoftware/vlad-heavy-strike | a4da4df617e9ccd6ebd9819ad166d892924638ce | [
"MIT"
] | 1 | 2019-07-20T05:36:31.000Z | 2019-07-20T22:22:49.000Z | Shoot/src/Color.cpp | aminere/vlad-heavy-strike | a4da4df617e9ccd6ebd9819ad166d892924638ce | [
"MIT"
] | null | null | null | /*
Amine Rehioui
Created: May 1st 2010
*/
#include "Shoot.h"
#include "Color.h"
namespace shoot
{
// static variables initialization
Color Color::Red = Color(1.0f, 0.0f, 0.0f, 1.0f);
Color Color::Green = Color(0.0f, 1.0f, 0.0f, 1.0f);
Color Color::Blue = Color(0.0f, 0.0f, 1.0f, 1.0f);
Color Color::White = Color(1.0f, 1.0f, 1.0f, 1.0f);
Color Color::Black = Color(0.0f, 0.0f, 0.0f, 1.0f);
Color Color::Yellow = Color(1.0f, 1.0f, 0.0f, 1.0f);
Color Color::Zero = Color(0.0f, 0.0f, 0.0f, 0.0f);
//! constructor
Color::Color() : R(1.0f), G(1.0f), B(1.0f), A(1.0f)
{
}
bool Color::operator == (const Color& other) const
{
return (Math::FEqual(R, other.R)
&& Math::FEqual(G, other.G)
&& Math::FEqual(B, other.B)
&& Math::FEqual(A, other.A));
}
Color Color::operator + (const Color& other) const
{
Color result(R+other.R, G+other.G, B+other.B, A+other.A);
return result;
}
Color Color::operator - (const Color& other) const
{
Color result(R-other.R, G-other.G, B-other.B, A-other.A);
return result;
}
Color Color::operator * (f32 fValue) const
{
Color result(R*fValue, G*fValue, B*fValue, A*fValue);
return result;
}
}
| 21.436364 | 59 | 0.617472 |
d8deb83ab03c9ca632a51a4283072a78d2a0add6 | 9,846 | cpp | C++ | src/main.cpp | katsumin/HomeM5 | ca0cf55e3d6a415d2a07d9adcc81b1f9c9a3b021 | [
"MIT"
] | null | null | null | src/main.cpp | katsumin/HomeM5 | ca0cf55e3d6a415d2a07d9adcc81b1f9c9a3b021 | [
"MIT"
] | null | null | null | src/main.cpp | katsumin/HomeM5 | ca0cf55e3d6a415d2a07d9adcc81b1f9c9a3b021 | [
"MIT"
] | null | null | null | #include <queue>
#include <M5Stack.h>
#include <time.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <Ethernet.h>
#include <Wire.h>
#include <BME280_t.h> // import BME280 template library
#include "InfluxDb.h"
#include "smartmeter.h"
#include "config.h"
#include "debugView.h"
#include "FunctionButton.h"
#include "MainView.h"
#include "HeadView.h"
#include "PowerView.h"
#include "Rtc.h"
#include "EchonetUdp.h"
#include "Ecocute.h"
#include "Aircon.h"
#include "log.h"
#include "DataStore.h"
#include "View.h"
#define SCK 18
#define MISO 19
#define MOSI 23
#define CS 26
// #define TEST
// instances
FunctionButton btnA(&M5.BtnA);
FunctionButton btnB(&M5.BtnB);
FunctionButton btnC(&M5.BtnC);
DebugView debugView(0, 100, 320, SCROLL_SIZE * 10);
InfluxDb influx(INFLUX_SERVER, INFLUX_DB);
SmartMeter sm;
NtpClient ntp;
Rtc rtc;
DataStore dataStore;
MainView mainView(&dataStore);
PowerView powerView(&dataStore, &rtc);
ViewController viewController;
/*
スマートメータ接続タスク
*/
void bp35c0_monitoring_task(void *arm)
{
// bJoined = false;
Serial.println("task start");
// bTaskRunning = true;
// スマートメータ接続
sm.disconnect();
delay(500);
sm.connect(PWD, BID);
Serial.println("task stop");
vTaskDelete(NULL);
}
#define TIMEZONE 9 * 3600
boolean rcvEv29 = false;
void bp35c0_polling()
{
int res;
char buf[1024];
RCV_CODE code = sm.polling(buf, sizeof(buf));
switch (code)
{
case RCV_CODE::ERXUDP:
case RCV_CODE::OTHER:
// UDP受信
debugView.output(buf);
sd_log.out(buf);
break;
case RCV_CODE::ERXUDP_E7:
dataStore.setPower(sm.getPower());
snprintf(buf, sizeof(buf), "power value=%ld", sm.getPower());
debugView.output(buf);
res = influx.write(buf);
debugView.output(res);
break;
case RCV_CODE::ERXUDP_EAB:
dataStore.setWattHourPlus(sm.getWattHourPlus(), sm.getTimePlus() + TIMEZONE);
dataStore.setWattHourMinus(sm.getWattHourMinus(), sm.getTimeMinus() + TIMEZONE);
snprintf(buf, sizeof(buf), "+power value=%.1f %ld000000000", sm.getWattHourPlus(), sm.getTimePlus());
debugView.output(buf);
res = influx.write(buf);
debugView.output(res);
snprintf(buf, sizeof(buf), "-power value=%.1f %ld000000000", sm.getWattHourMinus(), sm.getTimeMinus());
debugView.output(buf);
res = influx.write(buf);
debugView.output(res);
if (rcvEv29)
{
// EVENT29受信からEVENT25受信しなかったら、再接続開始
xTaskCreate(&bp35c0_monitoring_task, "bp35c0r", 4096, NULL, 5, NULL);
rcvEv29 = false;
}
break;
case RCV_CODE::EVENT_25:
// 接続完了 → 要求コマンドを開始
sm.setConnectState(CONNECT_STATE::CONNECTED);
Serial.println("EV25");
sd_log.out("EV25");
sm.request();
rcvEv29 = false;
break;
case RCV_CODE::EVENT_26:
// セッション切断要求 → 再接続開始
case RCV_CODE::EVENT_27:
// PANA セッションの終了に成功 → 再接続開始
case RCV_CODE::EVENT_28:
// PANA セッションの終了要求に対する応答がなくタイムアウトした(セッションは終了) → 再接続開始
Serial.println("EV26-28");
sd_log.out("EV26-28");
xTaskCreate(&bp35c0_monitoring_task, "bp35c0r", 4096, NULL, 5, NULL);
break;
case RCV_CODE::EVENT_29:
// セッション期限切れ → 送信を止め、'EVENT 25'を待つ
sm.setConnectState(CONNECT_STATE::CONNECTING);
Serial.println("EV29");
sd_log.out("EV29");
rcvEv29 = true;
break;
case RCV_CODE::TIMEOUT:
default:
break;
}
}
boolean bEco = false;
void ecocuteCallback(Ecocute *ec)
{
// sd_log.out("Ecocute callback");
Serial.println("Ecocute callback");
bEco = true;
}
boolean bAir = false;
void airconCallback(Aircon *ac)
{
// sd_log.out("Aircon callback");
Serial.println("Aircon callback");
bAir = true;
}
void callbackNtp(void *arg)
{
Serial.println("callbacked !");
btnB.enable("NTP");
}
WiFiMulti wm;
void nw_init()
{
Serial.println();
SPI.begin(SCK, MISO, MOSI, -1);
Ethernet.init(CS); // Ethernet/Ethernet2
IPAddress addr;
char buf[64];
UDP *udpNtp = nullptr;
UDP *udpEchonet = nullptr;
if (Ethernet.linkStatus() == LinkON) // Ethernet
{
// Ethernet
Serial.println("Ethernet connected");
Serial.println("IP address: ");
Ethernet.begin(mac);
addr = Ethernet.localIP();
influx.setEthernet(true);
snprintf(buf, sizeof(buf), "%s(Ethernet)", addr.toString().c_str());
headView.setNwType("Ethernet");
udpNtp = new EthernetUDP();
udpEchonet = new EthernetUDP();
}
else
{
// WiFi
Serial.print("Connecting to WIFI");
wm.addAP(WIFI_SSID, WIFI_PASS);
while (wm.run() != WL_CONNECTED)
{
Serial.print(".");
delay(100);
}
Serial.println("WiFi connected");
Serial.println("IP address: ");
addr = WiFi.localIP();
influx.setEthernet(false);
snprintf(buf, sizeof(buf), "%s(WiFi)", addr.toString().c_str());
headView.setNwType("WiFi");
udpNtp = new WiFiUDP();
udpEchonet = new WiFiUDP();
}
Serial.println(buf);
headView.setIpAddress(addr);
// RTC
ntp.init(udpNtp, (char *)NTP_SERVER, random(10000, 19999));
ntp.setCallback(callbackNtp, nullptr);
rtc.init(&ntp);
// echonet
echonetUdp.init(udpEchonet);
// ecocute
ecocute.init(&echonetUdp, ECOCUTE_ADDRESS, ecocuteCallback);
// aircon
aircon.init(&echonetUdp, AIRCON_ADDRESS, airconCallback);
}
BME280<> BMESensor; // instantiate sensor
void updateBme(boolean withInflux)
{
while (true)
{
BMESensor.refresh(); // read current sensor data
float p = BMESensor.pressure;
if (p >= 90000.0)
break;
Serial.println(p);
delay(100);
}
dataStore.setTemperature(BMESensor.temperature);
dataStore.setHumidity(BMESensor.humidity);
dataStore.setPressure(BMESensor.pressure / 100.0F);
if (withInflux)
{
char buf[64];
snprintf(buf, sizeof(buf), "room temp=%.1f,hum=%.1f,press=%.1f", BMESensor.temperature, BMESensor.humidity, BMESensor.pressure / 100.0F);
debugView.output(buf);
int res = influx.write(buf);
debugView.output(res);
}
}
#define VIEWKEY_MAIN ((const char *)"MAIN")
#define VIEWKEY_POWER ((const char *)"POWER")
CONNECT_STATE preState;
void setup()
{
M5.begin();
// DataStore
dataStore.init();
// View
M5.Lcd.clear();
headView.init();
headView.setRtc(&rtc);
sd_log.setRtc(&rtc);
viewController.setView(VIEWKEY_MAIN, &mainView, VIEWKEY_POWER);
viewController.setView(VIEWKEY_POWER, &powerView, VIEWKEY_MAIN);
viewController.changeNext();
// スマートメータ
sm.setDebugView(&debugView);
sm.init();
preState = sm.getConnectState();
btnA.enable("JOIN");
btnC.enable(viewController.getNextKey());
// LAN
btnB.disable("NTP");
nw_init();
// Sensor
Wire.begin(GPIO_NUM_21, GPIO_NUM_22); // initialize I2C that connects to sensor
#ifndef TEST
BMESensor.begin(); // initalize bme280 sensor
updateBme(true);
#endif
// delay(1000);
ecocute.request();
aircon.request();
}
time_t rtcTest = 0;
float wattHourTest = 0.0;
unsigned long preMeas = millis();
unsigned long preView = preMeas;
#define INTERVAL (120 * 1000)
#define VIEW_INTERVAL (1000)
void loop()
{
CONNECT_STATE curState = sm.getConnectState();
if (curState != preState)
{
// スマートメータ 状態変化
switch (curState)
{
case CONNECT_STATE::CONNECTED:
btnA.enable("TERM");
break;
case CONNECT_STATE::DISCONNECTED:
btnA.enable("JOIN");
break;
case CONNECT_STATE::CONNECTING:
btnA.disable("CONNECTING");
for (int i = 0; i < 7; i++)
sd_log.out(sm.getScnannedParam(i));
break;
case CONNECT_STATE::SCANNING:
btnA.disable("SCANNING");
break;
}
}
#ifndef TEST
if (curState == CONNECT_STATE::CONNECTED || curState == CONNECT_STATE::CONNECTING)
{
bp35c0_polling();
}
#else
bp35c0_polling();
#endif
preState = curState;
long cur = millis();
long d = cur - preMeas;
if (d < 0)
d += ULONG_MAX;
if (d >= INTERVAL) // debug
{
preMeas = cur;
char buf[64];
snprintf(buf, sizeof(buf), "%ld -> %ld, memory(%d)", preMeas, d, xPortGetFreeHeapSize());
debugView.output(buf);
// BME280
#ifndef TEST
updateBme(true);
#endif
// smartmeter
if (curState == CONNECT_STATE::CONNECTED)
{
// 要求コマンド送信
sm.request();
}
// ecocute
ecocute.request();
// aircon
aircon.request();
}
char buf[64];
if (bEco)
{
dataStore.setEcoPower(ecocute.getPower());
dataStore.setEcoTank(ecocute.getTank());
snprintf(buf, sizeof(buf), "ecocute power=%ld,powerSum=%ld,tank=%ld", ecocute.getPower(), ecocute.getTotalPower(), ecocute.getTank());
debugView.output(buf);
int res = influx.write(buf);
debugView.output(res);
bEco = false;
}
if (bAir)
{
dataStore.setAirPower(aircon.getPower());
dataStore.setAirTempOut(aircon.getTempOut());
dataStore.setAirTempRoom(aircon.getTempRoom());
snprintf(buf, sizeof(buf), "aircon power=%ld,tempOut=%ld,tempRoom=%ld", aircon.getPower(), aircon.getTempOut(), aircon.getTempRoom());
debugView.output(buf);
int res = influx.write(buf);
debugView.output(res);
bAir = false;
}
d = cur - preView;
if (d < 0)
d += ULONG_MAX;
if (d >= VIEW_INTERVAL)
{
preView = cur;
headView.update();
viewController.update();
}
if (btnA.isEnable() && btnA.getButton()->wasPressed())
{
switch (curState)
{
case CONNECT_STATE::CONNECTED:
// 切断
sm.disconnect();
break;
case CONNECT_STATE::DISCONNECTED:
// 接続
xTaskCreate(&bp35c0_monitoring_task, "bp35c0r", 4096, NULL, 5, NULL);
break;
case CONNECT_STATE::CONNECTING:
break;
case CONNECT_STATE::SCANNING:
break;
}
}
else if (btnB.isEnable() && btnB.getButton()->wasPressed())
{
rtc.adjust();
btnB.disable("NTP");
}
else if (btnC.isEnable() && btnC.getButton()->wasPressed())
{
viewController.changeNext();
btnC.enable(viewController.getNextKey());
}
delay(1);
M5.update();
} | 24.132353 | 141 | 0.657323 |
d8df3c1daffa3d064eeca194082eebff5b91e34e | 311 | cpp | C++ | legion/engine/llri-dx/llri.cpp | Rythe-Interactive/Legion-LLRI | e0cc449cc8c2ba0701a73b8c07b80ccfd8f20477 | [
"MIT"
] | 16 | 2021-09-10T18:11:37.000Z | 2022-01-26T06:28:51.000Z | legion/engine/llri-dx/llri.cpp | Rythe-Interactive/Legion-LLRI | e0cc449cc8c2ba0701a73b8c07b80ccfd8f20477 | [
"MIT"
] | 13 | 2021-09-12T16:28:47.000Z | 2022-02-07T19:34:01.000Z | legion/engine/llri-dx/llri.cpp | Rythe-Interactive/Legion-LLRI | e0cc449cc8c2ba0701a73b8c07b80ccfd8f20477 | [
"MIT"
] | 1 | 2021-08-15T23:35:32.000Z | 2021-08-15T23:35:32.000Z | /**
* @file llri.cpp
* @copyright 2021-2021 Leon Brands. All rights served.
* @license: https://github.com/Legion-Engine/Legion-LLRI/blob/main/LICENSE
*/
#include <llri/llri.hpp>
namespace llri
{
[[nodiscard]] implementation getImplementation()
{
return implementation::DirectX12;
}
}
| 19.4375 | 75 | 0.678457 |
d8e4153c4406f004e7438070813d1b8ed7ad35ac | 958 | cpp | C++ | dev/test/simple_start_stop/main.cpp | Stiffstream/mosquitto_transport | b7bd85746b7b5ba9f96a9128a12292ebb0604454 | [
"BSD-3-Clause"
] | 3 | 2020-01-25T12:49:55.000Z | 2021-11-08T10:42:09.000Z | dev/test/simple_start_stop/main.cpp | Stiffstream/mosquitto_transport | b7bd85746b7b5ba9f96a9128a12292ebb0604454 | [
"BSD-3-Clause"
] | null | null | null | dev/test/simple_start_stop/main.cpp | Stiffstream/mosquitto_transport | b7bd85746b7b5ba9f96a9128a12292ebb0604454 | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <mosquitto_transport/a_transport_manager.hpp>
#include <so_5/all.hpp>
using namespace std::chrono_literals;
void
do_test()
{
mosquitto_transport::lib_initializer_t mosq_lib;
so_5::launch( [&mosq_lib]( auto & env ) {
env.introduce_coop( [&mosq_lib]( so_5::coop_t & coop ) {
using namespace mosquitto_transport;
coop.make_agent< a_transport_manager_t >(
std::ref(mosq_lib),
connection_params_t{
"test-client",
"localhost",
1883u,
5u },
spdlog::stdout_logger_mt( "mosqt" ) );
struct stop : so_5::signal_t {};
auto stopper = coop.define_agent();
stopper.on_start( [stopper]{
so_5::send_delayed< stop >( stopper, 15s );
} );
stopper.event< stop >(
stopper, [&coop] { coop.deregister_normally(); } );
} );
} );
}
int main()
{
try
{
do_test();
}
catch( const std::exception & ex )
{
std::cerr << "Oops! " << ex.what() << std::endl;
}
}
| 19.16 | 58 | 0.627349 |
d8e694d86bf0df4afeb16f257b966127ed42f3fd | 867 | cpp | C++ | projects/abuild/cache/abi.cpp | agnesoft/adev-alt | 3df0329939e3048bbf5db252efb5f74de9c0f061 | [
"Apache-2.0"
] | null | null | null | projects/abuild/cache/abi.cpp | agnesoft/adev-alt | 3df0329939e3048bbf5db252efb5f74de9c0f061 | [
"Apache-2.0"
] | null | null | null | projects/abuild/cache/abi.cpp | agnesoft/adev-alt | 3df0329939e3048bbf5db252efb5f74de9c0f061 | [
"Apache-2.0"
] | null | null | null | #ifndef __clang__
export module abuild.cache:abi;
export import astl;
#endif
namespace abuild
{
//! The `ABI` represent the compiler toolchain
//! application binary interface.
export struct ABI
{
//! Processor architecture.
enum class Architecture
{
//! ARM
ARM,
//! Intel x86
X86
};
//! Architecture's register size.
enum class Bitness
{
//! 32 bits
X32,
//! 64 bits
X64
};
//! Platform or operating system.
enum class Platform
{
//! Linux
Linux,
//! Unix
Unix,
//! Windows
Windows
};
//! Processor architecture
Architecture architecture = Architecture::X86;
//! Register size
Bitness bitness = Bitness::X64;
//! Target platform
Platform platform = Platform::Linux;
};
}
| 15.763636 | 50 | 0.558247 |
d8e8d67e6a22e721c27a4f9ef527f81eb4c477a2 | 1,201 | cpp | C++ | 9999/1197.cpp | rmagur1203/acmicpc | 83c4018548e42fc758b3858e8290990701e69e73 | [
"MIT"
] | null | null | null | 9999/1197.cpp | rmagur1203/acmicpc | 83c4018548e42fc758b3858e8290990701e69e73 | [
"MIT"
] | null | null | null | 9999/1197.cpp | rmagur1203/acmicpc | 83c4018548e42fc758b3858e8290990701e69e73 | [
"MIT"
] | 1 | 2022-01-11T05:03:52.000Z | 2022-01-11T05:03:52.000Z | #include <iostream>
#include <tuple>
#include <vector>
#include <queue>
using namespace std;
vector<pair<int, int>> graph[10001];
int visited[10001];
int main()
{
cin.tie(NULL)->sync_with_stdio(false);
int V, E;
cin >> V >> E;
for (int i = 0; i < E; i++)
{
int s, e, w;
cin >> s >> e >> w;
graph[s].push_back(make_pair(e, w));
graph[e].push_back(make_pair(s, w));
}
int cost = 0;
vector<int> mst_nodes;
vector<pair<int, int>> mst_edges;
priority_queue<tuple<int, int, int>> pq;
mst_nodes.push_back(1);
visited[1] = true;
for (int i = 0; i < graph[1].size(); i++){
pq.push(make_tuple(-graph[1][i].second, 1, graph[1][i].first));
}
while (!pq.empty())
{
int w = -get<0>(pq.top());
int s = get<1>(pq.top());
int e = get<2>(pq.top());
pq.pop();
if (visited[e]) continue;
mst_nodes.push_back(e);
mst_edges.push_back(make_pair(s, e));
for (int i = 0; i < graph[e].size(); i++){
pq.push(make_tuple(-graph[e][i].second, e, graph[e][i].first));
}
cost += w;
visited[e] = true;
}
cout << cost;
} | 24.510204 | 75 | 0.512073 |
d8e99a8f9376036a394248698698d57d76039d1d | 12,337 | cpp | C++ | GraphicsSandbox/Engine.cpp | UberCelloCzar/GraphicsSandbox | 3a96f99ca3693a67fdff69fdf7d338e8e5d21086 | [
"MIT"
] | null | null | null | GraphicsSandbox/Engine.cpp | UberCelloCzar/GraphicsSandbox | 3a96f99ca3693a67fdff69fdf7d338e8e5d21086 | [
"MIT"
] | null | null | null | GraphicsSandbox/Engine.cpp | UberCelloCzar/GraphicsSandbox | 3a96f99ca3693a67fdff69fdf7d338e8e5d21086 | [
"MIT"
] | null | null | null | #include "Engine.h"
#include "D11Graphics.h"
Engine::Engine()
{
}
Engine::~Engine()
{
}
void Engine::Initialize()
{
assetManager = new AssetManager();
graphics = new D11Graphics(); // Create whichever graphics system we're using and initialize it
graphics->Initialize();
GameSetup();
__int64 perfFreq;
QueryPerformanceFrequency((LARGE_INTEGER*)&perfFreq);
perfCounterSeconds = 1.0 / (double)perfFreq;
__int64 now;
QueryPerformanceCounter((LARGE_INTEGER*)&now);
startTime = now;
currentTime = now;
previousTime = now;
}
void Engine::GameSetup()
{
/* Load Shaders */
assetManager->LoadVertexShader((char*)"BaseVS", "BaseVertexShader", graphics);
assetManager->LoadPixelShader((char*)"BasePS", "BasePixelShader", graphics);
assetManager->LoadVertexShader((char*)"SkyboxVS", "SkyboxVertexShader", graphics);
assetManager->LoadPixelShader((char*)"SkyboxPS", "SkyboxPixelShader", graphics);
/* Initialize Camera */
camera = new Camera();
camera->position = XMFLOAT3(0.f, 0.f, -10.f);
camera->direction = XMFLOAT3(0.f, 0.f, 1.f);
camera->up = XMFLOAT3(0.f, 1.f, 0.f);
camera->rotationRads = XMFLOAT2(0.f, 0.f);
//camera->rotationMatrix = glm::rotate(glm::rotate(glm::mat4(1.f), -.1f, glm::vec3(1, 0, 0)), .1f, glm::vec3(0,1,0)); // Identity matrix
XMStoreFloat4(&camera->rotationQuaternion, XMQuaternionIdentity());
CalculateProjectionMatrix();
CalculateProjViewMatrix();
/* Load Models */
assetManager->LoadModel((char*)"Cube", "cube.obj", graphics);
assetManager->LoadModel((char*)"Cone", "cone.obj", graphics);
assetManager->LoadModel((char*)"Sphere", "sphere.obj", graphics);
assetManager->LoadModel((char*)"Cerberus", "Cerberus.fbx", graphics);
/* Load Textures */
{
assetManager->LoadDDSTexture((char*)"SM_EnvMap", "SnowMachineEnv", graphics);
assetManager->LoadDDSTexture((char*)"SM_IrrMap", "SnowMachineIrr", graphics);
assetManager->LoadDDSTexture((char*)"SM_SpecMap", "SnowMachineSpec", graphics);
assetManager->LoadDDSTexture((char*)"BRDF_LUT", "SnowMachineBrdf", graphics);
assetManager->LoadWICTexture((char*)"M_100Metal", "solidgoldmetal.png", graphics);
assetManager->LoadWICTexture((char*)"M_0Metal", "nometallic.png", graphics);
assetManager->LoadWICTexture((char*)"A_Gold", "solidgoldbase.png", graphics);
assetManager->LoadWICTexture((char*)"N_Plain", "solidgoldnormal.png", graphics);
assetManager->LoadWICTexture((char*)"R_Gold", "solidgoldroughness.png", graphics);
assetManager->LoadWICTexture((char*)"A_Snow", "Snow_001_COLOR.png", graphics);
assetManager->LoadWICTexture((char*)"N_Snow", "Snow_001_NORM.png", graphics);
assetManager->LoadWICTexture((char*)"R_Snow", "Snow_001_ROUGH.png", graphics);
assetManager->LoadWICTexture((char*)"AO_Snow", "Snow_001_OCC.png", graphics);
assetManager->LoadWICTexture((char*)"A_Rock", "holey-rock1-albedo.png", graphics);
assetManager->LoadWICTexture((char*)"AO_Rock", "holey-rock1-ao.png", graphics);
assetManager->LoadWICTexture((char*)"N_Rock", "holey-rock1-normal-ue.png", graphics);
assetManager->LoadWICTexture((char*)"R_Rock", "holey-rock1-roughness.png", graphics);
assetManager->LoadWICTexture((char*)"A_Cerberus", "Cerberus_A.jpg", graphics);
assetManager->LoadWICTexture((char*)"N_Cerberus", "Cerberus_N.jpg", graphics);
assetManager->LoadWICTexture((char*)"M_Cerberus", "Cerberus_M.jpg", graphics);
assetManager->LoadWICTexture((char*)"R_Cerberus", "Cerberus_R.jpg", graphics);
assetManager->LoadWICTexture((char*)"AO_Cerberus", "Cerberus_AO.jpg", graphics);
}
/* Create Game Objects */
GameEntity* cube = new GameEntity(); // Entity 0 should always be a unit cube
cube->position = XMFLOAT3(0.f, 0.f, 0.f);
cube->scale = XMFLOAT3(1.f, 1.f, 1.f);
XMStoreFloat4(&cube->rotationQuaternion, XMQuaternionIdentity());
cube->modelKey = "Cube";
cube->albedoKey = "A_Gold";
cube->normalKey = "N_Plain";
cube->metallicKey = "M_100Metal";
cube->roughnessKey = "R_Gold";
cube->aoKey = "M_100Metal";
cube->vertexShaderConstants = {};
GameEntity* snowball = new GameEntity();
snowball->position = XMFLOAT3(0.f, 0.f, 5.0f);
snowball->scale = XMFLOAT3(2.f, 2.f, 2.f);
XMStoreFloat4(&snowball->rotationQuaternion, XMQuaternionIdentity());
snowball->modelKey = "Sphere";
snowball->albedoKey = "A_Snow";
snowball->normalKey = "N_Snow";
snowball->metallicKey = "M_0Metal";
snowball->roughnessKey = "R_Snow";
snowball->aoKey = "AO_Snow";
snowball->vertexShaderConstants = {};
GameEntity* rock = new GameEntity();
rock->scale = XMFLOAT3(2.f, 2.f, 2.f);
rock->position = XMFLOAT3(5.f, 0.f, 5.0f);
XMStoreFloat4(&rock->rotationQuaternion, XMQuaternionIdentity());
rock->modelKey = "Sphere";
rock->albedoKey = "A_Rock";
rock->normalKey = "N_Rock";
rock->metallicKey = "M_0Metal";
rock->roughnessKey = "R_Rock";
rock->aoKey = "AO_Rock";
rock->vertexShaderConstants = {};
GameEntity* block = new GameEntity();
block->scale = XMFLOAT3(1.f, 1.f, 1.f);
block->position = XMFLOAT3(-5.f, 0.f, 5.0f);
XMStoreFloat4(&block->rotationQuaternion, XMQuaternionIdentity());
block->modelKey = "Cube";
block->albedoKey = "A_Gold";
block->normalKey = "N_Plain";
block->metallicKey = "M_100Metal";
block->roughnessKey = "R_Gold";
block->aoKey = "M_100Metal";
block->vertexShaderConstants = {};
GameEntity* cerberus = new GameEntity();
cerberus->scale = XMFLOAT3(.1f, .1f, .1f);
cerberus->position = XMFLOAT3(-10.f, 0.f, 20.0f);
XMStoreFloat4(&cerberus->rotationQuaternion, XMQuaternionIdentity());
cerberus->modelKey = "Cerberus";
cerberus->albedoKey = "A_Cerberus";
cerberus->normalKey = "N_Cerberus";
cerberus->metallicKey = "M_Cerberus";
cerberus->roughnessKey = "R_Cerberus";
cerberus->aoKey = "AO_Cerberus";
cerberus->vertexShaderConstants = {};
entities.push_back(cube);
entities.push_back(snowball);
entities.push_back(rock);
entities.push_back(block);
entities.push_back(cerberus);
for (auto& e : entities)
{
CalculateProjViewWorldMatrix(e);
e->vertexShaderConstantBuffer = graphics->CreateConstantBuffer(&(e->vertexShaderConstants), sizeof(VShaderConstants));
}
/* Create Constant Buffers */
pixelShaderConstants.cameraPosition.x = camera->position.x;
pixelShaderConstants.cameraPosition.y = camera->position.y;
pixelShaderConstants.cameraPosition.z = camera->position.z;
pixelShaderConstants.lightPos1 = XMFLOAT3A(5.f, 2.f, 15.f);
pixelShaderConstants.lightPos2 = XMFLOAT3A(10.f, 5.f, 3.f);
pixelShaderConstants.lightPos3 = XMFLOAT3A(0.f, 10.f, 7.f);
pixelShaderConstants.lightColor1 = XMFLOAT3A(.95f, .95f, 0.f);
pixelShaderConstants.lightColor2 = XMFLOAT3A(0.f, .95f, .95f);
pixelShaderConstants.lightColor3 = XMFLOAT3A(.95f, 0.f, .95f);
skyboxVShaderConstants.projection = camera->projection;
skyboxVShaderConstants.view = camera->view;
skyboxVShaderConstants.projection = camera->projection;
skyboxVShaderConstants.view = camera->view;
pixelShaderConstantBuffer = graphics->CreateConstantBuffer(&pixelShaderConstants, sizeof(PShaderConstants));
skyboxVShaderConstantBuffer = graphics->CreateConstantBuffer(&skyboxVShaderConstants, sizeof(SkyboxVShaderConstants));
}
void Engine::Run()
{
Initialize();
bool quit = false;
while (!quit)
{
UpdateTimer();
graphics->UpdateStats(totalTime);
Update();
Draw();
quit = graphics->HandleLowLevelEvents(GetAsyncKeyState(VK_ESCAPE));
}
ShutDown();
}
void Engine::UpdateTimer()
{
__int64 now;
QueryPerformanceCounter((LARGE_INTEGER*)&now); // Gat current time
currentTime = now;
deltaTime = std::max((float)((currentTime - previousTime) * perfCounterSeconds), 0.0f); // Calc delta time, ensure it's not less than zero
totalTime = (float)((currentTime - startTime) * perfCounterSeconds); // Calculate the total time from start to now
previousTime = currentTime; // Save current time for next frame
}
void Engine::Update()
{
//printf("%f, %f\n", graphics->rotateBy.x, graphics->rotateBy.y);
camera->Rotate(graphics->rotateBy.x, graphics->rotateBy.y);
graphics->rotateBy = XMFLOAT2(0, 0);
float right = 0;
float forward = 0;
float vert = 0;
if (GetAsyncKeyState('A') & 0x8000) right -= 5 * deltaTime;
if (GetAsyncKeyState('D') & 0x8000) right += 5 * deltaTime;
if (GetAsyncKeyState('W') & 0x8000) forward += 5 * deltaTime;
if (GetAsyncKeyState('S') & 0x8000) forward -= 5 * deltaTime;
if (GetAsyncKeyState('Q') & 0x8000) vert -= 5 * deltaTime;
if (GetAsyncKeyState('E') & 0x8000) vert += 5 * deltaTime;
if (forward != 0 || right != 0 || vert != 0) camera->Move(forward, right, vert);
}
void Engine::Draw()
{
graphics->BeginNewFrame();
CalculateProjViewMatrix();
graphics->SetVertexShader(assetManager->GetVertexShader(std::string("BaseVS")));
graphics->SetPixelShader(assetManager->GetPixelShader(std::string("BasePS")));
pixelShaderConstants.cameraPosition.x = camera->position.x;
pixelShaderConstants.cameraPosition.y = camera->position.y;
pixelShaderConstants.cameraPosition.z = camera->position.z;
for (size_t i = 1; i < entities.size(); ++i)
{
CalculateProjViewWorldMatrix(entities[i]); // Update the main matrix in the vertex shader constants area of the entity
graphics->SetConstantBufferVS(entities[i]->vertexShaderConstantBuffer, &(entities[i]->vertexShaderConstants), sizeof(VShaderConstants));
graphics->SetConstantBufferPS(pixelShaderConstantBuffer, &pixelShaderConstants, sizeof(PShaderConstants));
graphics->SetTexture(assetManager->GetTexture(entities[i]->albedoKey), 0);
graphics->SetTexture(assetManager->GetTexture(entities[i]->normalKey), 1);
graphics->SetTexture(assetManager->GetTexture(entities[i]->metallicKey), 2);
graphics->SetTexture(assetManager->GetTexture(entities[i]->roughnessKey), 3);
graphics->SetTexture(assetManager->GetTexture(entities[i]->aoKey), 4);
graphics->SetTexture(assetManager->GetTexture("BRDF_LUT"), 5);
graphics->SetTexture(assetManager->GetTexture("SM_IrrMap"), 6);
graphics->SetTexture(assetManager->GetTexture("SM_SpecMap"), 7);
Model* model = assetManager->GetModel(entities[i]->modelKey);
for (size_t j = 0; j < model->meshes.size(); ++j)
{
graphics->DrawMesh(model->meshes[j]); // If we have a bunch of the same object and we have time, I can add a render for instancing
}
}
/* Draw the Skybox Last */
graphics->SetVertexShader(assetManager->GetVertexShader(std::string("SkyboxVS")));
graphics->SetPixelShader(assetManager->GetPixelShader(std::string("SkyboxPS")));
CalculateProjViewWorldMatrix(entities[0]); // Update the main matrix in the vertex shader constants area of the entity
skyboxVShaderConstants.projection = camera->projection;
skyboxVShaderConstants.view = camera->view;
graphics->SetConstantBufferVS(skyboxVShaderConstantBuffer, &skyboxVShaderConstants, sizeof(SkyboxVShaderConstants));
graphics->SetTexture(assetManager->GetTexture("SM_EnvMap"), 0);
Model* model = assetManager->GetModel(entities[0]->modelKey);
graphics->DrawSkybox(model->meshes[0]);
graphics->EndFrame();
}
void Engine::ShutDown()
{
pixelShaderConstantBuffer->Release();
skyboxVShaderConstantBuffer->Release();
for (auto& e : entities)
{
e->vertexShaderConstantBuffer->Release();
delete e;
}
delete camera;
assetManager->Destroy();
graphics->DestroyGraphics();
delete assetManager;
delete graphics;
}
void Engine::CalculateProjectionMatrix()
{
XMStoreFloat4x4(&camera->projection, XMMatrixTranspose(XMMatrixPerspectiveFovLH(fov, graphics->aspectRatio, 0.1f, 1000.0f))); // Update with new w/h
}
void Engine::CalculateProjViewMatrix()
{
XMMATRIX view = XMMatrixTranspose(XMMatrixLookToLH(XMLoadFloat3(&camera->position), XMLoadFloat3(&camera->direction), XMLoadFloat3(&camera->up)));
XMStoreFloat4x4(&camera->view, view);
XMStoreFloat4x4(&camera->projView, XMLoadFloat4x4(&camera->projection) * view);
}
void Engine::CalculateProjViewWorldMatrix(GameEntity* entity)
{
XMMATRIX world = XMMatrixTranspose(XMMatrixScaling(entity->scale.x, entity->scale.y, entity->scale.z) * XMMatrixRotationQuaternion(XMLoadFloat4(&entity->rotationQuaternion)) * XMMatrixTranslation(entity->position.x, entity->position.y, entity->position.z));
XMStoreFloat4x4(&entity->vertexShaderConstants.world, world);
XMStoreFloat4x4(&entity->vertexShaderConstants.projViewWorld, XMLoadFloat4x4(&camera->projView) * world); // This result is already transpose, as the individual matrices are transpose and the mult order is reversed
}
| 39.415335 | 258 | 0.739078 |
d8efad03b3048947dc4ca59b2e5113576c4760ba | 475 | cc | C++ | extensions/basic/types_bucket/types_bucket.cc | blockspacer/chromium_base_conan | b4749433cf34f54d2edff52e2f0465fec8cb9bad | [
"Apache-2.0",
"BSD-3-Clause"
] | 6 | 2020-12-22T05:48:31.000Z | 2022-02-08T19:49:49.000Z | extensions/basic/types_bucket/types_bucket.cc | blockspacer/chromium_base_conan | b4749433cf34f54d2edff52e2f0465fec8cb9bad | [
"Apache-2.0",
"BSD-3-Clause"
] | 4 | 2020-05-22T18:36:43.000Z | 2021-05-19T10:20:23.000Z | extensions/basic/types_bucket/types_bucket.cc | blockspacer/chromium_base_conan | b4749433cf34f54d2edff52e2f0465fec8cb9bad | [
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2019-12-06T11:48:16.000Z | 2021-09-16T04:44:47.000Z | #include "basic/types_bucket/types_bucket.h" // IWYU pragma: associated
#include <base/memory/singleton.h>
#include <base/no_destructor.h>
#include <base/task/post_task.h>
#include <base/threading/sequence_local_storage_slot.h>
#include <base/threading/sequenced_task_runner_handle.h>
#include <base/memory/ptr_util.h>
#include <base/lazy_instance.h>
#include <memory>
namespace basic {
TypesBucket::TypesBucket()
{}
TypesBucket::~TypesBucket()
{}
} // namespace basic
| 21.590909 | 71 | 0.772632 |
d8f3c20502910b642f3ca733a9c5e5b8a24ad94c | 607 | cpp | C++ | C++/Dynamic_Programming/1003.cpp | SkydevilK/BOJ | 4b79a258c52aca24683531d64736b91cbdfca3f2 | [
"MIT"
] | null | null | null | C++/Dynamic_Programming/1003.cpp | SkydevilK/BOJ | 4b79a258c52aca24683531d64736b91cbdfca3f2 | [
"MIT"
] | null | null | null | C++/Dynamic_Programming/1003.cpp | SkydevilK/BOJ | 4b79a258c52aca24683531d64736b91cbdfca3f2 | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstring>
using namespace std;
int note_zero[41];
int note_one[41];
void dp()
{
for (int i = 2; i < 41; ++i)
{
note_zero[i] = note_zero[i - 2] + note_zero[i - 1];
note_one[i] = note_one[i - 2] + note_one[i - 1];
}
}
int main(void)
{
ios::sync_with_stdio(false);
memset(note_zero, -1, sizeof(note_zero));
memset(note_one, -1, sizeof(note_one));
note_zero[0] = 1;
note_one[0] = 0;
note_zero[1] = 0;
note_one[1] = 1;
dp();
int T;
cin >> T;
for (int test = 1; test <= T; ++test)
{
int N = 0;
cin >> N;
cout << note_zero[N] << " " << note_one[N] << "\n";
}
}
| 18.393939 | 53 | 0.578254 |
d8f5827ed2e61a8b336526ab372312d3a21186ff | 666 | hpp | C++ | Canteen.hpp | dianabacon/stalag-escape | 445085f1d95bec4190f29d72843bf4878d8f45ac | [
"MIT"
] | null | null | null | Canteen.hpp | dianabacon/stalag-escape | 445085f1d95bec4190f29d72843bf4878d8f45ac | [
"MIT"
] | null | null | null | Canteen.hpp | dianabacon/stalag-escape | 445085f1d95bec4190f29d72843bf4878d8f45ac | [
"MIT"
] | null | null | null | /*********************************************************************
** Program Filename: Canteen.cpp
** Author: Diana Bacon
** Date: 2015-12-05
** Description: Definition of the Canteen class. Functions and data
** related to the derived class for Canteen spaces.
*********************************************************************/
#ifndef Canteen_hpp
#define Canteen_hpp
#include <iostream>
#include "Space.hpp"
class Canteen : public Space
{
private:
public:
Canteen(); // default constructor
bool enter(Airman* const); // special function
~Canteen() {}; // destructor
};
#endif /* Canteen_hpp */
| 25.615385 | 71 | 0.510511 |
d8f5f664fe03cf939591e9af0b3f1e7f625f0439 | 2,430 | cc | C++ | tests/libtests/bc/obsolete/TestBoundaryConditionPoints.cc | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | 93 | 2015-01-08T16:41:22.000Z | 2022-02-25T13:40:02.000Z | tests/libtests/bc/obsolete/TestBoundaryConditionPoints.cc | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | 277 | 2015-02-20T16:27:35.000Z | 2022-03-30T21:13:09.000Z | tests/libtests/bc/obsolete/TestBoundaryConditionPoints.cc | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | 71 | 2015-03-24T12:11:08.000Z | 2022-03-03T04:26:02.000Z | // -*- C++ -*-
//
// ----------------------------------------------------------------------
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University of Chicago
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2017 University of California, Davis
//
// See COPYING for license information.
//
// ----------------------------------------------------------------------
//
#include <portinfo>
#include "TestBoundaryConditionPoints.hh" // Implementation of class methods
#include "pylith/bc/PointForce.hh" // USES PointForce
#include "data/PointForceDataTri3.hh" // USES PointForceDataTri3
#include "pylith/topology/Mesh.hh" // USES Mesh
#include "pylith/topology/MeshOps.hh" // USES MeshOps::nondimensionalize()
#include "pylith/topology/Stratum.hh" // USES Stratum
#include "pylith/meshio/MeshIOAscii.hh" // USES MeshIOAscii
#include "spatialdata/geocoords/CSCart.hh" // USES CSCart
#include "spatialdata/units/Nondimensional.hh" // USES Nondimensional
// ----------------------------------------------------------------------
CPPUNIT_TEST_SUITE_REGISTRATION( pylith::bc::TestBoundaryConditionPoints );
// ----------------------------------------------------------------------
// Test _getPoints().
void
pylith::bc::TestBoundaryConditionPoints::testGetPoints(void)
{ // testGetPoints
PYLITH_METHOD_BEGIN;
topology::Mesh mesh;
PointForce bc;
PointForceDataTri3 data;
meshio::MeshIOAscii iohandler;
iohandler.filename(data.meshFilename);
iohandler.read(&mesh);
spatialdata::geocoords::CSCart cs;
spatialdata::units::Nondimensional normalizer;
cs.setSpaceDim(mesh.dimension());
cs.initialize();
mesh.coordsys(&cs);
topology::MeshOps::nondimensionalize(&mesh, normalizer);
bc.label(data.label);
bc.BoundaryConditionPoints::_getPoints(mesh);
const PetscDM dmMesh = mesh.dmMesh();CPPUNIT_ASSERT(dmMesh);
topology::Stratum heightStratum(dmMesh, topology::Stratum::HEIGHT, 0);
const PetscInt numCells = heightStratum.size();
const size_t numPoints = data.numForcePts;
// Check points
const int offset = numCells;
CPPUNIT_ASSERT_EQUAL(numPoints, bc._points.size());
for (int i=0; i < numPoints; ++i)
CPPUNIT_ASSERT_EQUAL(data.forcePoints[i]+offset, bc._points[i]);
PYLITH_METHOD_END;
} // testGetPoints
// End of file
| 30.759494 | 76 | 0.654321 |
d8f72b9194e0af9370f4ece7e39abd1393eef4a3 | 567 | hpp | C++ | src/palm/batch.hpp | leezhenghui/Mushroom | 8aed2bdd80453d856145925d067bef5ed9d10ee0 | [
"BSD-3-Clause"
] | 351 | 2016-10-12T14:06:09.000Z | 2022-03-24T14:53:54.000Z | src/palm/batch.hpp | leezhenghui/Mushroom | 8aed2bdd80453d856145925d067bef5ed9d10ee0 | [
"BSD-3-Clause"
] | 7 | 2017-03-07T01:49:16.000Z | 2018-07-27T08:51:54.000Z | src/palm/batch.hpp | UncP/Mushroom | 8aed2bdd80453d856145925d067bef5ed9d10ee0 | [
"BSD-3-Clause"
] | 62 | 2016-10-31T12:46:45.000Z | 2021-12-28T11:25:26.000Z | /**
* > Author: UncP
* > Github: www.github.com/UncP/Mushroom
* > License: BSD-3
* > Time: 2018-7-28 15:33:00
**/
#ifndef _BATCH_HPP_
#define _BATCH_HPP_
#include "../include/utility.hpp"
namespace Mushroom {
class KeySlice;
class Batch : private NoCopy
{
public:
static uint32_t Size;
static void SetSize(uint32_t size);
Batch();
~Batch();
void SetKeySlice(uint32_t idx, const char *key);
const KeySlice* GetKeySlice(uint32_t idx) const;
private:
KeySlice **batch_;
};
} // Mushroom
#endif /* _BATCH_HPP_ */ | 14.921053 | 50 | 0.643739 |
d8f7962309b2a67a96dd3175fe91d2d67fc5eb4e | 10,980 | cpp | C++ | project/src/main.cpp | PhuNH/hpc-lab | 25874fc36c87c57f2b6312d93897de9b898fbf26 | [
"MIT"
] | null | null | null | project/src/main.cpp | PhuNH/hpc-lab | 25874fc36c87c57f2b6312d93897de9b898fbf26 | [
"MIT"
] | null | null | null | project/src/main.cpp | PhuNH/hpc-lab | 25874fc36c87c57f2b6312d93897de9b898fbf26 | [
"MIT"
] | null | null | null | #include <cmath>
#include <iostream>
#include <mpi.h>
#include "tclap/CmdLine.h"
#include "typedefs.h"
#include "Simulator.h"
#include "Grid.h"
#include "InitialCondition.h"
#include "RankDependentOutput.h"
#include "GlobalMatrices.h"
#include "microkernels.h"
void computeAuxMatrices(GlobalConstants& globals)
{
double factorx = -globals.hx / (globals.hx * globals.hy),
factory = -globals.hy / (globals.hx * globals.hy),
hx_1 = 1.0 / globals.hx,
hy_1 = 1.0 / globals.hy;
for (int i = 0; i < GLOBAL_MATRIX_SIZE; ++i) {
globals.hxKxiT[i] = (-hx_1) * (GlobalMatrices::KxiT[i]);
globals.hyKetaT[i] = (-hy_1) * (GlobalMatrices::KetaT[i]);
globals.hxKxi[i] = hx_1 * (GlobalMatrices::Kxi[i]);
globals.hyKeta[i] = hy_1 * (GlobalMatrices::Keta[i]);
globals.hxFxm0[i] = factorx * (GlobalMatrices::Fxm0[i]);
globals.hxFxm1[i] = factorx * (GlobalMatrices::Fxm1[i]);
globals.hyFym0[i] = factory * (GlobalMatrices::Fym0[i]);
globals.hyFym1[i] = factory * (GlobalMatrices::Fym1[i]);
globals.hxFxp0[i] = factorx * (GlobalMatrices::Fxp0[i]);
globals.hxFxp1[i] = factorx * (GlobalMatrices::Fxp1[i]);
globals.hyFyp0[i] = factory * (GlobalMatrices::Fyp0[i]);
globals.hyFyp1[i] = factory * (GlobalMatrices::Fyp1[i]);
}
}
void get_size_subgrid(int index_proc_axis, int nb_procs_axis, int grid_size, int * size_current, int * start) {
int min_size = ((int) grid_size / nb_procs_axis),
remainder = grid_size % nb_procs_axis;
if (remainder > index_proc_axis) {
*size_current = min_size + 1;
*start = index_proc_axis * (*size_current);
} else {
*size_current = min_size;
*start = remainder + index_proc_axis * min_size;
}
}
void initScenario0(GlobalConstants& globals, LocalConstants& locals, Grid<Material>& materialGrid, Grid<DegreesOfFreedom>& degreesOfFreedomGrid)
{
for (int y = 0; y < globals.Y; ++y) {
for (int x = 0; x < globals.X; ++x) {
Material& material = materialGrid.get(x, y);
material.rho0 = 1.;
material.K0 = 4.;
material.wavespeed = sqrt(4./1.);
}
}
initialCondition(globals, locals, materialGrid, degreesOfFreedomGrid);
}
void initScenario1(GlobalConstants& globals, LocalConstants& locals, Grid<Material>& materialGrid, Grid<DegreesOfFreedom>& degreesOfFreedomGrid)
{
double checkerWidth = 0.25;
for (int y = 0; y < globals.Y; ++y) {
for (int x = 0; x < globals.X; ++x) {
Material& material = materialGrid.get(x, y);
int matId = static_cast<int>(x*globals.hx/checkerWidth) % 2 ^ static_cast<int>(y*globals.hy/checkerWidth) % 2;
if (matId == 0) {
material.rho0 = 1.;
material.K0 = 2.;
material.wavespeed = sqrt(2./1.);
} else {
material.rho0 = 2.;
material.K0 = 0.5;
material.wavespeed = sqrt(0.5/2.);
}
}
}
initialCondition(globals, locals, materialGrid, degreesOfFreedomGrid);
}
double sourceFunctionAntiderivative(double time)
{
return sin(time);
}
void initSourceTerm23(GlobalConstants& globals, SourceTerm& sourceterm)
{
sourceterm.quantity = 0; // pressure source
double xs = 0.5;
double ys = 0.5;
sourceterm.x = static_cast<int>(xs / (globals.hx));
sourceterm.y = static_cast<int>(ys / (globals.hy));
double xi = (xs - sourceterm.x*globals.hx) / globals.hx;
double eta = (ys - sourceterm.y*globals.hy) / globals.hy;
initSourcetermPhi(xi, eta, sourceterm);
sourceterm.antiderivative = sourceFunctionAntiderivative;
}
void initScenario2(GlobalConstants& globals, Grid<Material>& materialGrid, Grid<DegreesOfFreedom>& degreesOfFreedomGrid, SourceTerm& sourceterm)
{
for (int y = 0; y < globals.Y; ++y) {
for (int x = 0; x < globals.X; ++x) {
Material& material = materialGrid.get(x, y);
material.rho0 = 1.;
material.K0 = 2.;
material.wavespeed = sqrt(2./1.);
}
}
initSourceTerm23(globals, sourceterm);
}
void initScenario3(GlobalConstants& globals, Grid<Material>& materialGrid, Grid<DegreesOfFreedom>& degreesOfFreedomGrid, SourceTerm& sourceterm)
{
for (int y = 0; y < globals.Y; ++y) {
for (int x = 0; x < globals.X; ++x) {
Material& material = materialGrid.get(x, y);
int matId;
double xp = x*globals.hx;
double yp = y*globals.hy;
matId = (xp >= 0.25 && xp <= 0.75 && yp >= 0.25 && yp <= 0.75) ? 0 : 1;
if (matId == 0) {
material.rho0 = 1.;
material.K0 = 2.;
material.wavespeed = sqrt(2./1.);
} else {
material.rho0 = 2.;
material.K0 = 0.5;
material.wavespeed = sqrt(0.5/2.);
}
}
}
initSourceTerm23(globals, sourceterm);
}
int main(int argc, char** argv)
{
int scenario;
double wfwInterval;
std::string wfwBasename;
GlobalConstants globals;
LocalConstants locals;
// Initialize MPI functions
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &locals.rank);
MPI_Comm_size(MPI_COMM_WORLD, &globals.nb_procs);
RankDependentOutput *rdOutput;
try {
TCLAP::CmdLine cmd("ADER-DG for linear acoustics.", ' ', "0.1");
TCLAP::ValueArg<int> scenarioArg("s", "scenario", "Scenario. 0=Convergence test. 1=Checkerboard.", true, 0, "int");
TCLAP::ValueArg<int> XArg("x", "x-number-of-cells", "Number of cells in x direction.", true, 0, "int");
TCLAP::ValueArg<int> YArg("y", "y-number-of-cells", "Number of cells in y direction.", true, 0, "int");
TCLAP::ValueArg<std::string> basenameArg("o", "output", "Basename of wavefield writer output. Leave empty for no output.", false, "", "string");
TCLAP::ValueArg<double> intervalArg("i", "interval", "Time interval of wavefield writer.", false, 0.1, "double");
TCLAP::ValueArg<double> timeArg("t", "end-time", "Final simulation time.", false, 0.5, "double");
TCLAP::ValueArg<int> horizontalArg("u", "hprocs", "Number of nodes - Horizontal axis", true, 0, "int");
TCLAP::ValueArg<int> verticalArg("v", "vprocs", "Number of nodes - Vertical axis", true, 0, "int");
cmd.add(scenarioArg);
cmd.add(XArg);
cmd.add(YArg);
cmd.add(basenameArg);
cmd.add(intervalArg);
cmd.add(timeArg);
cmd.add(horizontalArg);
cmd.add(verticalArg);
rdOutput = new RankDependentOutput(locals.rank);
cmd.setOutput(rdOutput);
cmd.parse(argc, argv);
scenario = scenarioArg.getValue();
globals.X = XArg.getValue();
globals.Y = YArg.getValue();
wfwBasename = basenameArg.getValue();
wfwInterval = intervalArg.getValue();
globals.endTime = timeArg.getValue();
globals.dims_proc[0] = verticalArg.getValue();
globals.dims_proc[1] = horizontalArg.getValue();
delete rdOutput;
if (scenario < 0 || scenario > 3) {
if (locals.rank == 0) std::cerr << "Unknown scenario." << std::endl;
return -1;
}
if (globals.X < 0 || globals.Y < 0) {
if (locals.rank == 0) std::cerr << "X or Y smaller than 0. Does not make sense." << std::endl;
return -1;
}
} catch (TCLAP::ArgException &e) {
delete rdOutput;
if (locals.rank == 0) std::cerr << "Error: " << e.error() << " for arg " << e.argId() << std::endl;
return -1;
}
globals.hx = 1. / globals.X;
globals.hy = 1. / globals.Y;
// Initialize cartesian grid
int periods[2] = {1, 1}, reorder = 0;
MPI_Comm cartcomm;
MPI_Cart_create(MPI_COMM_WORLD, 2, globals.dims_proc, periods, reorder, &cartcomm);
MPI_Cart_coords(cartcomm, locals.rank, 2, locals.coords_proc);
MPI_Cart_shift(cartcomm, 0, 1, &locals.adj_list[UP], &locals.adj_list[DOWN]);
MPI_Cart_shift(cartcomm, 1, 1, &locals.adj_list[LEFT], &locals.adj_list[RIGHT]);
MPI_Group worldGroup;
MPI_Comm_group(MPI_COMM_WORLD, &worldGroup);
for (int i = 0; i < 4; i++)
MPI_Group_incl(worldGroup, 1, &locals.adj_list[i], &(locals.nbGroups[i]));
// Initializing locals variable
get_size_subgrid(locals.coords_proc[0], globals.dims_proc[0], globals.Y, &locals.elts_size[1], &locals.start_elts[1]);
get_size_subgrid(locals.coords_proc[1], globals.dims_proc[1], globals.X, &locals.elts_size[0], &locals.start_elts[0]);
//printf("Rank : %d -- iproc = %d -- jproc = %d -- (xstart = %d, ystart = %d) -- (xsize = %d, ysize = %d) \n",locals.rank,locals.coords_proc [0],locals.coords_proc[1],locals.start_elts[0],locals.start_elts[1],locals.elts_size[0],locals.elts_size[1]);
Grid<DegreesOfFreedom> degreesOfFreedomGrid(locals.elts_size[0], locals.elts_size[1]); // Change with MPI structure
Grid<Material> materialGrid(globals.X, globals.Y); // Each node stores all : could be optimized - to see later
SourceTerm sourceterm;
switch (scenario) {
case 0:
initScenario0(globals, locals, materialGrid, degreesOfFreedomGrid);
break;
case 1:
initScenario1(globals, locals, materialGrid, degreesOfFreedomGrid);
break;
case 2:
initScenario2(globals, materialGrid, degreesOfFreedomGrid, sourceterm);
break;
case 3:
initScenario3(globals, materialGrid, degreesOfFreedomGrid, sourceterm);
break;
default:
break;
}
globals.maxTimestep = determineTimestep(globals.hx, globals.hy, materialGrid);
WaveFieldWriter waveFieldWriter(wfwBasename, globals, locals, wfwInterval, static_cast<int>(ceil( sqrt(NUMBER_OF_BASIS_FUNCTIONS) )));
double t1, t2;
t1 = MPI_Wtime();
computeAuxMatrices(globals);
globals.dgemm_beta_0 = microkernels[(CONVERGENCE_ORDER-2)*2];
globals.dgemm_beta_1 = microkernels[(CONVERGENCE_ORDER-2)*2+1];
int steps = simulate(globals, locals, materialGrid, degreesOfFreedomGrid, waveFieldWriter, sourceterm);
t2 = MPI_Wtime();
if (scenario == 0) {
double local_L2error_squared[NUMBER_OF_QUANTITIES];
L2error_squared(globals.endTime, globals, locals, materialGrid, degreesOfFreedomGrid, local_L2error_squared);
//printf("rank %d p %f vx %f vy %f\n", locals.rank, local_L2error_squared[0], local_L2error_squared[1], local_L2error_squared[2]);
double global_L2error_squared[NUMBER_OF_QUANTITIES];
MPI_Reduce(local_L2error_squared,global_L2error_squared,NUMBER_OF_QUANTITIES,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);
if (locals.rank == 0) {
square_root_array(global_L2error_squared,NUMBER_OF_QUANTITIES);
std::cout << "L2 error analysis" << std::endl << "=================" << std::endl;
std::cout << "Pressue (p): " << global_L2error_squared[0] << std::endl;
std::cout << "X-Velocity (u): " << global_L2error_squared[1] << std::endl;
std::cout << "Y-Velocity (v): " << global_L2error_squared[2] << std::endl;
}
}
if (locals.rank == 0) std::cout << "Total number of timesteps: " << steps << std::endl;
MPI_Group_free(&worldGroup);
for (int i = 0; i < 4; i++)
MPI_Group_free(&locals.nbGroups[i]);
MPI_Finalize();
printf("Simulation time: %f s\n", t2 - t1 );
return 0;
}
| 37.220339 | 252 | 0.650546 |
d8f910b00400f6a61a3f8ce43feb3f07939971c1 | 912 | cpp | C++ | test/bench2_rosenbrock.cpp | marcorushdy/realGen | 2441cbb81d034137926c0f50c7dcdc6777329b76 | [
"MIT"
] | 16 | 2017-04-23T23:24:08.000Z | 2021-03-12T21:38:28.000Z | test/bench2_rosenbrock.cpp | marcorushdy/realGen | 2441cbb81d034137926c0f50c7dcdc6777329b76 | [
"MIT"
] | null | null | null | test/bench2_rosenbrock.cpp | marcorushdy/realGen | 2441cbb81d034137926c0f50c7dcdc6777329b76 | [
"MIT"
] | 6 | 2017-06-14T11:50:37.000Z | 2019-05-16T20:09:07.000Z | #include "testcommon.h"
#include "fitnessfunction.h"
class RosenbrockFitness : public FitnessFunction {
public:
RosenbrockFitness() {}
double eval(const RealGenotype &g) {
double dx1 = g.gene[0]*g.gene[0]-g.gene[1];
double dx2 = 1.0 - g.gene[0];
return 100.0*dx1*dx1+dx2*dx2;
}
};
void bench2_rosenbrock(RealGenOptions opt, GAResults &results) {
vector<float> LB = { -2.048, -2.048 };
vector<float> UB = { 2.048, 2.048};
RosenbrockFitness *myFitnessFunction = new RosenbrockFitness();
strcpy(results.name, "Rosenbrock");
results.maxIter = 5000;
results.Np = 200;
opt.setPopulationSize(results.Np);
opt.setChromosomeSize(2);
opt.setBounds(LB, UB);
RealGen ga(opt);
ga.setFitnessFunction(myFitnessFunction);
testRealGen(ga, results.maxIter, 1e-4, results);
delete myFitnessFunction;
}
| 26.823529 | 68 | 0.639254 |
d8febc737fe1416c65cd87a7bace3dc194b673ca | 3,369 | cpp | C++ | source_code/system_sys/source_code/gui/Sys_Output_Flag_Dia.cpp | dabachma/ProMaIDes_src | 3fa6263c46f89abbdb407f2e1643843d54eb6ccc | [
"BSD-3-Clause"
] | null | null | null | source_code/system_sys/source_code/gui/Sys_Output_Flag_Dia.cpp | dabachma/ProMaIDes_src | 3fa6263c46f89abbdb407f2e1643843d54eb6ccc | [
"BSD-3-Clause"
] | null | null | null | source_code/system_sys/source_code/gui/Sys_Output_Flag_Dia.cpp | dabachma/ProMaIDes_src | 3fa6263c46f89abbdb407f2e1643843d54eb6ccc | [
"BSD-3-Clause"
] | null | null | null | #include "Sys_Headers_Precompiled.h"
//#include "Sys_Output_Flag_Dia.h"
// Constructor
Sys_Output_Flag_Dia::Sys_Output_Flag_Dia(QWidget *parent) : QDialog(parent){
this->old_flag=false;
this->new_flag=false;
ui.setupUi(this);
ui.checkBox->setChecked(this->old_flag);
QObject::connect(ui.okButton, SIGNAL(clicked()), this, SLOT(accept()));
QObject::connect(ui.cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
//count the memory
Sys_Memory_Count::self()->add_mem((sizeof(Sys_Output_Flag_Dia)), _sys_system_modules::SYS_SYS);
}
// Destructor
Sys_Output_Flag_Dia::~Sys_Output_Flag_Dia(void){
Sys_Memory_Count::self()->minus_mem(sizeof(Sys_Output_Flag_Dia), _sys_system_modules::SYS_SYS);
}
//___________
//public
//Set the text for which moduls the outputflag should be changed
void Sys_Output_Flag_Dia::set_txt_modul_type(_sys_system_modules type){
QIcon icon;
switch (type){
case _sys_system_modules::SYS_SYS:
this->text = "Change the flag for the Modul SYS";
ui.typeLineEdit->setText(text);
ui.typeLineEdit->setReadOnly(true);
icon.addFile(":prom_icon");
this->setWindowIcon(icon);
break;
case _sys_system_modules::FPL_SYS:
this->text = "Change the flag for the Modul FPL";
ui.typeLineEdit->setText(text);
ui.typeLineEdit->setReadOnly(true);
icon.addFile(":fpl_icon");
this->setWindowIcon(icon);
break;
case _sys_system_modules::HYD_SYS:
this->text = "Change the flag for the Modul HYD";
ui.typeLineEdit->setText(text);
ui.typeLineEdit->setReadOnly(true);
icon.addFile(":hyd_icon");
this->setWindowIcon(icon);
break;
case _sys_system_modules::MADM_SYS:
this->text = "Change the flag for the Modul MADM";
ui.typeLineEdit->setText(text);
ui.typeLineEdit->setReadOnly(true);
icon.addFile(":madm_icon");
this->setWindowIcon(icon);
break;
case _sys_system_modules::DAM_SYS:
this->text = "Change the flag for the Modul DAM";
ui.typeLineEdit->setText(text);
ui.typeLineEdit->setReadOnly(true);
icon.addFile(":dam_icon");
this->setWindowIcon(icon);
break;
case _sys_system_modules::RISK_SYS:
this->text = "Change the flag for the Modul RISK";
ui.typeLineEdit->setText(text);
ui.typeLineEdit->setReadOnly(true);
icon.addFile(":risk_icon");
this->setWindowIcon(icon);
break;
case _sys_system_modules::ALT_SYS:
this->text = "Change the flag for the Modul ALT";
ui.typeLineEdit->setText(text);
ui.typeLineEdit->setReadOnly(true);
icon.addFile(":alt_icon");
this->setWindowIcon(icon);
break;
case _sys_system_modules::COST_SYS:
this->text = "Change the flag for the Modul COST";
ui.typeLineEdit->setText(text);
ui.typeLineEdit->setReadOnly(true);
icon.addFile(":cost_icon");
this->setWindowIcon(icon);
break;
default:
this->text = "Change the flag for the Modul NOTKNOWN";
ui.typeLineEdit->setText(text);
ui.typeLineEdit->setReadOnly(true);
}
}
//Set the current output flag
void Sys_Output_Flag_Dia::set_current_flag(const bool flag){
this->old_flag=flag;
ui.checkBox->setChecked(this->old_flag);
}
//Make the dialog and get the new detailed flag
bool Sys_Output_Flag_Dia::get_new_detailed_flag(void){
int decision =this->exec();
//rejected
if(decision ==0){
return this->old_flag;
}
//accepted
else{
this->new_flag=ui.checkBox->isChecked();
return this->new_flag;
}
} | 30.908257 | 96 | 0.724844 |
2b045b93305594bb73add275c035977d2754913a | 322 | cpp | C++ | compendium/test_bundles/TestBundleDSDependentOptional/src/ServiceImpl.cpp | fmilano/CppMicroServices | b7e79edb558a63e45f6788e4a8b4e787cf956689 | [
"Apache-2.0"
] | 588 | 2015-10-07T15:55:08.000Z | 2022-03-29T00:35:44.000Z | compendium/test_bundles/TestBundleDSDependentOptional/src/ServiceImpl.cpp | fmilano/CppMicroServices | b7e79edb558a63e45f6788e4a8b4e787cf956689 | [
"Apache-2.0"
] | 459 | 2015-10-05T23:29:59.000Z | 2022-03-29T14:13:37.000Z | compendium/test_bundles/TestBundleDSDependentOptional/src/ServiceImpl.cpp | fmilano/CppMicroServices | b7e79edb558a63e45f6788e4a8b4e787cf956689 | [
"Apache-2.0"
] | 218 | 2015-11-04T08:19:48.000Z | 2022-03-24T02:17:08.000Z | #include "ServiceImpl.hpp"
namespace dependent {
TestBundleDSDependentOptionalImpl::TestBundleDSDependentOptionalImpl(
const std::shared_ptr<test::TestBundleDSUpstreamDependency>& c)
: test::TestBundleDSDependent()
, ref(c)
{}
TestBundleDSDependentOptionalImpl::~TestBundleDSDependentOptionalImpl() =
default;
}
| 24.769231 | 73 | 0.807453 |
2b04b3877e617f99a2f6f8ab7d0f3c076b5873a2 | 373 | cpp | C++ | Player.cpp | samapraku/blocktrix_project | bc70e382d218bd1bd85c68258487c33e0506a479 | [
"BSD-2-Clause"
] | null | null | null | Player.cpp | samapraku/blocktrix_project | bc70e382d218bd1bd85c68258487c33e0506a479 | [
"BSD-2-Clause"
] | null | null | null | Player.cpp | samapraku/blocktrix_project | bc70e382d218bd1bd85c68258487c33e0506a479 | [
"BSD-2-Clause"
] | null | null | null | /*
* Institute of Automation - University of Bremen
*BLOCKTRIX GAME AUTO PLAYER
* GROUP MEMBERS:
* ERIC GAMOR
* JIBIN JOHN
* SAMUEL APRAKU
*
*/
#include "Player.h"
void Player::Play(IBoard *pBoard)
{
playerBoard = dynamic_cast<BlockTrixBoard *>(pBoard); // cast pBoard to BlockTrixBoard
playerBoard->SetAutoPlay(true); // tell game to start autoplay
}
| 20.722222 | 91 | 0.702413 |
2b0b1a3c8acf26e971ecac158c0b31e96a01c8c3 | 3,581 | cpp | C++ | src/orocos_kinematics_dynamics/orocos_kdl/src/treeiksolverpos_nr_jl.cpp | matchRos/simulation_multirobots | 286c5add84d521ad371b2c8961dea872c34e7da2 | [
"BSD-2-Clause"
] | 742 | 2017-07-05T02:49:36.000Z | 2022-03-30T12:55:43.000Z | src/orocos_kinematics_dynamics/orocos_kdl/src/treeiksolverpos_nr_jl.cpp | matchRos/simulation_multirobots | 286c5add84d521ad371b2c8961dea872c34e7da2 | [
"BSD-2-Clause"
] | 73 | 2017-07-06T12:50:51.000Z | 2022-03-07T08:07:07.000Z | src/orocos_kinematics_dynamics/orocos_kdl/src/treeiksolverpos_nr_jl.cpp | matchRos/simulation_multirobots | 286c5add84d521ad371b2c8961dea872c34e7da2 | [
"BSD-2-Clause"
] | 425 | 2017-07-04T22:03:29.000Z | 2022-03-29T06:59:06.000Z | // Copyright (C) 2007-2008 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Copyright (C) 2008 Mikael Mayer
// Copyright (C) 2008 Julia Jesse
// Version: 1.0
// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl
// This 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 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#include "treeiksolverpos_nr_jl.hpp"
namespace KDL {
TreeIkSolverPos_NR_JL::TreeIkSolverPos_NR_JL(const Tree& _tree,
const std::vector<std::string>& _endpoints,
const JntArray& _q_min, const JntArray& _q_max,
TreeFkSolverPos& _fksolver, TreeIkSolverVel& _iksolver,
unsigned int _maxiter, double _eps) :
tree(_tree), q_min(_q_min), q_max(_q_max), iksolver(_iksolver),
fksolver(_fksolver), delta_q(tree.getNrOfJoints()),
endpoints(_endpoints), maxiter(_maxiter), eps(_eps)
{
for (size_t i = 0; i < endpoints.size(); i++) {
frames.insert(Frames::value_type(endpoints[i], Frame::Identity()));
delta_twists.insert(Twists::value_type(endpoints[i], Twist::Zero()));
}
}
double TreeIkSolverPos_NR_JL::CartToJnt(const JntArray& q_init, const Frames& p_in, JntArray& q_out) {
q_out = q_init;
//First check if all elements in p_in are available:
for(Frames::const_iterator f_des_it=p_in.begin();f_des_it!=p_in.end();++f_des_it)
if(frames.find(f_des_it->first)==frames.end())
return -2;
unsigned int k=0;
while(++k <= maxiter) {
for (Frames::const_iterator f_des_it=p_in.begin();f_des_it!=p_in.end();++f_des_it){
//Get all iterators for this endpoint
Frames::iterator f_it = frames.find(f_des_it->first);
Twists::iterator delta_twist = delta_twists.find(f_des_it->first);
fksolver.JntToCart(q_out, f_it->second, f_it->first);
delta_twist->second = diff(f_it->second, f_des_it->second);
}
double res = iksolver.CartToJnt(q_out, delta_twists, delta_q);
if (res < eps) return res;
Add(q_out, delta_q, q_out);
for (unsigned int j = 0; j < q_min.rows(); j++) {
if (q_out(j) < q_min(j))
q_out( j) = q_min(j);
else if (q_out(j) > q_max(j))
q_out( j) = q_max(j);
}
}
if (k <= maxiter)
return 0;
else
return -3;
}
TreeIkSolverPos_NR_JL::~TreeIkSolverPos_NR_JL() {
}
}//namespace
| 42.129412 | 106 | 0.586987 |
2b0c787652070af035f365871a15e179c7f10756 | 505 | cpp | C++ | src/test/config/schema.cpp | mpoeter/config | 9a20b1dde685d42190310fa51ecd271e66d90ea0 | [
"MIT"
] | 1 | 2020-03-17T20:47:52.000Z | 2020-03-17T20:47:52.000Z | src/test/config/schema.cpp | mpoeter/config | 9a20b1dde685d42190310fa51ecd271e66d90ea0 | [
"MIT"
] | null | null | null | src/test/config/schema.cpp | mpoeter/config | 9a20b1dde685d42190310fa51ecd271e66d90ea0 | [
"MIT"
] | null | null | null | // Copyright (c) 2019-2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/config/
#include <tao/config.hpp>
#include <tao/config/schema.hpp>
int main()
{
const auto tcs = tao::config::schema::from_file( "tests/schema.tcs" );
const auto data = tao::config::from_file( "tests/schema.jaxn" );
const auto error = tcs.validate( data );
if( error ) {
std::cerr << std::setw( 2 ) << error << std::endl;
}
return !error ? 0 : 1;
}
| 28.055556 | 76 | 0.645545 |
2b0dbed5783e7ff3c89e007e407fb39d6512d7d5 | 1,467 | cpp | C++ | src/mayaToCorona/src/Corona/CoronaRoundCorners.cpp | haggi/OpenMaya | 746e0740f480d9ef8d2173f31b3c99b9b0ea0d24 | [
"MIT"
] | 42 | 2015-01-03T15:07:25.000Z | 2021-12-09T03:56:59.000Z | src/mayaToCorona/src/Corona/CoronaRoundCorners.cpp | haggi/OpenMaya | 746e0740f480d9ef8d2173f31b3c99b9b0ea0d24 | [
"MIT"
] | 66 | 2015-01-02T13:28:44.000Z | 2022-03-16T14:00:57.000Z | src/mayaToCorona/src/Corona/CoronaRoundCorners.cpp | haggi/OpenMaya | 746e0740f480d9ef8d2173f31b3c99b9b0ea0d24 | [
"MIT"
] | 12 | 2015-02-07T05:02:17.000Z | 2020-07-10T17:21:44.000Z | #include "Corona.h"
#include "CoronaRoundCorners.h"
#include <maya/MFnDependencyNode.h>
#include "utilities/attrTools.h"
#include "world.h"
#include "renderGlobals.h"
RoundCorners::RoundCorners(MObject shaderObject)
{
MFnDependencyNode depFn(shaderObject);
radius = getFloatAttr("radius", depFn, 0.0f);
samplesCount = getIntAttr("samples", depFn, 10);
float globalScaleFactor = 1.0f;
if (MayaTo::getWorldPtr()->worldRenderGlobalsPtr != nullptr)
globalScaleFactor = MayaTo::getWorldPtr()->worldRenderGlobalsPtr->scaleFactor;
else
globalScaleFactor = MayaTo::getWorldPtr()->scaleFactor;
radius *= globalScaleFactor;
};
RoundCorners::RoundCorners()
{};
RoundCorners::~RoundCorners(){};
Corona::Rgb RoundCorners::evalColor(const Corona::IShadeContext& context, Corona::TextureCache* cache, float& outAlpha)
{
outAlpha = 1.0f;
float f = 1.0f;
return Corona::Rgb(f, f, f);
}
float RoundCorners::evalMono(const Corona::IShadeContext& context, Corona::TextureCache* cache, float& outAlpha)
{
return evalColor(context, cache, outAlpha).grayValue();
}
Corona::Dir RoundCorners::evalBump(const Corona::IShadeContext& context, Corona::TextureCache* cache)
{
Corona::Dir inNormal(0,0,0);
if (normalCamera.getMap() != nullptr)
inNormal = normalCamera.getMap()->evalBump(context, cache);
return evalPerturbation(context, radius) + inNormal;
}
//void RoundCorners::renderTo(Corona::Bitmap<Corona::Rgb>& output)
//{
// STOP; //currently not supported
//}
| 28.764706 | 119 | 0.748466 |
2b0e369b3ee9925c6967788de2cba07a22e4465a | 842 | cc | C++ | CPP/biweekly-contest-33/No1.cc | hxz1998/funny_leetcode | 1d2c425af09b57a030fc018ddc1e1a5ffb966cd0 | [
"Apache-2.0"
] | null | null | null | CPP/biweekly-contest-33/No1.cc | hxz1998/funny_leetcode | 1d2c425af09b57a030fc018ddc1e1a5ffb966cd0 | [
"Apache-2.0"
] | null | null | null | CPP/biweekly-contest-33/No1.cc | hxz1998/funny_leetcode | 1d2c425af09b57a030fc018ddc1e1a5ffb966cd0 | [
"Apache-2.0"
] | null | null | null | /**
* Created by Xiaozhong on 2020/8/22.
* Copyright (c) 2020/8/22 Xiaozhong. All rights reserved.
*/
#include "string"
#include "vector"
#include "iostream"
#include "algorithm"
using namespace std;
class Solution {
public:
string thousandSeparator(int n) {
if (n == 0) return "0";
if (n < 1000) return to_string(n);
string s = to_string(n);
int times = 0;
string ans = "";
for (int i = s.length() - 1; i >= 0; i--) {
ans.push_back(s[i]);
if (++times % 3 == 0) {
if (i != 0) ans.append(".");
times = 0;
}
}
reverse(ans.begin(), ans.end());
return ans;
}
};
int main() {
Solution s;
cout << s.thousandSeparator(51040) << endl;
cout << s.thousandSeparator(123456789) << endl;
} | 23.388889 | 58 | 0.511876 |
2b0f385d3a233869388c2265c1633d8543717815 | 46,960 | cpp | C++ | Breeder/BR.cpp | wolqws/sws | 4086745d38cc7375ee38843214a63bd8d285a84d | [
"MIT",
"Unlicense"
] | null | null | null | Breeder/BR.cpp | wolqws/sws | 4086745d38cc7375ee38843214a63bd8d285a84d | [
"MIT",
"Unlicense"
] | null | null | null | Breeder/BR.cpp | wolqws/sws | 4086745d38cc7375ee38843214a63bd8d285a84d | [
"MIT",
"Unlicense"
] | null | null | null | /*****************************************************************************
/ BR.cpp
/
/ Copyright (c) 2012-2014 Dominik Martin Drzic
/ http://forum.cockos.com/member.php?u=27094
/ https://code.google.com/p/sws-extension
/
/ 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 "stdafx.h"
#include "BR.h"
#include "BR_ContinuousActions.h"
#include "BR_Envelope.h"
#include "BR_Loudness.h"
#include "BR_MidiEditor.h"
#include "BR_Misc.h"
#include "BR_ProjState.h"
#include "BR_Tempo.h"
#include "BR_Update.h"
#include "BR_Util.h"
#include "../reaper/localize.h"
//!WANT_LOCALIZE_1ST_STRING_BEGIN:sws_actions
static COMMAND_T g_commandTable[] =
{
/******************************************************************************
* Envelopes *
******************************************************************************/
{ { DEFACCEL, "SWS/BR: Set closest envelope point's value to mouse cursor (perform until shortcut released)" }, "BR_ENV_PT_VAL_CLOSEST_MOUSE", SetEnvPointMouseValue, NULL, 0},
{ { DEFACCEL, "SWS/BR: Set closest left side envelope point's value to mouse cursor (perform until shortcut released)" }, "BR_ENV_PT_VAL_CLOSEST_LEFT_MOUSE", SetEnvPointMouseValue, NULL, 1},
{ { DEFACCEL, "SWS/BR: Move edit cursor to next envelope point" }, "SWS_BRMOVEEDITTONEXTENV", CursorToEnv1, NULL, 1},
{ { DEFACCEL, "SWS/BR: Move edit cursor to next envelope point and select it" }, "SWS_BRMOVEEDITSELNEXTENV", CursorToEnv1, NULL, 2},
{ { DEFACCEL, "SWS/BR: Move edit cursor to next envelope point and add to selection" }, "SWS_BRMOVEEDITTONEXTENVADDSELL", CursorToEnv2, NULL, 1},
{ { DEFACCEL, "SWS/BR: Move edit cursor to previous envelope point" }, "SWS_BRMOVEEDITTOPREVENV", CursorToEnv1, NULL, -1},
{ { DEFACCEL, "SWS/BR: Move edit cursor to previous envelope point and select it" }, "SWS_BRMOVEEDITSELPREVENV", CursorToEnv1, NULL, -2},
{ { DEFACCEL, "SWS/BR: Move edit cursor to previous envelope point and add to selection" }, "SWS_BRMOVEEDITTOPREVENVADDSELL", CursorToEnv2, NULL, -1},
{ { DEFACCEL, "SWS/BR: Select next envelope point" }, "BR_ENV_SEL_NEXT_POINT", SelNextPrevEnvPoint, NULL, 1},
{ { DEFACCEL, "SWS/BR: Select previous envelope point" }, "BR_ENV_SEL_PREV_POINT", SelNextPrevEnvPoint, NULL, -1},
{ { DEFACCEL, "SWS/BR: Expand envelope point selection to the right" }, "BR_ENV_SEL_EXPAND_RIGHT", ExpandEnvSel, NULL, 1},
{ { DEFACCEL, "SWS/BR: Expand envelope point selection to the left" }, "BR_ENV_SEL_EXPAND_LEFT", ExpandEnvSel, NULL, -1},
{ { DEFACCEL, "SWS/BR: Expand envelope point selection to the right (end point only)" }, "BR_ENV_SEL_EXPAND_RIGHT_END", ExpandEnvSelEnd, NULL, 1},
{ { DEFACCEL, "SWS/BR: Expand envelope point selection to the left (end point only)" }, "BR_ENV_SEL_EXPAND_L_END", ExpandEnvSelEnd, NULL, -1},
{ { DEFACCEL, "SWS/BR: Shrink envelope point selection from the right" }, "BR_ENV_SEL_SHRINK_RIGHT", ShrinkEnvSel, NULL, 1},
{ { DEFACCEL, "SWS/BR: Shrink envelope point selection from the left" }, "BR_ENV_SEL_SHRINK_LEFT", ShrinkEnvSel, NULL, -1},
{ { DEFACCEL, "SWS/BR: Shrink envelope point selection from the right (end point only)" }, "BR_ENV_SEL_SHRINK_RIGHT_END", ShrinkEnvSelEnd, NULL, 1},
{ { DEFACCEL, "SWS/BR: Shrink envelope point selection from the left (end point only)" }, "BR_ENV_SEL_SHRINK_LEFT_END", ShrinkEnvSelEnd, NULL, -1},
{ { DEFACCEL, "SWS/BR: Shift envelope point selection left" }, "BR_ENV_SHIFT_SEL_LEFT", ShiftEnvSelection, NULL, -1},
{ { DEFACCEL, "SWS/BR: Shift envelope point selection right" }, "BR_ENV_SHIFT_SEL_RIGHT", ShiftEnvSelection, NULL, 1},
{ { DEFACCEL, "SWS/BR: Select peaks in envelope (add to selection)" }, "BR_ENV_SEL_PEAKS_ADD", PeaksDipsEnv, NULL, 1},
{ { DEFACCEL, "SWS/BR: Select peaks in envelope" }, "BR_ENV_SEL_PEAKS", PeaksDipsEnv, NULL, 2},
{ { DEFACCEL, "SWS/BR: Select dips in envelope (add to selection)" }, "BR_ENV_SEL_DIPS_ADD", PeaksDipsEnv, NULL, -1},
{ { DEFACCEL, "SWS/BR: Select dips in envelope" }, "BR_ENV_SEL_DIPS", PeaksDipsEnv, NULL, -2},
{ { DEFACCEL, "SWS/BR: Unselect envelope points outside time selection" }, "BR_ENV_UNSEL_OUT_TIME_SEL", SelEnvTimeSel, NULL, -1},
{ { DEFACCEL, "SWS/BR: Unselect envelope points in time selection" }, "BR_ENV_UNSEL_IN_TIME_SEL", SelEnvTimeSel, NULL, 1},
{ { DEFACCEL, "SWS/BR: Set selected envelope points to next point's value" }, "BR_SET_ENV_TO_NEXT_VAL", SetEnvValToNextPrev, NULL, 1},
{ { DEFACCEL, "SWS/BR: Set selected envelope points to previous point's value" }, "BR_SET_ENV_TO_PREV_VAL", SetEnvValToNextPrev, NULL, -1},
{ { DEFACCEL, "SWS/BR: Set selected envelope points to last selected point's value" }, "BR_SET_ENV_TO_LAST_SEL_VAL", SetEnvValToNextPrev, NULL, 2},
{ { DEFACCEL, "SWS/BR: Set selected envelope points to first selected point's value" }, "BR_SET_ENV_TO_FIRST_SEL_VAL", SetEnvValToNextPrev, NULL, -2},
{ { DEFACCEL, "SWS/BR: Move closest envelope point to edit cursor" }, "BR_MOVE_CLOSEST_ENV_ECURSOR", MoveEnvPointToEditCursor, NULL, 0},
{ { DEFACCEL, "SWS/BR: Move closest selected envelope point to edit cursor" }, "BR_MOVE_CLOSEST_SEL_ENV_ECURSOR", MoveEnvPointToEditCursor, NULL, 1},
{ { DEFACCEL, "SWS/BR: Insert 2 envelope points at time selection" }, "BR_INSERT_2_ENV_POINT_TIME_SEL", Insert2EnvPointsTimeSelection, NULL, 1},
{ { DEFACCEL, "SWS/BR: Fit selected envelope points to time selection" }, "BR_FIT_ENV_POINTS_TO_TIMESEL", FitEnvPointsToTimeSel, NULL},
{ { DEFACCEL, "SWS/BR: Hide all but selected track envelope for all tracks" }, "BR_ENV_HIDE_ALL_BUT_ACTIVE", ShowActiveTrackEnvOnly, NULL, 0},
{ { DEFACCEL, "SWS/BR: Hide all but selected track envelope for selected tracks" }, "BR_ENV_HIDE_ALL_BUT_ACTIVE_SEL", ShowActiveTrackEnvOnly, NULL, 1},
{ { DEFACCEL, "SWS/BR: Insert new envelope point at mouse cursor using value at current position (obey snapping)" }, "BR_ENV_POINT_MOUSE_CURSOR", CreateEnvPointMouse, NULL},
{ { DEFACCEL, "SWS/BR: Save envelope point selection, slot 1" }, "BR_SAVE_ENV_SEL_SLOT_1", SaveEnvSelSlot, NULL, 0},
{ { DEFACCEL, "SWS/BR: Save envelope point selection, slot 2" }, "BR_SAVE_ENV_SEL_SLOT_2", SaveEnvSelSlot, NULL, 1},
{ { DEFACCEL, "SWS/BR: Save envelope point selection, slot 3" }, "BR_SAVE_ENV_SEL_SLOT_3", SaveEnvSelSlot, NULL, 2},
{ { DEFACCEL, "SWS/BR: Save envelope point selection, slot 4" }, "BR_SAVE_ENV_SEL_SLOT_4", SaveEnvSelSlot, NULL, 3},
{ { DEFACCEL, "SWS/BR: Save envelope point selection, slot 5" }, "BR_SAVE_ENV_SEL_SLOT_5", SaveEnvSelSlot, NULL, 4},
{ { DEFACCEL, "SWS/BR: Restore envelope point selection, slot 1" }, "BR_RESTORE_ENV_SEL_SLOT_1", RestoreEnvSelSlot, NULL, 0},
{ { DEFACCEL, "SWS/BR: Restore envelope point selection, slot 2" }, "BR_RESTORE_ENV_SEL_SLOT_2", RestoreEnvSelSlot, NULL, 1},
{ { DEFACCEL, "SWS/BR: Restore envelope point selection, slot 3" }, "BR_RESTORE_ENV_SEL_SLOT_3", RestoreEnvSelSlot, NULL, 2},
{ { DEFACCEL, "SWS/BR: Restore envelope point selection, slot 4" }, "BR_RESTORE_ENV_SEL_SLOT_4", RestoreEnvSelSlot, NULL, 3},
{ { DEFACCEL, "SWS/BR: Restore envelope point selection, slot 5" }, "BR_RESTORE_ENV_SEL_SLOT_5", RestoreEnvSelSlot, NULL, 4},
/******************************************************************************
* Loudness *
******************************************************************************/
{ { DEFACCEL, "SWS/BR: Analyze loudness..." }, "BR_ANALAYZE_LOUDNESS_DLG", AnalyzeLoudness, NULL, 0, IsAnalyzeLoudnessVisible},
{ { DEFACCEL, "SWS/BR: Normalize loudness of selected tracks..." }, "BR_NORMALIZE_LOUDNESS_TRACKS", NormalizeLoudness, NULL, 0, },
{ { DEFACCEL, "SWS/BR: Normalize loudness of selected tracks to -23 LUFS" }, "BR_NORMALIZE_LOUDNESS_TRACKS23", NormalizeLoudness, NULL, 1, },
{ { DEFACCEL, "SWS/BR: Normalize loudness of selected items..." }, "BR_NORMALIZE_LOUDNESS_ITEMS", NormalizeLoudness, NULL, 2, },
{ { DEFACCEL, "SWS/BR: Normalize loudness of selected items to -23 LUFS" }, "BR_NORMALIZE_LOUDNESS_ITEMS23", NormalizeLoudness, NULL, 3, },
/******************************************************************************
* Midi editor - Media item preview *
******************************************************************************/
{ { DEFACCEL, "SWS/BR: Stop media item preview" }, "BR_ME_STOP_PREV_ACT_ITEM", NULL, NULL, 0, NULL, 32060, ME_StopMidiTakePreview},
{ { DEFACCEL, "SWS/BR: Preview active media item through track" }, "BR_ME_PREV_ACT_ITEM", NULL, NULL, 1111, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Preview active media item through track (start from mouse position)" }, "BR_ME_PREV_ACT_ITEM_POS", NULL, NULL, 1211, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Preview active media item through track (sync with next measure)" }, "BR_ME_PREV_ACT_ITEM_SYNC", NULL, NULL, 1311, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Preview active media item through track and pause during preview" }, "BR_ME_PREV_ACT_ITEM_PAUSE", NULL, NULL, 1112, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Preview active media item through track and pause during preview (start from mouse position)" }, "BR_ME_PREV_ACT_ITEM_PAUSE_POS", NULL, NULL, 1212, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Preview active media item (selected notes only) through track" }, "BR_ME_PREV_ACT_ITEM_NOTES", NULL, NULL, 1121, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Preview active media item (selected notes only) through track (start from mouse position)" }, "BR_ME_PREV_ACT_ITEM_NOTES_POS", NULL, NULL, 1221, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Preview active media item (selected notes only) through track (sync with next measure)" }, "BR_ME_PREV_ACT_ITEM_NOTES_SYNC", NULL, NULL, 1321, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Preview active media item (selected notes only) through track and pause during preview" }, "BR_ME_PREV_ACT_ITEM_NOTES_PAUSE", NULL, NULL, 1122, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Preview active media item (selected notes only) through track and pause during preview (start from mouse position)" }, "BR_ME_PREV_ACT_ITEM_NOTES_PAUSE_POS", NULL, NULL, 1222, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Toggle preview active media item through track" }, "BR_ME_TPREV_ACT_ITEM", NULL, NULL, 2111, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Toggle preview active media item through track (start from mouse position)" }, "BR_ME_TPREV_ACT_ITEM_POS", NULL, NULL, 2211, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Toggle preview active media item through track (sync with next measure)" }, "BR_ME_TPREV_ACT_ITEM_SYNC", NULL, NULL, 2311, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Toggle preview active media item through track and pause during preview" }, "BR_ME_TPREV_ACT_ITEM_PAUSE", NULL, NULL, 2112, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Toggle preview active media item through track and pause during preview (start from mouse position)" }, "BR_ME_TPREV_ACT_ITEM_PAUSE_POS", NULL, NULL, 2212, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Toggle preview active media item (selected notes only) through track" }, "BR_ME_TPREV_ACT_ITEM_NOTES", NULL, NULL, 2121, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Toggle preview active media item (selected notes only) through track (start from mouse position)" }, "BR_ME_TPREV_ACT_ITEM_NOTES_POS", NULL, NULL, 2221, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Toggle preview active media item (selected notes only) through track (sync with next measure)" }, "BR_ME_TPREV_ACT_ITEM_NOTES_SYNC", NULL, NULL, 2321, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Toggle preview active media item (selected notes only) through track and pause during preview" }, "BR_ME_TPREV_ACT_ITEM_NOTES_PAUSE", NULL, NULL, 2122, NULL, 32060, ME_PreviewActiveTake},
{ { DEFACCEL, "SWS/BR: Toggle preview active media item (selected notes only) through track and pause during preview (start from mouse position)" }, "BR_ME_TPREV_ACT_ITEM_NOTES_PAUSE_POS", NULL, NULL, 2222, NULL, 32060, ME_PreviewActiveTake},
/******************************************************************************
* Midi editor - Misc *
******************************************************************************/
{ { DEFACCEL, "SWS/BR: Play from mouse cursor position" }, "BR_ME_PLAY_MOUSECURSOR", NULL, NULL, 0, NULL, 32060, ME_PlaybackAtMouseCursor},
{ { DEFACCEL, "SWS/BR: Play/pause from mouse cursor position" }, "BR_ME_PLAY_PAUSE_MOUSECURSOR", NULL, NULL, 1, NULL, 32060, ME_PlaybackAtMouseCursor},
{ { DEFACCEL, "SWS/BR: Play/stop from mouse cursor position" }, "BR_ME_PLAY_STOP_MOUSECURSOR", NULL, NULL, 2, NULL, 32060, ME_PlaybackAtMouseCursor},
{ { DEFACCEL, "SWS/BR: Save edit cursor position, slot 1" }, "BR_ME_SAVE_CURSOR_POS_SLOT_1", NULL, NULL, 0, NULL, 32060, ME_SaveCursorPosSlot},
{ { DEFACCEL, "SWS/BR: Save edit cursor position, slot 2" }, "BR_ME_SAVE_CURSOR_POS_SLOT_2", NULL, NULL, 1, NULL, 32060, ME_SaveCursorPosSlot},
{ { DEFACCEL, "SWS/BR: Save edit cursor position, slot 3" }, "BR_ME_SAVE_CURSOR_POS_SLOT_3", NULL, NULL, 2, NULL, 32060, ME_SaveCursorPosSlot},
{ { DEFACCEL, "SWS/BR: Save edit cursor position, slot 4" }, "BR_ME_SAVE_CURSOR_POS_SLOT_4", NULL, NULL, 3, NULL, 32060, ME_SaveCursorPosSlot},
{ { DEFACCEL, "SWS/BR: Save edit cursor position, slot 5" }, "BR_ME_SAVE_CURSOR_POS_SLOT_5", NULL, NULL, 4, NULL, 32060, ME_SaveCursorPosSlot},
{ { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 1" }, "BR_ME_RESTORE_CURSOR_POS_SLOT_1", NULL, NULL, 0, NULL, 32060, ME_RestoreCursorPosSlot},
{ { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 2" }, "BR_ME_RESTORE_CURSOR_POS_SLOT_2", NULL, NULL, 1, NULL, 32060, ME_RestoreCursorPosSlot},
{ { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 3" }, "BR_ME_RESTORE_CURSOR_POS_SLOT_3", NULL, NULL, 2, NULL, 32060, ME_RestoreCursorPosSlot},
{ { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 4" }, "BR_ME_RESTORE_CURSOR_POS_SLOT_4", NULL, NULL, 3, NULL, 32060, ME_RestoreCursorPosSlot},
{ { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 5" }, "BR_ME_RESTORE_CURSOR_POS_SLOT_5", NULL, NULL, 4, NULL, 32060, ME_RestoreCursorPosSlot},
{ { DEFACCEL, "SWS/BR: Save note selection from active take, slot 1" }, "BR_ME_SAVE_NOTE_SEL_SLOT_1", NULL, NULL, 0, NULL, 32060, ME_SaveNoteSelSlot},
{ { DEFACCEL, "SWS/BR: Save note selection from active take, slot 2" }, "BR_ME_SAVE_NOTE_SEL_SLOT_2", NULL, NULL, 1, NULL, 32060, ME_SaveNoteSelSlot},
{ { DEFACCEL, "SWS/BR: Save note selection from active take, slot 3" }, "BR_ME_SAVE_NOTE_SEL_SLOT_3", NULL, NULL, 2, NULL, 32060, ME_SaveNoteSelSlot},
{ { DEFACCEL, "SWS/BR: Save note selection from active take, slot 4" }, "BR_ME_SAVE_NOTE_SEL_SLOT_4", NULL, NULL, 3, NULL, 32060, ME_SaveNoteSelSlot},
{ { DEFACCEL, "SWS/BR: Save note selection from active take, slot 5" }, "BR_ME_SAVE_NOTE_SEL_SLOT_5", NULL, NULL, 4, NULL, 32060, ME_SaveNoteSelSlot},
{ { DEFACCEL, "SWS/BR: Restore note selection to active take, slot 1" }, "BR_ME_RESTORE_NOTE_SEL_SLOT_1", NULL, NULL, 0, NULL, 32060, ME_RestoreNoteSelSlot},
{ { DEFACCEL, "SWS/BR: Restore note selection to active take, slot 2" }, "BR_ME_RESTORE_NOTE_SEL_SLOT_2", NULL, NULL, 1, NULL, 32060, ME_RestoreNoteSelSlot},
{ { DEFACCEL, "SWS/BR: Restore note selection to active take, slot 3" }, "BR_ME_RESTORE_NOTE_SEL_SLOT_3", NULL, NULL, 2, NULL, 32060, ME_RestoreNoteSelSlot},
{ { DEFACCEL, "SWS/BR: Restore note selection to active take, slot 4" }, "BR_ME_RESTORE_NOTE_SEL_SLOT_4", NULL, NULL, 3, NULL, 32060, ME_RestoreNoteSelSlot},
{ { DEFACCEL, "SWS/BR: Restore note selection to active take, slot 5" }, "BR_ME_RESTORE_NOTE_SEL_SLOT_5", NULL, NULL, 4, NULL, 32060, ME_RestoreNoteSelSlot},
{ { DEFACCEL, "SWS/BR: Show only used CC lanes (detect 14-bit)" }, "BR_ME_SHOW_USED_CC_14_BIT", NULL, NULL, 0, NULL, 32060, ME_ShowUsedCCLanesDetect14Bit},
/******************************************************************************
* Misc *
******************************************************************************/
{ { DEFACCEL, "SWS/BR: Split selected items at tempo markers" }, "SWS_BRSPLITSELECTEDTEMPO", SplitItemAtTempo},
{ { DEFACCEL, "SWS/BR: Create project markers from selected tempo markers" }, "BR_TEMPO_TO_MARKERS", MarkersAtTempo},
{ { DEFACCEL, "SWS/BR: Enable \"Ignore project tempo\" for selected MIDI items (use tempo at item's start)" }, "BR_MIDI_PROJ_TEMPO_ENB", MidiItemTempo, NULL, 0},
{ { DEFACCEL, "SWS/BR: Disable \"Ignore project tempo\" for selected MIDI items" }, "BR_MIDI_PROJ_TEMPO_DIS", MidiItemTempo, NULL, 1},
{ { DEFACCEL, "SWS/BR: Trim MIDI item to active content" }, "BR_TRIM_MIDI_ITEM_ACT_CONTENT", MidiItemTrim, NULL},
{ { DEFACCEL, "SWS/BR: Create project markers from notes in selected MIDI items" }, "BR_MIDI_NOTES_TO_MARKERS", MarkersAtNotes},
{ { DEFACCEL, "SWS/BR: Create project markers from stretch markers in selected items" }, "BR_STRETCH_MARKERS_TO_MARKERS", MarkersAtStretchMarkers},
{ { DEFACCEL, "SWS/BR: Create project markers from selected items (name by item's notes)" }, "BR_ITEMS_TO_MARKERS_NOTES", MarkersRegionsAtItems, NULL, 0},
{ { DEFACCEL, "SWS/BR: Create regions from selected items (name by item's notes)" }, "BR_ITEMS_TO_REGIONS_NOTES", MarkersRegionsAtItems, NULL, 1},
{ { DEFACCEL, "SWS/BR: Toggle \"Grid snap settings follow grid visibility\"" }, "BR_OPTIONS_SNAP_FOLLOW_GRID_VIS", SnapFollowsGridVis, NULL, 0, IsSnapFollowsGridVisOn},
{ { DEFACCEL, "SWS/BR: Toggle \"Playback position follows project timebase when changing tempo\"" }, "BR_OPTIONS_PLAYBACK_TEMPO_CHANGE", PlaybackFollowsTempoChange, NULL, 0, IsPlaybackFollowingTempoChange},
{ { DEFACCEL, "SWS/BR: Set \"Apply trim when adding volume/pan envelopes\" to \"Always\"" }, "BR_OPTIONS_ENV_TRIM_ALWAYS", TrimNewVolPanEnvs, NULL, 0, IsTrimNewVolPanEnvsOn},
{ { DEFACCEL, "SWS/BR: Set \"Apply trim when adding volume/pan envelopes\" to \"In read/write\"" }, "BR_OPTIONS_ENV_TRIM_READWRITE", TrimNewVolPanEnvs, NULL, 1, IsTrimNewVolPanEnvsOn},
{ { DEFACCEL, "SWS/BR: Set \"Apply trim when adding volume/pan envelopes\" to \"Never\"" }, "BR_OPTIONS_ENV_TRIM_NEVER", TrimNewVolPanEnvs, NULL, 2, IsTrimNewVolPanEnvsOn},
{ { DEFACCEL, "SWS/BR: Cycle through record modes" }, "BR_CYCLE_RECORD_MODES", CycleRecordModes},
{ { DEFACCEL, "SWS/BR: Focus arrange window" }, "BR_FOCUS_ARRANGE_WND", FocusArrange},
{ { DEFACCEL, "SWS/BR: Toggle media item online/offline" }, "BR_TOGGLE_ITEM_ONLINE", ToggleItemOnline},
{ { DEFACCEL, "SWS/BR: Copy take media source file path of selected items to clipboard" }, "BR_TSOURCE_PATH_TO_CLIPBOARD", ItemSourcePathToClipBoard},
{ { DEFACCEL, "SWS/BR: Play from mouse cursor position" }, "BR_PLAY_MOUSECURSOR", PlaybackAtMouseCursor, NULL, 0},
{ { DEFACCEL, "SWS/BR: Play/pause from mouse cursor position" }, "BR_PLAY_PAUSE_MOUSECURSOR", PlaybackAtMouseCursor, NULL, 1},
{ { DEFACCEL, "SWS/BR: Play/stop from mouse cursor position" }, "BR_PLAY_STOP_MOUSECURSOR", PlaybackAtMouseCursor, NULL, 2},
{ { DEFACCEL, "SWS/BR: Save edit cursor position, slot 1" }, "BR_SAVE_CURSOR_POS_SLOT_1", SaveCursorPosSlot, NULL, 0},
{ { DEFACCEL, "SWS/BR: Save edit cursor position, slot 2" }, "BR_SAVE_CURSOR_POS_SLOT_2", SaveCursorPosSlot, NULL, 1},
{ { DEFACCEL, "SWS/BR: Save edit cursor position, slot 3" }, "BR_SAVE_CURSOR_POS_SLOT_3", SaveCursorPosSlot, NULL, 2},
{ { DEFACCEL, "SWS/BR: Save edit cursor position, slot 4" }, "BR_SAVE_CURSOR_POS_SLOT_4", SaveCursorPosSlot, NULL, 3},
{ { DEFACCEL, "SWS/BR: Save edit cursor position, slot 5" }, "BR_SAVE_CURSOR_POS_SLOT_5", SaveCursorPosSlot, NULL, 4},
{ { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 1" }, "BR_RESTORE_CURSOR_POS_SLOT_1", RestoreCursorPosSlot, NULL, 0},
{ { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 2" }, "BR_RESTORE_CURSOR_POS_SLOT_2", RestoreCursorPosSlot, NULL, 1},
{ { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 3" }, "BR_RESTORE_CURSOR_POS_SLOT_3", RestoreCursorPosSlot, NULL, 2},
{ { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 4" }, "BR_RESTORE_CURSOR_POS_SLOT_4", RestoreCursorPosSlot, NULL, 3},
{ { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 5" }, "BR_RESTORE_CURSOR_POS_SLOT_5", RestoreCursorPosSlot, NULL, 4},
/******************************************************************************
* Media item preview *
******************************************************************************/
{ { DEFACCEL, "SWS/BR: Preview media item under mouse" }, "BR_PREV_ITEM_CURSOR", PreviewItemAtMouse, NULL, 1111},
{ { DEFACCEL, "SWS/BR: Preview media item under mouse (start from mouse cursor position)" }, "BR_PREV_ITEM_CURSOR_POS", PreviewItemAtMouse, NULL, 1121},
{ { DEFACCEL, "SWS/BR: Preview media item under mouse (sync with next measure)" }, "BR_PREV_ITEM_CURSOR_SYNC", PreviewItemAtMouse, NULL, 1131},
{ { DEFACCEL, "SWS/BR: Preview media item under mouse and pause during preview" }, "BR_PREV_ITEM_PAUSE_CURSOR", PreviewItemAtMouse, NULL, 1112},
{ { DEFACCEL, "SWS/BR: Preview media item under mouse and pause during preview (start from mouse cursor position)" }, "BR_PREV_ITEM_PAUSE_CURSOR_POS", PreviewItemAtMouse, NULL, 1122},
{ { DEFACCEL, "SWS/BR: Preview media item under mouse at track fader volume" }, "BR_PREV_ITEM_CURSOR_FADER", PreviewItemAtMouse, NULL, 1211},
{ { DEFACCEL, "SWS/BR: Preview media item under mouse at track fader volume (start from mouse position)" }, "BR_PREV_ITEM_CURSOR_FADER_POS", PreviewItemAtMouse, NULL, 1221},
{ { DEFACCEL, "SWS/BR: Preview media item under mouse at track fader volume (sync with next measure)" }, "BR_PREV_ITEM_CURSOR_FADER_SYNC", PreviewItemAtMouse, NULL, 1231},
{ { DEFACCEL, "SWS/BR: Preview media item under mouse at track fader volume and pause during preview" }, "BR_PREV_ITEM_PAUSE_CURSOR_FADER", PreviewItemAtMouse, NULL, 1212},
{ { DEFACCEL, "SWS/BR: Preview media item under mouse at track fader volume and pause during preview (start from mouse cursor position)" }, "BR_PREV_ITEM_PAUSE_CURSOR_FADER_POS", PreviewItemAtMouse, NULL, 1222},
{ { DEFACCEL, "SWS/BR: Preview media item under mouse through track" }, "BR_PREV_ITEM_CURSOR_TRACK", PreviewItemAtMouse, NULL, 1311},
{ { DEFACCEL, "SWS/BR: Preview media item under mouse through track (start from mouse position)" }, "BR_PREV_ITEM_CURSOR_TRACK_POS", PreviewItemAtMouse, NULL, 1321},
{ { DEFACCEL, "SWS/BR: Preview media item under mouse through track (sync with next measure)" }, "BR_PREV_ITEM_CURSOR_TRACK_SYNC", PreviewItemAtMouse, NULL, 1331},
{ { DEFACCEL, "SWS/BR: Preview media item under mouse through track and pause during preview" }, "BR_PREV_ITEM_PAUSE_CURSOR_TRACK", PreviewItemAtMouse, NULL, 1312},
{ { DEFACCEL, "SWS/BR: Preview media item under mouse through track and pause during preview (start from mouse cursor position)" }, "BR_PREV_ITEM_PAUSE_CURSOR_TRACK_POS", PreviewItemAtMouse, NULL, 1322},
{ { DEFACCEL, "SWS/BR: Toggle preview media item under mouse" }, "BR_TPREV_ITEM_CURSOR", PreviewItemAtMouse, NULL, 2111},
{ { DEFACCEL, "SWS/BR: Toggle preview media item under mouse (start from mouse position)" }, "BR_TPREV_ITEM_CURSOR_POS", PreviewItemAtMouse, NULL, 2121},
{ { DEFACCEL, "SWS/BR: Toggle preview media item under mouse (sync with next measure)" }, "BR_TPREV_ITEM_CURSOR_SYNC", PreviewItemAtMouse, NULL, 2131},
{ { DEFACCEL, "SWS/BR: Toggle preview media item under mouse and pause during preview" }, "BR_TPREV_ITEM_PAUSE_CURSOR", PreviewItemAtMouse, NULL, 2112},
{ { DEFACCEL, "SWS/BR: Toggle preview media item under mouse and pause during preview (start from mouse cursor position)" }, "BR_TPREV_ITEM_PAUSE_CURSOR_POS", PreviewItemAtMouse, NULL, 2122},
{ { DEFACCEL, "SWS/BR: Toggle preview media item under mouse at track fader volume" }, "BR_TPREV_ITEM_CURSOR_FADER", PreviewItemAtMouse, NULL, 2211},
{ { DEFACCEL, "SWS/BR: Toggle preview media item under mouse at track fader volume (start from mouse position)" }, "BR_TPREV_ITEM_CURSOR_FADER_POS", PreviewItemAtMouse, NULL, 2221},
{ { DEFACCEL, "SWS/BR: Toggle preview media item under mouse at track fader volume (sync with next measure)" }, "BR_TPREV_ITEM_CURSOR_FADER_SYNC", PreviewItemAtMouse, NULL, 2231},
{ { DEFACCEL, "SWS/BR: Toggle preview media item under mouse at track fader volume and pause during preview" }, "BR_TPREV_ITEM_PAUSE_CURSOR_FADER", PreviewItemAtMouse, NULL, 2212},
{ { DEFACCEL, "SWS/BR: Toggle preview media item under mouse at track fader volume and pause during preview (start from mouse cursor position)" }, "BR_TPREV_ITEM_PAUSE_CURSOR_FADER_POS", PreviewItemAtMouse, NULL, 2222},
{ { DEFACCEL, "SWS/BR: Toggle preview media item under mouse through track" }, "BR_TPREV_ITEM_CURSOR_TRACK", PreviewItemAtMouse, NULL, 2311},
{ { DEFACCEL, "SWS/BR: Toggle preview media item under mouse through track (start from mouse position)" }, "BR_TPREV_ITEM_CURSOR_TRACK_POS", PreviewItemAtMouse, NULL, 2321},
{ { DEFACCEL, "SWS/BR: Toggle preview media item under mouse through track (sync with next measure)" }, "BR_TPREV_ITEM_CURSOR_TRACK_SYNC", PreviewItemAtMouse, NULL, 2331},
{ { DEFACCEL, "SWS/BR: Toggle preview media item under mouse through track and pause during preview" }, "BR_TPREV_ITEM_PAUSE_CURSOR_TRACK", PreviewItemAtMouse, NULL, 2312},
{ { DEFACCEL, "SWS/BR: Toggle preview media item under mouse through track and pause during preview (start from mouse cursor position)" }, "BR_TPREV_ITEM_PAUSE_CURSOR_TRACK_POS", PreviewItemAtMouse, NULL, 2322},
/******************************************************************************
* Grid *
******************************************************************************/
{ { DEFACCEL, "SWS/BR: Move closest tempo marker to mouse cursor (perform until shortcut released)" }, "BR_MOVE_CLOSEST_TEMPO_MOUSE", MoveGridToMouse, NULL, 0},
{ { DEFACCEL, "SWS/BR: Move closest grid line to mouse cursor (perform until shortcut released)" }, "BR_MOVE_GRID_TO_MOUSE", MoveGridToMouse, NULL, 1},
{ { DEFACCEL, "SWS/BR: Move closest measure grid line to mouse cursor (perform until shortcut released)" }, "BR_MOVE_M_GRID_TO_MOUSE", MoveGridToMouse, NULL, 2},
{ { DEFACCEL, "SWS/BR: Move closest grid line to edit cursor" }, "BR_MOVE_GRID_TO_EDIT_CUR", MoveGridToEditPlayCursor, NULL, 0},
{ { DEFACCEL, "SWS/BR: Move closest grid line to play cursor" }, "BR_MOVE_GRID_TO_PLAY_CUR", MoveGridToEditPlayCursor, NULL, 1},
{ { DEFACCEL, "SWS/BR: Move closest measure grid line to edit cursor" }, "BR_MOVE_M_GRID_TO_EDIT_CUR", MoveGridToEditPlayCursor, NULL, 2},
{ { DEFACCEL, "SWS/BR: Move closest measure grid line to play cursor" }, "BR_MOVE_M_GRID_TO_PLAY_CUR", MoveGridToEditPlayCursor, NULL, 3},
{ { DEFACCEL, "SWS/BR: Move closest left side grid line to edit cursor" }, "BR_MOVE_L_GRID_TO_EDIT_CUR", MoveGridToEditPlayCursor, NULL, 4},
{ { DEFACCEL, "SWS/BR: Move closest right side grid line to edit cursor" }, "BR_MOVE_R_GRID_TO_EDIT_CUR", MoveGridToEditPlayCursor, NULL, 5},
/******************************************************************************
* Tempo *
******************************************************************************/
{ { DEFACCEL, "SWS/BR: Move tempo marker forward 0.1 ms" }, "SWS_BRMOVETEMPOFORWARD01", MoveTempo, NULL, 1},
{ { DEFACCEL, "SWS/BR: Move tempo marker forward 1 ms" }, "SWS_BRMOVETEMPOFORWARD1", MoveTempo, NULL, 10},
{ { DEFACCEL, "SWS/BR: Move tempo marker forward 10 ms"}, "SWS_BRMOVETEMPOFORWARD10", MoveTempo, NULL, 100},
{ { DEFACCEL, "SWS/BR: Move tempo marker forward 100 ms"}, "SWS_BRMOVETEMPOFORWARD100", MoveTempo, NULL, 1000},
{ { DEFACCEL, "SWS/BR: Move tempo marker forward 1000 ms" }, "SWS_BRMOVETEMPOFORWARD1000", MoveTempo, NULL, 10000},
{ { DEFACCEL, "SWS/BR: Move tempo marker back 0.1 ms"}, "SWS_BRMOVETEMPOBACK01", MoveTempo, NULL, -1},
{ { DEFACCEL, "SWS/BR: Move tempo marker back 1 ms"}, "SWS_BRMOVETEMPOBACK1", MoveTempo, NULL, -10},
{ { DEFACCEL, "SWS/BR: Move tempo marker back 10 ms"}, "SWS_BRMOVETEMPOBACK10", MoveTempo, NULL, -100},
{ { DEFACCEL, "SWS/BR: Move tempo marker back 100 ms"}, "SWS_BRMOVETEMPOBACK100", MoveTempo, NULL, -1000},
{ { DEFACCEL, "SWS/BR: Move tempo marker back 1000 ms"}, "SWS_BRMOVETEMPOBACK1000", MoveTempo, NULL, -10000},
{ { DEFACCEL, "SWS/BR: Move tempo marker forward" }, "SWS_BRMOVETEMPOFORWARD", MoveTempo, NULL, 2},
{ { DEFACCEL, "SWS/BR: Move tempo marker back" }, "SWS_BRMOVETEMPOBACK", MoveTempo, NULL, -2},
{ { DEFACCEL, "SWS/BR: Move closest tempo marker to edit cursor" }, "BR_MOVE_CLOSEST_TEMPO", MoveTempo, NULL, 3},
{ { DEFACCEL, "SWS/BR: Increase tempo marker 0.001 BPM (preserve overall tempo)" }, "BR_INC_TEMPO_0.001_BPM", EditTempo, NULL, 1},
{ { DEFACCEL, "SWS/BR: Increase tempo marker 0.01 BPM (preserve overall tempo)" }, "BR_INC_TEMPO_0.01_BPM", EditTempo, NULL, 10},
{ { DEFACCEL, "SWS/BR: Increase tempo marker 0.1 BPM (preserve overall tempo)" }, "BR_INC_TEMPO_0.1_BPM", EditTempo, NULL, 100},
{ { DEFACCEL, "SWS/BR: Increase tempo marker 01 BPM (preserve overall tempo)" }, "BR_INC_TEMPO_1_BPM", EditTempo, NULL, 1000},
{ { DEFACCEL, "SWS/BR: Decrease tempo marker 0.001 BPM (preserve overall tempo)" }, "BR_DEC_TEMPO_0.001_BPM", EditTempo, NULL, -1},
{ { DEFACCEL, "SWS/BR: Decrease tempo marker 0.01 BPM (preserve overall tempo)" }, "BR_DEC_TEMPO_0.01_BPM", EditTempo, NULL, -10},
{ { DEFACCEL, "SWS/BR: Decrease tempo marker 0.1 BPM (preserve overall tempo)" }, "BR_DEC_TEMPO_0.1_BPM", EditTempo, NULL, -100},
{ { DEFACCEL, "SWS/BR: Decrease tempo marker 01 BPM (preserve overall tempo)" }, "BR_DEC_TEMPO_1_BPM", EditTempo, NULL, -1000},
{ { DEFACCEL, "SWS/BR: Increase tempo marker 0.001% (preserve overall tempo)" }, "BR_INC_TEMPO_0.001_PERC", EditTempo, NULL, 2},
{ { DEFACCEL, "SWS/BR: Increase tempo marker 0.01% (preserve overall tempo)" }, "BR_INC_TEMPO_0.01_PERC", EditTempo, NULL, 20},
{ { DEFACCEL, "SWS/BR: Increase tempo marker 0.1% (preserve overall tempo)" }, "BR_INC_TEMPO_0.1_PERC", EditTempo, NULL, 200},
{ { DEFACCEL, "SWS/BR: Increase tempo marker 01% (preserve overall tempo)" }, "BR_INC_TEMPO_1_PERC", EditTempo, NULL, 2000},
{ { DEFACCEL, "SWS/BR: Decrease tempo marker 0.001% (preserve overall tempo)" }, "BR_DEC_TEMPO_0.001_PERC", EditTempo, NULL, -2},
{ { DEFACCEL, "SWS/BR: Decrease tempo marker 0.01% (preserve overall tempo)" }, "BR_DEC_TEMPO_0.01_PERC", EditTempo, NULL, -20},
{ { DEFACCEL, "SWS/BR: Decrease tempo marker 0.1% (preserve overall tempo)" }, "BR_DEC_TEMPO_0.1_PERC", EditTempo, NULL, -200},
{ { DEFACCEL, "SWS/BR: Decrease tempo marker 01% (preserve overall tempo)" }, "BR_DEC_TEMPO_1_PERC", EditTempo, NULL, -2000},
{ { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (increase 0.001 BPM)" }, "BR_INC_GR_TEMPO_0.001_BPM", EditTempoGradual, NULL, 1},
{ { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (increase 0.01 BPM)" }, "BR_INC_GR_TEMPO_0.01_BPM", EditTempoGradual, NULL, 10},
{ { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (increase 0.1 BPM)" }, "BR_INC_GR_TEMPO_0.1_BPM", EditTempoGradual, NULL, 100},
{ { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (increase 01 BPM)" }, "BR_INC_GR_TEMPO_1_BPM", EditTempoGradual, NULL, 1000},
{ { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (decrease 0.001 BPM)" }, "BR_DEC_GR_TEMPO_0.001_BPM", EditTempoGradual, NULL, -1},
{ { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (decrease 0.01 BPM)" }, "BR_DEC_GR_TEMPO_0.01_BPM", EditTempoGradual, NULL, -10},
{ { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (decrease 0.1 BPM)" }, "BR_DEC_GR_TEMPO_0.1_BPM", EditTempoGradual, NULL, -100},
{ { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (decrease 01 BPM)" }, "BR_DEC_GR_TEMPO_1_BPM", EditTempoGradual, NULL, -1000},
{ { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (increase 0.001%)" }, "BR_INC_GR_TEMPO_0.001_PERC", EditTempoGradual, NULL, 2},
{ { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (increase 0.01%)" }, "BR_INC_GR_TEMPO_0.01_PERC", EditTempoGradual, NULL, 20},
{ { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (increase 0.1%)" }, "BR_INC_GR_TEMPO_0.1_PERC", EditTempoGradual, NULL, 200},
{ { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (increase 01%)" }, "BR_INC_GR_TEMPO_1_PERC", EditTempoGradual, NULL, 2000},
{ { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (decrease 0.001%)" }, "BR_DEC_GR_TEMPO_0.001_PERC", EditTempoGradual, NULL, -2},
{ { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (decrease 0.01%)" }, "BR_DEC_GR_TEMPO_0.01_PERC", EditTempoGradual, NULL, -20},
{ { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (decrease 0.1%)" }, "BR_DEC_GR_TEMPO_0.1_PERC", EditTempoGradual, NULL, -200},
{ { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (decrease 01%)" }, "BR_DEC_GR_TEMPO_1_PERC", EditTempoGradual, NULL, -2000},
{ { DEFACCEL, "SWS/BR: Delete tempo marker (preserve overall tempo and positions if possible)" }, "BR_DELETE_TEMPO", DeleteTempo},
{ { DEFACCEL, "SWS/BR: Delete tempo marker and preserve position and length of items (including MIDI events)" }, "BR_DELETE_TEMPO_ITEMS", DeleteTempoPreserveItems, NULL, 0},
{ { DEFACCEL, "SWS/BR: Delete tempo marker and preserve position and length of selected items (including MIDI events)" }, "BR_DELETE_TEMPO_ITEMS_SEL", DeleteTempoPreserveItems, NULL, 1},
{ { DEFACCEL, "SWS/BR: Create tempo markers at grid after every selected tempo marker" }, "BR_TEMPO_GRID", TempoAtGrid},
{ { DEFACCEL, "SWS/BR: Convert project markers to tempo markers..." }, "SWS_BRCONVERTMARKERSTOTEMPO", ConvertMarkersToTempoDialog, NULL, 0, IsConvertMarkersToTempoVisible},
{ { DEFACCEL, "SWS/BR: Select and adjust tempo markers..." }, "SWS_BRADJUSTSELTEMPO", SelectAdjustTempoDialog, NULL, 0, IsSelectAdjustTempoVisible},
{ { DEFACCEL, "SWS/BR: Randomize tempo markers..." }, "BR_RANDOMIZE_TEMPO", RandomizeTempoDialog},
{ { DEFACCEL, "SWS/BR: Set tempo marker shape (options)..." }, "BR_TEMPO_SHAPE_OPTIONS", TempoShapeOptionsDialog, NULL, 0, IsTempoShapeOptionsVisible},
{ { DEFACCEL, "SWS/BR: Set tempo marker shape to linear (preserve positions)" }, "BR_TEMPO_SHAPE_LINEAR", TempoShapeLinear},
{ { DEFACCEL, "SWS/BR: Set tempo marker shape to square (preserve positions)" }, "BR_TEMPO_SHAPE_SQUARE", TempoShapeSquare},
{ {}, LAST_COMMAND, },
};
//!WANT_LOCALIZE_1ST_STRING_END
static void InitContinuousActions ()
{
MoveGridToMouseInit();
SetEnvPointMouseValueInit();
}
int BR_Init ()
{
SWSRegisterCommands(g_commandTable);
InitContinuousActions (); // call only after registering all actions
ProjStateInit();
AnalyzeLoudnessInit();
VersionCheckInit();
return 1;
}
void BR_Exit ()
{
AnalyzeLoudnessExit();
}
bool BR_ActionHook (int cmd, int flag)
{
return ContinuousActionHook(cmd, flag);
}
void BR_CSurfSetPlayState (bool play, bool pause, bool rec)
{
MidiTakePreviewPlayState(play, rec);
} | 129.723757 | 246 | 0.549127 |
2b0f49c1638c7ea6bf8f3d63268c53943d885bd0 | 21,707 | hpp | C++ | src/character/character.hpp | Galfurian/RadMud | 1362cb0ee1b7a17386e57a98e29dd8baeea75af3 | [
"MIT"
] | 18 | 2016-05-26T18:11:31.000Z | 2022-02-10T20:00:52.000Z | src/character/character.hpp | Galfurian/RadMud | 1362cb0ee1b7a17386e57a98e29dd8baeea75af3 | [
"MIT"
] | null | null | null | src/character/character.hpp | Galfurian/RadMud | 1362cb0ee1b7a17386e57a98e29dd8baeea75af3 | [
"MIT"
] | 2 | 2016-06-30T15:20:01.000Z | 2020-08-27T18:28:33.000Z | /// @file character.hpp
/// @brief Define all the methods need to manipulate a character.
/// @details It's the master class for both Player and Mobile, here are defined
/// all the common methods needed to manipulate every dynamic living
/// beeing that are playing.
/// @author Enrico Fraccaroli
/// @date Aug 23 2014
/// @copyright
/// Copyright (c) 2016 Enrico Fraccaroli <enrico.fraccaroli@gmail.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.
#pragma once
#include "ability.hpp"
#include "exit.hpp"
#include "race.hpp"
#include "item.hpp"
#include "faction.hpp"
#include "bodyPart.hpp"
#include "stringBuilder.hpp"
#include "effectManager.hpp"
#include "processInput.hpp"
#include "combatAction.hpp"
#include "argumentHandler.hpp"
#include "meleeWeaponItem.hpp"
#include "rangedWeaponItem.hpp"
#include "characterPosture.hpp"
#include "characterVector.hpp"
#include "skillManager.hpp"
#include "itemUtils.hpp"
#include <deque>
#include <mutex>
class Room;
class Player;
class Mobile;
struct lua_State;
/// The list of possible actions.
using GenderType = enum class GenderType_t
{
None, ///< The character has no gender (robot).
Female, ///< The character is a female.
Male ///< The character is a male.
};
/// Used to determine the flag of the character.
using CharacterFlag = enum class CharacterFlag_t
{
None = 0, ///< No flag.
IsGod = 1, ///< The character is a GOD.
Invisible = 2 ///< The character is invisible.
};
/// @brief Character class, father of Player and Mobile.
/// @details
/// It's the main class that contains all the information that both
/// players and NPCs shares. In order to allow dynamic casting(polymorphism),
/// i've created a method called isMobile, used to identify the subtype of the
/// subclass.
class Character :
public UpdateInterface
{
public:
/// Character name.
std::string name;
/// Character description.
std::string description;
/// Character gender.
GenderType gender;
/// Character weight.
double weight;
/// Character level.
unsigned int level;
/// Character flags.
unsigned int flags;
/// The character race.
Race * race;
/// The character faction.
Faction * faction;
/// Character health value.
unsigned int health;
/// Character stamina value.
unsigned int stamina;
/// Character level of hunger
int hunger;
/// Character level of thirst.
int thirst;
/// Character abilities.
std::map<Ability, unsigned int> abilities;
/// The current room the character is in.
Room * room;
/// Character's inventory.
ItemVector inventory;
/// Character's equipment.
ItemVector equipment;
/// Character's posture.
CharacterPosture posture;
/// The lua_State associated with this character.
lua_State * L;
/// Character current action.
std::deque<std::shared_ptr<GeneralAction>> actionQueue;
/// Mutex for the action queue.
mutable std::mutex actionQueueMutex;
/// The input handler.
std::shared_ptr<ProcessInput> inputProcessor;
/// Active effects on player.
EffectManager effectManager;
/// The player's list of skills.
SkillManager skillManager;
/// List of opponents.
CombatHandler combatHandler;
/// @brief Constructor.
Character();
/// @brief Destructor.
virtual ~Character();
/// @brief Disable copy constructor.
Character(const Character & source) = delete;
/// @brief Disable assign operator.
Character & operator=(const Character &) = delete;
/// @brief Check the correctness of the character information.
/// @return <b>True</b> if the information are correct,<br>
/// <b>False</b> otherwise.
virtual bool check() const;
/// @brief Used to identify if this character is an npc.
/// @return <b>True</b> if is an NPC,<br>
/// <b>False</b> otherwise.
virtual bool isMobile() const;
/// @brief Used to identify if this character is a player.
/// @return <b>True</b> if is an NPC,<br>
/// <b>False</b> otherwise.
virtual bool isPlayer() const;
/// @brief Fills the provided table with the information concerning the
/// character.
/// @param sheet The table that has to be filled.
virtual void getSheet(Table & sheet) const;
/// @brief Initializes the variables of the chracter.
virtual void initialize();
/// @brief Return the name of the character with all lowercase characters.
/// @return The name of the character.
virtual std::string getName() const = 0;
/// @brief Return the name of the character.
/// @return The name of the character.
std::string getNameCapital() const;
/// @brief Return the static description of this character.
/// @return The static description.
std::string getStaticDesc() const;
/// @brief Return the subject pronoun for the character.
std::string getSubjectPronoun() const;
/// @brief Return the possessive pronoun for the character.
std::string getPossessivePronoun() const;
/// @brief Return the object pronoun for the character.
std::string getObjectPronoun() const;
/// @brief Allows to set the value of a given ability.
/// @param ability The ability to set.
/// @param value The value to set.
/// @return <b>True</b> if the value is correct,<br>
/// <b>False</b> otherwise.
bool setAbility(const Ability & ability, const unsigned int & value);
/// @brief Provides the value of the given ability.
/// @param ability The ability to retrieve.
/// @param withEffects If set to false, this function just return the
/// ability value without the contribution due to
/// the active effects.
/// @return The overall ability value.
unsigned int getAbility(const Ability & ability,
bool withEffects = true) const;
/// @brief Provides the modifier of the given ability.
/// @param ability The ability of which the modifier has to be
/// retrieved.
/// @param withEffects If set to false, this function just return the
/// ability modifier without the contribution due
/// to the active effects.
/// @return The overall ability modifer.
unsigned int getAbilityModifier(const Ability & ability,
bool withEffects = true) const;
/// @brief Provides the base ten logarithm of the desired ability
/// modifier, multiplied by an optional multiplier. Also,
/// a base value can be provided.
/// @details Value = Base + (Multiplier * log10(AbilityModifier))
/// @param ability The ability of which the modifier has to be
/// retrieved.
/// @param base The base value to which the evaluated modifier is summed.
/// @param multiplier The log10 modifer is multiplied by this value.
/// @param withEffects If set to false, this function just return the
/// ability modifier without the contribution due
/// to the active effects.
/// @return The overall base ten logarithm of the given ability modifer.
unsigned int getAbilityLog(
const Ability & ability,
const double & base = 0.0,
const double & multiplier = 1.0,
const bool & withEffects = true) const;
/// @brief Allows to SET the health value.
/// @param value The value to set.
/// @param force <b>True</b> if the value is greather than the maximum
/// the function set the health to it and
/// returns true,<br>
/// <b>False</b> return false.
/// @return <b>True</b> if the function has set the value,<br>
/// <b>False</b> otherwise.
bool setHealth(const unsigned int & value, const bool & force = false);
/// @brief Allows to ADD a value to the current health value.
/// @param value The value to add.
/// @param force <b>True</b> if the resulting value is greather than
/// the maximum the function set the health to it and
/// returns true,<br>
/// <b>False</b> return false.
/// @return <b>True</b> if the function has added the value,<br>
/// <b>False</b> otherwise.
bool addHealth(const unsigned int & value, const bool & force = false);
/// @brief Allows to REMOVE a value to the current health value.
/// @param value The value to remove.
/// @param force <b>True</b> if the resulting value is lesser than
/// zero the function set the health to it and
/// returns true,<br>
/// <b>False</b> return false.
/// @return <b>True</b> if the function has removed the value,<br>
/// <b>False</b> otherwise.
bool remHealth(const unsigned int & value, const bool & force = false);
/// @brief Return the max health value.
/// @param withEffects <b>True</b> also add the health due to effects,<br>
/// <b>False</b> otherwise.
/// @return The maximum health for this character.
unsigned int getMaxHealth(bool withEffects = true) const;
/// @brief Get character condition.
/// @param self If the sentence has to be for another character or not.
/// @return Condition of this character.
std::string getHealthCondition(const bool & self = false);
/// @brief Allows to SET the stamina value.
/// @param value The value to set.
/// @param force <b>True</b> if the value is greather than the maximum
/// the function set the stamina to it and
/// returns true,<br>
/// <b>False</b> return false.
/// @return <b>True</b> if the function has set the value,<br>
/// <b>False</b> otherwise.
bool setStamina(const unsigned int & value, const bool & force = false);
/// @brief Allows to ADD a value to the current stamina value.
/// @param value The value to add.
/// @param force <b>True</b> if the resulting value is greather than
/// the maximum the function set the stamina to it and
/// returns true,<br>
/// <b>False</b> return false.
/// @return <b>True</b> if the function has added the value,<br>
/// <b>False</b> otherwise.
bool addStamina(const unsigned int & value, const bool & force = false);
/// @brief Allows to REMOVE a value to the current stamina value.
/// @param value The value to remove.
/// @param force <b>True</b> if the resulting value is lesser than
/// zero the function set the stamina to it and
/// returns true,<br>
/// <b>False</b> return false.
/// @return <b>True</b> if the function has removed the value,<br>
/// <b>False</b> otherwise.
bool remStamina(const unsigned int & value, const bool & force = false);
/// @brief Return the max stamina value.
/// @param withEffects <b>True</b> also add the stamina due to effects,<br>
/// <b>False</b> otherwise.
/// @return The maximum stamina for this character.
unsigned int getMaxStamina(bool withEffects = true) const;
/// @brief Get the character stamina condition.
/// @return Stamina condition of the character.
std::string getStaminaCondition();
/// @brief Evaluate the maximum distance at which the character can still see.
/// @return The maximum radius of view.
int getViewDistance() const;
/// @brief Allows to set an action.
/// @param _action The action that has to be set.
void pushAction(const std::shared_ptr<GeneralAction> & _action);
/// @brief Provides a pointer to the action at the front position and
/// then remove it from the queue.
void popAction();
/// @brief Provides a pointer to the current action.
std::shared_ptr<GeneralAction> & getAction();
/// @brief Provides a pointer to the current action.
std::shared_ptr<GeneralAction> const & getAction() const;
/// @brief Performs any pending action.
void performAction();
/// @brief Allows to reset the entire action queue.
void resetActionQueue();
/// @brief Search for the item in the inventory.
/// @param key The item to search.
/// @param number Position of the item we want to look for.
/// @return The item, if it's in the character's inventory.
inline Item * findInventoryItem(std::string const & key, int & number)
{
return ItemUtils::FindItemIn(inventory, key, number);
}
/// @brief Search for the item in equipment.
/// @param key The item to search.
/// @param number Position of the item we want to look for.
/// @return The item, if it's in the character's equipment.
Item * findEquipmentItem(std::string const & key, int & number)
{
return ItemUtils::FindItemIn(equipment, key, number);
}
/// @brief Search an item nearby, (eq, inv, room).
/// @param key The item to search.
/// @param number Position of the item we want to look for.
/// @return The item, if it's found.
Item * findNearbyItem(std::string const & key, int & number);
/// @brief Search the item at given position and return it.
/// @param bodyPart The body part where the method need to search the item.
/// @return The item, if it's in the character's equipment.
Item * findItemAtBodyPart(const std::shared_ptr<BodyPart> & bodyPart) const;
/// @brief Add the passed item to character's inventory.
/// @param item The item to add to inventory.
virtual void addInventoryItem(Item *& item);
/// @brief Equip the passed item.
/// @param item The item to equip.
virtual void addEquipmentItem(Item *& item);
/// @brief Remove the passed item from the character's inventory.
/// @param item The item to remove from inventory.
/// @return <b>True</b> if the operation goes well,<br>
/// <b>False</b> otherwise.
virtual bool remInventoryItem(Item * item);
/// @brief Remove from current equipment the item.
/// @param item The item to remove.
/// @return <b>True</b> if the operation goes well,<br>
/// <b>False</b> otherwise.
virtual bool remEquipmentItem(Item * item);
/// @brief Check if the player can carry the item.
/// @param item The item we want to check.
/// @param quantity The amount of item to check (by default it is 1).
/// @return <b>True</b> if the character can lift the item,<br>
/// <b>False</b> otherwise.
bool canCarry(Item * item, unsigned int quantity) const;
/// @brief The total carrying weight for this character.
/// @return The total carrying weight.
double getCarryingWeight() const;
/// @brief The maximum carrying weight for this character.
/// @return The maximum carrying weight.
double getMaxCarryingWeight() const;
/// @brief Check if the character can wield a given item.
/// @param item The item to wield.
/// @param error The error message.
/// @return Where the item can be wielded.
std::vector<std::shared_ptr<BodyPart>> canWield(Item * item,
std::string & error) const;
/// @brief Check if the character can wear a given item.
/// @param item The item to wear.
/// @param error The error message.
/// @return Where the item can be worn.
std::vector<std::shared_ptr<BodyPart>> canWear(Item * item,
std::string & error) const;
/// @brief Checks if inside the inventory there is a light source.
/// @return <b>True</b> if there is a light source,<br>
/// <b>False</b> otherwise.
bool inventoryIsLit() const;
/// @brief Sums the given value to the current thirst.
/// @param value The value to sum.
void addThirst(const int & value);
/// @brief Get character level of thirst.
/// @return Thirst of this character.
std::string getThirstCondition() const;
/// @brief Sums the given value to the current hunger.
/// @param value The value to sum.
void addHunger(const int & value);
/// @brief Get character level of hunger.
/// @return Hunger of this character.
std::string getHungerCondition() const;
/// @brief Update the health.
void updateHealth();
/// @brief Update the stamina.
void updateStamina();
/// @brief Update the hunger.
void updateHunger();
/// @brief Update the thirst.
void updateThirst();
/// @brief Update the list of expired effects.
void updateExpiredEffects();
/// @brief Update the list of activated effects.
void updateActivatedEffects();
/// @brief Provide a detailed description of the character.
/// @return A detailed description of the character.
std::string getLook();
/// @brief Check if the current character can see the target character.
/// @param target The target character.
/// @return <b>True</b> if the can see the other character,<br>
/// <b>False</b> otherwise.
bool canSee(Character * target) const;
// Combat functions.
/// @brief Provides the overall armor class.
/// @return The armor class.
unsigned int getArmorClass() const;
/// @brief Function which checks if the character can attack
/// with a weapon equipped at the given body part.
/// @param bodyPart The body part at which the weapon could be.
/// @return <b>True</b> if the item is there,<br>
/// <b>False</b> otherwise.
bool canAttackWith(const std::shared_ptr<BodyPart> & bodyPart) const;
/// @brief Checks if the given target is both In Sight and within the Range of Sight.
/// @param target The target character.
/// @param range The maximum range.
/// @return <b>True</b> if the target is in sight,<br>
/// <b>False</b> otherwise.
bool isAtRange(Character * target, const int & range);
/// @brief Handle what happend when this character die.
virtual void kill();
/// @brief Create a corpse on the ground.
/// @return A pointer to the corpse.
Item * createCorpse();
/// @brief Handle character input.
/// @param command Command that need to be handled.
/// @return <b>True</b> if the command has been correctly executed,<br>
/// <b>False</b> otherwise.
bool doCommand(const std::string & command);
/// @brief Returns the character <b>statically</b> casted to player.
/// @return The player version of the character.
Player * toPlayer();
/// @brief Returns the character <b>statically</b> casted to mobile.
/// @return The mobile version of the character.
Mobile * toMobile();
/// @brief Specific function used by lua to add an equipment item.
void luaAddEquipment(Item * item);
/// @brief Specific function used by lua to remove an equipment item.
bool luaRemEquipment(Item * item);
/// @brief Specific function used by lua to add an inventory item.
void luaAddInventory(Item * item);
/// @brief Specific function used by lua to remove an inventory item.
bool luaRemInventory(Item * item);
/// @brief Operator used to order the character based on their name.
bool operator<(const class Character & source) const;
/// @brief Operator used to order the character based on their name.
bool operator==(const class Character & source) const;
/// @brief Sends a message to the character.
/// @param msg Message to send.
virtual void sendMsg(const std::string & msg);
/// @brief Sends a message to the character.
/// @param msg The message to send
/// @param args Packed arguments.
template<typename ... Args>
void sendMsg(const std::string & msg, const Args & ... args)
{
this->sendMsg(StringBuilder::build(msg, args ...));
}
protected:
void updateTicImpl() override;
void updateHourImpl() override;
};
/// @addtogroup FlagsToList
/// @{
/// Return the string describing the type of Gender.
std::string GetGenderTypeName(GenderType type);
/// Return the string describing the given character flag.
std::string GetCharacterFlagName(CharacterFlag flag);
/// Return a list of string containg the Character flags contained inside the value.
std::string GetCharacterFlagString(unsigned int flags);
/// @}
| 39.111712 | 89 | 0.642466 |
2b108cb66775235bc0ce8abd982dc031aad83e6d | 760 | hpp | C++ | TurbulentArena/DebugWindow.hpp | doodlemeat/Turbulent-Arena | 9030f291693e670f7751e23538e649cc24dc929f | [
"MIT"
] | 2 | 2017-02-03T04:30:29.000Z | 2017-03-27T19:33:38.000Z | TurbulentArena/DebugWindow.hpp | doodlemeat/Turbulent-Arena | 9030f291693e670f7751e23538e649cc24dc929f | [
"MIT"
] | null | null | null | TurbulentArena/DebugWindow.hpp | doodlemeat/Turbulent-Arena | 9030f291693e670f7751e23538e649cc24dc929f | [
"MIT"
] | null | null | null | //DebugWindow.hpp
#pragma once
#include <sstream>
namespace bjoernligan
{
class DebugWindow : public sf::Drawable
{
private:
DebugWindow(const bool &p_bActive);
DebugWindow(const DebugWindow&);
DebugWindow& operator=(const DebugWindow&);
public:
typedef std::unique_ptr<DebugWindow> Ptr;
static Ptr Create(const bool &p_bActive = false);
bool Initialize();
void draw(sf::RenderTarget& target, sf::RenderStates states) const;
void Update(const float &p_fDeltaTime);
void SetActive(const bool &p_bActive);
void SetPos(const float &p_x, const float &p_y);
void SetPos(const sf::Vector2f &p_xPos);
private:
bool m_bActive;
sf::Text m_xFps;
std::stringstream m_xSStream;
std::unique_ptr<sf::RectangleShape> m_xBgRect;
};
} | 22.352941 | 69 | 0.734211 |
2b1308ba57844e88e867c04472f9112a469d6e1b | 2,512 | cpp | C++ | code/src/pdflib/page_tree.cpp | jgresula/jagpdf | 6c36958b109e6522e6b57d04144dd83c024778eb | [
"MIT"
] | 54 | 2015-02-16T14:25:16.000Z | 2022-03-16T07:54:25.000Z | code/src/pdflib/page_tree.cpp | jgresula/jagpdf | 6c36958b109e6522e6b57d04144dd83c024778eb | [
"MIT"
] | null | null | null | code/src/pdflib/page_tree.cpp | jgresula/jagpdf | 6c36958b109e6522e6b57d04144dd83c024778eb | [
"MIT"
] | 30 | 2015-03-05T08:52:25.000Z | 2022-02-17T13:49:15.000Z | // Copyright (c) 2005-2009 Jaroslav Gresula
//
// Distributed under the MIT license (See accompanying file
// LICENSE.txt or copy at http://jagpdf.org/LICENSE.txt)
//
#include "precompiled.h"
#include "page_tree.h"
#include "page_tree_node.h"
#include "page_object.h"
#include <core/generic/refcountedimpl.h>
#include <boost/ref.hpp>
using namespace boost;
namespace jag {
namespace pdf {
PageTreeBuilder::PageTreeBuilder(DocWriterImpl& doc, int t)
: m_doc(doc)
, m_t(t)
, m_max_children(2*t)
{
}
//
//
//
TreeNode::TreeNodePtr PageTreeBuilder::BuildPageTree(
boost::ptr_vector<PageObject>& nodes)
{
// copy page objects to buffer_a
m_buffer_a.reserve(nodes.size());
boost::ptr_vector<PageObject>::iterator it;
for (it = nodes.begin(); it != nodes.end(); ++it)
{
TreeNode::TreeNodePtr data(&*it);
m_buffer_a.push_back(data);
}
m_source = &m_buffer_a;
// reserve some memory in the buffer_b
m_buffer_b.reserve(nodes.size() / m_max_children + 1);
m_dest = &m_buffer_b;
// build tree levels, one at a time
do
{
BuildOneTreeLevel();
std::swap(m_source, m_dest);
m_dest->resize(0);
}
while(m_source->size() > 1);
if (m_source->size() == 1)
{
return (*m_source)[0];
}
else
{
return TreeNode::TreeNodePtr();
}
}
//
//
//
void PageTreeBuilder::BuildOneTreeLevel()
{
int remaining_nodes = static_cast<int>(m_source->size());
int start_offset = 0;
while(remaining_nodes)
{
int num_kids_for_this_node = 0;
if (remaining_nodes >= m_max_children + m_t)
{
// at least two nodes are going to be created
num_kids_for_this_node = m_max_children;
}
else if (remaining_nodes <= m_max_children)
{
// only single node is going to be created
num_kids_for_this_node = remaining_nodes;
}
else
{
// exactly two nodes are going to be created, none of them is full
num_kids_for_this_node = remaining_nodes / 2;
}
TreeNode::TreeNodePtr new_node = m_nodes.construct(ref(m_doc));
m_dest->push_back(new_node);
for (int i=start_offset; i<start_offset+num_kids_for_this_node; ++i)
{
new_node->add_kid(m_source->at(i));
}
start_offset += num_kids_for_this_node;
remaining_nodes -= num_kids_for_this_node;
}
}
}} //namespace jag::pdf
| 23.045872 | 78 | 0.617834 |
2b154804a41ee453695ad335d17a303a816c4e21 | 402 | hpp | C++ | raptor/gallery/par_matrix_market.hpp | lukeolson/raptor | 526c88d0801634e6fb41375ae077f2d4aa3241a4 | [
"BSD-2-Clause"
] | 25 | 2017-11-20T21:45:43.000Z | 2019-01-27T15:03:25.000Z | raptor/gallery/par_matrix_market.hpp | haoxiangmiao/raptor | 866977b8166e39675a6a1fb883c57b7b9395d32f | [
"BSD-2-Clause"
] | 3 | 2017-11-21T01:20:20.000Z | 2018-11-16T17:33:06.000Z | raptor/gallery/par_matrix_market.hpp | haoxiangmiao/raptor | 866977b8166e39675a6a1fb883c57b7b9395d32f | [
"BSD-2-Clause"
] | 5 | 2017-11-20T22:03:57.000Z | 2018-12-05T10:30:22.000Z | /*
* Matrix Market I/O library for ANSI C
*
* See http://math.nist.gov/MatrixMarket for details.
*
*
*/
#ifndef PAR_MM_IO_H
#define PAR_MM_IO_H
#include "matrix_market.hpp"
#include "core/types.hpp"
#include "core/par_matrix.hpp"
using namespace raptor;
/* high level routines */
ParCSRMatrix* read_par_mm(const char *fname);
void write_par_mm(ParCSRMatrix* A, const char *fname);
#endif
| 15.461538 | 54 | 0.723881 |
2b15ae0c66fac4c2c4afbc7a6ce2c233d8fe5be9 | 867 | hpp | C++ | include/basic3d/zbuffer.hpp | MasterQ32/Basic3D | 1da1ad64116018afe2b97372d9632d0b72b1ff95 | [
"MIT"
] | 1 | 2018-11-15T22:29:55.000Z | 2018-11-15T22:29:55.000Z | include/basic3d/zbuffer.hpp | MasterQ32/Basic3D | 1da1ad64116018afe2b97372d9632d0b72b1ff95 | [
"MIT"
] | null | null | null | include/basic3d/zbuffer.hpp | MasterQ32/Basic3D | 1da1ad64116018afe2b97372d9632d0b72b1ff95 | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include <array>
#include <limits>
namespace Basic3D
{
//! Provides a basic z-buffer
template<int WIDTH, int HEIGHT, typename Depth = std::uint16_t>
class ZBuffer
{
public:
typedef Depth depth_t;
private:
std::array<depth_t, WIDTH * HEIGHT> zvalues;
public:
ZBuffer() : zvalues() {
this->clear();
}
void clear(depth_t depth = std::numeric_limits<depth_t>::max()) {
for(int i = 0; i < WIDTH * HEIGHT; i++)
this->zvalues[i] = depth;
}
public:
void setDepth(int x, int y, depth_t const & value) {
zvalues[y * WIDTH + x] = value;
}
depth_t const & getDepth(int x, int y) const {
return zvalues[y * WIDTH + x];
}
};
}
| 23.432432 | 74 | 0.509804 |
2b18c1a58e5c452db93b6d20e5409e76dce55d31 | 1,331 | cpp | C++ | 109. Convert Sorted List to Binary Search Tree/solution.cpp | KailinLi/LeetCode-Solutions | bad6aa401b290a203a572362e63e0b1085f7fc36 | [
"MIT"
] | 2 | 2017-03-27T09:53:32.000Z | 2017-04-07T07:48:54.000Z | 109. Convert Sorted List to Binary Search Tree/solution.cpp | KailinLi/LeetCode-Solutions | bad6aa401b290a203a572362e63e0b1085f7fc36 | [
"MIT"
] | null | null | null | 109. Convert Sorted List to Binary Search Tree/solution.cpp | KailinLi/LeetCode-Solutions | bad6aa401b290a203a572362e63e0b1085f7fc36 | [
"MIT"
] | null | null | null | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(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* change(ListNode* start, int length) {
if (length == 1) {
TreeNode* get = new TreeNode(start->val);
return get;
}
else if (length == 2) {
TreeNode* get = new TreeNode(start->next->val);
TreeNode* next = new TreeNode(start->val);
get->left = next;
return get;
}
ListNode *p = start;
int half = length / 2 + 1;
for (int i = 1; i < half; i++) {
p = p->next;
}
TreeNode* get = new TreeNode(p->val);
get->left = change(start, half - 1);
get->right = change(p->next, length - half);
return get;
}
TreeNode* sortedListToBST(ListNode* head) {
ListNode* p = head;
int length = 0;
while (p) {
p = p->next;
length++;
}
if (length == 0) return nullptr;
return change(head, length);
}
}; | 26.098039 | 59 | 0.486852 |
2b24d50623f5ba9c0ed59fd55b0cb00c616c6aa3 | 2,353 | tpp | C++ | src/algorithms/rem_factorial_EltZZ.tpp | adienes/remainder-tree | 0aa76214ab6f2a4389ec45a239ea660749989a90 | [
"MIT"
] | null | null | null | src/algorithms/rem_factorial_EltZZ.tpp | adienes/remainder-tree | 0aa76214ab6f2a4389ec45a239ea660749989a90 | [
"MIT"
] | null | null | null | src/algorithms/rem_factorial_EltZZ.tpp | adienes/remainder-tree | 0aa76214ab6f2a4389ec45a239ea660749989a90 | [
"MIT"
] | null | null | null | // included by rem_factorial_custom.tpp (in case we want to change the file location)
#include <cassert>
#include <NTL/ZZ_pX.h>
#include <NTL/matrix.h>
#include "../elements/element.hpp"
#include "factorial_engine.hpp"
using NTL::ZZ;
using NTL::ZZ_p;
using NTL::ZZ_pX;
using NTL::Mat;
Elt<ZZ> calculate_factorial(long n, const Elt<ZZ>& m, const std::function<vector<Elt<ZZ>> (long, long)>& get_A, const PolyMatrix& formula){
if (n == 0) {
return Elt<ZZ>(1);
}
assert(("No formula given!" && not formula.empty()));
assert(("Element given is not a square matrix." && (formula.size() == formula[0].size())));
// Matrix-type elements
assert(("ZZ's must have 1x1 matrix formulas." && ((long)formula.size() <= 1)));
// Do naive_factorial if n is small enough
if(n < 30000 || formula.size() == 0){
return naive_factorial<Elt<ZZ>, Elt<ZZ>>(n, m, get_A); // TODO: write naive_factorial
}
long maxdeg = 0;
for(const auto& term : formula[0][0]){
if(term.first > maxdeg){
maxdeg = term.first;
}
}
// Linear and Polynomial-type elements
if(n < 1000000000 || maxdeg >= 2){
// TODO: convert polynomial coefficients into ZZ_p and call poly_factorial()
// Otherwise, do poly_factorial
ZZ_pX poly;
for(const auto& term : formula[0][0]){
ZZ_p coeff;
coeff.init(m.t);
coeff = term.second;
SetCoeff(poly, term.first, coeff);
}
ZZ_p output;
output.init(m.t);
output = poly_factorial(n, m.t, poly); // TODO: write poly_factorial
Elt<ZZ> output_elt(rep(output));
return output_elt;
}
// Large Linear-type elements
else{
// TODO: convert polynomial coefficients into Mat<ZZ_p> and call matrix_factorial()
Mat<ZZ_pX> matrix;
matrix.SetDims(1, 1);
ZZ_pX poly;
for(const auto& term : formula[0][0]){
ZZ_p coeff;
coeff.init(m.t);
coeff = term.second;
SetCoeff(poly, term.first, coeff);
}
matrix.put(0, 0, poly);
Mat<ZZ_p> output;
output.SetDims(1, 1);
output = matrix_factorial(n, m.t, matrix);
Elt<ZZ> output_elt(rep(output.get(0, 0)));
return output_elt;
}
}
| 30.166667 | 139 | 0.576711 |
2b2777a48d51b5b62324cc2b275bf89676eaf08a | 9,032 | cpp | C++ | tacmap/DelaunayTriangulation.cpp | parrishmyers/tacmap | 21c494723e482b3622362278144613819e21dafc | [
"MIT"
] | null | null | null | tacmap/DelaunayTriangulation.cpp | parrishmyers/tacmap | 21c494723e482b3622362278144613819e21dafc | [
"MIT"
] | null | null | null | tacmap/DelaunayTriangulation.cpp | parrishmyers/tacmap | 21c494723e482b3622362278144613819e21dafc | [
"MIT"
] | null | null | null |
#include <fstream>
#include <boost/format.hpp>
#include "DelaunayTriangulation.h"
#include "DT_Circle.h"
bool isContained(Triangle * t, Vertex * p);
bool inCircle(Triangle *a, Vertex * pr);
bool inCircle(Vertex * a, Vertex * b, Vertex * c, Vertex * d);
Circle circleForPoints(Vertex * a, Vertex * b, Vertex * c);
Vertex pointAlongLine2D(Vertex * a, Vertex * b, double tn = 0.5);
bool onEdge(Vertex * a, Vertex * b, Vertex * pr);
double distance2Point(Vertex * a, Vertex * b, Vertex * pr);
//
// Friend functions of Triangle & Vertex
//
bool isContained(Triangle * t, Vertex * p) {
double x = p->getX();
double y = p->getY();
double x1 = t->data[0]->getX();
double y1 = t->data[0]->getY();
double x2 = t->data[1]->getX();
double y2 = t->data[1]->getY();
double x3 = t->data[2]->getX();
double y3 = t->data[2]->getY();
double denom = 1.0 / (x1*(y2 - y3) + y1*(x3 - x2) + x2*y3 - y2*x3);
double t1 = (x*(y3 - y1) + y*(x1 - x3) - x1*y3 + y1*x3) * denom;
double t2 = (x*(y2 - y1) + y*(x1 - x2) - x1*y2 + y1*x2) * -denom;
if (0.0 <= t1 && t1 <= 1.0 &&
0.0 <= t2 && t2 <= 1.0 &&
t1 + t2 <= 1.0)
return true;
else
return false;
}
bool inCircle(Triangle *a, Vertex * pr)
{
Vertex ** p = a->getVertices();
return inCircle(p[0],p[1],p[2],pr);
}
bool inCircle(Vertex * a, Vertex * b, Vertex * c, Vertex * d)
{
double xa = a->getX();
double xb = b->getX();
double xc = c->getX();
double xd = d->getX();
double ya = a->getY();
double yb = b->getY();
double yc = c->getY();
double yd = d->getY();
double sa = xa * xa + ya * ya;
double sb = xb * xb + yb * yb;
double sc = xc * xc + yc * yc;
double sd = xd * xd + yd * yd;
double det = 0.0;
det = xa * ( yb * (sc - sd) - sb * (yc - yd) + (yc * sd - yd * sc) );
det -= ya * ( xb * (sc - sd) - sb * (xc - xd) + (xc * sd - xd * sc) );
det += sa * ( xb * (yc - yd) - yb * (xc - xd) + (xc * yd - xd * yc) );
det -= ( xb * (yc * sd - yd * sc) - yb * (xc * sd - xd * sc) + sb * (xc * yd - xd * yc) );
if (det > 0.0)
return true;
else
return false;
}
Circle circleForPoints(Vertex * a, Vertex * b, Vertex * c)
{
double x1 = a->getX();
double x2 = b->getX();
double x3 = c->getX();
double y1 = a->getY();
double y2 = b->getY();
double y3 = c->getY();
double X2 = (double)(x2-x1);
double X3 = (double)(x3-x1);
double Y2 = (double)(y2-y1);
double Y3 = (double)(y3-y1);
double alpha = X3 / X2;
double bx2 = (x2+x1) * X2;
double bx3 = (x3+x1) * X3;
double by2 = (y2+y1) * Y2;
double by3 = (y3+y1) * Y3;
double h = 0.0;
double k = 0.0;
double r = 0.0;
k = bx3 + by3 - alpha * (bx2 + by2);
k /= 2 * (Y3 - alpha * Y2);
h = bx2 + by2 - 2 * k * Y2;
h /= 2 * X2;
r = sqrt( (x1 - h)*(x1 - h) + (y1 - k)*(y1 - k) );
return Circle(h,k,r);
}
Vertex pointAlongLine2D(Vertex * a, Vertex * b, double tn)
{
double nx = a->getX() + tn * (b->getX() - a->getX());
double ny = a->getY() + tn * (b->getY() - a->getY());
return Vertex(nx,ny);
}
bool onEdge(Vertex * a, Vertex * b, Vertex * pr) {
double minx = (a->getX() <= b->getX())? a->getX() : b->getX();
double maxx = (a->getX() >= b->getX())? a->getX() : b->getX();
double miny = (a->getY() <= b->getY())? a->getY() : b->getY();
double maxy = (a->getY() >= b->getY())? a->getY() : b->getY();
if (pr->getX() < minx)
return false;
else if (pr->getX() > maxx)
return false;
else if (pr->getY() < miny)
return false;
else if (pr->getY() > maxy)
return false;
else
return distance2Point(a,b,pr) < Constants::DIST_THRESH;
}
double distance2Point(Vertex * a, Vertex * b, Vertex * pr) {
double nx = b->getX() - a->getX();
double ny = b->getY() - a->getY();
double nmag = sqrt(nx * nx + ny * ny);
double px = pr->getX() - a->getX();
double py = pr->getY() - a->getY();
//double pmag = sqrt(px * px + py * py);
double dnp = nx * px + ny * py; // dot(n,p)
double dnpx = nx * dnp / (nmag * nmag);
double dnpy = ny * dnp / (nmag * nmag);
double perx = dnpx - px;
double pery = dnpy - py;
return sqrt(perx * perx + pery * pery);
}
void DelaunayTriangulation::permute()
{
std::srand(pts.len());
for (int i = 0; i < pts.len(); i++) {
rPerm[i] = i;
}
for (int i = pts.len() - 1; i >= 0; i--) {
int j = std::rand() % (i + 1);
int temp = rPerm[i];
rPerm[i] = rPerm[j];
rPerm[j] = temp;
}
}
void DelaunayTriangulation::init()
{
omg1.set( 3.0 * M, 0.0);
omg2.set( 0.0, 3.0 * M);
omg3.set(-3.0 * M, -3.0 * M);
Triangle * itri = dag.get();
itri->setVertices(&omg1, &omg2, &omg3);
}
DelaunayTriangulation::DelaunayTriangulation() : M(0)
{
}
DelaunayTriangulation::~DelaunayTriangulation()
{
}
void DelaunayTriangulation::addPt(double x, double y, double z = 0.0)
{
Vertex * v = pts.get();
if (nullptr != v) {
v->set(x, y, z);
int max = (x >= y) ? x : y;
if (M <= max)
M = max;
}
else {
fprintf(stdout,"WARNING: Pool of points is empty!\n");
}
}
Vertex * DelaunayTriangulation::getPoint(int i)
{
int rPerm_[10] = {2, 9, 7, 8, 4, 1, 3, 0, 6, 5};
return pts[rPerm_[i]];
//return pts[rPerm[i]];
}
///
// ValidEdge(∆, pr,D(P))
// Let ∆adj be the triangle opposite to pr and adjacent to ∆
// if InCircle(∆adj , pr) then
// (* We have to make an edge flip *)
// flip(∆,∆adj, pr,D(P))
// Let ∆′ and ∆′′ be the two new triangles, recursively legalize them
// ValidEdge(∆′, pr,D(P))
// ValidEdge(∆′′, pr,D(P))
// end if
///
void DelaunayTriangulation::validEdge(Triangle *a, Vertex *pr)
{
TriangleList<Constants::adjListSize> copy;
// Let ∆adj be the triangle opposite to pr and adjacent to ∆
dag.findAdjacentTriangle(a, pr, false);
copy.copy(dag.adjList);
if (copy.len > 1) {
Vertex ** points = copy[1]->getVertices();
Circle c = circleForPoints(points[0], points[1], points[2]);
bool answer1 = c.pointInside(pr->getX(), pr->getY());
bool answer2 = inCircle(copy[1], pr);
if (answer1 != answer2) {
fprintf(stdout, "WARNING: inCircle produced wrong answer.\n");
fprintf(stdout, "\t%s\n", c.to_json().dump().c_str());
fprintf(stdout, "\t%s\n", a->to_json().dump().c_str());
fprintf(stdout, "\t%s\n", pr->to_json().dump().c_str());
}
if (answer1) {
Triangle *n[2];
dag.flip(copy[0],copy[1],pr,n);
validEdge(n[0], pr);
validEdge(n[1], pr);
}
}
}
void DelaunayTriangulation::compute()
{
if (pts.len() < 3) {
fprintf(stdout, "WARNING: Not enough points added to Pool\n");
return;
}
init();
permute();
logPoints();
json j;
for (int i = 0; i < pts.len(); i++) {
Vertex * p = getPoint(i);
logStep(i, p);
dag.findTriangleContainingPoint(p);
if (2 == dag.adjList.len) { // on edge
dag.divideOnEdge(dag.adjList[0], dag.adjList[1], p);
} else { // on interior
dag.divideOnInterior(dag.adjList[0], p);
}
TriangleList<Constants::splitListSize> copy;
copy.copy(dag.splitList);
for (int i = 0; i < copy.len; i++) {
assert(true == copy[i]->isValid());
validEdge(copy[i], p);
}
}
//
// removing all triangles with the initial fake points added to DAG.
//
dag.removeTriangleContainingPoint(omg1);
dag.removeTriangleContainingPoint(omg2);
dag.removeTriangleContainingPoint(omg3);
json sol = dag.to_json();
std::ofstream log;
log.open ("solution.json");
log << sol.dump();
log.close();
}
void DelaunayTriangulation::logStep(int loop, Vertex * p)
{
json j;
j["loop"] = loop;
j["point"] = p->to_json();
j["dag"] = dag.len();
std::ofstream log;
log.open (str(boost::format("loop_%05d.json") % dag.len()));
log << j.dump();
log.close();
}
void DelaunayTriangulation::logPoints()
{
std::ofstream log;
log.open ("points.json");
json j;
j.push_back(omg1.to_json());
j.push_back(omg2.to_json());
j.push_back(omg3.to_json());
for (int i = 0; i < pts.len(); i++) {
j.push_back( pts[i]->to_json() );
}
log << j.dump();
log.close();
} | 26.961194 | 100 | 0.494464 |
2b27eac05c8402f32f1dbad10a6b1ff5dc8f5ac5 | 2,363 | cpp | C++ | codeforces/round-278/div-2/candy_boxes.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-07-16T01:46:38.000Z | 2020-07-16T01:46:38.000Z | codeforces/round-278/div-2/candy_boxes.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | null | null | null | codeforces/round-278/div-2/candy_boxes.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-05-27T14:30:43.000Z | 2020-05-27T14:30:43.000Z | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
inline void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
inline void solve_with_four_left_boxes(const vector<unsigned int>& boxes)
{
if ((3 * boxes[0] == boxes[3]) && (boxes[1] + boxes[2] == 4 * boxes[0]))
{
cout << "YES\n";
}
else
{
cout << "NO\n";
}
}
inline void solve_with_three_left_boxes(const vector<unsigned int>& boxes)
{
unsigned int missing_box;
if (3 * boxes[0] == boxes[2])
{
missing_box = 4 * boxes[0] - boxes[1];
}
else if (boxes[1] + boxes[2] == 4 * boxes[0])
{
missing_box = 3 * boxes[0];
}
else if (4 * boxes[2] == 3 * (boxes[0] + boxes[1]))
{
missing_box = boxes[2] / 3;
}
else
{
cout << "NO\n";
return;
}
cout << "YES" << '\n'
<< missing_box << '\n';
}
inline void solve_with_two_left_boxes(const vector<unsigned int>& boxes)
{
if (boxes[1] <= 3 * boxes[0])
{
cout << "YES" << '\n'
<< 4 * boxes[0] - boxes[1] << '\n'
<< 3 * boxes[0] << '\n';
}
else
{
cout << "NO\n";
}
}
inline void solve_with_one_left_box(const vector<unsigned int>& boxes)
{
cout << "YES" << '\n'
<< boxes[0] << '\n'
<< 3 * boxes[0] << '\n'
<< 3 * boxes[0] << '\n';
}
inline void solve_with_zero_left_boxes(const vector<unsigned int>& boxes)
{
cout << "YES" << '\n'
<< 1 << '\n'
<< 1 << '\n'
<< 3 << '\n'
<< 3 << '\n';
}
int main()
{
use_io_optimizations();
unsigned int left_boxes;
cin >> left_boxes;
vector<unsigned int> boxes(4);
for (unsigned int i {0}; i < left_boxes; ++i)
{
cin >> boxes[i];
}
sort(boxes.begin(), boxes.begin() + left_boxes);
switch (left_boxes)
{
case 4:
solve_with_four_left_boxes(boxes);
break;
case 3:
solve_with_three_left_boxes(boxes);
break;
case 2:
solve_with_two_left_boxes(boxes);
break;
case 1:
solve_with_one_left_box(boxes);
break;
case 0:
solve_with_zero_left_boxes(boxes);
break;
}
return 0;
}
| 19.211382 | 76 | 0.493017 |
1a7098538ce52920df14b974fe6a6a1f795fb3b6 | 396 | cpp | C++ | src/ClosestBinarySearchTreeValue.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 43 | 2015-10-10T12:59:52.000Z | 2018-07-11T18:07:00.000Z | src/ClosestBinarySearchTreeValue.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | null | null | null | src/ClosestBinarySearchTreeValue.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 11 | 2015-10-10T14:41:11.000Z | 2018-07-28T06:03:16.000Z | #include "ClosestBinarySearchTreeValue.hpp"
#include <cmath>
using namespace std;
int ClosestBinarySearchTreeValue::closestValue(TreeNode *root, double target) {
int closest = root->val;
while (root) {
if (abs(root->val - target) < abs(closest - target))
closest = root->val;
root = root->val < target ? root->right : root->left;
}
return closest;
} | 26.4 | 79 | 0.643939 |
1a751dfcaf4dbf84cbd4870d1bb0d7be2d22a8ed | 11,084 | cpp | C++ | src/lib/serialport/qserialportinfo_mac.cpp | Hayesie88/emstudio | 0ae4353e5dcaa76b6306ff0aabd5a89999c4dc1b | [
"MIT"
] | 8 | 2015-11-16T19:15:55.000Z | 2021-02-17T23:58:33.000Z | src/lib/serialport/qserialportinfo_mac.cpp | Hayesie88/emstudio | 0ae4353e5dcaa76b6306ff0aabd5a89999c4dc1b | [
"MIT"
] | 5 | 2015-11-12T00:19:59.000Z | 2020-03-23T10:18:19.000Z | src/lib/serialport/qserialportinfo_mac.cpp | Hayesie88/emstudio | 0ae4353e5dcaa76b6306ff0aabd5a89999c4dc1b | [
"MIT"
] | 11 | 2015-03-15T23:02:48.000Z | 2021-09-05T14:17:13.000Z | /****************************************************************************
**
** Copyright (C) 2011-2012 Denis Shienkov <denis.shienkov@gmail.com>
** Copyright (C) 2011 Sergey Belyashov <Sergey.Belyashov@gmail.com>
** Copyright (C) 2012 Laszlo Papp <lpapp@kde.org>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtSerialPort module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qserialportinfo.h"
#include "qserialportinfo_p.h"
#include <sys/param.h>
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/serial/IOSerialKeys.h>
#include <IOKit/storage/IOStorageDeviceCharacteristics.h> // for kIOPropertyProductNameKey
#include <IOKit/usb/USB.h>
#if defined(MAC_OS_X_VERSION_10_4) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_4)
# include <IOKit/serial/ioss.h>
#endif
#include <IOKit/IOBSD.h>
QT_BEGIN_NAMESPACE
enum { MATCHING_PROPERTIES_COUNT = 6 };
QList<QSerialPortInfo> QSerialPortInfo::availablePorts()
{
QList<QSerialPortInfo> serialPortInfoList;
int matchingPropertiesCounter = 0;
::CFMutableDictionaryRef matching = ::IOServiceMatching(kIOSerialBSDServiceValue);
if (!matching)
return serialPortInfoList;
::CFDictionaryAddValue(matching,
CFSTR(kIOSerialBSDTypeKey),
CFSTR(kIOSerialBSDAllTypes));
io_iterator_t iter = 0;
kern_return_t kr = ::IOServiceGetMatchingServices(kIOMasterPortDefault,
matching,
&iter);
if (kr != kIOReturnSuccess)
return serialPortInfoList;
io_registry_entry_t service;
while ((service = ::IOIteratorNext(iter))) {
::CFTypeRef device = 0;
::CFTypeRef portName = 0;
::CFTypeRef description = 0;
::CFTypeRef manufacturer = 0;
::CFTypeRef vendorIdentifier = 0;
::CFTypeRef productIdentifier = 0;
io_registry_entry_t entry = service;
// Find MacOSX-specific properties names.
do {
if (!device) {
device =
::IORegistryEntrySearchCFProperty(entry,
kIOServicePlane,
CFSTR(kIOCalloutDeviceKey),
kCFAllocatorDefault,
0);
if (device)
++matchingPropertiesCounter;
}
if (!portName) {
portName =
::IORegistryEntrySearchCFProperty(entry,
kIOServicePlane,
CFSTR(kIOTTYDeviceKey),
kCFAllocatorDefault,
0);
if (portName)
++matchingPropertiesCounter;
}
if (!description) {
description =
::IORegistryEntrySearchCFProperty(entry,
kIOServicePlane,
CFSTR(kIOPropertyProductNameKey),
kCFAllocatorDefault,
0);
if (!description)
description =
::IORegistryEntrySearchCFProperty(entry,
kIOServicePlane,
CFSTR(kUSBProductString),
kCFAllocatorDefault,
0);
if (!description)
description =
::IORegistryEntrySearchCFProperty(entry,
kIOServicePlane,
CFSTR("BTName"),
kCFAllocatorDefault,
0);
if (description)
++matchingPropertiesCounter;
}
if (!manufacturer) {
manufacturer =
::IORegistryEntrySearchCFProperty(entry,
kIOServicePlane,
CFSTR(kUSBVendorString),
kCFAllocatorDefault,
0);
if (manufacturer)
++matchingPropertiesCounter;
}
if (!vendorIdentifier) {
vendorIdentifier =
::IORegistryEntrySearchCFProperty(entry,
kIOServicePlane,
CFSTR(kUSBVendorID),
kCFAllocatorDefault,
0);
if (vendorIdentifier)
++matchingPropertiesCounter;
}
if (!productIdentifier) {
productIdentifier =
::IORegistryEntrySearchCFProperty(entry,
kIOServicePlane,
CFSTR(kUSBProductID),
kCFAllocatorDefault,
0);
if (productIdentifier)
++matchingPropertiesCounter;
}
// If all matching properties is found, then force break loop.
if (matchingPropertiesCounter == MATCHING_PROPERTIES_COUNT)
break;
kr = ::IORegistryEntryGetParentEntry(entry, kIOServicePlane, &entry);
} while (kr == kIOReturnSuccess);
(void) ::IOObjectRelease(entry);
// Convert from MacOSX-specific properties to Qt4-specific.
if (matchingPropertiesCounter > 0) {
QSerialPortInfo serialPortInfo;
QByteArray buffer(MAXPATHLEN, 0);
if (device) {
if (::CFStringGetCString(CFStringRef(device),
buffer.data(),
buffer.size(),
kCFStringEncodingUTF8)) {
serialPortInfo.d_ptr->device = QString::fromUtf8(buffer);
}
::CFRelease(device);
}
if (portName) {
if (::CFStringGetCString(CFStringRef(portName),
buffer.data(),
buffer.size(),
kCFStringEncodingUTF8)) {
serialPortInfo.d_ptr->portName = QString::fromUtf8(buffer);
}
::CFRelease(portName);
}
if (description) {
if (::CFStringGetCString(CFStringRef(description),
buffer.data(),
buffer.size(),
kCFStringEncodingUTF8)) {
serialPortInfo.d_ptr->description = QString::fromUtf8(buffer);
}
::CFRelease(description);
}
if (manufacturer) {
if (::CFStringGetCString(CFStringRef(manufacturer),
buffer.data(),
buffer.size(),
kCFStringEncodingUTF8)) {
serialPortInfo.d_ptr->manufacturer = QString::fromUtf8(buffer);
}
::CFRelease(manufacturer);
}
quint16 value = 0;
if (vendorIdentifier) {
serialPortInfo.d_ptr->hasVendorIdentifier = ::CFNumberGetValue(CFNumberRef(vendorIdentifier), kCFNumberIntType, &value);
if (serialPortInfo.d_ptr->hasVendorIdentifier)
serialPortInfo.d_ptr->vendorIdentifier = value;
::CFRelease(vendorIdentifier);
}
if (productIdentifier) {
serialPortInfo.d_ptr->hasProductIdentifier = ::CFNumberGetValue(CFNumberRef(productIdentifier), kCFNumberIntType, &value);
if (serialPortInfo.d_ptr->hasProductIdentifier)
serialPortInfo.d_ptr->productIdentifier = value;
::CFRelease(productIdentifier);
}
serialPortInfoList.append(serialPortInfo);
}
(void) ::IOObjectRelease(service);
}
(void) ::IOObjectRelease(iter);
return serialPortInfoList;
}
QT_END_NAMESPACE
| 40.600733 | 138 | 0.480603 |
1a775015d67a723319faa41188ea368f93b840f6 | 764 | cpp | C++ | greedy_problems/maximum_frequency_of_element.cpp | sanathvernekar/Routine_codes | a898ca7e79cf39c289cb2fefaf764c9f8e0eb331 | [
"MIT"
] | null | null | null | greedy_problems/maximum_frequency_of_element.cpp | sanathvernekar/Routine_codes | a898ca7e79cf39c289cb2fefaf764c9f8e0eb331 | [
"MIT"
] | null | null | null | greedy_problems/maximum_frequency_of_element.cpp | sanathvernekar/Routine_codes | a898ca7e79cf39c289cb2fefaf764c9f8e0eb331 | [
"MIT"
] | null | null | null | #include <vector>
#include <map>
#include<bits/stdc++.h>
using namespace std;
long long int max_frequency(vector<long long int> const& v)
{
map<long long int, long long int> frequencyMap;
long long int maxFrequency = 0;
long long int mostFrequentElement = 0;
for (long long int x : v)
{
long long int f = ++frequencyMap[x];
if (f > maxFrequency)
{
maxFrequency = f;
mostFrequentElement = x;
}
}
return maxFrequency;
}
int main()
{
long long int t,n,i,j,temp;
cin>>t;
while(t--){
cin>>n;
vector<long long int >v;
for(i=0;i<n;i++){
cin>>temp;
v.push_back(temp);
}
cout<<max_frequency(v)<<endl;
}
} | 21.222222 | 59 | 0.537958 |
1a7d0a4b1f6fbfbd04070f3df6da1bcfbd53a229 | 1,077 | cpp | C++ | STRINGS/Upper case conversion.cpp | snanacha/Coding-questions | 18c4b5a23fc3da5c419d2ec69fbf13b7b4ecee0d | [
"MIT"
] | null | null | null | STRINGS/Upper case conversion.cpp | snanacha/Coding-questions | 18c4b5a23fc3da5c419d2ec69fbf13b7b4ecee0d | [
"MIT"
] | 1 | 2021-03-30T14:00:56.000Z | 2021-03-30T14:00:56.000Z | STRINGS/Upper case conversion.cpp | snanacha/Coding-questions | 18c4b5a23fc3da5c419d2ec69fbf13b7b4ecee0d | [
"MIT"
] | null | null | null | /*
Upper case conversion
School Accuracy: 72.51% Submissions: 1152 Points: 0
Given a string str, convert the first letter of each word in the string to uppercase.
Example 1:
Input:
str = "i love programming"
Output: "I Love Programming"
Explanation:
'I', 'L', 'P' are the first letters of
the three words.
Your Task:
You dont need to read input or print anything. Complete the function transform() which takes s as input parameter and returns the transformed string.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N) to store resultant string
Constraints:
1 <= N <= 104
The original string str only consists of lowercase alphabets and spaces to separate words.
*/
CODE
----
string transform(string s)
{
// code here
int i;
for(i=0;i<s.size();i++) // to check if first few characters of a string have spaces
{
if(s[i]!=' ')
{ s[i]=toupper(s[i]); break; }
}
for(;i<s.size();i++)
{
if(s[i]==' ')
{ s[i+1]=toupper(s[i+1]); }
}
return s;
} | 22.914894 | 150 | 0.622098 |
1a7d59aa8da04b3bc9b6a7c6c73cdfb020f12695 | 2,133 | cpp | C++ | examples/sample2.cpp | SoultatosStefanos/preconditions | 7c306219153e32afe6a915178f1e1c9fa1bdac8b | [
"MIT"
] | 1 | 2021-09-07T21:10:05.000Z | 2021-09-07T21:10:05.000Z | examples/sample2.cpp | SoultatosStefanos/preconditions | 7c306219153e32afe6a915178f1e1c9fa1bdac8b | [
"MIT"
] | null | null | null | examples/sample2.cpp | SoultatosStefanos/preconditions | 7c306219153e32afe6a915178f1e1c9fa1bdac8b | [
"MIT"
] | null | null | null | /**
* @file sample2.cpp
* @author Soultatos Stefanos (stefanoss1498@gmail.com)
* @brief Contains sample code for the filters
* @version 2.0
* @date 2021-10-29
*
* @copyright Copyright (c) 2021
*
*/
#include "preconditions/filters.hpp"
#include <array>
#include <string>
namespace {
// Instead of:
//
// if (b.empty)
// {
// throw std::invalid_argument();
// }
// return b;
//
//
std::string verify_non_empty_string(const std::string b)
{
const auto not_empty = [&](const std::string x) { return x.empty(); };
return Preconditions::filter_argument<std::string>(b, not_empty);
}
// Instead of:
//
// if (b == 0)
// {
// throw std::domain_error();
// }
//
//
int divide(const int a, const int b)
{
Preconditions::filter_domain<int>(
b, [&](const int x) { return x != 0; }); // inline
Preconditions::filter_domain<int>(
b, [&](const int x) { return x != 0; }, "zero!"); // with msg
return a / b;
}
// Instead of:
//
// if (length < 1)
// {
// throw std::length_error();
// }
//
//
void peek_length(const int length)
{
Preconditions::filter_length<int>(
length, [&](const int) { return length >= 1; }); // inline
Preconditions::filter_length<int>(
length, [&](const int) { return length >= 1; },
"illegal length"); // with msg
}
// Instead of:
//
// if (index >= 3)
// {
// throw std::out_of_range();
// }
//
//
int get_index_of_array(const std::array<int, 3> a, const int index)
{
const auto in_range = [&](const int i) { return i <= 2; };
Preconditions::filter_range<int>(index, in_range); // inline
Preconditions::filter_range<int>(index, in_range, "range!"); // with msg
return a[index];
}
class Entity {
public:
bool valid() const { return true; }
};
// Instead of:
//
// if(!en.valid())
// {
// ??
// }
//
//
void do_wth_entity(const Entity& en)
{
const auto valid = [&](const Entity& e) { return e.valid(); };
Preconditions::filter_state<Entity>(en, valid); // inline
Preconditions::filter_state<Entity>(en, valid,
"invalid state"); // with msg
}
} // namespace | 20.708738 | 76 | 0.586498 |
1a7e496044132273825225cbae15412343883b22 | 1,899 | cpp | C++ | Odyssey/OdysseyVulkanCore/OdysseyVulkanCore/Initialize/SubmitClasses/ImmediateSubmit.cpp | paulburgess1357/Odyssey | ad351d1df7eeb1b4223ffbdf91ec7e3307b87983 | [
"MIT"
] | 1 | 2022-03-10T02:45:04.000Z | 2022-03-10T02:45:04.000Z | Odyssey/OdysseyVulkanCore/OdysseyVulkanCore/Initialize/SubmitClasses/ImmediateSubmit.cpp | paulburgess1357/Odyssey | ad351d1df7eeb1b4223ffbdf91ec7e3307b87983 | [
"MIT"
] | null | null | null | Odyssey/OdysseyVulkanCore/OdysseyVulkanCore/Initialize/SubmitClasses/ImmediateSubmit.cpp | paulburgess1357/Odyssey | ad351d1df7eeb1b4223ffbdf91ec7e3307b87983 | [
"MIT"
] | null | null | null | #include "OdysseyVulkanCore/OdysseyVulkanCore/Initialize/SubmitClasses/ImmediateSubmit.h"
#include "OdysseyVulkanCore/OdysseyVulkanCore/Initialize/SubmitClasses/Exceptions.h"
#include "OdysseyVulkanCore/OdysseyVulkanCore/Initialize/CreateInfo.h"
#include "OdysseyVulkanCore/OdysseyVulkanCore/Utility/Macros.h"
#include <functional>
namespace OdysseyVulkanCore::Initialize {
ImmediateSubmit::ImmediateSubmit(VkDevice vk_device, Handles::CommandPoolHandle m_short_term_cmd_pool,
ScopedCommandBuffer scoped_buffer, Handles::FenceHandle fence)
: m_vk_device{vk_device}, m_short_term_cmd_pool{std::move(m_short_term_cmd_pool)},
m_scoped_cmd_buffer{std::move(scoped_buffer)}, m_fence{std::move(fence)} {
}
void ImmediateSubmit::submit(std::function<void(VkCommandBuffer cmd)>&& function) const {
auto vk_cmd_buffer = m_scoped_cmd_buffer.vk_cmd;
const VkCommandBufferBeginInfo begin_info = CreateInfo::vk_command_buffer_begin_info(
VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT);
VK_ERROR(vkBeginCommandBuffer(vk_cmd_buffer, &begin_info), "Failed to begin command buffer recording!",
Exceptions::CommandBufferRecordingException())
function(vk_cmd_buffer);
VK_ERROR(vkEndCommandBuffer(vk_cmd_buffer), "Failed to end command buffer recording",
Exceptions::CommandBufferRecordingException())
const VkSubmitInfo submit = CreateInfo::vk_submit_info(&vk_cmd_buffer);
VK_ERROR(vkQueueSubmit(m_scoped_cmd_buffer.vk_submission_queue, 1, &submit, m_fence.m_handle),
"Failed to submit command to queue (immediate submit)", Exceptions::CommandBufferSubmissionException())
vkWaitForFences(m_vk_device, 1, &m_fence.m_handle, VK_TRUE, UINT64_MAX);
vkResetFences(m_vk_device, 1, &m_fence.m_handle);
vkResetCommandPool(m_vk_device, m_short_term_cmd_pool.m_handle, 0);
}
} // namespace OdysseyVulkanCore::Initialize
| 52.75 | 114 | 0.796735 |
1a7e908bd3cc80291942a076353938cb2bee4a7b | 7,925 | cpp | C++ | avdev-jni/src/main/cpp/dependencies/windows/mf/src/MFVideoCaptureDevice.cpp | lectureStudio/avdev | 02b980705565ed2dcf3eacc4992bdf2f244f24a0 | [
"Apache-2.0"
] | 1 | 2021-08-10T02:59:58.000Z | 2021-08-10T02:59:58.000Z | avdev-jni/src/main/cpp/dependencies/windows/mf/src/MFVideoCaptureDevice.cpp | lectureStudio/avdev | 02b980705565ed2dcf3eacc4992bdf2f244f24a0 | [
"Apache-2.0"
] | null | null | null | avdev-jni/src/main/cpp/dependencies/windows/mf/src/MFVideoCaptureDevice.cpp | lectureStudio/avdev | 02b980705565ed2dcf3eacc4992bdf2f244f24a0 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2016 Alex Andres
*
* 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 "MFVideoCaptureDevice.h"
#include "MFVideoOutputStream.h"
#include "MFTypeConverter.h"
#include "MFInitializer.h"
#include "WindowsHelper.h"
#include <algorithm>
#include <Mfreadwrite.h>
#include <Mferror.h>
namespace avdev {
MFVideoCaptureDevice::MFVideoCaptureDevice(std::string name, std::string descriptor) :
VideoCaptureDevice(name, descriptor)
{
MFInitializer initializer;
jni::ComPtr<IMFMediaSource> mediaSource;
mmf::CreateMediaSource(MFMediaType_Video, getDescriptor(), &mediaSource);
mediaSource->QueryInterface(IID_IAMVideoProcAmp, (void**)&procAmp);
mediaSource->QueryInterface(IID_IAMCameraControl, (void**)&cameraControl);
}
MFVideoCaptureDevice::~MFVideoCaptureDevice()
{
}
std::list<PictureFormat> MFVideoCaptureDevice::getPictureFormats()
{
// Check, if formats already loaded.
if (!formats.empty()) {
return formats;
}
MFInitializer initializer;
jni::ComPtr<IMFMediaSource> mediaSource;
jni::ComPtr<IMFSourceReader> sourceReader;
jni::ComPtr<IMFMediaType> type;
DWORD typeIndex = 0;
HRESULT hr;
mmf::CreateMediaSource(MFMediaType_Video, getDescriptor(), &mediaSource);
hr = MFCreateSourceReaderFromMediaSource(mediaSource, nullptr, &sourceReader);
THROW_IF_FAILED(hr, "MMF: Create source reader from media source failed.");
while (SUCCEEDED(hr)) {
hr = sourceReader->GetNativeMediaType(0, typeIndex, &type);
if (hr == MF_E_NO_MORE_TYPES) {
break;
}
else if (SUCCEEDED(hr)) {
UINT32 width, height;
GUID guid;
hr = MFGetAttributeSize(type, MF_MT_FRAME_SIZE, &width, &height);
THROW_IF_FAILED(hr, "MMF: Get frame size failed.");
hr = type->GetGUID(MF_MT_SUBTYPE, &guid);
THROW_IF_FAILED(hr, "MMF: Get type guid failed.");
formats.push_back(PictureFormat(width, height, MFTypeConverter::toPixelFormat(guid)));
}
++typeIndex;
}
formats.unique();
return formats;
}
std::list<CameraControl> MFVideoCaptureDevice::getCameraControls()
{
// Check, if controls already loaded.
if (!cameraControls.empty()) {
return cameraControls;
}
if (!cameraControl) {
// The device does not support IAMCameraControl.
return cameraControls;
}
const MFTypeConverter::CameraControlMap controlMap = MFTypeConverter::getCameraControlMap();
HRESULT hr;
for (auto const & kv : controlMap) {
long min, max, delta, def, flags;
hr = cameraControl->GetRange(kv.first, &min, &max, &delta, &def, &flags);
if (FAILED(hr) || min == max) {
continue;
}
bool autoMode = (flags & KSPROPERTY_CAMERACONTROL_FLAGS_AUTO);
cameraControls.push_back(CameraControl(kv.second, min, max, delta, def, autoMode));
}
return cameraControls;
}
std::list<PictureControl> MFVideoCaptureDevice::getPictureControls()
{
// Check, if controls already loaded.
if (!pictureControls.empty()) {
return pictureControls;
}
if (!procAmp) {
// The device does not support IAMVideoProcAmp.
return pictureControls;
}
const MFTypeConverter::PictureControlMap controlMap = MFTypeConverter::getPictureControlMap();
HRESULT hr;
for (auto const & kv : controlMap) {
long min, max, delta, def, flags;
hr = procAmp->GetRange(kv.first, &min, &max, &delta, &def, &flags);
if (FAILED(hr) || min == max) {
continue;
}
bool autoMode = (flags & KSPROPERTY_VIDEOPROCAMP_FLAGS_AUTO);
pictureControls.push_back(PictureControl(kv.second, min, max, delta, def, autoMode));
}
return pictureControls;
}
void MFVideoCaptureDevice::setPictureControlAutoMode(PictureControlType type, bool autoMode)
{
if (!procAmp) {
return;
}
long value = 0;
long flags = 0;
HRESULT hr = procAmp->Get(MFTypeConverter::toApiType(type), &value, &flags);
THROW_IF_FAILED(hr, "MMF: Get picture control value failed.");
flags = autoMode ? KSPROPERTY_VIDEOPROCAMP_FLAGS_AUTO : KSPROPERTY_VIDEOPROCAMP_FLAGS_MANUAL;
hr = procAmp->Set(MFTypeConverter::toApiType(type), value, flags);
THROW_IF_FAILED(hr, "MMF: Set picture control value failed.");
}
bool MFVideoCaptureDevice::getPictureControlAutoMode(PictureControlType type)
{
long value = getPictureControlValue(type);
return value != 0;
}
void MFVideoCaptureDevice::setPictureControlValue(PictureControlType type, long value)
{
if (!procAmp) {
return;
}
long min, max, delta, def, flags;
HRESULT hr = procAmp->GetRange(MFTypeConverter::toApiType(type), &min, &max, &delta, &def, &flags);
if (FAILED(hr)) {
return;
}
// Respect the device range values.
value = (std::max)(value, min);
value = (std::min)(value, max);
hr = procAmp->Set(MFTypeConverter::toApiType(type), value, flags);
THROW_IF_FAILED(hr, "MMF: Set picture control value failed.");
}
long MFVideoCaptureDevice::getPictureControlValue(PictureControlType type)
{
if (!procAmp) {
return 0;
}
long value = 0;
long flags = 0;
HRESULT hr = procAmp->Get(MFTypeConverter::toApiType(type), &value, &flags);
THROW_IF_FAILED(hr, "MMF: Get picture control value failed.");
return value;
}
void MFVideoCaptureDevice::setCameraControlAutoMode(CameraControlType type, bool autoMode)
{
if (!cameraControl) {
return;
}
long value = 0;
long flags = 0;
HRESULT hr = cameraControl->Get(MFTypeConverter::toApiType(type), &value, &flags);
THROW_IF_FAILED(hr, "MMF: Get camera control value failed.");
flags = autoMode ? KSPROPERTY_CAMERACONTROL_FLAGS_AUTO : KSPROPERTY_CAMERACONTROL_FLAGS_MANUAL;
hr = cameraControl->Set(MFTypeConverter::toApiType(type), value, flags);
THROW_IF_FAILED(hr, "MMF: Set camera control value failed.");
}
bool MFVideoCaptureDevice::getCameraControlAutoMode(CameraControlType type)
{
long value = getCameraControlValue(type);
return value != 0;
}
void MFVideoCaptureDevice::setCameraControlValue(CameraControlType type, long value)
{
if (!cameraControl) {
return;
}
long min, max, delta, def, flags;
HRESULT hr = cameraControl->GetRange(MFTypeConverter::toApiType(type), &min, &max, &delta, &def, &flags);
if (FAILED(hr)) {
return;
}
// Respect the device range values.
value = (std::max)(value, min);
value = (std::min)(value, max);
hr = cameraControl->Set(MFTypeConverter::toApiType(type), value, KSPROPERTY_CAMERACONTROL_FLAGS_MANUAL);
THROW_IF_FAILED(hr, "MMF: Set camera control value failed.");
}
long MFVideoCaptureDevice::getCameraControlValue(CameraControlType type)
{
if (!cameraControl) {
return 0;
}
long value = 0;
long flags = 0;
HRESULT hr = cameraControl->Get(MFTypeConverter::toApiType(type), &value, &flags);
THROW_IF_FAILED(hr, "MMF: Get camera control value failed.");
return value;
}
void MFVideoCaptureDevice::setPictureFormat(PictureFormat format)
{
this->format = format;
}
PictureFormat const& MFVideoCaptureDevice::getPictureFormat() const
{
return format;
}
void MFVideoCaptureDevice::setFrameRate(float frameRate)
{
this->frameRate = frameRate;
}
float MFVideoCaptureDevice::getFrameRate() const
{
return frameRate;
}
PVideoOutputStream MFVideoCaptureDevice::createOutputStream(PVideoSink sink)
{
PVideoOutputStream stream = std::make_unique<MFVideoOutputStream>(getDescriptor(), sink);
stream->setFrameRate(getFrameRate());
stream->setPictureFormat(getPictureFormat());
return stream;
}
} | 26.155116 | 107 | 0.720505 |
1a8046f70fc3a8f51fa385ecdcfba6767d5f840f | 313 | cpp | C++ | Codeforces Round 323/Asphalting Roads/main.cpp | sqc1999-oi/Codeforces | 5551e0e4b9dc66bb77c697568f0584aac3dbefae | [
"MIT"
] | 1 | 2016-07-18T12:05:56.000Z | 2016-07-18T12:05:56.000Z | Codeforces Round 323/Asphalting Roads/main.cpp | sqc1999/Codeforces | 5551e0e4b9dc66bb77c697568f0584aac3dbefae | [
"MIT"
] | null | null | null | Codeforces Round 323/Asphalting Roads/main.cpp | sqc1999/Codeforces | 5551e0e4b9dc66bb77c697568f0584aac3dbefae | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
using namespace std;
bool vh[51], vv[51];
int main()
{
ios::sync_with_stdio(false);
int n;
cin >> n;
for (int i = 1; i <= n*n; i++)
{
int h, v;
cin >> h >> v;
if (!vh[h] && !vv[v])
{
vh[h] = vv[v] = true;
cout << i << ' ';
}
}
}
| 14.904762 | 32 | 0.456869 |
1a8b5129949c5c0ff7268512f53daab7dcbdecd0 | 433 | cpp | C++ | binary_search.cpp | ankitelectronicsenemy/CppCodes | e2f274330c12e59a6c401c162e8d899690db0e14 | [
"Apache-2.0"
] | null | null | null | binary_search.cpp | ankitelectronicsenemy/CppCodes | e2f274330c12e59a6c401c162e8d899690db0e14 | [
"Apache-2.0"
] | null | null | null | binary_search.cpp | ankitelectronicsenemy/CppCodes | e2f274330c12e59a6c401c162e8d899690db0e14 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
using namespace std;
int binary_search(int arr[],int n,int key)
{
int s=0;
int e=n-1;
while(s<=e)
{
int mid=(s+e)/2;
if(arr[mid]==key)
{
return mid;
}
if(arr[mid]>key)
{
e=mid-1;
}
else if(arr[mid]<key)
{
s=mid+1;
}
else
return -1 ;
}
return -1;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int key;
cin>>key;
cout<< binary_search(arr,n,key);
} | 8.836735 | 42 | 0.556582 |
1a8c74b4b5e597e0cc6288bffb2bbdcec3b8371b | 2,585 | cpp | C++ | VC2010Samples/ATL/Advanced/mfcatl/objone.cpp | alonmm/VCSamples | 6aff0b4902f5027164d593540fcaa6601a0407c3 | [
"MIT"
] | 300 | 2019-05-09T05:32:33.000Z | 2022-03-31T20:23:24.000Z | VC2010Samples/ATL/Advanced/mfcatl/objone.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 9 | 2016-09-19T18:44:26.000Z | 2018-10-26T10:20:05.000Z | VC2010Samples/ATL/Advanced/mfcatl/objone.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 633 | 2019-05-08T07:34:12.000Z | 2022-03-30T04:38:28.000Z | // ObjOne.cpp : implementation file
//
// This is a part of the Active Template Library.
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Active Template Library Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Active Template Library product.
#include "premfcat.h"
#include "MfcAtl.h"
#include "ObjOne.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CObjectOne
IMPLEMENT_DYNCREATE(CObjectOne, CCmdTarget)
CObjectOne::CObjectOne()
{
EnableAutomation();
// To keep the application running as long as an OLE automation
// object is active, the constructor calls AfxOleLockApp.
AfxOleLockApp();
}
CObjectOne::~CObjectOne()
{
// To terminate the application when all objects created with
// with OLE automation, the destructor calls AfxOleUnlockApp.
AfxOleUnlockApp();
}
void CObjectOne::OnFinalRelease()
{
// When the last reference for an automation object is released
// OnFinalRelease is called. The base class will automatically
// deletes the object. Add additional cleanup required for your
// object before calling the base class.
CCmdTarget::OnFinalRelease();
}
BEGIN_MESSAGE_MAP(CObjectOne, CCmdTarget)
//{{AFX_MSG_MAP(CObjectOne)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BEGIN_DISPATCH_MAP(CObjectOne, CCmdTarget)
//{{AFX_DISPATCH_MAP(CObjectOne)
DISP_FUNCTION(CObjectOne, "SayHello", SayHello, VT_BSTR, VTS_NONE)
//}}AFX_DISPATCH_MAP
END_DISPATCH_MAP()
// Note: we add support for IID_IObjectOne to support typesafe binding
// from VBA. This IID must match the GUID that is attached to the
// dispinterface in the .ODL file.
// {5D0CE84F-D909-11CF-91FC-00A0C903976F}
static const IID IID_IObjectOne =
{ 0x5d0ce84f, 0xd909, 0x11cf, { 0x91, 0xfc, 0x0, 0xa0, 0xc9, 0x3, 0x97, 0x6f } };
BEGIN_INTERFACE_MAP(CObjectOne, CCmdTarget)
INTERFACE_PART(CObjectOne, IID_IObjectOne, Dispatch)
END_INTERFACE_MAP()
// {5D0CE850-D909-11CF-91FC-00A0C903976F}
IMPLEMENT_OLECREATE(CObjectOne, "MfcAtl.ObjectOne", 0x5d0ce850, 0xd909, 0x11cf, 0x91, 0xfc, 0x0, 0xa0, 0xc9, 0x3, 0x97, 0x6f)
/////////////////////////////////////////////////////////////////////////////
// CObjectOne message handlers
BSTR CObjectOne::SayHello()
{
return SysAllocString(OLESTR("Hello from Object One!"));
}
| 28.406593 | 125 | 0.716441 |
1a8e101fc9fd68633703ee9420f4a7abe1788773 | 954 | cpp | C++ | src/Gui/ExportToDotDialog.cpp | loganek/gstcreator | 619f1a6f1ee39c7c5b883c0a676cd490f59ac81b | [
"BSD-3-Clause"
] | 1 | 2015-10-10T23:21:00.000Z | 2015-10-10T23:21:00.000Z | src/Gui/ExportToDotDialog.cpp | loganek/gstcreator | 619f1a6f1ee39c7c5b883c0a676cd490f59ac81b | [
"BSD-3-Clause"
] | null | null | null | src/Gui/ExportToDotDialog.cpp | loganek/gstcreator | 619f1a6f1ee39c7c5b883c0a676cd490f59ac81b | [
"BSD-3-Clause"
] | null | null | null | /*
* gstcreator
* ExportToDotDialog.cpp
*
* Created on: 24 sty 2014
* Author: Marcin Kolny <marcin.kolny@gmail.com>
*/
#include "ExportToDotDialog.h"
#include "ui_ExportToDotDialog.h"
#include <QCheckBox>
#include <QFileDialog>
#include <cstdlib>
ExportToDotDialog::ExportToDotDialog(QWidget *parent)
: QDialog(parent),
ui(new Ui::ExportToDotDialog)
{
ui->setupUi(this);
ui->pathLineEdit->setText(getenv("GST_DEBUG_DUMP_DOT_DIR"));
}
ExportToDotDialog::~ExportToDotDialog()
{
delete ui;
}
int ExportToDotDialog::get_graph_details() const
{
return (ui->statesCheckBox->isChecked() << 0) |
(ui->statesCheckBox->isChecked() << 1) |
(ui->statesCheckBox->isChecked() << 2) |
(ui->statesCheckBox->isChecked() << 3);
}
std::string ExportToDotDialog::get_filename() const
{
return ui->filenameLineEdit->text().toStdString();
}
bool ExportToDotDialog::is_master_model() const
{
return ui->mainBinRadioButton->isChecked();
}
| 20.73913 | 61 | 0.715933 |
1a8e647f78fe3b7f6ef04a0cdfd2407338557fae | 1,191 | cpp | C++ | components/system/sources/platform/android/android_crash_processor.cpp | untgames/funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 7 | 2016-03-30T17:00:39.000Z | 2017-03-27T16:04:04.000Z | components/system/sources/platform/android/android_crash_processor.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2017-11-21T11:25:49.000Z | 2018-09-20T17:59:27.000Z | components/system/sources/platform/android/android_crash_processor.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2016-11-29T15:18:40.000Z | 2017-03-27T16:04:08.000Z | #include "shared.h"
using namespace syslib;
using namespace syslib::android;
namespace
{
typedef void (*sighandler_t)(int);
sighandler_t prev_segv_handler = 0; //предыдущий обработчик сигнала SEGV
// дамп карты памяти
void dump_maps ()
{
static char line [256];
FILE *fp = fopen ("/proc/self/maps", "r");
if (!fp)
return;
while (fgets (line, sizeof (line), fp))
{
size_t len = strlen (line);
len--;
line [len] = 0;
if (!strstr (line, "/system/") && !strstr (line, "/dev/") && !strstr (line, "[stack]") && line [len-1] != ' ')
printf ("segment %s\n", line);
}
fclose (fp);
fflush (stdout);
Application::Sleep (1000);
}
// обработчик сигналогв
void sighandler (int signum)
{
switch (signum)
{
case SIGSEGV:
printf ("Crash detected\n");
dump_maps ();
prev_segv_handler (signum);
break;
default:
break;
}
}
}
namespace syslib
{
namespace android
{
/// регистрация обратчиков аварийного завершения
void register_crash_handlers ()
{
prev_segv_handler = signal(SIGSEGV, sighandler);
}
}
}
| 16.315068 | 115 | 0.56927 |
1a8f43595b382c481b51b8c6c60c53c69bd2f49c | 1,532 | cpp | C++ | blades/xbmc/xbmc/filesystem/SFTPDirectory.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 4 | 2016-04-26T03:43:54.000Z | 2016-11-17T08:09:04.000Z | blades/xbmc/xbmc/filesystem/SFTPDirectory.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 17 | 2015-01-05T21:06:22.000Z | 2015-12-07T20:45:44.000Z | blades/xbmc/xbmc/filesystem/SFTPDirectory.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 3 | 2016-04-26T03:43:55.000Z | 2020-11-06T11:02:08.000Z | /*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "SFTPDirectory.h"
#ifdef HAS_FILESYSTEM_SFTP
#include "SFTPFile.h"
#include "utils/log.h"
#include "URL.h"
using namespace XFILE;
CSFTPDirectory::CSFTPDirectory(void)
{
}
CSFTPDirectory::~CSFTPDirectory(void)
{
}
bool CSFTPDirectory::GetDirectory(const CURL& url, CFileItemList &items)
{
CSFTPSessionPtr session = CSFTPSessionManager::CreateSession(url);
return session->GetDirectory(url.GetWithoutFilename().c_str(), url.GetFileName().c_str(), items);
}
bool CSFTPDirectory::Exists(const CURL& url)
{
CSFTPSessionPtr session = CSFTPSessionManager::CreateSession(url);
if (session)
return session->DirectoryExists(url.GetFileName().c_str());
else
{
CLog::Log(LOGERROR, "SFTPDirectory: Failed to create session to check exists");
return false;
}
}
#endif
| 27.854545 | 99 | 0.727807 |
1a94bd2c1627daf0ff179c9c0c565a1262e87623 | 1,528 | cpp | C++ | winml/lib/Api.Image/DisjointBufferHelpers.cpp | dennyac/onnxruntime | d5175795d2b7f2db18b0390f394a49238f814668 | [
"MIT"
] | 18 | 2020-05-19T12:48:07.000Z | 2021-04-28T06:41:57.000Z | winml/lib/Api.Image/DisjointBufferHelpers.cpp | dennyac/onnxruntime | d5175795d2b7f2db18b0390f394a49238f814668 | [
"MIT"
] | 61 | 2021-05-31T05:15:41.000Z | 2022-03-29T22:34:33.000Z | winml/lib/Api.Image/DisjointBufferHelpers.cpp | dennyac/onnxruntime | d5175795d2b7f2db18b0390f394a49238f814668 | [
"MIT"
] | 9 | 2021-05-14T20:17:26.000Z | 2022-03-20T11:44:29.000Z | #include "pch.h"
#include "inc/DisjointBufferHelpers.h"
namespace _winml {
static void LoadOrStoreDisjointBuffers(
bool should_load_buffer,
size_t num_buffers,
std::function<gsl::span<byte>(size_t)> get_buffer,
gsl::span<byte>& buffer_span) {
auto size_in_bytes = buffer_span.size_bytes();
auto buffer = buffer_span.data();
size_t offset_in_bytes = 0;
for (size_t i = 0; i < num_buffers && size_in_bytes > offset_in_bytes; i++) {
auto span = get_buffer(i);
auto current_size_in_bytes = span.size_bytes();
auto current_buffer = span.data();
if (size_in_bytes - offset_in_bytes < current_size_in_bytes) {
current_size_in_bytes = size_in_bytes - offset_in_bytes;
}
auto offset_buffer = buffer + offset_in_bytes;
if (should_load_buffer) {
memcpy(offset_buffer, current_buffer, current_size_in_bytes);
} else {
memcpy(current_buffer, offset_buffer, current_size_in_bytes);
}
offset_in_bytes += current_size_in_bytes;
}
}
void LoadSpanFromDisjointBuffers(
size_t num_buffers,
std::function<gsl::span<byte>(size_t)> get_buffer,
gsl::span<byte>& buffer_span) {
LoadOrStoreDisjointBuffers(true /*load into the span*/, num_buffers, get_buffer, buffer_span);
}
void StoreSpanIntoDisjointBuffers(
size_t num_buffers,
std::function<gsl::span<byte>(size_t)> get_buffer,
gsl::span<byte>& buffer_span) {
LoadOrStoreDisjointBuffers(false /*store into buffers*/, num_buffers, get_buffer, buffer_span);
}
} // namespace _winml
| 31.183673 | 97 | 0.725131 |
1a98d628ebe2402e2871ca4d09c060ce8f3c353c | 726 | cpp | C++ | homomorphic_evaluation/src/main.cpp | dklee0501/PLDI_20_242_artifact_publication | f2b73df9165c76e8b521d8ebd639d68321e3862b | [
"MIT"
] | 1 | 2022-02-14T02:37:58.000Z | 2022-02-14T02:37:58.000Z | homomorphic_evaluation/src/main.cpp | dklee0501/Lobster | f2b73df9165c76e8b521d8ebd639d68321e3862b | [
"MIT"
] | null | null | null | homomorphic_evaluation/src/main.cpp | dklee0501/Lobster | f2b73df9165c76e8b521d8ebd639d68321e3862b | [
"MIT"
] | null | null | null | #include "FHE.h"
#include <timing.h>
#include <EncryptedArray.h>
#include <NTL/lzz_pXFactoring.h>
#include <vector>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <string>
#include <string.h>
#include <fstream>
#include <vector>
#include "NTL/ZZ_p.h"
#include <NTL/ZZ_pX.h>
#include <NTL/vec_ZZ_p.h>
#include <assert.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
long m=0, p=127, r=1; // Native plaintext space
// Computations will be 'modulo p'
long L; // Levels
long c=2; // Columns in key switching matrix
long w=64; // Hamming weight of secret key
long d=1;
long security;
long s;
long bnd;
ZZX G;
return 0;
}
| 20.742857 | 58 | 0.633609 |
1a9f73f10763b2b4da74948126545e7293c229b3 | 793 | cpp | C++ | main.cpp | anasteyshakoshman/lab12 | 205071d7e28fea46aae604584d9b29f467ee7c57 | [
"MIT"
] | null | null | null | main.cpp | anasteyshakoshman/lab12 | 205071d7e28fea46aae604584d9b29f467ee7c57 | [
"MIT"
] | null | null | null | main.cpp | anasteyshakoshman/lab12 | 205071d7e28fea46aae604584d9b29f467ee7c57 | [
"MIT"
] | null | null | null | #include <iostream>
#include <functional>
#include <future>
#include <thread>
#include <curl/curl.h>
void GetResponse(std::future<char*> &fut)
{
CURL *curl;
CURLcode res;
char *url = fut.get();
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_NOBODY, 1);
}
res = curl_easy_perform(curl);
long http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
std::cout << "Response answer == " << http_code << '\n';
}
int main(int argc, char *argv[])
{
char *url = argv[1];
std::promise<char*> prom;
std::future<char*> fut = prom.get_future();
std::thread th1 (GetResponse, std::ref(fut));
prom.set_value(url);
th1.join();
return 0;
}
| 20.868421 | 64 | 0.624212 |
1aa048d51d3dc8d3221ace15e82671a0cb56b13d | 984 | cpp | C++ | Online Judges/HackerEarth/Grid.cpp | NelsonGomesNeto/ProgramC | e743b1b869f58f7f3022d18bac00c5e0b078562e | [
"MIT"
] | 3 | 2018-12-18T13:39:42.000Z | 2021-06-23T18:05:18.000Z | Online Judges/HackerEarth/Grid.cpp | NelsonGomesNeto/ProgramC | e743b1b869f58f7f3022d18bac00c5e0b078562e | [
"MIT"
] | 1 | 2018-11-02T21:32:40.000Z | 2018-11-02T22:47:12.000Z | Online Judges/HackerEarth/Grid.cpp | NelsonGomesNeto/ProgramC | e743b1b869f58f7f3022d18bac00c5e0b078562e | [
"MIT"
] | 6 | 2018-10-27T14:07:52.000Z | 2019-11-14T13:49:29.000Z | #include <bits/stdc++.h>
using namespace std;
const int maxN = 1e3;
int n, m, q, si = 0, sj = 0;
char grid[maxN][maxN + 1];
int dist[maxN][maxN], dy[4] = {0, 0, 1, -1}, dx[4] = {1, -1, 0, 0};
int valid(int i, int j)
{
return(!(i < 0 || i >= n || j < 0 || j >= m));
}
void bfs()
{
memset(dist, -1, sizeof(dist));
queue<pair<int, int>> q; q.push({si, sj}); dist[si][sj] = 0;
while (!q.empty())
{
int i = q.front().first, j = q.front().second; q.pop();
for (int k = 0; k < 4; k ++)
if (valid(i + dy[k], j + dx[k]) && dist[i + dy[k]][j + dx[k]] == -1 && grid[i + dy[k]][j + dx[k]] == 'O')
q.push({i + dy[k], j + dx[k]}), dist[i + dy[k]][j + dx[k]] = dist[i][j] + 1;
}
}
int main()
{
scanf("%d %d %d", &n, &m, &q);
for (int i = 0; i < n; i ++) scanf("\n%s", grid[i]);
scanf("%d %d", &si, &sj); si --, sj --;
bfs();
while (q --)
{
int di, dj; scanf("%d %d", &di, &dj); di --, dj --;
printf("%d\n", dist[di][dj]);
}
return(0);
} | 24.6 | 111 | 0.442073 |
1aa123e07b2c41de5af220ab5574fa59ba0e2940 | 6,306 | cpp | C++ | src/RcppExports.cpp | shriv/edgebundle | d1c4801cb69133ad02a0112712afa7f13236cf23 | [
"MIT"
] | null | null | null | src/RcppExports.cpp | shriv/edgebundle | d1c4801cb69133ad02a0112712afa7f13236cf23 | [
"MIT"
] | null | null | null | src/RcppExports.cpp | shriv/edgebundle | d1c4801cb69133ad02a0112712afa7f13236cf23 | [
"MIT"
] | null | null | null | // Generated by using Rcpp::compileAttributes() -> do not edit by hand
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#include <Rcpp.h>
using namespace Rcpp;
#ifdef RCPP_USE_GLOBAL_ROSTREAM
Rcpp::Rostream<true>& Rcpp::Rcout = Rcpp::Rcpp_cout_get();
Rcpp::Rostream<false>& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get();
#endif
// force_bundle_iter
List force_bundle_iter(NumericMatrix edges_xy, List elist, double K, int C, int P, int P_rate, double S, int I, double I_rate, double compatibility_threshold, double eps);
RcppExport SEXP _edgebundle_force_bundle_iter(SEXP edges_xySEXP, SEXP elistSEXP, SEXP KSEXP, SEXP CSEXP, SEXP PSEXP, SEXP P_rateSEXP, SEXP SSEXP, SEXP ISEXP, SEXP I_rateSEXP, SEXP compatibility_thresholdSEXP, SEXP epsSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< NumericMatrix >::type edges_xy(edges_xySEXP);
Rcpp::traits::input_parameter< List >::type elist(elistSEXP);
Rcpp::traits::input_parameter< double >::type K(KSEXP);
Rcpp::traits::input_parameter< int >::type C(CSEXP);
Rcpp::traits::input_parameter< int >::type P(PSEXP);
Rcpp::traits::input_parameter< int >::type P_rate(P_rateSEXP);
Rcpp::traits::input_parameter< double >::type S(SSEXP);
Rcpp::traits::input_parameter< int >::type I(ISEXP);
Rcpp::traits::input_parameter< double >::type I_rate(I_rateSEXP);
Rcpp::traits::input_parameter< double >::type compatibility_threshold(compatibility_thresholdSEXP);
Rcpp::traits::input_parameter< double >::type eps(epsSEXP);
rcpp_result_gen = Rcpp::wrap(force_bundle_iter(edges_xy, elist, K, C, P, P_rate, S, I, I_rate, compatibility_threshold, eps));
return rcpp_result_gen;
END_RCPP
}
// criterion_angular_resolution
double criterion_angular_resolution(List adj, NumericMatrix xy);
RcppExport SEXP _edgebundle_criterion_angular_resolution(SEXP adjSEXP, SEXP xySEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List >::type adj(adjSEXP);
Rcpp::traits::input_parameter< NumericMatrix >::type xy(xySEXP);
rcpp_result_gen = Rcpp::wrap(criterion_angular_resolution(adj, xy));
return rcpp_result_gen;
END_RCPP
}
// criterion_edge_length
double criterion_edge_length(IntegerMatrix el, NumericMatrix xy, double lg);
RcppExport SEXP _edgebundle_criterion_edge_length(SEXP elSEXP, SEXP xySEXP, SEXP lgSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< IntegerMatrix >::type el(elSEXP);
Rcpp::traits::input_parameter< NumericMatrix >::type xy(xySEXP);
Rcpp::traits::input_parameter< double >::type lg(lgSEXP);
rcpp_result_gen = Rcpp::wrap(criterion_edge_length(el, xy, lg));
return rcpp_result_gen;
END_RCPP
}
// criterion_balanced_edge_length
double criterion_balanced_edge_length(List adj_deg2, NumericMatrix xy);
RcppExport SEXP _edgebundle_criterion_balanced_edge_length(SEXP adj_deg2SEXP, SEXP xySEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List >::type adj_deg2(adj_deg2SEXP);
Rcpp::traits::input_parameter< NumericMatrix >::type xy(xySEXP);
rcpp_result_gen = Rcpp::wrap(criterion_balanced_edge_length(adj_deg2, xy));
return rcpp_result_gen;
END_RCPP
}
// criterion_line_straightness
double criterion_line_straightness();
RcppExport SEXP _edgebundle_criterion_line_straightness() {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
rcpp_result_gen = Rcpp::wrap(criterion_line_straightness());
return rcpp_result_gen;
END_RCPP
}
// criterion_octilinearity
double criterion_octilinearity(IntegerMatrix el, NumericMatrix xy);
RcppExport SEXP _edgebundle_criterion_octilinearity(SEXP elSEXP, SEXP xySEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< IntegerMatrix >::type el(elSEXP);
Rcpp::traits::input_parameter< NumericMatrix >::type xy(xySEXP);
rcpp_result_gen = Rcpp::wrap(criterion_octilinearity(el, xy));
return rcpp_result_gen;
END_RCPP
}
// layout_as_metro_iter
NumericMatrix layout_as_metro_iter(List adj, IntegerMatrix el, List adj_deg2, NumericMatrix xy, NumericMatrix bbox, double l, double gr, NumericVector w, double bsize);
RcppExport SEXP _edgebundle_layout_as_metro_iter(SEXP adjSEXP, SEXP elSEXP, SEXP adj_deg2SEXP, SEXP xySEXP, SEXP bboxSEXP, SEXP lSEXP, SEXP grSEXP, SEXP wSEXP, SEXP bsizeSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< List >::type adj(adjSEXP);
Rcpp::traits::input_parameter< IntegerMatrix >::type el(elSEXP);
Rcpp::traits::input_parameter< List >::type adj_deg2(adj_deg2SEXP);
Rcpp::traits::input_parameter< NumericMatrix >::type xy(xySEXP);
Rcpp::traits::input_parameter< NumericMatrix >::type bbox(bboxSEXP);
Rcpp::traits::input_parameter< double >::type l(lSEXP);
Rcpp::traits::input_parameter< double >::type gr(grSEXP);
Rcpp::traits::input_parameter< NumericVector >::type w(wSEXP);
Rcpp::traits::input_parameter< double >::type bsize(bsizeSEXP);
rcpp_result_gen = Rcpp::wrap(layout_as_metro_iter(adj, el, adj_deg2, xy, bbox, l, gr, w, bsize));
return rcpp_result_gen;
END_RCPP
}
static const R_CallMethodDef CallEntries[] = {
{"_edgebundle_force_bundle_iter", (DL_FUNC) &_edgebundle_force_bundle_iter, 11},
{"_edgebundle_criterion_angular_resolution", (DL_FUNC) &_edgebundle_criterion_angular_resolution, 2},
{"_edgebundle_criterion_edge_length", (DL_FUNC) &_edgebundle_criterion_edge_length, 3},
{"_edgebundle_criterion_balanced_edge_length", (DL_FUNC) &_edgebundle_criterion_balanced_edge_length, 2},
{"_edgebundle_criterion_line_straightness", (DL_FUNC) &_edgebundle_criterion_line_straightness, 0},
{"_edgebundle_criterion_octilinearity", (DL_FUNC) &_edgebundle_criterion_octilinearity, 2},
{"_edgebundle_layout_as_metro_iter", (DL_FUNC) &_edgebundle_layout_as_metro_iter, 9},
{NULL, NULL, 0}
};
RcppExport void R_init_edgebundle(DllInfo *dll) {
R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}
| 49.265625 | 224 | 0.771646 |
1aa1ca3764f44acc65714469fd96138ceacc60c5 | 1,534 | cpp | C++ | MPAGSCipher/CaesarCipher.cpp | MPAGS-CPP-2019/mpags-day-3-rrStein | e4ff5e2023dbb8e4a7981b25c7d11811ead13c0c | [
"MIT"
] | null | null | null | MPAGSCipher/CaesarCipher.cpp | MPAGS-CPP-2019/mpags-day-3-rrStein | e4ff5e2023dbb8e4a7981b25c7d11811ead13c0c | [
"MIT"
] | null | null | null | MPAGSCipher/CaesarCipher.cpp | MPAGS-CPP-2019/mpags-day-3-rrStein | e4ff5e2023dbb8e4a7981b25c7d11811ead13c0c | [
"MIT"
] | null | null | null | #include "CaesarCipher.hpp"
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
// #include "RunCaesarCipher.hpp"
// #include "RunCaesarCipher.cpp"
CaesarCipher::CaesarCipher(const std::string &caesar_key)
: caesar_key_{std::stoul(caesar_key)} {}
CaesarCipher::CaesarCipher(const size_t &caesar_key)
: caesar_key_{caesar_key} {}
std::string CaesarCipher::applyCipher(const std::string &inputText,
const bool encrypt) const
// : inputText_{inputText}, encrypt_{encrypt}
{
const size_t truncatedKey{caesar_key_ % alphabetSize_};
std::string outputText{""};
// Loop over the input text
char processedChar{'x'};
for (const auto &origChar : inputText) {
// For each character in the input text, find the corresponding position in
// the alphabet by using an indexed loop over the alphabet container
for (size_t i{0}; i < alphabetSize_; ++i) {
if (origChar == alphabet_[i]) {
// Apply the appropriate shift (depending on whether we're encrypting
// or decrypting) and determine the new character
// Can then break out of the loop over the alphabet
if (encrypt) {
processedChar = alphabet_[(i + truncatedKey) % alphabetSize_];
} else {
processedChar =
alphabet_[(i + alphabetSize_ - truncatedKey) % alphabetSize_];
}
break;
}
}
// Add the new character to the output text
outputText += processedChar;
}
return outputText;
} | 30.68 | 79 | 0.656454 |
1aaa3c3ebc0ac201b16987d8482409b46de800bb | 2,512 | hpp | C++ | include/graphplan/Action.hpp | aldukeman/graphplan | 33b575a75aa25243e0a3bc658a7932e75a1ef2ef | [
"MIT"
] | null | null | null | include/graphplan/Action.hpp | aldukeman/graphplan | 33b575a75aa25243e0a3bc658a7932e75a1ef2ef | [
"MIT"
] | 1 | 2016-01-13T20:42:26.000Z | 2022-03-10T02:14:49.000Z | include/graphplan/Action.hpp | aldukeman/graphplan | 33b575a75aa25243e0a3bc658a7932e75a1ef2ef | [
"MIT"
] | 1 | 2019-08-24T10:25:44.000Z | 2019-08-24T10:25:44.000Z | /**
* The MIT License (MIT)
*
* Copyright (c) 2014 Anton Dukeman
*
* 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.
*/
/**
* @file Action.hpp
* @author Anton Dukeman <anton.dukeman@gmail.com>
*
* An Action in Graphplan
*/
#ifndef _GRAPHPLAN_ACTION_H_
#define _GRAPHPLAN_ACTION_H_
#include <string>
#include <set>
#include "graphplan/Proposition.hpp"
namespace graphplan
{
class Action
{
public:
/// Constructor
Action(const std::string& n = "");
/// equality operator
bool operator==(const Action& a) const;
/// less than operator
bool operator<(const Action& a) const;
/// add delete
void add_effect(const Proposition& p);
/// add precondition
void add_precondition(const Proposition& p);
/// get proposition name
const std::string& get_name() const;
/// get adds
const std::set<Proposition>& get_effects() const;
/// get preconditions
const std::set<Proposition>& get_preconditions() const;
/// check if this is a maintenance action
bool is_maintenance_action() const;
/// get string version
std::string to_string() const;
/// set action name
void set_name(const std::string& n);
protected:
/// name of the proposition
std::string name_;
/// added propositions
std::set<Proposition> effects_;
/// required propositions
std::set<Proposition> preconditions_;
}; // class Action
} // namespace graphplan
#endif // _GRAPHPLAN_ACTION_H_
| 27.604396 | 80 | 0.705414 |
1aad3a3ec328941ebf17269947721d86450d3671 | 1,836 | cpp | C++ | test/stc/test-vcs.cpp | antonvw/wxExtension | d5523346cf0b1dbd45fd20dc33bf8d679299676c | [
"MIT"
] | 9 | 2016-01-10T20:59:02.000Z | 2019-01-09T14:18:13.000Z | test/stc/test-vcs.cpp | antonvw/wxExtension | d5523346cf0b1dbd45fd20dc33bf8d679299676c | [
"MIT"
] | 31 | 2015-01-30T17:46:17.000Z | 2017-03-04T17:33:50.000Z | test/stc/test-vcs.cpp | antonvw/wxExtension | d5523346cf0b1dbd45fd20dc33bf8d679299676c | [
"MIT"
] | 2 | 2015-04-05T08:45:22.000Z | 2018-08-24T06:43:24.000Z | ////////////////////////////////////////////////////////////////////////////////
// Name: test-vcs.cpp
// Purpose: Implementation for wex unit testing
// Author: Anton van Wezenbeek
// Copyright: (c) 2021 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wex/core/config.h>
#include <wex/stc/vcs.h>
#include <wex/ui/menu.h>
#include "../test.h"
#include <vector>
TEST_SUITE_BEGIN("wex::vcs");
TEST_CASE("wex::vcs")
{
wex::path file(wex::test::get_path("test.h"));
file.make_absolute();
SUBCASE("statics")
{
REQUIRE(wex::vcs::load_document());
REQUIRE(wex::vcs::dir_exists(file));
REQUIRE(!wex::vcs::empty());
REQUIRE(wex::vcs::size() > 0);
}
SUBCASE("others")
{
// In wex::app the vcs is loaded, so current vcs is known,
// using this constructor results in command id 3, being add.
wex::vcs vcs(std::vector<wex::path>{file}, 3);
REQUIRE(vcs.config_dialog(wex::data::window().button(wxAPPLY | wxCANCEL)));
#ifndef __WXMSW__
REQUIRE(vcs.execute());
REQUIRE(vcs.execute("status"));
REQUIRE(!vcs.execute("xxx"));
REQUIRE(vcs.show_dialog(wex::data::window().button(wxAPPLY | wxCANCEL)));
REQUIRE(vcs.request(wex::data::window().button(wxAPPLY | wxCANCEL)));
REQUIRE(vcs.entry().build_menu(100, new wex::menu("test", 0)) > 0);
REQUIRE(vcs.entry().get_command().get_command() == "add");
REQUIRE(!vcs.get_branch().empty());
REQUIRE(vcs.toplevel().string().find("wex") != std::string::npos);
REQUIRE(vcs.name() == "Auto");
REQUIRE(!vcs.entry().get_command().is_open());
wex::config(_("vcs.Base folder"))
.set(std::list<std::string>{wxGetCwd().ToStdString()});
REQUIRE(vcs.set_entry_from_base());
REQUIRE(vcs.use());
#endif
}
}
TEST_SUITE_END();
| 27 | 80 | 0.582244 |
1ab07d703b2db70916abe6b16f78f7bd63606c4b | 2,219 | cpp | C++ | contract/lite-client/tddb/td/db/utils/FileSyncState.cpp | TONCommunity/ton-sync-payments-channel | 2e5cd4902406923fdba32b8309ab8c40db3ae5bc | [
"MIT"
] | 5 | 2019-10-15T18:26:06.000Z | 2020-05-09T14:09:49.000Z | contract/lite-client/tddb/td/db/utils/FileSyncState.cpp | TONCommunity/ton-sync-payments-channel | 2e5cd4902406923fdba32b8309ab8c40db3ae5bc | [
"MIT"
] | null | null | null | contract/lite-client/tddb/td/db/utils/FileSyncState.cpp | TONCommunity/ton-sync-payments-channel | 2e5cd4902406923fdba32b8309ab8c40db3ae5bc | [
"MIT"
] | 2 | 2020-07-24T16:09:02.000Z | 2021-08-18T17:08:28.000Z | /*
This file is part of TON Blockchain Library.
TON Blockchain 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 2 of the License, or
(at your option) any later version.
TON Blockchain 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 a copy of the GNU Lesser General Public License
along with TON Blockchain Library. If not, see <http://www.gnu.org/licenses/>.
Copyright 2017-2019 Telegram Systems LLP
*/
#include "FileSyncState.h"
namespace td {
std::pair<FileSyncState::Reader, FileSyncState::Writer> FileSyncState::create() {
auto self = std::make_shared<Self>();
return {Reader(self), Writer(self)};
}
FileSyncState::Reader::Reader(std::shared_ptr<Self> self) : self(std::move(self)) {
}
bool FileSyncState::Reader::set_requested_sync_size(size_t size) const {
if (self->requested_synced_size.load(std::memory_order_relaxed) == size) {
return false;
}
self->requested_synced_size.store(size, std::memory_order_release);
return true;
}
size_t FileSyncState::Reader::synced_size() const {
return self->synced_size;
}
size_t FileSyncState::Reader::flushed_size() const {
return self->flushed_size;
}
FileSyncState::Writer::Writer(std::shared_ptr<Self> self) : self(std::move(self)) {
}
size_t FileSyncState::Writer::get_requested_synced_size() {
return self->requested_synced_size.load(std::memory_order_acquire);
}
bool FileSyncState::Writer::set_synced_size(size_t size) {
if (self->synced_size.load(std::memory_order_relaxed) == size) {
return false;
}
self->synced_size.store(size, std::memory_order_release);
return true;
}
bool FileSyncState::Writer::set_flushed_size(size_t size) {
if (self->flushed_size.load(std::memory_order_relaxed) == size) {
return false;
}
self->flushed_size.store(size, std::memory_order_release);
return true;
}
} // namespace td
| 32.632353 | 83 | 0.741325 |
1ab2a2b907d33254514ee46febe49a69ed08a539 | 3,229 | cpp | C++ | Source/Core/BuildCommon/BakeModel.cpp | schuttejoe/ShootyEngine | 56a7fab5a479ec93d7f641bb64b8170f3b0d3095 | [
"MIT"
] | 81 | 2018-07-31T17:13:47.000Z | 2022-03-03T09:24:22.000Z | Source/Core/BuildCommon/BakeModel.cpp | schuttejoe/ShootyEngine | 56a7fab5a479ec93d7f641bb64b8170f3b0d3095 | [
"MIT"
] | 2 | 2018-10-15T04:39:43.000Z | 2019-12-05T03:46:50.000Z | Source/Core/BuildCommon/BakeModel.cpp | schuttejoe/ShootyEngine | 56a7fab5a479ec93d7f641bb64b8170f3b0d3095 | [
"MIT"
] | 9 | 2018-10-11T06:32:12.000Z | 2020-10-01T03:46:37.000Z | //=================================================================================================================================
// Joe Schutte
//=================================================================================================================================
#include "BuildCommon/BakeModel.h"
#include "BuildCore/BuildContext.h"
#include "SceneLib/ModelResource.h"
namespace Selas
{
//=============================================================================================================================
Error BakeModel(BuildProcessorContext* context, cpointer name, const BuiltModel& model)
{
ModelResourceData data;
data.aaBox = model.aaBox;
data.totalVertexCount = (uint32)model.positions.Count();
data.totalCurveVertexCount = (uint32)model.curveVertices.Count();
data.curveModelName = model.curveModelNameHash;
data.pad = 0;
data.indexSize = model.indices.DataSize();
data.faceIndexSize = model.faceIndexCounts.DataSize();
data.positionSize = model.positions.DataSize();
data.normalsSize = model.normals.DataSize();
data.tangentsSize = model.tangents.DataSize();
data.uvsSize = model.uvs.DataSize();
data.curveIndexSize = model.curveIndices.DataSize();
data.curveVertexSize = model.curveVertices.DataSize();
data.cameras.Append(model.cameras);
data.textureResourceNames.Append(model.textures);
data.materials.Append(model.materials);
data.materialHashes.Append(model.materialHashes);
data.meshes.Append(model.meshes);
data.curves.Append(model.curves);
context->CreateOutput(ModelResource::kDataType, ModelResource::kDataVersion, name, data);
ModelGeometryData geometry;
geometry.indexSize = model.indices.DataSize();
geometry.faceIndexSize = model.faceIndexCounts.DataSize();
geometry.positionSize = model.positions.DataSize();
geometry.normalsSize = model.normals.DataSize();
geometry.tangentsSize = model.tangents.DataSize();
geometry.uvsSize = model.uvs.DataSize();
geometry.curveIndexSize = model.curveIndices.DataSize();
geometry.curveVertexSize = model.curveVertices.DataSize();
geometry.indices = (uint32*)model.indices.DataPointer();
geometry.faceIndexCounts = (uint32*)model.faceIndexCounts.DataPointer();
geometry.positions = (float3*)model.positions.DataPointer();
geometry.normals = (float3*)model.normals.DataPointer();
geometry.tangents = (float4*)model.tangents.DataPointer();
geometry.uvs = (float2*)model.uvs.DataPointer();
geometry.curveIndices = (uint32*)model.curveIndices.DataPointer();
geometry.curveVertices = (float4*)model.curveVertices.DataPointer();
context->CreateOutput(ModelResource::kGeometryDataType, ModelResource::kDataVersion, name, geometry);
return Success_;
}
} | 52.934426 | 131 | 0.557138 |
1ab3c6a1df288059f40f05ae58d6ee12e894cd73 | 1,037 | cpp | C++ | tests/fixture/test_assert.cpp | sugawaray/filemanager | 3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1 | [
"MIT"
] | null | null | null | tests/fixture/test_assert.cpp | sugawaray/filemanager | 3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1 | [
"MIT"
] | null | null | null | tests/fixture/test_assert.cpp | sugawaray/filemanager | 3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1 | [
"MIT"
] | null | null | null | #include <sstream>
#include "assert.h"
#include "test_assert.h"
using std::cerr;
using std::endl;
using std::ostringstream;
using test::fixture::Assert;
START_TEST(should_not_output_when_true)
{
ostringstream os;
Assert(true, 1, 2, os);
if (os.str() != "")
cerr << "should_not_output_when_true" << endl;
}
END_TEST
START_TEST(should_output_when_false_with_2_params)
{
ostringstream os;
Assert(false, 1, 2, os);
ostringstream expected;
expected << 1 << ":" << 2 << endl;
if (os.str() != expected.str()) {
cerr << os.str();
cerr << "should_output_when_false_with_2_params" << endl;
}
}
END_TEST
namespace test {
namespace fixture {
TCase* create_assert_tcase()
{
TCase* tcase(tcase_create("assert"));
tcase_add_test(tcase, should_not_output_when_true);
tcase_add_test(tcase, should_output_when_false_with_2_params);
return tcase;
}
Suite* create_assert_fixture_suite()
{
Suite* suite(suite_create("test::fixture::Assert"));
suite_add_tcase(suite, create_assert_tcase());
return suite;
}
} // fixture
} // test
| 19.942308 | 63 | 0.724204 |
1ab59718d64e2d57fadb5d3a4edd505beb48fc2b | 1,071 | cpp | C++ | third_party/txt/tests/UnicodeUtilsTest.cpp | onix39/engine | ec66a45a3a7d5b9dfc2e0feab8965db7a91027cc | [
"BSD-3-Clause"
] | 5,823 | 2015-09-20T02:43:18.000Z | 2022-03-31T23:38:55.000Z | third_party/txt/tests/UnicodeUtilsTest.cpp | shoryukenn/engine | 0dc86cda19d55aba8b719231c11306eeaca4b798 | [
"BSD-3-Clause"
] | 20,081 | 2015-09-19T16:07:59.000Z | 2022-03-31T23:33:26.000Z | third_party/txt/tests/UnicodeUtilsTest.cpp | shoryukenn/engine | 0dc86cda19d55aba8b719231c11306eeaca4b798 | [
"BSD-3-Clause"
] | 5,383 | 2015-09-24T22:49:53.000Z | 2022-03-31T14:33:51.000Z | /*
* Copyright (C) 2016 The Android Open Source Project
*
* 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 "UnicodeUtils.h"
namespace minikin {
TEST(UnicodeUtils, parse) {
const size_t BUF_SIZE = 256;
uint16_t buf[BUF_SIZE];
size_t offset;
size_t size;
ParseUnicode(buf, BUF_SIZE, "U+000D U+1F431 | 'a'", &size, &offset);
EXPECT_EQ(size, 4u);
EXPECT_EQ(offset, 3u);
EXPECT_EQ(buf[0], 0x000D);
EXPECT_EQ(buf[1], 0xD83D);
EXPECT_EQ(buf[2], 0xDC31);
EXPECT_EQ(buf[3], 'a');
}
} // namespace minikin
| 28.184211 | 75 | 0.708683 |
1ab88a18dd8f74b863bbd45e262d092e29d0acfa | 432 | cpp | C++ | WindowsServiceCppTemplate/ServiceControlManager.cpp | AinoMegumi/WindowsServiceCppTemplate | fd123fe43c13356308b3d27a7a5692078979426d | [
"MIT"
] | 1 | 2021-07-06T14:31:15.000Z | 2021-07-06T14:31:15.000Z | WindowsServiceCppTemplate/ServiceControlManager.cpp | AinoMegumi/WindowsServiceCppTemplate | fd123fe43c13356308b3d27a7a5692078979426d | [
"MIT"
] | null | null | null | WindowsServiceCppTemplate/ServiceControlManager.cpp | AinoMegumi/WindowsServiceCppTemplate | fd123fe43c13356308b3d27a7a5692078979426d | [
"MIT"
] | null | null | null | #include "ServiceControlManager.h"
#include "GetErrorMessage.h"
#include <stdexcept>
ServiceControlManager::ServiceControlManager()
: SCM(OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS)) {
if (this->SCM == nullptr) {
throw std::runtime_error(
"Failed In OpenSCManager Function\n"
+ GetErrorMessageA()
);
}
}
ServiceControlManager::operator const SC_HANDLE& () const noexcept { return this->SCM; }
| 25.411765 | 89 | 0.710648 |
1ab92d52afb6aff23e6b6df1dcee0273b674a834 | 4,415 | cpp | C++ | src/args/Arg.cpp | GAStudyGroup/VRP | 54ec7ff3f0a4247d3effe609cf916fc235a08664 | [
"MIT"
] | 8 | 2018-11-28T15:13:26.000Z | 2021-10-08T18:34:28.000Z | sources/Arg.cpp | Arch23/Cpp-Argument-Parser | 03787751e725db8820b02b702e65b31537dc73d2 | [
"MIT"
] | 4 | 2018-03-28T19:26:27.000Z | 2018-04-07T03:02:15.000Z | sources/Arg.cpp | Arch23/Cpp-Argument-Parser | 03787751e725db8820b02b702e65b31537dc73d2 | [
"MIT"
] | 2 | 2019-12-12T09:36:48.000Z | 2020-04-23T08:26:22.000Z | #include "Arg.hpp"
#include <sstream>
using std::istringstream;
#include <set>
using std::set;
#include <algorithm>
using std::any_of;
#include <iostream>
using std::cout;
using std::endl;
Arg::Arg(int argc, char **argv):argc(argc),argv(argv){
programName = "Default Name";
helpSetted = false;
}
void Arg::newArgument(string arg, bool required, string description){
vector<string> argV{split(arg,'|')};
arguments.push_back(Argument(argV, required, description));
}
void Arg::validateArguments(){
//programmer error, name or alias repeated
nameConflict();
processInput();
if(helpSetted && isSet("help")){
throw std::runtime_error(help());
}else{
processRequired();
}
}
void Arg::processRequired(){
bool error{false};
string errorMsg{""};
for(Argument a : arguments){
if(a.getRequired() && a.getOption().empty()){
if(error){
errorMsg += "\n";
}
error = true;
errorMsg += "Required argument: "+a.getArg()[0];
}
}
throwException(errorMsg);
}
void Arg::processInput(){
vector<string> argVector;
bool error{false};
string errorMsg{""};
for(int i=1;i<argc;i++){
string arg = argv[i];
if(arg[0] == '-'){
arg.erase(0,1);
argVector.push_back(arg);
}else{
argVector.back() += " ";
argVector.back() += arg;
}
}
for(string arg : argVector){
vector<string> argSplited = split(arg);
Argument *a = getArgument(argSplited[0]);
if(a==nullptr){
if(error){
errorMsg += "\n";
}
error = true;
errorMsg += "Unexpected argument: "+argSplited[0];
}else{
string option{""};
for(unsigned i=1;i<argSplited.size();i++){
option += argSplited[i];
if((++i)<argSplited.size()){
option += " ";
}
}
a->setOption(option);
a->setArg(true);
}
}
throwException(errorMsg);
}
void Arg::throwException(string errorMsg){
if(!errorMsg.empty()){
if(helpSetted){
errorMsg += "\nUse -help or -h to display program options.";
}
throw std::runtime_error(errorMsg);
}
}
string Arg::help(){
string tmp{};
tmp += programName+"\n\n";
tmp += "Options:\n";
for(Argument a : arguments){
tmp += a.to_string();
tmp += "\n\n";
}
return(tmp);
}
Arg::Argument* Arg::getArgument(string arg){
vector<string> argV = split(arg,'|');
for(string s : argV){
for(Argument &a : arguments){
for(string name : a.getArg()){
if(name == s){
return(&a);
}
}
}
}
return(nullptr);
}
bool Arg::isSet(string arg){
Argument *a = getArgument(arg);
if(a!=nullptr){
return(a->isSet());
}
return false;
}
string Arg::getOption(string arg){
Argument *a = getArgument(arg);
if(a!=nullptr){
return(a->getOption());
}
return {};
}
void Arg::nameConflict(){
set<string> conflicting;
for(unsigned i=0;i<arguments.size();i++){
for(string n : arguments[i].getArg()){
for(unsigned j=0;j<arguments.size();j++){
if(i!=j){
vector<string> tmp{arguments[j].getArg()};
if(find(tmp.begin(),tmp.end(),n)!=tmp.end()){
conflicting.insert(n);
}
}
}
}
}
bool error{false};
string errorMsg{};
for(string n : conflicting){
if(error){
errorMsg+="\n";
}
error = true;
errorMsg += "Conflicting name or alias: "+n;
}
throwException(errorMsg);
}
void Arg::setProgramName(string name){
this->programName = name;
}
void Arg::setHelp(){
helpSetted = true;
newArgument("help|h",false,"Display options available.");
}
vector<string> Arg::split(const string s, char c) {
vector<string> tokens;
string token;
istringstream tokenStream(s);
while (getline(tokenStream, token, c)) {
if (!token.empty()) {
tokens.push_back(token);
}
}
return tokens;
}
| 22.757732 | 72 | 0.512797 |
1aba131b0dfdbc8f2f780904bd7fd8947f4e4925 | 5,240 | cpp | C++ | StatsAPI/statsapi.cpp | freem/SMOnline-v1 | b7202ebf1b2d291952000d8c1673ea6175eb4bdd | [
"MIT"
] | 1 | 2021-05-24T09:23:49.000Z | 2021-05-24T09:23:49.000Z | StatsAPI/statsapi.cpp | freem/SMOnline-v1 | b7202ebf1b2d291952000d8c1673ea6175eb4bdd | [
"MIT"
] | null | null | null | StatsAPI/statsapi.cpp | freem/SMOnline-v1 | b7202ebf1b2d291952000d8c1673ea6175eb4bdd | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include "statsapi.h"
using namespace std;
void main(int argc, char* argv[])
{
statsAPI* api = NULL;
vector<CString> args;
if ((argc < 2) || (argc > 21))
return;
args.resize(argc - 1);
for(unsigned int i = 1; i < argc; i++)
args[i - 1] = argv[i];
api = new statsAPI;
api->ProcessCommandsV(args);
if (api)
{
delete api;
api = NULL;
}
}
statsAPI::statsAPI()
{
m_lktype = NONE;
m_database = NULL;
m_startInfo.Database = "stepmani_newstats"; //Not implemented
m_startInfo.Password = "1000Hilltop";
m_startInfo.Port = 3306;
m_startInfo.ServerName = "stepmaniaonline.com";
m_startInfo.UserName = "stepmani_stats";
}
statsAPI::~statsAPI()
{
//Make the API signal the end of the data when destructing.
cout << "END:END";
if (m_database)
delete m_database;
}
void statsAPI::ProcessCommandsV(vector<CString>& commands)
{
CString flag, value;
unsigned int pos = 0;
for (unsigned int i = 0; i < commands.size(); i++)
{
pos = commands[i].Find("=");
if (pos == CString::npos)
{
PrintError("Command \"" + commands[i] + "\" invalid. Ignoring.");
return;
}
flag = commands[i].substr(0,pos);
value = commands[i].substr(pos+1);
if (flag == "id")
{
m_id = value;
m_lktype = ID;
}
else if (flag == "name")
{
m_name = value;
m_lktype = NAME;
}
else if(flag == "op")
{
if (OpenSQLConnection())
ParseOperation(value);
else
PrintError(CString("SQL connection failed"));
}
else
{
PrintError("Unknown command \"" + commands[i] +"\".");
}
}
}
void statsAPI::PrintError(CString& error)
{
cout << "ERROR:" << error << endl;
}
bool statsAPI::ParseOperation(CString& op)
{
if (op == "lr")
{
switch (m_lktype)
{
case NONE:
break;
case NAME:
m_id = QueryID(m_name);
if (m_id != "Unknown" )
m_lktype = ID;
else
{
PrintError("Unknown name " + m_name);
return false;
}
case ID:
PrintQuery(QueryLastRound(m_id), "lr");
break;
}
return true;
}
else if (op == "total")
{
return true;
}
else
PrintError("Unknown operation \"" + op + "\". Ignoring.");
return false;
}
bool statsAPI::OpenSQLConnection()
{
try {
m_database = new ezMySQLConnection(m_startInfo);
m_database->Connect();
}
catch (const ezSQLException &e) {
PrintError(CString("SQL ERROR THROWN! Dec:" + e.Description));
return false;
}
return m_database->m_bLoggedIn;
}
CString statsAPI::QueryID(const CString& name)
{
m_query.m_InitialQuery = "select user_id from `stepmani_stats`.`phpbb_users` where username=\"" + name + "\" limit 0,1";
m_database->BlockingQuery( m_query );
if (m_result.isError)
throw;
m_result = m_query.m_ResultInfo;
if (m_result.FieldContents.size() <= 0)
return "Unknown";
return m_result.FieldContents[0][0].ToString();
}
void statsAPI::PrintQuery( ezSQLQuery &tQuery, string prefix )
{
//In the event we have an error, show it
if ( tQuery.m_ResultInfo.errorNum != 0 )
{
PrintError(CString(tQuery.m_ResultInfo.errorDesc));
exit ( 0 );
}
if ( tQuery.m_ResultInfo.FieldContents.size() == 0 )
{
PrintError(CString("No data for this user."));
exit (0);
}
//Record seed for finding rank.
//show table header
unsigned i = 0;
for ( i = 0; i < tQuery.m_ResultInfo.Header.size(); i++ )
{
cout << prefix<<tQuery.m_ResultInfo.Header[i].Field<<":";
if ( tQuery.m_ResultInfo.FieldContents.size() > 0 )
if ( tQuery.m_ResultInfo.FieldContents[0].size() > i )
{
cout<< tQuery.m_ResultInfo.FieldContents[0][i].ToString()<<endl;
// if ( tQuery.m_ResultInfo.Header[i].Field == "seed" )
// seed = tQuery.m_ResultInfo.FieldContents[0][i].ToString();
}
}
}
ezSQLQuery statsAPI::QueryLastRound(const CString& ID)
{
m_query.m_InitialQuery = "select * from player_stats where pid=" + ID + " order by round_ID desc limit 0,1";
m_database->BlockingQuery( m_query );
return m_query;
}
/*
* (c) 2003-2004 Joshua Allen, Charles Lohr
* All rights reserved.
*
* 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, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* 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 OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
| 24.036697 | 121 | 0.676718 |
1abc839ce6fb2fcc80893976bb0e5bdc0d297b2a | 165 | hpp | C++ | algorithm/tests/SortTests.hpp | AirChen/AlgorithmCpp | a1af7ee437278682d9d0319bab76d85473c3baa0 | [
"MIT"
] | null | null | null | algorithm/tests/SortTests.hpp | AirChen/AlgorithmCpp | a1af7ee437278682d9d0319bab76d85473c3baa0 | [
"MIT"
] | null | null | null | algorithm/tests/SortTests.hpp | AirChen/AlgorithmCpp | a1af7ee437278682d9d0319bab76d85473c3baa0 | [
"MIT"
] | null | null | null | //
// SortTests.hpp
// tests
//
// Created by tuRen on 2021/5/17.
//
#ifndef SortTests_hpp
#define SortTests_hpp
#include <stdio.h>
#endif /* SortTests_hpp */
| 11.785714 | 34 | 0.660606 |
1abdfc77cd9a9c7b46e8dc87f3257e84faa19fcb | 2,921 | cpp | C++ | qubus/src/isl/flow.cpp | qubusproject/Qubus | 0feb8d6df00459c5af402545dbe7c82ee3ec4b7c | [
"BSL-1.0"
] | null | null | null | qubus/src/isl/flow.cpp | qubusproject/Qubus | 0feb8d6df00459c5af402545dbe7c82ee3ec4b7c | [
"BSL-1.0"
] | null | null | null | qubus/src/isl/flow.cpp | qubusproject/Qubus | 0feb8d6df00459c5af402545dbe7c82ee3ec4b7c | [
"BSL-1.0"
] | null | null | null | #include <qubus/isl/flow.hpp>
namespace qubus
{
namespace isl
{
union_access_info::union_access_info(isl_union_access_info* handle_) : handle_(handle_)
{
}
union_access_info::union_access_info(const union_access_info& other)
: handle_(isl_union_access_info_copy(other.native_handle()))
{
}
union_access_info::~union_access_info()
{
isl_union_access_info_free(handle_);
}
union_access_info& union_access_info::operator=(union_access_info other)
{
isl_union_access_info_free(handle_);
handle_ = other.release();
return *this;
}
void union_access_info::set_must_source(isl::union_map source)
{
handle_ = isl_union_access_info_set_must_source(handle_, source.release());
}
void union_access_info::set_may_source(isl::union_map source)
{
handle_ = isl_union_access_info_set_may_source(handle_, source.release());
}
void union_access_info::set_schedule(isl::schedule sched)
{
handle_ = isl_union_access_info_set_schedule(handle_, sched.release());
}
isl_union_access_info* union_access_info::native_handle() const
{
return handle_;
}
isl_union_access_info* union_access_info::release() noexcept
{
isl_union_access_info* temp = handle_;
handle_ = nullptr;
return temp;
}
union_access_info union_access_info::from_sink(union_map sink)
{
return union_access_info(isl_union_access_info_from_sink(sink.release()));
}
union_flow::union_flow(isl_union_flow* handle_) : handle_(handle_)
{
}
union_flow::~union_flow()
{
isl_union_flow_free(handle_);
}
union_map union_flow::get_must_dependence() const
{
return union_map(isl_union_flow_get_must_dependence(handle_));
}
union_map union_flow::get_may_dependence() const
{
return union_map(isl_union_flow_get_may_dependence(handle_));
}
isl_union_flow* union_flow::native_handle() const
{
return handle_;
}
isl_union_flow* union_flow::release() noexcept
{
isl_union_flow* temp = handle_;
handle_ = nullptr;
return temp;
}
union_flow compute_flow(union_access_info access_info)
{
return union_flow(isl_union_access_info_compute_flow(access_info.release()));
}
int compute_flow(union_map sink, union_map must_source, union_map may_source, union_map schedule,
union_map& must_dep, union_map& may_dep, union_map& must_no_source,
union_map& may_no_source)
{
isl_union_map* must_dep_;
isl_union_map* may_dep_;
isl_union_map* must_no_source_;
isl_union_map* may_no_source_;
int result = isl_union_map_compute_flow(sink.release(), must_source.release(),
may_source.release(), schedule.release(), &must_dep_,
&may_dep_, &must_no_source_, &may_no_source_);
must_dep = union_map(must_dep_);
may_dep = union_map(may_dep_);
must_no_source = union_map(must_no_source_);
may_no_source = union_map(may_no_source_);
return result;
}
}
} | 23.556452 | 97 | 0.741869 |
1ac16c952417ad528f3a24ca9c19effbbebb83a6 | 3,876 | cpp | C++ | GUIproject/CourseWorkHypermarket/productlist.cpp | ashnaider/CourseWorkHypermarket | 9dd52dadf987020c2490f2a9a9cdcaa5b52fb12a | [
"MIT"
] | 3 | 2020-05-27T18:37:43.000Z | 2020-06-21T05:40:57.000Z | GUIproject/CourseWorkHypermarket/productlist.cpp | ashnaider/CourseWorkHypermarket | 9dd52dadf987020c2490f2a9a9cdcaa5b52fb12a | [
"MIT"
] | null | null | null | GUIproject/CourseWorkHypermarket/productlist.cpp | ashnaider/CourseWorkHypermarket | 9dd52dadf987020c2490f2a9a9cdcaa5b52fb12a | [
"MIT"
] | null | null | null | #include "productlist.h"
#include "product.h"
#include <sstream>
#include <string>
#include <vector>
ProductList::ProductList(QString productClass)
{
utilities = new Utilities;
QString filePath = utilities->generateFilePathForProduct(productClass);
productsInfo = utilities->readFileByWord(filePath, true);
productInfoHeader = productsInfo[0];
productsInfo.erase(productsInfo.begin());
allocateProducts(productClass);
}
void ProductList::allocateProducts(QString productClass) {
currectProductClass = productClass.toStdString();
for (const auto& line : productsInfo) {
std::string firm = line[0];
std::string name = line[1];
double price = std::stod(line[2]);
double maxDiscount = std::stod(line[3]);
if (productClass == "MobilePhones") {
bool isContract = (line[4] == "1") ? true : false;
int maxSimCards = std::stoi(line[5]);
fieldsQuantity = 6;
MobilePhone *mobilePhone;
mobilePhone = new MobilePhone(firm, name, price, maxDiscount,
isContract, maxSimCards);
ptrVecProductList.push_back(mobilePhone);
} else if (productClass == "Smartphones") {
bool isContract = (line[4] == "1") ? true : false;
int maxSimCards = std::stoi(line[5]);
std::string OS = line[6];
std::string preinstalledProgramms = line[7];
fieldsQuantity = 8;
std::stringstream sspp(preinstalledProgramms);
std::vector<std::string> pp;
std::string temp;
while (sspp >> temp) {
pp.push_back(temp);
}
Smartphone *smartphone;
smartphone = new Smartphone(firm, name, price, maxDiscount,
isContract, maxSimCards,
OS, pp);
ptrVecProductList.push_back(smartphone);
} else if (productClass == "Laptops") {
double diagonalSize = std::stod(line[4]);
double weight = std::stod(line[5]);
int cpuCores = std::stoi(line[6]);
int mainMemory = std::stoi(line[7]);
fieldsQuantity = 8;
Laptop *laptop;
laptop = new Laptop(firm, name, price, maxDiscount,
diagonalSize, weight, cpuCores, mainMemory);
ptrVecProductList.push_back(laptop);
}
}
}
const Product* ProductList::getProductByIndex(int index) {
if (index >= 0 && index < ptrVecProductList.size()) {
return ptrVecProductList[index];
} else {
return { };
}
}
int ProductList::GetFieldsQuantity() const {
return fieldsQuantity;
}
QString ProductList::GetQStringProductInfo(const Product *product) const {
QString result = QString::fromStdString(product->GetFirm()) +
"\t" +
QString::fromStdString(product->GetName()) +
"\t" +
QString::number(product->GetPrice()) +
"\t";
return result;
}
std::vector<std::string> ProductList::GetProductInfoInVec(int pNum) const {
return productsInfo[pNum];
}
QList<QString> ProductList::GetProductInfoHeader() const {
QList<QString> result;
for (const auto& word : productInfoHeader) {
result.push_back(QString::fromStdString(word));
}
return result;
}
ProductList::~ProductList() {
delete utilities;
for (auto& product : ptrVecProductList) {
delete product;
}
productsInfo.clear();
}
| 32.033058 | 81 | 0.54257 |
1ac39ca5b2ddb057e71738c30bbe6b4536a54da3 | 378 | hpp | C++ | simsync/include/simsync/synchronization/thread_start.hpp | mariobadr/simsync-pmam | c541d2bf3a52eec8579e254a0300442bc3d6f1d4 | [
"Apache-2.0"
] | null | null | null | simsync/include/simsync/synchronization/thread_start.hpp | mariobadr/simsync-pmam | c541d2bf3a52eec8579e254a0300442bc3d6f1d4 | [
"Apache-2.0"
] | null | null | null | simsync/include/simsync/synchronization/thread_start.hpp | mariobadr/simsync-pmam | c541d2bf3a52eec8579e254a0300442bc3d6f1d4 | [
"Apache-2.0"
] | null | null | null | #ifndef SIMSYNC_THREAD_START_HPP
#define SIMSYNC_THREAD_START_HPP
#include <simsync/synchronization/event.hpp>
namespace simsync {
class thread_start : public event {
public:
explicit thread_start(int32_t thread_id, thread_model &tm);
transition synchronize() override;
private:
void print(std::ostream &stream) const override;
};
}
#endif //SIMSYNC_THREAD_START_HPP
| 19.894737 | 61 | 0.793651 |
1ac5f29f8be19da29a2f75af508c1f322ef4907d | 296 | cpp | C++ | src/misc/memswap.cpp | Damdoshi/LibLapin | 800e0f17ed8f3c47797c48feea4c280bb0e4bdc9 | [
"BSD-3-Clause"
] | 38 | 2016-07-30T09:35:19.000Z | 2022-03-04T10:13:48.000Z | src/misc/memswap.cpp | Elania-Marvers/LibLapin | 800e0f17ed8f3c47797c48feea4c280bb0e4bdc9 | [
"BSD-3-Clause"
] | 15 | 2017-02-12T19:20:52.000Z | 2021-06-09T09:30:52.000Z | src/misc/memswap.cpp | Elania-Marvers/LibLapin | 800e0f17ed8f3c47797c48feea4c280bb0e4bdc9 | [
"BSD-3-Clause"
] | 12 | 2016-10-06T09:06:59.000Z | 2022-03-04T10:14:00.000Z | // Jason Brillante "Damdoshi"
// Hanged Bunny Studio 2014-2018
//
// Lapin library
#include "lapin_private.h"
void bunny_memswap(void *a,
void *b,
size_t s)
{
void *c = bunny_alloca(s);
memcpy(c, a, s);
memcpy(a, b, s);
memcpy(b, c, s);
bunny_freea(c);
}
| 15.578947 | 32 | 0.577703 |
1ac66153d28c9feb374678c860bffb6aca1c7739 | 4,534 | inl | C++ | include/ecst/context/system/instance/data_proxy/impl/base.inl | SuperV1234/ecst | b3c42e2c28978f1cd8ea620ade62613c6c875432 | [
"AFL-3.0"
] | 475 | 2016-05-03T13:34:30.000Z | 2021-11-26T07:02:47.000Z | include/ecst/context/system/instance/data_proxy/impl/base.inl | vittorioromeo/ecst | b3c42e2c28978f1cd8ea620ade62613c6c875432 | [
"AFL-3.0"
] | 28 | 2016-08-30T06:37:40.000Z | 2017-11-24T11:14:07.000Z | include/ecst/context/system/instance/data_proxy/impl/base.inl | vittorioromeo/ecst | b3c42e2c28978f1cd8ea620ade62613c6c875432 | [
"AFL-3.0"
] | 60 | 2016-05-11T22:16:15.000Z | 2021-08-02T20:42:35.000Z | // Copyright (c) 2015-2016 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: http://opensource.org/licenses/AFL-3.0
// http://vittorioromeo.info | vittorio.romeo@outlook.com
#pragma once
#include "./base.hpp"
#define ECST_IMPL_DP_BASE_TEMPLATE \
template <typename TSystemSignature, typename TContext, \
typename TInstance, typename TDerived>
#define ECST_IMPL_DP_BASE base<TSystemSignature, TContext, TInstance, TDerived>
ECST_CONTEXT_SYSTEM_NAMESPACE
{
namespace data_proxy
{
ECST_IMPL_DP_BASE_TEMPLATE
auto& ECST_IMPL_DP_BASE::state_wrapper() noexcept
{
// CRTP is used to efficiently get the state index.
return vrmc::to_derived<TDerived>(*this).state_wrapper();
}
ECST_IMPL_DP_BASE_TEMPLATE
auto& ECST_IMPL_DP_BASE::state() noexcept
{
return state_wrapper().as_state();
}
ECST_IMPL_DP_BASE_TEMPLATE
auto& ECST_IMPL_DP_BASE::output_data() noexcept
{
return state_wrapper().as_data();
}
ECST_IMPL_DP_BASE_TEMPLATE
template <typename TSystemTag>
constexpr auto ECST_IMPL_DP_BASE::can_get_output_of(
TSystemTag st) noexcept
{
constexpr auto ssl =
settings::system_signature_list(settings_type{});
constexpr auto my_ss = TSystemSignature{};
constexpr auto target_ss =
signature_list::system::signature_by_tag(ssl, st);
return signature_list::system::has_dependency_recursive(
ssl, my_ss, target_ss);
}
ECST_IMPL_DP_BASE_TEMPLATE
ECST_IMPL_DP_BASE::base( // .
instance_type& instance, // .
context_type& context // .
) noexcept : _instance{instance}, // .
_context{context} // .
{
}
ECST_IMPL_DP_BASE_TEMPLATE
template <typename TComponentTag>
decltype(auto) ECST_IMPL_DP_BASE::get(
TComponentTag ct, entity_id eid) noexcept
{
constexpr auto can_write =
signature::system::can_write<TSystemSignature>(ct);
constexpr auto can_read =
signature::system::can_read<TSystemSignature>(ct);
return static_if(can_write)
.then([ ct, eid ](auto& x_ctx) -> auto&
{
return x_ctx.get_component(ct, eid);
})
.else_if(can_read)
.then([ ct, eid ](auto& x_ctx) -> const auto&
{
return x_ctx.get_component(ct, eid);
})
.else_([](auto&)
{
// TODO: nicer error message
struct cant_access_that_component;
return cant_access_that_component{};
})(_context);
}
ECST_IMPL_DP_BASE_TEMPLATE
template <typename TComponentTag>
auto ECST_IMPL_DP_BASE::has(
TComponentTag ct, entity_id eid) const noexcept
{
return _context.has_component(ct, eid);
}
ECST_IMPL_DP_BASE_TEMPLATE
template <typename TF>
void ECST_IMPL_DP_BASE::defer(TF&& f)
{
state()._deferred_fns.add(FWD(f));
}
ECST_IMPL_DP_BASE_TEMPLATE
void ECST_IMPL_DP_BASE::kill_entity(entity_id eid)
{
state()._to_kill.add(eid);
}
ECST_IMPL_DP_BASE_TEMPLATE
auto& ECST_IMPL_DP_BASE::output() noexcept
{
ECST_S_ASSERT(
signature::system::has_data_output<system_signature_type>());
return output_data();
}
ECST_IMPL_DP_BASE_TEMPLATE
template <typename TSystemTag>
auto& ECST_IMPL_DP_BASE::system(TSystemTag st) noexcept
{
return _context.system(st);
}
ECST_IMPL_DP_BASE_TEMPLATE
template <typename TSystemTag, typename TF>
decltype(auto) ECST_IMPL_DP_BASE::for_previous_outputs(
TSystemTag st, TF&& f) noexcept
{
ECST_S_ASSERT_DT(can_get_output_of(st));
return _context.for_system_outputs(st, FWD(f));
}
}
}
ECST_CONTEXT_SYSTEM_NAMESPACE_END
#undef ECST_IMPL_DP_BASE
#undef ECST_IMPL_DP_BASE_TEMPLATE
| 31.268966 | 79 | 0.571901 |
1ac7e8aeb3dc27b7aa08ef5d61db26db632550de | 4,784 | cc | C++ | media/audio/audio_output_dispatcher.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | 1 | 2016-03-10T09:13:57.000Z | 2016-03-10T09:13:57.000Z | media/audio/audio_output_dispatcher.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | 1 | 2022-03-13T08:39:05.000Z | 2022-03-13T08:39:05.000Z | media/audio/audio_output_dispatcher.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 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 "media/audio/audio_output_dispatcher.h"
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/message_loop.h"
#include "base/time.h"
#include "media/audio/audio_io.h"
AudioOutputDispatcher::AudioOutputDispatcher(
AudioManager* audio_manager, const AudioParameters& params,
base::TimeDelta close_delay)
: audio_manager_(audio_manager),
message_loop_(MessageLoop::current()),
params_(params),
pause_delay_(base::TimeDelta::FromMilliseconds(
2 * params.frames_per_buffer() *
base::Time::kMillisecondsPerSecond / params.sample_rate())),
paused_proxies_(0),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_this_(this)),
close_timer_(FROM_HERE,
close_delay,
weak_this_.GetWeakPtr(),
&AudioOutputDispatcher::ClosePendingStreams) {
// We expect to be instantiated on the audio thread. Otherwise the
// message_loop_ member will point to the wrong message loop!
DCHECK(audio_manager->GetMessageLoop()->BelongsToCurrentThread());
}
AudioOutputDispatcher::~AudioOutputDispatcher() {
DCHECK_EQ(MessageLoop::current(), message_loop_);
}
bool AudioOutputDispatcher::StreamOpened() {
DCHECK_EQ(MessageLoop::current(), message_loop_);
paused_proxies_++;
// Ensure that there is at least one open stream.
if (idle_streams_.empty() && !CreateAndOpenStream()) {
return false;
}
close_timer_.Reset();
return true;
}
AudioOutputStream* AudioOutputDispatcher::StreamStarted() {
DCHECK_EQ(MessageLoop::current(), message_loop_);
if (idle_streams_.empty() && !CreateAndOpenStream()) {
return NULL;
}
AudioOutputStream* stream = idle_streams_.back();
idle_streams_.pop_back();
DCHECK_GT(paused_proxies_, 0u);
paused_proxies_--;
close_timer_.Reset();
// Schedule task to allocate streams for other proxies if we need to.
message_loop_->PostTask(FROM_HERE, base::Bind(
&AudioOutputDispatcher::OpenTask, weak_this_.GetWeakPtr()));
return stream;
}
void AudioOutputDispatcher::StreamStopped(AudioOutputStream* stream) {
DCHECK_EQ(MessageLoop::current(), message_loop_);
paused_proxies_++;
pausing_streams_.push_front(stream);
// Don't recycle stream until two buffers worth of time has elapsed.
message_loop_->PostDelayedTask(
FROM_HERE,
base::Bind(&AudioOutputDispatcher::StopStreamTask,
weak_this_.GetWeakPtr()),
pause_delay_);
}
void AudioOutputDispatcher::StopStreamTask() {
DCHECK_EQ(MessageLoop::current(), message_loop_);
if (pausing_streams_.empty())
return;
AudioOutputStream* stream = pausing_streams_.back();
pausing_streams_.pop_back();
idle_streams_.push_back(stream);
close_timer_.Reset();
}
void AudioOutputDispatcher::StreamClosed() {
DCHECK_EQ(MessageLoop::current(), message_loop_);
while (!pausing_streams_.empty()) {
idle_streams_.push_back(pausing_streams_.back());
pausing_streams_.pop_back();
}
DCHECK_GT(paused_proxies_, 0u);
paused_proxies_--;
while (idle_streams_.size() > paused_proxies_) {
idle_streams_.back()->Close();
idle_streams_.pop_back();
}
}
void AudioOutputDispatcher::Shutdown() {
DCHECK_EQ(MessageLoop::current(), message_loop_);
// Cancel any pending tasks to close paused streams or create new ones.
weak_this_.InvalidateWeakPtrs();
// No AudioOutputProxy objects should hold a reference to us when we get
// to this stage.
DCHECK(HasOneRef()) << "Only the AudioManager should hold a reference";
AudioOutputStreamList::iterator it = idle_streams_.begin();
for (; it != idle_streams_.end(); ++it)
(*it)->Close();
idle_streams_.clear();
it = pausing_streams_.begin();
for (; it != pausing_streams_.end(); ++it)
(*it)->Close();
pausing_streams_.clear();
}
bool AudioOutputDispatcher::CreateAndOpenStream() {
AudioOutputStream* stream = audio_manager_->MakeAudioOutputStream(params_);
if (!stream)
return false;
if (!stream->Open()) {
stream->Close();
return false;
}
idle_streams_.push_back(stream);
return true;
}
void AudioOutputDispatcher::OpenTask() {
// Make sure that we have at least one stream allocated if there
// are paused streams.
if (paused_proxies_ > 0 && idle_streams_.empty() &&
pausing_streams_.empty()) {
CreateAndOpenStream();
}
close_timer_.Reset();
}
// This method is called by |close_timer_|.
void AudioOutputDispatcher::ClosePendingStreams() {
DCHECK_EQ(MessageLoop::current(), message_loop_);
while (!idle_streams_.empty()) {
idle_streams_.back()->Close();
idle_streams_.pop_back();
}
}
| 27.976608 | 77 | 0.718436 |
1ac851422692a5f3ef1293a6065f0499859d4ede | 3,589 | cpp | C++ | src/app.cpp | VIGameStudio/Particles | 160beb20b3f23cf0973fd57043d901b3f01efa42 | [
"MIT"
] | null | null | null | src/app.cpp | VIGameStudio/Particles | 160beb20b3f23cf0973fd57043d901b3f01efa42 | [
"MIT"
] | null | null | null | src/app.cpp | VIGameStudio/Particles | 160beb20b3f23cf0973fd57043d901b3f01efa42 | [
"MIT"
] | null | null | null | #include "app.hpp"
/// App
#include "imgui.h"
#include "imgui-SFML.h"
#include "alloc.hpp"
#include "particlefx.hpp"
#include "particle_editor.hpp"
#include "vec2.hpp"
#define MAX_PARTICLES 32
#define P_RADIUS 10
#define P_SQRADIUS P_RADIUS*P_RADIUS
LinearAllocator* allocator;
std::vector<ParticleEmitter*> particles;
size_t active = 0;
ParticleEditor editor;
sf::CircleShape circle;
bool dragging = false;
bool App::init(const std::string& respath)
{
const size_t allocSize = sizeof(ParticleEmitter) * MAX_PARTICLES;
allocator = new LinearAllocator(allocSize, malloc(allocSize));
particles.emplace_back(mem::New<ParticleEmitter>(*allocator));
particles.emplace_back(mem::New<ParticleEmitter>(*allocator));
particles.emplace_back(mem::New<ParticleEmitter>(*allocator));
particles.emplace_back(mem::New<ParticleEmitter>(*allocator));
particles.emplace_back(mem::New<ParticleEmitter>(*allocator));
particles.emplace_back(mem::New<ParticleEmitter>(*allocator));
particles.emplace_back(mem::New<ParticleEmitter>(*allocator));
particles.emplace_back(mem::New<ParticleEmitter>(*allocator));
particles.emplace_back(mem::New<ParticleEmitter>(*allocator));
editor.setup(respath, "/textures/particle.png");
circle.setRadius(P_RADIUS);
circle.setOutlineThickness(1.f);
circle.setOutlineColor(sf::Color::Green);
circle.setFillColor(sf::Color::Transparent);
reset();
return true;
}
void App::reset()
{
for(auto p : particles)
p->resetAll();
}
void App::input(const sf::Event& event)
{
if(event.type == sf::Event::Resized) {
views[0].setSize(event.size.width, event.size.height);
}
else
if(event.type == sf::Event::KeyPressed) {
if(event.key.code == sf::Keyboard::R)
reset();
}
else
if(event.type == sf::Event::MouseButtonPressed) {
const sf::Vector2f mpos = getWindow().mapPixelToCoords(sf::Mouse::getPosition(getWindow()));
for(size_t i=0; i<particles.size(); ++i) {
float sqDist = vec2::magnitudeSq(particles[i]->emitter - mpos);
if(sqDist < P_SQRADIUS) {
active = i;
dragging = true;
}
}
}
else
if(event.type == sf::Event::MouseButtonReleased)
dragging = false;
}
void App::fixed(float t, float dt)
{}
void App::update(const sf::Time& elapsed)
{
ParticleEmitter* current = particles[active];
if(dragging) {
const sf::Vector2f mpos = getWindow().mapPixelToCoords(sf::Mouse::getPosition(getWindow()));
vec2::lerp(current->emitter, current->emitter, mpos, 0.2f);
}
for(auto p : particles)
p->update(elapsed);
if (ImGui::BeginMainMenuBar())
{
if (ImGui::BeginMenu("File"))
{
if(ImGui::MenuItem("Open")) editor.open(*current);
if(ImGui::MenuItem("Save")) editor.save(*current);
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
editor.update(*current, elapsed);
}
void App::pre_draw()
{
}
void App::draw(const sf::View& view)
{
getWindow().setView(view);
for(auto p : particles) {
getWindow().draw(*p);
circle.setPosition(p->emitter-sf::Vector2f(P_RADIUS, P_RADIUS));
getWindow().draw(circle);
}
}
void App::post_draw()
{}
void App::clean()
{
}
/// Main
#include "core/engine.hpp"
int main(int argc, char ** args)
{
if (argc < 2) {
std::cout << "Please specify a res path!\n";
return EXIT_FAILURE;
}
return Engine::start<App>(args[1]);
}
| 24.414966 | 100 | 0.637503 |
1ac8b3251f1aa9e69553c678c880a19926989df8 | 1,503 | hpp | C++ | include/Lodtalk/Math.hpp | ronsaldo/lodtalk | 4668e8923f508c8a9e87a00242ab67b26fb0c9a4 | [
"MIT"
] | 3 | 2017-02-10T18:18:58.000Z | 2019-02-21T02:35:29.000Z | include/Lodtalk/Math.hpp | ronsaldo/lodtalk | 4668e8923f508c8a9e87a00242ab67b26fb0c9a4 | [
"MIT"
] | null | null | null | include/Lodtalk/Math.hpp | ronsaldo/lodtalk | 4668e8923f508c8a9e87a00242ab67b26fb0c9a4 | [
"MIT"
] | null | null | null | #ifndef LODTALK_MATH_HPP
#define LODTALK_MATH_HPP
#include "Lodtalk/ObjectModel.hpp"
namespace Lodtalk
{
inline SmallIntegerValue divideRoundNeg(SmallIntegerValue dividend, SmallIntegerValue divisor)
{
// This algorithm was taken from the Squeak VM.
assert(divisor != 0);
if (dividend >= 0)
{
if (divisor > 0)
{
// Positive result.
return dividend / divisor;
}
else
{
// Negative result. Round towards minus infinite.
auto positiveDivisor = -divisor;
return -(dividend + positiveDivisor - 1) / divisor;
}
}
else
{
auto positiveDividend = -dividend;
if (divisor > 0)
{
// Negative result. Round towards minus infinite.
return -(positiveDividend + divisor - 1) / divisor;
}
else
{
// Positive result.
return dividend / divisor;
}
}
}
inline SmallIntegerValue moduleRoundNeg(SmallIntegerValue dividend, SmallIntegerValue divisor)
{
// This algorithm was taken from the Squeak VM.
assert(divisor != 0);
auto result = dividend % divisor;
// Make sure the result has the same sign as the divisor.
if (divisor < 0)
{
if (result > 0)
result += divisor;
}
else
{
if (result < 0)
result += divisor;
}
return result;
}
} // End of namespace Lodtalk
#endif //LODTALK_MATH_HPP
| 22.102941 | 94 | 0.571524 |
1ad0e382a2b2a74cf034d6474b5ff0b8f8b86f5a | 1,669 | hpp | C++ | src/neuron/SwcNode.hpp | yzx9/NeuronSdfViewer | 454164dfccf80b806aac3cd7cca09e2cb8bd3c2a | [
"MIT"
] | 1 | 2021-12-31T10:29:56.000Z | 2021-12-31T10:29:56.000Z | src/neuron/SwcNode.hpp | yzx9/NeuronSdfViewer | 454164dfccf80b806aac3cd7cca09e2cb8bd3c2a | [
"MIT"
] | null | null | null | src/neuron/SwcNode.hpp | yzx9/NeuronSdfViewer | 454164dfccf80b806aac3cd7cca09e2cb8bd3c2a | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <regex>
#include <memory>
class SwcNode
{
public:
int id;
int type;
float x;
float y;
float z;
float raidus;
int parent;
std::unique_ptr<SwcNode> child;
std::unique_ptr<SwcNode> next;
static bool try_parse(const std::string &s, std::unique_ptr<SwcNode> &out)
{
constexpr auto pattern =
"\\s*"
"(\\d+)\\s" // index
"(\\d+)\\s" // type
"(-?\\d*(?:\\.\\d+)?)\\s" // x
"(-?\\d*(?:\\.\\d+)?)\\s" // y
"(-?\\d*(?:\\.\\d+)?)\\s" // z
"(-?\\d*(?:\\.\\d+)?)\\s" // radius
"(-1|\\d+)\\s*"; // parent
const static std::regex regex(pattern);
std::smatch match;
if (!std::regex_match(s, match, regex))
return false;
out = std::make_unique<SwcNode>();
out->id = std::stoi(match[1]);
out->type = std::stoi(match[2]);
out->x = std::stof(match[3]);
out->y = std::stof(match[4]);
out->z = std::stof(match[5]);
out->raidus = std::stof(match[6]);
out->parent = std::stoi(match[7]);
out->child = nullptr;
out->next = nullptr;
return true;
};
void add_brother(std::unique_ptr<SwcNode> brother)
{
if (next)
next->add_brother(std::move(brother));
else
next = std::move(brother);
};
void add_child(std::unique_ptr<SwcNode> new_child)
{
if (child)
child->add_brother(std::move(new_child));
else
child = std::move(new_child);
}
};
| 24.910448 | 78 | 0.461354 |
1ad1c9ba27ea9312c984187f93241cd191ae6094 | 436 | inl | C++ | include/generator_python.inl | Three7Six/FastBinaryEncoding | 2d74ad66afe1cd30988fbbde059a25a2d6f215c6 | [
"MIT"
] | 1 | 2019-11-16T17:50:52.000Z | 2019-11-16T17:50:52.000Z | include/generator_python.inl | Three7Six/FastBinaryEncoding | 2d74ad66afe1cd30988fbbde059a25a2d6f215c6 | [
"MIT"
] | null | null | null | include/generator_python.inl | Three7Six/FastBinaryEncoding | 2d74ad66afe1cd30988fbbde059a25a2d6f215c6 | [
"MIT"
] | null | null | null | /*!
\file generator_python.inl
\brief Fast binary encoding Python generator inline implementation
\author Ivan Shynkarenka
\date 24.04.2018
\copyright MIT License
*/
namespace FBE {
inline GeneratorPython::GeneratorPython(const std::string& input, const std::string& output, int indent, char space)
: Generator(input, output, indent, space), _final(false), _json(false), _sender(false)
{
}
} // namespace FBE
| 25.647059 | 116 | 0.720183 |
1ada9add6985b6dd3426f201a064ccf6154cef73 | 7,724 | cc | C++ | content/renderer/pepper/pepper_plugin_instance_throttler_unittest.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-11-28T10:46:52.000Z | 2019-11-28T10:46:52.000Z | content/renderer/pepper/pepper_plugin_instance_throttler_unittest.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/pepper/pepper_plugin_instance_throttler_unittest.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-03-27T11:15:39.000Z | 2016-08-17T14:19:56.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/bind.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "content/public/common/content_switches.h"
#include "content/public/renderer/render_frame.h"
#include "content/renderer/pepper/pepper_plugin_instance_throttler.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "third_party/WebKit/public/web/WebPluginParams.h"
#include "ui/gfx/canvas.h"
using testing::_;
using testing::Return;
class GURL;
namespace content {
class PepperPluginInstanceThrottlerTest : public testing::Test {
protected:
PepperPluginInstanceThrottlerTest() : change_callback_calls_(0) {}
void SetUp() override {
blink::WebRect rect;
rect.width = 100;
rect.height = 100;
throttler_.reset(new PepperPluginInstanceThrottler(
nullptr, rect, true /* is_flash_plugin */, GURL("http://example.com"),
content::RenderFrame::POWER_SAVER_MODE_PERIPHERAL_THROTTLED,
base::Bind(&PepperPluginInstanceThrottlerTest::ChangeCallback,
base::Unretained(this))));
}
PepperPluginInstanceThrottler* throttler() {
DCHECK(throttler_.get());
return throttler_.get();
}
void DisablePowerSaverByRetroactiveWhitelist() {
throttler()->DisablePowerSaver(
PepperPluginInstanceThrottler::UNTHROTTLE_METHOD_BY_WHITELIST);
}
int change_callback_calls() { return change_callback_calls_; }
void EngageThrottle() {
throttler_->SetPluginThrottled(true);
}
void SendEventAndTest(blink::WebInputEvent::Type event_type,
bool expect_consumed,
bool expect_throttled,
int expect_change_callback_count) {
blink::WebMouseEvent event;
event.type = event_type;
event.modifiers = blink::WebInputEvent::Modifiers::LeftButtonDown;
EXPECT_EQ(expect_consumed, throttler()->ConsumeInputEvent(event));
EXPECT_EQ(expect_throttled, throttler()->is_throttled());
EXPECT_EQ(expect_change_callback_count, change_callback_calls());
}
private:
void ChangeCallback() { ++change_callback_calls_; }
scoped_ptr<PepperPluginInstanceThrottler> throttler_;
int change_callback_calls_;
base::MessageLoop loop_;
};
TEST_F(PepperPluginInstanceThrottlerTest, ThrottleAndUnthrottleByClick) {
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
EngageThrottle();
EXPECT_TRUE(throttler()->is_throttled());
EXPECT_EQ(1, change_callback_calls());
// MouseUp while throttled should be consumed and disengage throttling.
SendEventAndTest(blink::WebInputEvent::Type::MouseUp, true, false, 2);
}
TEST_F(PepperPluginInstanceThrottlerTest, ThrottleByKeyframe) {
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
SkBitmap boring_bitmap;
gfx::Canvas canvas(gfx::Size(20, 10), 1.0f, true);
canvas.FillRect(gfx::Rect(20, 10), SK_ColorBLACK);
canvas.FillRect(gfx::Rect(10, 10), SK_ColorWHITE);
SkBitmap interesting_bitmap =
skia::GetTopDevice(*canvas.sk_canvas())->accessBitmap(false);
// Don't throttle for a boring frame.
throttler()->OnImageFlush(&boring_bitmap);
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
// Don't throttle for non-consecutive interesting frames.
throttler()->OnImageFlush(&interesting_bitmap);
throttler()->OnImageFlush(&boring_bitmap);
throttler()->OnImageFlush(&interesting_bitmap);
throttler()->OnImageFlush(&boring_bitmap);
throttler()->OnImageFlush(&interesting_bitmap);
throttler()->OnImageFlush(&boring_bitmap);
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
// Throttle after consecutive interesting frames.
throttler()->OnImageFlush(&interesting_bitmap);
throttler()->OnImageFlush(&interesting_bitmap);
throttler()->OnImageFlush(&interesting_bitmap);
throttler()->OnImageFlush(&interesting_bitmap);
EXPECT_TRUE(throttler()->is_throttled());
EXPECT_EQ(1, change_callback_calls());
}
TEST_F(PepperPluginInstanceThrottlerTest, IgnoreThrottlingAfterMouseUp) {
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
// MouseUp before throttling engaged should not be consumed, but should
// prevent subsequent throttling from engaging.
SendEventAndTest(blink::WebInputEvent::Type::MouseUp, false, false, 0);
EngageThrottle();
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
}
TEST_F(PepperPluginInstanceThrottlerTest, FastWhitelisting) {
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
DisablePowerSaverByRetroactiveWhitelist();
EngageThrottle();
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(1, change_callback_calls());
}
TEST_F(PepperPluginInstanceThrottlerTest, SlowWhitelisting) {
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
EngageThrottle();
EXPECT_TRUE(throttler()->is_throttled());
EXPECT_EQ(1, change_callback_calls());
DisablePowerSaverByRetroactiveWhitelist();
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(2, change_callback_calls());
}
TEST_F(PepperPluginInstanceThrottlerTest, EventConsumption) {
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
EngageThrottle();
EXPECT_TRUE(throttler()->is_throttled());
EXPECT_EQ(1, change_callback_calls());
// Consume but don't unthrottle on a variety of other events.
SendEventAndTest(blink::WebInputEvent::Type::MouseDown, true, true, 1);
SendEventAndTest(blink::WebInputEvent::Type::MouseWheel, true, true, 1);
SendEventAndTest(blink::WebInputEvent::Type::MouseMove, true, true, 1);
SendEventAndTest(blink::WebInputEvent::Type::KeyDown, true, true, 1);
SendEventAndTest(blink::WebInputEvent::Type::KeyUp, true, true, 1);
// Consume and unthrottle on MouseUp
SendEventAndTest(blink::WebInputEvent::Type::MouseUp, true, false, 2);
// Don't consume events after unthrottle.
SendEventAndTest(blink::WebInputEvent::Type::MouseDown, false, false, 2);
SendEventAndTest(blink::WebInputEvent::Type::MouseWheel, false, false, 2);
SendEventAndTest(blink::WebInputEvent::Type::MouseMove, false, false, 2);
SendEventAndTest(blink::WebInputEvent::Type::KeyDown, false, false, 2);
SendEventAndTest(blink::WebInputEvent::Type::KeyUp, false, false, 2);
// Subsequent MouseUps should also not be consumed.
SendEventAndTest(blink::WebInputEvent::Type::MouseUp, false, false, 2);
}
TEST_F(PepperPluginInstanceThrottlerTest, ThrottleOnLeftClickOnly) {
EXPECT_FALSE(throttler()->is_throttled());
EXPECT_EQ(0, change_callback_calls());
EngageThrottle();
EXPECT_TRUE(throttler()->is_throttled());
EXPECT_EQ(1, change_callback_calls());
blink::WebMouseEvent event;
event.type = blink::WebInputEvent::Type::MouseUp;
event.modifiers = blink::WebInputEvent::Modifiers::RightButtonDown;
EXPECT_FALSE(throttler()->ConsumeInputEvent(event));
EXPECT_TRUE(throttler()->is_throttled());
event.modifiers = blink::WebInputEvent::Modifiers::MiddleButtonDown;
EXPECT_TRUE(throttler()->ConsumeInputEvent(event));
EXPECT_TRUE(throttler()->is_throttled());
event.modifiers = blink::WebInputEvent::Modifiers::LeftButtonDown;
EXPECT_TRUE(throttler()->ConsumeInputEvent(event));
EXPECT_FALSE(throttler()->is_throttled());
}
} // namespace content
| 35.59447 | 78 | 0.752201 |
1adff208083bea1d0805b338aabccdebbc09a1d9 | 315 | inl | C++ | src/readers/F3DExodusIIReader.inl | Meakk/f3d | 40db15ab2a6500ea67bfee5d35714b5c5e2d993c | [
"BSD-3-Clause"
] | 318 | 2021-11-14T02:22:32.000Z | 2022-03-31T02:32:52.000Z | src/readers/F3DExodusIIReader.inl | Meakk/f3d | 40db15ab2a6500ea67bfee5d35714b5c5e2d993c | [
"BSD-3-Clause"
] | 223 | 2021-11-12T20:52:41.000Z | 2022-03-29T21:35:18.000Z | src/readers/F3DExodusIIReader.inl | Meakk/f3d | 40db15ab2a6500ea67bfee5d35714b5c5e2d993c | [
"BSD-3-Clause"
] | 24 | 2021-11-12T22:12:24.000Z | 2022-03-28T12:42:17.000Z | void ApplyCustomReader(vtkAlgorithm* reader, const std::string&) const override
{
vtkExodusIIReader* exReader = vtkExodusIIReader::SafeDownCast(reader);
exReader->UpdateInformation();
exReader->SetAllArrayStatus(vtkExodusIIReader::NODAL, 1);
exReader->SetAllArrayStatus(vtkExodusIIReader::ELEM_BLOCK, 1);
}
| 39.375 | 79 | 0.8 |
1ae6ee53a1b5bd07a80998f710a02123d3fe9285 | 5,254 | hpp | C++ | Altis_Life.Altis/config/Config_Process.hpp | TomLorenzi/AltasiaV2-Public | 324e20c4730587de8f7e3eab8acbe9cb02912a1a | [
"MIT"
] | null | null | null | Altis_Life.Altis/config/Config_Process.hpp | TomLorenzi/AltasiaV2-Public | 324e20c4730587de8f7e3eab8acbe9cb02912a1a | [
"MIT"
] | null | null | null | Altis_Life.Altis/config/Config_Process.hpp | TomLorenzi/AltasiaV2-Public | 324e20c4730587de8f7e3eab8acbe9cb02912a1a | [
"MIT"
] | null | null | null | /*
* class:
* MaterialsReq (Needed to process) = Array - Format -> {{"ITEM CLASS",HOWMANY}}
* MaterialsGive (Returned items) = Array - Format -> {{"ITEM CLASS",HOWMANY}}
* Text (Progess Bar Text) = Localised String
* NoLicenseCost (Cost to process w/o license) = Scalar
*
* Example for multiprocess:
*
* class Example {
* MaterialsReq[] = {{"cocaine_processed",1},{"heroin_processed",1}};
* MaterialsGive[] = {{"diamond_cut",1}};
* Text = "STR_Process_Example";
* //ScrollText = "Process Example";
* NoLicenseCost = 4000;
* };
*/
class ProcessAction {
class oil {
MaterialsReq[] = {{"oil_unprocessed",1}};
MaterialsGive[] = {{"oil_processed",1}};
Text = "STR_Process_Oil";
//ScrollText = "Process Oil";
NoLicenseCost = 1200;
};
class diamond {
MaterialsReq[] = {{"diamond_uncut",1}};
MaterialsGive[] = {{"diamond_cut",1}};
Text = "STR_Process_Diamond";
//ScrollText = "Cut Diamonds";
NoLicenseCost = 1350;
};
class heroin {
MaterialsReq[] = {{"heroin_unprocessed",1}};
MaterialsGive[] = {{"heroin_processed",1}};
Text = "STR_Process_Heroin";
//ScrollText = "Process Heroin";
NoLicenseCost = 1750;
};
class copper {
MaterialsReq[] = {{"copper_unrefined",1}};
MaterialsGive[] = {{"copper_refined",1}};
Text = "STR_Process_Copper";
//ScrollText = "Refine Copper";
NoLicenseCost = 750;
};
class iron {
MaterialsReq[] = {{"iron_unrefined",1}};
MaterialsGive[] = {{"iron_refined",1}};
Text = "STR_Process_Iron";
//ScrollText = "Refine Iron";
NoLicenseCost = 1120;
};
class sand {
MaterialsReq[] = {{"sand",1}};
MaterialsGive[] = {{"glass",1}};
Text = "STR_Process_Sand";
//ScrollText = "Melt Sand into Glass";
NoLicenseCost = 650;
};
class salt {
MaterialsReq[] = {{"salt_unrefined",1}};
MaterialsGive[] = {{"salt_refined",1}};
Text = "STR_Process_Salt";
//ScrollText = "Refine Salt";
NoLicenseCost = 450;
};
class cocaine {
MaterialsReq[] = {{"cocaine_unprocessed",1}};
MaterialsGive[] = {{"cocaine_processed",1}};
Text = "STR_Process_Cocaine";
//ScrollText = "Process Cocaine";
NoLicenseCost = 1500;
};
class marijuana {
MaterialsReq[] = {{"cannabis",1}};
MaterialsGive[] = {{"marijuana",1}};
Text = "STR_Process_Marijuana";
//ScrollText = "Harvest Marijuana";
NoLicenseCost = 500;
};
class nos {
MaterialsReq[] = {{"marijuana",1}};
MaterialsGive[] = {{"joint",1}};
Text = "STR_Process_Joint";
NoLicenseCost = 500;
};
class cement {
MaterialsReq[] = {{"rock",1}};
MaterialsGive[] = {{"cement",1}};
Text = "STR_Process_Cement";
//ScrollText = "Mix Cement";
NoLicenseCost = 350;
};
class wood {
MaterialsReq[] = {{"wood",1}};
MaterialsGive[] = {{"paper",1}};
Text = "STR_Process_Wood";
NoLicenseCost = 350;
};
class paper {
MaterialsReq[] = {{"paper",1}};
MaterialsGive[] = {{"fakeMoney",1}};
Text = "STR_Process_FakeMoney";
NoLicenseCost = 350;
};
class cigarette {
MaterialsReq[] = {{"tabac",1}};
MaterialsGive[] = {{"cigarette",1}};
Text = "STR_Process_Cigarette";
NoLicenseCost = 350;
};
class cigar {
MaterialsReq[] = {{"tabac",1}};
MaterialsGive[] = {{"cigar",1}};
Text = "STR_Process_Cigar";
NoLicenseCost = 350;
};
class uraClean {
MaterialsReq[] = {{"uraWaste",1}};
MaterialsGive[] = {{"uraClean",1}};
Text = "STR_Process_UraClean";
NoLicenseCost = 350;
};
class uraRich {
MaterialsReq[] = {{"uraClean",1}};
MaterialsGive[] = {{"uraRich",1}};
Text = "STR_Process_UraRich";
NoLicenseCost = 350;
};
class uraFinal {
MaterialsReq[] = {{"uraRich",1}};
MaterialsGive[] = {{"uraFinal",1}};
Text = "STR_Process_UraFinal";
NoLicenseCost = 350;
};
class diamondHub {
MaterialsReq[] = {{"diamond_cut",1}};
MaterialsGive[] = {{"bague",1}};
Text = "STR_Process_Bague";
NoLicenseCost = 350;
};
class OxyScrap {
MaterialsReq[] = {{"copper_refined",1}};
MaterialsGive[] = {{"tuyau",1}};
Text = "STR_Process_Tuyau";
NoLicenseCost = 350;
};
class carte_graph {
MaterialsReq[] = {{"carte_graph_endom",1}};
MaterialsGive[] = {{"carte_graph",1}};
Text = "STR_Process_Carte_Graph";
NoLicenseCost = 350;
};
class bitcoin {
MaterialsReq[] = {{"carte_graph",18}};
MaterialsGive[] = {{"bitcoin",1}};
Text = "STR_Process_Bitcoin";
NoLicenseCost = 350;
};
class ordi {
MaterialsReq[] = {{"carte_graph",1}};
MaterialsGive[] = {{"ordi",1}};
Text = "STR_Process_Ordi";
NoLicenseCost = 350;
};
};
| 27.507853 | 85 | 0.533879 |
1ae9cfbf8cb82475063bd9410a9aa6fccb9208cf | 64,799 | cc | C++ | deps/sparsehash/src/hashtable_unittest.cc | PelionIoT/twlib | 7a2219924e66cb33810dad5a8314b0f0cff49018 | [
"DOC",
"MIT"
] | 1 | 2017-09-15T19:48:30.000Z | 2017-09-15T19:48:30.000Z | deps/sparsehash/src/hashtable_unittest.cc | PelionIoT/twlib | 7a2219924e66cb33810dad5a8314b0f0cff49018 | [
"DOC",
"MIT"
] | null | null | null | deps/sparsehash/src/hashtable_unittest.cc | PelionIoT/twlib | 7a2219924e66cb33810dad5a8314b0f0cff49018 | [
"DOC",
"MIT"
] | 1 | 2019-10-23T08:48:56.000Z | 2019-10-23T08:48:56.000Z | // Copyright (c) 2005, Google Inc.
// 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 Google Inc. 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
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---
// Author: Craig Silverstein
//
// This tests <google/sparsehash/densehashtable.h>
// This tests <google/dense_hash_set>
// This tests <google/dense_hash_map>
// This tests <google/sparsehash/sparsehashtable.h>
// This tests <google/sparse_hash_set>
// This tests <google/sparse_hash_map>
// Since {dense,sparse}hashtable is templatized, it's important that
// we test every function in every class in this file -- not just to
// see if it works, but even if it compiles.
#include "config.h"
#include <stdio.h>
#include <sys/stat.h> // for stat()
#ifdef HAVE_UNISTD_H
#include <unistd.h> // for unlink()
#endif
#include <string.h>
#include <time.h> // for silly random-number-seed generator
#include <math.h> // for sqrt()
#include <map>
#include <set>
#include <iterator> // for insert_iterator
#include <iostream>
#include <iomanip> // for setprecision()
#include <string>
#include <stdexcept> // for std::length_error
#include HASH_FUN_H // defined in config.h
#include <google/type_traits.h>
#include <google/sparsehash/libc_allocator_with_realloc.h>
#include <google/dense_hash_map>
#include <google/dense_hash_set>
#include <google/sparsehash/densehashtable.h>
#include <google/sparse_hash_map>
#include <google/sparse_hash_set>
#include <google/sparsehash/sparsehashtable.h>
// Otherwise, VC++7 warns about size_t -> int in the cout logging lines
#ifdef _MSC_VER
#pragma warning(disable:4267)
#endif
using GOOGLE_NAMESPACE::sparse_hash_map;
using GOOGLE_NAMESPACE::dense_hash_map;
using GOOGLE_NAMESPACE::sparse_hash_set;
using GOOGLE_NAMESPACE::dense_hash_set;
using GOOGLE_NAMESPACE::sparse_hashtable;
using GOOGLE_NAMESPACE::dense_hashtable;
using GOOGLE_NAMESPACE::libc_allocator_with_realloc;
using STL_NAMESPACE::map;
using STL_NAMESPACE::set;
using STL_NAMESPACE::vector;
using STL_NAMESPACE::pair;
using STL_NAMESPACE::make_pair;
using STL_NAMESPACE::string;
using STL_NAMESPACE::insert_iterator;
using STL_NAMESPACE::allocator;
using STL_NAMESPACE::equal_to;
using STL_NAMESPACE::ostream;
typedef unsigned char uint8;
#define LOGF STL_NAMESPACE::cout // where we log to; LOGF is a historical name
#define CHECK(cond) do { \
if (!(cond)) { \
LOGF << "Test failed: " #cond "\n"; \
exit(1); \
} \
} while (0)
#define CHECK_EQ(a, b) CHECK((a) == (b))
#define CHECK_LT(a, b) CHECK((a) < (b))
#define CHECK_GT(a, b) CHECK((a) > (b))
#define CHECK_LE(a, b) CHECK((a) <= (b))
#define CHECK_GE(a, b) CHECK((a) >= (b))
#ifndef _MSC_VER // windows defines its own version
static string TmpFile(const char* basename) {
return string("/tmp/") + basename;
}
#endif
const char *words[] = {"Baffin\n", // in /usr/dict/words
"Boffin\n", // not in
"baffin\n", // not in
"genial\n", // last word in
"Aarhus\n", // first word alphabetically
"Zurich\n", // last word alphabetically
"Getty\n",
};
const char *nwords[] = {"Boffin\n",
"baffin\n",
};
const char *default_dict[] = {"Aarhus\n",
"aback\n",
"abandon\n",
"Baffin\n",
"baffle\n",
"bagged\n",
"congenial\n",
"genial\n",
"Getty\n",
"indiscreet\n",
"linens\n",
"pence\n",
"reassure\n",
"sequel\n",
"zoning\n",
"zoo\n",
"Zurich\n",
};
// Likewise, it's not standard to hash a string pre-tr1. Luckily, it is a char*
#ifdef HAVE_UNORDERED_MAP
typedef SPARSEHASH_HASH<string> StrHash;
struct CharStarHash {
size_t operator()(const char* s) const {
return StrHash()(string(s));
}
// These are used by MSVC:
bool operator()(const char* a, const char* b) const {
return strcmp(a, b) < 0;
}
static const size_t bucket_size = 4; // These are required by MSVC
static const size_t min_buckets = 8; // 4 and 8 are the defaults
};
#else
typedef SPARSEHASH_HASH<const char*> CharStarHash;
struct StrHash {
size_t operator()(const string& s) const {
return SPARSEHASH_HASH<const char*>()(s.c_str());
}
// These are used by MSVC:
bool operator()(const string& a, const string& b) const {
return a < b;
}
static const size_t bucket_size = 4; // These are required by MSVC
static const size_t min_buckets = 8; // 4 and 8 are the defaults
};
#endif
// Let us log the pairs that make up a hash_map
template<class P1, class P2>
ostream& operator<<(ostream& s, const pair<P1, P2>& p) {
s << "pair(" << p.first << ", " << p.second << ")";
return s;
}
struct strcmp_fnc {
bool operator()(const char* s1, const char* s2) const {
return ((s1 == 0 && s2 == 0) ||
(s1 && s2 && *s1 == *s2 && strcmp(s1, s2) == 0));
}
};
namespace {
template <class T, class H, class I, class S, class C, class A>
void set_empty_key(sparse_hashtable<T,T,H,I,S,C,A> *ht, T val) {
}
template <class T, class H, class C, class A>
void set_empty_key(sparse_hash_set<T,H,C,A> *ht, T val) {
}
template <class K, class V, class H, class C, class A>
void set_empty_key(sparse_hash_map<K,V,H,C,A> *ht, K val) {
}
template <class T, class H, class I, class S, class C, class A>
void set_empty_key(dense_hashtable<T,T,H,I,S,C,A> *ht, T val) {
ht->set_empty_key(val);
}
template <class T, class H, class C, class A>
void set_empty_key(dense_hash_set<T,H,C,A> *ht, T val) {
ht->set_empty_key(val);
}
template <class K, class V, class H, class C, class A>
void set_empty_key(dense_hash_map<K,V,H,C,A> *ht, K val) {
ht->set_empty_key(val);
}
template <class T, class H, class I, class S, class C, class A>
bool clear_no_resize(sparse_hashtable<T,T,H,I,S,C,A> *ht) {
return false;
}
template <class T, class H, class C, class A>
bool clear_no_resize(sparse_hash_set<T,H,C,A> *ht) {
return false;
}
template <class K, class V, class H, class C, class A>
bool clear_no_resize(sparse_hash_map<K,V,H,C,A> *ht) {
return false;
}
template <class T, class H, class I, class S, class C, class A>
bool clear_no_resize(dense_hashtable<T,T,H,I,S,C,A> *ht) {
ht->clear_no_resize();
return true;
}
template <class T, class H, class C, class A>
bool clear_no_resize(dense_hash_set<T,H,C,A> *ht) {
ht->clear_no_resize();
return true;
}
template <class K, class V, class H, class C, class A>
bool clear_no_resize(dense_hash_map<K,V,H,C,A> *ht) {
ht->clear_no_resize();
return true;
}
template <class T, class H, class I, class S, class C, class A>
void insert(dense_hashtable<T,T,H,I,S,C,A> *ht, T val) {
ht->insert(val);
}
template <class T, class H, class C, class A>
void insert(dense_hash_set<T,H,C,A> *ht, T val) {
ht->insert(val);
}
template <class K, class V, class H, class C, class A>
void insert(dense_hash_map<K,V,H,C,A> *ht, K val) {
ht->insert(pair<K,V>(val,V()));
}
template <class T, class H, class I, class S, class C, class A>
void insert(sparse_hashtable<T,T,H,I,S,C,A> *ht, T val) {
ht->insert(val);
}
template <class T, class H, class C, class A>
void insert(sparse_hash_set<T,H,C,A> *ht, T val) {
ht->insert(val);
}
template <class K, class V, class H, class C, class A>
void insert(sparse_hash_map<K,V,H,C,A> *ht, K val) {
ht->insert(pair<K,V>(val,V()));
}
template <class HT, class Iterator>
void insert(HT *ht, Iterator begin, Iterator end) {
ht->insert(begin, end);
}
// For hashtable's and hash_set's, the iterator insert works fine (and
// is used). But for the hash_map's, the iterator insert expects the
// iterators to point to pair's. So by looping over and calling insert
// on each element individually, the code below automatically expands
// into inserting a pair.
template <class K, class V, class H, class C, class A, class Iterator>
void insert(dense_hash_map<K,V,H,C,A> *ht, Iterator begin, Iterator end) {
while (begin != end) {
insert(ht, *begin);
++begin;
}
}
template <class K, class V, class H, class C, class A, class Iterator>
void insert(sparse_hash_map<K,V,H,C,A> *ht, Iterator begin, Iterator end) {
while (begin != end) {
insert(ht, *begin);
++begin;
}
}
// Just like above, but uses operator[] when possible.
template <class T, class H, class I, class S, class C, class A>
void bracket_insert(dense_hashtable<T,T,H,I,S,C,A> *ht, T val) {
ht->insert(val);
}
template <class T, class H, class C, class A>
void bracket_insert(dense_hash_set<T,H,C,A> *ht, T val) {
ht->insert(val);
}
template <class K, class V, class H, class C, class A>
void bracket_insert(dense_hash_map<K,V,H,C,A> *ht, K val) {
(*ht)[val] = V();
}
template <class T, class H, class I, class S, class C, class A>
void bracket_insert(sparse_hashtable<T,T,H,I,S,C,A> *ht, T val) {
ht->insert(val);
}
template <class T, class H, class C, class A>
void bracket_insert(sparse_hash_set<T,H,C,A> *ht, T val) {
ht->insert(val);
}
template <class K, class V, class H, class C, class A>
void bracket_insert(sparse_hash_map<K,V,H,C,A> *ht, K val) {
(*ht)[val] = V();
}
template <class HT, class Iterator>
void bracket_insert(HT *ht, Iterator begin, Iterator end) {
ht->bracket_insert(begin, end);
}
template <class K, class V, class H, class C, class A, class Iterator>
void bracket_insert(dense_hash_map<K,V,H,C,A> *ht,
Iterator begin, Iterator end) {
while (begin != end) {
bracket_insert(ht, *begin);
++begin;
}
}
template <class K, class V, class H, class C, class A, class Iterator>
void bracket_insert(sparse_hash_map<K,V,H,C,A> *ht,
Iterator begin, Iterator end) {
while (begin != end) {
bracket_insert(ht, *begin);
++begin;
}
}
// A version of insert that uses the insert_iterator. But insert_iterator
// isn't defined for the low level hashtable classes, so we just punt to insert.
template <class T, class H, class I, class S, class C, class A>
void iterator_insert(dense_hashtable<T,T,H,I,S,C,A>* ht, T val,
insert_iterator<dense_hashtable<T,T,H,I,S,C,A> >* ) {
ht->insert(val);
}
template <class T, class H, class C, class A>
void iterator_insert(dense_hash_set<T,H,C,A>* , T val,
insert_iterator<dense_hash_set<T,H,C,A> >* ii) {
*(*ii)++ = val;
}
template <class K, class V, class H, class C, class A>
void iterator_insert(dense_hash_map<K,V,H,C,A>* , K val,
insert_iterator<dense_hash_map<K,V,H,C,A> >* ii) {
*(*ii)++ = pair<K,V>(val,V());
}
template <class T, class H, class I, class S, class C, class A>
void iterator_insert(sparse_hashtable<T,T,H,I,S,C,A>* ht, T val,
insert_iterator<sparse_hashtable<T,T,H,I,S,C,A> >* ) {
ht->insert(val);
}
template <class T, class H, class C, class A>
void iterator_insert(sparse_hash_set<T,H,C,A>* , T val,
insert_iterator<sparse_hash_set<T,H,C,A> >* ii) {
*(*ii)++ = val;
}
template <class K, class V, class H, class C, class A>
void iterator_insert(sparse_hash_map<K,V,H,C,A> *, K val,
insert_iterator<sparse_hash_map<K,V,H,C,A> >* ii) {
*(*ii)++ = pair<K,V>(val,V());
}
void write_item(FILE *fp, const char *val) {
fwrite(val, strlen(val), 1, fp); // \n serves to separate
}
// The weird 'const' declarations are desired by the compiler. Yucko.
void write_item(FILE *fp, const pair<char*const,int> &val) {
fwrite(val.first, strlen(val.first), 1, fp);
}
void write_item(FILE *fp, const string &val) {
fwrite(val.data(), val.length(), 1, fp); // \n serves to separate
}
// The weird 'const' declarations are desired by the compiler. Yucko.
void write_item(FILE *fp, const pair<const string,int> &val) {
fwrite(val.first.data(), val.first.length(), 1, fp);
}
char* read_line(FILE* fp, char* line, int linesize) {
if ( fgets(line, linesize, fp) == NULL )
return NULL;
// normalize windows files :-(
const size_t linelen = strlen(line);
if ( linelen >= 2 && line[linelen-2] == '\r' && line[linelen-1] == '\n' ) {
line[linelen-2] = '\n';
line[linelen-1] = '\0';
}
return line;
}
void read_item(FILE *fp, char*const* val) {
char line[1024];
read_line(fp, line, sizeof(line));
char **p = const_cast<char**>(val);
*p = strdup(line);
}
void read_item(FILE *fp, pair<char*const,int> *val) {
char line[1024];
read_line(fp, line, sizeof(line));
char **p = const_cast<char**>(&val->first);
*p = strdup(line);
}
void read_item(FILE *fp, const string* val) {
char line[1024];
read_line(fp, line, sizeof(line));
new(const_cast<string*>(val)) string(line); // need to use placement new
}
void read_item(FILE *fp, pair<const string,int> *val) {
char line[1024];
read_line(fp, line, sizeof(line));
new(const_cast<string*>(&val->first)) string(line);
}
void free_item(char*const* val) {
free(*val);
}
void free_item(pair<char*const,int> *val) {
free(val->first);
}
int get_int_item(int int_item) {
return int_item;
}
int get_int_item(pair<int, int> val) {
return val.first;
}
int getintkey(int i) { return i; }
int getintkey(const pair<int, int> &p) { return p.first; }
template<typename T>
class DenseStringMap : public dense_hash_map<string, T> {
public:
DenseStringMap() { this->set_empty_key(string()); }
};
class DenseStringSet : public dense_hash_set<string> {
public:
DenseStringSet() { this->set_empty_key(string()); }
};
// Allocator that uses uint8 as size_type to test overflowing on insert.
// Also, to test allocators with state, if you pass in an int*, we
// increment it on every alloc and realloc call. Because we use this
// allocator in a vector, we need to define != and swap for gcc.
template<typename T, typename SizeT, int MAX_SIZE>
struct Alloc {
typedef T value_type;
typedef SizeT size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
Alloc(int* count = NULL) : count_(count) {}
~Alloc() {}
pointer address(reference r) const { return &r; }
const_pointer address(const_reference r) const { return &r; }
pointer allocate(size_type n, const_pointer = 0) {
if (count_) ++(*count_);
return static_cast<pointer>(malloc(n * sizeof(value_type)));
}
void deallocate(pointer p, size_type n) {
free(p);
}
pointer reallocate(pointer p, size_type n) {
if (count_) ++(*count_);
return static_cast<pointer>(realloc(p, n * sizeof(value_type)));
}
size_type max_size() const {
return static_cast<size_type>(MAX_SIZE);
}
void construct(pointer p, const value_type& val) {
new(p) value_type(val);
}
void destroy(pointer p) { p->~value_type(); }
bool is_custom_alloc() const { return true; }
template <class U>
Alloc(const Alloc<U, SizeT, MAX_SIZE>& that) : count_(that.count_) {}
template <class U>
struct rebind {
typedef Alloc<U, SizeT, MAX_SIZE> other;
};
bool operator!=(const Alloc<T,SizeT,MAX_SIZE>& that) {
return this->count_ != that.count_;
}
private:
template<typename U, typename U_SizeT, int U_MAX_SIZE> friend class Alloc;
int* count_;
};
} // end anonymous namespace
// Performs tests where the hashtable's value type is assumed to be int.
template <class htint>
void test_int() {
htint x;
htint y(1000);
htint z(64);
set_empty_key(&x, 0xefefef);
set_empty_key(&y, 0xefefef);
set_empty_key(&z, 0xefefef);
CHECK(y.empty());
insert(&y, 1);
CHECK(!y.empty());
insert(&y, 11);
insert(&y, 111);
insert(&y, 1111);
insert(&y, 11111);
insert(&y, 111111);
insert(&y, 1111111); // 1M, more or less
insert(&y, 11111111);
insert(&y, 111111111);
insert(&y, 1111111111); // 1B, more or less
for ( int i = 0; i < 64; ++i )
insert(&z, i);
// test the second half of the insert with an insert_iterator
insert_iterator<htint> insert_iter(z, z.begin());
for ( int i = 32; i < 64; ++i )
iterator_insert(&z, i, &insert_iter);
// only perform the following CHECKs for
// dense{hashtable, _hash_set, _hash_map}
if (clear_no_resize(&x)) {
// make sure x has to increase its number of buckets
typename htint::size_type empty_bucket_count = x.bucket_count();
int last_element = 0;
while (x.bucket_count() == empty_bucket_count) {
insert(&x, last_element);
++last_element;
}
// if clear_no_resize is supported (i.e. htint is a
// dense{hashtable,_hash_set,_hash_map}), it should leave the bucket_count
// as is.
typename htint::size_type last_bucket_count = x.bucket_count();
clear_no_resize(&x);
CHECK(last_bucket_count == x.bucket_count());
CHECK(x.empty());
LOGF << "x has " << x.bucket_count() << " buckets\n";
LOGF << "x size " << x.size() << "\n";
// when inserting the same number of elements again, no resize should be
// necessary
for (int i = 0; i < last_element; ++i) {
insert(&x, i);
CHECK(x.bucket_count() == last_bucket_count);
}
}
for ( typename htint::const_iterator it = y.begin(); it != y.end(); ++it )
LOGF << "y: " << get_int_item(*it) << "\n";
z.insert(y.begin(), y.end());
swap(y,z);
for ( typename htint::iterator it = y.begin(); it != y.end(); ++it )
LOGF << "y+z: " << get_int_item(*it) << "\n";
LOGF << "z has " << z.bucket_count() << " buckets\n";
LOGF << "y has " << y.bucket_count() << " buckets\n";
LOGF << "z size: " << z.size() << "\n";
for (int i = 0; i < 64; ++i)
CHECK(y.find(i) != y.end());
CHECK(z.size() == 10);
z.set_deleted_key(1010101010); // an unused value
CHECK(z.deleted_key() == 1010101010);
z.erase(11111);
CHECK(z.size() == 9);
insert(&z, 11111); // should retake deleted value
CHECK(z.size() == 10);
// Do the delete/insert again. Last time we probably resized; this time no
z.erase(11111);
insert(&z, 11111); // should retake deleted value
CHECK(z.size() == 10);
z.erase(-11111); // shouldn't do anything
CHECK(z.size() == 10);
z.erase(1);
CHECK(z.size() == 9);
typename htint::iterator itdel = z.find(1111);
pair<typename htint::iterator,typename htint::iterator> itdel2
= z.equal_range(1111);
CHECK(itdel2.first != z.end());
CHECK(&*itdel2.first == &*itdel); // while we're here, check equal_range()
CHECK(itdel2.second == ++itdel2.first);
pair<typename htint::const_iterator,typename htint::const_iterator> itdel3
= const_cast<const htint*>(&z)->equal_range(1111);
CHECK(itdel3.first != z.end());
CHECK(&*itdel3.first == &*itdel);
CHECK(itdel3.second == ++itdel3.first);
z.erase(itdel);
CHECK(z.size() == 8);
itdel2 = z.equal_range(1111);
CHECK(itdel2.first == z.end());
CHECK(itdel2.second == itdel2.first);
itdel3 = const_cast<const htint*>(&z)->equal_range(1111);
CHECK(itdel3.first == z.end());
CHECK(itdel3.second == itdel3.first);
itdel = z.find(2222); // should be end()
z.erase(itdel); // shouldn't do anything
CHECK(z.size() == 8);
for ( typename htint::const_iterator it = z.begin(); it != z.end(); ++it )
LOGF << "y: " << get_int_item(*it) << "\n";
z.set_deleted_key(1010101011); // a different unused value
CHECK(z.deleted_key() == 1010101011);
for ( typename htint::const_iterator it = z.begin(); it != z.end(); ++it )
LOGF << "y: " << get_int_item(*it) << "\n";
LOGF << "That's " << z.size() << " elements\n";
z.erase(z.begin(), z.end());
CHECK(z.empty());
y.clear();
CHECK(y.empty());
LOGF << "y has " << y.bucket_count() << " buckets\n";
// Let's do some crash-testing with operator[]
y.set_deleted_key(-1);
for (int iters = 0; iters < 10; iters++) {
// We start at 33 because after shrinking, we'll be at 32 buckets.
for (int i = 33; i < 133; i++) {
bracket_insert(&y, i);
}
clear_no_resize(&y);
// This will force a shrink on the next insert, which we want to test.
insert(&y, 0);
y.erase(0);
}
}
// Performs tests where the hashtable's value type is assumed to be char*.
// The read_write parameters specifies whether the read/write tests
// should be performed. Note that densehashtable::write_metdata is not
// implemented, so we only do the read/write tests for the
// sparsehashtable varieties.
template <class ht>
void test_charptr(bool read_write) {
ht w;
set_empty_key(&w, (char*) NULL);
insert(&w, const_cast<char **>(nwords),
const_cast<char **>(nwords) + sizeof(nwords) / sizeof(*nwords));
LOGF << "w has " << w.size() << " items\n";
CHECK(w.size() == 2);
CHECK(w == w);
ht x;
set_empty_key(&x, (char*) NULL);
long dict_size = 1; // for size stats -- can't be 0 'cause of division
map<string, int> counts;
// Hash the dictionary
{
// automake says 'look for all data files in $srcdir.' OK.
string filestr = (string(getenv("srcdir") ? getenv("srcdir") : ".") +
"/src/words");
const char* file = filestr.c_str();
FILE *fp = fopen(file, "rb");
if ( fp == NULL ) {
LOGF << "Can't open " << file << ", using small, built-in dict...\n";
for (int i = 0; i < sizeof(default_dict)/sizeof(*default_dict); ++i) {
insert(&x, strdup(default_dict[i]));
counts[default_dict[i]] = 0;
}
} else {
char line[1024];
while ( read_line(fp, line, sizeof(line)) ) {
insert(&x, strdup(line));
counts[line] = 0;
}
LOGF << "Read " << x.size() << " words from " << file << "\n";
fclose(fp);
struct stat buf;
stat(file, &buf);
dict_size = buf.st_size;
LOGF << "Size of " << file << ": " << buf.st_size << " bytes\n";
}
for (char **word = const_cast<char **>(words);
word < const_cast<char **>(words) + sizeof(words) / sizeof(*words);
++word ) {
if (x.find(*word) == x.end()) {
CHECK(w.find(*word) != w.end());
} else {
CHECK(w.find(*word) == w.end());
}
}
}
CHECK(counts.size() == x.size());
// Save the hashtable.
if (read_write) {
const string file_string = TmpFile(".hashtable_unittest_dicthash");
const char* file = file_string.c_str();
FILE *fp = fopen(file, "wb");
if ( fp == NULL ) {
// maybe we can't write to /tmp/. Try the current directory
file = ".hashtable_unittest_dicthash";
fp = fopen(file, "wb");
}
if ( fp == NULL ) {
LOGF << "Can't open " << file << " skipping hashtable save...\n";
} else {
x.write_metadata(fp); // this only writes meta-information
int write_count = 0;
for ( typename ht::iterator it = x.begin(); it != x.end(); ++it ) {
write_item(fp, *it);
free_item(&(*it));
++write_count;
}
LOGF << "Wrote " << write_count << " words to " << file << "\n";
fclose(fp);
struct stat buf;
stat(file, &buf);
LOGF << "Size of " << file << ": " << buf.st_size << " bytes\n";
LOGF << STL_NAMESPACE::setprecision(3)
<< "Hashtable overhead "
<< (buf.st_size - dict_size) * 100.0 / dict_size
<< "% ("
<< (buf.st_size - dict_size) * 8.0 / write_count
<< " bits/entry)\n";
x.clear();
// Load the hashtable
fp = fopen(file, "rb");
if ( fp == NULL ) {
LOGF << "Can't open " << file << " skipping hashtable reload...\n";
} else {
x.read_metadata(fp); // reads metainformation
LOGF << "Hashtable size: " << x.size() << "\n";
int read_count = 0;
for ( typename ht::iterator it = x.begin(); it != x.end(); ++it ) {
read_item(fp, &(*it));
++read_count;
}
LOGF << "Read " << read_count << " words from " << file << "\n";
fclose(fp);
unlink(file);
for ( char **word = const_cast<char **>(words);
word < const_cast<char **>(words) + sizeof(words) / sizeof(*words);
++word ) {
if (x.find(*word) == x.end()) {
CHECK(w.find(*word) != w.end());
} else {
CHECK(w.find(*word) == w.end());
}
}
}
}
}
for ( typename ht::iterator it = x.begin(); it != x.end(); ++it ) {
free_item(&(*it));
}
}
// Perform tests where the hashtable's value type is assumed to
// be string.
// TODO(austern): factor out the bulk of test_charptr and test_string
// into a common function.
template <class ht>
void test_string(bool read_write) {
ht w;
set_empty_key(&w, string("-*- empty key -*-"));
const int N = sizeof(nwords) / sizeof(*nwords);
string* nwords1 = new string[N];
for (int i = 0; i < N; ++i)
nwords1[i] = nwords[i];
insert(&w, nwords1, nwords1 + N);
delete[] nwords1;
LOGF << "w has " << w.size() << " items\n";
CHECK(w.size() == 2);
CHECK(w == w);
ht x;
set_empty_key(&x, string("-*- empty key -*-"));
long dict_size = 1; // for size stats -- can't be 0 'cause of division
map<string, int> counts;
// Hash the dictionary
{
// automake says 'look for all data files in $srcdir.' OK.
string filestr = (string(getenv("srcdir") ? getenv("srcdir") : ".") +
"/src/words");
const char* file = filestr.c_str();
FILE *fp = fopen(file, "rb");
if ( fp == NULL ) {
LOGF << "Can't open " << file << ", using small, built-in dict...\n";
for (int i = 0; i < sizeof(default_dict)/sizeof(*default_dict); ++i) {
insert(&x, string(default_dict[i]));
counts[default_dict[i]] = 0;
}
} else {
char line[1024];
while ( fgets(line, sizeof(line), fp) ) {
insert(&x, string(line));
counts[line] = 0;
}
LOGF << "Read " << x.size() << " words from " << file << "\n";
fclose(fp);
struct stat buf;
stat(file, &buf);
dict_size = buf.st_size;
LOGF << "Size of " << file << ": " << buf.st_size << " bytes\n";
}
for ( const char* const* word = words;
word < words + sizeof(words) / sizeof(*words);
++word ) {
if (x.find(*word) == x.end()) {
CHECK(w.find(*word) != w.end());
} else {
CHECK(w.find(*word) == w.end());
}
}
}
CHECK(counts.size() == x.size());
{
// verify that size() works correctly
int xcount = 0;
for ( typename ht::iterator it = x.begin(); it != x.end(); ++it ) {
++xcount;
}
CHECK(x.size() == xcount);
}
// Save the hashtable.
if (read_write) {
const string file_string = TmpFile(".hashtable_unittest_dicthash_str");
const char* file = file_string.c_str();
FILE *fp = fopen(file, "wb");
if ( fp == NULL ) {
// maybe we can't write to /tmp/. Try the current directory
file = ".hashtable_unittest_dicthash_str";
fp = fopen(file, "wb");
}
if ( fp == NULL ) {
LOGF << "Can't open " << file << " skipping hashtable save...\n";
} else {
x.write_metadata(fp); // this only writes meta-information
int write_count = 0;
for ( typename ht::iterator it = x.begin(); it != x.end(); ++it ) {
write_item(fp, *it);
++write_count;
}
LOGF << "Wrote " << write_count << " words to " << file << "\n";
fclose(fp);
struct stat buf;
stat(file, &buf);
LOGF << "Size of " << file << ": " << buf.st_size << " bytes\n";
LOGF << STL_NAMESPACE::setprecision(3)
<< "Hashtable overhead "
<< (buf.st_size - dict_size) * 100.0 / dict_size
<< "% ("
<< (buf.st_size - dict_size) * 8.0 / write_count
<< " bits/entry)\n";
x.clear();
// Load the hashtable
fp = fopen(file, "rb");
if ( fp == NULL ) {
LOGF << "Can't open " << file << " skipping hashtable reload...\n";
} else {
x.read_metadata(fp); // reads metainformation
LOGF << "Hashtable size: " << x.size() << "\n";
int count = 0;
for ( typename ht::iterator it = x.begin(); it != x.end(); ++it ) {
read_item(fp, &(*it));
++count;
}
LOGF << "Read " << count << " words from " << file << "\n";
fclose(fp);
unlink(file);
for ( const char* const* word = words;
word < words + sizeof(words) / sizeof(*words);
++word ) {
if (x.find(*word) == x.end()) {
CHECK(w.find(*word) != w.end());
} else {
CHECK(w.find(*word) == w.end());
}
}
}
}
}
// ensure that destruction is done properly in clear_no_resize()
if (!clear_no_resize(&w)) w.clear();
}
// The read_write parameters specifies whether the read/write tests
// should be performed. Note that densehashtable::write_metdata is not
// implemented, so we only do the read/write tests for the
// sparsehashtable varieties.
template<class ht, class htstr, class htint>
void test(bool read_write) {
test_int<htint>();
test_string<htstr>(read_write);
test_charptr<ht>(read_write);
}
// For data types with trivial copy-constructors and destructors, we
// should use an optimized routine for data-copying, that involves
// memmove. We test this by keeping count of how many times the
// copy-constructor is called; it should be much less with the
// optimized code.
class Memmove {
public:
Memmove(): i_(0) {}
explicit Memmove(int i): i_(i) {}
Memmove(const Memmove& that) {
this->i_ = that.i_;
num_copies_++;
}
int i_;
static int num_copies_;
};
int Memmove::num_copies_ = 0;
// This is what tells the hashtable code it can use memmove for this class:
_START_GOOGLE_NAMESPACE_
template<> struct has_trivial_copy<Memmove> : true_type { };
template<> struct has_trivial_destructor<Memmove> : true_type { };
_END_GOOGLE_NAMESPACE_
class NoMemmove {
public:
NoMemmove(): i_(0) {}
explicit NoMemmove(int i): i_(i) {}
NoMemmove(const NoMemmove& that) {
this->i_ = that.i_;
num_copies_++;
}
int i_;
static int num_copies_;
};
int NoMemmove::num_copies_ = 0;
void TestSimpleDataTypeOptimizations() {
{
sparse_hash_map<int, Memmove> memmove;
sparse_hash_map<int, NoMemmove> nomemmove;
Memmove::num_copies_ = 0; // reset
NoMemmove::num_copies_ = 0; // reset
for (int i = 10000; i > 0; i--) {
memmove[i] = Memmove(i);
}
for (int i = 10000; i > 0; i--) {
nomemmove[i] = NoMemmove(i);
}
LOGF << "sparse_hash_map copies for unoptimized/optimized cases: "
<< NoMemmove::num_copies_ << "/" << Memmove::num_copies_ << "\n";
CHECK(NoMemmove::num_copies_ > Memmove::num_copies_);
}
// dense_hash_map doesn't use this optimization, so no need to test it.
}
void TestShrinking() {
// We want to make sure that when we create a hashtable, and then
// add and delete one element, the size of the hashtable doesn't
// change.
{
sparse_hash_set<int> s;
s.set_deleted_key(0);
const int old_bucket_count = s.bucket_count();
s.insert(4);
s.erase(4);
s.insert(4);
s.erase(4);
CHECK_EQ(old_bucket_count, s.bucket_count());
}
{
dense_hash_set<int> s;
s.set_deleted_key(0);
s.set_empty_key(1);
const int old_bucket_count = s.bucket_count();
s.insert(4);
s.erase(4);
s.insert(4);
s.erase(4);
CHECK_EQ(old_bucket_count, s.bucket_count());
}
{
sparse_hash_set<int> s(2); // start small: only expects 2 items
CHECK_LT(s.bucket_count(), 32); // verify we actually do start small
s.set_deleted_key(0);
const int old_bucket_count = s.bucket_count();
s.insert(4);
s.erase(4);
s.insert(4);
s.erase(4);
CHECK_EQ(old_bucket_count, s.bucket_count());
}
{
dense_hash_set<int> s(2); // start small: only expects 2 items
CHECK_LT(s.bucket_count(), 32); // verify we actually do start small
s.set_deleted_key(0);
s.set_empty_key(1);
const int old_bucket_count = s.bucket_count();
s.insert(4);
s.erase(4);
s.insert(4);
s.erase(4);
CHECK_EQ(old_bucket_count, s.bucket_count());
}
}
class TestHashFcn : public SPARSEHASH_HASH<int> {
public:
explicit TestHashFcn(int i)
: id_(i) {
}
int id() const {
return id_;
}
private:
int id_;
};
class TestEqualTo : public equal_to<int> {
public:
explicit TestEqualTo(int i)
: id_(i) {
}
int id() const {
return id_;
}
private:
int id_;
};
// Test combining Hash and EqualTo function into 1 object
struct HashWithEqual {
int key_inc;
HashWithEqual() : key_inc(17) {}
explicit HashWithEqual(int i) : key_inc(i) {}
size_t operator()(const int& a) const { return a + key_inc; }
bool operator()(const int& a, const int& b) const { return a == b; }
};
// Here, NonHT is the non-hash version of HT: "map" to HT's "hash_map"
template<class HT, class NonHT>
void TestSparseConstructors() {
const TestHashFcn fcn(1);
const TestEqualTo eqt(2);
int alloc_count = 0;
const Alloc<int, int, 10000> alloc(&alloc_count);
{
const HT simple(0, fcn, eqt, alloc);
CHECK_EQ(fcn.id(), simple.hash_funct().id());
CHECK_EQ(eqt.id(), simple.key_eq().id());
CHECK(simple.get_allocator().is_custom_alloc());
}
{
const NonHT input;
const HT iterated(input.begin(), input.end(), 0, fcn, eqt, alloc);
CHECK_EQ(fcn.id(), iterated.hash_funct().id());
CHECK_EQ(eqt.id(), iterated.key_eq().id());
CHECK(iterated.get_allocator().is_custom_alloc());
}
// Now test each of the constructor types.
HT ht(0, fcn, eqt, alloc);
for (int i = 0; i < 1000; i++) {
insert(&ht, i * i);
}
CHECK_GT(alloc_count, 0);
alloc_count = 0;
HT ht_copy(ht);
CHECK(ht == ht_copy);
CHECK_GT(alloc_count, 0);
alloc_count = 0;
HT ht_equal(0, fcn, eqt, alloc);
ht_equal = ht;
CHECK(ht == ht_copy);
CHECK_GT(alloc_count, 0);
alloc_count = 0;
HT ht_iterator(ht.begin(), ht.end(), 0, fcn, eqt, alloc);
CHECK(ht == ht_iterator);
CHECK_GT(alloc_count, 0);
alloc_count = 0;
HT ht_size(ht.size(), fcn, eqt, alloc);
for (typename HT::const_iterator it = ht.begin(); it != ht.end(); ++it)
ht_size.insert(*it);
CHECK(ht == ht_size);
CHECK_GT(alloc_count, 0);
alloc_count = 0;
}
// Sadly, we need a separate version of this test because the iterator
// constructors require an extra arg in densehash-land.
template<class HT, class NonHT>
void TestDenseConstructors() {
const TestHashFcn fcn(1);
const TestEqualTo eqt(2);
int alloc_count;
const Alloc<int, int, 10000> alloc(&alloc_count);
{
const HT simple(0, fcn, eqt, alloc);
CHECK_EQ(fcn.id(), simple.hash_funct().id());
CHECK_EQ(eqt.id(), simple.key_eq().id());
CHECK(simple.get_allocator().is_custom_alloc());
}
{
const NonHT input;
const HT iterated(input.begin(), input.end(), -1, 0, fcn, eqt, alloc);
CHECK_EQ(fcn.id(), iterated.hash_funct().id());
CHECK_EQ(eqt.id(), iterated.key_eq().id());
CHECK(iterated.get_allocator().is_custom_alloc());
}
// Now test each of the constructor types.
HT ht(0, fcn, eqt, alloc);
ht.set_empty_key(-1);
for (int i = 0; i < 1000; i++) {
insert(&ht, i * i);
}
CHECK_GT(alloc_count, 0);
alloc_count = 0;
HT ht_copy(ht);
CHECK(ht == ht_copy);
CHECK_GT(alloc_count, 0);
alloc_count = 0;
HT ht_equal(0, fcn, eqt, alloc);
ht_equal = ht;
CHECK(ht == ht_copy);
CHECK_GT(alloc_count, 0);
alloc_count = 0;
HT ht_iterator(ht.begin(), ht.end(), ht.empty_key(), 0, fcn, eqt, alloc);
CHECK(ht == ht_iterator);
CHECK_GT(alloc_count, 0);
alloc_count = 0;
HT ht_size(ht.size(), fcn, eqt, alloc);
ht_size.set_empty_key(ht.empty_key());
for (typename HT::const_iterator it = ht.begin(); it != ht.end(); ++it)
ht_size.insert(*it);
CHECK(ht == ht_size);
CHECK_GT(alloc_count, 0);
alloc_count = 0;
}
static void TestCopyConstructor() {
{ // Copy an empty table with no empty key set.
dense_hash_map<int, string> table1;
dense_hash_map<int, string> table2(table1);
CHECK_EQ(32, table2.bucket_count()); // default number of buckets.
}
}
static void TestOperatorEquals() {
{
dense_hash_set<int> sa, sb;
sa.set_empty_key(-1);
sb.set_empty_key(-1);
CHECK(sa.empty_key() == -1);
sa.set_deleted_key(-2);
sb.set_deleted_key(-2);
CHECK(sa == sb);
sa.insert(1);
CHECK(sa != sb);
sa.insert(2);
CHECK(sa != sb);
sb.insert(2);
CHECK(sa != sb);
sb.insert(1);
CHECK(sa == sb);
sb.erase(1);
CHECK(sa != sb);
}
{
dense_hash_map<int, string> sa, sb;
sa.set_empty_key(-1);
sb.set_empty_key(-1);
CHECK(sa.empty_key() == -1);
sa.set_deleted_key(-2);
sb.set_deleted_key(-2);
CHECK(sa == sb);
sa.insert(make_pair(1, "a"));
CHECK(sa != sb);
sa.insert(make_pair(2, "b"));
CHECK(sa != sb);
sb.insert(make_pair(2, "b"));
CHECK(sa != sb);
sb.insert(make_pair(1, "a"));
CHECK(sa == sb);
sa[1] = "goodbye";
CHECK(sa != sb);
sb.erase(1);
CHECK(sa != sb);
}
{ // Copy table with a different empty key.
dense_hash_map<string, string, StrHash> table1;
table1.set_empty_key("key1");
CHECK(table1.empty_key() == "key1");
dense_hash_map<string, string, StrHash> table2;
table2.set_empty_key("key2");
table1.insert(make_pair("key", "value"));
table2.insert(make_pair("a", "b"));
table1 = table2;
CHECK_EQ("b", table1["a"]);
CHECK_EQ(1, table1.size());
}
{ // Assign to a map without an empty key.
dense_hash_map<string, string, StrHash> table1;
dense_hash_map<string, string, StrHash> table2;
table2.set_empty_key("key2");
CHECK(table2.empty_key() == "key2");
table2.insert(make_pair("key", "value"));
table1 = table2;
CHECK_EQ("value", table1["key"]);
}
{ // Copy a map without an empty key.
dense_hash_map<string, string, StrHash> table1;
dense_hash_map<string, string, StrHash> table2;
table1 = table2;
CHECK_EQ(0, table1.size());
table1.set_empty_key("key1");
CHECK(table1.empty_key() == "key1");
table1.insert(make_pair("key", "value"));
table1 = table2;
CHECK_EQ(0, table1.size());
table1.set_empty_key("key1");
table1.insert(make_pair("key", "value"));
CHECK_EQ("value", table1["key"]);
}
{
sparse_hash_map<string, string, StrHash> table1;
table1.set_deleted_key("key1");
table1.insert(make_pair("key", "value"));
sparse_hash_map<string, string, StrHash> table2;
table2.set_deleted_key("key");
table2 = table1;
CHECK_EQ(1, table2.size());
table2.erase("key");
CHECK(table2.empty());
}
}
// Test the interface for setting the resize parameters in a
// sparse_hash_set or dense_hash_set. If use_tr1_api is true,
// we use the newer tr1-inspired functions to set resize_parameters,
// rather than my old, home-grown API
template<class HS, bool USE_TR1_API>
static void TestResizingParameters() {
const int kSize = 16536;
// Check growing past various thresholds and then shrinking below
// them.
for (float grow_threshold = 0.2f;
grow_threshold <= 0.8f;
grow_threshold += 0.2f) {
HS hs;
hs.set_deleted_key(-1);
set_empty_key(&hs, -2);
if (USE_TR1_API) {
hs.max_load_factor(grow_threshold);
hs.min_load_factor(0.0);
} else {
hs.set_resizing_parameters(0.0, grow_threshold);
}
hs.resize(kSize);
size_t bucket_count = hs.bucket_count();
// Erase and insert an element to set consider_shrink = true,
// which should not cause a shrink because the threshold is 0.0.
insert(&hs, 1);
hs.erase(1);
for (int i = 0;; ++i) {
insert(&hs, i);
if (static_cast<float>(hs.size())/bucket_count < grow_threshold) {
CHECK(hs.bucket_count() == bucket_count);
} else {
CHECK(hs.bucket_count() > bucket_count);
break;
}
}
// Now set a shrink threshold 1% below the current size and remove
// items until the size falls below that.
const float shrink_threshold = static_cast<float>(hs.size()) /
hs.bucket_count() - 0.01f;
if (USE_TR1_API) {
hs.max_load_factor(1.0);
hs.min_load_factor(shrink_threshold);
} else {
hs.set_resizing_parameters(shrink_threshold, 1.0);
}
bucket_count = hs.bucket_count();
for (int i = 0;; ++i) {
hs.erase(i);
// A resize is only triggered by an insert, so add and remove a
// value every iteration to trigger the shrink as soon as the
// threshold is passed.
hs.erase(i+1);
insert(&hs, i+1);
if (static_cast<float>(hs.size())/bucket_count > shrink_threshold) {
CHECK(hs.bucket_count() == bucket_count);
} else {
CHECK(hs.bucket_count() < bucket_count);
break;
}
}
}
}
// This tests for a problem we had where we could repeatedly "resize"
// a hashtable to the same size it was before, on every insert.
template<class HT>
static void TestHashtableResizing() {
HT ht;
ht.set_deleted_key(-1);
set_empty_key(&ht, -2);
const int kSize = 1<<10; // Pick any power of 2
const float kResize = 0.8f; // anything between 0.5 and 1 is fine.
const int kThreshold = static_cast<int>(kSize * kResize - 1);
ht.set_resizing_parameters(0, kResize);
// Get right up to the resizing threshold.
for (int i = 0; i <= kThreshold; i++) {
ht.insert(i);
}
// The bucket count should equal kSize.
CHECK_EQ(ht.bucket_count(), kSize);
// Now start doing erase+insert pairs. This should cause us to
// copy the hashtable at most once.
const int pre_copies = ht.num_table_copies();
for (int i = 0; i < kSize; i++) {
if (i % 100 == 0)
LOGF << "erase/insert: " << i
<< " buckets: " << ht.bucket_count()
<< " size: " << ht.size() << "\n";
ht.erase(kThreshold);
ht.insert(kThreshold);
}
CHECK_LT(ht.num_table_copies(), pre_copies + 2);
// Now create a hashtable where we go right to the threshold, then
// delete everything and do one insert. Even though our hashtable
// is now tiny, we should still have at least kSize buckets, because
// our shrink threshhold is 0.
HT ht2;
ht2.set_deleted_key(-1);
set_empty_key(&ht2, -2);
ht2.set_resizing_parameters(0, kResize);
CHECK_LT(ht2.bucket_count(), kSize);
for (int i = 0; i <= kThreshold; i++) {
ht2.insert(i);
}
CHECK_EQ(ht2.bucket_count(), kSize);
for (int i = 0; i <= kThreshold; i++) {
ht2.erase(i);
CHECK_EQ(ht2.bucket_count(), kSize);
}
ht2.insert(kThreshold+1);
CHECK_GE(ht2.bucket_count(), kSize);
}
// Tests the some of the tr1-inspired API features.
template<class HS>
static void TestTR1API() {
HS hs;
hs.set_deleted_key(-1);
set_empty_key(&hs, -2);
typename HS::size_type expected_bucknum = hs.bucket(1);
insert(&hs, 1);
typename HS::size_type bucknum = hs.bucket(1);
CHECK(expected_bucknum == bucknum);
typename HS::const_local_iterator b = hs.begin(bucknum);
typename HS::const_local_iterator e = hs.end(bucknum);
CHECK(b != e);
CHECK(getintkey(*b) == 1);
b++;
CHECK(b == e);
hs.erase(1);
bucknum = hs.bucket(1);
CHECK(expected_bucknum == bucknum);
b = hs.begin(bucknum);
e = hs.end(bucknum);
CHECK(b == e);
// For very small sets, the min-bucket-size gets in the way, so
// let's make our hash_set bigger.
for (int i = 0; i < 10000; i++)
insert(&hs, i);
float f = hs.load_factor();
CHECK(f >= hs.min_load_factor());
CHECK(f <= hs.max_load_factor());
}
// People can do better than to have a hash_map of hash_maps, but we
// should still support it. HT should map from string to another
// hashtable (map or set) or some kind. Mostly we're just checking
// for memory leaks or crashes here.
template<class HT>
static void TestNestedHashtable() {
HT ht;
set_empty_key(&ht, string());
ht["hi"]; // creates a sub-ht with default values
ht["lo"]; // creates a sub-ht with default values
HT ht2 = ht;
}
class MemUsingKey {
public:
// TODO(csilvers): nix this when requirement for zero-arg keys goes away
MemUsingKey() : data_(new int) {
net_allocations_++;
}
MemUsingKey(int i) : data_(new int(i)) {
net_allocations_++;
}
MemUsingKey(const MemUsingKey& that) : data_(new int(*that.data_)) {
net_allocations_++;
}
~MemUsingKey() {
delete data_;
net_allocations_--;
CHECK_GE(net_allocations_, 0);
}
MemUsingKey& operator=(const MemUsingKey& that) {
delete data_;
data_ = new int(*that.data_);
return *this;
}
struct Hash {
size_t operator()(const MemUsingKey& x) const { return *x.data_; }
};
struct Equal {
bool operator()(const MemUsingKey& x, const MemUsingKey& y) const {
return *x.data_ == *y.data_;
}
};
static int net_allocations() { return net_allocations_; }
private:
int* data_;
static int net_allocations_;
};
class MemUsingValue {
public:
// This also tests that value does not need to have a zero-arg constructor
explicit MemUsingValue(const char* data) : data_(NULL) {
Strcpy(data);
}
MemUsingValue(const MemUsingValue& that) : data_(NULL) {
Strcpy(that.data_);
}
~MemUsingValue() {
if (data_) {
free(data_);
net_allocations_--;
CHECK_GE(net_allocations_, 0);
}
}
MemUsingValue& operator=(const MemUsingValue& that) {
if (data_) {
free(data_);
net_allocations_--;
CHECK_GE(net_allocations_, 0);
}
Strcpy(that.data_);
return *this;
}
static int net_allocations() { return net_allocations_; }
private:
void Strcpy(const char* data) {
if (data) {
data_ = (char*)malloc(strlen(data) + 1); // use malloc this time
strcpy(data_, data); // strdup isn't so portable
net_allocations_++;
} else {
data_ = NULL;
}
}
char* data_;
static int net_allocations_;
};
// TODO(csilvers): nix this when set_empty_key doesn't require zero-arg value
class MemUsingValueWithZeroArgConstructor : public MemUsingValue {
public:
MemUsingValueWithZeroArgConstructor(const char* data=NULL)
: MemUsingValue(data) { }
MemUsingValueWithZeroArgConstructor(
const MemUsingValueWithZeroArgConstructor& that)
: MemUsingValue(that) { }
MemUsingValueWithZeroArgConstructor& operator=(
const MemUsingValueWithZeroArgConstructor& that) {
*static_cast<MemUsingValue*>(this)
= *static_cast<const MemUsingValue*>(&that);
return *this;
}
};
int MemUsingKey::net_allocations_ = 0;
int MemUsingValue::net_allocations_ = 0;
void TestMemoryManagement() {
MemUsingKey deleted_key(-1);
MemUsingKey empty_key(-2);
{
// TODO(csilvers): fix sparsetable to allow missing zero-arg value ctor
sparse_hash_map<MemUsingKey, MemUsingValueWithZeroArgConstructor,
MemUsingKey::Hash, MemUsingKey::Equal> ht;
ht.set_deleted_key(deleted_key);
for (int i = 0; i < 1000; i++) {
ht.insert(pair<MemUsingKey,MemUsingValueWithZeroArgConstructor>(
i, MemUsingValueWithZeroArgConstructor("hello!")));
ht.erase(i);
CHECK_EQ(0, MemUsingValue::net_allocations());
}
}
// Various copies of deleted_key will be hanging around until the
// hashtable is destroyed, so it's only safe to do this test now.
CHECK_EQ(2, MemUsingKey::net_allocations()); // for deleted+empty_key
{
dense_hash_map<MemUsingKey, MemUsingValueWithZeroArgConstructor,
MemUsingKey::Hash, MemUsingKey::Equal> ht;
ht.set_empty_key(empty_key);
ht.set_deleted_key(deleted_key);
for (int i = 0; i < 1000; i++) {
// As long as we have a zero-arg constructor for the value anyway,
// use operator[] rather than the more verbose insert().
ht[i] = MemUsingValueWithZeroArgConstructor("hello!");
ht.erase(i);
CHECK_EQ(0, MemUsingValue::net_allocations());
}
}
CHECK_EQ(2, MemUsingKey::net_allocations()); // for deleted+empty_key
}
void TestHugeResize() {
try {
dense_hash_map<int, int> ht;
ht.resize(static_cast<size_t>(-1));
LOGF << "dense_hash_map resize should have failed\n";
abort();
} catch (const std::length_error&) {
// Good, the resize failed.
}
try {
sparse_hash_map<int, int> ht;
ht.resize(static_cast<size_t>(-1));
LOGF << "sparse_hash_map resize should have failed\n";
abort();
} catch (const std::length_error&) {
// Good, the resize failed.
}
static const int kMax = 256;
vector<int> test_data(kMax);
for (int i = 0; i < kMax; ++i) {
test_data[i] = i+1000;
}
sparse_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>, Alloc<int, uint8, 10> > shs;
dense_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>, Alloc<int, uint8, 10> > dhs;
dhs.set_empty_key(-1);
// Test we are using the correct allocator
CHECK(shs.get_allocator().is_custom_alloc());
CHECK(dhs.get_allocator().is_custom_alloc());
// Test size_type overflow in insert(it, it)
try {
dhs.insert(test_data.begin(), test_data.end());
LOGF << "dense_hash_map insert(it,it) should have failed\n";
abort();
} catch (const std::length_error&) {
}
try {
shs.insert(test_data.begin(), test_data.end());
LOGF << "sparse_hash_map insert(it,it) should have failed\n";
abort();
} catch (const std::length_error&) {
}
// Test max_size overflow
try {
dhs.insert(test_data.begin(), test_data.begin() + 11);
LOGF << "dense_hash_map max_size check should have failed\n";
abort();
} catch (const std::length_error&) {
}
try {
shs.insert(test_data.begin(), test_data.begin() + 11);
LOGF << "sparse_hash_map max_size check should have failed\n";
abort();
} catch (const std::length_error&) {
}
// Test min-buckets overflow, when we want to resize too close to size_type
try {
dhs.resize(250);
} catch (const std::length_error&) {
}
try {
shs.resize(250);
} catch (const std::length_error&) {
}
// Test size_type overflow in resize_delta()
sparse_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>, Alloc<int, uint8, 1000> > shs2;
dense_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>, Alloc<int, uint8, 1000> > dhs2;
dhs2.set_empty_key(-1);
for (int i = 0; i < 9; i++) {
dhs2.insert(i);
shs2.insert(i);
}
try {
dhs2.insert(test_data.begin(), test_data.begin() + 250);
LOGF << "dense_hash_map insert-check should have failed (9+250 > 256)\n";
abort();
} catch (const std::length_error&) {
}
try {
shs2.insert(test_data.begin(), test_data.begin() + 250);
LOGF << "sparse_hash_map insert-check should have failed (9+250 > 256)\n";
abort();
} catch (const std::length_error&) {
}
}
class DataCounter {
public:
DataCounter() {
++ctors_;
}
static int ctors() { int r = ctors_; ctors_ = 0; return r; }
private:
static int ctors_;
};
int DataCounter::ctors_ = 0;
class HashCounter {
public:
size_t operator()(int x) const {
++hashes_;
return x;
}
static int hashes() { int r = hashes_; hashes_ = 0; return r; }
private:
static int hashes_;
};
int HashCounter::hashes_ = 0;
template<class HT>
void TestHashCounts() {
HT ht;
set_empty_key(&ht, -1);
const int kIter = 2000; // enough for some resizing to happen
ht.clear();
for (int i = 0; i < kIter; i++)
insert(&ht, i);
const int insert_hashes = HashCounter::hashes();
int actual_ctors = DataCounter::ctors();
// dense_hash_* has an extra ctor during resizes, for emptykey,
// so allow for a log_2(kIter) slack, which we estimate as .01*kIter.
if (actual_ctors != 0) // will be 0 for hash_sets, >0 for maps.
CHECK_LT(kIter, actual_ctors + kIter/100);
// Make sure that do-nothing inserts don't result in extra hashes or
// ctors. insert() itself (in this test file) does one ctor call;
// that should be all we see.
for (int i = 0; i < kIter; i++)
insert(&ht, i);
CHECK_EQ(kIter, HashCounter::hashes());
actual_ctors = DataCounter::ctors();
if (actual_ctors != 0) // will be 0 for hash_sets, >0 for maps.
CHECK_EQ(kIter, actual_ctors); // no resizing is happening here.
// Make sure we never do any extraneous hashes in find() calls.
for (int i = 0; i < kIter; i++)
(void)ht.find(i);
CHECK_EQ(kIter, HashCounter::hashes());
CHECK_EQ(0, DataCounter::ctors());
// Make sure that whether we use insert() or operator[], we hash the
// same. Actually that's not quite true: we do an extra hash per
// hashtable-resize with operator[] (we could avoid this, but I
// don't think it's worth the work), so allow for a log_2(kIter)
// slack, which we estimate as .01*kIter.
HT ht2;
set_empty_key(&ht2, -1);
for (int i = 0; i < kIter; i++)
bracket_insert(&ht2, i);
CHECK_LT(HashCounter::hashes(), insert_hashes + kIter/100);
actual_ctors = DataCounter::ctors();
// We expect two ctor calls per insert, one by operator[] when it
// creates a new object that wasn't in the hashtable before, and one
// by bracket_insert() itself.
if (actual_ctors != 0) // will be 0 for hash_sets, >0 for maps.
CHECK_LT(kIter*2, actual_ctors + kIter/100);
// Like insert(), bracket_insert() itself does one ctor call. But
// the hashtable implementation shouldn't do any, since these
// objects already exist.
for (int i = 0; i < kIter; i++)
bracket_insert(&ht, i);
CHECK_EQ(kIter, HashCounter::hashes());
actual_ctors = DataCounter::ctors();
if (actual_ctors != 0) // will be 0 for hash_sets, >0 for maps.
CHECK_EQ(kIter, actual_ctors);
}
template<class Key>
struct SetKey {
void operator()(Key* key, const Key& new_key) const {
*key = new_key;
}
};
template<class Value>
struct Identity {
Value& operator()(Value& v) const { return v; }
const Value& operator()(const Value& v) const { return v; }
};
int main(int argc, char **argv) {
typedef sparse_hash_set<int, SPARSEHASH_HASH<int>,equal_to<int>, Alloc<int,int,8> > Shs;
typedef dense_hash_set<int, SPARSEHASH_HASH<int>,equal_to<int>, Alloc<int,int,8> > Dhs;
Shs shs;
Dhs dhs;
LOGF << "<sizeof, max_size>: sparse_hash_set<int>=(" << sizeof(Shs)
<< "," << static_cast<size_t>(shs.max_size())
<< "); dense_hash_set<int>=(" << sizeof(Dhs)
<< "," << static_cast<size_t>(dhs.max_size()) << ")";
TestCopyConstructor();
TestOperatorEquals();
// SPARSEHASH_HASH is defined in sparseconfig.h. It resolves to the
// system hash function (usually, but not always, named "hash") on
// whatever system we're on.
// First try with the low-level hashtable interface
LOGF << "\n\nTEST WITH DENSE_HASHTABLE\n\n";
test<dense_hashtable<char *, char *, CharStarHash,
Identity<char *>, SetKey<char *>, strcmp_fnc,
libc_allocator_with_realloc<char *> >,
dense_hashtable<string, string, StrHash,
Identity<string>, SetKey<string>, equal_to<string>,
libc_allocator_with_realloc<string> >,
dense_hashtable<int, int, SPARSEHASH_HASH<int>,
Identity<int>, SetKey<int>, equal_to<int>,
libc_allocator_with_realloc<int> > >(false);
test<dense_hashtable<char *, char *, CharStarHash,
Identity<char *>, SetKey<char *>, strcmp_fnc,
allocator<char *> >,
dense_hashtable<string, string, StrHash,
Identity<string>, SetKey<string>, equal_to<string>,
allocator<string> >,
dense_hashtable<int, int, SPARSEHASH_HASH<int>,
Identity<int>, SetKey<int>, equal_to<int>,
allocator<int> > >(
false);
// Now try with hash_set, which should be equivalent
LOGF << "\n\nTEST WITH DENSE_HASH_SET\n\n";
test<dense_hash_set<char *, CharStarHash, strcmp_fnc>,
dense_hash_set<string, StrHash>,
dense_hash_set<int> >(false);
test<dense_hash_set<char *, CharStarHash, strcmp_fnc, allocator<char *> >,
dense_hash_set<string, StrHash, equal_to<string>, allocator<string> >,
dense_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>, allocator<int> > >(false);
TestResizingParameters<dense_hash_set<int>, true>(); // use tr1 API
TestResizingParameters<dense_hash_set<int>, false>(); // use older API
TestResizingParameters<dense_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>,
allocator<int> >, true>(); // use tr1 API
TestResizingParameters<dense_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>,
allocator<int> >, false>(); // use older API
TestHashtableResizing<dense_hashtable<int, int, SPARSEHASH_HASH<int>,
Identity<int>, SetKey<int>, equal_to<int>,
libc_allocator_with_realloc<int> > >();
TestHashtableResizing<sparse_hashtable<int, int, SPARSEHASH_HASH<int>,
Identity<int>, SetKey<int>, equal_to<int>,
allocator<int> > >();
// Now try with hash_map, which differs only in insert()
LOGF << "\n\nTEST WITH DENSE_HASH_MAP\n\n";
test<dense_hash_map<char *, int, CharStarHash, strcmp_fnc>,
dense_hash_map<string, int, StrHash>,
dense_hash_map<int, int> >(false);
test<dense_hash_map<char *, int, CharStarHash, strcmp_fnc,
allocator<char *> >,
dense_hash_map<string, int, StrHash, equal_to<string>,
allocator<string> >,
dense_hash_map<int, int, SPARSEHASH_HASH<int>, equal_to<int>,
allocator<int> > >(false);
// First try with the low-level hashtable interface
LOGF << "\n\nTEST WITH SPARSE_HASHTABLE\n\n";
test<sparse_hashtable<char *, char *, CharStarHash,
Identity<char *>, SetKey<char *>, strcmp_fnc,
libc_allocator_with_realloc<char *> >,
sparse_hashtable<string, string, StrHash,
Identity<string>, SetKey<string>, equal_to<string>,
libc_allocator_with_realloc<string> >,
sparse_hashtable<int, int, SPARSEHASH_HASH<int>,
Identity<int>, SetKey<int>, equal_to<int>,
libc_allocator_with_realloc<int> > >(true);
test<sparse_hashtable<char *, char *, CharStarHash,
Identity<char *>, SetKey<char *>, strcmp_fnc,
allocator<char *> >,
sparse_hashtable<string, string, StrHash,
Identity<string>, SetKey<string>, equal_to<string>,
allocator<string> >,
sparse_hashtable<int, int, SPARSEHASH_HASH<int>,
Identity<int>, SetKey<int>, equal_to<int>,
allocator<int> > >(true);
// Now try with hash_set, which should be equivalent
LOGF << "\n\nTEST WITH SPARSE_HASH_SET\n\n";
test<sparse_hash_set<char *, CharStarHash, strcmp_fnc>,
sparse_hash_set<string, StrHash>,
sparse_hash_set<int> >(true);
test<sparse_hash_set<char *, CharStarHash, strcmp_fnc, allocator<int> >,
sparse_hash_set<string, StrHash, equal_to<string>, allocator<int> >,
sparse_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>, allocator<int> > >(true);
TestResizingParameters<sparse_hash_set<int>, true>();
TestResizingParameters<sparse_hash_set<int>, false>();
TestResizingParameters<sparse_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>,
allocator<int> >, true>();
TestResizingParameters<sparse_hash_set<int, SPARSEHASH_HASH<int>, equal_to<int>,
allocator<int> >, false>();
// Now try with hash_map, which differs only in insert()
LOGF << "\n\nTEST WITH SPARSE_HASH_MAP\n\n";
test<sparse_hash_map<char *, int, CharStarHash, strcmp_fnc>,
sparse_hash_map<string, int, StrHash>,
sparse_hash_map<int, int> >(true);
test<sparse_hash_map<char *, int, CharStarHash, strcmp_fnc,
allocator<char *> >,
sparse_hash_map<string, int, StrHash, equal_to<string>,
allocator<string> >,
sparse_hash_map<int, int, SPARSEHASH_HASH<int>, equal_to<int>,
allocator<int> > >(true);
// Test that we use the optimized routines for simple data types
LOGF << "\n\nTesting simple-data-type optimizations\n";
TestSimpleDataTypeOptimizations();
// Test shrinking to very small sizes
LOGF << "\n\nTesting shrinking behavior\n";
TestShrinking();
LOGF << "\n\nTesting constructors, hashers, and key_equals\n";
TestSparseConstructors< sparse_hash_map<int, int, TestHashFcn, TestEqualTo,
Alloc<int,int,10000> >,
map<int, int> >();
TestSparseConstructors< sparse_hash_set<int, TestHashFcn, TestEqualTo,
Alloc<int,int,10000> >,
set<int, int> >();
TestDenseConstructors< dense_hash_map<int, int, TestHashFcn, TestEqualTo,
Alloc<int,int,10000> >,
map<int, int> >();
TestDenseConstructors< dense_hash_set<int, TestHashFcn, TestEqualTo,
Alloc<int,int,10000> >,
set<int, int> >();
LOGF << "\n\nTesting tr1 API\n";
TestTR1API<sparse_hash_map<int, int> >();
TestTR1API<dense_hash_map<int, int> >();
TestTR1API<sparse_hash_set<int> >();
TestTR1API<dense_hash_set<int> >();
TestTR1API<dense_hash_map<int, int, HashWithEqual, HashWithEqual> >();
TestTR1API<sparse_hash_map<int, int, HashWithEqual, HashWithEqual> >();
TestTR1API<dense_hash_set<int, HashWithEqual, HashWithEqual> >();
TestTR1API<sparse_hash_set<int, HashWithEqual, HashWithEqual> >();
LOGF << "\n\nTesting nested hashtables\n";
TestNestedHashtable<sparse_hash_map<string, sparse_hash_map<string, int> > >();
TestNestedHashtable<sparse_hash_map<string, sparse_hash_set<string> > >();
TestNestedHashtable<dense_hash_map<string, DenseStringMap<int> > >();
TestNestedHashtable<dense_hash_map<string, DenseStringSet> >();
// Test memory management when the keys and values are non-trivial
LOGF << "\n\nTesting memory management\n";
TestMemoryManagement();
TestHugeResize();
// Make sure we don't hash more than we need to
LOGF << "\n\nTesting hash counts\n";
TestHashCounts<sparse_hash_map<int, DataCounter, HashCounter> >();
TestHashCounts<sparse_hash_set<int, HashCounter> >();
TestHashCounts<dense_hash_map<int, DataCounter, HashCounter> >();
TestHashCounts<dense_hash_set<int, HashCounter> >();
LOGF << "\nAll tests pass.\n";
return 0;
}
| 32.710247 | 91 | 0.621939 |
1aeb56dbe4e30c69fbc1793cc1cc979b07f51758 | 3,955 | cpp | C++ | base/pbr/VulkanObjModel.cpp | wessles/vkmerc | cb087f425cdbc0b204298833474cf62874505388 | [
"Unlicense"
] | 6 | 2020-10-09T02:48:54.000Z | 2021-07-30T06:31:20.000Z | base/pbr/VulkanObjModel.cpp | wessles/vkmerc | cb087f425cdbc0b204298833474cf62874505388 | [
"Unlicense"
] | null | null | null | base/pbr/VulkanObjModel.cpp | wessles/vkmerc | cb087f425cdbc0b204298833474cf62874505388 | [
"Unlicense"
] | null | null | null | #include "VulkanObjModel.h"
#include <unordered_map>
#include <filesystem>
#include <iostream>
#include <glm/glm.hpp>
#include <glm/gtx/string_cast.hpp>
#define TINYOBJLOADER_IMPLEMENTATION
#include <tiny_obj_loader.h>
#include "../VulkanMesh.h"
#include "../scene/Scene.h"
#include "PbrMaterial.h"
static std::string GetBaseDir(const std::string& filepath) {
if (filepath.find_last_of("/\\") != std::string::npos)
return filepath.substr(0, filepath.find_last_of("/\\"));
return "";
}
namespace vku {
VulkanObjModel::VulkanObjModel(const std::string& filename, Scene* scene, Pass* pass, std::map<std::string, std::string> macros) {
VulkanMeshData meshData{};
std::string base_dir = GetBaseDir(filename);
if (base_dir.empty()) {
base_dir = ".";
}
#ifdef _WIN32
base_dir += "\\";
#else
base_dir += "/";
#endif
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string warn, err;
if (!tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, filename.c_str(), base_dir.c_str())) {
throw std::runtime_error(warn + err);
}
if (warn.size() + err.size() > 0) {
std::cout << "OBJ warning: " << (warn + err) << std::endl;
}
// load mesh data
std::unordered_map<Vertex, uint32_t> uniqueVertices{};
for (const auto& shape : shapes) {
for (const auto& index : shape.mesh.indices) {
Vertex vertex{};
vertex.pos = {
attrib.vertices[3 * index.vertex_index + 0],
attrib.vertices[3 * index.vertex_index + 1],
attrib.vertices[3 * index.vertex_index + 2]
};
// calculate bounding box
min.x = std::min(min.x, vertex.pos.x);
min.y = std::min(min.y, vertex.pos.y);
min.z = std::min(min.z, vertex.pos.z);
max.x = std::max(max.x, vertex.pos.x);
max.y = std::max(max.y, vertex.pos.y);
max.z = std::max(max.z, vertex.pos.z);
vertex.normal = {
attrib.normals[3 * index.normal_index + 0],
attrib.normals[3 * index.normal_index + 1],
attrib.normals[3 * index.normal_index + 2],
};
vertex.texCoord = {
attrib.texcoords[2 * index.texcoord_index + 0],
1.0f - attrib.texcoords[2 * index.texcoord_index + 1]
};
vertex.color = { 1.0f, 1.0f, 1.0f };
if (uniqueVertices.count(vertex) == 0) {
uniqueVertices[vertex] = static_cast<uint32_t>(meshData.vertices.size());
meshData.vertices.push_back(vertex);
}
meshData.indices.push_back(uniqueVertices[vertex]);
}
}
aabb = glm::translate(glm::mat4(1.0f), min) * glm::scale(glm::mat4(1.0f), max - min);
this->meshBuf = new VulkanMeshBuffer(scene->device, meshData);
// load material, based on default Blender BSDF .mtl export
if (materials.size() > 0) {
tinyobj::material_t mat = materials[0];
glm::vec4 albedo = glm::vec4(static_cast<float>(mat.diffuse[0]), static_cast<float>(mat.diffuse[1]), static_cast<float>(mat.diffuse[2]), 1.0f);
glm::vec4 emission = glm::vec4(static_cast<float>(mat.emission[0]), static_cast<float>(mat.emission[1]), static_cast<float>(mat.emission[2]), 1.0f);
float metallic = mat.specular[0];
float roughness = 1.0f - (static_cast<float>(mat.shininess) / 1000.0f);
PbrUniform uniform{};
uniform.albedo = albedo;
uniform.emissive = emission;
uniform.metallic = metallic;
uniform.roughness = roughness;
this->mat = new TexturelessPbrMaterial(uniform, scene, pass, macros);
}
}
VulkanObjModel::~VulkanObjModel() {
delete meshBuf;
delete mat;
}
void VulkanObjModel::render(VkCommandBuffer cmdBuf, uint32_t swapIdx, bool noMaterial) {
if (!noMaterial) {
mat->mat->bind(cmdBuf);
mat->matInstance->bind(cmdBuf, swapIdx);
}
vkCmdPushConstants(cmdBuf, mat->mat->pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(glm::mat4), &this->localTransform);
meshBuf->draw(cmdBuf);
}
glm::mat4 VulkanObjModel::getAABBTransform()
{
return localTransform * aabb;
}
} | 29.736842 | 159 | 0.668015 |
1aec5d14b869793dd0ebb8bd7d89960e250e6ada | 2,321 | cc | C++ | depends/dbcommon/test/unit/common/test-tuple-batch-store.cc | YangHao666666/hawq | 10cff8350f1ba806c6fec64eb67e0e6f6f24786c | [
"Artistic-1.0-Perl",
"ISC",
"bzip2-1.0.5",
"TCL",
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"PostgreSQL",
"BSD-3-Clause"
] | 1 | 2020-05-11T01:39:13.000Z | 2020-05-11T01:39:13.000Z | depends/dbcommon/test/unit/common/test-tuple-batch-store.cc | YangHao666666/hawq | 10cff8350f1ba806c6fec64eb67e0e6f6f24786c | [
"Artistic-1.0-Perl",
"ISC",
"bzip2-1.0.5",
"TCL",
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"PostgreSQL",
"BSD-3-Clause"
] | 1 | 2021-03-01T02:57:26.000Z | 2021-03-01T02:57:26.000Z | depends/dbcommon/test/unit/common/test-tuple-batch-store.cc | YangHao666666/hawq | 10cff8350f1ba806c6fec64eb67e0e6f6f24786c | [
"Artistic-1.0-Perl",
"ISC",
"bzip2-1.0.5",
"TCL",
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"PostgreSQL",
"BSD-3-Clause"
] | 1 | 2020-05-03T07:29:21.000Z | 2020-05-03T07:29:21.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "dbcommon/common/tuple-batch-store.h"
#include "dbcommon/testutil/tuple-batch-utils.h"
#include "dbcommon/utils/global.h"
#include "gtest/gtest.h"
namespace dbcommon {
TEST(TestTupleBatchStore, Test) {
auto filesystem(FSManager.get("file://localhost"));
TupleBatchUtility tbu;
auto desc = tbu.generateTupleDesc(
"schema: boolean int8 int16 int32 int64 float double "
"bpchar bpchar(10) varchar varchar(5) string binary timestamp "
"time date");
auto tb0 = tbu.generateTupleBatchRandom(*desc, 0, 20, true, false);
auto tb1 = tbu.generateTupleBatchRandom(*desc, 0, 233, true, true);
auto tb2 = tbu.generateTupleBatchRandom(*desc, 0, 666, false, true);
auto tb3 = tbu.generateTupleBatchRandom(*desc, 0, 555, false, false);
std::string filename = "/tmp/TestTupleBatchStore";
NTupleBatchStore tbs(filesystem, filename, NTupleBatchStore::Mode::OUTPUT);
tbs.PutIntoNTupleBatchStore(tb0->clone());
tbs.PutIntoNTupleBatchStore(tb1->clone());
tbs.PutIntoNTupleBatchStore(tb2->clone());
tbs.PutIntoNTupleBatchStore(tb3->clone());
tbs.writeEOF();
NTupleBatchStore tbsLoad(filesystem, filename, NTupleBatchStore::Mode::INPUT);
EXPECT_EQ(tb0->toString(), tbsLoad.GetFromNTupleBatchStore()->toString());
EXPECT_EQ(tb1->toString(), tbsLoad.GetFromNTupleBatchStore()->toString());
EXPECT_EQ(tb2->toString(), tbsLoad.GetFromNTupleBatchStore()->toString());
EXPECT_EQ(tb3->toString(), tbsLoad.GetFromNTupleBatchStore()->toString());
}
} // namespace dbcommon
| 41.446429 | 80 | 0.744076 |
8c1d6f83dd2669c716d71f751abe3b49418da6ad | 3,375 | cpp | C++ | vector.cpp | csiro-robotics/Morphogenesis | 4d390609f941a58f09529371d185a344573de35f | [
"BSD-3-Clause"
] | null | null | null | vector.cpp | csiro-robotics/Morphogenesis | 4d390609f941a58f09529371d185a344573de35f | [
"BSD-3-Clause"
] | null | null | null | vector.cpp | csiro-robotics/Morphogenesis | 4d390609f941a58f09529371d185a344573de35f | [
"BSD-3-Clause"
] | null | null | null |
#include "vector.h"
#include "matrix.h"
#define VTYPE float
Vector3DF &Vector3DF::operator*= (const MatrixF &op)
{
double *m = op.GetDataF ();
float xa, ya, za;
xa = x * float(*m++); ya = x * float(*m++); za = x * float(*m++); m++;
xa += y * float(*m++); ya += y * float(*m++); za += y * float(*m++); m++;
xa += z * float(*m++); ya += z * float(*m++); za += z * float(*m++); m++;
xa += float(*m++); ya += float(*m++); za += float(*m++);
x = xa; y = ya; z = za;
return *this;
}
// p' = Mp
Vector3DF &Vector3DF::operator*= (const Matrix4F &op)
{
float xa, ya, za;
xa = x * op.data[0] + y * op.data[4] + z * op.data[8] + op.data[12];
ya = x * op.data[1] + y * op.data[5] + z * op.data[9] + op.data[13];
za = x * op.data[2] + y * op.data[6] + z * op.data[10] + op.data[14];
x = xa; y = ya; z = za;
return *this;
}
Vector3DF& Vector3DF::Clamp (float a, float b)
{
x = (x<a) ? a : ((x>b) ? b : x);
y = (y<a) ? a : ((y>b) ? b : y);
z = (z<a) ? a : ((z>b) ? b : z);
return *this;
}
#define min3(a,b,c) ( (a<b) ? ((a<c) ? a : c) : ((b<c) ? b : c) )
#define max3(a,b,c) ( (a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c) )
Vector3DF Vector3DF::RGBtoHSV ()
{
float h,s,v;
float minv, maxv;
int i;
float f;
minv = min3(x, y, z);
maxv = max3(x, y, z);
if (minv==maxv) {
v = (float) maxv;
h = 0.0;
s = 0.0;
} else {
v = (float) maxv;
s = (maxv - minv) / maxv;
f = (x == minv) ? y - z : ((y == minv) ? z - x : x - y);
i = (x == minv) ? 3 : ((y == minv) ? 5 : 1);
h = (i - f / (maxv - minv) ) / 6.0f;
}
return Vector3DF(h,s,v);
}
Vector3DF Vector3DF::HSVtoRGB ()
{
double m, n, f;
int i = floor ( x*6.0 );
f = x*6.0 - i;
if ( i % 2 == 0 ) f = 1.0 - f;
m = z * (1.0 - y );
n = z * (1.0 - y * f );
switch ( i ) {
case 6:
case 0: return Vector3DF( z, n, m ); break;
case 1: return Vector3DF( n, z, m ); break;
case 2: return Vector3DF( m, z, n ); break;
case 3: return Vector3DF( m, n, z ); break;
case 4: return Vector3DF( n, m, z ); break;
case 5: return Vector3DF( z, m, n ); break;
};
return Vector3DF(1,1,1);
}
Vector4DF &Vector4DF::operator*= (const MatrixF &op)
{
double *m = op.GetDataF ();
VTYPE xa, ya, za, wa;
xa = x * float(*m++); ya = x * float(*m++); za = x * float(*m++); wa = x * float(*m++);
xa += y * float(*m++); ya += y * float(*m++); za += y * float(*m++); wa += y * float(*m++);
xa += z * float(*m++); ya += z * float(*m++); za += z * float(*m++); wa += z * float(*m++);
xa += w * float(*m++); ya += w * float(*m++); za += w * float(*m++); wa += w * float(*m++);
x = xa; y = ya; z = za; w = wa;
return *this;
}
Vector4DF &Vector4DF::operator*= (const Matrix4F &op)
{
float xa, ya, za, wa;
xa = x * op.data[0] + y * op.data[4] + z * op.data[8] + w * op.data[12];
ya = x * op.data[1] + y * op.data[5] + z * op.data[9] + w * op.data[13];
za = x * op.data[2] + y * op.data[6] + z * op.data[10] + w * op.data[14];
wa = x * op.data[3] + y * op.data[7] + z * op.data[11] + w * op.data[15];
x = xa; y = ya; z = za; w = wa;
return *this;
}
Vector4DF &Vector4DF::operator*= (const float* op)
{
float xa, ya, za, wa;
xa = x * op[0] + y * op[4] + z * op[8] + w * op[12];
ya = x * op[1] + y * op[5] + z * op[9] + w * op[13];
za = x * op[2] + y * op[6] + z * op[10] + w * op[14];
wa = x * op[3] + y * op[7] + z * op[11] + w * op[15];
x = xa; y = ya; z = za; w = wa;
return *this;
}
| 28.601695 | 92 | 0.47437 |
8c1dde0196518bd1550bee9b3f84249cf7060d1c | 198 | cpp | C++ | test_index_reference.cpp | insertinterestingnamehere/cython_overload_except | 00d76ad8020fcb21948545de8161da65f7f4acd8 | [
"BSD-2-Clause"
] | null | null | null | test_index_reference.cpp | insertinterestingnamehere/cython_overload_except | 00d76ad8020fcb21948545de8161da65f7f4acd8 | [
"BSD-2-Clause"
] | null | null | null | test_index_reference.cpp | insertinterestingnamehere/cython_overload_except | 00d76ad8020fcb21948545de8161da65f7f4acd8 | [
"BSD-2-Clause"
] | null | null | null | #include "add.cpp"
#include <iostream>
int main(){
wrapped_int a = 3;
long long b = 2;
std::cout << a[b].val << std::endl;
wrapped_int &temp = a[b];
std::cout << temp.val << std::endl;
}
| 18 | 37 | 0.580808 |
8c1e21fcc1bfc1f79fd2dad6a5aa8ff6dc21c3ff | 2,280 | cpp | C++ | app/main.cpp | shivamakhauri04/midterm_project | 4d062d90cb459d035fa9453aa837463b1e72f5a5 | [
"MIT"
] | null | null | null | app/main.cpp | shivamakhauri04/midterm_project | 4d062d90cb459d035fa9453aa837463b1e72f5a5 | [
"MIT"
] | 9 | 2019-10-19T06:55:30.000Z | 2019-10-21T15:08:33.000Z | app/main.cpp | shivamakhauri04/midterm_project | 4d062d90cb459d035fa9453aa837463b1e72f5a5 | [
"MIT"
] | 1 | 2019-10-19T02:12:38.000Z | 2019-10-19T02:12:38.000Z | /**
* @file main.cpp
* @author Shivam Akhauri (Driver),Toyas Dhake (Navigator),
* @date 20 October 2019
* @copyright 2019 Toyas Dhake, Shivam Akhauri
* @brief Main file for implementation of the Depth Perception project.
*/
#include <dlib/opencv.h>
#include <dlib/gui_widgets.h>
#include <dlib/image_processing/frontal_face_detector.h>
#include <iostream>
#include <distance.hpp>
#include <face.hpp>
#include <opencv2/highgui/highgui.hpp>
int main() {
// Constructor call for distance calculation
CalculateDistance calculateDistance;
// Initialise the video frame buffer of the camera
cv::VideoCapture cap(0);
// Check if the opencv was able to communicate with the camera
if (!cap.isOpened()) {
std::cout << "Unable to connect to camera" << std::endl;
return 1;
}
dlib::frontal_face_detector detector = dlib::get_frontal_face_detector();
// Assign a window named win to show the current frame
dlib::image_window win;
// Grab each frame and calculate distance till the window is closed
while (!win.is_closed()) {
// read each frame in the buffer one by one
cv::Mat temp;
// if not able to read a frame in the buffer, close the application
if (!cap.read(temp)) {
break;
}
std::vector<Face> faces = calculateDistance.getDistance(temp, detector);
// This is vector of faces with their distance
dlib::cv_image<dlib::bgr_pixel> cimg(temp);
// Display the frame all on the screen
win.clear_overlay();
win.set_image(cimg);
for (auto&& face : faces) {
// draw a bounding box around the face
dlib::rectangle rect(face.getX(), face.getY(), face.getW(),
face.getH());
// write the distance and the x,y coordinates
// of the detected face below the bounding box
win.add_overlay(dlib::image_window::overlay_rect(rect,
dlib::rgb_pixel(0, 255, 0),
std::to_string(face.getX()) + ", " +
std::to_string(face.getY()) + ", " +
std::to_string(face.getDistance())+" m"));
}
}
return 0;
}
| 38.644068 | 80 | 0.601316 |
8c20e2958890ef25c6c2b2117176bf264b857fb7 | 5,608 | cpp | C++ | applications/SavageHutter/SlopeLimiters/TvbLimiter1D.cpp | hpgem/hpgem | b2f7ac6bdef3262af0c3e8559cb991357a96457f | [
"BSD-3-Clause-Clear"
] | 5 | 2020-04-01T15:35:26.000Z | 2022-02-22T02:48:12.000Z | applications/SavageHutter/SlopeLimiters/TvbLimiter1D.cpp | hpgem/hpgem | b2f7ac6bdef3262af0c3e8559cb991357a96457f | [
"BSD-3-Clause-Clear"
] | 139 | 2020-01-06T12:42:24.000Z | 2022-03-10T20:58:14.000Z | applications/SavageHutter/SlopeLimiters/TvbLimiter1D.cpp | hpgem/hpgem | b2f7ac6bdef3262af0c3e8559cb991357a96457f | [
"BSD-3-Clause-Clear"
] | 4 | 2020-04-10T09:19:33.000Z | 2021-08-21T07:20:42.000Z | /*
This file forms part of hpGEM. This package has been developed over a number of
years by various people at the University of Twente and a full list of
contributors can be found at http://hpgem.org/about-the-code/team
This code is distributed using BSD 3-Clause License. A copy of which can found
below.
Copyright (c) 2014, University of Twente
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the copyright holder 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.
*/
#include "TvbLimiter1D.h"
#include "Base/Face.h"
using namespace hpgem;
TvbLimiter1D::TvbLimiter1D(std::size_t numberOfVariables)
: SlopeLimiter(numberOfVariables) {}
void TvbLimiter1D::limitSlope(Base::Element *element) {
for (std::size_t iVar = 0; iVar < numberOfVariables_; ++iVar) {
if (!hasSmallSlope(element, iVar)) {
limitWithMinMod(element, iVar);
}
}
}
///\details Doing it the DG way for p=1 does not lead to conservation of mass,
/// so for now, do it the FVM way. Don't look at the slope in this element at
/// all, just at the averages of this element and the adjacent elements. We also
/// assume that we limit only once per time step. Lastly, it is assumed that the
/// first two basis functions are the nodal basis functions
void TvbLimiter1D::limitWithMinMod(Base::Element *element,
const std::size_t iVar) {
// this does not work for boundaries, probably also not for triangular mesh.
// maybe write getNeighbour(face), which deals with nullpointers in case of
// a boundary?
const Base::Element *elemL;
const Base::Element *elemR;
if (element->getFace(0)->isInternal())
elemL = element->getFace(0)->getPtrElementLeft();
else
return; // for now, just don't use the limiter here...
if (element->getFace(1)->isInternal())
elemR = element->getFace(1)->getPtrElementRight();
else
return; // for now, just don't use the limiter here...
logger.assert_always(elemR->getID() == element->getID() + 1 &&
element->getID() == elemL->getID() + 1,
"elements not in correct order");
const double u0 = Helpers::computeAverageOfSolution<1>(
element, element->getTimeIntegrationVector(0),
elementIntegrator_)(iVar);
const double uElemR = Helpers::computeAverageOfSolution<1>(
const_cast<Base::Element *>(elemR), elemR->getTimeIntegrationVector(0),
elementIntegrator_)(iVar);
const double uElemL = Helpers::computeAverageOfSolution<1>(
const_cast<Base::Element *>(elemL), elemL->getTimeIntegrationVector(0),
elementIntegrator_)(iVar);
logger(INFO, "uLeft: %\nu0: %\nuRight: %", uElemL, u0, uElemR);
LinearAlgebra::MiddleSizeVector newCoeffs =
LinearAlgebra::MiddleSizeVector(element->getNumberOfBasisFunctions());
if (Helpers::sign(uElemR - u0) != Helpers::sign(u0 - uElemL)) // phi(r) = 0
{
newCoeffs[0] = u0;
newCoeffs[1] = u0;
logger(INFO, "phi = 0");
} else {
if ((u0 - uElemL) / (uElemR - u0) < 1) // phi(r) = r
{
newCoeffs[0] = .5 * u0 + .5 * uElemL;
newCoeffs[1] = 1.5 * u0 - .5 * uElemL;
logger(INFO, "phi = r");
} else // phi(r) = 1
{
newCoeffs[0] = 1.5 * u0 - .5 * uElemR;
newCoeffs[1] = .5 * u0 + .5 * uElemR;
logger(INFO, "phi = 1");
}
}
logger(INFO, "new coefficients: % \n \n", newCoeffs);
element->setTimeIntegrationSubvector(0, iVar, newCoeffs);
}
bool TvbLimiter1D::hasSmallSlope(const Base::Element *element,
const std::size_t iVar) {
const PointReferenceT &pRefL =
element->getReferenceGeometry()->getReferenceNodeCoordinate(0);
const PointReferenceT &pRefR =
element->getReferenceGeometry()->getReferenceNodeCoordinate(1);
const double uPlus = element->getSolution(0, pRefR)[iVar];
const double uMinus = element->getSolution(0, pRefL)[iVar];
const double M = 1;
return (std::abs(uPlus - uMinus) <
M * (2 * element->calcJacobian(pRefL).determinant()) *
(2 * element->calcJacobian(pRefL).determinant()));
} | 43.472868 | 80 | 0.67582 |
8c26d6f600c31e11a935c11e6908364b90d2dbf3 | 2,408 | cpp | C++ | old/extgcd.inc.cpp | kmyk/competitive-programming-library | 77efa23a69f06202bb43f4dc6b0550e4cdb48e0b | [
"MIT"
] | 55 | 2018-01-11T02:20:02.000Z | 2022-03-24T06:18:54.000Z | number/extgcd.inc.cpp | Mohammad-Yasser/competitive-programming-library | 4656ac0d625abce98b901965c7607c1b908b093f | [
"MIT"
] | 10 | 2016-10-29T08:20:04.000Z | 2021-02-27T13:14:53.000Z | number/extgcd.inc.cpp | Mohammad-Yasser/competitive-programming-library | 4656ac0d625abce98b901965c7607c1b908b093f | [
"MIT"
] | 11 | 2016-10-29T06:00:53.000Z | 2021-06-16T14:32:43.000Z | /**
* @brief extended gcd
* @description for given a and b, find x, y and gcd(a, b) such that ax + by = 1
* @note O(log n)
* @see https://topcoder.g.hatena.ne.jp/spaghetti_source/20130126/1359171466
*/
tuple<ll, ll, ll> extgcd(ll a, ll b) {
ll x = 0, y = 1;
for (ll u = 1, v = 0; a; ) {
ll q = b / a;
x -= q * u; swap(x, u);
y -= q * v; swap(y, v);
b -= q * a; swap(b, a);
}
return make_tuple(x, y, b);
}
unittest {
random_device device;
default_random_engine gen(device());
REP (iteration, 1000) {
ll a = uniform_int_distribution<ll>(1, 10000)(gen);
ll b = uniform_int_distribution<ll>(1, 10000)(gen);
ll x, y, d; tie(x, y, d) = extgcd(a, b);
assert (a * x + b * y == d);
assert (d == __gcd(a, b));
}
}
/**
* @note recursive version (slow)
*/
pair<int, int> extgcd_recursive(int a, int b) {
if (b == 0) return { 1, 0 };
int na, nb; tie(na, nb) = extgcd(b, a % b);
return { nb, na - a/b * nb };
}
/**
* @note x and m must be relatively prime
* @note O(log m)
*/
ll modinv(ll x, int m) {
assert (1 <= x and x < m);
ll y, d; tie(y, ignore, d) = extgcd(x, m);
if (d != 1) return 0; // no inverse
assert (x * y % m == 1);
return (y % m + m) % m;
}
/**
* @brief chinese remainder theorem
* @note the unit element is (0, 1)
*/
pair<ll, ll> crt(pair<ll, ll> eqn1, pair<ll, ll> eqn2) {
ll x1, m1; tie(x1, m1) = eqn1;
ll x2, m2; tie(x2, m2) = eqn2;
ll x = x1 + m1 * (x2 - x1) * modinv(m1 % m2, m2);
ll m = m1 * m2;
return { (x % m + m) % m, m };
}
ll multmod(ll a, ll b, ll m) {
a = (a % m + m) % m;
b = (b % m + m) % m;
ll c = 0;
REP (i, 63) {
if (b & (1ll << i)) {
c += a;
if (c > m) c -= m;
}
a *= 2;
if (a > m) a -= m;
}
return c;
}
pair<ll, ll> crt(pair<ll, ll> eqn1, pair<ll, ll> eqn2) {
ll x1, m1; tie(x1, m1) = eqn1;
ll x2, m2; tie(x2, m2) = eqn2;
if (m1 == 0 or m2 == 0) return make_pair(0ll, 0ll);
assert (1 <= m1 and 1 <= m2);
ll m1_inv, d; tie(m1_inv, ignore, d) = extgcd(m1, m2);
if ((x1 - x2) % d) return make_pair(0ll, 0ll);
ll m = m1 * m2 / d;
// ll x = x1 + (m1 / d) * (x2 - x1) % m * (m1_inv % m) % m;
ll x = x1 + multmod(multmod(m1 / d, x2 - x1, m), m1_inv, m);
return make_pair((x % m + m) % m, m);
}
| 26.755556 | 80 | 0.475914 |
8c28ff85a56ee2abce629feee801ca4185d9fd4e | 355 | cpp | C++ | tests/mixed/mixed_invalid_unwrap_test.cpp | pacmancoder/exl | ffd66d30e76d60aa7e4efe75274e4a8a35427961 | [
"BSL-1.0"
] | 1 | 2019-05-02T12:00:50.000Z | 2019-05-02T12:00:50.000Z | tests/mixed/mixed_invalid_unwrap_test.cpp | pacmancoder/exl | ffd66d30e76d60aa7e4efe75274e4a8a35427961 | [
"BSL-1.0"
] | 14 | 2019-02-13T17:21:07.000Z | 2019-03-08T21:40:38.000Z | tests/mixed/mixed_invalid_unwrap_test.cpp | pacmancoder/exl | ffd66d30e76d60aa7e4efe75274e4a8a35427961 | [
"BSL-1.0"
] | null | null | null | // Copyright (C) 2019 Vladislav Nikonov <mail@pacmancoder.xyz>
//
// 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 <exl/mixed.hpp>
#include <termination_test.hpp>
void termination_test()
{
exl::mixed<char, int> m(422);
m.unwrap<char>();
} | 25.357143 | 83 | 0.715493 |
8c2a7228c91fe29e32f4bdf0d3796f4e551b287c | 5,812 | hpp | C++ | src/libv/diff/diff.hpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | 2 | 2018-04-11T03:07:03.000Z | 2019-03-29T15:24:12.000Z | src/libv/diff/diff.hpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | null | null | null | src/libv/diff/diff.hpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | 1 | 2021-06-13T06:39:06.000Z | 2021-06-13T06:39:06.000Z | // Project: libv.diff, File: src/libv/diff/diff.hpp, Author: Császár Mátyás [Vader]
#pragma once
// libv
#include <libv/utility/bytes/input_bytes.hpp>
#include <libv/utility/bytes/output_bytes.hpp>
// std
#include <optional>
#include <string>
#include <vector>
namespace libv {
namespace diff {
// -------------------------------------------------------------------------------------------------
static constexpr size_t default_match_block_size = 64;
// -------------------------------------------------------------------------------------------------
struct diff_info {
private:
static constexpr size_t invalid = std::numeric_limits<size_t>::max();
public:
size_t old_size = invalid;
size_t new_size = invalid;
public:
[[nodiscard]] constexpr inline bool valid() const noexcept {
return
old_size != invalid &&
new_size != invalid;
}
[[nodiscard]] explicit constexpr inline operator bool() const noexcept {
return valid();
}
[[nodiscard]] constexpr inline bool operator!() const noexcept {
return !valid();
}
};
namespace detail { // ------------------------------------------------------------------------------
void aux_create_diff(libv::input_bytes old, libv::input_bytes new_, libv::output_bytes out_diff, size_t match_block_size);
[[nodiscard]] diff_info aux_get_diff_info(libv::input_bytes diff);
[[nodiscard]] bool aux_check_diff(libv::input_bytes old, libv::input_bytes new_, libv::input_bytes diff);
[[nodiscard]] bool apply_patch(libv::input_bytes old, libv::input_bytes diff, libv::output_bytes out_new);
} // namespace -------------------------------------------------------------------------------------
/// Create a diff from \c old to \c new and appends at the end of \c diff.
///
/// \param old - The old version of the data
/// \param new_ - The new version of the data
/// \param match_block_size - Smaller block size improves compression but at the cost of performance. Recommended 16-16384
/// \return The resulting diff that can be applied to \c old to get \c new
template <typename In0, typename In1, typename Out>
inline void create_diff(In0&& old, In1&& new_, Out&& out_diff, size_t match_block_size = default_match_block_size) {
detail::aux_create_diff(libv::input_bytes(old), libv::input_bytes(new_), libv::output_bytes(out_diff), match_block_size);
}
/// Returns a diff created from \c old to \c new.
///
/// \template T - The output type used for diff (std::string or std::vector<std::byte>)
/// \param old - The old version of the data
/// \param new_ - The new version of the data
/// \param match_block_size - Smaller block size improves compression but at the cost of performance. Recommended 16-16384
/// \return The resulting diff that can be applied to \c old to get \c new
template <typename T, typename In0, typename In1>
[[nodiscard]] inline T create_diff(In0&& old, In1&& new_, size_t match_block_size = default_match_block_size) {
T diff;
create_diff(old, new_, diff, match_block_size);
return diff;
}
template <typename In0, typename In1>
[[nodiscard]] inline std::string create_diff_str(In0&& old, In1&& new_, size_t match_block_size = default_match_block_size) {
return create_diff<std::string>(old, new_, match_block_size);
}
template <typename In0, typename In1>
[[nodiscard]] inline std::vector<std::byte> create_diff_bin(In0&& old, In1&& new_, size_t match_block_size = default_match_block_size) {
return create_diff<std::vector<std::byte>>(old, new_, match_block_size);
}
/// \return Returns a non valid diff_info object upon failure, otherwise returns the diff info
template <typename In0>
[[nodiscard]] diff_info get_diff_info(In0&& diff) {
return detail::aux_get_diff_info(libv::input_bytes(diff));
}
/// Check if the \c diff applied to \c old will result in \c new.
///
/// \param old - The old version of the data
/// \param new_ - The new version of the data
/// \param diff - The diff that will be applied to \c old
/// \return Returns true if \c diff can be applied to \c old and it results in \c new
template <typename In0, typename In1, typename In2>
[[nodiscard]] inline bool check_diff(In0&& old, In1&& new_, In2&& diff) {
return detail::aux_check_diff(libv::input_bytes(old), libv::input_bytes(new_), libv::input_bytes(diff));
}
/// Applies \c diff to \c old.
///
/// \param old - The old version of the data
/// \param diff - The diff that will be applied to \c old
/// \return Returns the new version of the data after applying the \c diff or an empty optional if the \c diff cannot be applied to \olc
template <typename In0, typename In1, typename Out>
[[nodiscard]] inline bool apply_patch(In0&& old, In1&& diff, Out&& out_new) {
return detail::apply_patch(libv::input_bytes(old), libv::input_bytes(diff), libv::output_bytes(out_new));
}
/// Applies \c diff to \c old.
///
/// \param old - The old version of the data
/// \param diff - The diff that will be applied to \c old
/// \return Returns the new version of the data after applying the \c diff or an empty optional if the \c diff cannot be applied to \olc
template <typename T, typename In0, typename In1>
[[nodiscard]] inline std::optional<T> apply_patch(In0&& old, In1&& diff) {
std::optional<T> new_(std::in_place);
const auto success = apply_patch(old, diff, *new_);
if (!success)
new_.reset();
return new_;
}
template <typename In0, typename In1>
[[nodiscard]] inline std::optional<std::string> apply_patch_str(In0&& old, In1&& diff) {
return apply_patch<std::string>(old, diff);
}
template <typename In0, typename In1>
[[nodiscard]] inline std::optional<std::vector<std::byte>> apply_patch_bin(In0&& old, In1&& diff) {
return apply_patch<std::vector<std::byte>>(old, diff);
}
// -------------------------------------------------------------------------------------------------
} // namespace diff
} // namespace libv
| 39.808219 | 136 | 0.668789 |
8c2ad38fa61b19ad767dd011d39cf3a68dc734fd | 2,690 | cpp | C++ | src/cpp/common-bio/Multiseq.cpp | UTbioinf/SMSC | 0d5765518b3863d2363f264d9f256063c7f7ce71 | [
"MIT"
] | null | null | null | src/cpp/common-bio/Multiseq.cpp | UTbioinf/SMSC | 0d5765518b3863d2363f264d9f256063c7f7ce71 | [
"MIT"
] | 2 | 2019-05-31T06:36:36.000Z | 2019-09-18T22:13:09.000Z | src/cpp/common-bio/Multiseq.cpp | UTbioinf/SMSC | 0d5765518b3863d2363f264d9f256063c7f7ce71 | [
"MIT"
] | 1 | 2021-12-01T10:30:58.000Z | 2021-12-01T10:30:58.000Z | #include <fstream>
#include <cctype>
#include "Multiseq.h"
#include "util.h"
namespace loon
{
void Fasta::save_fasta(std::ostream& out)
{
out << ">" << tag << tag_remaining << std::endl;
for(size_t i = 0; i < seq.length(); i += 80)
out << seq.substr(i, 80) << std::endl;
}
char Fasta::base_rc(char c)
{
if(c >= 'a' && c <= 'z')
c = c - 'a' + 'A';
switch(c)
{
case 'A': return 'T';
case 'T': return 'A';
case 'G': return 'C';
case 'C': return 'G';
case 'R': return 'Y';
case 'Y': return 'R';
case 'S': return 'S';
case 'W': return 'W';
case 'M': return 'K';
case 'K': return 'M';
case 'B': return 'V';
case 'D': return 'H';
case 'H': return 'D';
case 'V': return 'B';
case 'N': return 'N';
case '-': return '-';
default:
ERROR_PRINT("Unknown base [%d: %c]", int(c), c);
exit(1);
}
}
void Fasta::compute_reverse_complement()
{
rev.clear();
rev.reserve( seq.length() );
for(std::string::reverse_iterator rit = seq.rbegin(); rit != seq.rend(); ++rit)
rev.push_back( base_rc( *rit ) );
}
void Multiseq::read_fasta(const char* fname)
{
std::ifstream fin(fname);
check_file_open(fin, fname);
std::string line;
while(std::getline(fin, line))
{
if(line[0] == '>')
{
this->push_back( Fasta() );
Fasta& fasta = this->back();
std::size_t space_pos = line.find(' ');
if(space_pos != std::string::npos)
{
fasta.tag = line.substr(1, space_pos-1);
fasta.tag_remaining = line.substr(space_pos);
}
else
fasta.tag = line.substr(1);
}
else if(line[0] != ';')
{
for(std::size_t i = 0; i<line.length(); ++i)
{
line[i] = expand_base( line[i] );
}
this->back().seq += line;
}
}
fin.close();
}
void Multiseq::save_fasta(const char* fname)
{
std::ofstream fout(fname);
check_file_open(fout, fname);
for(std::vector<Fasta>::iterator it = this->begin(); it != this->end(); ++it)
{
fout << ">" << (it->tag) << (it->tag_remaining) << std::endl;
for(size_t i = 0; i < it->seq.length(); i += 80)
fout << (it->seq.substr(i, 80)) << std::endl;
}
fout.close();
}
void Multiseq::compute_reverse_complement()
{
for(std::vector<Fasta>::iterator it = this->begin(); it != this->end(); ++it)
it->compute_reverse_complement();
}
}
| 24.907407 | 83 | 0.477695 |
8c2b0f8c42e3757625f710420e30b7d152444f96 | 14,696 | cpp | C++ | LSL/GLUtils.cpp | AntonBogomolov/LightSpeedLimit | 215d573f46eef63801cbd8df654f104401bae581 | [
"MIT"
] | null | null | null | LSL/GLUtils.cpp | AntonBogomolov/LightSpeedLimit | 215d573f46eef63801cbd8df654f104401bae581 | [
"MIT"
] | null | null | null | LSL/GLUtils.cpp | AntonBogomolov/LightSpeedLimit | 215d573f46eef63801cbd8df654f104401bae581 | [
"MIT"
] | null | null | null | #include "global.h"
#include "GLUtils.h"
#include "GLShaderObject.h"
#include "TextureManager.h"
#include "Texture.h"
#include "TextureAtlas.h"
#include "VertexArray.h"
#include "VertexBuffer.h"
#include "SceneGraphNode.h"
#include "ScreenObj.h"
#include "VideoManeger.h"
#include "DrawablePrimitive.h"
CGLUtils* CGLUtils::instance = NULL;
CVertexBuffer* CGLUtils::quad = NULL;
CVertexBuffer* CGLUtils::revQuad = NULL;
CVertexBuffer* CGLUtils::lQuad = NULL;
CDrawablePrimitive* CGLUtils::QuadNode = NULL;
CDrawablePrimitive* CGLUtils::revQuadNode = NULL;
byte* CGLUtils::glGetTexImage(const int texId, const int texW, const int texH)
{
GLuint* framebuffer = new GLuint[1];
glGenFramebuffers(1, framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer[0]);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, CTextureManager::getTexture(texId)->getID(), 0); // texId
int status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE)
{
// Log.e("glGetTexImage", "image load faild");
}
byte* buff = new byte[texW * texH * 4];
glReadPixels(0, 0, texW, texH, GL_RGBA, GL_UNSIGNED_BYTE, buff);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, framebuffer);
return buff;
}
void CGLUtils::checkGlError(const string op)
{
int error;
while ((error = glGetError()) != GL_NO_ERROR)
{
}
}
CSceneGraphNodeDrawable* CGLUtils::getFullscreenDrawableNode()
{
if (!QuadNode) initFullscreenQuad();
return (CSceneGraphNodeDrawable*)QuadNode;
}
CSceneGraphNodeDrawable* CGLUtils::getFullscreenRevDrawableNode()
{
if (!revQuadNode) initFullscreenRevQuad();
return (CSceneGraphNodeDrawable*)revQuadNode;
}
CVertexBuffer* CGLUtils::initFullscreenQuad()
{
if (quad) delete quad;
quad = NULL;
quad = new CVertexBuffer();
if (!QuadNode) QuadNode = new CDrawablePrimitive();
GLfloat qverts[] = { 0, 0, 0, CVideoManeger::scrWidth, 0, 0, CVideoManeger::scrWidth, CVideoManeger::scrHeight, 0, 0, CVideoManeger::scrHeight, 0 };
GLfloat qcoords[] = { 0, 0, 1, 0, 1, 1, 0, 1 };
short qind[] = { 0, 1, 2, 0, 2, 3 };
quad->setVerticesData(qverts, 4 * 3);
quad->setTexData(qcoords, 4 * 2);
quad->setIndicesData(qind, 6);
QuadNode->setVBO(quad);
return quad;
}
void CGLUtils::drawFullscreenQuad(const CGLShaderObject* currShader)
{
if (quad == NULL) initFullscreenQuad();
if (quad)
{
quad->drawElements(0, currShader);
}
}
CVertexBuffer* CGLUtils::initFullscreenRevQuad()
{
if (revQuad) delete revQuad;
revQuad = NULL;
revQuad = new CVertexBuffer();
if (!revQuadNode) revQuadNode = new CDrawablePrimitive();
GLfloat qverts[] = { 0, 0, 0, CVideoManeger::scrWidth, 0, 0, CVideoManeger::scrWidth, CVideoManeger::scrHeight, 0, 0, CVideoManeger::scrHeight, 0 };
GLfloat qcoords[] = { 0, 1, 1, 1, 1, 0, 0, 0 };
short qind[] = { 0, 1, 2, 0, 2, 3 };
revQuad->setVerticesData(qverts, 4 * 3);
revQuad->setTexData(qcoords, 4 * 2);
revQuad->setIndicesData(qind, 6);
revQuadNode->setVBO(revQuad);
return revQuad;
}
void CGLUtils::drawFullscreenRevQuad(const CGLShaderObject* currShader)
{
if (revQuad == NULL) initFullscreenRevQuad();
if (revQuad)
{
revQuad->drawElements(0, currShader);
}
}
CVertexBuffer* CGLUtils::initLFullscreenQuad()
{
float flDataVert[] = { 0, 0, 0, 0, 0,
CVideoManeger::scrWidth, 0, 0, CVideoManeger::scrWidth, 0,
0, CVideoManeger::scrHeight, 0, 0, CVideoManeger::scrHeight,
CVideoManeger::scrWidth, 0, 0, CVideoManeger::scrWidth, 0,
0, CVideoManeger::scrHeight, 0, 0, CVideoManeger::scrHeight,
CVideoManeger::scrWidth, CVideoManeger::scrHeight, 0, CVideoManeger::scrWidth, CVideoManeger::scrHeight
};
return NULL;
}
void CGLUtils::drawLFullscreenQuad(const CGLShaderObject* currShader)
{
if (lQuad == NULL) initLFullscreenQuad();
}
void CGLUtils::fillVBOData( float* vert, float* tex, float* vtex, short* ind, const CTexCoord* sprite, const CTexCoord* vsprite,
const int index, const CScreenObj* obj, const int direction, const float offset)
{
bool hasAdditionalTexCoord = false;
if (vtex != NULL && vsprite != NULL) hasAdditionalTexCoord = true;
if (vert == NULL) return;
if (tex == NULL ) return;
if (ind == NULL ) return;
if (sprite == NULL) return;
const glm::vec2* points = obj->getPointsCoords();
int X1 = points[0].x;
int Y1 = points[0].y;
int X2 = points[1].x;
int Y2 = points[1].y;
int X3 = points[2].x;
int Y3 = points[2].y;
int X4 = points[3].x;
int Y4 = points[3].y;
vert[index * 12 + 0] = X1; vert[index * 12 + 1] = Y1; vert[index * 12 + 2] = 0;
vert[index * 12 + 3] = X2 + offset; vert[index * 12 + 4] = Y2; vert[index * 12 + 5] = 0;
vert[index * 12 + 6] = X3 + offset; vert[index * 12 + 7] = Y3 + offset; vert[index * 12 + 8] = 0;
vert[index * 12 + 9] = X4; vert[index * 12 + 10] =Y4 + offset; vert[index * 12 + 11] = 0;
switch (direction)
{
case Defines::DIR_DOWN:
tex[index * 8 + 0] = sprite->tx + sprite->twidth; tex[index * 8 + 1] = sprite->ty + sprite->theight;
tex[index * 8 + 2] = sprite->tx; tex[index * 8 + 3] = sprite->ty + sprite->theight;
tex[index * 8 + 4] = sprite->tx; tex[index * 8 + 5] = sprite->ty;
tex[index * 8 + 6] = sprite->tx + sprite->twidth; tex[index * 8 + 7] = sprite->ty;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 1] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 2] = vsprite->tx; vtex[index * 8 + 3] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 4] = vsprite->tx; vtex[index * 8 + 5] = vsprite->ty;
vtex[index * 8 + 6] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 7] = vsprite->ty;
}
break;
case Defines::DIR_LEFT:
tex[index * 8 + 0] = sprite->tx + sprite->twidth; tex[index * 8 + 1] = sprite->ty;
tex[index * 8 + 2] = sprite->tx + sprite->twidth; tex[index * 8 + 3] = sprite->ty + sprite->theight;
tex[index * 8 + 4] = sprite->tx; tex[index * 8 + 5] = sprite->ty + sprite->theight;
tex[index * 8 + 6] = sprite->tx; tex[index * 8 + 7] = sprite->ty;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 1] = vsprite->ty;
vtex[index * 8 + 2] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 3] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 4] = vsprite->tx; vtex[index * 8 + 5] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 6] = vsprite->tx; vtex[index * 8 + 7] = vsprite->ty;
}
break;
case Defines::DIR_RIGHT:
tex[index * 8 + 0] = sprite->tx; tex[index * 8 + 1] = sprite->ty + sprite->theight;
tex[index * 8 + 2] = sprite->tx; tex[index * 8 + 3] = sprite->ty;
tex[index * 8 + 4] = sprite->tx + sprite->twidth; tex[index * 8 + 5] = sprite->ty;
tex[index * 8 + 6] = sprite->tx + sprite->twidth; tex[index * 8 + 7] = sprite->ty + sprite->theight;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx; vtex[index * 8 + 1] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 2] = vsprite->tx; vtex[index * 8 + 3] = vsprite->ty;
vtex[index * 8 + 4] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 5] = vsprite->ty;
vtex[index * 8 + 6] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 7] = vsprite->ty + vsprite->theight;
}
break;
default:
tex[index * 8 + 0] = sprite->tx; tex[index * 8 + 1] = sprite->ty;
tex[index * 8 + 2] = sprite->tx + sprite->twidth; tex[index * 8 + 3] = sprite->ty;
tex[index * 8 + 4] = sprite->tx + sprite->twidth; tex[index * 8 + 5] = sprite->ty + sprite->theight;
tex[index * 8 + 6] = sprite->tx; tex[index * 8 + 7] = sprite->ty + sprite->theight;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx; vtex[index * 8 + 1] = vsprite->ty;
vtex[index * 8 + 2] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 3] = vsprite->ty;
vtex[index * 8 + 4] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 5] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 6] = vsprite->tx; vtex[index * 8 + 7] = vsprite->ty + vsprite->theight;
}
break;
}
ind[index * 6 + 0] = (short)(index * 4); ind[index * 6 + 1] = (short)(index * 4 + 1); ind[index * 6 + 2] = (short)(index * 4 + 2);
ind[index * 6 + 3] = (short)(index * 4); ind[index * 6 + 4] = (short)(index * 4 + 2); ind[index * 6 + 5] = (short)(index * 4 + 3);
}
void CGLUtils::fillVBOVertData(float* vert, const int index, const CScreenObj* obj, const float offset)
{
if (vert == NULL) return;
const glm::vec2* points = obj->getPointsCoords();
int X1 = points[0].x;
int Y1 = points[0].y;
int X2 = points[1].x;
int Y2 = points[1].y;
int X3 = points[2].x;
int Y3 = points[2].y;
int X4 = points[3].x;
int Y4 = points[3].y;
vert[index * 12 + 0] = X1; vert[index * 12 + 1] = Y1; vert[index * 12 + 2] = 0;
vert[index * 12 + 3] = X2 + offset; vert[index * 12 + 4] = Y2; vert[index * 12 + 5] = 0;
vert[index * 12 + 6] = X3 + offset; vert[index * 12 + 7] = Y3 + offset; vert[index * 12 + 8] = 0;
vert[index * 12 + 9] = X4; vert[index * 12 + 10] =Y4 + offset; vert[index * 12 + 11] = 0;
}
void CGLUtils::fillVBOTexData(float* tex, float* vtex, const CTexCoord* sprite, const CTexCoord* vsprite, const int index, const int direction, const float offset)
{
bool hasAdditionalTexCoord = false;
if (vtex != NULL && vsprite != NULL) hasAdditionalTexCoord = true;
if (tex == NULL) return;
if (sprite == NULL) return;
switch (direction)
{
case Defines::DIR_DOWN:
tex[index * 8 + 0] = sprite->tx + sprite->twidth; tex[index * 8 + 1] = sprite->ty + sprite->theight;
tex[index * 8 + 2] = sprite->tx; tex[index * 8 + 3] = sprite->ty + sprite->theight;
tex[index * 8 + 4] = sprite->tx; tex[index * 8 + 5] = sprite->ty;
tex[index * 8 + 6] = sprite->tx + sprite->twidth; tex[index * 8 + 7] = sprite->ty;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 1] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 2] = vsprite->tx; vtex[index * 8 + 3] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 4] = vsprite->tx; vtex[index * 8 + 5] = vsprite->ty;
vtex[index * 8 + 6] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 7] = vsprite->ty;
}
break;
case Defines::DIR_LEFT:
tex[index * 8 + 0] = sprite->tx + sprite->twidth; tex[index * 8 + 1] = sprite->ty;
tex[index * 8 + 2] = sprite->tx + sprite->twidth; tex[index * 8 + 3] = sprite->ty + sprite->theight;
tex[index * 8 + 4] = sprite->tx; tex[index * 8 + 5] = sprite->ty + sprite->theight;
tex[index * 8 + 6] = sprite->tx; tex[index * 8 + 7] = sprite->ty;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 1] = vsprite->ty;
vtex[index * 8 + 2] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 3] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 4] = vsprite->tx; vtex[index * 8 + 5] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 6] = vsprite->tx; vtex[index * 8 + 7] = vsprite->ty;
}
break;
case Defines::DIR_RIGHT:
tex[index * 8 + 0] = sprite->tx; tex[index * 8 + 1] = sprite->ty + sprite->theight;
tex[index * 8 + 2] = sprite->tx; tex[index * 8 + 3] = sprite->ty;
tex[index * 8 + 4] = sprite->tx + sprite->twidth; tex[index * 8 + 5] = sprite->ty;
tex[index * 8 + 6] = sprite->tx + sprite->twidth; tex[index * 8 + 7] = sprite->ty + sprite->theight;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx; vtex[index * 8 + 1] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 2] = vsprite->tx; vtex[index * 8 + 3] = vsprite->ty;
vtex[index * 8 + 4] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 5] = vsprite->ty;
vtex[index * 8 + 6] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 7] = vsprite->ty + vsprite->theight;
}
break;
default:
tex[index * 8 + 0] = sprite->tx; tex[index * 8 + 1] = sprite->ty;
tex[index * 8 + 2] = sprite->tx + sprite->twidth; tex[index * 8 + 3] = sprite->ty;
tex[index * 8 + 4] = sprite->tx + sprite->twidth; tex[index * 8 + 5] = sprite->ty + sprite->theight;
tex[index * 8 + 6] = sprite->tx; tex[index * 8 + 7] = sprite->ty + sprite->theight;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx; vtex[index * 8 + 1] = vsprite->ty;
vtex[index * 8 + 2] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 3] = vsprite->ty;
vtex[index * 8 + 4] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 5] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 6] = vsprite->tx; vtex[index * 8 + 7] = vsprite->ty + vsprite->theight;
}
break;
}
}
void CGLUtils::fillVBOIndData(short* ind, const int index)
{
if (ind == NULL) return;
ind[index * 6 + 0] = (short)(index * 4); ind[index * 6 + 1] = (short)(index * 4 + 1); ind[index * 6 + 2] = (short)(index * 4 + 2);
ind[index * 6 + 3] = (short)(index * 4); ind[index * 6 + 4] = (short)(index * 4 + 2); ind[index * 6 + 5] = (short)(index * 4 + 3);
}
void CGLUtils::fillVBOData(float* vert, short* ind, const int index, const float* geomData, const int geomDataCoordCnt, const float offset)
{
if (vert == NULL || ind == NULL || geomData == NULL) return;
if (geomDataCoordCnt < 1 || geomDataCoordCnt > 3) return;
int X = (int)geomData[index * geomDataCoordCnt + 0];
int Y = (int)geomData[index * geomDataCoordCnt + 1];
int Z = (int)geomData[index * geomDataCoordCnt + 2];
if (geomDataCoordCnt == 1)
{
X = (int)geomData[index * geomDataCoordCnt + 0];
Y = 0;
Z = 0;
}
if (geomDataCoordCnt == 2)
{
X = (int)geomData[index * geomDataCoordCnt + 0];
Y = (int)geomData[index * geomDataCoordCnt + 1];
Z = 0;
}
vert[index * 3 + 0] = X; vert[index * 3 + 1] = Y; vert[index * 3 + 2] = Z;
ind[index] = index;
}
CGLUtils::CGLUtils()
{
}
CGLUtils::~CGLUtils()
{
if (quad) delete quad;
if (lQuad) delete lQuad;
if (revQuad) delete revQuad;
if (QuadNode) delete QuadNode;
if (revQuadNode) delete revQuadNode;
}
CGLUtils* CGLUtils::GetInstance()
{
if (instance == NULL)
{
instance = new CGLUtils();
}
return instance;
}
void CGLUtils::resizeWindow()
{
glViewport(0, 0, CVideoManeger::scrWidth, CVideoManeger::scrHeight);
if (QuadNode)
{
GLfloat qverts[] = { 0, 0, 0, CVideoManeger::scrWidth, 0, 0, CVideoManeger::scrWidth, CVideoManeger::scrHeight, 0, 0, CVideoManeger::scrHeight, 0 };
QuadNode->getVBOForModify()->setVerticesData(qverts, 4 * 3);
}
if (revQuadNode)
{
GLfloat qverts[] = { 0, 0, 0, CVideoManeger::scrWidth, 0, 0, CVideoManeger::scrWidth, CVideoManeger::scrHeight, 0, 0, CVideoManeger::scrHeight, 0 };
revQuadNode->getVBOForModify()->setVerticesData(qverts, 4 * 3);
}
} | 37.394402 | 163 | 0.62187 |
8c30e0dc1e6c398403e44f85fb9ee154f306f186 | 2,165 | cc | C++ | chrome/browser/media/router/mojo/media_router_mojo_metrics_unittest.cc | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | chrome/browser/media/router/mojo/media_router_mojo_metrics_unittest.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | chrome/browser/media/router/mojo/media_router_mojo_metrics_unittest.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/router/mojo/media_router_mojo_metrics.h"
#include "base/version.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace media_router {
TEST(MediaRouterMojoMetricsTest, TestGetMediaRouteProviderVersion) {
const base::Version kBrowserVersion("50.0.2396.71");
EXPECT_EQ(MediaRouteProviderVersion::SAME_VERSION_AS_CHROME,
MediaRouterMojoMetrics::GetMediaRouteProviderVersion(
base::Version("50.0.2396.71"), kBrowserVersion));
EXPECT_EQ(MediaRouteProviderVersion::SAME_VERSION_AS_CHROME,
MediaRouterMojoMetrics::GetMediaRouteProviderVersion(
base::Version("50.0.2100.0"), kBrowserVersion));
EXPECT_EQ(MediaRouteProviderVersion::SAME_VERSION_AS_CHROME,
MediaRouterMojoMetrics::GetMediaRouteProviderVersion(
base::Version("51.0.2117.0"), kBrowserVersion));
EXPECT_EQ(MediaRouteProviderVersion::ONE_VERSION_BEHIND_CHROME,
MediaRouterMojoMetrics::GetMediaRouteProviderVersion(
base::Version("49.0.2138.0"), kBrowserVersion));
EXPECT_EQ(MediaRouteProviderVersion::MULTIPLE_VERSIONS_BEHIND_CHROME,
MediaRouterMojoMetrics::GetMediaRouteProviderVersion(
base::Version("47.0.1134.0"), kBrowserVersion));
EXPECT_EQ(MediaRouteProviderVersion::UNKNOWN,
MediaRouterMojoMetrics::GetMediaRouteProviderVersion(
base::Version("blargh"), kBrowserVersion));
EXPECT_EQ(MediaRouteProviderVersion::UNKNOWN,
MediaRouterMojoMetrics::GetMediaRouteProviderVersion(
base::Version(""), kBrowserVersion));
EXPECT_EQ(MediaRouteProviderVersion::UNKNOWN,
MediaRouterMojoMetrics::GetMediaRouteProviderVersion(
base::Version("-1.0.0.0"), kBrowserVersion));
EXPECT_EQ(MediaRouteProviderVersion::UNKNOWN,
MediaRouterMojoMetrics::GetMediaRouteProviderVersion(
base::Version("0"), kBrowserVersion));
}
} // namespace media_router
| 49.204545 | 73 | 0.728868 |
8c32011a805538118756eb62bf63bb51db53a544 | 377 | cc | C++ | below2.1/speeding.cc | danzel-py/Kattis-Problem-Archive | bce1929d654b1bceb104f96d68c74349273dd1ff | [
"Apache-2.0"
] | null | null | null | below2.1/speeding.cc | danzel-py/Kattis-Problem-Archive | bce1929d654b1bceb104f96d68c74349273dd1ff | [
"Apache-2.0"
] | null | null | null | below2.1/speeding.cc | danzel-py/Kattis-Problem-Archive | bce1929d654b1bceb104f96d68c74349273dd1ff | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
int main(){
int nu;
cin>>nu;
int t,p;
cin>>t>>p;
int mem, memp;
int max = 0;
for (int i = 0; i < nu-1; i++)
{
mem = t;
memp = p;
cin>>t>>p;
if((p - memp)/(t-mem)>max){
max = (p - memp)/(t-mem);
}
}
cout<<max;
return 0;
} | 15.08 | 37 | 0.37931 |
8c37014f2bfe8acc6bb1093f96c356c3b6ddb71d | 876 | hh | C++ | include/Main.hh | FatmanUK/guess-word | 811f660d111dabdb81dc4baa95a33841643fccb0 | [
"BSD-2-Clause"
] | null | null | null | include/Main.hh | FatmanUK/guess-word | 811f660d111dabdb81dc4baa95a33841643fccb0 | [
"BSD-2-Clause"
] | null | null | null | include/Main.hh | FatmanUK/guess-word | 811f660d111dabdb81dc4baa95a33841643fccb0 | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <map>
using std::map;
#include <sstream>
using std::istringstream;
using std::ostringstream;
#include <iostream>
using std::cout;
using std::cerr;
using std::cin;
using std::endl;
#include <fstream>
using std::ifstream;
#include <algorithm>
using std::count;
#include <system_error>
using std::runtime_error;
using std::exception;
#include <random>
using std::default_random_engine;
using std::uniform_int_distribution;
#include <chrono>
using std::chrono::high_resolution_clock;
#include <cstring>
using std::memset;
#include "docopt.h"
#ifndef CONFDIR
#error CONFDIR should be defined by the build system. Check \
your build config.
#endif
const unsigned short ver_maj{0};
const unsigned short ver_min{1};
const unsigned short ver_rel{0};
| 16.528302 | 69 | 0.732877 |
8c38b1f3f05a74824dc7ef74d8f65ded63d62a3a | 263 | hpp | C++ | tools/mem_usage/mem_usage.hpp | LioQing/personal-utils | e24d1ea1510087797c6b85bae89a3801a2e77f3d | [
"Unlicense"
] | null | null | null | tools/mem_usage/mem_usage.hpp | LioQing/personal-utils | e24d1ea1510087797c6b85bae89a3801a2e77f3d | [
"Unlicense"
] | null | null | null | tools/mem_usage/mem_usage.hpp | LioQing/personal-utils | e24d1ea1510087797c6b85bae89a3801a2e77f3d | [
"Unlicense"
] | null | null | null | #pragma once
#include <cstdint>
namespace lio
{
enum MemArgs : uint8_t
{
USAGE = 0b001,
COUNT = 0b010,
PEAK = 0b100
};
extern size_t memory_count;
extern size_t memory_used;
extern size_t memory_peak;
void print_mem_isage(uint8_t args = USAGE);
} | 13.842105 | 44 | 0.714829 |
8c4025d9dbd5731fa3083db7d2c4fd5895e88a69 | 4,798 | cpp | C++ | Framework/Math/Scissor.cpp | dengwenyi88/Deferred_Lighting | b45b6590150a3119b0c2365f4795d93b3b4f0748 | [
"MIT"
] | 110 | 2017-06-23T17:12:28.000Z | 2022-02-22T19:11:38.000Z | RunTest/Framework3/Math/Scissor.cpp | dtrebilco/ECSAtto | 86a04f0bdc521c79f758df94250c1898c39213c8 | [
"MIT"
] | null | null | null | RunTest/Framework3/Math/Scissor.cpp | dtrebilco/ECSAtto | 86a04f0bdc521c79f758df94250c1898c39213c8 | [
"MIT"
] | 3 | 2018-02-12T00:16:18.000Z | 2018-02-18T11:12:35.000Z |
/* * * * * * * * * * * * * Author's note * * * * * * * * * * * *\
* _ _ _ _ _ _ _ _ _ _ _ _ *
* |_| |_| |_| |_| |_|_ _|_| |_| |_| _|_|_|_|_| *
* |_|_ _ _|_| |_| |_| |_|_|_|_|_| |_| |_| |_|_ _ _ *
* |_|_|_|_|_| |_| |_| |_| |_| |_| |_| |_| |_|_|_|_ *
* |_| |_| |_|_ _ _|_| |_| |_| |_|_ _ _|_| _ _ _ _|_| *
* |_| |_| |_|_|_| |_| |_| |_|_|_| |_|_|_|_| *
* *
* http://www.humus.name *
* *
* This file is a part of the work done by Humus. You are free to *
* use the code in any way you like, modified, unmodified or copied *
* into your own work. However, I expect you to respect these points: *
* - If you use this file and its contents unmodified, or use a major *
* part of this file, please credit the author and leave this note. *
* - For use in anything commercial, please request my approval. *
* - Share your work and ideas too as much as you can. *
* *
\* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "Scissor.h"
/*
bool getScissorRectangle(const mat4 &projection, const mat4 &modelview, const vec3 &camPos, const vec3 &lightPos, const float radius, const int width, const int height, int *x, int *y, int *w, int *h){
float d = distance(camPos, lightPos);
float p = d * radius / sqrtf(d * d - radius * radius);
vec3 dx = modelview.rows[0].xyz();
vec3 dy = modelview.rows[1].xyz();
// vec3 dz = normalize(lightPos - camPos);
// dx = cross(dy, dz);
// dy = cross(dz, dx);
vec3 dz = normalize(lightPos - camPos);
vec3 dx = normalize(vec3(dz.z, 0, -dz.x));
vec3 dy = normalize(cross(dz, dx));
vec4 leftPos = vec4(lightPos - p * dx, 1.0f);
vec4 rightPos = vec4(lightPos + p * dx, 1.0f);
mat4 mvp = projection * modelview;
leftPos = mvp * leftPos;
rightPos = mvp * rightPos;
int left = int(width * (leftPos.x / leftPos.z * 0.5f + 0.5f));
int right = int(width * (rightPos.x / rightPos.z * 0.5f + 0.5f));
*x = left;
*w = right - left;
*y = 0;
*h = height;
return true;
}
*/
#define EPSILON 0.0005f
bool getScissorRectangle(const mat4 &modelview, const vec3 &pos, const float radius, const float fov, const int width, const int height, int *x, int *y, int *w, int *h){
vec4 lightPos = modelview * vec4(pos, 1.0f);
float ex = tanf(fov / 2);
float ey = ex * height / width;
float Lxz = (lightPos.x * lightPos.x + lightPos.z * lightPos.z);
float a = -radius * lightPos.x / Lxz;
float b = (radius * radius - lightPos.z * lightPos.z) / Lxz;
float f = -b + a * a;
float lp = 0;
float rp = 1;
float bp = 0;
float tp = 1;
// if (f > EPSILON){
if (f > 0){
float Nx0 = -a + sqrtf(f);
float Nx1 = -a - sqrtf(f);
float Nz0 = (radius - Nx0 * lightPos.x) / lightPos.z;
float Nz1 = (radius - Nx1 * lightPos.x) / lightPos.z;
float x0 = 0.5f * (1 - Nz0 / (Nx0 * ex));
float x1 = 0.5f * (1 - Nz1 / (Nx1 * ex));
float Pz0 = (Lxz - radius * radius) / (lightPos.z - lightPos.x * Nz0 / Nx0);
float Pz1 = (Lxz - radius * radius) / (lightPos.z - lightPos.x * Nz1 / Nx1);
float Px0 = -(Pz0 * Nz0) / Nx0;
float Px1 = -(Pz1 * Nz1) / Nx1;
if (Px0 > lightPos.x) rp = x0;
if (Px0 < lightPos.x) lp = x0;
if (Px1 > lightPos.x && x1 < rp) rp = x1;
if (Px1 < lightPos.x && x1 > lp) lp = x1;
}
float Lyz = (lightPos.y * lightPos.y + lightPos.z * lightPos.z);
a = -radius * lightPos.y / Lyz;
b = (radius * radius - lightPos.z * lightPos.z) / Lyz;
f = -b + a * a;
// if (f > EPSILON){
if (f > 0){
float Ny0 = -a + sqrtf(f);
float Ny1 = -a - sqrtf(f);
float Nz0 = (radius - Ny0 * lightPos.y) / lightPos.z;
float Nz1 = (radius - Ny1 * lightPos.y) / lightPos.z;
float y0 = 0.5f * (1 - Nz0 / (Ny0 * ey));
float y1 = 0.5f * (1 - Nz1 / (Ny1 * ey));
float Pz0 = (Lyz - radius * radius) / (lightPos.z - lightPos.y * Nz0 / Ny0);
float Pz1 = (Lyz - radius * radius) / (lightPos.z - lightPos.y * Nz1 / Ny1);
float Py0 = -(Pz0 * Nz0) / Ny0;
float Py1 = -(Pz1 * Nz1) / Ny1;
if (Py0 > lightPos.y) tp = y0;
if (Py0 < lightPos.y) bp = y0;
if (Py1 > lightPos.y && y1 < tp) tp = y1;
if (Py1 < lightPos.y && y1 > bp) bp = y1;
}
lp *= width;
rp *= width;
tp *= height;
bp *= height;
int left = int(lp);
int right = int(rp);
int top = int(tp);
int bottom = int(bp);
if (right <= left || top <= bottom) return false;
*x = min(max(int(left), 0), width - 1);
*y = min(max(int(bottom), 0), height - 1);
*w = min(int(right) - *x, width - *x);
*h = min(int(top) - *y, height - *y);
return (*w > 0 && *h > 0);
}
| 32.418919 | 201 | 0.516048 |
8c402ea7a19d66f47675ff19cdb33761cb9c5fe1 | 10,767 | cpp | C++ | app/src/main/jni/comitton/PdfCrypt.cpp | mryp/ComittoNxA | 9b46c267bff22c2090d75ac70b589f9a12d61457 | [
"Unlicense"
] | 14 | 2020-08-05T09:36:01.000Z | 2022-02-23T01:48:18.000Z | app/src/main/jni/comitton/PdfCrypt.cpp | yuma2a/ComittoNxA-Continued | 9d85c4f5753e534c3ff0cf83fe53df588872c8ff | [
"Unlicense"
] | 1 | 2021-11-13T14:23:07.000Z | 2021-11-13T14:23:07.000Z | app/src/main/jni/comitton/PdfCrypt.cpp | mryp/ComittoNxA | 9b46c267bff22c2090d75ac70b589f9a12d61457 | [
"Unlicense"
] | 4 | 2021-04-21T02:56:50.000Z | 2021-11-08T12:02:32.000Z | /*
MD5C.C - RSA Data Security, Inc., MD5 message-digest algorithm
Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991.
All rights reserved.
License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided
that such works are identified as "derived from the RSA Data
Security, Inc. MD5 Message-Digest Algorithm" in all material
mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
*/
//#include "fitz-internal.h"
#include <string.h>
#include <android/log.h>
#include "PdfCrypt.h"
//#define DEBUG
/*
* Compute an encryption key (PDF 1.7 algorithm 3.2)
*/
static const unsigned char padding[32] =
{
0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41,
0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa, 0x01, 0x08,
0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80,
0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a
};
/*
* PDF 1.7 algorithm 3.1 and ExtensionLevel 3 algorithm 3.1a
*
* Using the global encryption key that was generated from the
* password, create a new key that is used to decrypt individual
* objects and streams. This key is based on the object and
* generation numbers.
*/
int computeObjectKey(int method, BYTE *crypt_key, int crypt_len, int num, int gen, BYTE *res_key)
{
fz_md5 md5;
unsigned char message[5];
if (method == PDF_CRYPT_AESV3) {
memcpy(res_key, crypt_key, crypt_len / 8);
return crypt_len / 8;
}
fz_md5_init(&md5);
fz_md5_update(&md5, crypt_key, crypt_len / 8);
message[0] = (num) & 0xFF;
message[1] = (num >> 8) & 0xFF;
message[2] = (num >> 16) & 0xFF;
message[3] = (gen) & 0xFF;
message[4] = (gen >> 8) & 0xFF;
fz_md5_update(&md5, message, 5);
if (method == PDF_CRYPT_AESV2) {
fz_md5_update(&md5, (unsigned char *)"sAlT", 4);
}
fz_md5_final(&md5, res_key);
if (crypt_len / 8 + 5 > 16) {
return 16;
}
return crypt_len / 8 + 5;
}
static void
pdf_compute_encryption_key(pdf_crypt *crypt, unsigned char *password, int pwlen, unsigned char *key)
{
#ifdef DEBUG
LOGD("pdf_compute_encryption_key");
#endif
unsigned char buf[32];
unsigned int p;
int i, n;
fz_md5 md5;
n = crypt->length / 8;
/* Step 1 - copy and pad password string */
if (pwlen > 32)
pwlen = 32;
memcpy(buf, password, pwlen);
memcpy(buf + pwlen, padding, 32 - pwlen);
#ifdef DEBUG
LOGD("pdf_compute_encryption_key: 1-buf=%d,%d,%d,%d,%d,%d..., n=%d", (int)buf[0], (int)buf[1], (int)buf[2], (int)buf[3], (int)buf[4], (int)buf[5], n);
#endif
/* Step 2 - init md5 and pass value of step 1 */
fz_md5_init(&md5);
fz_md5_update(&md5, buf, 32);
#ifdef DEBUG
LOGD("pdf_compute_encryption_key: 2-buf=%d,%d,%d,%d,%d,%d..., n=%d", (int)buf[0], (int)buf[1], (int)buf[2], (int)buf[3], (int)buf[4], (int)buf[5], n);
#endif
/* Step 3 - pass O value */
fz_md5_update(&md5, crypt->o, 32);
/* Step 4 - pass P value as unsigned int, low-order byte first */
p = (unsigned int) crypt->p;
buf[0] = (p) & 0xFF;
buf[1] = (p >> 8) & 0xFF;
buf[2] = (p >> 16) & 0xFF;
buf[3] = (p >> 24) & 0xFF;
fz_md5_update(&md5, buf, 4);
#ifdef DEBUG
LOGD("pdf_compute_encryption_key: 3-buf=%d,%d,%d,%d,%d,%d..., n=%d", (int)buf[0], (int)buf[1], (int)buf[2], (int)buf[3], (int)buf[4], (int)buf[5], n);
#endif
/* Step 5 - pass first element of ID array */
fz_md5_update(&md5, crypt->id, crypt->id_len);
#ifdef DEBUG
LOGD("pdf_compute_encryption_key: id=%s,%d", crypt->id, crypt->id_len);
#endif
/* Step 6 (revision 4 or greater) - if metadata is not encrypted pass 0xFFFFFFFF */
if (crypt->r >= 4)
{
if (!crypt->encrypt_metadata)
{
buf[0] = 0xFF;
buf[1] = 0xFF;
buf[2] = 0xFF;
buf[3] = 0xFF;
fz_md5_update(&md5, buf, 4);
}
}
/* Step 7 - finish the hash */
fz_md5_final(&md5, buf);
#ifdef DEBUG
LOGD("pdf_compute_encryption_key: 4-buf=%d,%d,%d,%d,%d,%d..., n=%d", (int)buf[0], (int)buf[1], (int)buf[2], (int)buf[3], (int)buf[4], (int)buf[5], n);
#endif
/* Step 8 (revision 3 or greater) - do some voodoo 50 times */
if (crypt->r >= 3)
{
for (i = 0; i < 50; i++)
{
fz_md5_init(&md5);
fz_md5_update(&md5, buf, n);
fz_md5_final(&md5, buf);
}
}
/* Step 9 - the key is the first 'n' bytes of the result */
#ifdef DEBUG
LOGD("pdf_compute_encryption_key: 5-buf=%d,%d,%d,%d,%d,%d..., n=%d", (int)buf[0], (int)buf[1], (int)buf[2], (int)buf[3], (int)buf[4], (int)buf[5], n);
#endif
memcpy(key, buf, n);
}
/*
* Compute an encryption key (PDF 1.7 ExtensionLevel 3 algorithm 3.2a)
*/
static void
pdf_compute_encryption_key_r5(pdf_crypt *crypt, unsigned char *password, int pwlen, int ownerkey, unsigned char *validationkey)
{
unsigned char buffer[128 + 8 + 48];
fz_sha256 sha256;
fz_aes aes;
/* Step 2 - truncate UTF-8 password to 127 characters */
if (pwlen > 127)
pwlen = 127;
/* Step 3/4 - test password against owner/user key and compute encryption key */
memcpy(buffer, password, pwlen);
if (ownerkey)
{
memcpy(buffer + pwlen, crypt->o + 32, 8);
memcpy(buffer + pwlen + 8, crypt->u, 48);
}
else
memcpy(buffer + pwlen, crypt->u + 32, 8);
fz_sha256_init(&sha256);
fz_sha256_update(&sha256, buffer, pwlen + 8 + (ownerkey ? 48 : 0));
fz_sha256_final(&sha256, validationkey);
/* Step 3.5/4.5 - compute file encryption key from OE/UE */
memcpy(buffer + pwlen, crypt->u + 40, 8);
fz_sha256_init(&sha256);
fz_sha256_update(&sha256, buffer, pwlen + 8);
fz_sha256_final(&sha256, buffer);
/* clear password buffer and use it as iv */
memset(buffer + 32, 0, sizeof(buffer) - 32);
aes_setkey_dec(&aes, buffer, crypt->length);
aes_crypt_cbc(&aes, AES_DECRYPT, 32, buffer + 32, ownerkey ? crypt->oe : crypt->ue, crypt->key);
}
/*
* Computing the user password (PDF 1.7 algorithm 3.4 and 3.5)
* Also save the generated key for decrypting objects and streams in crypt->key.
*/
static void
pdf_compute_user_password(pdf_crypt *crypt, unsigned char *password, int pwlen, unsigned char *output)
{
#ifdef DEBUG
LOGD("pdf_compute_user_password: r=%d", crypt->r);
#endif
if (crypt->r == 2)
{
fz_arc4 arc4;
#ifdef DEBUG
LOGD("r==2", crypt->r);
#endif
pdf_compute_encryption_key(crypt, password, pwlen, crypt->key);
fz_arc4_init(&arc4, crypt->key, crypt->length / 8);
fz_arc4_encrypt(&arc4, output, padding, 32);
}
if (crypt->r == 3 || crypt->r == 4)
{
unsigned char xors[32];
unsigned char digest[16];
fz_md5 md5;
fz_arc4 arc4;
int i, x, n;
n = crypt->length / 8;
pdf_compute_encryption_key(crypt, password, pwlen, crypt->key);
fz_md5_init(&md5);
fz_md5_update(&md5, padding, 32);
fz_md5_update(&md5, crypt->id, crypt->id_len);
fz_md5_final(&md5, digest);
fz_arc4_init(&arc4, crypt->key, n);
fz_arc4_encrypt(&arc4, output, digest, 16);
for (x = 1; x <= 19; x++)
{
for (i = 0; i < n; i++)
xors[i] = crypt->key[i] ^ x;
fz_arc4_init(&arc4, xors, n);
fz_arc4_encrypt(&arc4, output, output, 16);
}
memcpy(output + 16, padding, 16);
}
if (crypt->r == 5)
{
pdf_compute_encryption_key_r5(crypt, password, pwlen, 0, output);
}
}
/*
* Authenticating the user password (PDF 1.7 algorithm 3.6
* and ExtensionLevel 3 algorithm 3.11)
* This also has the side effect of saving a key generated
* from the password for decrypting objects and streams.
*/
static int
pdf_authenticate_user_password(pdf_crypt *crypt, unsigned char *password, int pwlen)
{
#ifdef DEBUG
LOGD("pdf_authenticate_user_password");
#endif
unsigned char output[32];
pdf_compute_user_password(crypt, password, pwlen, output);
if (crypt->r == 2 || crypt->r == 5)
return memcmp(output, crypt->u, 32) == 0;
if (crypt->r == 3 || crypt->r == 4)
return memcmp(output, crypt->u, 16) == 0;
return 0;
}
/*
* Authenticating the owner password (PDF 1.7 algorithm 3.7
* and ExtensionLevel 3 algorithm 3.12)
* Generates the user password from the owner password
* and calls pdf_authenticate_user_password.
*/
static int
pdf_authenticate_owner_password(pdf_crypt *crypt, unsigned char *ownerpass, int pwlen)
{
unsigned char pwbuf[32];
unsigned char key[32];
unsigned char xors[32];
unsigned char userpass[32];
int i, n, x;
fz_md5 md5;
fz_arc4 arc4;
if (crypt->r == 5)
{
/* PDF 1.7 ExtensionLevel 3 algorithm 3.12 */
pdf_compute_encryption_key_r5(crypt, ownerpass, pwlen, 1, key);
return !memcmp(key, crypt->o, 32);
}
n = crypt->length / 8;
/* Step 1 -- steps 1 to 4 of PDF 1.7 algorithm 3.3 */
/* copy and pad password string */
if (pwlen > 32)
pwlen = 32;
memcpy(pwbuf, ownerpass, pwlen);
memcpy(pwbuf + pwlen, padding, 32 - pwlen);
/* take md5 hash of padded password */
fz_md5_init(&md5);
fz_md5_update(&md5, pwbuf, 32);
fz_md5_final(&md5, key);
/* do some voodoo 50 times (Revision 3 or greater) */
if (crypt->r >= 3)
{
for (i = 0; i < 50; i++)
{
fz_md5_init(&md5);
fz_md5_update(&md5, key, 16);
fz_md5_final(&md5, key);
}
}
/* Step 2 (Revision 2) */
if (crypt->r == 2)
{
fz_arc4_init(&arc4, key, n);
fz_arc4_encrypt(&arc4, userpass, crypt->o, 32);
}
/* Step 2 (Revision 3 or greater) */
if (crypt->r >= 3)
{
memcpy(userpass, crypt->o, 32);
for (x = 0; x < 20; x++)
{
for (i = 0; i < n; i++)
xors[i] = key[i] ^ (19 - x);
fz_arc4_init(&arc4, xors, n);
fz_arc4_encrypt(&arc4, userpass, userpass, 32);
}
}
return pdf_authenticate_user_password(crypt, userpass, 32);
}
int
pdf_authenticate_password(pdf_crypt *crypt, char *password)
{
#ifdef DEBUG
LOGD("pdf_authenticate_password");
#endif
if (crypt)
{
if (!password)
password = (char*)"";
if (pdf_authenticate_user_password(crypt, (unsigned char *)password, strlen(password)))
return 1;
if (pdf_authenticate_owner_password(crypt, (unsigned char *)password, strlen(password)))
return 1;
return 0;
}
return 1;
}
int
pdf_needs_password(pdf_crypt *crypt)
{
if (!crypt)
return 0;
if (pdf_authenticate_password(crypt, (char*)""))
return 0;
return 1;
}
int
pdf_has_permission(pdf_crypt *crypt, int p)
{
if (!crypt)
return 1;
return crypt->p & p;
}
unsigned char *
pdf_crypt_key(pdf_crypt *crypt)
{
if (crypt)
return crypt->key;
return NULL;
}
int
pdf_crypt_version(pdf_crypt *crypt)
{
if (crypt)
return crypt->v;
return 0;
}
int pdf_crypt_revision(pdf_crypt *crypt)
{
if (crypt)
return crypt->r;
return 0;
}
int
pdf_crypt_length(pdf_crypt *crypt)
{
if (crypt)
return crypt->length;
return 0;
}
| 24.414966 | 151 | 0.665181 |
8c4362e959450f80b6bf82e2f1ed5afb88ab06c5 | 13,332 | cpp | C++ | src/ui/inspectMode.cpp | averrin/lss | c2aa0486641fba15daceab3241122e387720c898 | [
"MIT"
] | 4 | 2018-07-09T20:53:06.000Z | 2018-07-12T07:10:19.000Z | src/ui/inspectMode.cpp | averrin/lss | c2aa0486641fba15daceab3241122e387720c898 | [
"MIT"
] | null | null | null | src/ui/inspectMode.cpp | averrin/lss | c2aa0486641fba15daceab3241122e387720c898 | [
"MIT"
] | null | null | null | #include "ui/inspectMode.hpp"
#include "ui/LSSApp.hpp"
#include "ui/fragment.hpp"
#include "lss/generator/room.hpp"
#include "lss/utils.hpp"
#include "ui/utils.hpp"
auto F = [](std::string c) { return std::make_shared<Fragment>(c); };
bool InspectMode::processKey(KeyEvent event) {
switch (event.getCode()) {
case SDL_SCANCODE_S:
highlightWhoCanSee = !highlightWhoCanSee;
app->state->invalidateSelection("change view mode");
render();
return true;
case SDL_SCANCODE_R:
showRooms = !showRooms;
app->state->invalidateSelection("change view mode");
render();
return true;
case SDL_SCANCODE_J:
case SDL_SCANCODE_H:
case SDL_SCANCODE_L:
if (event.isShiftDown()) {
showLightSources = !showLightSources;
app->state->invalidateSelection("change view mode");
render();
return true;
}
case SDL_SCANCODE_K:
case SDL_SCANCODE_Y:
case SDL_SCANCODE_U:
case SDL_SCANCODE_B:
case SDL_SCANCODE_N: {
auto d = ui_utils::getDir(event.getCode());
if (d == std::nullopt)
break;
auto nc = app->hero->currentLocation->getCell(
app->hero->currentLocation
->cells[app->state->cursor.y][app->state->cursor.x],
*utils::getDirectionByName(*d));
if (!nc)
break;
app->state->selectionClear();
app->state->setCursor({(*nc)->x, (*nc)->y});
render();
return true;
} break;
}
return false;
}
void InspectMode::render() {
auto location = app->hero->currentLocation;
auto cell = location->cells[app->state->cursor.y][app->state->cursor.x];
auto objects = location->getObjects(cell);
auto cc = app->hero->currentCell;
auto check = "<span color='green'>✔</span>";
app->state->selection.clear();
auto line = location->getLine(app->hero->currentCell, cell);
for (auto c : line) {
app->state->setSelection({{c->x, c->y}, COLORS::CURSOR_TRACE});
}
app->inspectState->setContent(
{F(fmt::format("Selected cell: <b>{}.{}</b>", cell->x, cell->y))});
app->inspectState->appendContent(State::END_LINE);
auto vs = "UNKNOWN";
if (cell->visibilityState == VisibilityState::SEEN) {
vs = "SEEN";
} else if (cell->visibilityState == VisibilityState::VISIBLE) {
vs = "VISISBLE";
}
app->inspectState->appendContent(
{F(fmt::format("Visibility state: <b>{}</b>", vs))});
app->inspectState->appendContent(State::END_LINE);
if (!app->debug && !app->hero->canSee(cell)) {
app->inspectState->appendContent(
{F(fmt::format("You cannot see this cell"))});
app->inspectState->appendContent(State::END_LINE);
return;
}
app->inspectState->appendContent(
{F(fmt::format("Type: <b>{}</b>", cell->type.name))});
app->inspectState->appendContent(State::END_LINE);
if (cell->type == CellType::UNKNOWN)
return;
app->inspectState->appendContent(
{F(fmt::format("Type <b>PASS</b>THROUGH: [<b>{}</b>]",
cell->type.passThrough ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
{F(fmt::format("Type <b>SEE</b>THROUGH: [<b>{}</b>]",
cell->type.passThrough ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(fmt::format(
"<b>PASS</b>THROUGH: [<b>{}</b>]", cell->passThrough ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(fmt::format(
"<b>SEE</b>THROUGH: [<b>{}</b>]", cell->passThrough ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(fmt::format(
"Illuminated: [<b>{}</b>]", cell->illuminated ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
{F(fmt::format("Illumination: <b>{}</b>", cell->illumination))});
app->inspectState->appendContent(State::END_LINE);
auto f = app->state->fragments[cell->y * app->state->width + cell->x];
// app->inspectState->appendContent({F(fmt::format(
// "Cell Illumination: <b>{}</b>", f->alpha))});
// app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(
fmt::format("Cell features count: <b>{}</b>", cell->features.size()))});
app->inspectState->appendContent(State::END_LINE);
if (cell->features.size() > 0) {
app->inspectState->appendContent({F("<b>Cell Features</b>")});
app->inspectState->appendContent(State::END_LINE);
}
for (auto f : cell->features) {
if (f == CellFeature::BLOOD) {
app->inspectState->appendContent(
{F(fmt::format("BLOOD: [<b>{}</b>]", check))});
}
if (f == CellFeature::CAVE) {
app->inspectState->appendContent(
{F(fmt::format("CAVE: [<b>{}</b>]", check))});
}
if (f == CellFeature::ACID) {
app->inspectState->appendContent(
{F(fmt::format("ACID: [<b>{}</b>]", check))});
}
if (f == CellFeature::FROST) {
app->inspectState->appendContent(
{F(fmt::format("FROST: [<b>{}</b>]", check))});
}
app->inspectState->appendContent(State::END_LINE);
}
app->inspectState->appendContent(State::END_LINE);
if (cell->room == nullptr) {
app->inspectState->appendContent(
{F(fmt::format("<b>Room is nullptr!</b>"))});
app->inspectState->appendContent(State::END_LINE);
} else {
app->inspectState->appendContent(
{F(fmt::format("Room @ <b>{}.{} [{}x{}]</b>", cell->room->x,
cell->room->y, cell->room->width, cell->room->height))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
{F(fmt::format("HALL: [<b>{}</b>]",
cell->room->type == RoomType::HALL ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
{F(fmt::format("PASSAGE: [<b>{}</b>]",
cell->room->type == RoomType::PASSAGE ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(fmt::format(
"Room features count: <b>{}</b>", cell->room->features.size()))});
app->inspectState->appendContent(State::END_LINE);
if (app->debug && showRooms) {
for (auto c : cell->room->cells) {
app->state->selection.push_back({{c->x, c->y}, "#811"});
}
}
if (cell->room->features.size() > 0) {
app->inspectState->appendContent({F("<b>Room Features</b>")});
app->inspectState->appendContent(State::END_LINE);
}
for (auto f : cell->room->features) {
if (f == RoomFeature::DUNGEON) {
app->inspectState->appendContent(
{F(fmt::format("DUNGEON: [<b>{}</b>]", check))});
}
if (f == RoomFeature::CAVE) {
app->inspectState->appendContent(
{F(fmt::format("CAVE: [<b>{}</b>]", check))});
}
app->inspectState->appendContent(State::END_LINE);
}
app->inspectState->appendContent(State::END_LINE);
}
app->inspectState->appendContent(
{F(fmt::format("Light sources: <b>{}</b>", cell->lightSources.size()))});
if (showLightSources) {
for (auto ls : cell->lightSources) {
auto c = ls->currentCell;
app->state->selection.push_back({{c->x, c->y}, "#1f1"});
}
}
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(fmt::format(
"Hero: [<b>{}</b>]", cell == app->hero->currentCell ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
{F(fmt::format("Hero can <b>pass</b>: [<b>{}</b>]",
cell->canPass(app->hero->traits) ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
{F(fmt::format("Hero can <b>see</b>: [<b>{}</b>]",
app->hero->canSee(cell) ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(
fmt::format("Distance to hero: <b>{}</b>",
sqrt(pow(cc->x - cell->x, 2) + pow(cc->y - cell->y, 2))))});
app->inspectState->appendContent(State::END_LINE);
if (cell->type == CellType::WALL)
return;
auto allEnemies = utils::castObjects<Enemy>(location->objects);
for (auto e : allEnemies) {
if (e->canSee(cell) && highlightWhoCanSee) {
app->inspectState->appendContent(
{F(fmt::format("<b>{} @ {}.{}</b> can see: [<b>{}</b>]", e->type.name,
e->currentCell->x, e->currentCell->y,
e->canSee(cell) ? check : " "))});
app->state->selection.push_back(
{{e->currentCell->x, e->currentCell->y}, "#aaaa88"});
app->inspectState->appendContent(State::END_LINE);
}
}
app->inspectState->appendContent(
{F(fmt::format("Objects count: <b>{}</b>", objects.size()))});
app->inspectState->appendContent(State::END_LINE);
if (objects.size() > 0) {
auto isDoor = utils::castObjects<Door>(objects).size() > 0;
app->inspectState->appendContent(
{F(fmt::format("Door: [<b>{}</b>]", isDoor ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
// auto isTorch = utils::castObjects<TorchStand>(objects).size() > 0;
// app->inspectState->appendContent(
// {F(fmt::format("Torch: [<b>{}</b>]", isTorch ? check : " "))});
// app->inspectState->appendContent(State::END_LINE);
// auto isStatue = utils::castObjects<Statue>(objects).size() > 0;
// app->inspectState->appendContent(
// {F(fmt::format("Statue: [<b>{}</b>]", isStatue ? check : " "))});
// app->inspectState->appendContent(State::END_LINE);
auto enemies = utils::castObjects<Enemy>(objects);
if (enemies.size() > 0) {
std::vector<std::string> enemyNames;
for (auto e : enemies) {
enemyNames.push_back(e->type.name);
app->inspectState->appendContent(
{F(fmt::format("<b>{} @ {}.{}</b> can see HERO: [<b>{}</b>]",
e->type.name, e->currentCell->x, e->currentCell->y,
e->canSee(cc) ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(fmt::format(
"Has glow: [<b>{}</b>]", e->hasLight() ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
auto glow = e->getGlow();
if (glow) {
app->inspectState->appendContent(
{F(fmt::format("Light: <b>{}</b>, stable: {}", (*glow).distance,
(*glow).stable))});
app->inspectState->appendContent(State::END_LINE);
}
app->inspectState->appendContent({F(fmt::format(
"<b>HP</b>: {:d}/{:d} ({:d})", int(e->HP(e.get())),
int(e->HP_MAX(e.get())), int(e->hp_max * e->strength)))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(F(fmt::format(
"<b>MP</b>: {:d}/{:d} ({:d})", int(e->MP(e.get())),
int(e->MP_MAX(e.get())), int(e->mp_max * e->intelligence))));
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(F(fmt::format("<b>Speed</b>: {} ({})",
e->SPEED(e.get()), e->speed)));
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(F(fmt::format("<b>Defence</b>: {:d}",
int(e->DEF(e.get())))));
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
F(fmt::format("<b>Damage</b>: {}", e->getDmgDesc())));
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F("Traits:")});
app->inspectState->appendContent(State::END_LINE);
for (auto t : e->traits) {
app->inspectState->appendContent(
{F(fmt::format(" * {}", t.name))});
app->inspectState->appendContent(State::END_LINE);
}
app->inspectState->appendContent({F("Inventory:")});
app->inspectState->appendContent(State::END_LINE);
for (auto s : e->equipment->slots) {
app->inspectState->appendContent({F(fmt::format(
" * {} -- {}", s->name,
s->item != nullptr ? s->item->getTitle(true) : "empty"))});
app->inspectState->appendContent(State::END_LINE);
}
}
app->inspectState->appendContent({F(
fmt::format("Enemies: <b>{}</b>", LibLog::utils::join(enemyNames, ", ")))});
app->inspectState->appendContent(State::END_LINE);
}
auto items = utils::castObjects<Item>(objects);
if (items.size() > 0) {
std::vector<std::string> itemNames;
for (auto i : items) {
itemNames.push_back(i->getFullTitle(true));
}
app->inspectState->appendContent(
{F(fmt::format("Items: <b>{}</b>", LibLog::utils::join(itemNames, ", ")))});
app->inspectState->appendContent(State::END_LINE);
}
}
app->state->invalidateSelection("move inspect cursor");
}
| 41.6625 | 91 | 0.578533 |
8c43e0e106645fcd7d0bdf1e0d71a9925193356b | 1,551 | cc | C++ | auxil/binpac/src/pac_datadep.cc | hugolin615/zeek-4.0.0-ele420520-spring2021 | 258e9b2ee1f2a4bd45c6332a75304793b7d44d40 | [
"Apache-2.0"
] | 1 | 2021-03-06T19:51:07.000Z | 2021-03-06T19:51:07.000Z | auxil/binpac/src/pac_datadep.cc | hugolin615/zeek-4.0.0-ele420520-spring2021 | 258e9b2ee1f2a4bd45c6332a75304793b7d44d40 | [
"Apache-2.0"
] | null | null | null | auxil/binpac/src/pac_datadep.cc | hugolin615/zeek-4.0.0-ele420520-spring2021 | 258e9b2ee1f2a4bd45c6332a75304793b7d44d40 | [
"Apache-2.0"
] | null | null | null | #include "pac_datadep.h"
#include "pac_expr.h"
#include "pac_id.h"
#include "pac_type.h"
DataDepElement::DataDepElement(DDE_Type type)
: dde_type_(type), in_traversal(false)
{
}
bool DataDepElement::Traverse(DataDepVisitor *visitor)
{
// Avoid infinite loop
if ( in_traversal )
return true;
if ( ! visitor->PreProcess(this) )
return false;
in_traversal = true;
bool cont = DoTraverse(visitor);
in_traversal = false;
if ( ! cont )
return false;
if ( ! visitor->PostProcess(this) )
return false;
return true;
}
Expr *DataDepElement::expr()
{
return static_cast<Expr *>(this);
}
Type *DataDepElement::type()
{
return static_cast<Type *>(this);
}
bool RequiresAnalyzerContext::PreProcess(DataDepElement *element)
{
switch ( element->dde_type() )
{
case DataDepElement::EXPR:
ProcessExpr(element->expr());
break;
default:
break;
}
// Continue traversal until we know the answer is 'yes'
return ! requires_analyzer_context_;
}
bool RequiresAnalyzerContext::PostProcess(DataDepElement *element)
{
return ! requires_analyzer_context_;
}
void RequiresAnalyzerContext::ProcessExpr(Expr *expr)
{
if ( expr->expr_type() == Expr::EXPR_ID )
{
requires_analyzer_context_ =
(requires_analyzer_context_ ||
*expr->id() == *analyzer_context_id ||
*expr->id() == *context_macro_id);
}
}
bool RequiresAnalyzerContext::compute(DataDepElement *element)
{
RequiresAnalyzerContext visitor;
element->Traverse(&visitor);
return visitor.requires_analyzer_context_;
}
| 20.142857 | 66 | 0.704707 |
8c44271c7bf0cc4c2dbd268a407221645e9f8866 | 1,296 | cxx | C++ | Libraries/QtVgCommon/vgSwatchCache.cxx | PinkDiamond1/vivia | 70f7fbed4b33b14d34de35c69b2b14df3514d720 | [
"BSD-3-Clause"
] | 14 | 2016-09-16T12:33:05.000Z | 2021-02-14T02:16:33.000Z | Libraries/QtVgCommon/vgSwatchCache.cxx | PinkDiamond1/vivia | 70f7fbed4b33b14d34de35c69b2b14df3514d720 | [
"BSD-3-Clause"
] | 44 | 2016-10-06T22:12:57.000Z | 2021-01-07T19:39:07.000Z | Libraries/QtVgCommon/vgSwatchCache.cxx | PinkDiamond1/vivia | 70f7fbed4b33b14d34de35c69b2b14df3514d720 | [
"BSD-3-Clause"
] | 17 | 2015-06-30T13:41:47.000Z | 2021-11-22T17:38:48.000Z | // This file is part of ViViA, and is distributed under the
// OSI-approved BSD 3-Clause License. See top-level LICENSE file or
// https://github.com/Kitware/vivia/blob/master/LICENSE for details.
#include "vgSwatchCache.h"
#include <QCache>
#include <QColor>
#include <QPixmap>
QTE_IMPLEMENT_D_FUNC(vgSwatchCache)
//-----------------------------------------------------------------------------
class vgSwatchCachePrivate
{
public:
vgSwatchCachePrivate(int ssize, int csize) :
size(ssize), cache(csize > 0 ? csize : 100) {}
int size;
mutable QCache<quint32, QPixmap> cache;
};
//-----------------------------------------------------------------------------
vgSwatchCache::vgSwatchCache(int swatchSize, int cacheSize) :
d_ptr(new vgSwatchCachePrivate(swatchSize, cacheSize))
{
}
//-----------------------------------------------------------------------------
vgSwatchCache::~vgSwatchCache()
{
}
//-----------------------------------------------------------------------------
QPixmap vgSwatchCache::swatch(const QColor& color) const
{
QTE_D_CONST(vgSwatchCache);
quint32 key = color.rgba();
if (!d->cache.contains(key))
{
QPixmap* pixmap = new QPixmap(d->size, d->size);
pixmap->fill(color);
d->cache.insert(key, pixmap);
}
return *d->cache[key];
}
| 26.44898 | 79 | 0.536265 |
8c443728e0b738837b7b6dab96af75f860b10cca | 21,272 | cc | C++ | elang/compiler/analysis/method_analyzer_test.cc | eval1749/elang | 5208b386ba3a3e866a5c0f0271280f79f9aac8c4 | [
"Apache-2.0"
] | 1 | 2018-01-27T22:40:53.000Z | 2018-01-27T22:40:53.000Z | elang/compiler/analysis/method_analyzer_test.cc | eval1749/elang | 5208b386ba3a3e866a5c0f0271280f79f9aac8c4 | [
"Apache-2.0"
] | 1 | 2016-01-29T00:54:49.000Z | 2016-01-29T00:54:49.000Z | elang/compiler/analysis/method_analyzer_test.cc | eval1749/elang | 5208b386ba3a3e866a5c0f0271280f79f9aac8c4 | [
"Apache-2.0"
] | null | null | null | // Copyright 2014-2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "elang/compiler/analysis/analysis.h"
#include "elang/compiler/analysis/class_analyzer.h"
#include "elang/compiler/analysis/method_analyzer.h"
#include "elang/compiler/analysis/namespace_analyzer.h"
#include "elang/compiler/analysis/name_resolver.h"
#include "elang/compiler/ast/class.h"
#include "elang/compiler/ast/expressions.h"
#include "elang/compiler/ast/factory.h"
#include "elang/compiler/ast/method.h"
#include "elang/compiler/ast/namespace.h"
#include "elang/compiler/ast/query/node_queries.h"
#include "elang/compiler/ast/statements.h"
#include "elang/compiler/ast/visitor.h"
#include "elang/compiler/compilation_session.h"
#include "elang/compiler/modifiers.h"
#include "elang/compiler/namespace_builder.h"
#include "elang/compiler/parameter_kind.h"
#include "elang/compiler/predefined_names.h"
#include "elang/compiler/semantics/factory.h"
#include "elang/compiler/semantics/nodes.h"
#include "elang/compiler/testing/analyzer_test.h"
#include "elang/compiler/token_type.h"
namespace elang {
namespace compiler {
//////////////////////////////////////////////////////////////////////
//
// Collector
//
class Collector final : private ast::Visitor {
public:
explicit Collector(ast::Method* method);
Collector() = default;
const std::vector<ast::Call*>& calls() const { return calls_; }
const std::vector<ast::NamedNode*> variables() const { return variables_; }
private:
// ast::Visitor expressions
void VisitCall(ast::Call* node);
// ast::Visitor statements
void VisitForEachStatement(ast::ForEachStatement* node);
void VisitVarStatement(ast::VarStatement* node);
std::vector<ast::Call*> calls_;
std::vector<ast::NamedNode*> variables_;
DISALLOW_COPY_AND_ASSIGN(Collector);
};
Collector::Collector(ast::Method* method) {
for (auto const parameter : method->parameters())
variables_.push_back(parameter);
auto const body = method->body();
if (!body)
return;
Traverse(body);
}
// ast::Visitor statements
void Collector::VisitForEachStatement(ast::ForEachStatement* node) {
variables_.push_back(node->variable());
ast::Visitor::DoDefaultVisit(node);
}
void Collector::VisitVarStatement(ast::VarStatement* node) {
for (auto const variable : node->variables()) {
variables_.push_back(variable);
auto const value = variable->expression();
if (!value)
continue;
Traverse(value);
}
}
// ast::Visitor expressions
void Collector::VisitCall(ast::Call* node) {
ast::Visitor::DoDefaultVisit(node);
calls_.push_back(node);
}
//////////////////////////////////////////////////////////////////////
//
// MyNamespaceBuilder
// Installs classes and methods for testing.
//
class MyNamespaceBuilder final : public NamespaceBuilder {
public:
explicit MyNamespaceBuilder(NameResolver* name_resolver);
~MyNamespaceBuilder() = default;
void Build();
private:
DISALLOW_COPY_AND_ASSIGN(MyNamespaceBuilder);
};
MyNamespaceBuilder::MyNamespaceBuilder(NameResolver* name_resolver)
: NamespaceBuilder(name_resolver) {
}
void MyNamespaceBuilder::Build() {
// public class Console {
// public static void WriteLine(String string);
// public static void WriteLine(String string, Object object);
// }
auto const console_class = NewClass("Console", "Object");
auto const factory = session()->semantic_factory();
auto const write_line =
factory->NewMethodGroup(console_class, NewName("WriteLine"));
factory->NewMethod(
write_line,
Modifiers(Modifier::Extern, Modifier::Public, Modifier::Static),
factory->NewSignature(SemanticOf("System.Void")->as<sm::Type>(),
{NewParameter(ParameterKind::Required, 0,
"System.String", "string")}));
factory->NewMethod(
write_line,
Modifiers(Modifier::Extern, Modifier::Public, Modifier::Static),
factory->NewSignature(
SemanticOf("System.Void")->as<sm::Type>(),
{NewParameter(ParameterKind::Required, 0, "System.String", "string"),
NewParameter(ParameterKind::Required, 0, "System.Object",
"object")}));
}
//////////////////////////////////////////////////////////////////////
//
// MethodAnalyzerTest
//
class MethodAnalyzerTest : public testing::AnalyzerTest {
protected:
MethodAnalyzerTest() = default;
~MethodAnalyzerTest() override = default;
std::string DumpSemanticTree(ast::Node* node);
// Collect all semantics
std::string QuerySemantics(TokenType token_type);
// Collect calls in method |method_name|.
std::string GetCalls(base::StringPiece method_name);
// Collect variables used in method |method_name|.
std::string VariablesOf(base::StringPiece method_name);
// ::testing::Test
void SetUp() final;
private:
DISALLOW_COPY_AND_ASSIGN(MethodAnalyzerTest);
};
class PostOrderTraverse final : public ast::Visitor {
public:
explicit PostOrderTraverse(ast::Node* node) { Traverse(node); }
std::vector<ast::Node*>::iterator begin() { return nodes_.begin(); }
std::vector<ast::Node*>::iterator end() { return nodes_.end(); }
private:
// ast::Visitor
void DoDefaultVisit(ast::Node* node) final {
ast::Visitor::DoDefaultVisit(node);
nodes_.push_back(node);
}
std::vector<ast::Node*> nodes_;
DISALLOW_COPY_AND_ASSIGN(PostOrderTraverse);
};
std::string MethodAnalyzerTest::DumpSemanticTree(ast::Node* start_node) {
auto const analysis = session()->analysis();
std::ostringstream ostream;
for (auto node : PostOrderTraverse(start_node)) {
auto const semantic = analysis->SemanticOf(node);
if (!semantic)
continue;
ostream << node << " : " << ToString(semantic) << std::endl;
}
return ostream.str();
}
std::string MethodAnalyzerTest::QuerySemantics(TokenType token_type) {
typedef std::pair<ast::Node*, sm::Semantic*> KeyValue;
std::vector<KeyValue> key_values;
for (auto const key_value : analysis()->all()) {
if (!key_value.first->token()->location().start_offset())
continue;
if (key_value.first->token() != token_type)
continue;
key_values.push_back(key_value);
}
std::sort(key_values.begin(), key_values.end(),
[](const KeyValue& a, const KeyValue& b) {
return a.first->token()->location().start_offset() <
b.first->token()->location().start_offset();
});
std::ostringstream ostream;
for (auto const key_value : key_values)
ostream << *key_value.second << std::endl;
return ostream.str();
}
std::string MethodAnalyzerTest::GetCalls(base::StringPiece method_name) {
auto const method = FindMember(method_name)->as<ast::Method>();
if (!method)
return std::string("Not found: ") + method_name.as_string();
Collector collector(method);
std::ostringstream ostream;
for (auto const call : collector.calls()) {
if (auto const method = analysis()->SemanticOf(call->callee()))
ostream << *method;
else
ostream << "Not resolved: " << *call;
ostream << std::endl;
}
return ostream.str();
}
std::string MethodAnalyzerTest::VariablesOf(base::StringPiece method_name) {
auto const method = FindMember(method_name)->as<ast::Method>();
if (!method)
return std::string("Not found: ") + method_name.as_string();
Collector collector(method);
std::ostringstream ostream;
for (auto const variable : collector.variables())
ostream << *analysis()->SemanticOf(variable) << std::endl;
return ostream.str();
}
// Install methods for testing
void MethodAnalyzerTest::SetUp() {
MyNamespaceBuilder(name_resolver()).Build();
}
//////////////////////////////////////////////////////////////////////
//
// Test cases
//
// Array access
TEST_F(MethodAnalyzerTest, ArrayAccess) {
Prepare(
"using System;"
"class Sample {"
" static void Main(String[] args) {"
" Console.WriteLine(args[1]);"
" }"
"}");
ASSERT_EQ("", Analyze());
EXPECT_EQ("System.String[]\n", QuerySemantics(TokenType::LeftSquareBracket));
}
TEST_F(MethodAnalyzerTest, ArrayAccessErrorArray) {
Prepare(
"using System;"
"class Sample {"
" static void Main(int args) {"
" Console.WriteLine(args[1]);"
" }"
"}");
ASSERT_EQ("TypeResolver.ArrayAccess.Array(79) args\n", Analyze());
}
TEST_F(MethodAnalyzerTest, ArrayAccessErrorIndex) {
Prepare(
"using System;"
"class Sample {"
" static void Main(String[] args) {"
" Console.WriteLine(args[\"foo\"]);"
" }"
"}");
ASSERT_EQ("TypeResolver.ArrayAccess.Index(89) \"foo\"\n", Analyze());
}
TEST_F(MethodAnalyzerTest, ArrayAccessErrorRank) {
Prepare(
"using System;"
"class Sample {"
" static void Main(int[] args) {"
" Console.WriteLine(args[1, 2]);"
" }"
"}");
ASSERT_EQ("TypeResolver.ArrayAccess.Rank(85) [\n", Analyze());
}
// Assignment
TEST_F(MethodAnalyzerTest, AssignField) {
Prepare(
"class Sample {"
" int length_;"
" void SetLength(int new_length) { length_ = new_length; }"
"}");
ASSERT_EQ("", Analyze());
auto const method = FindMember("Sample.SetLength")->as<ast::Method>();
EXPECT_EQ(
"length_ : System.Int32 Sample.length_\n"
"new_length : ReadOnly System.Int32 new_length\n",
DumpSemanticTree(method->body()));
}
TEST_F(MethodAnalyzerTest, AssignErrorNoThis) {
Prepare(
"class Sample {"
" int length_;"
" static void SetLength(int n) { length_ = n; }"
"}");
ASSERT_EQ("TypeResolver.Field.NoThis(69) =\n", Analyze());
}
TEST_F(MethodAnalyzerTest, AssignErrorVoid) {
Prepare(
"class Sample {"
" static void Foo() { int x = 0; x = Bar(); }"
" static void Bar() {}"
"}");
// TODO(eval1749) We should have specific error code for void binding.
EXPECT_EQ("TypeResolver.Expression.Invalid(51) Bar\n", Analyze());
}
// Binary operations
TEST_F(MethodAnalyzerTest, BinaryOperationArithmeticFloat64) {
Prepare(
"class Sample {"
" void Foo(float64 f64, float32 f32,"
" int8 i8, int16 i16, int32 i32, int64 i64,"
" uint8 u8, uint16 u16, uint32 u32, uint64 u64) {"
" var f64_f32 = f64 + f32;"
" var f64_f64 = f64 + f64;"
""
" var f64_i8 = f64 + i8;"
" var f64_i16 = f64 + i16;"
" var f64_i32 = f64 + i32;"
" var f64_i64 = f64 + i64;"
""
" var f64_u8 = f64 + u8;"
" var f64_u16 = f64 + u16;"
" var f64_u32 = f64 + u32;"
" var f64_u64 = f64 + u64;"
" }"
"}");
ASSERT_EQ("", Analyze());
EXPECT_EQ(
"System.Float64\n"
"System.Float64\n"
"System.Float64\n"
"System.Float64\n"
"System.Float64\n"
"System.Float64\n"
"System.Float64\n"
"System.Float64\n"
"System.Float64\n"
"System.Float64\n",
QuerySemantics(TokenType::Add));
}
TEST_F(MethodAnalyzerTest, BinaryOperationArithmeticFloat32) {
Prepare(
"class Sample {"
" void Foo(float64 f64, float32 f32,"
" int8 i8, int16 i16, int32 i32, int64 i64,"
" uint8 u8, uint16 u16, uint32 u32, uint64 u64) {"
" var f32_f32 = f32 + f32;"
" var f32_f64 = f32 + f64;"
""
" var f32_i8 = f32 + i8;"
" var f32_i16 = f32 + i16;"
" var f32_i32 = f32 + i32;"
" var f32_i64 = f32 + i64;"
""
" var f32_u8 = f32 + u8;"
" var f32_u16 = f32 + u16;"
" var f32_u32 = f32 + u32;"
" var f32_u64 = f32 + u64;"
" }"
"}");
ASSERT_EQ("", Analyze());
EXPECT_EQ(
"System.Float32\n"
"System.Float64\n"
"System.Float32\n"
"System.Float32\n"
"System.Float32\n"
"System.Float32\n"
"System.Float32\n"
"System.Float32\n"
"System.Float32\n"
"System.Float32\n",
QuerySemantics(TokenType::Add));
}
TEST_F(MethodAnalyzerTest, Comparison) {
Prepare(
"class Sample {"
" static bool Use(bool x) { return x; }"
" static void Foo(int x, int y) {"
" Use(x == y);"
" Use(x != y);"
" Use(x < y);"
" Use(x <= y);"
" Use(x > y);"
" Use(x >= y);"
" }"
"}");
ASSERT_EQ("", Analyze());
auto const method = FindMember("Sample.Foo")->as<ast::Method>();
EXPECT_EQ(
"Use : System.Bool Sample.Use(System.Bool)\n"
"x : ReadOnly System.Int32 x\n"
"y : ReadOnly System.Int32 y\n"
"operator==(x, y) : System.Int32\n"
"Use : System.Bool Sample.Use(System.Bool)\n"
"x : ReadOnly System.Int32 x\n"
"y : ReadOnly System.Int32 y\n"
"operator!=(x, y) : System.Int32\n"
"Use : System.Bool Sample.Use(System.Bool)\n"
"x : ReadOnly System.Int32 x\n"
"y : ReadOnly System.Int32 y\n"
"operator<(x, y) : System.Int32\n"
"Use : System.Bool Sample.Use(System.Bool)\n"
"x : ReadOnly System.Int32 x\n"
"y : ReadOnly System.Int32 y\n"
"operator<=(x, y) : System.Int32\n"
"Use : System.Bool Sample.Use(System.Bool)\n"
"x : ReadOnly System.Int32 x\n"
"y : ReadOnly System.Int32 y\n"
"operator>(x, y) : System.Int32\n"
"Use : System.Bool Sample.Use(System.Bool)\n"
"x : ReadOnly System.Int32 x\n"
"y : ReadOnly System.Int32 y\n"
"operator>=(x, y) : System.Int32\n",
DumpSemanticTree(method->body()));
}
// Conditional expression
TEST_F(MethodAnalyzerTest, Conditional) {
Prepare(
"class Sample {"
" void Main() { Foo(Cond() ? 12 : 34); }"
" bool Cond() { return true; }"
" int Foo(int x) { return x; }"
" }");
ASSERT_EQ("", Analyze());
}
TEST_F(MethodAnalyzerTest, ConditionalErrorBool) {
Prepare(
"class Sample {"
" void Main() { Foo(Cond() ? 12 : 34); }"
" int Cond() { return 12; }"
" int Foo(int x) { return x; }"
" }");
EXPECT_EQ("TypeResolver.Expression.NotBool(36) Cond\n", Analyze());
}
TEST_F(MethodAnalyzerTest, ConditionalErrorResult) {
Prepare(
"class Sample {"
" void Main() { Cond() ? 12 : 34.0; }"
" bool Cond() { return true; }"
" }");
EXPECT_EQ("TypeResolver.Conditional.NotMatch(41) 12 34\n", Analyze());
}
// 'do' statement
TEST_F(MethodAnalyzerTest, Do) {
Prepare(
"class Sample {"
" void Main() { do { Foo(12); } while (Cond()); }"
" bool Cond() { return true; }"
" int Foo(int x) { return x; }"
" }");
ASSERT_EQ("", Analyze());
}
TEST_F(MethodAnalyzerTest, DoErrorCondition) {
Prepare(
"class Sample {"
" void Main() { do { Foo(0); } while (Foo(1)); }"
" abstract Sample Foo(int x);"
" }");
EXPECT_EQ("TypeResolver.Expression.NotBool(54) Foo\n", Analyze());
}
// field
TEST_F(MethodAnalyzerTest, Field) {
Prepare(
"class Point {"
" int x_;"
" int y_;"
" int X() { return x_; }"
"}");
ASSERT_EQ("", Analyze());
auto const method = FindMember("Point.X")->as<ast::Method>();
EXPECT_EQ("x_ : System.Int32 Point.x_\n", DumpSemanticTree(method->body()));
}
TEST_F(MethodAnalyzerTest, FieldError) {
Prepare(
"class Sample {"
" int length_;"
" static int Length() { return length_; }"
"}");
EXPECT_EQ("TypeResolver.Field.NoThis(59) length_\n", Analyze());
}
// 'for' statement
TEST_F(MethodAnalyzerTest, For) {
Prepare(
"class Sample {"
" void Main() { for (Foo(3); Cond(); Foo(4)) { Foo(12); } }"
" bool Cond() { return true; }"
" int Foo(int x) { return x; }"
" }");
ASSERT_EQ("", Analyze());
}
TEST_F(MethodAnalyzerTest, ForErrorCondition) {
Prepare(
"class Sample {"
" void Main() { for (;Foo(1);) { Foo(0); } }"
" abstract Sample Foo(int x);"
" }");
EXPECT_EQ("TypeResolver.Expression.NotBool(38) Foo\n", Analyze());
}
// for each statement
TEST_F(MethodAnalyzerTest, ForEach) {
Prepare(
"using System;"
"class Sample {"
" static void Main(String[] args) {"
" for (var arg : args)"
" Console.WriteLine(arg);"
" }"
"}");
ASSERT_EQ("", Analyze());
EXPECT_EQ(
"ReadOnly System.String[] args\n"
"ReadOnly System.String arg\n",
VariablesOf("Sample.Main"));
}
TEST_F(MethodAnalyzerTest, ForEachError) {
Prepare(
"using System;"
"class Sample {"
" static void Main(String[] args) {"
" for (int arg : args)"
" Console.WriteLine(arg);"
" }"
"}");
EXPECT_EQ(
"TypeResolver.ForEach.ElementType(75) arg\n"
"TypeResolver.Expression.Invalid(110) arg\n",
Analyze());
}
// 'if' statement
TEST_F(MethodAnalyzerTest, If) {
Prepare(
"class Sample {"
" void Main() { if (Cond()) Foo(12); }"
" void Other() { if (Cond()) Foo(12); else Foo(34); }"
" bool Cond() { return true; }"
" int Foo(int x) { return x; }"
" }");
ASSERT_EQ("", Analyze());
}
TEST_F(MethodAnalyzerTest, IfErrorCondition) {
Prepare(
"class Sample {"
" void Main() { if (Foo(0)) Foo(12); else Foo(34); }"
" abstract Sample Foo(int x);"
" }");
EXPECT_EQ("TypeResolver.Expression.NotBool(36) Foo\n", Analyze());
}
// Increment
TEST_F(MethodAnalyzerTest, Increment) {
Prepare(
"class Sample {"
" void Foo() { var x = 0; ++x; x++; }"
"}");
ASSERT_EQ("", Analyze());
EXPECT_EQ("System.Int32\n", QuerySemantics(TokenType::Increment));
EXPECT_EQ("System.Int32\n", QuerySemantics(TokenType::PostIncrement));
}
// Method resolution
TEST_F(MethodAnalyzerTest, Method) {
Prepare(
"using System;"
"class Sample {"
" void Main() { Console.WriteLine(\"Hello world!\"); }"
" }");
ASSERT_EQ("", Analyze());
EXPECT_EQ("System.Void System.Console.WriteLine(System.String)\n",
GetCalls("Sample.Main"));
}
TEST_F(MethodAnalyzerTest, Method2) {
Prepare(
"class Sample {"
" static void Foo(char x) {}"
" static void Foo(int x) {}"
" static void Foo(float32 x) {}"
" static void Foo(float64 x) {}"
" void Main() { Foo('a'); Foo(123); Foo(12.3); }"
" }");
ASSERT_EQ("", Analyze());
EXPECT_EQ(
"System.Void Sample.Foo(System.Char)\n"
"System.Void Sample.Foo(System.Int32)\n"
"System.Void Sample.Foo(System.Float64)\n",
GetCalls("Sample.Main"));
}
TEST_F(MethodAnalyzerTest, Parameter) {
Prepare(
"class Sample {"
" int Foo(int ival) { return ival; }" // ReadOnly
" char Foo(char ch) { ch = 'a'; return ch; }" // Local
" void Foo(float32 f32) {}" // Void == no references
" }");
ASSERT_EQ("", Analyze());
ast::NameQuery query(session()->NewAtomicString(L"Foo"));
auto const nodes = session()->QueryAstNodes(query);
std::ostringstream ostream;
for (auto node : nodes) {
auto const method = node->as<ast::Method>();
for (auto const parameter : method->parameters()) {
auto const variable =
analysis()->SemanticOf(parameter)->as<sm::Variable>();
if (!variable)
continue;
ostream << *parameter->name() << " " << variable->storage() << std::endl;
}
}
EXPECT_EQ("ival ReadOnly\nch Local\nf32 Void\n", ostream.str());
}
TEST_F(MethodAnalyzerTest, ReturnError) {
Prepare(
"class Sample {"
" int Foo() { return; }"
" void Bar() { return 42; }"
" }");
EXPECT_EQ(
"Method.Return.Void(30) return\n"
"Method.Return.NotVoid(56) return\n",
Analyze());
}
TEST_F(MethodAnalyzerTest, TypeVariable) {
Prepare(
"using System;"
"class Sample {"
" static char Foo(char x) { return x; }"
" static int Foo(int x) {}"
" void Main() { var x = Foo('a'); Foo(x); }"
" }");
ASSERT_EQ("", Analyze());
EXPECT_EQ(
"System.Char Sample.Foo(System.Char)\n"
"System.Char Sample.Foo(System.Char)\n",
GetCalls("Sample.Main"));
}
// 'var' statement
TEST_F(MethodAnalyzerTest, VarVoid) {
Prepare(
"class Sample {"
" static void Foo() { int x = Bar(); }"
" static void Bar() {}"
"}");
// TODO(eval1749) We should have specific error code for void binding.
EXPECT_EQ("TypeResolver.Expression.Invalid(44) Bar\n", Analyze());
}
// 'while' statement
TEST_F(MethodAnalyzerTest, While) {
Prepare(
"class Sample {"
" void Main() { while (Cond()) { Foo(12); } }"
" bool Cond() { return true; }"
" int Foo(int x) { return x; }"
" }");
ASSERT_EQ("", Analyze());
}
TEST_F(MethodAnalyzerTest, WhileErrorCondition) {
Prepare(
"class Sample {"
" void Main() { while (Foo(1)) { Foo(0); } }"
" abstract Sample Foo(int x);"
" }");
EXPECT_EQ("TypeResolver.Expression.NotBool(39) Foo\n", Analyze());
}
} // namespace compiler
} // namespace elang
| 29.421853 | 80 | 0.599144 |
8c4761fc6234aa0a84b2b3511d7fb746f566f793 | 9,649 | cpp | C++ | experiments/src/globimap_test_polygons_mask.cpp | mlaass/globimap | 6bbcbf33cc39ed343662e6b98871dc6dfbc4648f | [
"MIT"
] | null | null | null | experiments/src/globimap_test_polygons_mask.cpp | mlaass/globimap | 6bbcbf33cc39ed343662e6b98871dc6dfbc4648f | [
"MIT"
] | null | null | null | experiments/src/globimap_test_polygons_mask.cpp | mlaass/globimap | 6bbcbf33cc39ed343662e6b98871dc6dfbc4648f | [
"MIT"
] | null | null | null | #include "globimap/counting_globimap.hpp"
#include "globimap_test_config.hpp"
#include <algorithm>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <limits>
#include <math.h>
#include <string>
#include <highfive/H5File.hpp>
#include <tqdm.hpp>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include "archive.h"
#include "loc.hpp"
#include "rasterizer.hpp"
#include "shapefile.hpp"
#include <H5Cpp.h>
namespace fs = std::filesystem;
namespace bg = boost::geometry;
namespace bgi = boost::geometry::index;
namespace bgt = boost::geometry::strategy::transform;
typedef bg::model::point<double, 2, bg::cs::cartesian> point_t;
typedef bg::model::box<point_t> box_t;
typedef bg::model::polygon<point_t> polygon_t;
typedef std::vector<polygon_t> poly_collection_t;
#ifndef TUM1_ICAML_ORG
const std::string base_path = "/mnt/G/datasets/atlas/";
const std::string vector_base_path = "/mnt/G/datasets/vector/";
const std::string experiments_path =
"/home/moritz/workspace/bgdm/globimap/experiments/";
#else
const std::string base_path = "/home/moritz/tf/pointclouds_2d/data/";
const std::string experiments_path = "/home/moritz/tf/globimap/experiments/";
const std::string vector_base_path = "/home/moritz/tf/vector/";
#endif
std::vector<std::string> datasets{"twitter_1mio_coords.h5",
"twitter_10mio_coords.h5",
"twitter_100mio_coords.h5"};
// std::vector<std::string> datasets{"twitter_200mio_coords.h5",
// "asia_200mio_coords.h5"};
std::vector<std::string> polygon_sets{"tl_2017_us_zcta510",
"Global_LSIB_Polygons_Detailed"};
template <typename T> std::string render_hist(std::vector<T> hist) {
std::stringstream ss;
ss << "[";
for (auto i = 0; i < hist.size(); ++i) {
ss << hist[i] << ((i < (hist.size() - 1)) ? ", " : "");
}
ss << "]";
return ss.str();
}
template <typename T>
std::string render_stat(const std::string &name, std::vector<T> stat) {
double stat_min = FLT_MAX;
double stat_max = 0;
double stat_mean = 0;
double stat_std = 0;
for (double v : stat) {
stat_min = std::min(stat_min, v);
stat_max = std::max(stat_max, v);
stat_mean += v;
}
stat_mean /= stat.size();
for (double v : stat) {
stat_std += pow((stat_mean - v), 2);
}
stat_std /= stat.size();
stat_std = sqrt(stat_std);
std::stringstream ss;
ss << "\"" << name << "\": {\n";
ss << "\"min\": " << stat_min << ",\n";
ss << "\"max\": " << stat_max << ",\n";
ss << "\"mean\": " << stat_mean << ",\n";
ss << "\"std\": " << stat_std << ",\n";
ss << "\"hist\": " << render_hist(globimap::make_histogram(stat, 1000))
<< "\n";
ss << "}";
return ss.str();
}
std::string
test_polys_mask(globimap::CountingGloBiMap<> &g, size_t poly_size,
std::function<std::vector<uint64_t>(size_t)> poly_gen) {
std::vector<uint32_t> errors_mask;
std::vector<uint32_t> errors_hash;
std::vector<uint32_t> diff_mask_hash;
std::vector<uint32_t> sizes;
std::vector<uint32_t> sums_mask;
std::vector<uint32_t> sums_hash;
std::vector<uint32_t> sums;
std::vector<double> errors_mask_pc;
std::vector<double> errors_hash_pc;
int n = 0;
std::cout << "polygons: " << poly_size << " ..." << std::endl;
auto P = tq::trange(poly_size);
P.set_prefix("mask for polygons ");
for (const auto &idx : P) {
auto raster = poly_gen(idx);
if (raster.size() > 0) {
auto hsfn = g.to_hashfn(raster);
auto mask_conf = globimap::FilterConfig{
g.config.hash_k, {{1, g.config.layers[0].logsize}}};
auto mask = globimap::CountingGloBiMap(mask_conf, false);
mask.put_all(raster);
auto res_raster = g.get_sum_raster_collected(raster);
auto res_mask = g.get_sum_masked(mask);
auto res_hashfn = g.get_sum_hashfn(raster);
sums.push_back(res_raster);
sums_mask.push_back(res_mask);
sums_hash.push_back(res_hashfn);
uint64_t err_mask = std::abs((int64_t)res_mask - (int64_t)res_raster);
uint64_t err_hash = std::abs((int64_t)res_hashfn - (int64_t)res_raster);
uint64_t hash_mask_diff =
std::abs((int64_t)res_mask - (int64_t)res_hashfn);
errors_mask.push_back(err_mask);
errors_hash.push_back(err_hash);
double div = (double)res_raster;
double err_mask_pc = ((double)err_mask) / div;
double err_hash_pc = ((double)err_hash) / div;
if (div == 0) {
err_mask_pc = (err_mask > 0 ? 1 : 0);
err_hash_pc = (err_hash > 0 ? 1 : 0);
}
errors_mask_pc.push_back(err_mask_pc);
errors_hash_pc.push_back(err_hash_pc);
sizes.push_back(raster.size() / 2);
n++;
}
}
std::stringstream ss;
ss << "{\n";
ss << "\"summary\": " << g.summary() << ",\n";
ss << "\"polygons\": " << n << ",\n";
ss << render_stat("errors_mask_pc", errors_mask_pc) << ",\n";
ss << render_stat("errors_hash_pc", errors_hash_pc) << ",\n";
ss << render_stat("errors_mask", errors_mask) << ",\n";
ss << render_stat("errors_hash", errors_hash) << ",\n";
ss << render_stat("sums", sums) << ",\n";
ss << render_stat("sums_mask", sums_mask) << ",\n";
ss << render_stat("sums_hash", sums_hash) << ",\n";
ss << render_stat("sizes", sizes) << "\n";
ss << "\n}" << std::endl;
// std::cout << ss.str();
return ss.str();
}
static void encode_dataset(globimap::CountingGloBiMap<> &g,
const std::string &name, const std::string &ds,
uint width, uint height) {
auto filename = base_path + ds;
auto batch_size = 4096;
std::cout << "Encode \"" << filename << "\" \nwith cfg: " << name
<< std::endl;
using namespace HighFive;
// we create a new hdf5 file
auto file = File(filename, File::ReadWrite);
std::vector<std::vector<double>> read_data;
// we get the dataset
DataSet dataset = file.getDataSet("coords");
using std::chrono::duration;
using std::chrono::duration_cast;
using std::chrono::high_resolution_clock;
using std::chrono::milliseconds;
auto t1 = high_resolution_clock::now();
std::vector<std::vector<double>> result;
auto shape = dataset.getDimensions();
int batches = std::floor(shape[0] / batch_size);
auto R = tq::trange(batches);
R.set_prefix("encoding batches ");
for (auto i : R) {
dataset.select({i * batch_size, 0}, {batch_size, 2}).read(result);
for (auto p : result) {
double x = (double)width * (((double)p[0] + 180.0) / 360.0);
double y = (double)height * (((double)p[0] + 90.0) / 180.0);
g.put({(uint64_t)x, (uint64_t)y});
}
}
auto t2 = high_resolution_clock::now();
duration<double, std::milli> insert_time = t2 - t1;
}
int main() {
std::vector<std::vector<globimap::LayerConfig>> cfgs;
get_configurations(cfgs, {16, 20, 24}, {8, 16, 32});
{
uint k = 8;
auto x = 0;
uint width = 2 * 8192, height = 2 * 8192;
std::string exp_name = "test_polygons_mask1";
save_configs(experiments_path + std::string("config_") + exp_name, cfgs);
mkdir((experiments_path + exp_name).c_str(), 0777);
for (auto c : cfgs) {
globimap::FilterConfig fc{k, c};
std::cout << "\n******************************************"
<< "\n******************************************" << std::endl;
std::cout << x << " / " << cfgs.size() << " fc: " << fc.to_string()
<< std::endl;
auto y = 0;
for (auto shp : polygon_sets) {
std::stringstream ss1;
ss1 << shp << "-" << width << "x" << height;
auto polyset_name = ss1.str();
std::stringstream ss;
ss << vector_base_path << polyset_name;
auto poly_path = ss.str();
int poly_count = 0;
for (auto e : fs::directory_iterator(poly_path))
poly_count += (e.is_regular_file() ? 1 : 0);
for (auto ds : datasets) {
std::stringstream fss;
fss << experiments_path << exp_name << "/" << exp_name << ".w"
<< width << "h" << height << "." << fc.to_string() << ds << "."
<< polyset_name << ".json";
if (file_exists(fss.str())) {
std::cout << "file already exists: " << fss.str() << std::endl;
} else {
std::cout << "run: " << fss.str() << std::endl;
std::ofstream out(fss.str());
auto g = globimap::CountingGloBiMap(fc, true);
encode_dataset(g, fc.to_string(), ds, width, height);
// g.detect_errors(0, 0, width, height);
std::cout << " COUNTER SIZE: " << g.counter.size() << std::endl;
std::cout << "test: " << polyset_name << std::endl;
out << test_polys_mask(g, poly_count, [&](int idx) {
std::vector<uint64_t> raster;
std::stringstream ss;
ss << poly_path << "/" << std::setw(8) << std::setfill('0')
<< idx;
auto filename = ss.str();
std::ifstream ifile(filename, std::ios::binary);
if (!ifile.is_open()) {
std::cout << "ERROR file doesn't exist: " << filename
<< std::endl;
return raster;
}
Archive<std::ifstream> a(ifile);
a >> raster;
ifile.close();
return raster;
});
out.close();
std::cout << "\n" << std::endl;
}
}
y++;
}
x++;
}
}
};
| 33.272414 | 79 | 0.5755 |