blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
59e8901da994f0c56ea5b6a41c9f241731cafd3d
5fd1cf1c3e4501e9e79a26b9b214689ef0154a0d
/src/audio/alsa/base.cpp
9949df3dcb1729ea5d0fd92c0aad0e01fa14d0c7
[ "BSD-2-Clause" ]
permissive
mekanix/libmaolan
67e6d2da8d7ceef66c55ad8d5cefbc624f9e4c0a
f71b890d582919496884586e37d5dd0cf1d942b8
refs/heads/master
2021-05-11T12:53:48.929542
2021-02-16T17:57:16
2021-02-16T17:57:16
117,667,721
0
0
null
null
null
null
UTF-8
C++
false
false
2,946
cpp
#include <iostream> #include "maolan/audio/alsa/base.hpp" #include "maolan/audio/alsa/config.hpp" #include "maolan/config.hpp" #include "maolan/constants.hpp" static void checkError(int &value, const std::string &message) { if (value != 0) { throw std::invalid_argument(message); } } using namespace maolan::audio; ALSA::ALSA(const std::string &deviceName, const int &chs, const snd_pcm_uframes_t &frames) : IO(0, true, true, deviceName), device{nullptr} { bool found = false; for (const auto iter : IO::devices) { if (iter == device) { found = true; device = (ALSAConfig *)iter; ++(device->count); } } int error = 0; if (!found) { device = new ALSAConfig; device->frames = frames; device->audioChannels = chs; error = snd_pcm_open(&(device->handle), deviceName.data(), SND_PCM_STREAM_PLAYBACK, 0); checkError(error, "snd_pcm_open"); if (device->handle == nullptr) { return; } // Allocate and init a hardware parameters object snd_pcm_hw_params_alloca(&(device->params)); try { error = snd_pcm_hw_params_any(device->handle, device->params); checkError(error, "params"); error = snd_pcm_hw_params_set_access(device->handle, device->params, SND_PCM_ACCESS_RW_INTERLEAVED); checkError(error, "access"); error = snd_pcm_hw_params_set_format(device->handle, device->params, SND_PCM_FORMAT_FLOAT); checkError(error, "format"); error = snd_pcm_hw_params_set_channels(device->handle, device->params, device->audioChannels); checkError(error, "channels"); error = snd_pcm_hw_params_set_rate_near(device->handle, device->params, &(Config::samplerate), 0); checkError(error, "sample rate"); error = snd_pcm_hw_params_set_period_size_near( device->handle, device->params, &(device->frames), 0); checkError(error, "period size"); error = snd_pcm_hw_params(device->handle, device->params); checkError(error, "hw params"); } catch (const std::invalid_argument &ex) { std::cerr << _type << " error: " << ex.what(); if (error != 0) { std::cerr << ' ' << snd_strerror(error) << std::endl; } std::cerr << '\n'; exit(1); } Config::audioBufferSize = device->frames; std::cerr << Config::audioBufferSize << '\n'; } frame = new float[Config::audioBufferSize * sizeof(float)]; } ALSA::~ALSA() { delete[] frame; --(device->count); if (device->count < 1) { for (auto iter = IO::devices.begin(); iter != IO::devices.end(); ++iter) { if (*iter == device) { devices.erase(iter); } } } } std::size_t ALSA::channels() const { return outputs.size(); }
[ "meka@tilda.center" ]
meka@tilda.center
85aa89a58e3833bb06fe9a670104279e838eeca3
916f2ce5a1fabd27bf597eb4c03bf39ab7bc16f2
/include/eigenml/core/model_traits.hpp
41d8913548721ccebe04f5d577c470ec992529f3
[ "Apache-2.0" ]
permissive
guillempalou/eigenml
ddefb072baab7a09f250cfd4146336e8488793e9
3991ddbfd01032cbbe698f6ec35eecbfe127e9b4
refs/heads/master
2021-01-10T10:59:50.456143
2016-01-10T17:54:00
2016-01-10T17:54:00
48,426,824
0
0
null
null
null
null
UTF-8
C++
false
false
490
hpp
#include <eigenml/core/types.hpp> namespace eigenml { template<ModelType modelType, class FeatureMatrix, class TargetMatrix> struct model_traits { // scalar types typedef typename FeatureMatrix::Scalar FeatureScalarType; typedef typename TargetMatrix::Scalar TargetScalarType; // sample types typedef typename FeatureMatrix::ConstRowXpr ConstSampleType; typedef typename FeatureMatrix::RowXpr SampleType; }; }
[ "gpalou@palantir.com" ]
gpalou@palantir.com
46051c43df1c5e53f221d4d74d8404e716c3474d
4e9ace268b7a9418b5d04d3da91f1ebddd515dc1
/C++/http/http.cpp
dcf632f94c85658301228b90d9670655afb22000
[]
no_license
anyks/aming
8cc2709ba244a26094d8084987e62136701fa170
1f221f65a561c345253f8397de9580e455f78fa4
refs/heads/master
2021-08-18T18:48:00.340849
2017-11-23T14:50:06
2017-11-23T14:50:06
108,564,023
3
0
null
null
null
null
UTF-8
C++
false
false
40,129
cpp
#include "http.h" // Устанавливаем пространство имен using namespace std; /** * split Функция разделения строк на составляющие * @param str строка для поиска * @param delim разделитель * @param v результирующий вектор */ void Http::split(const string &str, const string delim, vector <string> &v){ string::size_type i = 0; string::size_type j = str.find(delim); u_int len = delim.length(); // Выполняем разбиение строк while(j != string::npos){ v.push_back(str.substr(i, j - i)); i = ++j + (len - 1); j = str.find(delim, j); if(j == string::npos) v.push_back(str.substr(i, str.length())); } } /** * toCase Функция перевода в указанный регистр * @param str строка для перевода в указанных регистр * @param flag флаг указания типа регистра * @return результирующая строка */ string Http::toCase(string str, bool flag){ // Переводим в указанный регистр transform(str.begin(), str.end(), str.begin(), (flag ? ::toupper : ::tolower)); // Выводим результат return str; } /** * rtrim Функция усечения указанных символов с правой стороны строки * @param str строка для усечения * @param t список символов для усечения * @return результирующая строка */ string & Http::rtrim(string &str, const char * t){ str.erase(str.find_last_not_of(t) + 1); return str; } /** * ltrim Функция усечения указанных символов с левой стороны строки * @param str строка для усечения * @param t список символов для усечения * @return результирующая строка */ string & Http::ltrim(string &str, const char * t){ str.erase(0, str.find_first_not_of(t)); return str; } /** * trim Функция усечения указанных символов с правой и левой стороны строки * @param str строка для усечения * @param t список символов для усечения * @return результирующая строка */ string & Http::trim(string &str, const char * t){ return ltrim(rtrim(str, t), t); } /** * getHeaders Функция извлечения данных http запроса * @param str строка http запроса * @return данные http запроса */ Http::HttpData Http::getHeaders(string str){ // Создаем структуру данных HttpData data; // Проверяем существуют ли данные if(!str.empty()){ // Определяем конец запроса size_t end_query = str.find("\r\n\r\n"); // Если конец запроса найден if(end_query != string::npos){ // Массив строк vector <string> strings, params; // Выполняем разбиение строк split(str, "\r\n", strings); // Если строки найдены if(!strings.empty()){ // Позиция найденного разделителя size_t pos; // Запоминаем http запрос data.http = trim(strings[0]); // Переходим по всему массиву строк for(u_int i = 1; i < strings.size(); i++){ // Выполняем поиск разделитель pos = strings[i].find(":"); // Если разделитель найден if(pos != string::npos){ // Получаем ключ string key = strings[i].substr(0, pos); // Получаем значение string val = strings[i].substr(pos + 1, strings[i].length() - (pos + 1)); // Запоминаем найденны параметры data.headers.insert(pair <string, string>(toCase(trim(key)), trim(val))); // Запоминаем оригинальные параметры заголовков data.origin.insert(pair <string, string>(toCase(trim(key)), trim(key))); } } } // Получаем длину массива заголовков data.length = end_query + 4; } } // Выводим результат return data; } /** * Http::checkPort Функция проверки на качество порта * @param port входная строка якобы содержащая порт * @return результат проверки */ bool Http::checkPort(string port){ // Если строка существует if(!port.empty()){ // Проверяем цифры это или нет bool number = (port.find_first_not_of("0123456789") == string::npos); // Преобразуем строку в цифры if(number && ::atoi(port.c_str()) > 65535) // Если длина порта меньше максимального return false; // Если порт прошел все проверки else return true; } // Сообщаем что ничего не нашли return false; } /** * getConnection Функция извлечения данных подключения * @param str строка запроса * @return объект с данными запроса */ Http::connect Http::getConnection(string str){ // Полученные данные подключения connect data; // Выполняем поиск протокола size_t pos = str.find("://"); // Если протокол найден if(pos != (size_t) string::npos){ // Выполняем разделение на протокол vector <string> prt; // Функция разбиения на составляющие split(str, "://", prt); // Если протокол найден if(!prt.empty()){ // Запоминаем версию протокола data.protocol = prt[0]; // Запоминаем оставшуюся часть строки str = prt[1]; } // Очищаем память выделенную для вектора vector <string> ().swap(prt); // Устанавливаем протокол по умолчанию } else data.protocol = query.protocol; // Выполняем поиск порта и хоста pos = str.find(":"); // Если хост и порт найдены if(pos != (size_t) string::npos){ // Выполняем разделение на протокол vector <string> prt; // Функция разбиения на составляющие split(str, ":", prt); // Если порт и хост найдены if(!prt.empty()){ // Запоминаем хост data.host = prt[0]; // Запоминаем порт data.port = (checkPort(prt[1]) ? prt[1] : "80"); } // Очищаем память выделенную для вектора vector <string> ().swap(prt); // Если хост и порт не найдены } else { // Запоминаем хост data.host = str; // Запоминаем порт data.port = "80"; } // Устанавливаем номер порта в зависимости от типа протокола if(!strcmp(toCase(data.protocol).c_str(), "https") || !strcmp(toCase(query.method).c_str(), "connect")) data.port = "443"; // Устанавливаем версию протокола в зависимости от порта if(!strcmp(toCase(data.port).c_str(), "443")) data.protocol = "https"; // Запоминаем найденный хост str = data.host; // Выполняем поиск дирректории в хосте pos = str.find("/"); // Если дирректория найдена значит это не хост if(pos != (size_t) string::npos){ // Извлекаем название домена str = str.substr(0, pos); // Выполняем поиск точки в домене pos = str.find("."); // Если это домен if(pos != (size_t) string::npos) data.host = str; // Если это не домен то устанавливаем что это корень else data.host = "/"; } // Выводим результат return data; } /** * Http::getHeader Функция извлекает данные заголовка по его ключу * @param key ключ заголовка * @param headers массив заголовков * @return строка с данными заголовка */ string Http::getHeader(string key, map <string, string> headers){ // Проверяем существует ли такой заголовок if(headers.count(key) > 0) return headers.find(key)->second; // Сообщаем что ничего не найдено return ""; } /** * createHead Функция получения сформированного заголовка запроса */ void Http::createHead(){ // Очищаем заголовок query.request.clear(); // Создаем строку запроса query.request.append( toCase(query.method, true) + string(" ") + query.path + string(" ") + string("HTTP/") + query.version + string("\r\n") ); /* // Устанавливаем заголовок Host: query.request.append( string("Host: ") + query.host + string(":") + query.port + string("\r\n") ); */ // Устанавливаем заголовок Host: query.request.append(string("Host: ") + query.host + string("\r\n")); // Добавляем useragent if(!query.useragent.empty()) query.request.append(string("User-Agent: ") + query.useragent + string("\r\n")); // Добавляем остальные заголовки for(map <string, string>::iterator it = query.headers.begin(); it != query.headers.end(); ++it){ // Фильтруем заголовки if((it->first != "host") && (it->first != "user-agent") && (it->first != "connection") && (it->first != "proxy-authorization") && (it->first != "proxy-connection")){ // Если прокси является smarty //&& (it->first != "accept-encoding")){ // Добавляем оставшиеся заголовки query.request.append( query.origin[it->first] + string(": ") + it->second + string("\r\n") ); } } // Добавляем заголовок connection if(!query.connection.empty()){ // Устанавливаем заголовок подключения query.request.append(string("Connection: ") + query.connection + string("\r\n")); // Проверяем есть ли заголовок соединения прокси string pc = getHeader("proxy-connection", query.headers); // Если это не smarty // Добавляем заголовок закрытия подключения if(pc.empty()) query.request.append(string("Proxy-Connection: ") + query.connection + string("\r\n")); } // Запоминаем конец запроса query.request.append(string("\r\n")); } /** * isConnect Метод проверяет является ли метод, методом connect * @return результат проверки на метод connect */ bool Http::isConnect(){ // Сообщаем является ли метод, методом connect return !strcmp(query.method.c_str(), "connect"); } /** * isClose Метод проверяет должно ли быть закрыто подключение * @return результат проверки на закрытие подключения */ bool Http::isClose(){ // Сообщаем должно ли быть закрыто подключение return !strcmp(query.connection.c_str(), "close"); } /** * isHttps Метод проверяет является ли подключение защищенным * @return результат проверки на защищенное подключение */ bool Http::isHttps(){ // Сообщаем является ли продключение защищенным return !strcmp(query.protocol.c_str(), "https"); } /** * isAlive Метод определения нужно ли держать соединение для прокси * @return результат проверки */ bool Http::isAlive(){ // Если это версия протокола 1.1 и подключение установлено постоянное для прокси if(getVersion() > 1){ // Проверяем указан ли заголовок отключения if(!strcmp(query.connection.c_str(), "close")) return false; // Иначе сообщаем что подключение должно жить долго return true; // Проверяем указан ли заголовок удержания соединения } else if(!strcmp(query.connection.c_str(), "keep-alive")) return true; // Сообщаем что подключение жить не должно return false; } /** * isHttp Метод проверки на то http это или нет * @param buffer буфер входящих данных * @return результат проверки */ bool Http::isHttp(const string buffer){ // Если буфер существует if(!buffer.empty()){ // Создаем новый буфер char buf[4]; // Шаблон основных комманд char cmds[8][4] = {"get", "hea", "pos", "put", "pat", "del", "tra", "con"}; // Копируем нужное количество символов strncpy(buf, buffer.c_str(), 3); // Устанавливаем завершающий символ buf[3] = '\0'; // Переходим по всему массиву команд for(int i = 0; i < 8; i++) if(!strcmp(toCase(buf).c_str(), cmds[i])) return true; } // Сообщаем что это не http return false; } /** * generateHttp Метод генерации данных http запроса */ void Http::generateHttp(){ // Разделяем на составляющие команду vector <string> cmd; // Функция разбиения на составляющие split(query.http, " ", cmd); // Получаем размер массива size_t size = cmd.size(); // Если комманда существует if(size && (size == 3)){ // Запоминаем метод запроса query.method = toCase(cmd[0]); // Запоминаем путь запроса query.path = cmd[1]; // Разбиваем протокол и тип протокола на части vector <string> prt; // Функция разбиения на составляющие split(cmd[2], "/", prt); // Получаем размер массива size = prt.size(); // Если данные найдены if(size && (size == 2)){ // Запоминаем протокол запроса query.protocol = toCase(prt[0]); // Запоминаем версию протокола query.version = prt[1]; // Извлекаем данные хоста string host = getHeader("host", query.headers); // Извлекаем данные авторизации string auth = getHeader("proxy-authorization", query.headers); // Получаем заголовок Proxy-Connection string proxy_connection = getHeader("proxy-connection", query.headers); // Получаем данные юзерагента query.useragent = getHeader("user-agent", query.headers); // Получаем данные заголовока коннекта query.connection = toCase(getHeader("connection", query.headers)); // Если постоянное соединение не установлено if(!proxy_connection.empty()) query.connection = proxy_connection; // Если прокси является smarty // Если хост найден if(!host.empty()){ // Выполняем получение параметров подключения connect gcon = getConnection(query.path); // Выполняем получение параметров подключения connect scon = getConnection(host); // Создаем полный адрес запроса string fulladdr1 = scon.protocol + string("://") + scon.host; string fulladdr2 = fulladdr1 + "/"; string fulladdr3 = fulladdr1 + string(":") + scon.port; string fulladdr4 = fulladdr3 + "/"; // Определяем путь if(strcmp(toCase(query.method).c_str(), "connect") && (!strcmp(toCase(query.path).c_str(), toCase(host).c_str()) || !strcmp(toCase(query.path).c_str(), toCase(fulladdr1).c_str()) || !strcmp(toCase(query.path).c_str(), toCase(fulladdr2).c_str()) || !strcmp(toCase(query.path).c_str(), toCase(fulladdr3).c_str()) || !strcmp(toCase(query.path).c_str(), toCase(fulladdr4).c_str()))) query.path = "/"; // Выполняем удаление из адреса доменного имени else if(strstr(query.path.c_str(), fulladdr1.c_str()) != NULL){ // Запоминаем текущий путь string tmp_path = query.path; // Вырезаем домер из пути tmp_path = tmp_path.replace(0, fulladdr1.length(), ""); // Если путь существует if(!tmp_path.empty()) query.path = tmp_path; } // Запоминаем хост query.host = toCase(scon.host); // Запоминаем порт if(strcmp(scon.port.c_str(), gcon.port.c_str()) && !strcmp(gcon.port.c_str(), "80")){ // Запоминаем протокол query.protocol = toCase(scon.protocol); // Уделяем предпочтение 443 порту query.port = scon.port; // Запоминаем порт такой какой он есть } else if(gcon.port.find_first_not_of("0123456789") == string::npos) { // Запоминаем протокол query.protocol = toCase(gcon.protocol); // Запоминаем порт query.port = gcon.port; // Устанавливаем значение порта и протокола по умолчанию } else { // Запоминаем протокол query.protocol = "http"; // Устанавливаем http порт query.port = "80"; } } // Если авторизация найдена if(!auth.empty()){ // Выполняем разделение на тип и данные авторизации vector <string> lgn; // Функция разбиения на составляющие split(auth, " ", lgn); // Запоминаем размер массива size = lgn.size(); // Если данные получены if(size && (size == 2)){ // Запоминаем тип авторизации query.auth = toCase(lgn[0]); // Если это тип авторизация basic, тогда выполняем декодирования данных авторизации if(!strcmp(query.auth.c_str(), "basic")){ // Выполняем декодирование логина и пароля string dauth = base64_decode(lgn[1].c_str()); // Выполняем поиск авторизационных данных size_t pos = dauth.find(":"); // Если протокол найден if(pos != string::npos){ // Выполняем разделение на логин и пароль vector <string> lp; // Функция разбиения на составляющие split(dauth, ":", lp); // Запоминаем размер массива size = lp.size(); // Если данные получены if(size && (size == 2)){ // Запоминаем логин query.login = lp[0]; // Запоминаем пароль query.password = lp[1]; } // Очищаем память выделенную для вектора vector <string> ().swap(lp); } } } // Очищаем память выделенную для вектора vector <string> ().swap(lgn); } } // Очищаем память выделенную для вектора vector <string> ().swap(prt); } // Очищаем память выделенную для вектора vector <string> ().swap(cmd); // Генерируем параметры для запроса createHead(); } /** * modify Функция модифицирования ответных данных * @param data ссылка на данные полученные от сервера */ void Http::modify(vector <char> &data){ // Если заголовки не заняты тогда выполняем модификацию if(!_query.length){ // Выполняем парсинг http запроса _query = getHeaders(data.data()); // Проверяем есть ли заголовок соединения прокси string pc = getHeader("proxy-connection", _query.headers); // Если не smarty // Проверяем есть ли заголовок соединения string co = getHeader("connection", _query.headers); // Если заголовок не найден if(pc.empty() && !co.empty()){ // Поздиция конца заголовков int pos = -1; // Получаем данные ответа const char * headers = data.data(); // Ищем первое вхождение подстроки в строке const char * end_headers = strstr(headers, "\r\n\r\n"); // Если завершение заголовка найдено if(end_headers != NULL) pos = end_headers - headers; // Если позиция найдена if(pos > -1){ // Копируем заголовки string str(headers, pos); // Устанавливаем название прокси str.append(string("\r\nProxy-Agent: ") + appname + string("/") + appver); // Если нужно устанавливать название приложения // Добавляем заголовок закрытия подключения str.append(string("\r\nProxy-Connection: ") + co); // Если не smarty // Начальные и конечные блоки данных vector <char> first, last; // Заполняем первичные данные структуры first.assign(str.begin(), str.end()); // Заполняем последние данные структуры last.assign(data.begin() + pos, data.end()); // Объединяем блоки copy(last.begin(), last.end(), back_inserter(first)); // Заменяем первоначальный блок с данными data = first; } } // Очищаем объект _query.clear(); } } /** * Http::checkCharEnd Функция проверяет по массиву символов, достигнут ли конец запроса * @param buffer буфер с данными * @param size размер буфера * @param chs массив с символами завершающими запрос * @return результат проверки */ bool Http::checkCharEnd(const char * buffer, size_t size, vector <short> chs){ // Результат проверки bool check = false; // Выполняем реверс массива reverse(chs.begin(), chs.end()); // Переходим по всему массиву for(u_int i = 0; i < chs.size(); i++){ // Выполняем проверку завершающих символов if((short) buffer[size - (i + 1)] == chs[i]) check = true; else { check = false; break; } } // Выводим результат return check; } /** * checkEnd Функция проверки завершения запроса * @param buffer буфер с входящими данными * @param size размер входящих данных * @return результат проверки */ Http::HttpEnd Http::checkEnd(const char * buffer, size_t size){ // Создаем блок данных HttpEnd data; // Выполняем парсинг http запроса if(!_query.length) _query = getHeaders(buffer); // Если данные существуют if(!_query.http.empty()){ // Проверяем есть ли размер вложений string cl = getHeader("content-length", _query.headers); // Проверяем есть ли чанкование string ch = getHeader("transfer-encoding", _query.headers); // Проверяем есть ли закрытие соединения string cc = getHeader("connection", _query.headers); // Если найден размер вложений if(!cl.empty() && (cl.find_first_not_of("0123456789") == string::npos)){ // Определяем размер вложений int body_size = ::atoi(cl.c_str()); // Получаем размер вложения if(size >= (_query.length + body_size)){ // Заполняем структуру данными data.type = 4; // Заполняем размеры data.begin = _query.length; data.end = _query.length + body_size; } // Если это чанкование } else if(!ch.empty() && (ch.find("chunked") != string::npos)){ // Если конец строки найден if(((size > 5) && (_query.length < size)) // 0\r\n\r\n && (checkCharEnd(buffer, size, {48, 13, 10, 13, 10}) || checkCharEnd(buffer, size, {48, 10, 10}))){ // Заполняем структуру данными data.type = 5; // Заполняем размеры data.begin = _query.length; data.end = size; } // Если это автозакрытие подключения } else if(!cc.empty() && (cc == "close")){ // Если конец строки найден if(((size > 4) && (_query.length < size)) // \r\n\r\n && (checkCharEnd(buffer, size, {13, 10, 13, 10}) || checkCharEnd(buffer, size, {10, 10}))){ // Заполняем структуру данными data.type = 3; // Заполняем размеры data.begin = _query.length; data.end = size; } // Если указан тип данных но длина вложенных данных не указана } else if(!ch.empty()) data.type = 0; // Если найден конечный символ else if((short) buffer[size - 1] == 0) data.type = 2; // Если вложения не найдены else data.type = 1; // Если флаг установлен тогда очищаем структуру if(data.type) _query.clear(); // Ечищаем структуру если пришел мусор } else _query.clear(); // Выводим результат return data; } /** * parse Метод выполнения парсинга * @param buffer буфер входящих данных из сокета * @param size размер переданных данных * @return результат определения завершения запроса */ bool Http::parse(const char * buffer, size_t size){ // Выполняем проверку завершения передачи данных HttpEnd check = checkEnd(buffer, size); // Если флаг установлен if(check.type){ // Выполняем парсинг http запроса query = getHeaders(buffer); // Определяем тип запроса switch(check.type){ // Если присутствуют вложения case 3: case 4: { // Извлекаем указанные данные query.entitybody.assign(buffer + check.begin, buffer + check.end); // Добавляем завершающий байт query.entitybody.push_back('\0'); } break; } // Генерируем данные generateHttp(); // Сообщаем что все удачно получено return true; } // Сообщаем что данные не получены return false; } /** * brokenRequest Метод получения ответа (неудачного отправленного запроса) * @return ответ в формате html */ Http::HttpQuery Http::brokenRequest(){ // Устанавливаем дефолтное название прокси string defname = "ProxyAnyks/1.0"; // Определяем позицию дефолтного названия size_t pos = html[9].find(defname); // Результирующая строка string result; // Если это домен if(pos != string::npos){ // Заменяем дефолтное название на указанное result = html[9].replace(pos, defname.length(), appname + string("/") + appver); } // Выводим шаблон сообщения о неудачном отправленном запросе result = html[9]; // Данные для вывода HttpQuery data(501, result); // Выводим результат return data; } /** * faultConnect Метод получения ответа (неудачного подключения к удаленному серверу) * @return ответ в формате html */ Http::HttpQuery Http::faultConnect(){ // Устанавливаем дефолтное название прокси string defname = "ProxyAnyks/1.0"; // Определяем позицию дефолтного названия size_t pos = html[6].find(defname); // Результирующая строка string result; // Если это домен if(pos != string::npos){ // Заменяем дефолтное название на указанное result = html[6].replace(pos, defname.length(), appname + string("/") + appver); } // Выводим шаблон сообщения о неудачном подключении result = html[6]; // Данные для вывода HttpQuery data(502, result); // Выводим результат return data; } /** * faultAuth Метод получения ответа (неудачной авторизации) * @return ответ в формате html */ Http::HttpQuery Http::faultAuth(){ // Устанавливаем дефолтное название прокси string defname = "ProxyAnyks/1.0"; // Определяем позицию дефолтного названия size_t pos = html[5].find(defname); // Результирующая строка string result; // Если это домен if(pos != string::npos){ // Выводим шаблон сообщения о неудачной авторизации result = html[5].replace(pos, defname.length(), appname + string("/") + appver); } // Выводим шаблон сообщения о неудачной авторизации result = html[5]; // Данные для вывода HttpQuery data(403, result); // Выводим результат return data; } /** * requiredAuth Метод получения ответа (запроса ввода логина и пароля) * @return ответ в формате html */ Http::HttpQuery Http::requiredAuth(){ // Устанавливаем дефолтное название прокси string defname = "ProxyAnyks/1.0"; // Определяем позицию дефолтного названия size_t pos = html[2].find(defname); // Результирующая строка string result; // Если это домен if(pos != string::npos){ // Выводим шаблон сообщения о неудачной авторизации result = html[2].replace(pos, defname.length(), appname + string("/") + appver); } // Выводим шаблон сообщения о требовании авторизации result = html[2]; // Данные для вывода HttpQuery data(407, result); // Выводим результат return data; } /** * authSuccess Метод получения ответа (подтверждения авторизации) * @return ответ в формате html */ Http::HttpQuery Http::authSuccess(){ // Устанавливаем дефолтное название прокси string defname = "ProxyAnyks/1.0"; // Определяем позицию дефолтного названия size_t pos = html[0].find(defname); // Результирующая строка string result; // Если это домен if(pos != string::npos){ // Выводим шаблон сообщения о неудачной авторизации result = html[0].replace(pos, defname.length(), appname + string("/") + appver); } // Выводим шаблон сообщения о том что авторизация пройдена result = html[0]; // Данные для вывода HttpQuery data(200, result); // Выводим результат return data; } /** * getQuery Метод получения сформированного http запроса * @return сформированный http запрос */ Http::HttpQuery Http::getQuery(){ // Данные для вывода HttpQuery data(200, query.request, query.entitybody); // Выводим результат return data; } /** * getMethod Метод получения метода запроса * @return метод запроса */ string Http::getMethod(){ // Выводим значение переменной return query.method; } /** * getHost Метод получения хоста запроса * @return хост запроса */ string Http::getHost(){ // Выводим значение переменной return query.host; } /** * getPath Метод получения пути запроса * @return путь запроса */ string Http::getPath(){ // Выводим значение переменной return query.path; } /** * getProtocol Метод получения протокола запроса * @return протокол запроса */ string Http::getProtocol(){ // Выводим значение переменной return query.protocol; } /** * getAuth Метод получения метода авторизации запроса * @return метод авторизации */ string Http::getAuth(){ // Выводим значение переменной return query.auth; } /** * getLogin Метод получения логина авторизации запроса * @return логин авторизации */ string Http::getLogin(){ // Выводим значение переменной return query.login; } /** * getPassword Метод получения пароля авторизации запроса * @return пароль авторизации */ string Http::getPassword(){ // Выводим значение переменной return query.password; } /** * getUseragent Метод получения юзерагента запроса * @return юзерагент */ string Http::getUseragent(){ // Выводим значение переменной return query.useragent; } /** * getPort Метод получения порта запроса * @return порт удаленного ресурса */ u_int Http::getPort(){ // Выводим значение переменной return (!query.port.empty() ? ::atoi(query.port.c_str()) : 80); } /** * getVersion Метод получения версии протокола запроса * @return версия протокола запроса */ float Http::getVersion(){ // Выводим значение переменной return (!query.version.empty() ? ::atof(query.version.c_str()) : 1.0); } /** * setMethod Метод установки метода запроса * @param str строка с данными для установки */ void Http::setMethod(const string str){ // Запоминаем данные query.method = str; // Выполняем генерацию результирующего запроса createHead(); } /** * setHost Метод установки хоста запроса * @param str строка с данными для установки */ void Http::setHost(const string str){ // Запоминаем данные query.host = str; // Выполняем генерацию результирующего запроса createHead(); } /** * setPort Метод установки порта запроса * @param number номер порта для установки */ void Http::setPort(u_int number){ // Запоминаем данные query.port = to_string(number); // Выполняем генерацию результирующего запроса createHead(); } /** * setPath Метод установки пути запроса * @param str строка с данными для установки */ void Http::setPath(const string str){ // Запоминаем данные query.path = str; // Выполняем генерацию результирующего запроса createHead(); } /** * setProtocol Метод установки протокола запроса * @param str строка с данными для установки */ void Http::setProtocol(const string str){ // Запоминаем данные query.protocol = str; // Выполняем генерацию результирующего запроса createHead(); } /** * setVersion Метод установки версии протокола запроса * @param number номер версии протокола */ void Http::setVersion(float number){ // Запоминаем данные query.version = to_string(number); // Если это всего один символ тогда дописываем ноль if(query.version.length() == 1) query.version += ".0"; // Выполняем генерацию результирующего запроса createHead(); } /** * setClose Метод установки принудительного отключения после запроса */ void Http::setClose(){ // Запоминаем данные query.connection = "close"; // Выполняем генерацию результирующего запроса createHead(); } /** * setAuth Метод установки метода авторизации запроса * @param str строка с данными для установки */ void Http::setAuth(const string str){ // Запоминаем данные query.auth = str; // Выполняем генерацию результирующего запроса createHead(); } /** * setUseragent Метод установки юзерагента запроса * @param str строка с данными для установки */ void Http::setUseragent(const string str){ // Запоминаем данные query.useragent = str; // Выполняем генерацию результирующего запроса createHead(); } /** * Http::clear Метод очистки всех полученных данных */ void Http::clear(){ // Очищаем заголовки _query.clear(); query.clear(); } /** * Http Конструктор * @param str строка содержащая название сервиса */ Http::Http(const string str, string ver){ // Если имя передано то запоминаем его appname = str; // Устанавливаем версию системы appver = ver; } /** * Http Деструктор */ Http::~Http(){ // Очищаем заголовки _query.clear(); query.clear(); // Очищаем память выделенную для вектора vector <char> ().swap(query.entitybody); }
[ "forman@anyks.com" ]
forman@anyks.com
dda37aee35f2d92cb208ea345fed052b6cd8824d
09a4e01d9af958c27dea623ba4269b945b43cc1a
/src/HCSearchLib/InitialStateFunction.cpp
e81049d8411092d1f7cd3a630af421219847c4eb
[ "MIT" ]
permissive
jizhihang/hcsearch_cv
bd84c72481d69bc9bb7eea2181869a81fd4f717a
f25c575a7fe4eb0313d0dcf976482e4b065b8ed8
refs/heads/master
2021-01-20T13:21:45.593003
2016-06-08T12:53:28
2016-06-08T12:53:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,805
cpp
#include "MyFileSystem.hpp" #include "InitialStateFunction.hpp" #include "Globals.hpp" namespace HCSearch { /**************** Initial Prediction Functions ****************/ /**************** Logistic Regression ****************/ const double LogRegInit::DEFAULT_C = 10; const double LogRegInit::BINARY_CONFIDENCE_THRESHOLD = 0.75; LogRegInit::LogRegInit() { if (Global::settings->RANK == 0) trainClassifier(); #ifdef USE_MPI EasyMPI::EasyMPI::synchronize("INITPREDSTART", "INITPREDEND"); #endif } LogRegInit::~LogRegInit() { } ImgLabeling LogRegInit::getInitialPrediction(ImgFeatures& X) { string initStatePath = Global::settings->paths->INPUT_INITIAL_STATES_DIR + X.getFileName() + ".txt"; // if initial states file doesn't exist, generate prediction in temp folder if (!MyFileSystem::FileSystem::checkFileExists(initStatePath)) { LOG() << "Setting up initial state..." << endl; // output features imgfeatures2liblinear(X, Global::settings->paths->OUTPUT_INITFUNC_FEATURES_FILE); // perform IID SVM prediction on patches stringstream ssPredictInitFuncCmd; ssPredictInitFuncCmd << Global::settings->cmds->LIBLINEAR_PREDICT_CMD << " -b 1 " << Global::settings->paths->OUTPUT_INITFUNC_FEATURES_FILE << " " + Global::settings->paths->OUTPUT_INITFUNC_MODEL_FILE << " " << Global::settings->paths->OUTPUT_INITFUNC_PREDICT_FILE; int retcode = MyFileSystem::Executable::executeRetriesFatal(ssPredictInitFuncCmd.str()); initStatePath = Global::settings->paths->OUTPUT_INITFUNC_PREDICT_FILE; } ImgLabeling Y = ImgLabeling(); Y.graph = LabelGraph(); Y.graph.adjList = X.graph.adjList; Y.graph.nodesData = VectorXi::Ones(X.getNumNodes()); // now need to get labels data and confidences... // read in initial prediction liblinear2imglabeling(Y, initStatePath); // eliminate 1-islands eliminateIslands(Y); return Y; } void LogRegInit::eliminateIslands(ImgLabeling& Y) { if (!Global::settings->CLASSES.backgroundClassExists()) return; const int numNodes = Y.getNumNodes(); for (int node = 0; node < numNodes; node++) { if (!Global::settings->CLASSES.classLabelIsBackground(Y.getLabel(node)) && !hasForegroundNeighbors(Y, node)) { int label = Y.getLabel(node); double probEstimate = Y.confidences(node, Global::settings->CLASSES.getClassIndex(label)); if (probEstimate < BINARY_CONFIDENCE_THRESHOLD) { Y.graph.nodesData(node) = Global::settings->CLASSES.getBackgroundLabel(); } } } } // Train logistic regression model void LogRegInit::trainClassifier() { // train on IID classifier first for initial function string fileName = Global::settings->paths->OUTPUT_INITFUNC_MODEL_FILE; ifstream fh(fileName.c_str()); if (!fh.is_open()) { LOG() << "Training log reg initial function model..." << endl; stringstream ssTrainInitFuncCmd; // LOGISTIC REGRESSION ssTrainInitFuncCmd << Global::settings->cmds->LIBLINEAR_TRAIN_CMD << " -s 7 -c " << DEFAULT_C << " "; // the rest of the training cmd ssTrainInitFuncCmd << Global::settings->paths->INPUT_INITFUNC_TRAINING_FILE << " " + Global::settings->paths->OUTPUT_INITFUNC_MODEL_FILE; // run command MyFileSystem::Executable::executeRetries(ssTrainInitFuncCmd.str()); LOG() << "...Finished training initial function model." << endl; } else { LOG() << "Initial function model found. Using it..." << endl; fh.close(); } } void LogRegInit::imgfeatures2liblinear(ImgFeatures& X, string filename) { const int numNodes = X.getNumNodes(); const int featureDim = X.getFeatureDim(); ofstream fh(filename.c_str()); if (fh.is_open()) { for (int node = 0; node < numNodes; node++) { fh << "1"; // dummy class for prediction for (int feat = 0; feat < featureDim; feat++) { if (X.getFeature(node, feat) != 0) { fh << " " << feat+1 << ":" << X.getFeature(node, feat); } } fh << endl; } fh.close(); } else { LOG(ERROR) << "cannot open file for writing LIBLINEAR/LIBSVM features!"; abort(); } } void LogRegInit::liblinear2imglabeling(ImgLabeling& Y, string filename) { const int numClasses = Global::settings->CLASSES.numClasses(); const int numNodes = Y.getNumNodes(); vector<int> labelOrderFound; int lineIndex = 0; string line; ifstream fh(filename.c_str()); if (fh.is_open()) { int numClassesFound = 0; while (fh.good() && lineIndex < numNodes+1) { getline(fh, line); if (lineIndex == 0) { // parse first line to get label order stringstream ss(line); string token; int columnIndex = 0; while (getline(ss, token, ' ')) { // first token on first line should be "labels" if (columnIndex == 0) { if (token.compare("labels") != 0) { LOG(ERROR) << "parsing invalid prediction file while trying to get liblinear confidences!"; fh.close(); abort(); } columnIndex++; continue; } int label = atoi(token.c_str()); labelOrderFound.push_back(label); columnIndex++; } numClassesFound = labelOrderFound.size(); if (numClassesFound == 0) { Y.confidencesAvailable = false; } else if (numClassesFound != numClasses) { LOG(ERROR) << "number of classes found in prediction file while trying to get liblinear confidences is not correct!" << endl << "\texpected: " << numClasses << endl << "\tfound: " << numClassesFound << endl << "\tglobal: " << Global::settings->CLASSES.numClasses(); LOG(ERROR) << "parsing invalid prediction file while trying to get liblinear confidences!"; fh.close(); abort(); } else { Y.confidencesAvailable = true; Y.confidences = MatrixXd::Zero(numNodes, numClasses); } } else if (!line.empty()) { // parse line to get label and confidences stringstream ss(line); string token; int columnIndex = 0; while (getline(ss, token, ' ')) { if (columnIndex == 0) { int nodeIndex = lineIndex-1; Y.graph.nodesData(nodeIndex) = atoi(token.c_str()); } else if (Y.confidencesAvailable) { int nodeIndex = lineIndex-1; int classIndex = Global::settings->CLASSES.getClassIndex(labelOrderFound[columnIndex-1]); Y.confidences(nodeIndex, classIndex) = atof(token.c_str()); } columnIndex++; } } lineIndex++; } fh.close(); } else { LOG(ERROR) << "cannot open file for reading LIBLINEAR/LIBSVM confidences!"; abort(); } } bool LogRegInit::hasForegroundNeighbors(ImgLabeling& Y, int node) { int nodeLabel = Y.getLabel(node); NeighborSet_t neighbors = Y.graph.adjList[node]; bool hasNeighbors = false; for (NeighborSet_t::iterator it = neighbors.begin(); it != neighbors.end(); ++it) { int neighborNode = *it; int neighborLabel = Y.getLabel(neighborNode); if (!Global::settings->CLASSES.classLabelIsBackground(neighborLabel)) { hasNeighbors = true; break; } } return hasNeighbors; } /**************** Logistic Regression with Mutex ****************/ const int MutexLogRegInit::MUTEX_THRESHOLD = 100; MutexLogRegInit::MutexLogRegInit() { this->initialized = false; } MutexLogRegInit::~MutexLogRegInit() { } ImgLabeling MutexLogRegInit::getInitialPrediction(ImgFeatures& X) { ImgLabeling Y = LogRegInit::getInitialPrediction(X); if (this->initialized) { LOG() << "Checking if initial prediction satisfies mutex..." << endl; bool satisfied = false; const int numNodes = X.getNumNodes(); const int numClasses = Global::settings->CLASSES.numClasses(); VectorXi confidenceIndices = VectorXi::Zero(numNodes); while (!satisfied) { satisfied = true; for (int node1 = 0; node1 < numNodes && satisfied; node1++) { for (int node2 = 0; node2 < numNodes && satisfied; node2++) { if (node1 == node2) continue; // get node features and label VectorXd nodeFeatures1 = X.graph.nodesData.row(node1); double nodeLocationX1 = X.getNodeLocationX(node1); double nodeLocationY1 = X.getNodeLocationY(node1); int nodeLabel1 = Y.getLabel(node1); VectorXd nodeFeatures2 = X.graph.nodesData.row(node2); double nodeLocationX2 = X.getNodeLocationX(node2); double nodeLocationY2 = X.getNodeLocationY(node2); int nodeLabel2 = Y.getLabel(node2); vector<int> node1ConfidentLabels = Y.getLabelsByConfidence(node1); if (nodeLabel1 != nodeLabel2) { if (nodeLocationX1 < nodeLocationX2) { string mutexKey = mutexStringHelper(nodeLabel1, nodeLabel2, "L"); if (this->mutex.count(mutexKey) == 0) satisfied = false; else if (this->mutex[mutexKey] <= MUTEX_THRESHOLD) satisfied = false; if (!satisfied) { LOG(DEBUG) << "not satisfied: " << node1 << ", " << node2; if (confidenceIndices(node1)+1 >= numClasses) { satisfied = true; } else { Y.graph.nodesData(node1) = node1ConfidentLabels[confidenceIndices(node1)+1]; confidenceIndices(node1) += 1; } } } else if (nodeLocationX1 > nodeLocationX2) { string mutexKey = mutexStringHelper(nodeLabel1, nodeLabel2, "R"); if (this->mutex.count(mutexKey) == 0) satisfied = false; else if (this->mutex[mutexKey] <= MUTEX_THRESHOLD) satisfied = false; if (!satisfied) { LOG(DEBUG) << "not satisfied: " << node1 << ", " << node2; if (confidenceIndices(node1)+1 >= numClasses) { satisfied = true; } else { Y.graph.nodesData(node1) = node1ConfidentLabels[confidenceIndices(node1)+1]; confidenceIndices(node1) += 1; } } } if (nodeLocationY1 < nodeLocationY2) { string mutexKey = mutexStringHelper(nodeLabel1, nodeLabel2, "U"); if (this->mutex.count(mutexKey) == 0) satisfied = false; else if (this->mutex[mutexKey] <= MUTEX_THRESHOLD) satisfied = false; if (!satisfied) { LOG(DEBUG) << "not satisfied: " << node1 << ", " << node2; if (confidenceIndices(node1)+1 >= numClasses) { satisfied = true; } else { Y.graph.nodesData(node1) = node1ConfidentLabels[confidenceIndices(node1)+1]; confidenceIndices(node1) += 1; } } } else if (nodeLocationY1 > nodeLocationY2) { string mutexKey = mutexStringHelper(nodeLabel1, nodeLabel2, "D"); if (this->mutex.count(mutexKey) == 0) satisfied = false; else if (this->mutex[mutexKey] <= MUTEX_THRESHOLD) satisfied = false; if (!satisfied) { LOG(DEBUG) << "not satisfied: " << node1 << ", " << node2; if (confidenceIndices(node1)+1 >= numClasses) { satisfied = true; } else { Y.graph.nodesData(node1) = node1ConfidentLabels[confidenceIndices(node1)+1]; confidenceIndices(node1) += 1; } } } } } } } } return Y; } void MutexLogRegInit::setMutex(map<string, int>& mutex) { this->mutex = mutex; this->initialized = true; } map<string, int> MutexLogRegInit::getMutex() { return this->mutex; } string MutexLogRegInit::mutexStringHelper(int class1, int class2, string config) { stringstream ss; ss << class1 << " " << class2 << " " << config; return ss.str(); } }
[ "lamm@eecs.oregonstate.edu" ]
lamm@eecs.oregonstate.edu
43ad0c93b8ca9937496f2993d9ffdabe47db908f
2bc46842f7d5ec44473e75e8265beba9a1375ec0
/src/fs_snapshot.h
03b21a641c8b75125276d9c3e3ce928321a59721
[]
no_license
jackstenglein/strata_crash_consistency
3f5633b545a86959471be934eeee61d6011d60e5
704746a7977af6e59918fd368742c4e641f1b18d
refs/heads/master
2020-09-14T23:06:01.104814
2019-12-10T06:09:34
2019-12-10T06:09:34
223,231,806
0
0
null
null
null
null
UTF-8
C++
false
false
798
h
#include <iostream> #include <fstream> #include <sys/stat.h> #include <map> #include <vector> // Represents a snapshot of single file. class FileSnapshot { int status; int error; struct stat snapshot; public: FileSnapshot(const std::string); FileSnapshot(std::ifstream&); bool operator ==(const FileSnapshot other) const; void printState(std::ostream&) const; void writeToFile(std::ofstream&) const; }; // Represents a snapshot of the filesystem. class FSSnapshot { std::map<std::string, FileSnapshot> snapshots; std::string mountDir; public: FSSnapshot(std::string, const std::vector<std::string>&); FSSnapshot(std::string filename); bool operator==(const FSSnapshot other) const; void printState(std::ostream&) const; void writeToFile(std::string filename) const; };
[ "jackstenglein@utexas.edu" ]
jackstenglein@utexas.edu
e9f725795b7e8b1812566658c0d174749b1c7f39
c91b48a8d9884b4a4ab46f4f937e3583d32250db
/Assignment6/NYUCodebase/SheetSprite.cpp
b0d0cac2b66dba5cfbe9aea9b38f5f5e110d0686
[]
no_license
at2706/Game-Programming
e611cfbe0c82e8ae26a5ad51f240c8a1a9a1c4ca
5b48a21e4d529c4705c5b72fa42384264933c80b
refs/heads/master
2021-01-23T13:55:04.904896
2014-11-19T12:55:13
2014-11-19T12:55:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,569
cpp
#include "SheetSprite.h" SheetSprite::SheetSprite() { } SheetSprite::~SheetSprite() { } SheetSprite::SheetSprite(GLuint texID, GLfloat u, GLfloat v, GLfloat width, GLfloat height) : textureID(texID), u(u), v(v), width(width), height(height){ } GLvoid SheetSprite::draw(GLfloat x, GLfloat y, GLfloat facing, GLfloat scale){ glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, textureID); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glTranslatef(x, y, 0.0); GLint flip = (facing > 90.0f && facing < 270.0f) ? -1 : 1; GLfloat quad[] = { flip * -width * scale, height * scale / 2, flip * -width * scale, -height * scale / 2, flip * width * scale, -height * scale / 2, flip * width * scale, height * scale / 2 }; glVertexPointer(2, GL_FLOAT, 0, quad); glEnableClientState(GL_VERTEX_ARRAY); GLfloat quadUVs[] = { u, v, u, v + height, u + width, v + height, u + width, v }; glTexCoordPointer(2, GL_FLOAT, 0, quadUVs); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDrawArrays(GL_QUADS, 0, 4); glDisable(GL_TEXTURE_2D); glPopMatrix(); } SpriteUniformed::SpriteUniformed(GLuint texID, GLint index, GLint SpriteCountX, GLint SpriteCountY) : index(index), spriteCountX(SpriteCountX), spriteCountY(SpriteCountY){ textureID = texID; u = (GLfloat)(((GLint)index) % spriteCountX) / (GLfloat)spriteCountX; v = (GLfloat)(((GLint)index) / spriteCountX) / (GLfloat)spriteCountY; width = (spriteCountX / spriteCountY) / (GLfloat)spriteCountX; height = 1.0 / (GLfloat)spriteCountY; } GLvoid SpriteUniformed::draw(GLfloat x, GLfloat y, GLfloat facing, GLfloat scale){ glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, textureID); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glTranslatef(x, y, 0.0); GLint flip = (facing > 90.0f && facing < 270.0f) ? -1 : 1; GLfloat quad[] = { flip * -width * scale / 2, height * scale / 2, flip * -width * scale / 2, -height * scale / 2, flip * width * scale / 2, -height * scale / 2, flip * width * scale / 2, height * scale / 2 }; glVertexPointer(2, GL_FLOAT, 0, quad); glEnableClientState(GL_VERTEX_ARRAY); GLfloat quadUVs[] = { u, v, u, v + height, u + (width / (spriteCountX / spriteCountY)), v + height, u + (width / (spriteCountX / spriteCountY)), v }; glTexCoordPointer(2, GL_FLOAT, 0, quadUVs); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDrawArrays(GL_QUADS, 0, 4); glDisable(GL_TEXTURE_2D); glPopMatrix(); }
[ "at2706@nyu.edu" ]
at2706@nyu.edu
0bbb02865015381b8ac1dee3fee197f19ce9cdd4
8e28bfe260efb068c45df4429246e4354c5ea6f3
/counter.cpp
c770aecb50fceaada494076e64b211f1189794ee
[]
no_license
Michal944/adder_binary
7cde8617a425d03496ff64fc5efdc49ac7d8d2d6
41d344f84cc45eace3039d8dff62ef74fd3b2e56
refs/heads/master
2020-12-25T22:47:38.602956
2016-09-21T10:02:33
2016-09-21T10:02:33
68,737,027
0
0
null
null
null
null
UTF-8
C++
false
false
2,962
cpp
#include "counter.hpp" using std::cout; using std::endl; using std::cin; Counter::Counter(){cout<<"READY!"<<endl;} Counter::~Counter(){cout<<"CLOSE"<<endl;} void change_to_binary(const int &value, const US &bitX, std::vector<US> &vec) { int N; if(value<0) { int last_bit=1; for(N=0; N<(bitX-1); N++) last_bit*=2; last_bit--; last_bit+=value; for(N=0; N<(bitX-1); N++) { if(last_bit%2) vec.push_back(1); else vec.push_back(0); last_bit/=2; } vec.push_back(1); } else { int all_bits; all_bits=value; N=(bitX-1); while(N) { if(all_bits%2) vec.push_back(1); else vec.push_back(0); all_bits/=2; N--; } vec.push_back(0); } } void Counter::view() { std::vector<US>::const_iterator iter; iter=VALUE.cend(); iter--; std::vector<US>::const_iterator iter_1; std::vector<US>::const_iterator iter_2; iter_1=A.cend(); iter_2=B.cend(); iter_1--; iter_2--; US N=bits; while(N) { cout<<*iter_1; iter_1--; N--; } cout<<endl; N=bits; while(N) { cout<<*iter_2; iter_2--; N--; } cout<<endl; N=bits; while(N) { cout<<*iter; iter--; N--; } cout<<endl; } void Counter::put_value() { cout<<"-----VALUE1----"<<endl; cout<<"DECIMAL: "; cin>>value_a; cin.clear(); cin.ignore(100,'\n'); cout<<"-----VALUE2----"<<endl; cout<<"DECIMAL: "; cin>>value_b; cin.clear(); cin.ignore(100,'\n'); cout<<"-----BITS------"<<endl; cout<<"DECIMAL "; cin>>bits; } void Counter::add_f() { auto iter = A.cbegin(); auto iter2= B.cbegin(); bool bufor=0; for(; iter!=A.cend() && iter2!=B.cend(); iter++, iter2++) { if(*iter && *iter2) { if(!bufor) { VALUE.push_back(0); bufor=1; } else VALUE.push_back(1); } else if(!(*iter || *iter2)) { if(bufor) { bufor=0; VALUE.push_back(1); } else VALUE.push_back(0); } else if( (*iter || *iter2) && (*iter!=*iter2) ) { if(!bufor) VALUE.push_back(1); else VALUE.push_back(0); } } auto iter_buf=VALUE.begin(); int N=VALUE.size(); while(bufor && N) { if(!(*iter_buf)) { *iter_buf=1; bufor=0; } iter_buf++; N--; } }
[ "michal.kosik.mail@gmail.com" ]
michal.kosik.mail@gmail.com
d5c5d6ba53fe8215ec1f399c21a48f5826e7262a
aec89a8f9a1aa1ddce297ac5c1189ee3c041ad4f
/SqlStore.cpp
5219e2049109a00a528bdf062b3887af3ccace80
[]
no_license
vmlobanov78/SqlModel
3bffe015676735ff9c5e90655049f6852bfb2622
3b78ff1fb8b67157c42d152ed0698fc9de2d1864
refs/heads/master
2021-04-12T08:18:36.625914
2018-03-20T10:53:01
2018-03-20T10:53:01
126,003,333
0
0
null
null
null
null
UTF-8
C++
false
false
12,197
cpp
#include <string.h> #include <stdlib.h> #include <glib-object.h> #include <gtk/gtk.h> #include "Sql.h" #include "SqlStore.h" #include "SqlStore-private.h" static GObjectClass *parent_class = NULL; static void g_ptr_array_free_full (gpointer data) { g_ptr_array_free ((GPtrArray*)data, TRUE); } static gint g_int_cmp (gpointer x, gpointer y) { gint x_int, y_int; x_int = GPOINTER_TO_INT (x); y_int = GPOINTER_TO_INT (y); if (x > y) return 1; else if (x < y) return -1; else return 0; } GType sql_store_get_type (void) { static GType my_type = 0; if (!my_type) { static const GTypeInfo my_info = { sizeof(SqlStoreClass), NULL, /* base init */ NULL, /* base finalize */ (GClassInitFunc) sql_store_class_init, NULL, /* class finalize */ NULL, /* class data */ sizeof (SqlStore), 1, /* n_preallocs */ (GInstanceInitFunc) sql_store_init, NULL }; my_type = g_type_register_static (G_TYPE_OBJECT, "SqlStore", &my_info, (GTypeFlags) 0); static const GInterfaceInfo tree_model_info = { (GInterfaceInitFunc) sql_store_tree_model_init, NULL, NULL}; g_type_add_interface_static (my_type, GTK_TYPE_TREE_MODEL, &tree_model_info); } return my_type; } static void sql_store_class_init (SqlStoreClass *klass) { GObjectClass *gobject_class; gobject_class = (GObjectClass*) klass; parent_class = (_GObjectClass*) g_type_class_peek_parent (klass); gobject_class->finalize = sql_store_finalize; g_type_class_add_private (gobject_class, sizeof (SqlStorePrivate)); } static void sql_store_tree_model_init (GtkTreeModelIface *iface) { iface->get_flags = sql_store_get_flags; iface->get_n_columns = sql_store_get_n_columns; iface->get_column_type = sql_store_get_column_type; iface->get_iter = sql_store_get_iter; iface->get_path = sql_store_get_path; iface->get_value = sql_store_get_value; iface->iter_next = sql_store_iter_next; iface->iter_children = sql_store_iter_children; iface->iter_has_child = sql_store_iter_has_child; iface->iter_n_children = sql_store_iter_n_children; iface->iter_nth_child = sql_store_iter_nth_child; iface->iter_parent = sql_store_iter_parent; } static void sql_store_init (SqlStore *self) { SqlStorePrivate *priv; self->n_columns = 0; self->stamp = g_random_int (); priv = SQL_STORE_GET_PRIVATE (self); g_assert (priv); priv->cache = g_tree_new_full ((GCompareDataFunc) strcmp, NULL, NULL, g_ptr_array_free_full); g_assert (priv->cache); priv->rcache = g_tree_new ((GCompareFunc) g_int_cmp); g_assert (priv->rcache); } static void sql_store_finalize (GObject *self) { SqlStorePrivate *priv; g_return_if_fail (IS_SQL_STORE (self)); priv = SQL_STORE_GET_PRIVATE (self); g_assert (priv); if (priv->dbh) sqlite3_close (priv->dbh); if (priv->table) g_free (priv->table); if (priv->cache) g_tree_destroy (priv->cache); G_OBJECT_CLASS (parent_class)->finalize (self); } static GtkTreeModelFlags sql_store_get_flags (GtkTreeModel *tree_model) { g_return_val_if_fail (IS_SQL_STORE (tree_model), (GtkTreeModelFlags) 0); return (GtkTreeModelFlags)(GTK_TREE_MODEL_LIST_ONLY | GTK_TREE_MODEL_ITERS_PERSIST); } static gint sql_store_get_n_columns (GtkTreeModel *tree_model) { g_return_val_if_fail (IS_SQL_STORE (tree_model), 0); return SQL_STORE (tree_model)->n_columns; } static GType sql_store_get_column_type (GtkTreeModel *tree_model, gint index) { g_return_val_if_fail (IS_SQL_STORE (tree_model), G_TYPE_INVALID); g_return_val_if_fail (index < SQL_STORE (tree_model)->n_columns && index >= 0, G_TYPE_INVALID); return G_TYPE_STRING; } static gboolean sql_store_get_iter (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreePath *path) { SqlStore *self; SqlStorePrivate *priv; GPtrArray *data; gint *indices, depth; g_assert (IS_SQL_STORE (tree_model)); g_assert (path != NULL); self = SQL_STORE (tree_model); priv = SQL_STORE_GET_PRIVATE (self); g_assert (priv); indices = gtk_tree_path_get_indices (path); depth = gtk_tree_path_get_depth (path); g_assert (depth == 1); /* lookup the row position b-tree cache */ data = (GPtrArray*)g_tree_lookup (priv->rcache, GINT_TO_POINTER (indices[0])); if (!data) { data = sql_fetch_nth_row (priv->dbh, priv->table, indices[0]); } /* DON'T FREE THE KEY! */ gchar *key = (gchar*) g_ptr_array_index (data, 0); if (data && key) { if (g_tree_lookup (priv->cache, key) == NULL) g_tree_insert (priv->cache, key, data); if (g_tree_lookup (priv->rcache, GINT_TO_POINTER (indices[0])) == NULL) g_tree_insert (priv->rcache, GINT_TO_POINTER (indices[0]), data); } if (!data || data->len < 1) return FALSE; iter->stamp = self->stamp; iter->user_data = key; iter->user_data2 = NULL; iter->user_data3 = NULL; return TRUE; } static GtkTreePath* sql_store_get_path (GtkTreeModel *tree_model, GtkTreeIter *iter) { SqlStore *self; SqlStorePrivate *priv; GtkTreePath *path; gint pos; g_return_val_if_fail (IS_SQL_STORE (tree_model), NULL); g_return_val_if_fail (iter != NULL, NULL); g_return_val_if_fail (iter->user_data != NULL, NULL); self = SQL_STORE (tree_model); priv = SQL_STORE_GET_PRIVATE (self); g_assert (priv); pos = sql_fetch_row_pos (priv->dbh, priv->table, (gchar*)iter->user_data); path = gtk_tree_path_new (); gtk_tree_path_append_index (path, pos); return path; } static void sql_store_get_value (GtkTreeModel *tree_model, GtkTreeIter *iter, gint column, GValue *value) { SqlStore *self; SqlStorePrivate *priv; GPtrArray *data; g_return_if_fail (IS_SQL_STORE (tree_model)); g_return_if_fail (iter != NULL || iter->user_data != NULL); g_return_if_fail (column < SQL_STORE (tree_model)->n_columns); self = SQL_STORE (tree_model); priv = SQL_STORE_GET_PRIVATE (self); g_assert (priv); g_value_init (value, G_TYPE_STRING); data = (GPtrArray*)g_tree_lookup (priv->cache, iter->user_data); if (!data) { data = (GPtrArray*) sql_fetch_row (priv->dbh, priv->table, (gchar*)iter->user_data); /* Cache the results if they were retrieved */ if (data) g_tree_insert (priv->cache, iter->user_data, data); } if (data && column < data->len) g_value_set_string (value, (const gchar*)g_ptr_array_index (data, column)); } static gboolean sql_store_iter_next (GtkTreeModel *tree_model, GtkTreeIter *iter) { SqlStore *self; SqlStorePrivate *priv; GPtrArray *data = NULL; g_return_val_if_fail (IS_SQL_STORE (tree_model), FALSE); if (iter == NULL || iter->user_data == NULL) return FALSE; self = SQL_STORE (tree_model); priv = SQL_STORE_GET_PRIVATE (self); /* if a oid is set in iter->user_data, lets convert it to an integer * and increment it by one. if that value is found in the cache, we * use it instead of doing a sqlite query. Note that this still isn't * a good way to do this since cache would never hit if a row was * removed from the table. */ if (iter->user_data) { gchar *key = g_strdup_printf ("%d", atoi ((const gchar*)(iter->user_data)) + 1); data = (GPtrArray*)g_tree_lookup (priv->cache, key); g_free (key); } if (!data) { data = sql_fetch_next (priv->dbh, priv->table, (gchar*)iter->user_data); if (data != NULL && data->len > 0) { g_tree_insert (priv->cache, g_ptr_array_index (data, 0), data); } else return FALSE; } iter->user_data = g_ptr_array_index (data, 0); iter->user_data2 = NULL; iter->user_data3 = NULL; return TRUE; } static gboolean sql_store_iter_children (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *parent) { SqlStore *self; SqlStorePrivate *priv; GPtrArray *data; gchar *key; g_return_val_if_fail (IS_SQL_STORE (tree_model), FALSE); self = SQL_STORE (tree_model); priv = SQL_STORE_GET_PRIVATE (self); g_assert (priv); key = g_strdup ("1"); data = (GPtrArray*)g_tree_lookup (priv->cache, key); g_free (key); if (!data) { data = sql_fetch_next (priv->dbh, priv->table, NULL); if (data) { g_tree_insert (priv->cache, g_ptr_array_index (data, 0), data); } } if (data) { iter->stamp = self->stamp; iter->user_data = g_ptr_array_index (data, 0); iter->user_data2 = NULL; iter->user_data3 = NULL; return TRUE; } return FALSE; } static gboolean sql_store_iter_has_child (GtkTreeModel *tree_model, GtkTreeIter *iter) { return FALSE; } static gint sql_store_iter_n_children (GtkTreeModel *tree_model, GtkTreeIter *iter) { SqlStore *self; SqlStorePrivate *priv; g_return_val_if_fail (IS_SQL_STORE (tree_model), -1); g_return_val_if_fail (iter == NULL || iter->user_data != NULL, -1); self = SQL_STORE (tree_model); priv = SQL_STORE_GET_PRIVATE (self); g_assert (priv); if (!iter) { return sql_count_rows (priv->dbh, priv->table); } return 0; } static gboolean sql_store_iter_nth_child (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *parent, gint n) { SqlStore *self; SqlStorePrivate *priv; GPtrArray *data; g_return_val_if_fail (IS_SQL_STORE (tree_model), FALSE); self = SQL_STORE (tree_model); priv = SQL_STORE_GET_PRIVATE (self); g_assert (priv); if (parent) return FALSE; iter->stamp = self->stamp; iter->user_data = NULL; iter->user_data2 = NULL; iter->user_data3 = NULL; data = sql_fetch_nth_row (priv->dbh, priv->table, n); if (data && !g_tree_lookup (priv->cache, g_ptr_array_index (data, 0))) g_tree_insert (priv->cache, g_ptr_array_index (data, 0), data); if (data) { iter->user_data = g_ptr_array_index (data, 0); return TRUE; } return FALSE; } static gboolean sql_store_iter_parent (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *child) { return FALSE; } GtkTreeModel* sql_store_new (void) { return GTK_TREE_MODEL (g_object_new (TYPE_SQL_STORE, NULL)); } void sql_store_set_filename (SqlStore *self, const gchar *filename, GError **error) { SqlStorePrivate *priv; g_return_if_fail (IS_SQL_STORE (self)); priv = SQL_STORE_GET_PRIVATE (self); g_assert (priv); if (priv->dbh != NULL) { if (error == NULL) return; *error = g_error_new (SQL_STORE_ERROR, 1, "Database cannont be changed!"); return; } else if (!g_file_test (filename, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_REGULAR))) { if (error == NULL) return; *error = g_error_new (SQL_STORE_ERROR, 2, "Database does not exists!"); return; } else if (SQLITE_OK != sqlite3_open (filename, &priv->dbh)) { if (error == NULL) return; *error = g_error_new (SQL_STORE_ERROR, 3, "Error opening database!"); return; } } void sql_store_set_table (SqlStore *self, const gchar *table, GError **error) { SqlStorePrivate *priv; g_return_if_fail (IS_SQL_STORE (self)); priv = SQL_STORE_GET_PRIVATE (self); g_assert (priv); if (!priv->dbh) { *error = g_error_new (SQL_STORE_ERROR, 4, "No database connection set!"); return; } else if (priv->dbh && priv->table) { *error = g_error_new (SQL_STORE_ERROR, 4, "Cannot change table after connection"); return; } if (priv->table) g_free (priv->table); priv->table = g_strdup (table); self->n_columns = sql_fetch_n_columns (priv->dbh, priv->table); } const gchar* sql_store_get_table (SqlStore *self) { g_return_val_if_fail (IS_SQL_STORE (self), NULL); return SQL_STORE_GET_PRIVATE (self)->table; } void sql_store_set (SqlStore *self, GtkTreeIter *iter, ...) { #warning sql_store_set not implemented } void sql_store_clear (SqlStore *self) { #warning sql_store_clear not implemented } gboolean sql_store_iter_is_valid (SqlStore *self, GtkTreeIter *iter) { #warning sql_store_iter_is_valid not Implemented return TRUE; } void sql_store_remove (SqlStore *self, GtkTreeIter *iter) { #warning sql_store_remove not Implemented. } void sql_store_append (SqlStore *self, GtkTreeIter *iter) { #warning sql_store_append not Implemented. }
[ "37369729+vmlobanov78@users.noreply.github.com" ]
37369729+vmlobanov78@users.noreply.github.com
0edbabb228fd5093caa2d294edff03cf8108569f
e0f129d30ae2611fe1b78f11573a51df5af0945f
/PA1.RayCasting/student-code/include/camera.hpp
483e241210b969036be27b2970fbfc0e61e57acc
[]
no_license
TianhuaTao/computer-graphics-assignment
1b8034fe72cf481bb352053842d3ef9116786176
4f1bddac59f0ecb6be2a82bd86b709f57a69195f
refs/heads/master
2022-11-10T02:03:55.090071
2020-06-21T06:39:29
2020-06-21T06:39:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,376
hpp
#ifndef CAMERA_H #define CAMERA_H #include "ray.hpp" #include <vecmath.h> #include <float.h> #include <cmath> class Camera { public: Camera(const Vector3f &center, const Vector3f &direction, const Vector3f &up, int imgW, int imgH) { this->center = center; this->direction = direction.normalized(); // world this->horizontal = Vector3f::cross(this->direction, up).normalized(); this->up = Vector3f::cross(this->horizontal, this->direction).normalized(); this->width = imgW; this->height = imgH; } // Generate rays for each screen-space coordinate virtual Ray generateRay(const Vector2f &point) = 0; virtual ~Camera() = default; int getWidth() const { return width; } int getHeight() const { return height; } protected: // Extrinsic parameters Vector3f center; Vector3f direction; Vector3f up; Vector3f horizontal; // Intrinsic parameters int width; int height; }; // TODO: Implement Perspective camera // You can add new functions or variables whenever needed. class PerspectiveCamera : public Camera { public: PerspectiveCamera(const Vector3f &center, const Vector3f &direction, const Vector3f &up, int imgW, int imgH, float angle) : Camera(center, direction, up, imgW, imgH), fov(angle) { // angle is in radian. float half_height = tan(fov / 2); float half_width = half_height; lower_left_corner = center + this->direction - half_height * this->up - half_width * this->horizontal; filmHeight = 2 * half_height * this->up; filmWidth = 2 * half_width * this->horizontal; fx = (float) imgW / half_width / 2.0f; fy = (float) imgH / half_height / 2.0f; rotation = Matrix3f(this->horizontal, -this->up, this->direction); } Ray generateRay(const Vector2f &point) override { return Ray(center, lower_left_corner + point.x() / width * filmWidth + point.y() / height * filmHeight - center); } protected: float fov; // field of view, vertical, in radian. Matrix3f rotation; private: Vector3f lower_left_corner; Vector3f filmWidth; Vector3f filmHeight; float fx, fy; }; #endif //CAMERA_H
[ "tth135@126.com" ]
tth135@126.com
9129bcb0c2251ec91e2eee5fd7f3594c1b49ea42
53a7a843d06046aa58a408ad907556b8e1d374d9
/MeasureMotorSpeed/fftpf.h
49b18a451b4f995fb6feb520967d43273f21d7c2
[ "Apache-2.0" ]
permissive
luischuang/MeasureMotorSpeed
f0e6e0b3340ec9467d72f2474cb6f818102e4181
a9b58c289c1de10d8c59e1d6a821ae361d0c5fcc
refs/heads/master
2020-06-13T07:43:46.736007
2019-07-01T02:53:49
2019-07-01T02:56:54
194,589,315
0
0
null
null
null
null
UTF-8
C++
false
false
6,363
h
/* * Copyright (c) 2008-2011 Zhang Ming (M. Zhang), zmjerry@163.com * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 2 or any later version. * * 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. * * 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. A copy of the GNU General Public License is available at: * http://www.fsf.org/licensing/licenses */ /***************************************************************************** * fftpf.h * * Fast Fourier Transform with prime factor algorithm * * This class is designed for calculating discrete Fourier transform and * inverse discrete Fourier transform of 1D signals by using prime factor * algorithms. The signals can be arbitrary length. The largest prime factor * of n must be less than or equal to the constant PRIMEFACTOR defined below. * * The general idea is to factor the length of the DFT "n" into factors that are * efficiently handled by the routines. A number of short DFT's are implemented * with a minimum of arithmetical operations and using(almost) straight line * code resultingin very fast execution when the factors of n belong to this * set. Especially radix-10 is optimized. Prime factors, that are not in the * set of short DFT's are handled with direct evaluation of the DFP expression. * * The algorithm is modified from "xFFT.h" of "Pratical Fourier Transform * and C++ Implementation" written by Hequan Sun. * * Zhang Ming, 2010-09, Xi'an Jiaotong University. *****************************************************************************/ #ifndef FFTPF_H #define FFTPF_H #include "vector.h" #define PRIMEFACTOR 37 #define PRIMEFACTORHALF (PRIMEFACTOR+1)/2 #define PRIMECOUNT 20 namespace splab { template<class Type> class FFTPF { public: FFTPF(); ~FFTPF(); void fft( const Vector<Type> &xn, Vector< complex<Type> > &Xk ); void ifft( const Vector< complex<Type> > &Xk, Vector<Type> &xn ); void fft( const Vector< complex<Type> > &xn, Vector< complex<Type> > &Xk ); void ifft( const Vector< complex<Type> > &Xk, Vector< complex<Type> > &xn ); private: bool bAlloc; int mNOldSize, mNFactor, nNewFactorSize, nHalfFactorSize, groupOffset, dataOffset, blockOffset, adr, groupNo, dataNo, blockNo, twNo; int mSofarRadix[PRIMECOUNT], mActualRadix[PRIMECOUNT], mRemainRadix[PRIMECOUNT]; Type tPI, t2PI, tIRT2, tIRT3, omega, twRe, twIim; Type *pftwRe, *pftgRe, *pfzRe, *pfvRe, *pfwRe, *pftwIm, *pftgIm, *pfzIm, *pfvIm, *pfwIm; Type twiddleRe[PRIMEFACTOR], trigRe[PRIMEFACTOR], zRe[PRIMEFACTOR], twiddleIm[PRIMEFACTOR], trigIm[PRIMEFACTOR], zIm[PRIMEFACTOR], vRe[PRIMEFACTORHALF], wRe[PRIMEFACTORHALF], vIm[PRIMEFACTORHALF], wIm[PRIMEFACTORHALF]; Type c3_1, c5_1, c5_2, c5_3, c5_4, c5_5, c7_1, c7_2, c7_3, c7_4, c7_5, c7_6, c9_2, c9_3, c9_4, c9_5, c9_6, c9_7, c9_8, c9_9, c11_1, c11_2, c11_3, c11_4, c11_5, c11_6, c11_7, c11_8, c11_9, c11_10, c13_1, c13_2, c13_3, c13_4, c13_5, c13_6, c13_7, c13_8, c13_9, c13_10, c13_11, c13_12, c16_2, c16_3, c16_4, c16_5; Type ttmp, t1_re, t1_im, t2_re, t2_im, t3_re, t3_im, t4_re, t4_im, t5_re, t5_im, t6_re, t6_im, t7_re, t7_im, t8_re, t8_im, t9_re, t9_im, t10_re, t10_im, t11_re, t11_im, t12_re, t12_im, t13_re, t13_im, t14_re, t14_im, t15_re, t15_im, t16_re, t16_im, t17_re, t17_im, t18_re, t18_im, t19_re, t19_im, t20_re, t20_im, t21_re, t21_im, t22_re, t22_im, m1_re, m1_im, m2_re, m2_im, m3_re, m3_im, m4_re, m4_im, m5_re, m5_im, m6_re, m6_im, m7_re, m7_im, m8_re, m8_im, m9_re, m9_im, m10_re, m10_im, m11_re, m11_im, m12_re, m12_im; void releaseMem(); void allocateMem(); void factorize( int n, int &nFact, int *fact); void primeSetup( int nPoints ); void permute( const Vector<Type> &xn, Vector< complex<Type> > &yn ); void permute( const Vector< complex<Type> > &xn, Vector< complex<Type> > &yn, bool bTrans=true ); void initTrig( int radix ); void radix2( Type *aRe, Type *aIm ); void radix3( Type *aRe, Type *aIm ); void radix4( Type *aRe, Type *aIm ); void radix5( Type *aRe, Type *aIm ); void radix7( Type *aRe, Type *aIm ); void radix8( Type *aRe, Type *aIm ); void radix9( Type *aRe, Type *aIm ); void radix10( Type *aRe, Type *aIm ); void radix11( Type *aRe, Type *aIm ); void radix13( Type *aRe, Type *aIm ); void radix16( Type *aRe, Type *aIm ); void radixOther( int radix ); void twiddleFFT( int sofarRadix, int radix, int remainRadix, Vector< complex<Type> > &yn ); }; // class FFTPF #include "fftpf-impl.h" } // namespace splab #endif //FFTPF_H
[ "914765033@qq.com" ]
914765033@qq.com
a8c452802275b56b0a7e8e29caebfa4d5c1f211a
9d0fc723adc2526490abe44f81383375224a4eb5
/maximum_xor_subarray.cpp
b13a4e353d29c37638dcff340d22db18ea92f967
[]
no_license
gupta2140/SerpentineDataStructures
33315e91b6e53db0b4cf6a6b1e64e804668601f4
4f1b1c76da9a463119f659cf237f4ad59f507e67
refs/heads/master
2020-03-31T02:08:49.191624
2018-10-06T08:54:17
2018-10-06T08:54:17
151,810,230
0
0
null
2018-10-06T06:07:49
2018-10-06T06:07:49
null
UTF-8
C++
false
false
2,396
cpp
#include <bits/stdc++.h> // Considering the maximum number which will be entered will have at max 30 bits in binary representation. #define MAX_BITS 30 using namespace std; // A trie structure whose left child refers to 0 and right child refers to 1. struct trie { trie *bits[2]; }; // Inserts the number into the trie following its binary representation. void insertIntoTrie(int number, trie *root) { for(int i = MAX_BITS - 1; i >= 0; i--) { // Retrieve the ith bit. int bit = (number & (1 << i)) != 0; // If the trie doesn't have this bit at the current position, create it. if(root -> bits[bit] == NULL) { root -> bits[bit] = new trie; } // Follow down the path of the current bit. root = root -> bits[bit]; } } // Finds the maximum XOR for the queried number. int query(int number, trie *root) { // The maximum XOR value for the queried number. int xorValue = 0; for(int i = MAX_BITS - 1; i >= 0; i--) { // Retrieve the ith bit. int bit = (number & (1 << i)) != 0; // As soon as we get different MSB, it is sure to give the maximum XOR. The following conditions implements this logic. if(root -> bits[bit ^ 1] != NULL) { // If different bits are available, the xorValue will become (xorValue + 1 * 2^i) which can be written in the form as written below. xorValue += (1 << i); root = root -> bits[bit ^ 1]; } else { root = root -> bits[bit]; } } return xorValue; } /* The main logic is, XOR of any subarray from a[i]...a[j] can be represented as (a[1] ^ a[2]...^a[j]) ^ (a[1] ^ a[2]...^a[i - 1]). Hence we now have to find two numbers in the prefix xor array whose XOR is maximum. For this, the maximum XOR of the array will be maximum XOR of any element with any available element. We achieve this with Trie data structure. Follow the code for more understanding. */ int main() { // Number of elements in the array int n; cin >> n; int a[n + 1], maxXOR = 0; a[0] = 0; trie *root = new trie; insertIntoTrie(0, root); for(int i = 1; i <= n; i++) { cin >> a[i]; // Find prefix XOR. a[i] ^= a[i - 1]; // insertIntoTrie this prefix sum value into trie. insertIntoTrie(a[i], root); // maxXOR will be maximum of current maxXOR and the max XOR of this queried number. maxXOR = max(maxXOR, query(a[i], root)); } cout<<maxXOR; } /* Input: Output: 6 13 1 2 4 6 3 8 */
[ "gupta2140@gmail.com" ]
gupta2140@gmail.com
95d984fee7d70364276c04e49fff64363bdae4ca
e018d8a71360d3a05cba3742b0f21ada405de898
/Client/Packet/Gpackets/GCTradeAddItemHandler.cpp
5012030969d342e773a27be85fd0d179266d6fb2
[]
no_license
opendarkeden/client
33f2c7e74628a793087a08307e50161ade6f4a51
321b680fad81d52baf65ea7eb3beeb91176c15f4
refs/heads/master
2022-11-28T08:41:15.782324
2022-11-26T13:21:22
2022-11-26T13:21:22
42,562,963
24
18
null
2022-11-26T13:21:23
2015-09-16T03:43:01
C++
UHC
C++
false
false
6,411
cpp
////////////////////////////////////////////////////////////////////// // // Filename : GCTradeAddItemHandler.cpp // Written By : 김성민 // Description : // ////////////////////////////////////////////////////////////////////// // include files #include "Client_PCH.h" #include "GCTradeAddItem.h" #include "ClientDef.h" #include "MTradeManager.h" #include "MItem.h" void GCTradeAddItemHandler::execute ( GCTradeAddItem * pPacket , Player * pPlayer ) throw ( ProtocolException , Error ) { __BEGIN_TRY #ifdef __GAME_CLIENT__ //------------------------------------------------------------------------ // TradeManager가 생성되지 않은 경우 --> -_-;; //------------------------------------------------------------------------ if (g_pTradeManager==NULL) { DEBUG_ADD( "[Error] TradeManager is NULL"); return; } //------------------------------------------------------------------------ // 추가되는 아이템 생성 //------------------------------------------------------------------------ MItem* pItem = MItem::NewItem( (ITEM_CLASS)pPacket->getItemClass() ); pItem->SetID( pPacket->getItemObjectID() ); pItem->SetItemType( pPacket->getItemType() ); pItem->SetItemOptionList( pPacket->getOptionType() ); pItem->SetCurrentDurability( pPacket->getDurability() ); pItem->SetSilver( pPacket->getSilver() ); pItem->SetGrade( pPacket->getGrade() ); //ObjectID_t getTargetObjectID() const throw() { return m_TargetObjectID; } //------------------------------------------------------------------------ // 개수 //------------------------------------------------------------------------ // 총인 경우 //------------------------------------------------------------------------ if (pItem->IsGunItem()) { MMagazine* pMagazine = (MMagazine*)MItem::NewItem( (ITEM_CLASS)ITEM_CLASS_MAGAZINE ); // 의미 없음 - -; pMagazine->SetID( 0 ); // 이거는 총에 맞춰서 해줘야된다. for (int j=0; j<(*g_pItemTable)[ITEM_CLASS_MAGAZINE].GetSize(); j++) { pMagazine->SetItemType( j ); if (pMagazine->IsInsertToItem( pItem )) { break; } } // 의미 없음 pMagazine->ClearItemOption(); // 탄창 개수 pMagazine->SetNumber( pPacket->getItemNum() ); //------------------------------------ // 탄창 설정 //------------------------------------ MGunItem* pGunItem = (MGunItem*)pItem; pGunItem->SetMagazine( pMagazine ); } //------------------------------------------------------------------------ // 총이 아닌 경우 //------------------------------------------------------------------------ else { pItem->SetNumber( pPacket->getItemNum() ); } pItem->SetEnchantLevel( pPacket->getEnchantLevel() ); //------------------------------------------------------------------------ // // Item에 다른 item들이 들어있는 경우 // //------------------------------------------------------------------------ if (pPacket->getListNum()!=0) { DEBUG_ADD_FORMAT("This Item has Sub item(s) : size=%d", pPacket->getListNum()); //------------------------------------------ // Belt인 경우 //------------------------------------------ if (pItem->GetItemClass()==ITEM_CLASS_BELT) { MBelt* pBelt = (MBelt*)pItem; int size = pPacket->getListNum(); for (int i=0; i<size; i++) { SubItemInfo * pSubItemInfo = pPacket->popListElement(); if (pSubItemInfo==NULL) { DEBUG_ADD("[Error] Sub Item is NULL"); } else { //------------------------------------------ // Sub Item의 정보를 설정한다. //------------------------------------------ MItem* pSubItem = MItem::NewItem( (enum ITEM_CLASS)pSubItemInfo->getItemClass() ); pSubItem->SetItemType( pSubItemInfo->getItemType() ); //pItem->SetItemOption( pSubItemInfo->getOptionType() ); pSubItem->SetID( pSubItemInfo->getObjectID() ); pSubItem->SetNumber( pSubItemInfo->getItemNum() ); //------------------------------------------ // Belt의 정해진 slot에 item을 추가시킨다. //------------------------------------------ pBelt->AddItem( pSubItem, pSubItemInfo->getSlotID() ); delete pSubItemInfo; } } }else if (pItem->GetItemClass()==ITEM_CLASS_OUSTERS_ARMSBAND) { MOustersArmsBand* pBelt = (MOustersArmsBand*)pItem; int size = pPacket->getListNum(); for (int i=0; i<size; i++) { SubItemInfo * pSubItemInfo = pPacket->popListElement(); if (pSubItemInfo==NULL) { DEBUG_ADD("[Error] Sub Item is NULL"); } else { //------------------------------------------ // Sub Item의 정보를 설정한다. //------------------------------------------ MItem* pSubItem = MItem::NewItem( (enum ITEM_CLASS)pSubItemInfo->getItemClass() ); pSubItem->SetItemType( pSubItemInfo->getItemType() ); //pItem->SetItemOption( pSubItemInfo->getOptionType() ); pSubItem->SetID( pSubItemInfo->getObjectID() ); pSubItem->SetNumber( pSubItemInfo->getItemNum() ); //------------------------------------------ // Belt의 정해진 slot에 item을 추가시킨다. //------------------------------------------ pBelt->AddItem( pSubItem, pSubItemInfo->getSlotID() ); delete pSubItemInfo; } } } else { DEBUG_ADD_FORMAT("This Item can't have Sub item : class=%d", (int)pItem->GetItemClass()); } } int gridX = pPacket->getX(); int gridY = pPacket->getY(); //------------------------------------------------------------------------ // other Inventory에 추가한다.. // 추가 안되면.. 콩가루.. - -; //------------------------------------------------------------------------ if (!g_pTradeManager->GetOtherInventory()->AddItem( pItem, gridX, gridY )) { DEBUG_ADD_FORMAT("[Error] Can't add item to OtherInventory:id=%d (%d, %d)", pItem->GetID(), gridX, gridY); delete pItem; } //----------------------------------------------------------- // 뭔가 바뀐다면... OK취소 //----------------------------------------------------------- g_pTradeManager->RefuseOtherTrade(); g_pTradeManager->RefuseMyTrade(); #endif __END_CATCH }
[ "tiancaiamao@gmail.com" ]
tiancaiamao@gmail.com
bad7c5f106cfcfb22c5782cc8c2d781fccbeb0e7
c72d419e9ece84353f4c957eea7418177112b591
/BMLPA OpenMP/source_code/bmlpa_unweighted.h
a25c175db0c10fba627b67632a1cda23279c2cb2
[]
no_license
ozamarripa/bmlpa
421d0d19b3b4ce3e09d8aee591c415e4022cbad5
694ab52ebbd1f6d1bc18dcca1ad5f7912ecb5f6a
refs/heads/master
2020-04-06T16:04:10.779203
2014-06-21T08:52:29
2014-06-21T08:52:29
21,064,341
5
1
null
null
null
null
UTF-8
C++
false
false
1,791
h
#ifndef BMLPA_UNWEIGHTED_H #define BMLPA_UNWEIGHTED_H #include "graph_unweighted.h" using namespace std; class Algorithm{ public: Algorithm(Graph *g); public: void roughcores(map<unsigned int,set<unsigned int> > &roughcore); void initbmlpa(); void propagate_bmlpa(unsigned int x); void propagate_bmlpa_2(unsigned int x); void propagate_bmlpa_2_vector(unsigned int x,vector<bool>& ids_vector); void propagate_bmlpa_parallel(vector<bool>& ids_vector,unsigned int x); void propagate_bmlpa_parallel(); void normalize(unsigned int x); void idl(vector< map<unsigned int, double> >& l, vector<unsigned int>& ids); void idl_vector(vector< map<unsigned int, double> >& l, vector<bool>& ids); void idl_set(vector< map<unsigned int, double> >& l, vector<unsigned int>& ids); void idx(map<unsigned int, double>& lx, vector<unsigned int>& ids); void idx_vector(map<unsigned int, double>& lx, vector<bool>& ids); void idx_set(map<unsigned int, double>& lx, vector<unsigned int>& ids); void count(); void count_parallel(); void mc(map<unsigned int, int>& newmin); void execute_bmlpa(); void execute_bmlpa_parallel(); void removeSubs(); void splitDisconnectComs(); void saveResult(string , string); void setp(double p); void saveTime(string ,string ,char* ); private: map< unsigned int, vector<unsigned int> > coms; map< unsigned int, vector<unsigned int> > sub; Graph *g; vector< map<unsigned int, double> > source; vector< map<unsigned int, double> > dest; map<unsigned int, int> counts; map<unsigned int, int> min; set<unsigned int> idnew_set; set<unsigned int> idold_set; double p; int k; map<unsigned int,set<unsigned int> > roughcore; }; #endif //BMLPA_UNWEIGHTED_H
[ "omar@ozamarripa.(none)" ]
omar@ozamarripa.(none)
f4a1e54cdb4ac7a4a31917d09e3b1b0046999b67
6bc3f5955699fcdac540823c51354bc21919fb06
/CS-Academy/81/81A.cpp
b5455ca56a4bf9a87623625ecbbb56ad2ded225e
[]
no_license
soroush-tabesh/Competitive-Programming
e1a265e2224359962088c74191b7dc87bbf314bf
a677578c2a0e21c0510258933548a251970d330d
refs/heads/master
2021-09-24T06:36:43.037300
2018-10-04T14:12:00
2018-10-04T14:12:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,054
cpp
//In The Name of Allah //Tue 16/3/97 #include <bits/stdc++.h> #define Init ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0) #define fori(i,a,b) for(ll i = a; i < b;i++) #define forar(i,n) fori(i,0,n) #define WFile freopen("test.in","r",stdin),freopen("test.out","w",stdout) #define Log(x) cout << "Log: " << x << endl; #define F first #define S second #define pb push_back #define mp make_pair #define LSB(x) (x&(-x)) using namespace std; typedef long long int ll; typedef long double ld; typedef pair<int,int> pii; typedef pair<ll,ll> pll; const ll mod = 1e9+7,M = 2e5+100; void Solution(); int q,x; pii inv[10000]; int32_t main() { Init; Solution(); return 0; } bool cmp(pii a,pii b){ return ((a.S-a.F) > (b.S-b.F)) || (((a.S-a.F) == (b.S-b.F)) && (a.F<b.F)); } inline void Solution(){ cin >> q >> x; forar(i,q){ cin >> inv[i].F >> inv[i].S; } sort(inv,inv+q,cmp); forar(t,12){ int delta = 0; forar(i,q){ if(inv[i].F <= x){ delta = inv[i].S - inv[i].F; break; } } x += max(delta,0); } cout << x <<endl; }
[ "sorooshtabesh@yahoo.com" ]
sorooshtabesh@yahoo.com
8d9271fee85d4d0d7c9c9c3a5a01f5df357d06d9
c426c1d5cca7d3e1f716b84f12032bf9ba8b9629
/src/Математические функции/HML_ExpMSxD2.cpp
f3444a40207cd9b607692a5bb1aa9cda4abae4fe
[ "MIT", "Apache-2.0" ]
permissive
Harrix/Harrix-MathLibrary
24ce89a6c567fa456ef166f1a3f33c322f492118
19a753874cb5e792ba64b5c2d88a994e0644fccb
refs/heads/main
2022-07-24T03:28:48.376683
2022-07-08T13:45:35
2022-07-08T13:45:35
10,152,735
7
1
null
null
null
null
UTF-8
C++
false
false
294
cpp
double HML_ExpMSxD2(double x) { /* Функция вычисляет выражение exp(-x*x/2). Входные параметры: x - входная переменная. Возвращаемое значение: Значение функции в точке. */ return exp(-x*x/2.); }
[ "sergienkoanton@mail.ru" ]
sergienkoanton@mail.ru
9b2bfeaeb103ea76af4d32de912b5bfb4b34dae8
25fdd6194d21a54d0fd4a7c12e77b7221b63ad56
/extras/FLIPCOIN.cpp
726ee1e1f78a372782c543856e6b2c0e308dcc70
[]
no_license
achintsetia/CodeChef
e81e66150b488aff8cf4186ee34005e13453dd09
af1f2b67c19e905acd20ebe4689e13556b20c2f5
refs/heads/master
2021-01-20T05:31:39.536650
2013-11-15T08:48:18
2013-11-15T08:48:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,248
cpp
#include <iostream> #include <string.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <vector> #include <algorithm> using namespace std; #define FASTIO 1 #if FASTIO ///////////////////// ////// INPUT //////// //////////////////// class INPUT { static const int BUFSIZE = 1<<16; static char buffer[]; char *bufpos; char *bufend; void grabBuffer(); public: INPUT() { grabBuffer(); } bool eof() { return bufend==buffer; } char nextChar() { return *bufpos; } inline char readChar(); inline void skipWS(); long long int readUnsigned(); long long int readInt(); }; char INPUT::buffer[INPUT::BUFSIZE]; void INPUT::grabBuffer() { bufpos = buffer; bufend = buffer + fread( buffer, 1,BUFSIZE,stdin); } char INPUT::readChar() { char res = *bufpos++; if(bufpos==bufend) grabBuffer(); return res; } inline bool myisspace(char c) { return c<=' '; } void INPUT::skipWS() { while(!eof() && myisspace(nextChar())) readChar(); } long long INPUT::readUnsigned() { skipWS(); long long res = 0; while(!eof() && isdigit(nextChar())) { res = 10u * res + (readChar()-'0'); } return res; } long long int INPUT::readInt() { skipWS(); bool neg = false; if(!eof() && nextChar()=='-') { neg=true; readChar(); } long long int res = static_cast<long long int>(readUnsigned()); if(neg) res = -res; return res; } ///////////////////// ////// OUTPUT ////// //////////////////// class OUTPUT { static const int BUFSIZE = 1<<16; static char buffer[]; char *bufpos; char *BUFLIMIT; void flushBuffer(); public: OUTPUT():bufpos(buffer),BUFLIMIT(buffer+BUFSIZE-100) {} ~OUTPUT() { flushBuffer(); } inline void operator()(char c); inline void operator()(unsigned x); inline void operator()(int x); inline void operator()(unsigned long long int x); inline void operator()(long long int x); inline void operator()(const char*s); void operator()(const string&s) { operator()(s.c_str()); } template<class A,class B> void operator()(const A& a,const B& b) { operator()(a); operator()(b); } template<class A,class B,class C> void operator()(const A& a,const B& b,const C&c) { operator()(a); operator()(b); operator()(c); } template<class A,class B,class C,class D> void operator()(const A& a,const B& b,const C&c,const D&d) { operator()(a); operator()(b); operator()(c); operator()(d); } template<class A,class B,class C,class D,class E> void operator()(const A& a,const B& b,const C&c,const D&d,const E&e) { operator()(a); operator()(b); operator()(c); operator()(d); operator()(e); } template<class A,class B,class C,class D,class E,class F> void operator()(const A& a,const B& b,const C&c,const D&d,const E&e,const F&f) { operator()(a); operator()(b); operator()(c); operator()(d); operator()(e); operator()(f); } }; char OUTPUT::buffer[OUTPUT::BUFSIZE]; void OUTPUT::flushBuffer() { char *p = buffer; while(p < bufpos) { p += fwrite( p,1, bufpos-p,stdout); } bufpos = buffer; } void OUTPUT::operator()(char c) { *bufpos = c; ++bufpos; if(bufpos >= BUFLIMIT) flushBuffer(); } void OUTPUT::operator()(unsigned x) { char *old = bufpos; do { *bufpos = char('0' + x % 10u); x /= 10u; ++bufpos; } while(x); reverse(old, bufpos); if(bufpos >= BUFLIMIT) flushBuffer(); } void OUTPUT::operator()(int x) { if(x<0) { operator()('-'); x = -x; } operator()(static_cast<unsigned>(x)); } void OUTPUT::operator()(unsigned long long int x) { char *old = bufpos; do { *bufpos = char('0' + x % 10u); x /= 10u; ++bufpos; } while(x); reverse(old, bufpos); if(bufpos >= BUFLIMIT) flushBuffer(); } void OUTPUT::operator()(long long int x) { if(x<0) { operator()('-'); x = -x; } operator()(static_cast<unsigned long long int>(x)); } void OUTPUT::operator()(const char*s) { while(*s) operator()(*s++); } INPUT input; OUTPUT output; #endif int main( int argc, char** argv) { int N = input.readInt(); int Q = input.readInt(); int O, A, B; for( int i=0; i<Q; i++) { O = input.readInt(); A = input.readInt(); B = input.readInt(); if( O == 1) { } else { } } return 0; }
[ "achint@achint-cvlab" ]
achint@achint-cvlab
18c3b3bda48e6a2071b1a94082774a5f6e0fcef7
b2ff8d0ebd3c5286d60cf0add3b618002489fad3
/Thunk.cpp
6047af0e58eb79501528348f058d5d369e1bdeff
[]
no_license
vebko/Configuration-61850
fe87e0be7666b235b51d4e24e1aec39f90c55639
67943eecafbf22edf961cd67f1c3298fe334585c
refs/heads/master
2021-06-15T03:44:13.092882
2017-03-13T08:56:50
2017-03-13T08:56:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,542
cpp
 /* Copyright 2006 - 2008, All Rights Reserved. thunk - 动态替换CPU指令 利用这个类可以将Windows API的回调函数封装 成C++类成员.这份代码只能在x86的CPU上执行. 作者 - 张鲁夺(zhangluduo) MSN - zhangluduo@msn.com QQ群 - 34064264 为所有爱我的人和我爱的人努力! */ #include "Thunk.h" void* Thunk::Thiscall(void* pThis, unsigned long MemberFxnAddr) { // Encoded machine instruction Equivalent assembly languate notation // --------------------------- ------------------------------------- // B9 ?? ?? ?? ?? mov ecx, pThis ; Load ecx with this pointer // E9 ?? ?? ?? ?? jmp target addr ; Jump to target message handler // unsigned long JmpAddr = MemberFxnAddr - (unsigned long) &m_ThiscallCode - sizeof(m_ThiscallCode); // m_ThiscallCode[0] = 0xB9; // m_ThiscallCode[5] = 0xE9; // *((unsigned long *) &m_ThiscallCode[1]) = (unsigned long) pThis; // *((unsigned long *) &m_ThiscallCode[6]) = JmpAddr; // // return (void*)m_ThiscallCode; m_THISCALL.Mov = 0xB9; m_THISCALL.This = (unsigned long) pThis; m_THISCALL.Jmp = 0xE9; m_THISCALL.Adrr = MemberFxnAddr - (unsigned long)&m_THISCALL - sizeof(THUNK_THISCALL); return (void*)(&m_THISCALL); } void* Thunk::Stdcall(void* pThis, unsigned long MemberFxnAddr) { // Encoded machine instruction Equivalent assembly languate notation // --------------------------- ------------------------------------- // FF 34 24 push dword ptr [esp] ; Save (or duplicate) // ; the return Address into stack // C7 44 24 04 ?? ?? ?? ?? mov dword ptr [esp+4], pThis ; Overwite the old; // ; Return Address with 'this pointer' // E9 ?? ?? ?? ?? jmp target addr ; Jump to target message handler // unsigned long JmpAddr = MemberFxnAddr - (unsigned long) &m_StdcallCode - sizeof(m_StdcallCode); // m_StdcallCode[11] = 0xE9; // *((unsigned long *) &m_StdcallCode[ 0]) = 0x002434FF; // *((unsigned long *) &m_StdcallCode[ 3]) = 0x042444C7; // *((unsigned long *) &m_StdcallCode[ 7]) = (unsigned long) pThis; // *((unsigned long *) &m_StdcallCode[12]) = JmpAddr; // // return (void*)m_StdcallCode; m_STDCALL.Push[0] = 0xFF; m_STDCALL.Push[1] = 0x34; m_STDCALL.Push[2] = 0x24; m_STDCALL.Move = 0x042444C7; m_STDCALL.This = (unsigned long) pThis; m_STDCALL.Jmp = 0xE9; m_STDCALL.Adrr = MemberFxnAddr - (unsigned long)&m_STDCALL - sizeof(THUNK_STDCALL); return (void*)(&m_STDCALL); }
[ "xcj19862003@163.com" ]
xcj19862003@163.com
f353a2ea78bffa005a9d81f7f699bf506e85c6d4
fda96f7627d603383baddfd252cb8dd0bc0615ea
/Zorkish/CommandList.cpp
85d9688e31f060241a4b0c74aa2a9f2f2cb732bf
[]
no_license
andreasioan/Zorkish
bde46d9574617c3cd7b592eae58b9e6f8de4ce19
5a73c6290d60478b4213f6e15043000204f06d19
refs/heads/master
2021-01-13T12:27:23.277203
2017-01-03T06:06:57
2017-01-03T06:06:57
72,583,478
0
0
null
null
null
null
UTF-8
C++
false
false
513
cpp
// // CommandList.cpp // Zorkish // // Created by Andreas Ioannidis on 12/10/16. // Copyright © 2016 Andreas Ioannidis. All rights reserved. // #include "CommandList.h" CommandList::CommandList() : Command((string[]){"list"}) { } CommandList::~CommandList() { } string CommandList::execute(Player &player, LocationManager& locMan, vector<string> text) { for (int i = 0; i < player.GetDestinationNames().size(); i++) { return " --> " + player.GetDestinationNames()[i]; } }
[ "a.j.ioannidis@hotmail.com" ]
a.j.ioannidis@hotmail.com
24dc1d099e22f280b2fb07b19a8568167d09f47e
c6dbbb08e9547a471187605d87336d7b0fa58845
/inbound_filters/AGMSBayesianSpamFilter/AGMSBayesianSpamFilter.h
cd725f24ea01b282329bbbebfc6eb408ece0b7b2
[]
no_license
HaikuArchives/BeMailDaemon
625faa4a22122a4c3e7b557356a25ef571653565
2fd5cd8e114a9e7ae96b3369b25cfea0af66b88b
refs/heads/master
2016-09-06T04:31:35.558754
2008-08-17T19:49:55
2008-08-17T19:49:55
39,097,297
1
0
null
null
null
null
UTF-8
C++
false
false
3,446
h
#ifndef AGMS_BAYESIAN_SPAM_FILTER_H #define AGMS_BAYESIAN_SPAM_FILTER_H /****************************************************************************** * AGMSBayesianSpamFilter - Uses Bayesian statistics to evaluate the spaminess * of a message. The evaluation is done by a separate server, this add-on just * gets the text and uses scripting commands to get an evaluation from the * server. If the server isn't running, it will be found and started up. Once * the evaluation has been received, it is added to the message as an attribute * and optionally as an addition to the subject. Some other add-on later in * the pipeline will use the attribute to delete the message or move it to some * other folder. * * Public Domain 2002, by Alexander G. M. Smith, no warranty. * * $Log$ * Revision 1.7 2003/05/27 17:12:59 nwhitehorn * Massive refactoring of the Protocol/ChainRunner/Filter system. You can probably * examine its scope by examining the number of files changed. Regardless, this is * preparation for lots of new features, and REAL WORKING IMAP. Yes, you heard me. * Enjoy, and prepare for bugs (although I've fixed all the ones I've found, I susp * ect there are some memory leaks in ChainRunner). * * Revision 1.6 2003/02/08 21:54:17 agmsmith * Updated the AGMSBayesianSpamServer documentation to match the current * version. Also removed the Beep options from the spam filter, now they * are turned on or off in the system sound preferences. * * Revision 1.5 2002/12/18 02:27:45 agmsmith * Added uncertain classification as suggested by BiPolar. * * Revision 1.4 2002/12/12 00:56:28 agmsmith * Added some new spam filter options - self training (not implemented yet) * and a button to edit the server settings. * * Revision 1.3 2002/11/28 20:20:57 agmsmith * Now checks if the spam database is running in headers only mode, and * then only downloads headers if that is the case. * * Revision 1.2 2002/11/10 19:36:27 agmsmith * Retry launching server a few times, but not too many. * * Revision 1.1 2002/11/03 02:06:15 agmsmith * Added initial version. * * Revision 1.5 2002/10/21 16:13:59 agmsmith * Added option to have no words mean spam. * * Revision 1.4 2002/10/11 20:01:28 agmsmith * Added sound effects (system beep) for genuine and spam, plus config option * for it. * * Revision 1.3 2002/09/23 19:14:13 agmsmith * Added an option to have the server quit when done. * * Revision 1.2 2002/09/23 03:33:34 agmsmith * First working version, with cutoff ratio and subject modification, * and an attribute added if a patch is made to the Folder filter. * * Revision 1.1 2002/09/21 20:47:57 agmsmith * Initial revision */ #include <Message.h> #include <List.h> #include <MailAddon.h> class AGMSBayesianSpamFilter : public BMailFilter { public: AGMSBayesianSpamFilter (BMessage *settings); virtual ~AGMSBayesianSpamFilter (); virtual status_t InitCheck (BString* out_message = NULL); virtual status_t ProcessMailMessage (BPositionIO** io_message, BEntry* io_entry, BMessage* io_headers, BPath* io_folder, const char* io_uid); private: bool fAddSpamToSubject; bool fAutoTraining; float fGenuineCutoffRatio; bool fHeaderOnly; int fLaunchAttemptCount; BMessenger fMessengerToServer; bool fNoWordsMeansSpam; bool fQuitServerWhenFinished; float fSpamCutoffRatio; }; #endif /* AGMS_BAYESIAN_SPAM_FILTER_H */
[ "" ]
e0db8b1aed8d87fdb4f3a01f4efa19f36632d3b8
de2a8f634a0e99f463df2ad79853dcf35bf23deb
/src/GeneratedFiles/ui_addnodedialog.h
0ed7e43c4b21d4cfef9e3c12184115339c07aa51
[ "MIT" ]
permissive
SelfSellTeam/Wallet
35a5bc42831fe43005ce055b13ff0623b235deba
15a047a308fb0145c6d5df4e54c53a58b59fbf07
refs/heads/master
2020-03-10T10:43:23.934099
2018-04-13T08:50:59
2018-04-13T08:50:59
129,339,549
1
0
null
null
null
null
UTF-8
C++
false
false
3,480
h
/******************************************************************************** ** Form generated from reading UI file 'addnodedialog.ui' ** ** Created by: Qt User Interface Compiler version 5.7.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_ADDNODEDIALOG_H #define UI_ADDNODEDIALOG_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QToolButton> QT_BEGIN_NAMESPACE class Ui_AddNodeDialog { public: QLabel *label; QLineEdit *ipLineEdit; QLabel *label_2; QLineEdit *portLineEdit; QToolButton *cancelBtn; QToolButton *addBtn; void setupUi(QDialog *AddNodeDialog) { if (AddNodeDialog->objectName().isEmpty()) AddNodeDialog->setObjectName(QStringLiteral("AddNodeDialog")); AddNodeDialog->resize(400, 200); QFont font; font.setFamily(QString::fromUtf8("\345\276\256\350\275\257\351\233\205\351\273\221")); AddNodeDialog->setFont(font); label = new QLabel(AddNodeDialog); label->setObjectName(QStringLiteral("label")); label->setGeometry(QRect(50, 30, 51, 30)); label->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter); ipLineEdit = new QLineEdit(AddNodeDialog); ipLineEdit->setObjectName(QStringLiteral("ipLineEdit")); ipLineEdit->setGeometry(QRect(130, 30, 171, 30)); label_2 = new QLabel(AddNodeDialog); label_2->setObjectName(QStringLiteral("label_2")); label_2->setGeometry(QRect(50, 80, 51, 30)); label_2->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter); portLineEdit = new QLineEdit(AddNodeDialog); portLineEdit->setObjectName(QStringLiteral("portLineEdit")); portLineEdit->setGeometry(QRect(130, 80, 171, 30)); cancelBtn = new QToolButton(AddNodeDialog); cancelBtn->setObjectName(QStringLiteral("cancelBtn")); cancelBtn->setGeometry(QRect(210, 140, 120, 36)); cancelBtn->setFont(font); cancelBtn->setCursor(QCursor(Qt::PointingHandCursor)); addBtn = new QToolButton(AddNodeDialog); addBtn->setObjectName(QStringLiteral("addBtn")); addBtn->setGeometry(QRect(70, 140, 120, 36)); addBtn->setFont(font); addBtn->setCursor(QCursor(Qt::PointingHandCursor)); retranslateUi(AddNodeDialog); QMetaObject::connectSlotsByName(AddNodeDialog); } // setupUi void retranslateUi(QDialog *AddNodeDialog) { AddNodeDialog->setWindowTitle(QApplication::translate("AddNodeDialog", "Dialog", Q_NULLPTR)); label->setText(QApplication::translate("AddNodeDialog", "IP", Q_NULLPTR)); label_2->setText(QApplication::translate("AddNodeDialog", "Port", Q_NULLPTR)); cancelBtn->setText(QApplication::translate("AddNodeDialog", "Cancel", Q_NULLPTR)); addBtn->setText(QApplication::translate("AddNodeDialog", "OK", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class AddNodeDialog: public Ui_AddNodeDialog {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_ADDNODEDIALOG_H
[ "36432234+david-selfsell@users.noreply.github.com" ]
36432234+david-selfsell@users.noreply.github.com
c63790c5141abf3c933bd0b03147f6cf0a47b8a2
fbf82b2d98003aa7edadbe5b02e9f1205ecbe46d
/weighted_graph/include/MinimumSpanningTree.h
f73eb9b49148c6f01bcec1741dbaaa29a19046fb
[ "BSD-3-Clause" ]
permissive
tide999/graphs-cpp
73a78416ca24c22f65c803c331d5b94e3cc6cc0d
64f71c864df89ebfdbf8fa3189e6f5a4d6ca12f4
refs/heads/master
2023-03-20T04:43:31.763469
2021-02-07T10:09:30
2021-02-07T10:09:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,170
h
#ifndef WEIGHTED_GRAPHS_CPP_MINIMUMSPANNINGTREE_H #define WEIGHTED_GRAPHS_CPP_MINIMUMSPANNINGTREE_H #include "EdgeWeightedGraph.h" #include "DisjointSets.h" #include <unordered_set> #include <algorithm> #include <queue> template <typename T> using min_priority_queue = std::priority_queue<T, std::vector<T>, std::greater<>>; // Find a https://en.wikipedia.org/wiki/Minimum_spanning_tree (or forest) // with Kruskal's algorithm (https://en.wikipedia.org/wiki/Kruskal%27s_algorithm) class MinimumSpanningTree { public: explicit MinimumSpanningTree(const EdgeWeightedGraph& graph) { if(graph.V() < 1) throw std::invalid_argument("Graph must contain at least one vertex"); tree.reserve(graph.V()-1); // create minimum priority queue of edges (i.e. ascending weights) auto edges = graph.edges(); min_priority_queue<Edge> edges_minPQ(edges.begin(), edges.end()); // building heap takes O(E) time // add edges to tree unless doing this would create a cycle (until N=V-1) DisjointSets uf(graph.V()); // O(V) while(tree.size() < static_cast<size_t>(graph.V()-1)) { // O(E) iterations if (edges_minPQ.empty()) throw std::invalid_argument("Could not create MST from graph"); const auto currMinEdge = edges_minPQ.top(); // edge with minimal weight edges_minPQ.pop(); // O(log(E)) // check whether adding this would create a cycle const int v1 = currMinEdge.either(); const int v2 = currMinEdge.other(v1); if (!uf.connected(v1, v2)) { // O(log*(V)) - nearly constant time op // would not create a cycle - matches O(V) times in total uf.setUnion(v1, v2); // O(log*(V)) tree.push_back(currMinEdge); mst_weight += currMinEdge.getWeight(); } } } [[nodiscard]] const std::vector<Edge>& edges() const { return tree; } [[nodiscard]] double weight() const { return mst_weight; } private: std::vector<Edge> tree; double mst_weight = 0; }; #endif //WEIGHTED_GRAPHS_CPP_MINIMUMSPANNINGTREE_H
[ "nicolai@xeve.de" ]
nicolai@xeve.de
cd581d261f5b32a13c9b65cee8d67181b61ba56c
10c3b82c62b81ca2b09522cc3840f8817b938523
/DNA_Assignment1/FileHandler.cpp
4d93c307a7c66011225a489eac30433c3fadfee8
[]
no_license
ewasserman6/fall2019_DNA_Nucleotides
db4b1fc557f260217c8141624aed5f1eb159d1f8
21960d6a1dd6bcd33bfdf0e97dccb28faf166b85
refs/heads/master
2020-07-26T04:47:47.761182
2019-10-02T05:12:07
2019-10-02T05:12:07
208,538,540
0
0
null
null
null
null
UTF-8
C++
false
false
1,457
cpp
/*Eric Wasserman 2300841 ewasserman@chapman.edu CPSC 350 Section 3 Assignment 1: DNA I created this class so I could open the file only when I needed to compared to opening it every time I called one of my functions in my main.cpp */ #include "FileHandler.h" #include <iostream> #include <fstream> #include <math.h> using namespace std; // constructor function FileHandler::FileHandler() { }; //destructor function FileHandler::~FileHandler() { cout << "Object has been deleted" << endl; }; /* lineCount calculates the number of lines in the string of nucleotides so I can calculate the mean. */ float FileHandler::lineCount(string fileName) { ifstream inFile; inFile.open(fileName); string dna; float lineCount = 0; while(true){ inFile >> dna; if(inFile.eof()) break; lineCount++; } inFile.close(); return lineCount; } /*This functions reads the dna file in. It also makes all the nucleotides upper case. */ string FileHandler::readFile(string fileName) { ifstream inFile; inFile.open(fileName); string dna; string output; string tempDna; while (true){ inFile >> dna; if (inFile.eof()){ break; } else{ tempDna += dna; } } // make everything upper case for (int i = 0; i < tempDna.length(); ++i) { output += toupper(tempDna[i]); } inFile.close(); return output; }
[ "ewasserman@chapman.edu" ]
ewasserman@chapman.edu
16cba099d1ce676d747b13c7b07528a114848bf0
12a35046e0bd567b2687bf2cd8dfa06022acd0be
/server/src/common/lib/agutil/main/AGdataStruct.cpp
372574fe289fdc4caef3f6eb6828fcf314ee4b86
[ "MIT" ]
permissive
ngphloc/agmagic
71e4e5a51faa37645136deeaf85f7976f172ed52
65d3ad6aeda3431e998e7f23aaa93381dcd10746
refs/heads/master
2022-05-18T22:37:33.142198
2022-05-03T02:49:48
2022-05-03T02:49:48
41,147,766
0
1
null
null
null
null
UTF-8
C++
false
false
13,957
cpp
#include "AGdataStruct.h" #if AGMAGIC_SUPPORT_MFC #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CAGmagicElementPtrArray::CAGmagicElementPtrArray() : CAGobjPtrArray<CAGmagicElement>() { } CAGmagicElementPtrArray::~CAGmagicElementPtrArray() { } agbool CAGmagicElementPtrArray::GetValueAt(agint32 idx, agfreal& value) { CAGmagicElement* e=(CAGmagicElement*)GetAt(idx); if(e==NULL) return agfalse; value=e->GetValue(); return agtrue; } agbool CAGmagicElementPtrArray::GetIDAt(agint32 idx, aguint_id& ID) { CAGmagicElement* e=(CAGmagicElement*)GetAt(idx); if(e==NULL) return agfalse; ID=e->GetID(); return agtrue; } agint32 CAGmagicElementPtrArray::LSearchID(aguint_id ID) { if(IsEmpty()) return -1; agint32 n=GetSize(); agint32 i=0; for(i=0; i<n; i++) { aguint_id TempID; if(!GetIDAt(i,TempID)) continue; if(TempID==ID) break; } if(i==n) return -1; return i; } agbool CAGmagicElementPtrArray::GetValueAtID(aguint_id ID, agfreal& value) { agint32 idx=LSearchID(ID); if(idx==-1) return agfalse; return GetValueAt(idx,value); } /*******************************class CAGbuRectVec*******************************/ CAGbuRectVec::CAGbuRectVec() : CAGbaseArray<AGBU_RECT>() { } CAGbuRectVec::~CAGbuRectVec() { } agint32 CAGbuRectVec::TotalWidth(agint32 wHinge) { agint32 total_width=0; agint32 n=GetSize(); for(agint32 i=0; i<n; i++) { AGBU_RECT rc=GetAt(i); agint32 w=(rc.right-rc.left); total_width +=w; if(i!=n-1) total_width +=(w>0?wHinge:0); } return total_width; } agint32 CAGbuRectVec::TotalHeight() { agint32 max_height=0; agint32 n=GetSize(); for(agint32 i=0; i<n; i++) { AGBU_RECT rc=GetAt(i); max_height= AGMAX(max_height,(agint32)(rc.top-rc.bottom)); } return max_height; } void CAGbuRectVec::Import(CAGtdRectVec* pRectVec) { RemoveAll(); if(pRectVec==NULL) return; agint32 n=pRectVec->GetSize(); if(n==0) return; agint32 max_height=pRectVec->TotalHeight(); SetSize(n); for(agint32 i=0; i<n; i++) { AGBU_RECT& bu_rc=ElementAt(i); AGTD_RECT td_rc=pRectVec->GetAt(i); CAGmagicMicUtil::ChangeTDtoBU(max_height,&bu_rc,&td_rc); } } void CAGbuRectVec::Import(CAGbuRectMatrix* pRectMatrix) { RemoveAll(); if(pRectMatrix==NULL) return; agint32 rows=pRectMatrix->GetSize(); for(agint32 i=0; i<rows; i++) { CAGbuRectVec* pRectVector=pRectMatrix->GetAt(i); if(pRectVector==NULL) continue; agint32 cols=pRectVector->GetSize(); for(agint32 j=0; j<cols; j++) Add(pRectVector->GetAt(j)); } } agbool CAGbuRectVec::CreateByCut(AGBU_RECT TotalRect, SIZE block_size) { CAGbuRectMatrix RectMatrix; agbool bResult=RectMatrix.CreateByCut(TotalRect, block_size); Import(&RectMatrix); return bResult; } agbool CAGbuRectVec::CreateByCut(AGBU_RECT TotalRect, agint32 nRows, agint32 nCols) { CAGbuRectMatrix RectMatrix; agbool bResult=RectMatrix.CreateByCut(TotalRect, nRows, nCols); Import(&RectMatrix); return bResult; } agbool CAGbuRectVec::CreateByCut(AGBU_RECT TotalRect, agint32 CXsizes[], agint32 nCXsizes, agint32 CYsizes[], agint32 nCYsizes) { CAGbuRectMatrix RectMatrix; agbool bResult=RectMatrix.CreateByCut(TotalRect, CXsizes, nCXsizes, CYsizes, nCYsizes); Import(&RectMatrix); return bResult; } /*******************************class CAGbuRectMatrix*******************************/ CAGbuRectMatrix::CAGbuRectMatrix() : CAGobjPtrArray<CAGbuRectVec>() { } CAGbuRectMatrix::~CAGbuRectMatrix() { } agint32 CAGbuRectMatrix::TotalWidth(agint32 wHinge) { agint32 max_width=0; agint32 n=GetSize(); for(agint32 i=0; i<n; i++) { CAGbuRectVec* pRectVec=GetAt(i); if(pRectVec) max_width = AGMAX(max_width,pRectVec->TotalWidth(wHinge)); } return max_width; } agint32 CAGbuRectMatrix::TotalHeight(agint32 hHinge) { agint32 total_height=0; agint32 n=GetSize(); for(agint32 i=0; i<n; i++) { CAGbuRectVec* pRectVec=GetAt(i); if(pRectVec) { agint32 h=pRectVec->TotalHeight(); total_height += h; if(i!=n-1) total_height +=(h>0?hHinge:0); } } return total_height; } void CAGbuRectMatrix::Import(CAGtdRectMatrix* pRectMatrix) { RemoveAll(); if(pRectMatrix==NULL) return; agint32 m=pRectMatrix->GetSize(); if(m==0) return; agint32 max_height=pRectMatrix->TotalHeight(); SetSize(m,agfalse); for(agint32 i=0; i<m; i++) { CAGbuRectVec*& pbuRectVec=ElementAt(i); CAGtdRectVec* ptdRectVec=pRectMatrix->GetAt(m-1-i); if(ptdRectVec==NULL) continue; agint32 n=ptdRectVec->GetSize(); if(n==0) continue; if(pbuRectVec) delete pbuRectVec; pbuRectVec=new CAGbuRectVec(); pbuRectVec->SetSize(n); for(agint32 j=0; j<n; j++) { AGBU_RECT& bu_rc=pbuRectVec->ElementAt(i); AGTD_RECT td_rc=ptdRectVec->GetAt(i); CAGmagicMicUtil::ChangeTDtoBU(max_height,&bu_rc,&td_rc); } } } agbool CAGbuRectMatrix::CreateByCut(AGBU_RECT TotalRect, SIZE block_size) { RemoveAll(); SIZE TotalSize; TotalSize.cx=TotalRect.right-TotalRect.left; TotalSize.cy=TotalRect.top-TotalRect.bottom; if(TotalSize.cx<=0 || TotalSize.cy<=0 || block_size.cx<=0 || block_size.cy<=0) return agfalse; if(block_size.cx > TotalSize.cx) block_size.cx = TotalSize.cx; if(block_size.cy > TotalSize.cy) block_size.cy = TotalSize.cy; agint32 rows=TotalSize.cy/block_size.cy; agint32 cols=TotalSize.cx/block_size.cx; for(agint32 i=0; i<rows; i++) { CAGbuRectVec* pRectVector=(CAGbuRectVec*)newAGOBJ_ARRAY_TYPE(); for(agint32 j=0; j<cols; j++) { AGBU_RECT rc; memset(&rc,0,sizeof(AGBU_RECT)); //goc trai,duoi rc.left =TotalRect.left + j*block_size.cx; rc.bottom=TotalRect.bottom + i*block_size.cy; //goc phai, tren if(j==cols-1) rc.right=TotalRect.right; else rc.right=rc.left + block_size.cx; if(i==rows-1) rc.top=TotalRect.top; else rc.top=rc.bottom + block_size.cy; pRectVector->Add(rc); } Add(pRectVector,agfalse); } return agtrue; } agbool CAGbuRectMatrix::CreateByCut(AGBU_RECT TotalRect, agint32 nRows, agint32 nCols) { RemoveAll(); if(nRows==0 || nCols==0) return false; SIZE TotalSize; TotalSize.cx=TotalRect.right-TotalRect.left; TotalSize.cy=TotalRect.top-TotalRect.bottom; SIZE block_size; block_size.cx=TotalSize.cx/nCols; block_size.cy=TotalSize.cy/nRows; return CreateByCut(TotalRect,block_size); } agbool CAGbuRectMatrix::CreateByCut(AGBU_RECT TotalRect, agint32 CXsizes[], agint32 nCXsizes, agint32 CYsizes[], agint32 nCYsizes) { RemoveAll(); if(CXsizes==NULL || nCXsizes==0 || CYsizes==NULL || nCYsizes==0) throw _T("Invalid parameter"); SIZE TotalSize; TotalSize.cx=TotalRect.right-TotalRect.left; TotalSize.cy=TotalRect.top-TotalRect.bottom; if(TotalSize.cx<=0 || TotalSize.cy<=0) return agfalse; agint32 accum_cy=0; for(agint32 i=0; i<nCYsizes; i++) { agint32 cy=CYsizes[i]; if(cy<=0) throw _T("Invalid parameter"); CAGbuRectVec* pRectVector=(CAGbuRectVec*)newAGOBJ_ARRAY_TYPE(); agint32 accum_cx=0; AGBU_RECT rc; for(agint32 j=0; j<nCXsizes; j++) { agint32 cx=CXsizes[j]; if(cx<=0) throw _T("Invalid parameter"); memset(&rc,0,sizeof(AGBU_RECT)); //goc trai,duoi rc.left = TotalRect.left + accum_cx; rc.bottom = TotalRect.bottom + accum_cy; //goc phai, tren rc.right=rc.left + cx; if(rc.right > TotalRect.right) rc.right = TotalRect.right; rc.top=rc.bottom + cy; if(rc.top > TotalRect.top) rc.top = TotalRect.top; pRectVector->Add(rc); if(rc.right == TotalRect.right) break; accum_cx +=cx; } Add(pRectVector,agfalse); if(rc.top == TotalRect.top) break; accum_cy +=cy; } return agtrue; } /*******************************class CAGtdRectVec*******************************/ CAGtdRectVec::CAGtdRectVec() : CAGbaseArray<AGTD_RECT>() { } CAGtdRectVec::~CAGtdRectVec() { } agint32 CAGtdRectVec::TotalWidth(agint32 wHinge) { agint32 total_width=0; agint32 n=GetSize(); for(agint32 i=0; i<n; i++) { AGTD_RECT rc=GetAt(i); agint32 w=(rc.right-rc.left); total_width +=w; if(i!=n-1) total_width +=(w>0?wHinge:0); } return total_width; } agint32 CAGtdRectVec::TotalHeight() { agint32 max_height=0; agint32 n=GetSize(); for(agint32 i=0; i<n; i++) { AGTD_RECT rc=GetAt(i); max_height= AGMAX(max_height,(agint32)(rc.bottom-rc.top)); } return max_height; } void CAGtdRectVec::Import(CAGbuRectVec* pRectVec) { RemoveAll(); if(pRectVec==NULL) return; agint32 n=pRectVec->GetSize(); if(n==0) return; agint32 max_height=pRectVec->TotalHeight(); SetSize(n); for(agint32 i=0; i<n; i++) { AGTD_RECT& td_rc=ElementAt(i); AGBU_RECT bu_rc=pRectVec->GetAt(i); CAGmagicMicUtil::ChangeBUtoTD(max_height,&td_rc,&bu_rc); } } void CAGtdRectVec::Import(CAGtdRectMatrix* pRectMatrix) { RemoveAll(); if(pRectMatrix==NULL) return; agint32 rows=pRectMatrix->GetSize(); for(agint32 i=0; i<rows; i++) { CAGtdRectVec* pRectVector=pRectMatrix->GetAt(i); agint32 cols=pRectVector->GetSize(); for(agint32 j=0; j<cols; j++) Add(pRectVector->GetAt(j)); } } agbool CAGtdRectVec::CreateByCut(AGTD_RECT TotalRect, SIZE block_size) { CAGtdRectMatrix RectMatrix; agbool bResult=RectMatrix.CreateByCut(TotalRect, block_size); Import(&RectMatrix); return bResult; } agbool CAGtdRectVec::CreateByCut(AGTD_RECT TotalRect, agint32 nRows, agint32 nCols) { CAGtdRectMatrix RectMatrix; agbool bResult=RectMatrix.CreateByCut(TotalRect, nRows, nCols); Import(&RectMatrix); return bResult; } agbool CAGtdRectVec::CreateByCut(AGTD_RECT TotalRect, agint32 CXsizes[], agint32 nCXsizes, agint32 CYsizes[], agint32 nCYsizes) { CAGtdRectMatrix RectMatrix; agbool bResult=RectMatrix.CreateByCut(TotalRect, CXsizes, nCXsizes, CYsizes, nCYsizes); Import(&RectMatrix); return bResult; } /*******************************class CAGtdRectMatrix*******************************/ CAGtdRectMatrix::CAGtdRectMatrix() : CAGobjPtrArray<CAGtdRectVec>() { } CAGtdRectMatrix::~CAGtdRectMatrix() { } agint32 CAGtdRectMatrix::TotalWidth(agint32 wHinge) { agint32 max_width=0; agint32 n=GetSize(); for(agint32 i=0; i<n; i++) { CAGtdRectVec* pRectVec=GetAt(i); if(pRectVec) max_width = AGMAX(max_width,pRectVec->TotalWidth(wHinge)); } return max_width; } agint32 CAGtdRectMatrix::TotalHeight(agint32 hHinge) { agint32 total_height=0; agint32 n=GetSize(); for(agint32 i=0; i<n; i++) { CAGtdRectVec* pRectVec=GetAt(i); if(pRectVec) { agint32 h=pRectVec->TotalHeight(); total_height += h; if(i!=n-1) total_height +=(h>0?hHinge:0); } } return total_height; } void CAGtdRectMatrix::Import(CAGbuRectMatrix* pRectMatrix) { RemoveAll(); if(pRectMatrix==NULL) return; agint32 m=pRectMatrix->GetSize(); if(m==0) return; agint32 max_height=pRectMatrix->TotalHeight(); SetSize(m,agfalse); for(agint32 i=0; i<m; i++) { CAGtdRectVec*& ptdRectVec=ElementAt(i); CAGbuRectVec* pbuRectVec=pRectMatrix->GetAt(m-1-i); if(pbuRectVec==NULL) continue; agint32 n=pbuRectVec->GetSize(); if(n==0) continue; if(ptdRectVec) delete ptdRectVec; ptdRectVec=new CAGtdRectVec(); ptdRectVec->SetSize(n); for(agint32 j=0; j<n; j++) { AGTD_RECT& td_rc=ptdRectVec->ElementAt(i); AGBU_RECT bu_rc=pbuRectVec->GetAt(i); CAGmagicMicUtil::ChangeBUtoTD(max_height,&td_rc,&bu_rc); } } } agbool CAGtdRectMatrix::CreateByCut(AGTD_RECT TotalRect, SIZE block_size) { RemoveAll(); SIZE TotalSize; TotalSize.cx=TotalRect.right-TotalRect.left; TotalSize.cy=TotalRect.bottom-TotalRect.top; if(TotalSize.cx<=0 || TotalSize.cy<=0 || block_size.cx<=0 || block_size.cy<=0) return agfalse; if(block_size.cx > TotalSize.cx) block_size.cx = TotalSize.cx; if(block_size.cy > TotalSize.cy) block_size.cy = TotalSize.cy; agint32 rows=TotalSize.cy/block_size.cy; agint32 cols=TotalSize.cx/block_size.cx; for(agint32 i=0; i<rows; i++) { CAGtdRectVec* pRectVector=(CAGtdRectVec*)newAGOBJ_ARRAY_TYPE(); for(agint32 j=0; j<cols; j++) { AGTD_RECT rc; memset(&rc,0,sizeof(AGTD_RECT)); //goc trai,duoi rc.left =TotalRect.left + j*block_size.cx; rc.top=TotalRect.top + i*block_size.cy; //goc phai, tren if(j==cols-1) rc.right=TotalRect.right; else rc.right=rc.left + block_size.cx; if(i==rows-1) rc.bottom=TotalRect.bottom; else rc.bottom=rc.top + block_size.cy; pRectVector->Add(rc); } Add(pRectVector,agfalse); } return agtrue; } agbool CAGtdRectMatrix::CreateByCut(AGTD_RECT TotalRect, agint32 nRows, agint32 nCols) { RemoveAll(); if(nRows==0 || nCols==0) return false; SIZE TotalSize; TotalSize.cx=TotalRect.right-TotalRect.left; TotalSize.cy=TotalRect.bottom-TotalRect.top; SIZE block_size; block_size.cx=TotalSize.cx/nCols; block_size.cy=TotalSize.cy/nRows; return CreateByCut(TotalRect,block_size); } agbool CAGtdRectMatrix::CreateByCut(AGTD_RECT TotalRect, agint32 CXsizes[], agint32 nCXsizes, agint32 CYsizes[], agint32 nCYsizes) { RemoveAll(); if(CXsizes==NULL || nCXsizes==0 || CYsizes==NULL || nCYsizes==0) throw _T("Invalid parameter"); SIZE TotalSize; TotalSize.cx=TotalRect.right-TotalRect.left; TotalSize.cy=TotalRect.bottom-TotalRect.top; if(TotalSize.cx<=0 || TotalSize.cy<=0) return agfalse; agint32 accum_cy=0; for(agint32 i=0; i<nCYsizes; i++) { agint32 cy=CYsizes[i]; if(cy<=0) throw _T("Invalid parameter"); CAGtdRectVec* pRectVector=(CAGtdRectVec*)newAGOBJ_ARRAY_TYPE(); agint32 accum_cx=0; AGTD_RECT rc; for(agint32 j=0; j<nCXsizes; j++) { agint32 cx=CXsizes[j]; if(cx<=0) throw _T("Invalid parameter"); memset(&rc,0,sizeof(AGTD_RECT)); //goc trai,duoi rc.left = TotalRect.left + accum_cx; rc.top = TotalRect.top + accum_cy; //goc phai, tren rc.right=rc.left + cx; if(rc.right > TotalRect.right) rc.right = TotalRect.right; rc.bottom=rc.top + cy; if(rc.bottom > TotalRect.bottom) rc.bottom = TotalRect.bottom; pRectVector->Add(rc); if(rc.right == TotalRect.right) break; accum_cx +=cx; } Add(pRectVector,agfalse); if(rc.bottom == TotalRect.bottom) break; accum_cy +=cy; } return agtrue; }
[ "ngphloc@gmail.com" ]
ngphloc@gmail.com
ee754d00b71e0871218baf7acc982536b889ee37
9eb72d37e42708e570642fca3cb4e3909231a96d
/daemon/src/Notifier.cpp
c204b145a399a55cf743e9d3e78a2a495e009a31
[ "Apache-2.0" ]
permissive
niojuju/ibrdtn
ed786b4211d994580fdeb18f3308868a8dd4eb79
0505267fbd83587e52bd288e2360f90d953d8ffb
refs/heads/master
2021-01-17T17:43:55.328441
2011-12-22T08:01:35
2011-12-22T08:01:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,321
cpp
/* * Notifier.cpp * * Created on: 11.12.2009 * Author: morgenro */ #include "Notifier.h" #include "core/NodeEvent.h" #include <stdlib.h> #include <sstream> namespace dtn { namespace daemon { using namespace dtn::core; Notifier::Notifier(std::string cmd) : _cmd(cmd) { } Notifier::~Notifier() { } void Notifier::componentUp() { bindEvent(NodeEvent::className); } void Notifier::componentDown() { unbindEvent(NodeEvent::className); } void Notifier::raiseEvent(const dtn::core::Event *evt) { const NodeEvent *node = dynamic_cast<const NodeEvent*>(evt); if (node != NULL) { std::stringstream msg; switch (node->getAction()) { case NODE_AVAILABLE: msg << "Node is available: " << node->getNode().toString(); notify("IBR-DTN", msg.str()); break; case NODE_UNAVAILABLE: msg << "Node is unavailable: " << node->getNode().toString(); notify("IBR-DTN", msg.str()); break; default: break; } } } void Notifier::notify(std::string title, std::string msg) { std::stringstream notifycmd; notifycmd << _cmd; notifycmd << " \"" << title << "\" \"" << msg << "\""; system(notifycmd.str().c_str()); } const std::string Notifier::getName() const { return "Notifier"; } } }
[ "morgenro@1cffb75b-d306-6187-5d55-5a277715007a" ]
morgenro@1cffb75b-d306-6187-5d55-5a277715007a
7f9b0020262ef6adf6d2bd0685802707330c55b8
cda2815b7c6efb39d6efe7cc42031fcb454a3617
/hpx-tutorial-examples/fibonacci.cpp
2de04595a8a4c5311d4eac4e8e37524ae229f60b
[ "BSD-3-Clause-Open-MPI" ]
permissive
hadimontakhabi/VolpexMPI-HPX
9ebcc99a92317946e28f526f6f4ed57dc23a1944
12356d9f657ae2b872d1923fee10d162c2b77851
refs/heads/master
2021-01-10T11:06:11.250922
2015-10-12T14:38:43
2015-10-12T14:38:43
44,113,069
0
1
null
null
null
null
UTF-8
C++
false
false
2,871
cpp
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2011 Bryce Lelbach // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) //////////////////////////////////////////////////////////////////////////////// // Naive SMP version implemented with futures. #include <hpx/hpx_init.hpp> #include <hpx/include/actions.hpp> #include <hpx/include/util.hpp> #include <iostream> #include <boost/cstdint.hpp> #include <boost/format.hpp> /////////////////////////////////////////////////////////////////////////////// //[fib_action // forward declaration of the Fibonacci function boost::uint64_t fibonacci(boost::uint64_t n); // This is to generate the required boilerplate we need for the remote // invocation to work. HPX_PLAIN_ACTION(fibonacci, fibonacci_action); //] /////////////////////////////////////////////////////////////////////////////// //[fib_func boost::uint64_t fibonacci(boost::uint64_t n) { if (n < 2) return n; // We restrict ourselves to execute the Fibonacci function locally. hpx::naming::id_type const locality_id = hpx::find_here(); // Invoking the Fibonacci algorithm twice is inefficient. // However, we intentionally demonstrate it this way to create some // heavy workload. using hpx::lcos::future; using hpx::async; fibonacci_action fib; future<boost::uint64_t> n1 = async(fib, locality_id, n - 1); future<boost::uint64_t> n2 = async(fib, locality_id, n - 2); return n1.get() + n2.get(); // wait for the Futures to return their values } //] /////////////////////////////////////////////////////////////////////////////// //[fib_hpx_main int hpx_main(boost::program_options::variables_map& vm) { // extract command line argument, i.e. fib(N) boost::uint64_t n = vm["n-value"].as<boost::uint64_t>(); { // Keep track of the time required to execute. hpx::util::high_resolution_timer t; // Wait for fib() to return the value fibonacci_action fib; boost::uint64_t r = fib(hpx::find_here(), n); char const* fmt = "fibonacci(%1%) == %2%\nelapsed time: %3% [s]\n"; std::cout << (boost::format(fmt) % n % r % t.elapsed()); } return hpx::finalize(); // Handles HPX shutdown } //] /////////////////////////////////////////////////////////////////////////////// //[fib_main int main(int argc, char* argv[]) { // Configure application-specific options boost::program_options::options_description desc_commandline("Usage: " HPX_APPLICATION_STRING " [options]"); desc_commandline.add_options() ( "n-value", boost::program_options::value<boost::uint64_t>()->default_value(10), "n value for the Fibonacci function") ; // Initialize and run HPX return hpx::init(desc_commandline, argc, argv); } //]
[ "hadi.montakhabi@gmail.com" ]
hadi.montakhabi@gmail.com
c4d2a6426bb951a19517e363debbae5c560df054
d7b5b64f6806c554eb29c32d0a846bd6c434e683
/Lab03/Bai 2/main.cpp
6c0afa8aedf3d50083df00747eb9294affde0d2c
[]
no_license
18520339/oop-lab
477325f7d350f21b6cf1b8eaf9bdc56a0d46ae15
da11c5586c1eca2616229d46029ade21c4721cc2
refs/heads/master
2023-01-24T16:21:07.031005
2020-12-13T16:39:09
2020-12-13T16:39:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
313
cpp
#include "TamGiac.h" int main() { TamGiac ABC; ABC.NhapTamGiac(); ABC.XuatTamGiac(); ABC.VeTamGiac(); ABC.TinhTienTamGiac(50, 50); ABC.XuatTamGiac(); ABC.VeTamGiac(); ABC.ThuPhongTamGiac(2); ABC.XuatTamGiac(); ABC.QuayTamGiac(180); ABC.XuatTamGiac(); cout << endl; system("pause"); return 0; }
[ "18520339@gm.uit.edu.vn" ]
18520339@gm.uit.edu.vn
b1ba1b5f5ca6a40870dd075542180346c905a491
8639ff9641d85811674a382d5dfd23ca184a4353
/src/util/math_util_complex.hpp
fda6030c915785b3982f072028ff1b129625565d
[]
no_license
IBirdSoft/openfpm_data_3.0.0
f85a8c050ed0a4aab46acd914dd7ffe44d70aa78
ea9ff5daf0feb8de5c28eae1e8858cbed801ed45
refs/heads/master
2022-12-28T22:08:35.867548
2020-10-16T00:46:06
2020-10-16T00:46:06
272,806,231
0
1
null
null
null
null
UTF-8
C++
false
false
1,661
hpp
/* * math_util_complex.hpp * * Created on: Oct 1, 2017 * Author: i-bird */ #ifndef OPENFPM_DATA_SRC_UTIL_MATH_UTIL_COMPLEX_DIOCANE_HPP_ #define OPENFPM_DATA_SRC_UTIL_MATH_UTIL_COMPLEX_DIOCANE_HPP_ //! extern vector for getFactorization extern std::vector<int> sieve_spf; namespace openfpm { namespace math { #define SIEVE_MAXN 4096 /*! \brief Precompute SPF (Smallest Prime Factor) for every * number till MAXN. * Time Complexity : O(nloglogn) * */ void inline init_getFactorization() { sieve_spf.resize(SIEVE_MAXN); sieve_spf[1] = 1; for (int i = 2; i < SIEVE_MAXN; i++) { // marking smallest prime factor for every // number to be itself. sieve_spf[i] = i; } // separately marking spf for every even // number as 2 for (int i = 4; i < SIEVE_MAXN; i += 2) {sieve_spf[i] = 2;} for (int i = 3; i*i < SIEVE_MAXN; i++) { // checking if i is prime if (sieve_spf[i] == i) { // marking SPF for all numbers divisible by i for (int j=i*i; j < SIEVE_MAXN; j+=i) { // marking spf[j] if it is not // previously marked if (sieve_spf[j] == j) {sieve_spf[j] = i;} } } } } /*! \brief A O(log n) function returning prime factorization * by dividing by smallest prime factor at every step * * \param x number to factor * \param factorization output * */ inline void getFactorization(int x, std::vector<size_t> & ret) { ret.clear(); while (x != 1) { ret.push_back(sieve_spf[x]); x = x / sieve_spf[x]; } } } } #endif /* OPENFPM_DATA_SRC_UTIL_MATH_UTIL_COMPLEX_DIOCANE_HPP_ */
[ "incardon@mpi-cbg.de" ]
incardon@mpi-cbg.de
2825d3c73be7f3d251b2dbc1a9eb6bb5e5293dd3
a78aa555b175e699c96553e3d714066bcc281ed8
/model/propertyclassvalue.cpp
8c7ade049cf7e58d070dbee42afadd558270d191
[ "Apache-2.0" ]
permissive
rdffg/bcaa_importer
0cb503c289002e573bcf8996178381cf001da742
f92e0b39673b5c557540154d4567c53a15adadcd
refs/heads/master
2021-08-28T16:05:39.936780
2021-08-20T20:00:53
2021-08-20T20:00:53
92,878,678
0
0
null
null
null
null
UTF-8
C++
false
false
3,037
cpp
#include "propertyclassvalue.h" namespace model { PropertyClassValue::PropertyClassValue(QObject *parent) : QDjangoModel(parent) { } Valuation *PropertyClassValue::grossValues() const { return qobject_cast<Valuation *>(foreignKey("grossValues")); } void PropertyClassValue::setGrossValues(Valuation *valuation) { setForeignKey("grossValues", valuation); } void PropertyClassValue::setGrossValues(std::unique_ptr<Valuation> valuation) { m_grossValues = valuation.get(); setGrossValues(valuation.release()); } Valuation *PropertyClassValue::taxExemptValues() const { return qobject_cast<Valuation *>(foreignKey("taxExemptValues")); } void PropertyClassValue::setTaxExemptValues(Valuation *valuation) { setForeignKey("taxExemptValues", valuation); } void PropertyClassValue::setTaxExemptValues(std::unique_ptr<Valuation> valuation) { m_taxExemptValues = valuation.release(); setTaxExemptValues(m_taxExemptValues); } Valuation *PropertyClassValue::netValues() const { return qobject_cast<Valuation *>(foreignKey("netValues")); } void PropertyClassValue::setNetValues(Valuation *valuation) { setForeignKey("netValues", valuation); } void PropertyClassValue::setNetValues(std::unique_ptr<Valuation> valuation) { m_netValues = valuation.release(); setNetValues(m_netValues); } QString PropertyClassValue::propertyClassCode() const { return m_propertyClassCode; } void PropertyClassValue::setPropertyClassCode(const QString &code) { m_propertyClassCode = code; } QString PropertyClassValue::propertyClassDescription() const { return m_propertyClassDescription; } void PropertyClassValue::setPropertyClassDescription(const QString &description) { m_propertyClassDescription = description; } QString PropertyClassValue::propertySubClassCode() const { return m_propertySubClassCode; } void PropertyClassValue::setPropertySubClassCode(const QString &code) { m_propertySubClassCode = code; } QString PropertyClassValue::propertySubClassDescription() const { return m_propertySubClassDescription; } void PropertyClassValue::setPropertySubClassDescription(const QString &description) { m_propertySubClassDescription = description; } PropertyClassValueType* PropertyClassValue::valueType() const { return qobject_cast<PropertyClassValueType *>(foreignKey("valueType")); } void PropertyClassValue::setValueType(PropertyClassValueType *type) { setForeignKey("valueType", type); } void PropertyClassValue::setValueType(std::unique_ptr<PropertyClassValueType> type) { m_valueType = type.release(); setForeignKey("valueType", m_valueType); } Folio *PropertyClassValue::folio() const { return qobject_cast<Folio *>(foreignKey("folio")); } void PropertyClassValue::setFolio(Folio *folio) { setForeignKey("folio", folio); } PropertyClassValue::~PropertyClassValue() { delete foreignKey("grossValues"); delete foreignKey("netValues"); delete foreignKey("taxExemptValues"); delete m_valueType; } } // namespace model
[ "dmahoney@rdffg.bc.ca" ]
dmahoney@rdffg.bc.ca
02f9b0313a5ebdf9df796f76c529ec0f0b7b0b7f
8199728ed6b05f5800387a2c9c52adbffc7a1859
/tensorflow/core/tfrt/saved_model/python/saved_model_load_and_run_wrapper.cc
270d3ab01fd7f3653e92859aa0a22f9efa99ef80
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
Manas1820/tensorflow
7d2c578edb06992173d0f646258113ae21dd3d89
c6dcf8e91a46d60b898dacd2f8e94b6e46a706a4
refs/heads/master
2023-09-01T11:50:58.798938
2023-07-13T23:45:54
2023-07-13T23:50:20
233,268,851
2
0
Apache-2.0
2022-09-08T12:56:41
2020-01-11T17:21:09
C++
UTF-8
C++
false
false
1,883
cc
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "pybind11/detail/common.h" // from @pybind11 #include "pybind11/pybind11.h" // from @pybind11 #include "pybind11/stl.h" // from @pybind11 #include "pybind11_abseil/status_casters.h" // from @pybind11_abseil #include "tensorflow/core/tfrt/graph_executor/graph_execution_options.h" #include "tensorflow/core/tfrt/saved_model/python/saved_model_load_and_run.h" #include "tensorflow/python/lib/core/pybind11_lib.h" namespace py = pybind11; namespace tensorflow::tfrt_stub { PYBIND11_MODULE(_pywrap_saved_model, m) { py::google::ImportStatusModule(); m.def("LoadSavedModel", &tensorflow::tfrt_stub::LoadSavedModel, py::arg("saved_model_dir") = absl::string_view(), py::arg("tags") = std::unordered_set<std::string>()); m.def("Run", &tensorflow::tfrt_stub::Run, py::arg("saved_model") = *(tensorflow::tfrt_stub::LoadSavedModel("", {}).value()), py::arg("run_options") = tensorflow::tfrt_stub::GraphExecutionRunOptions(), py::arg("name") = absl::string_view(), py::arg("inputs") = absl::Span<const tensorflow::Tensor>(), py::arg("outputs") = std::vector<tensorflow::Tensor>()); } } // namespace tensorflow::tfrt_stub
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
5edce87284f4fe0a041d308a54aad1a1e081108c
0518e53526c214da6142d940c42a428ec7d58122
/CWE-399/source_files/117122/CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_74b.cpp
0ec2cb36bde8192d3b3dcb1ae4af20f49f369864
[ "Apache-2.0" ]
permissive
Adam-01/VulDeePecker
eb03cfa2b94d736b1cba17fb1cdcb36b01e18f5e
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
refs/heads/master
2023-03-21T07:37:26.904949
2020-11-17T19:40:13
2020-11-17T19:40:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,536
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_74b.cpp Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml Template File: sources-sinks-74b.tmpl.cpp */ /* * @description * CWE: 789 Uncontrolled Memory Allocation * BadSource: fscanf Read data from the console using fscanf() * GoodSource: Small number greater than zero * Sinks: * GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated * BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated * Flow Variant: 74 Data flow: data passed in a map from one function to another in different source files * * */ #include "std_testcase.h" #include <map> #ifndef _WIN32 #include <wchar.h> #endif #define HELLO_STRING "hello" using namespace std; namespace CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_74 { #ifndef OMITBAD void badSink(map<int, size_t> dataMap) { /* copy data out of dataMap */ size_t data = dataMap[2]; { char * myString; /* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough * for the strcpy() function to not cause a buffer overflow */ /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */ if (data > strlen(HELLO_STRING)) { myString = (char *)malloc(data*sizeof(char)); /* Copy a small string into myString */ strcpy(myString, HELLO_STRING); printLine(myString); free(myString); } else { printLine("Input is less than the length of the source string"); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(map<int, size_t> dataMap) { size_t data = dataMap[2]; { char * myString; /* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough * for the strcpy() function to not cause a buffer overflow */ /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */ if (data > strlen(HELLO_STRING)) { myString = (char *)malloc(data*sizeof(char)); /* Copy a small string into myString */ strcpy(myString, HELLO_STRING); printLine(myString); free(myString); } else { printLine("Input is less than the length of the source string"); } } } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink(map<int, size_t> dataMap) { size_t data = dataMap[2]; { char * myString; /* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough * for the strcpy() function to not cause a buffer overflow */ /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */ if (data > strlen(HELLO_STRING) && data < 100) { myString = (char *)malloc(data*sizeof(char)); /* Copy a small string into myString */ strcpy(myString, HELLO_STRING); printLine(myString); free(myString); } else { printLine("Input is less than the length of the source string or too large"); } } } #endif /* OMITGOOD */ } /* close namespace */
[ "王苏菲" ]
王苏菲
6178be1c82110d9b9bcd9c8819cfaea77cfc43d6
bf21ca6365e5b99e4bae65d645dc2a97d2eb424f
/Text Decoding Messages.cpp
87e9f36f8f15f08d29f06fc9737b6669f93b9ec4
[]
no_license
thinkphp/GeeksforGeeks
4d0dc4dd4d9aebdd176dadf50524b7c3008bc3bd
6fa75e6fddae083d2f4ebed70c6fd4e9a2cbe063
refs/heads/master
2021-09-08T23:36:58.903085
2021-09-03T16:42:47
2021-09-03T16:42:47
87,708,186
1
3
null
null
null
null
UTF-8
C++
false
false
691
cpp
#include<bits/stdc++.h> using namespace std; int total_codes(string str,int i,int j) { if(i>j ) return 1; if(str[i]=='0') return 0; if(i==j) return 1; if(str[i]=='1') return total_codes(str,i+1,j)+total_codes(str,i+2,j); else if(str[i]=='2' && str[i+1]>='0' && str[i+1]<='6') return total_codes(str,i+1,j)+total_codes(str,i+2,j); else return total_codes(str,i+1,j); } int main() { int t; cin>>t; cin.ignore(); while(t--) { int n; cin>>n; string str; cin>>str; int ans=total_codes(str,0,n-1); cout<<ans<<endl; } return 0; }
[ "mergesortv@gmail.com" ]
mergesortv@gmail.com
1ee901e370903a029d1026f71fac0e0897b607e3
36be9459adb84677e935265c83b6e7b0b73b0a2b
/Unreal/CarlaUE4/Plugins/Carla/Source/Carla/DynamicWeather.cpp
15c0348d6ff13a702a62a03bc3bfb61702f25dd7
[ "MIT", "CC-BY-4.0" ]
permissive
zhao-zh10/carla
4d746153d38f5cdef092eb1f396476cbb6dba92f
00652c92de60deb23ebef956eccb3b27c81e5a9a
refs/heads/master
2020-04-24T19:06:12.907222
2019-02-13T20:40:14
2019-02-22T10:10:27
172,201,356
2
0
MIT
2019-02-23T10:30:07
2019-02-23T10:30:07
null
UTF-8
C++
false
false
6,751
cpp
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include "Carla.h" #include "DynamicWeather.h" #include "Util/IniFile.h" #include "Components/ArrowComponent.h" static FString GetIniFileName(const FString &MapName = TEXT("")) { const FString BaseName = TEXT("CarlaWeather"); constexpr auto Sep = TEXT("."); constexpr auto Ext = TEXT(".ini"); return (MapName.IsEmpty() ? (BaseName + Ext) : (BaseName + Sep + MapName + Ext)); } static bool GetWeatherIniFilePath(const FString &FileName, FString &FilePath) { FilePath = FPaths::Combine(FPaths::ProjectConfigDir(), FileName); const bool bFileExists = FPaths::FileExists(FilePath); if (!bFileExists) { UE_LOG(LogCarla, Warning, TEXT("\"%s\" not found"), *FilePath); } return bFileExists; } static bool CheckWeatherValidity(const FWeatherDescription &Weather) { if (Weather.Name.IsEmpty()) { UE_LOG(LogCarla, Error, TEXT("Weather doesn't have a name, please provide one")); return false; } return true; } void ADynamicWeather::LoadWeatherDescriptionsFromFile( const FString &MapName, TArray<FWeatherDescription> &Descriptions) { // Try to load config file. FString DefaultFilePath; if (GetWeatherIniFilePath(GetIniFileName(), DefaultFilePath)) { UE_LOG(LogCarla, Log, TEXT("Loading weather description from %s"), *DefaultFilePath); FIniFile ConfigFile(DefaultFilePath); { // Override map specific presets. FString MapOverridesFilePath; if (GetWeatherIniFilePath(GetIniFileName(MapName), MapOverridesFilePath)) { UE_LOG(LogCarla, Log, TEXT("Loading weather description from %s"), *MapOverridesFilePath); ConfigFile.Combine(MapOverridesFilePath); } } // For every section in the config file add a weather description. for (auto &Item : ConfigFile.GetFConfigFile()) { Descriptions.AddDefaulted(1u); Descriptions.Last().ReadFromConfigFile(ConfigFile, Item.Key); } } // If no description was found, append a defaulted one. if (Descriptions.Num() == 0) { UE_LOG(LogCarla, Warning, TEXT("No weather description found")); Descriptions.AddDefaulted(1u); Descriptions.Last().Name = TEXT("Default"); } } ADynamicWeather::ADynamicWeather(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) #if WITH_EDITORONLY_DATA , FileName(GetIniFileName()) #endif // WITH_EDITORONLY_DATA { PrimaryActorTick.bCanEverTick = false; RootComponent = ObjectInitializer.CreateDefaultSubobject<USceneComponent>(this, TEXT("SceneComponent0")); #if WITH_EDITORONLY_DATA ArrowComponent = CreateEditorOnlyDefaultSubobject<UArrowComponent>(TEXT("ArrowComponent0")); if (ArrowComponent) { ArrowComponent->ArrowColor = FColor(150, 200, 255); ArrowComponent->bTreatAsASprite = true; ArrowComponent->SpriteInfo.Category = TEXT("Lighting"); ArrowComponent->SpriteInfo.DisplayName = NSLOCTEXT( "SpriteCategory", "Lighting", "Lighting" ); ArrowComponent->SetupAttachment(RootComponent); ArrowComponent->bLightAttachment = true; ArrowComponent->bIsScreenSizeScaled = true; } #endif // WITH_EDITORONLY_DATA } void ADynamicWeather::OnConstruction(const FTransform &Transform) { Super::OnConstruction(Transform); #if WITH_EDITOR Update(); #endif // WITH_EDITOR } void ADynamicWeather::BeginPlay() { Super::BeginPlay(); #if WITH_EDITOR Update(); #endif // WITH_EDITOR } #if WITH_EDITOR void ADynamicWeather::PostEditChangeProperty(FPropertyChangedEvent &Event) { Super::PostEditChangeProperty(Event); const FName PropertyName = (Event.Property != NULL ? Event.Property->GetFName() : NAME_None); if (PropertyName == GET_MEMBER_NAME_CHECKED(ADynamicWeather, Weather)) { Update(); } else if ((PropertyName == GET_MEMBER_NAME_CHECKED(ADynamicWeather, bSaveToConfigFile)) || (PropertyName == GET_MEMBER_NAME_CHECKED(ADynamicWeather, bLoadFromConfigFile))) { // Do nothing. } else { AdjustSunPositionBasedOnActorRotation(); } if (bSaveToConfigFile) { bSaveToConfigFile = false; if (SaveToConfigFile()) { UE_LOG(LogCarla, Log, TEXT("Weather \"%s\" saved to config file"), *Weather.Name); } else { UE_LOG(LogCarla, Error, TEXT("Error saving weather to config file")); } } if (bLoadFromConfigFile) { bLoadFromConfigFile = false; if (LoadFromConfigFile()) { UE_LOG(LogCarla, Log, TEXT("Weather \"%s\" loaded from config file"), *Weather.Name); Update(); } else { UE_LOG(LogCarla, Error, TEXT("Error loading weather from config file")); } } } void ADynamicWeather::EditorApplyRotation( const FRotator &DeltaRotation, bool bAltDown, bool bShiftDown, bool bCtrlDown) { Super::EditorApplyRotation(DeltaRotation, bAltDown, bShiftDown, bCtrlDown); AdjustSunPositionBasedOnActorRotation(); } #endif // WITH_EDITOR FVector ADynamicWeather::GetSunDirection() const { const FVector2D SphericalCoords( FMath::DegreesToRadians(Weather.SunPolarAngle), FMath::DegreesToRadians(Weather.SunAzimuthAngle)); return - SphericalCoords.SphericalToUnitCartesian(); } void ADynamicWeather::AdjustSunPositionBasedOnActorRotation() { const FVector Direction = - GetActorQuat().GetForwardVector(); const FVector2D SphericalCoords = Direction.UnitCartesianToSpherical(); Weather.SunPolarAngle = FMath::RadiansToDegrees(SphericalCoords.X); Weather.SunAzimuthAngle = FMath::RadiansToDegrees(SphericalCoords.Y); } #if WITH_EDITOR void ADynamicWeather::Update() { // Modify this actor's rotation according to Sun position. if (!SetActorRotation(FQuat(GetSunDirection().Rotation()), ETeleportType::None)) { UE_LOG(LogCarla, Warning, TEXT("Unable to rotate actor")); } if (bRefreshAutomatically) { RefreshWeather(); } } bool ADynamicWeather::LoadFromConfigFile() { FString FilePath; if (GetWeatherIniFilePath(FileName, FilePath) && CheckWeatherValidity(Weather)) { FIniFile ConfigFile(FilePath); if (!ConfigFile.HasSection(Weather.Name)) { UE_LOG(LogCarla, Error, TEXT("Weather \"%s\" is not present in config file"), *Weather.Name); return false; } Weather.ReadFromConfigFile(ConfigFile, Weather.Name); return true; } else { return false; } } bool ADynamicWeather::SaveToConfigFile() const { FString FilePath; if (GetWeatherIniFilePath(FileName, FilePath) && CheckWeatherValidity(Weather)) { FIniFile ConfigFile(FilePath); Weather.WriteToConfigFile(ConfigFile); return ConfigFile.Write(FilePath); } else { return false; } } #endif // WITH_EDITOR
[ "nsubiron@cvc.uab.es" ]
nsubiron@cvc.uab.es
3e96f88f03e75b22d5033d685af1f6d1a694a309
13d1081bc5d46f979580438a772f47b7dc15550c
/Projects/Engine/MGEngine/Include/TerrainGridsDecorator.h
16b350795d6b433a7224ba4a60922b63ad52a2b4
[]
no_license
hackerlank/code-2
090035cc470d77a13a589419da7b04d0b97419e8
c8e72ad7ce7440001293a10619cd01efe5cfd22f
refs/heads/master
2021-01-13T15:50:39.784391
2014-06-16T14:00:06
2014-06-16T14:00:06
null
0
0
null
null
null
null
GB18030
C++
false
false
4,849
h
/******************************************************************************/ #ifndef _TERRAINGRIDSDECORATOR_H_ #define _TERRAINGRIDSDECORATOR_H_ /******************************************************************************/ #include "EnginePreqs.h" #include "IWireframeManager.h" /******************************************************************************/ namespace MG { /** ----------------------------------------------------------------------------- #note: 地形网格线框线列表 ----------------------------------------------------------------------------- */ class TerrainChunkGridsLineList { public: TerrainChunkGridsLineList(); void build( TerrainManager* terrainMgr ); std::vector<Vec3> mLinePointList; }; /** ----------------------------------------------------------------------------- #note: 地形网格逻辑线框线列表 ----------------------------------------------------------------------------- */ class TerrainLogicGridsLineList { public: TerrainLogicGridsLineList(); void build( TerrainManager* terrainMgr ); std::vector<Vec3> mLinePointList; }; /** ----------------------------------------------------------------------------- #note: 地形网格线框线列表 ----------------------------------------------------------------------------- */ class TerrainTileGridsLineList { public: TerrainTileGridsLineList(); void build( TerrainManager* terrainMgr ); std::vector<Vec3> mLinePointList; }; /** ----------------------------------------------------------------------------- #note: 地形网格线框显示 ----------------------------------------------------------------------------- */ class TerrainGridsDecorator : public ITerrainGridsDecorator { public: TerrainGridsDecorator(const String& name, Scene* scene); virtual ~TerrainGridsDecorator(); /// 构造 virtual void rebuild(void); /// 刷新模型 virtual void refresh(void); /// 设置折线模型粗细 virtual void setBoldSize(Flt size); /// 得到折线模型粗细 virtual Flt getBoldSize(void); /// 设置颜色 virtual void setColour(Color colour); /// 得到颜色 virtual Color getColour(); /// 设置颜色 virtual void setChunkColour(Color colour); /// 设置颜色 virtual void setTileColour(Color colour); /// 设置可见度 virtual void setVisible(Bool visible); /// 得到可见度 virtual Bool getVisible(); protected: /// 创建多边形对象 void createOgreManualObject(); /// 销毁多边形对象 void destroyOgreManualObject(); /// 创建材质 void buildMaterial(void); /// 得到材质名字 Str getMaterialName(void); /// 构造Ogre可手动创建模型对象 void buildMesh(void); /// 构造Ogre可手动创建模型对象 void refreshMesh(void); ////////////////////////////////////////////////////// private: // 场景对象 Scene* mScene; /// 折线模型粗细 Flt mBoldSize; /// 颜色 ColourValue mChunkColour; /// 颜色 ColourValue mTileColour; /// 颜色 ColourValue mLogicColour; ////////////////////////////////////////////////////// /// Ogre可手动创建模型对象 Ogre::ManualObject* mOgreManualObject; /// 节点对象 MGSceneNode* mSceneNode; /// Ogre材质接口 Ogre::MaterialPtr mOgreMaterialPtr; //////////////////////////////////////////////////////// TerrainChunkGridsLineList mTerrainChunkGridsLineList; Int mTerrainChunkGridsLineBuildPointCount; //////////////////////////////////////////////////////// TerrainTileGridsLineList mTerrainTileGridsLineList; Int mTerrainTileGridsLineBuildPointCount; //////////////////////////////////////////////////////// TerrainLogicGridsLineList mTerrainLogicGridsLineList; Int mTerrainLogicGridsLineBuildPointCount; }; } /******************************************************************************/ #endif
[ "linhu917@126.com" ]
linhu917@126.com
ff8538a0966bd0ef29f79615f68a2b88ffdb0b8a
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/src/library/aux_definition.cpp
6110b545e7f9f26b352fde5ab45eaaaa47cbab62
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
2021-01-22T23:16:20.399562
2017-03-18T20:48:21
2017-03-18T20:48:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,247
cpp
/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <algorithm> #include "kernel/type_checker.h" #include "kernel/replace_fn.h" #include "library/locals.h" #include "library/placeholder.h" #include "library/module.h" #include "library/trace.h" #include "library/aux_definition.h" #include "library/unfold_macros.h" namespace lean { struct mk_aux_definition_fn { type_context & m_ctx; name m_prefix; unsigned m_next_idx; name_set m_found_univ_params; name_map<level> m_univ_meta_to_param; name_map<level> m_univ_meta_to_param_inv; name_set m_found_local; name_map<expr> m_meta_to_param; name_map<expr> m_meta_to_param_inv; buffer<name> m_level_params; buffer<expr> m_params; mk_aux_definition_fn(type_context & ctx): m_ctx(ctx), m_prefix("_aux_param"), m_next_idx(0) {} level collect(level const & l) { return replace(l, [&](level const & l) { if (is_meta(l)) { name const & id = meta_id(l); if (auto r = m_univ_meta_to_param.find(id)) { return some_level(*r); } else { name n = m_prefix.append_after(m_next_idx); m_next_idx++; level new_r = mk_param_univ(n); m_univ_meta_to_param.insert(id, new_r); m_univ_meta_to_param_inv.insert(n, l); m_level_params.push_back(n); return some_level(new_r); } } else if (is_param(l)) { lean_assert(!is_placeholder(l)); name const & id = param_id(l); if (!m_found_univ_params.contains(id)) { m_found_univ_params.insert(id); m_level_params.push_back(id); } } return none_level(); }); } levels collect(levels const & ls) { bool modified = false; buffer<level> r; for (level const & l : ls) { level new_l = collect(l); if (new_l != l) modified = true; r.push_back(new_l); } if (!modified) return ls; else return to_list(r); } expr collect(expr const & e) { return replace(e, [&](expr const & e, unsigned) { if (is_metavar(e)) { name const & id = mlocal_name(e); if (auto r = m_meta_to_param.find(id)) { return some_expr(*r); } else { expr type = m_ctx.infer(e); expr x = m_ctx.push_local("_x", type); m_meta_to_param.insert(id, x); m_meta_to_param_inv.insert(mlocal_name(x), e); m_params.push_back(x); return some_expr(x); } } else if (is_local(e)) { name const & id = mlocal_name(e); if (!m_found_local.contains(id)) { m_found_local.insert(id); m_params.push_back(e); } } else if (is_sort(e)) { return some_expr(update_sort(e, collect(sort_level(e)))); } else if (is_constant(e)) { return some_expr(update_constant(e, collect(const_levels(e)))); } return none_expr(); }); } /* Collect (and sort) dependencies of collected parameters */ void collect_and_normalize_dependencies(buffer<expr> & norm_params) { name_map<expr> new_types; for (unsigned i = 0; i < m_params.size(); i++) { expr x = m_params[i]; expr new_type = collect(m_ctx.instantiate_mvars(m_ctx.infer(x))); new_types.insert(mlocal_name(x), new_type); } local_context const & lctx = m_ctx.lctx(); std::sort(m_params.begin(), m_params.end(), [&](expr const & l1, expr const & l2) { return lctx.get_local_decl(l1).get_idx() < lctx.get_local_decl(l2).get_idx(); }); for (unsigned i = 0; i < m_params.size(); i++) { expr x = m_params[i]; expr type = *new_types.find(mlocal_name(x)); expr new_type = replace_locals(type, i, m_params.data(), norm_params.data()); expr new_param = m_ctx.push_local(local_pp_name(x), new_type, local_info(x)); norm_params.push_back(new_param); } } pair<environment, expr> operator()(name const & c, expr const & type, expr const & value, bool is_lemma, optional<bool> const & is_meta) { lean_assert(!is_lemma || is_meta); lean_assert(!is_lemma || *is_meta == false); expr new_type = collect(m_ctx.instantiate_mvars(type)); expr new_value = collect(m_ctx.instantiate_mvars(value)); environment const & env = m_ctx.env(); buffer<expr> norm_params; collect_and_normalize_dependencies(norm_params); new_type = replace_locals(new_type, m_params, norm_params); new_value = replace_locals(new_value, m_params, norm_params); expr def_type = m_ctx.mk_pi(norm_params, new_type); expr def_value = m_ctx.mk_lambda(norm_params, new_value); bool untrusted = false; if (is_meta) untrusted = *is_meta; else untrusted = use_untrusted(env, def_type) || use_untrusted(env, def_value); if (!untrusted) { def_type = unfold_untrusted_macros(env, def_type); def_value = unfold_untrusted_macros(env, def_value); } declaration d; if (is_lemma) { d = mk_theorem(c, to_list(m_level_params), def_type, def_value); } else { bool use_self_opt = true; d = mk_definition(env, c, to_list(m_level_params), def_type, def_value, use_self_opt, !untrusted); } environment new_env = module::add(env, check(env, d, true)); buffer<level> ls; for (name const & n : m_level_params) { if (level const * l = m_univ_meta_to_param_inv.find(n)) ls.push_back(*l); else ls.push_back(mk_param_univ(n)); } buffer<expr> ps; for (expr const & x : m_params) { if (expr const * m = m_meta_to_param_inv.find(mlocal_name(x))) ps.push_back(*m); else ps.push_back(x); } expr r = mk_app(mk_constant(c, to_list(ls)), ps); return mk_pair(new_env, r); } }; pair<environment, expr> mk_aux_definition(environment const & env, metavar_context const & mctx, local_context const & lctx, name const & c, expr const & type, expr const & value, optional<bool> const & is_meta) { type_context ctx(env, options(), mctx, lctx, transparency_mode::All); bool is_lemma = false; return mk_aux_definition_fn(ctx)(c, type, value, is_lemma, is_meta); } pair<environment, expr> mk_aux_definition(environment const & env, metavar_context const & mctx, local_context const & lctx, name const & c, expr const & value, optional<bool> const & is_meta) { type_context ctx(env, options(), mctx, lctx, transparency_mode::All); expr type = ctx.infer(value); bool is_lemma = false; return mk_aux_definition_fn(ctx)(c, type, value, is_lemma, is_meta); } pair<environment, expr> mk_aux_lemma(environment const & env, metavar_context const & mctx, local_context const & lctx, name const & c, expr const & type, expr const & value) { type_context ctx(env, options(), mctx, lctx, transparency_mode::All); bool is_lemma = true; optional<bool> is_meta(false); return mk_aux_definition_fn(ctx)(c, type, value, is_lemma, is_meta); } }
[ "leonardo@microsoft.com" ]
leonardo@microsoft.com
d3203f9b51077c47813a95098fef38582db5985d
777239c62f7652c2565deab167430118f3fd070c
/src/libary/muduo/base/ThreadLocal.h
e14ed64010945cc71a7e2b3a19f8a1af319b40c9
[]
no_license
zhuanxuhit/sockets
c7c01e836abb1f47bfa492eda130f35822206c82
f90249b44edb1ea1706964776170f20e06c85849
refs/heads/master
2021-01-18T07:58:53.442708
2017-04-11T00:32:32
2017-04-11T00:32:32
84,299,390
0
0
null
null
null
null
UTF-8
C++
false
false
1,938
h
// Use of this source code is governed by a BSD-style license // that can be found in the License file. // // Author: Shuo Chen (chenshuo at chenshuo dot com) #ifndef MUDUO_BASE_THREADLOCAL_H #define MUDUO_BASE_THREADLOCAL_H #include <muduo/base/Mutex.h> // MCHECK #include <boost/noncopyable.hpp> #include <pthread.h> namespace muduo { template<typename T> // 对于PDO的数据,我们会直接使用 __thread的关键字 // 而对于非PDO的数据,我们则是使用 pthread_key_create // 同过 pthread_key_create 创建的key 进程中的每个线程都能看到,但是每个线程可以通过 // pthread_setspecific 来设置线程自己的值 // pthread_getspecific 来获取线程自己的值 // int pthread_key_create(pthread_key_t *key, void (*destructor)(void*)); // destructor 的作用是:当当前线程结束的时候,如果当前的key不为null,那会调用 destructor 来释放资源 class ThreadLocal : boost::noncopyable { public: ThreadLocal() { // thread-specific data key creation MCHECK(pthread_key_create(&pkey_, &ThreadLocal::destructor)); } ~ThreadLocal() { MCHECK(pthread_key_delete(pkey_)); } T &value() { T *perThreadValue = static_cast<T *>(pthread_getspecific(pkey_)); if (!perThreadValue) { T *newObj = new T(); MCHECK(pthread_setspecific(pkey_, newObj)); perThreadValue = newObj; } return *perThreadValue; } private: static void destructor(void *x) { T *obj = static_cast<T *>(x); // 技巧检查类型的完整性 typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1]; T_must_be_complete_type dummy; (void) dummy; delete obj; } private: pthread_key_t pkey_; }; } #endif
[ "893051481@qq.com" ]
893051481@qq.com
5d6359124c4e8e5fe5edc01663e746262222c103
fb227e3635b5c06e49bad48928f7b6d3254c4dca
/intensive/finodabuscabinaria/nifflhein.cpp
bb312a087e6ac5bb593f0aa4a9b34b343636590c
[]
no_license
BryanValeriano/marathon
5be2ab354e49187c865f0296f7dfb5ab3c3d6c9b
8dadfad7d1a6822f61ba5ed4a06e998541515634
refs/heads/master
2022-09-11T00:06:14.982588
2022-09-03T17:01:30
2022-09-03T17:01:30
141,581,750
0
0
null
null
null
null
UTF-8
C++
false
false
1,154
cpp
#include <bits/stdc++.h> using namespace std; #define pb push_back #define mk make_pair #define fi first #define sec second typedef long long ll; const int INF = 0x3f3f3f3f; const int TAM = 1e3+2; vector< pair<int, ll> >graph[TAM]; bool visitados[TAM]; void dfs(int ini, int fim, ll tempo) { visitados[ini] = true; if(ini == fim) return; for(int i = 0; i < graph[ini].size(); i++) { pair<int, ll>vizinho = graph[ini][i]; if(!visitados[vizinho.fi] && vizinho.sec <= tempo) dfs(vizinho.fi, fim, tempo); } } int main() { ios::sync_with_stdio(false); int n; cin >> n; int m; cin >> m; for(int i = 0; i < m; i++) { int tmp1, tmp2; ll peso; cin >> tmp1 >> tmp2 >> peso; graph[tmp1].pb(mk(tmp2, peso)); graph[tmp2].pb(mk(tmp1, peso)); } ll ini = 0; ll fim = 1e9+3; ll meio; while(ini <= fim) { memset(visitados, 0, sizeof visitados); meio = (ini + fim) >> 1; dfs(0, n-1, meio); if(visitados[n-1])fim = meio - 1; else ini = meio + 1; } cout << ini << endl; return 0; }
[ "bryan_311@hotmail.com" ]
bryan_311@hotmail.com
818029c2325f04587228e9c5fa1a11fce3b21016
792f2ee67210556f224daf88ef0b9785becadc9b
/atcoder/Other/tkppc4_2_b.cpp
b5987cbe0eebfe6b057f3ab4593c384f8d6dc6c3
[]
no_license
firiexp/contest_log
e5b345286e7d69ebf2a599d4a81bdb19243ca18d
6474a7127d3a2fed768ebb62031d5ff30eeeef86
refs/heads/master
2021-07-20T01:16:47.869936
2020-04-30T03:27:51
2020-04-30T03:27:51
150,196,219
0
0
null
null
null
null
UTF-8
C++
false
false
2,323
cpp
#include <iostream> #include <algorithm> #include <iomanip> #include <map> #include <set> #include <queue> #include <stack> #include <numeric> #include <bitset> #include <cmath> static const int MOD = 1000000007; using ll = long long; using u32 = uint32_t; using namespace std; template<class T> constexpr T INF = ::numeric_limits<T>::max()/32*15+208; int main() { int n, m; cin >> n >> m; vector<vector<int>> G(n); for (int i = 0; i < n-1; ++i) { int a, b; scanf("%d %d", &a, &b); a--; b--; G[a].emplace_back(b); G[b].emplace_back(a); } deque<int> Q; stack<int> s; int cnt = 0; vector<int> visited(n, 0), num(n); s.emplace(0); while(!s.empty()){ int a = s.top(); s.pop(); visited[a]++; num[a] = cnt++; Q.emplace_front(a); for (auto &&i : G[a]) { if(!visited[i]) s.emplace(i); } } vector<int> dp(n); for (int i = 0; i < m; ++i) { int a; scanf("%d", &a); dp[a-1]++; } int k = -1; for (int xx = 0; xx < n; ++xx) { int i = Q.front(); Q.pop_front(); if(!(~k)) { for (auto &&j : G[i]) { if(num[i] < num[j]) dp[i] += dp[j]; } if(dp[i] == m) k = i; } } int l = -1, r = -1; for (auto &&i : G[k]) { if(dp[i]){ if(~r && ~l){ puts("trumpet"); return 0; }else if(~l){ r = i; }else { l = i; } } } while(~l){ int newl = -1; for (auto &&i : G[l]) { if(num[l] < num[i] && dp[i]){ if(~newl){ puts("trumpet"); return 0; }else newl = i; } } if(!(~newl)) break; l = newl; } while(~r){ int newr = -1; for (auto &&i : G[r]) { if(num[r] < num[i] && dp[i]){ if(~newr){ puts("trumpet"); return 0; }else newr = i; } } if(!(~newr)) break; r = newr; } puts("Yes"); return 0; }
[ "firiexp@PC.localdomain" ]
firiexp@PC.localdomain
319306659adc07ccddbf6a41210a841bca128efa
890eb8e28dab8463138d6ae80359c80c4cf03ddd
/PSS/LTESpecific/SRoHC/Code/Src/RohcCompPktDeciderCommon.cpp
b172f4b9fbc426b484bc3245a81b9e2467f34632
[]
no_license
grant-h/shannon_S5123
d8c8dd1a2b49a9fe08268487b0af70ec3a19a5b2
8f7acbfdcf198779ed2734635990b36974657b7b
refs/heads/master
2022-06-17T05:43:03.224087
2020-05-06T15:39:39
2020-05-06T15:39:39
261,804,799
7
1
null
null
null
null
UTF-8
C++
false
false
1,143
cpp
Line 96: [ROHC-COMP]Change Hop Limit, decide Extension 3 Line 105: [ROHC-COMP]Change Traffic Class, decide Extension 3 Line 131: [ROHC-COMP][RRnd1PktChooser] (CntId ==> %d) (Sn_k ==> %d, IPID_k ==> %d ,Ts_k ==> %d ) Line 357: [ROHC-COMP][RRnd0PktChooser](CntId ==> %d) (Sn_k ==> %d, IPID_k ==> %d ,Ts_k ==> %d ) Line 676: [ROHC-COMP][RohcUoRnd0PktChooser] (CntId ==> %d) (Sn_k ==> %d, IPID_k ==> %d ,Ts_k ==> %d ) Line 982: [ROHC-COMP][RohcUoRnd1PktChooser] (CntId ==> %d)(Sn_k ==> %d, IPID_k ==> %d ,Ts_k ==> %d ) Line 1182: [ROHC-COMP] Change DF, Decide Extension 3 Line 1190: [ROHC-COMP] Change TOS, Decide Extension 3 Line 1198: [ROHC-COMP] Change TTL, Decide Extension 3 Line 1206: [ROHC-COMP] Change Protocol, Decide Extension 3 Line 1218: [ROHC-COMP] In function RohcCompRtpPktDeciderAuxillarySet Line 1223: RTP SSRC changed . Move to IR state Line 1238: [ROHC-COMP]FlagChngIndicator is set. Sending IR-DYN packet and changing state to FO Line 1249: [ROHC-COMP]Change PayloadType, decide Extension 3 Line 1266: TS Stride changed Line 1292: [ROHC-COMP] Video Stream. Choose IR-DYN packet type Line 1298: TsStride is Zero. Send IR DYN
[ "grant.h.hernandez@gmail.com" ]
grant.h.hernandez@gmail.com
a1b2c2f8bdf829e6ec53c91c5f7be16a7691b045
69005ab4c8cc5d88d7996d47ac8def0b28730b95
/msvc-cluster-realistic-1000/src/dir_3/perf193.cpp
bf9862f0363aa6045947807d66b3c504acf7ff14
[]
no_license
sakerbuild/performance-comparisons
ed603c9ffa0d34983a7da74f7b2b731dc3350d7e
78cd8d7896c4b0255ec77304762471e6cab95411
refs/heads/master
2020-12-02T19:14:57.865537
2020-05-11T14:09:40
2020-05-11T14:09:40
231,092,201
0
0
null
null
null
null
UTF-8
C++
false
false
373
cpp
#include <Windows.h> #include <vector> #include <inc_7/header_148.h> static_assert(sizeof(GenClass_148) > 0, "failed"); #include <inc_7/header_142.h> static_assert(sizeof(GenClass_142) > 0, "failed"); #include <inc_0/header_2.h> static_assert(sizeof(GenClass_2) > 0, "failed"); std::vector<int> perf_func_193() { LoadLibrary("abc.dll"); return {193}; }
[ "10866741+Sipkab@users.noreply.github.com" ]
10866741+Sipkab@users.noreply.github.com
8302d0e5847d8fed2abe59813720a805749639e4
ad273708d98b1f73b3855cc4317bca2e56456d15
/aws-cpp-sdk-appsync/include/aws/appsync/AppSyncErrorMarshaller.h
1a6b2cb5de7482e89610a2087b78448b13c053f9
[ "MIT", "Apache-2.0", "JSON" ]
permissive
novaquark/aws-sdk-cpp
b390f2e29f86f629f9efcf41c4990169b91f4f47
a0969508545bec9ae2864c9e1e2bb9aff109f90c
refs/heads/master
2022-08-28T18:28:12.742810
2020-05-27T15:46:18
2020-05-27T15:46:18
267,351,721
1
0
Apache-2.0
2020-05-27T15:08:16
2020-05-27T15:08:15
null
UTF-8
C++
false
false
966
h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/appsync/AppSync_EXPORTS.h> #include <aws/core/client/AWSErrorMarshaller.h> namespace Aws { namespace Client { class AWS_APPSYNC_API AppSyncErrorMarshaller : public Aws::Client::JsonErrorMarshaller { public: Aws::Client::AWSError<Aws::Client::CoreErrors> FindErrorByName(const char* exceptionName) const override; }; } // namespace Client } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
869478f0c71563bc75c47f945696778a6aa7ae6f
43da44edfe35fa80e045b824277e3a5f31e3a10a
/Practical1 Design Patterns/BridgePattern/BridgePattern/Player.h
69a5f0b0e26fb5b943142bec770e1ce54cb22683
[]
no_license
Davidnln13/GamesEngineering2
882d4d6fe6be601f60d19fc1a62ae6c57cfa5d19
60031bf95481ddca82b08fff964395ee19fe4cdb
refs/heads/master
2020-03-29T20:16:54.896215
2019-03-21T11:50:07
2019-03-21T11:50:07
150,304,094
0
0
null
null
null
null
UTF-8
C++
false
false
199
h
#pragma once #include "Character.h" #include "DrawAPI.h" class Player : public Character { public: Player(DrawAPI* api) { this->api = api; } void Draw() { api->Draw(); } private: DrawAPI* api; };
[ "davidnln13@yahoo.com" ]
davidnln13@yahoo.com
78ccbc5271f74f181abbfd83d93d0f9bc0e96102
6fe353b1dda615f09235b33b5e051db4876cdba1
/TriggerBrainArduino/s160_pageDefinitons.ino
753f0de1d79804a74872b8acfe078b5734e8beea
[]
no_license
zambari/TriggerBrainArduino
51ed86070ae1a2bedfdb944628eba4485de8305f
1d6d743eaee078ee55e493005f1c16f21062e957
refs/heads/master
2021-01-16T19:25:50.874893
2017-08-21T17:17:15
2017-08-21T17:17:15
100,166,386
0
0
null
null
null
null
UTF-8
C++
false
false
1,272
ino
//#include <LinkedList.h> class Page_Sys : public PageBase { PageSubSys1 a; PageSubSys1 b; PageSubSys1 c; public: void populateSubPages() override { subPages->add(&a); subPages->add(&b); subPages->add(&c); subPageIndex = 0; subPageCount = subPages->size(); activeSubPage = subPages->get(0); } void handleButton(int buttnr) override { Serial.write("\n systembtBn"); Serial.write('0'+buttnr); Serial.write("\n"); } // void test() override { Serial.write('B'); } char *GetLabel() override { return "SYS"; } }; class Page_Diag : public PageBase { SubPageDiag a; SubPageDiag bsd; SubPageDiag csd; public: void populateSubPages() override { subPages->add(&a); subPages->add(&bsd); subPages->add(&csd); subPageIndex = 0; subPageCount = subPages->size(); activeSubPage = subPages->get(0); } void handleButton(int buttnr) override { Serial.write("\n diagbt"); Serial.write('0'+buttnr); Serial.write("\n"); } char *GetLabel() override { return "Diag"; } };
[ "zambarii@gmail.com" ]
zambarii@gmail.com
7658460f452dd5cb2c7298daa53f573c27377b17
01837a379a09f74f7ef43807533093fa716e71ac
/src/utils/xulrunner-sdk/mozilla/dom/AudioContextBinding.h
bc2d14ad712c233324145f3a067ca70e2b5de779
[]
no_license
lasuax/jorhy-prj
ba2061d3faf4768cf2e12ee2484f8db51003bd3e
d22ded7ece50fb36aa032dad2cc01deac457b37f
refs/heads/master
2021-05-05T08:06:01.954941
2014-01-13T14:03:30
2014-01-13T14:03:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,656
h
/* THIS FILE IS AUTOGENERATED - DO NOT EDIT */ #ifndef mozilla_dom_AudioContextBinding_h__ #define mozilla_dom_AudioContextBinding_h__ #include "mozilla/ErrorResult.h" #include "mozilla/dom/BindingDeclarations.h" #include "mozilla/dom/BindingUtils.h" #include "mozilla/dom/CallbackFunction.h" #include "mozilla/dom/DOMJSClass.h" #include "mozilla/dom/DOMJSProxyHandler.h" class XPCWrappedNativeScope; namespace mozilla { namespace dom { class AudioContext; } // namespace dom } // namespace mozilla namespace mozilla { namespace dom { class AudioBuffer; } // namespace dom } // namespace mozilla namespace mozilla { namespace dom { template <> struct PrototypeTraits<prototypes::id::AudioContext> { enum { Depth = 0 }; typedef mozilla::dom::AudioContext NativeType; }; template <> struct PrototypeIDMap<mozilla::dom::AudioContext> { enum { PrototypeID = prototypes::id::AudioContext }; }; } // namespace dom } // namespace mozilla namespace mozilla { namespace dom { class DecodeSuccessCallback : public CallbackFunction { public: inline DecodeSuccessCallback(JSContext* cx, JSObject* aOwner, JSObject* aCallback, bool* aInited) : CallbackFunction(cx, aOwner, aCallback, aInited) { } explicit inline DecodeSuccessCallback(CallbackFunction* aOther) : CallbackFunction(aOther) { } template <typename T> inline void Call(const T& thisObj, mozilla::dom::AudioBuffer& decodedData, ErrorResult& aRv) { CallSetup s(mCallback); if (!s.GetContext()) { aRv.Throw(NS_ERROR_UNEXPECTED); return; } JSObject* thisObjJS = WrapCallThisObject(s.GetContext(), mCallback, thisObj); if (!thisObjJS) { aRv.Throw(NS_ERROR_FAILURE); return; } return Call(s.GetContext(), thisObjJS, decodedData, aRv); } inline void Call(mozilla::dom::AudioBuffer& decodedData, ErrorResult& aRv) { CallSetup s(mCallback); if (!s.GetContext()) { aRv.Throw(NS_ERROR_UNEXPECTED); return; } return Call(s.GetContext(), nullptr, decodedData, aRv); } private: void Call(JSContext* cx, JSObject* aThisObj, mozilla::dom::AudioBuffer& decodedData, ErrorResult& aRv); }; class DecodeErrorCallback : public CallbackFunction { public: inline DecodeErrorCallback(JSContext* cx, JSObject* aOwner, JSObject* aCallback, bool* aInited) : CallbackFunction(cx, aOwner, aCallback, aInited) { } explicit inline DecodeErrorCallback(CallbackFunction* aOther) : CallbackFunction(aOther) { } template <typename T> inline void Call(const T& thisObj, ErrorResult& aRv) { CallSetup s(mCallback); if (!s.GetContext()) { aRv.Throw(NS_ERROR_UNEXPECTED); return; } JSObject* thisObjJS = WrapCallThisObject(s.GetContext(), mCallback, thisObj); if (!thisObjJS) { aRv.Throw(NS_ERROR_FAILURE); return; } return Call(s.GetContext(), thisObjJS, aRv); } inline void Call(ErrorResult& aRv) { CallSetup s(mCallback); if (!s.GetContext()) { aRv.Throw(NS_ERROR_UNEXPECTED); return; } return Call(s.GetContext(), nullptr, aRv); } private: void Call(JSContext* cx, JSObject* aThisObj, ErrorResult& aRv); }; namespace AudioContextBinding { extern const NativePropertyHooks sNativePropertyHooks; void CreateInterfaceObjects(JSContext* aCx, JSObject* aGlobal, JSObject** protoAndIfaceArray); inline JSObject* GetProtoObject(JSContext* aCx, JSObject* aGlobal) { /* Get the interface prototype object for this class. This will create the object as needed. */ /* Make sure our global is sane. Hopefully we can remove this sometime */ if (!(js::GetObjectClass(aGlobal)->flags & JSCLASS_DOM_GLOBAL)) { return NULL; } /* Check to see whether the interface objects are already installed */ JSObject** protoAndIfaceArray = GetProtoAndIfaceArray(aGlobal); JSObject* cachedObject = protoAndIfaceArray[prototypes::id::AudioContext]; if (!cachedObject) { CreateInterfaceObjects(aCx, aGlobal, protoAndIfaceArray); cachedObject = protoAndIfaceArray[prototypes::id::AudioContext]; } /* cachedObject might _still_ be null, but that's OK */ return cachedObject; } inline JSObject* GetConstructorObject(JSContext* aCx, JSObject* aGlobal) { /* Get the interface object for this class. This will create the object as needed. */ /* Make sure our global is sane. Hopefully we can remove this sometime */ if (!(js::GetObjectClass(aGlobal)->flags & JSCLASS_DOM_GLOBAL)) { return NULL; } /* Check to see whether the interface objects are already installed */ JSObject** protoAndIfaceArray = GetProtoAndIfaceArray(aGlobal); JSObject* cachedObject = protoAndIfaceArray[constructors::id::AudioContext]; if (!cachedObject) { CreateInterfaceObjects(aCx, aGlobal, protoAndIfaceArray); cachedObject = protoAndIfaceArray[constructors::id::AudioContext]; } /* cachedObject might _still_ be null, but that's OK */ return cachedObject; } JSObject* DefineDOMInterface(JSContext* aCx, JSObject* aGlobal, bool* aEnabled); bool PrefEnabled(); extern DOMJSClass Class; JSObject* Wrap(JSContext* aCx, JSObject* aScope, mozilla::dom::AudioContext* aObject, nsWrapperCache* aCache, bool* aTriedToWrap); template <class T> inline JSObject* Wrap(JSContext* aCx, JSObject* aScope, T* aObject, bool* aTriedToWrap) { return Wrap(aCx, aScope, aObject, aObject, aTriedToWrap); } } // namespace AudioContextBinding } // namespace dom } // namespace mozilla #endif // mozilla_dom_AudioContextBinding_h__
[ "joorhy@gmail.com" ]
joorhy@gmail.com
842f60ed009ea6dc79da38b91f19ab9dc4e4a8ea
3defa4fbbacaa92a1695df8570912fb35466bb98
/flashlight/autograd/backend/cpu/Conv2D.cpp
30a2bd32b38115c96fb987738e53981163e0f4dd
[ "MIT" ]
permissive
josephmisiti/flashlight
11dbaceee63be381bd49a077d3ddf47065b5b8a3
a1349e84c9be19ecbbdc28d2d5a8eeeaaaa06273
refs/heads/master
2020-04-12T21:09:45.637210
2018-12-21T20:30:46
2018-12-21T20:30:46
162,756,364
3
0
MIT
2018-12-21T20:44:52
2018-12-21T20:44:51
null
UTF-8
C++
false
false
15,647
cpp
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <array> #include <memory> #include <vector> #include <arrayfire.h> #include <mkldnn.hpp> #include <flashlight/autograd/Functions.h> #include <flashlight/autograd/Variable.h> #include <flashlight/common/DevicePtr.h> #include "MkldnnUtils.h" using namespace mkldnn; namespace fl { namespace { // Input, output: WHCN; weights: WHIO constexpr size_t kInputWIdx = 0; constexpr size_t kInputHIdx = 1; constexpr size_t kKernelWIdx = 0; constexpr size_t kKernelHIdx = 1; constexpr size_t kOutputChannelSizeIdx = 2; constexpr size_t kInputBatchSizeIdx = 3; constexpr size_t kInputChannelSizeIdx = 2; constexpr size_t kOutputWIdx = 0; constexpr size_t kOutputHIdx = 1; constexpr size_t kWeightOutputChannelSizeIdx = 3; } // namespace Variable conv2d( const Variable& input, const Variable& weights, int sx, int sy, int px, int py, int groups) { auto dummy_bias = Variable(af::array(), false); return conv2d(input, weights, dummy_bias, sx, sy, px, py, groups); } Variable conv2d( const Variable& input, const Variable& weights, const Variable& bias, int sx, int sy, int px, int py, int groups) { auto output = af::array( (input.dims(kInputWIdx) + (2 * px) - weights.dims(kKernelWIdx)) / sx + 1, (input.dims(kInputHIdx) + (2 * py) - weights.dims(kKernelHIdx)) / sy + 1, weights.dims(kWeightOutputChannelSizeIdx), input.dims(kInputBatchSizeIdx)); auto hasBias = bias.elements() > 0; // flashlight input, weight, and output shapes in column-major: // Input is WHCN // Weights are WHIO // Output is WHCN // Since ArrayFire is column major, getting a raw pointer (1D representation) // of these shapes and viewing as if the representation is row major // transposes along all axis into NCHW for the input and output and OIHW for // the weights - these are the shapes we use for the convolution. auto dataType = memory::data_type::f32; // float 32 by default, configurable // Use memory::format::any for memory formatting even if convolution inputs // are shaped a particular way. auto formatAny = memory::format::any; // MKL-DNN convention is to always shape the input and output as NHWC and // weights as HWIO regardless of the actual data shape. One cannot create a // convolution descriptor with other formatting options. auto formatNCHW = memory::format::nchw; auto formatWeight = (groups == 1) ? memory::format::oihw : memory::format::goihw; /********************************* Forward *******************************/ // Create memory dims memory::dims mInputDims = detail::convertAfToMklDnnDims({input.dims(kInputBatchSizeIdx), input.dims(kInputChannelSizeIdx), input.dims(kInputHIdx), input.dims(kInputWIdx)}); memory::dims mWeightDims; if (groups == 1) { mWeightDims = detail::convertAfToMklDnnDims( {weights.dims(kWeightOutputChannelSizeIdx), input.dims(kInputChannelSizeIdx), weights.dims(kKernelHIdx), weights.dims(kKernelWIdx)}); } else { mWeightDims = detail::convertAfToMklDnnDims( {groups, weights.dims(kWeightOutputChannelSizeIdx) / groups, input.dims(kInputChannelSizeIdx) / groups, weights.dims(kKernelHIdx), weights.dims(kKernelWIdx)}); } memory::dims mOutputDims = detail::convertAfToMklDnnDims({input.dims(kInputBatchSizeIdx), weights.dims(kWeightOutputChannelSizeIdx), output.dims(kOutputHIdx), output.dims(kOutputWIdx)}); memory::dims mBiasDims = detail::convertAfToMklDnnDims( {weights.dims(kWeightOutputChannelSizeIdx)}); memory::dims mStrideDims = {sy, sx}; memory::dims mPaddingDims = {py, px}; // Create memory descriptors. using format::any gives the best performance auto inputMD = memory::desc({mInputDims}, dataType, formatAny); auto outputMD = memory::desc({mOutputDims}, dataType, formatAny); auto weightMD = memory::desc({mWeightDims}, dataType, formatWeight); auto biasMD = memory::desc({mBiasDims}, dataType, formatAny); // Convolution descriptor std::shared_ptr<convolution_forward::desc> fwdDescriptor; if (hasBias) { fwdDescriptor = std::make_shared<convolution_forward::desc>( prop_kind::forward_training, convolution_direct, inputMD, weightMD, biasMD, outputMD, mStrideDims, mPaddingDims, mPaddingDims, padding_kind::zero); } else { fwdDescriptor = std::make_shared<convolution_forward::desc>( prop_kind::forward_training, convolution_direct, inputMD, weightMD, outputMD, mStrideDims, mPaddingDims, mPaddingDims, padding_kind::zero); } // Primitive descriptor auto mkldnnEngine = detail::MkldnnEngine::getInstance().getEngine(); auto fwdPrimDesc = std::make_shared<convolution_forward::primitive_desc>( *fwdDescriptor, mkldnnEngine); // Create memory DevicePtr inputRaw(input.array()); auto inputMemoryInit = memory( {{{mInputDims}, dataType, formatNCHW}, mkldnnEngine}, inputRaw.get()); DevicePtr outputRaw(output); auto outputMemoryInit = memory( {{{mOutputDims}, dataType, formatNCHW}, mkldnnEngine}, outputRaw.get()); DevicePtr weightsRaw(weights.array()); auto weightsMemoryInit = memory( {{{mWeightDims}, dataType, formatWeight}, mkldnnEngine}, weightsRaw.get()); // Network for execution std::vector<primitive> network; // MKL-DNN suggests checking if the layout requested for the convolution // is different from NCHW/OIHW (even if specified), and reordering if // necessary, since the convolution itself may request a different // ordering auto inputPrimDesc = fwdPrimDesc->src_primitive_desc(); auto weightsPrimDesc = fwdPrimDesc->weights_primitive_desc(); auto outputPrimDesc = fwdPrimDesc->dst_primitive_desc(); // Input auto inputMemory = detail::mkldnnAlignOrdering(network, inputMemoryInit, inputPrimDesc); auto weightsMemory = detail::mkldnnAlignOrdering(network, weightsMemoryInit, weightsPrimDesc); // Output - adds a reorder after the conv if needed auto outputMemory = outputMemoryInit; if (outputMemoryInit.get_primitive_desc() != memory::primitive_desc(outputPrimDesc)) { outputMemory = memory(outputPrimDesc); } // Create convolution std::shared_ptr<convolution_forward> conv; DevicePtr biasRaw(bias.array()); auto formatBias = memory::format::x; auto biasMemory = memory( {{{mBiasDims}, dataType, formatBias}, mkldnnEngine}, biasRaw.get()); if (hasBias) { conv = std::make_shared<convolution_forward>( *fwdPrimDesc, inputMemory, weightsMemory, biasMemory, outputMemory); } else { conv = std::make_shared<convolution_forward>( *fwdPrimDesc, inputMemory, weightsMemory, outputMemory); } network.push_back(*conv); // Add output reordering if needed if (outputMemory != outputMemoryInit) { network.push_back(mkldnn::reorder(outputMemory, outputMemoryInit)); } detail::MkldnnStream::getInstance().getStream().submit(network); /***************************** Backward ******************************/ auto gradFunc = [hasBias, // Types dataType, formatNCHW, formatWeight, // Dims mInputDims, mWeightDims, mOutputDims, mBiasDims, mStrideDims, mPaddingDims, // Memory descriptors inputMD, outputMD, weightMD, biasMD, fwdPrimDesc // used for creating a bw desc ](std::vector<Variable>& inputs, const Variable& grad_output) { auto& inputRef = inputs[0]; auto& weightRef = inputs[1]; auto mkldnnEngineBwd = detail::MkldnnEngine::getInstance().getEngine(); /*** Compute the gradient with respect to the input ***/ if (inputRef.isCalcGrad()) { // Result auto gradInput = Variable(af::array(inputRef.dims(), inputRef.type()), false); // Backward descriptor auto bwdDataDesc = std::make_shared<convolution_backward_data::desc>( convolution_direct, inputMD, weightMD, outputMD, mStrideDims, mPaddingDims, mPaddingDims, padding_kind::zero); // Primitive descriptor auto bwdDataPrimDesc = std::make_shared<convolution_backward_data::primitive_desc>( *bwdDataDesc, mkldnnEngineBwd, *fwdPrimDesc); // Create memory DevicePtr gradOutputRaw(grad_output.array()); auto gradOutputMemoryInit = memory( {{{mOutputDims}, dataType, formatNCHW}, mkldnnEngineBwd}, gradOutputRaw.get()); DevicePtr gradInputRaw(gradInput.array()); auto gradInputMemoryInit = memory( {{{mInputDims}, dataType, formatNCHW}, mkldnnEngineBwd}, gradInputRaw.get()); DevicePtr weightRaw(weightRef.array()); auto weightsMemoryInitBackwards = memory( {{{mWeightDims}, dataType, formatWeight}, mkldnnEngineBwd}, weightRaw.get()); std::vector<primitive> networkBackwards; // Check for reorderings auto gradOutputPrimitiveDesc = bwdDataPrimDesc->diff_dst_primitive_desc(); auto weightsPrimitiveDesc = bwdDataPrimDesc->weights_primitive_desc(); auto gradInputPrimitiveDesc = bwdDataPrimDesc->diff_src_primitive_desc(); auto gradOutputMemory = detail::mkldnnAlignOrdering( networkBackwards, gradOutputMemoryInit, gradOutputPrimitiveDesc); auto weightsMemoryBackwards = detail::mkldnnAlignOrdering( networkBackwards, weightsMemoryInitBackwards, weightsPrimitiveDesc); auto gradInputMemory = gradInputMemoryInit; // Don't reorder the gradient until after the conv if (gradInputMemoryInit.get_primitive_desc() != memory::primitive_desc(gradInputPrimitiveDesc)) { gradInputMemory = memory(gradInputPrimitiveDesc); } // Convolution backwards auto convBwdData = std::make_shared<convolution_backward_data>( *bwdDataPrimDesc, gradOutputMemory, weightsMemoryBackwards, gradInputMemory); networkBackwards.push_back(*convBwdData); detail::MkldnnStream::getInstance().getStream().submit(networkBackwards); // Reorder the output (which is gradInput here) if necessary if (gradInputMemory != gradInputMemoryInit) { networkBackwards.push_back( mkldnn::reorder(gradInputMemory, gradInputMemoryInit)); } inputRef.addGrad(gradInput); } /*** Compute the gradient with respect to weight and bias ***/ if (weightRef.isCalcGrad()) { // Result auto gradWeights = Variable(af::array(weightRef.dims(), weightRef.type()), false); Variable gradBias; bool computeBiasGrad = hasBias && inputs[2].isCalcGrad(); auto& biasRef = inputs[2]; if (computeBiasGrad) { gradBias = Variable(af::array(biasRef.dims(), biasRef.type()), false); } // Weight backward descriptor std::shared_ptr<convolution_backward_weights::desc> bwdWeightDesc; if (hasBias) { bwdWeightDesc = std::make_shared<convolution_backward_weights::desc>( convolution_direct, inputMD, weightMD, biasMD, outputMD, mStrideDims, mPaddingDims, mPaddingDims, padding_kind::zero); } else { bwdWeightDesc = std::make_shared<convolution_backward_weights::desc>( convolution_direct, inputMD, weightMD, outputMD, mStrideDims, mPaddingDims, mPaddingDims, padding_kind::zero); } // Weight backward primitive descriptor auto bwdWeightPrimDesc = std::make_shared<convolution_backward_weights::primitive_desc>( *bwdWeightDesc, mkldnnEngineBwd, *fwdPrimDesc); // Create memory DevicePtr inputRawBackwards(inputRef.array()); auto inputMemoryInitBackwards = memory( {{{mInputDims}, dataType, formatNCHW}, mkldnnEngineBwd}, inputRawBackwards.get()); DevicePtr gradOutputRaw(grad_output.array()); auto gradOutputMemoryInit = memory( {{{mOutputDims}, dataType, formatNCHW}, mkldnnEngineBwd}, gradOutputRaw.get()); DevicePtr gradWeightsRaw(gradWeights.array()); auto gradWeightsMemoryInit = memory( {{{mWeightDims}, dataType, formatWeight}, mkldnnEngineBwd}, gradWeightsRaw.get()); std::vector<primitive> networkBackwards; // Check for reorderings, reorder if needed auto inputPrimitiveDesc = bwdWeightPrimDesc->src_primitive_desc(); auto gradOutputPrimitiveDesc = bwdWeightPrimDesc->diff_dst_primitive_desc(); auto gradWeightsPrimitiveDesc = bwdWeightPrimDesc->diff_weights_primitive_desc(); auto inputMemoryBackwards = detail::mkldnnAlignOrdering( networkBackwards, inputMemoryInitBackwards, inputPrimitiveDesc); auto gradOutputMemory = detail::mkldnnAlignOrdering( networkBackwards, gradOutputMemoryInit, gradOutputPrimitiveDesc); // Don't reorder the grads until after the conv bwd auto gradWeightsMemory = gradWeightsMemoryInit; if (gradWeightsMemoryInit.get_primitive_desc() != memory::primitive_desc(gradWeightsPrimitiveDesc)) { gradWeightsMemory = memory(gradWeightsPrimitiveDesc); } // Create the convolution backward weight std::shared_ptr<convolution_backward_weights> bwdWeights; DevicePtr biasRawBackwards(gradBias.array()); auto formatBias = memory::format::x; auto gradBiasMemory = memory( {{{mBiasDims}, dataType, formatBias}, mkldnnEngineBwd}, biasRawBackwards.get()); if (hasBias) { bwdWeights = std::make_shared<convolution_backward_weights>( *bwdWeightPrimDesc, inputMemoryBackwards, gradOutputMemory, gradWeightsMemory, gradBiasMemory); } else { bwdWeights = std::make_shared<convolution_backward_weights>( *bwdWeightPrimDesc, inputMemoryBackwards, gradOutputMemory, gradWeightsMemory); } networkBackwards.push_back(*bwdWeights); // Reorder weight gradients if necessary if (gradWeightsMemory != gradWeightsMemoryInit) { networkBackwards.push_back( mkldnn::reorder(gradWeightsMemory, gradWeightsMemoryInit)); } detail::MkldnnStream::getInstance().getStream().submit(networkBackwards); // Add weight and bias gradients weightRef.addGrad(gradWeights); if (computeBiasGrad) { biasRef.addGrad(gradBias); } } }; // Return for forward if (hasBias) { return Variable(output, {input, weights, bias}, gradFunc); } return Variable(output, {input, weights}, gradFunc); } } // namespace fl
[ "vineelkpratap@fb.com" ]
vineelkpratap@fb.com
37e6dd62978844764f84e06927e4c55e3ea9385f
f4f9796d06385b3e2d78127ac4e5989b35658aa3
/Ch 12. Searching/Compute the integer square root.cpp
f7ad89244568ee5a28b7e9ea2ce231b6f438a600
[]
no_license
shashishailaj/epi
52e9c7dacc8bd7174d42605b9576314d2c40d102
98de8aaa89abcae8be6b4747301a248ea03a500b
refs/heads/master
2020-05-18T01:18:45.021403
2017-05-15T05:30:00
2017-05-19T19:49:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
617
cpp
#include <bits/stdc++.h> using namespace std; class Solution { public: int mySqrt(int x) { long long num = (long long)x; long long L = -1LL; long long R = num + 1; while (R - L > 1) { long long M = L + (R - L) / 2; if (M * M <= num) { L = M; } else { R = M; } } return L; } }; int main() { ios::sync_with_stdio(false); Solution solution; assert(solution.mySqrt(17) == 4); assert(solution.mySqrt(16) == 4); assert(solution.mySqrt(1) == 1); return 0; }
[ "linouk23@gmail.com" ]
linouk23@gmail.com
35a033d9c97729ab905f0e8c82d0b86fef5e6dba
916e7c5c7fc660dfdb58d235051fdfd9d1c53f41
/ThirdParty/BCGControlBar/BCGControlBar/BCGFileDialog.cpp
197dcebeb05b711d2ec256dd8df9998436a6ed02
[ "MIT" ]
permissive
palestar/gamecq
13a98686273aef446f80099a003f156eba351b86
1fe2dfa396769bb8bfbe2a47914a41e5e821a26b
refs/heads/develop
2020-12-24T18:24:05.416537
2020-02-08T20:38:01
2020-02-08T20:38:01
59,443,046
10
11
null
2016-12-12T15:34:27
2016-05-23T01:20:10
C++
UTF-8
C++
false
false
17,912
cpp
//******************************************************************************* // COPYRIGHT NOTES // --------------- // This is a part of the BCGControlBar Library // Copyright (C) 1998-2006 BCGSoft Ltd. // All rights reserved. // // This source code can be used, distributed or modified // only under terms and conditions // of the accompanying license agreement. //******************************************************************************* // BCGFileDialog.cpp : implementation file // #include "stdafx.h" #include "bcgbarres.h" #include "bcglocalres.h" #include "BCGFileDialog.h" #include "globals.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif class CNewItemInfo : public CObject { friend class CBCGFileDialog; CNewItemInfo (LPCTSTR lpszName, int iIconIndex) { m_strName = lpszName; m_iIconIndex = iIconIndex; } CString m_strName; int m_iIconIndex; }; ///////////////////////////////////////////////////////////////////////////// // CBCGFileDialog const int iTabCtrlId = 200; const int iNewListCtrlId = 201; const int iRecentListCtrlId = 202; WNDPROC CBCGFileDialog::m_wndProc; IMPLEMENT_DYNAMIC(CBCGFileDialog, CFileDialog) CBCGFileDialog::CBCGFileDialog (LPCTSTR lpszCaption, BOOL bNewPage, LPCTSTR lpszDefExt, LPCTSTR lpszFileName, DWORD dwFlags, LPCTSTR lpszFilter, CWnd* pParentWnd) : CFileDialog (TRUE /*bOpenFileDialog*/, lpszDefExt, lpszFileName, dwFlags, lpszFilter, pParentWnd), m_pImagesNew (NULL), m_bNewPage (bNewPage), m_strCaption (lpszCaption), m_hIconBig (NULL), m_hIconSmall (NULL), m_iLogoAreaHeight (0), m_iExtraWidth (0), m_iExtraHeight (0) { m_iNewItemIndex = -1; m_pBmpLogo = NULL; CDocManager* pDocManager = AfxGetApp ()->m_pDocManager; if (pDocManager != NULL && lpszFilter == NULL) { CString strDefault; BOOL bFirst = TRUE; m_strFilter.Empty(); for (POSITION pos = pDocManager->GetFirstDocTemplatePosition (); pos != NULL;) { CDocTemplate* pTemplate = pDocManager->GetNextDocTemplate (pos); ASSERT_VALID (pTemplate); CString strFilterExt, strFilterName; if (pTemplate->GetDocString (strFilterExt, CDocTemplate::filterExt) && !strFilterExt.IsEmpty() && pTemplate->GetDocString(strFilterName, CDocTemplate::filterName) && !strFilterName.IsEmpty()) { #if _MSC_VER >= 1300 int iStart = 0; m_strFilter += strFilterName; m_strFilter += (TCHAR)'\0'; do { CString strExtension = strFilterExt.Tokenize( _T( ";" ), iStart ); if (iStart != -1) { // a file based document template - add to filter list // If you hit the following ASSERT, your document template // string is formatted incorrectly. The section of your // document template string that specifies the allowable file // extensions should be formatted as follows: // .<ext1>;.<ext2>;.<ext3> // Extensions may contain wildcards (e.g. '?', '*'), but must // begin with a '.' and be separated from one another by a ';'. // Example: // .jpg;.jpeg ASSERT(strExtension[0] == '.'); if ( strDefault.IsEmpty() ) { // set the default extension strDefault = strExtension.Mid( 1 ); // skip the '.' m_ofn.lpstrDefExt = const_cast< LPTSTR >((LPCTSTR)strDefault); m_ofn.nFilterIndex = m_ofn.nMaxCustFilter + 1; // 1 based number } m_strFilter += (TCHAR)'*'; m_strFilter += strExtension; m_strFilter += (TCHAR)';'; // Always append a ';'. The last ';' will get replaced with a '\0' later. } } while (iStart != -1); m_strFilter.SetAt( m_strFilter.GetLength()-1, '\0' );; // Replace the last ';' with a '\0' m_ofn.nMaxCustFilter++; #else // a file based document template - add to filter list ASSERT(strFilterExt[0] == '.'); if (bFirst) { strDefault = ((LPCTSTR)strFilterExt) + 1; // skip the '.' m_ofn.lpstrDefExt = strDefault; m_ofn.nFilterIndex = m_ofn.nMaxCustFilter + 1; // 1 based number } // add to filter m_strFilter += strFilterName; ASSERT(!m_strFilter.IsEmpty()); // must have a file type name m_strFilter += (TCHAR)'\0'; // next string please m_strFilter += (TCHAR)'*'; m_strFilter += strFilterExt; m_strFilter += (TCHAR)'\0'; // next string please m_ofn.nMaxCustFilter++; #endif } bFirst = FALSE; } CString allFilter; VERIFY(allFilter.LoadString(AFX_IDS_ALLFILTER)); m_strFilter += allFilter; m_strFilter += (TCHAR)'\0'; // next string please m_strFilter += _T("*.*"); m_strFilter += (TCHAR)'\0'; // last string m_ofn.nMaxCustFilter++; m_ofn.lpstrFilter = m_strFilter; } } //*************************************************************************************** CBCGFileDialog::~CBCGFileDialog () { while (!m_lstNewItems.IsEmpty ()) { delete m_lstNewItems.RemoveHead (); } } //*************************************************************************************** static CBCGFileDialog* GetBCGFileDlg (HWND hwdParent) { CFileDialog* pDlg = (CFileDialog*)CWnd::FromHandle (hwdParent); ASSERT (pDlg != NULL); CBCGFileDialog* pFD = (CBCGFileDialog*) pDlg->GetDlgItem(0); ASSERT (pFD != NULL); return pFD; } //*************************************************************************************** LRESULT CALLBACK CBCGFileDialog::WindowProcNew(HWND hwnd,UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_NOTIFY: { CBCGFileDialog* pFD = GetBCGFileDlg (hwnd); LPNMHDR pHdr = (LPNMHDR) lParam; ASSERT (pHdr != NULL); if (wParam == iTabCtrlId && pHdr->code == TCN_SELCHANGE) { pFD->OnTabSelchange(); } else if ((wParam == iNewListCtrlId || wParam == iRecentListCtrlId) && pHdr->code == NM_DBLCLK) { pFD->OnItemDblClick(); } } break; case WM_COMMAND: { if ((int) LOWORD(wParam) == IDOK) { CBCGFileDialog* pFD = GetBCGFileDlg (hwnd); if (pFD->GetPage () != CBCGFileDialog::BCGFileOpen) { pFD->OnItemDblClick(); return 0; } } } break; case WM_PAINT: { CBCGFileDialog* pFD = GetBCGFileDlg (hwnd); pFD->CollectControls (); if (pFD->m_pBmpLogo != NULL) { ASSERT_VALID (pFD->m_pBmpLogo); CFileDialog* pDlg = (CFileDialog*)CWnd::FromHandle (hwnd); ASSERT (pDlg != NULL); CPaintDC dc (pDlg); // device context for painting dc.DrawState (pFD->m_rectLogo.TopLeft (), pFD->m_rectLogo.Size (), pFD->m_pBmpLogo, DSS_NORMAL); CRect rectFrame = pFD->m_rectLogo; rectFrame.InflateRect (1, 1); dc.Draw3dRect (rectFrame, globalData.clrBtnShadow, globalData.clrBtnLight); } } break; case WM_SIZE: { LRESULT lRes = CallWindowProc(CBCGFileDialog::m_wndProc, hwnd, message, wParam, lParam); CBCGFileDialog* pFD = GetBCGFileDlg (hwnd); ASSERT_VALID (pFD); CWnd* pFDParent = pFD->GetParent(); ASSERT (pFDParent != NULL); CRect rectTabs; pFDParent->GetClientRect (rectTabs); rectTabs.DeflateRect (4, 4); rectTabs.top += pFD->m_iLogoAreaHeight; pFD->m_wndTab.SetWindowPos (NULL, -1, -1, rectTabs.Width (), rectTabs.Height (), SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER); pFD->m_lstFDControls.RemoveAll (); pFD->CollectControls (); return lRes; } } return CallWindowProc(CBCGFileDialog::m_wndProc, hwnd, message, wParam, lParam); } BEGIN_MESSAGE_MAP(CBCGFileDialog, CFileDialog) //{{AFX_MSG_MAP(CBCGFileDialog) //}}AFX_MSG_MAP END_MESSAGE_MAP() //----------------------------------------------------- // My "classic " trick - how I can access to protected // member m_pRecentFileList? //----------------------------------------------------- class CBCGApp : public CWinApp { friend class CBCGFileDialog; }; void CBCGFileDialog::OnInitDone() { const int iBorderWidth = 20; const int iBorderHeight = 40; CWnd* pFD = GetParent(); ASSERT (pFD != NULL); CRect rectClient; pFD->GetClientRect (rectClient); int nNewDlgWidth = rectClient.Width () + iBorderWidth * 2 + m_iExtraWidth; if (m_pBmpLogo != NULL) { BITMAP bmp; m_pBmpLogo->GetBitmap (&bmp); m_rectLogo = CRect (CPoint ((nNewDlgWidth - bmp.bmWidth) / 2, 8), CSize (bmp.bmWidth, bmp.bmHeight)); m_iLogoAreaHeight = bmp.bmHeight + 20; } //--------------------------- // Adjust parent window size: //--------------------------- pFD->ModifyStyle (WS_THICKFRAME, WS_DLGFRAME | WS_BORDER); pFD->ModifyStyleEx (WS_EX_WINDOWEDGE, 0); pFD->SetWindowPos (NULL, -1, -1, nNewDlgWidth, rectClient.Height () + iBorderHeight * 2 + m_iLogoAreaHeight + m_iExtraHeight, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); //------------------- // Move all controls: //------------------- CWnd* pWndChild = pFD->GetWindow (GW_CHILD); while (pWndChild != NULL) { CRect rectCtl; pWndChild->GetClientRect (rectCtl); pWndChild->MapWindowPoints (pFD, rectCtl); pWndChild->SetWindowPos (NULL, rectCtl.left + iBorderWidth, rectCtl.top + iBorderHeight + m_iLogoAreaHeight, rectCtl.Width (), rectCtl.Height (), SWP_NOZORDER | SWP_NOACTIVATE); pWndChild = pWndChild->GetNextWindow (); } //------------------------------------------ // Create new and recent file list controls: //------------------------------------------ CRect rectList (0, 0, 0, 0); m_wndNewList.Create (WS_BORDER | WS_TABSTOP | WS_CHILD | LVS_ICON | LVS_SINGLESEL, rectList, pFD, iNewListCtrlId); m_wndNewList.ModifyStyleEx (0, WS_EX_CLIENTEDGE); if (m_pImagesNew != NULL) { m_wndNewList.SetImageList (m_pImagesNew, LVSIL_NORMAL); } int i = 0; for (POSITION pos = m_lstNewItems.GetHeadPosition (); pos != NULL; i ++) { CNewItemInfo* pInfo = (CNewItemInfo*) m_lstNewItems.GetNext (pos); ASSERT_VALID (pInfo); m_wndNewList.InsertItem (i, pInfo->m_strName, pInfo->m_iIconIndex); } m_wndRecentList.Create (WS_TABSTOP | WS_CHILD | WS_BORDER | LVS_SINGLESEL | LVS_REPORT, rectList, pFD, iRecentListCtrlId); m_wndRecentList.ModifyStyleEx (0, WS_EX_CLIENTEDGE); m_ImagesRecent.Create ( ::GetSystemMetrics (SM_CXSMICON), ::GetSystemMetrics (SM_CYSMICON), ILC_COLOR8, 0, 10); m_wndRecentList.SetImageList (&m_ImagesRecent, LVSIL_SMALL); { CBCGLocalResource locaRes; CString strFile; strFile.LoadString (IDS_BCGBARRES_FILE); m_wndRecentList.InsertColumn (0, strFile, LVCFMT_LEFT, 100); CString strFolder; strFolder.LoadString (IDS_BCGBARRES_FOLDER); m_wndRecentList.InsertColumn (1, strFolder); } CRecentFileList* pMRUFiles = ((CBCGApp*) AfxGetApp ())->m_pRecentFileList; if (pMRUFiles != NULL) { TCHAR szCurDir [_MAX_PATH]; ::GetCurrentDirectory (_MAX_PATH, szCurDir); int nCurDir = lstrlen (szCurDir); ASSERT (nCurDir >= 0); szCurDir [nCurDir] = _T('\\'); szCurDir [++ nCurDir] = _T('\0'); //--------------- // Add MRU files: //--------------- int iNumOfFiles = 0; // Actual added to menu for (int i = 0; i < pMRUFiles->GetSize (); i ++) { CString strFile = (*pMRUFiles) [i]; if (!strFile.IsEmpty ()) { CString strPath; CString strName; int iImage = -1; int iIndex = strFile.ReverseFind (_T('\\')); if (iIndex != -1) { strPath = strFile.Left (iIndex); strName = strFile.Mid (iIndex + 1); } else { strName = strFile; } SHFILEINFO sfi; HIMAGELIST himlSmall = (HIMAGELIST) SHGetFileInfo (strFile, 0, &sfi, sizeof(SHFILEINFO), SHGFI_SYSICONINDEX | SHGFI_SMALLICON); if (himlSmall != NULL) { CImageList* pImages = CImageList::FromHandle (himlSmall); ASSERT (pImages != NULL); iImage = m_ImagesRecent.Add (pImages->ExtractIcon (sfi.iIcon)); } iIndex = m_wndRecentList.InsertItem (iNumOfFiles ++, strName, iImage); m_wndRecentList.SetItemText (iIndex, 1, strPath); int iPathWidth = m_wndRecentList.GetStringWidth (strPath) + 20; if (iPathWidth > m_wndRecentList.GetColumnWidth (1)) { m_wndRecentList.SetColumnWidth (1, iPathWidth); } } } } //--------------------- // Create tabs control: //--------------------- CRect rectTabs; pFD->GetClientRect (rectTabs); rectTabs.DeflateRect (4, 4); rectTabs.top += m_iLogoAreaHeight; m_wndTab.Create (CBCGTabWnd::STYLE_3D, rectTabs, pFD, iTabCtrlId, CBCGTabWnd::LOCATION_TOP); m_wndTab.m_pParent = this; m_wndTab.SetFont (GetFont ()); m_wndTab.SetOwner (this); m_wndDummy.Create (_T(""), WS_CHILD, CRect (0, 0, 0, 0), this); { CBCGLocalResource locaRes; CString strTab; if (m_bNewPage) { m_wndTab.AddTab (&m_wndDummy, IDS_BCGBARRES_NEW_FILE, (UINT)-1); } m_wndTab.AddTab (&m_wndDummy, IDS_BCGBARRES_EXISTING, (UINT)-1); m_wndTab.AddTab (&m_wndDummy, IDS_BCGBARRES_RECENT, (UINT)-1); } pFD->CenterWindow (); pFD->SetWindowText (m_strCaption); //------------------ // Set dilaog icons: //------------------ if (m_hIconSmall != NULL) { pFD->SetIcon (m_hIconSmall, FALSE); } if (m_hIconBig != NULL) { pFD->SetIcon (m_hIconBig, TRUE); } //-------------------------- // Setup parent window proc: //-------------------------- m_wndProc = (WNDPROC)SetWindowLongPtr(pFD->m_hWnd, GWLP_WNDPROC, (LONG_PTR) CBCGFileDialog::WindowProcNew); } //****************************************************************************************** void CBCGFileDialog::OnTabSelchange() { m_wndDummy,ShowWindow (SW_HIDE); int nPage = m_wndTab.GetActiveTab (); if (!m_bNewPage) { nPage ++; } switch (nPage) { case 0: m_nPage = BCGFileNew; break; case 1: m_nPage = BCGFileOpen; break; case 2: m_nPage = BCGFileRecent; break; default: ASSERT (FALSE); } //--------------------- // Show/hide file list: //--------------------- CWnd* pWnd = GetParent(); ASSERT (pWnd != NULL); CWnd* pWndChild = pWnd->GetWindow (GW_CHILD); while (pWndChild != NULL) { TCHAR szClass [256]; ::GetClassName (pWndChild->GetSafeHwnd (), szClass, 255); CString strClass = szClass; if (strClass.CompareNoCase (_T("SHELLDLL_DefView")) == 0) { pWndChild->ShowWindow (m_nPage == BCGFileOpen ? SW_SHOW : SW_HIDE); break; } pWndChild = pWndChild->GetNextWindow (); } //-------------------------- // Show/hide other controls: //-------------------------- for (POSITION pos = m_lstFDControls.GetHeadPosition (); pos != NULL;) { pWnd = CWnd::FromHandle (m_lstFDControls.GetNext (pos)); ASSERT (pWnd != NULL); pWnd->ShowWindow (m_nPage == BCGFileOpen ? SW_SHOW : SW_HIDE); } m_wndNewList.ShowWindow (m_nPage == BCGFileNew ? SW_SHOW : SW_HIDE); m_wndRecentList.ShowWindow (m_nPage == BCGFileRecent ? SW_SHOW : SW_HIDE); } //*************************************************************************************** void CBCGFileDialog::OnItemDblClick () { ASSERT (m_nPage != BCGFileOpen); CListCtrl& list = (m_nPage == BCGFileRecent) ? m_wndRecentList : m_wndNewList; int iSelIndex = list.GetNextItem (-1, LVNI_ALL | LVNI_SELECTED); if (iSelIndex == -1) { return; } if (m_nPage == BCGFileRecent) { CString strPath = list.GetItemText (iSelIndex, 1); CString strName = list.GetItemText (iSelIndex, 0); if (strPath.IsEmpty ()) { m_strRecentFilePath = strName; } else { m_strRecentFilePath = strPath; m_strRecentFilePath += _T('\\'); m_strRecentFilePath += strName; } } else { ASSERT (m_nPage == BCGFileNew); m_iNewItemIndex = iSelIndex; } CDialog* pWnd = (CDialog*) GetParent(); ASSERT (pWnd != NULL); pWnd->EndDialog (IDOK); } //**************************************************************************************** void CBCGFileDialog::CollectControls () { if (!m_lstFDControls.IsEmpty ()) { return; } CWnd* pWnd = GetParent(); ASSERT (pWnd != NULL); CRect rectList (0, 0, 0, 0); CWnd* pWndChild = pWnd->GetWindow (GW_CHILD); while (pWndChild != NULL) { BOOL bIsFileList = FALSE; UINT uiID = pWndChild->GetDlgCtrlID(); TCHAR szClass [256]; ::GetClassName (pWndChild->GetSafeHwnd (), szClass, 255); CString strClass = szClass; CRect rectCtl; pWndChild->GetClientRect (rectCtl); pWndChild->MapWindowPoints (pWnd, rectCtl); if (strClass.CompareNoCase (_T("SHELLDLL_DefView")) == 0) { rectList.left = rectCtl.left; rectList.right = rectCtl.right; rectList.bottom = rectCtl.bottom - 10; bIsFileList = TRUE; } if (strClass.CompareNoCase (_T("ToolbarWindow32")) == 0) { rectList.top = rectCtl.top; } if ((((strClass.CompareNoCase (_T("BUTTON")) != 0) || uiID != IDOK && uiID != IDCANCEL && uiID != IDHELP) && pWndChild->GetStyle () & WS_VISIBLE) && uiID != iTabCtrlId && uiID != iNewListCtrlId && uiID != iRecentListCtrlId && !bIsFileList) { m_lstFDControls.AddTail (pWndChild->GetSafeHwnd ()); } pWndChild = pWndChild->GetNextWindow (); } m_wndNewList.MoveWindow (rectList); m_wndRecentList.MoveWindow (rectList); OnTabSelchange(); } //************************************************************************************** void CBCGFileDialog::AddNewItem (LPCTSTR lpszName, int iIconIndex) { m_lstNewItems.AddTail (new CNewItemInfo (lpszName, iIconIndex)); } //************************************************************************************** void CBCGFileDialog::SetDlgIcon (HICON hIconBig, HICON hIconSmall/* = NULL*/) { m_hIconBig = hIconBig; m_hIconSmall = (hIconSmall == NULL) ? m_hIconBig : hIconSmall; } BEGIN_MESSAGE_MAP(CBCGFDTabWnd, CBCGTabWnd) ON_WM_ERASEBKGND() END_MESSAGE_MAP() BOOL CBCGFDTabWnd::OnEraseBkgnd(CDC* pDC) { CRect rectClient; GetClientRect (rectClient); pDC->FillRect (rectClient, &globalData.brBtnFace); return TRUE; } void CBCGFDTabWnd::FireChangeActiveTab (int /*nNewTab*/) { if (m_pParent != NULL) { m_pParent->OnTabSelchange (); } }
[ "rlyle@palestar.com" ]
rlyle@palestar.com
72254aac13e6b71c54d3e284bf6fd45ef04f6e49
eb1053122539721be26389a23cf0c582f517721f
/src/qt/networkstyle.h
e77c64d504044918bf3c4c5825772e594b4de271
[ "MIT" ]
permissive
MichaelHDesigns/Hodl
54429b80fd592bddf88840c9ff7e9aadce29ccb1
ae07a41aefa71ec96e1ba611bccd1b87a264f43f
refs/heads/main
2023-04-27T01:59:49.882947
2021-05-08T03:44:51
2021-05-08T03:44:51
364,439,724
0
0
null
null
null
null
UTF-8
C++
false
false
1,091
h
// Copyright (c) 2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef HODLCASH_QT_NETWORKSTYLE_H #define HODLCASH_QT_NETWORKSTYLE_H #include <QIcon> #include <QPixmap> #include <QString> /* Coin network-specific GUI style information */ class NetworkStyle { public: /** Get style associated with provided BIP70 network id, or 0 if not known */ static const NetworkStyle *instantiate(const QString &networkId); const QString &getAppName() const { return appName; } const QIcon &getAppIcon() const { return appIcon; } const QIcon &getTrayAndWindowIcon() const { return trayAndWindowIcon; } const QString &getTitleAddText() const { return titleAddText; } private: NetworkStyle(const QString &appName, const int iconColorHueShift, const int iconColorSaturationReduction, const char *titleAddText); QString appName; QIcon appIcon; QIcon trayAndWindowIcon; QString titleAddText; }; #endif // HODLCASH_QT_NETWORKSTYLE_H
[ "devilking6105@gmail.com" ]
devilking6105@gmail.com
21da7f5af9a254ec423c0f44edcaf828be03c702
73262276244f95135dd02c13b7036d9ba9df7ea4
/1087 有多少不同的值(20).cpp
a90e81f77ecaadb2300f57ff6d9ed462235799ce
[]
no_license
aptx1231/PAT_BasicLevel
dddd11a21f4df4bb071fa44861fddbe8763b4a27
49c03feb00b5ec37214a88296c67058c2ff9c120
refs/heads/master
2020-05-27T10:36:12.510971
2019-09-23T11:38:41
2019-09-23T11:38:41
188,585,055
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
333
cpp
#include<iostream> #include<algorithm> using namespace std; int a[11000]; //×î´óÖµ10000/2+10000/3+10000/5=10333 int main() { int n; cin >> n; int cnt = 0; for (int i=1;i<=n;i++) { int tmp = i/2+i/3+i/5; //cout << tmp << endl; if (a[tmp] == 0) { a[tmp] = 1; cnt++; } } cout << cnt << endl; return 0; }
[ "jwjiang_buaa@163.com" ]
jwjiang_buaa@163.com
35621c3ff484430d48261ff74f70d60bd571ba75
db1cd656cd37cdd48a146706253b9b74dda075a7
/CS388/Project1/Project1/BehaviorTrees/Source/BehaviorTrees/NodeData.h
bf5d81d2e3a10b7e6036b65ffc3f5cf6922b87c8
[]
no_license
tpugmire/digipen
c5eb9f3ba49b912ff16564e2e3c054919730e834
07e9d6db3a378858c85277d8d1411403e8a63d56
refs/heads/master
2021-03-24T12:38:46.884780
2016-09-22T06:32:49
2016-09-22T06:32:49
68,891,484
1
0
null
null
null
null
UTF-8
C++
false
false
4,272
h
/******************************************************************************/ /*! \file NodeData.h \project CS380/CS580 AI Framework \author Chi-Hao Kuo \summary Behavior tree node data. Copyright (C) 2016 DigiPen Institute of Technology. Reproduction or disclosure of this file or its contents without the prior written consent of DigiPen Institute of Technology is prohibited. */ /******************************************************************************/ #pragma once #include <BehaviorTrees/BehaviorTreesShared.h> namespace BT { // store actual data for each node per agent class NodeData { public: /* constructors/destructor */ // Constructor NodeData(BehaviorNode &btnode); // Move constructor NodeData(NodeData &&nodedata); /* getters/setters */ BehaviorNode &GetNodeLogic(void) { return *m_btnode_ptr; } BehaviorNode const &GetNodeLogic(void) const { return *m_btnode_ptr; } AgentBTData &GetAgentData(void) { return *m_agentdata_ptr; } AgentBTData const &GetAgentData(void) const { return *m_agentdata_ptr; } Status GetStatus(void) { return m_status; } int GetCurrentChildOrder(void) { return m_currentchildorder; } int GetCurrentChildNodeIndex(void) { return m_btnode_ptr->GetChildNodeIndex(m_currentchildorder); } unsigned GetStackIndex(void) { return m_stackindex; } bool GetStayStackFlag(void) { return m_stayStack; } Status GetChildStatus(int childorder) { return m_childstatus[childorder]; } std::vector<Status> &GetAllChildStatus(void) { return m_childstatus; } std::vector<Status> const &GetAllChildStatus(void) const { return m_childstatus; } NodeData &GetParentNodeData(void); // Get custom node data template <typename T> T *GetCustomData(void); void SetAgentData(AgentBTData *agentdata) { m_agentdata_ptr = agentdata; } void SetStatus(Status status) { m_status = status; } void SetCurrentChildOrder(int childorder) { m_currentchildorder = childorder; } void SetStackIndex(unsigned stackindex) { m_stackindex = stackindex; } void SetStayStackFlag(bool flag) { m_stayStack = flag; } // Set child status (set m_childstatus of current node, also update child's m_status). void SetChildStatus(int childorder, Status status); // Initial custom node data // (only accept derived struct from NodeAbstractData) template <typename T> void InitialCustomData(void); /* operators */ // Move operator NodeData &operator=(NodeData &&nodedata); /* methods */ // Increment current child order void IncrementCurrentChildOrder(void); // Reset node data void Reset(void); // Run node logic Status RunLogic(float dt); // Check if this node has parent bool HasParent(void); private: /* variables */ BehaviorNode *m_btnode_ptr; // node logic pointer AgentBTData *m_agentdata_ptr; // agent's behavior tree data Status m_status; // node status int m_currentchildorder; // the order of the current child in m_children to execute unsigned m_stackindex; // which stack the node is on bool m_stayStack; // flag: do not pop the node from stack automatically (parallel or root nodes) std::vector<Status> m_childstatus; // children status std::shared_ptr<NodeAbstractData> m_customdata; // custom node data }; /* Template Functions */ /*--------------------------------------------------------------------------* Name: GetCustomData Description: Get custom node data. Arguments: None. Returns: T*: Pointer of custom node data. *---------------------------------------------------------------------------*/ template <typename T> T *NodeData::GetCustomData(void) { return static_cast<T *>(m_customdata.get()); } /*--------------------------------------------------------------------------* Name: InitialCustomData Description: Initial custom node data. (only accept derived struct from NodeAbstractData) Arguments: None. Returns: void. *---------------------------------------------------------------------------*/ template <typename T> void NodeData::InitialCustomData(void) { m_customdata = std::make_shared<T>(); } }
[ "tyler.pugmire@yahoo.com" ]
tyler.pugmire@yahoo.com
d21f4633093da4167333a0a991e97c71a2a378db
4b2faf470adabd0f9cffc0b9e0dbf621a3026730
/winApi/winMain.cpp
45da6defec0be5849cab271f82ced5f942bb6937
[]
no_license
dksem12gh/winApi-MapTool
0027b17577e7955884241e1b82313083ce7c76c4
099d0a08d09e648ca45994bad8509737f67e5d39
refs/heads/master
2023-04-14T10:32:57.708237
2021-04-25T16:05:06
2021-04-25T16:05:06
361,149,942
0
0
null
null
null
null
UHC
C++
false
false
4,622
cpp
#include "stdafx.h" #include "mainGame.h" //===================== // ## 전역변수 ## //===================== HINSTANCE _hInstance; HWND _hWnd; POINT _ptMouse = { 0, 0 }; BOOL _leftButtonDown = false; mainGame* _mg; //====================== // ## 함수 전방선언 ## //====================== LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); void setWindowSize(int x, int y, int width, int height); //======================= // ## 윈도우 메인함수 ## //======================= int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdParam, int nCmdShow) { _mg = new mainGame(); //인스턴스를 전역변수에 담아둔다 _hInstance = hInstance; //WNDCLASS : 윈도우의 정보를 저장하기 위한 구조체 //윈도우 구조체 선언 및 초기화 WNDCLASS wndClass; wndClass.cbClsExtra = 0; //클래스 여분 메모리 wndClass.cbWndExtra = 0; //윈도우 여분 메모리 wndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); //백그라운드 wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); //마우스 커서 wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); //아이콘 wndClass.hInstance = hInstance; //인스턴스 wndClass.lpfnWndProc = (WNDPROC)WndProc; //윈도우 프로시져 wndClass.lpszClassName = WINNAME; //클래스 이름 wndClass.lpszMenuName = NULL; //메뉴이름 wndClass.style = CS_HREDRAW | CS_VREDRAW; //윈도우 스타일 //윈도우 클래스 등록 RegisterClass(&wndClass); //윈도우 생성 _hWnd = CreateWindow( WINNAME, //윈도우 클래스의 이름 WINNAME, //윈도우 타이틀바 이름 WINSTYLE, //윈도우 스타일 WINSTARTX, //윈도우 화면좌표 X WINSTARTY, //윈도우 화면좌표 Y WINSIZEX, //윈도우 화면 가로크기 WINSIZEY, //윈도우 화면 세로크기 NULL, //부모 윈도우 (HMENU)NULL, //메뉴핸들 hInstance, //인스턴스 지정 NULL //윈도우 및 자식 윈도우를 생성하면 지정해주고 그렇지 않으면 NULL ); //클라이언트 영역의 사이즈를 정확히 잡아준다 setWindowSize(WINSTARTX, WINSTARTY, WINSIZEX, WINSIZEY); //화면에 윈도우 보여준다 ShowWindow(_hWnd, nCmdShow); //메인게임 클래스의 초기화 실패시 종료 if (FAILED(_mg->init())) { return 0; } //MSG : 운영체제에서 발행하는 메세지 정보를 저장하기 위한 구조체 MSG message; //메세지 루프 //GetMessage : 메세지를 꺼내올 수 있을때까지 멈춰있는 함수 //PeekMessage : 메세지가 없더라도 리턴되는 함수 //게임용 while (true) { if (PeekMessage(&message, NULL, 0, 0, PM_REMOVE)) { if (message.message == WM_QUIT) break; TranslateMessage(&message); DispatchMessage(&message); } else { TIMEMANAGER->update(60.0f); _mg->update(); _mg->render(); } } //TranslateMessage : 키보드 입력메세지 처리를 담당 //입력된 키가 문자키인지 확인후 대문자 혹은 소문자, 한글, 영문인지에 대한 //WM_CHAR 메세지 발생시킨다 //DispatchMessage : 윈도우 프로시져에서 전달된 메세지를 실제 윈도우로 전달해준다 //일반 프로그래밍용 /* while (GetMessage(&message, 0, 0, 0)) { TranslateMessage(&message); DispatchMessage(&message); } */ _mg->release(); //윈도우 클래스 등록 해제 UnregisterClass(WINNAME, hInstance); return message.wParam; } //윈도우 프로시져 : 메세지를 운영체제에 전달하고 코딩하는 구간 //hWnd : 어느 윈도우에서 발생한 메세지인지 구분 //iMessage : 메세지 구분 번호 //wParam : unsigned int 마우스 버튼의 상태, 키보드 조합키의 상태를 전달 //lParam : unsigned long 마우스 클릭 좌표를 전달(x, y) LRESULT CALLBACK WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam) { return _mg->MainProc(hWnd, iMessage, wParam, lParam); } //================================================================= // ## 윈도우 크기 조정 ## (클라이언트 영역의 사이즈를 정확히 잡아준다) //================================================================= void setWindowSize(int x, int y, int width, int height) { RECT rc = { 0, 0, width, height }; //실제 윈도우 크기 조정 AdjustWindowRect(&rc, WINSTYLE, false); //위 렉트 정보로 윈도우 클라이언트 사이즈 셋팅 SetWindowPos(_hWnd, NULL, x, y, (rc.right - rc.left), (rc.bottom - rc.top), SWP_NOZORDER | SWP_NOMOVE); }
[ "dksem12gh@naver.com" ]
dksem12gh@naver.com
2b2deba9d5607bece962a30c61537326f975ac69
1035758a41da7766146d5a6ab08f83e5cad4ff1a
/SpaceInvaders/menu_state.h
b05e669bfb4896a88d16f3cb509a9af54316cefc
[]
no_license
Curriosityy/SpaceInvaders
b9ab8b827356f457959d6ea8de15d1626a238205
41f79f7ed880a69ad1bb6538c7268c0e1fe392bc
refs/heads/master
2021-01-19T14:49:35.268020
2017-03-29T23:30:13
2017-03-29T23:30:13
86,635,128
0
0
null
null
null
null
UTF-8
C++
false
false
475
h
#pragma once #include "game_state.h" class menu_state : public tiny_state { public: menu_state(); ~menu_state(); // Inherited via tiny_state void Initialize(sf::RenderWindow * window) override; void Update(sf::RenderWindow * window) override; void Render(sf::RenderWindow * window) override; void Destroy(sf::RenderWindow * window) override; private: sf::Font* font; sf::Text* title; sf::Text* play; sf::Text* quit; int selected = 0; bool upKey, downKey; };
[ "patryk9595@gmail.com" ]
patryk9595@gmail.com
65894d131f6a881b39ec1e93a00116761c6129d8
ece30e7058d8bd42bc13c54560228bd7add50358
/DataCollector/mozilla/xulrunner-sdk/include/mozilla/dom/HTMLUnknownElement.h
f04808ddcefc441ba7984be40498ffb7790683c2
[ "Apache-2.0" ]
permissive
andrasigneczi/TravelOptimizer
b0fe4d53f6494d40ba4e8b98cc293cb5451542ee
b08805f97f0823fd28975a36db67193386aceb22
refs/heads/master
2022-07-22T02:07:32.619451
2018-12-03T13:58:21
2018-12-03T13:58:21
53,926,539
1
0
Apache-2.0
2022-07-06T20:05:38
2016-03-15T08:16:59
C++
UTF-8
C++
false
false
1,079
h
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef mozilla_dom_HTMLUnknownElement_h #define mozilla_dom_HTMLUnknownElement_h #include "mozilla/Attributes.h" #include "nsGenericHTMLElement.h" namespace mozilla { namespace dom { class HTMLUnknownElement final : public nsGenericHTMLElement { public: explicit HTMLUnknownElement(already_AddRefed<mozilla::dom::NodeInfo>& aNodeInfo) : nsGenericHTMLElement(aNodeInfo) { if (NodeInfo()->Equals(nsGkAtoms::bdi)) { SetHasDirAuto(); } } virtual nsresult Clone(mozilla::dom::NodeInfo *aNodeInfo, nsINode **aResult) const override; protected: virtual JSObject* WrapNode(JSContext *aCx, JS::Handle<JSObject*> aGivenProto) override; }; } // namespace dom } // namespace mozilla #endif /* mozilla_dom_HTMLUnknownElement_h */
[ "andras.igneczi@doclerholding.com" ]
andras.igneczi@doclerholding.com
e055376431a7fdfdfd7d056d097f89cc6becd085
dac70221ae783796868881a66c1b9dc5572ae6ae
/Source of PBO/adx_pack/vehicles/dc3/CfgVehicles.hpp
86fdb1317eaba8e1b2ad39e991295a5157237f4e
[ "Unlicense" ]
permissive
ADXTeam/DayZADX
787ed2e71249c7fef2d7996ecf3ff59affc48b99
97924bc18ed374df854f2aa5eee0ae960bb47811
refs/heads/master
2020-04-06T06:43:27.579217
2013-11-08T15:20:20
2013-11-08T15:20:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,061
hpp
class CfgVehicles { class An2_Base_EP1; // External class reference class dc3 : An2_Base_EP1 { scope = public; faction = "rth_copter_class"; displayName = "Plane"; gearRetracting = true; model = "\origins_dc3\DC3.p3d"; destrType = "DestructBuilding"; driverAction = "C130_Pilot"; transportSoldier = 15; mapSize = 30; icon = "\origins_dc3\Data\icomap_DC3_CA.paa"; picture = "\origins_dc3\Data\DC3_CA.paa"; transportMaxMagazines = 150; transportMaxWeapons = 90; transportMaxBackpacks = 90; class Sounds { class EngineLowOut { sound[] = {"origins_dc3\Data\Sound\dakota_env01.ogg", 2.23872, 1.2, 700}; frequency = "1.0 min (rpm + 0.5)"; volume = "engineOn*(rpm factor[0.85, 0])"; }; class EngineHighOut { sound[] = {"origins_dc3\Data\Sound\dakota_engine01.ogg", 2.23872, 1.6, 700}; frequency = "1"; volume = "engineOn*(rpm factor[0.55, 1.0])"; }; class EngineLowIn { sound[] = {"origins_dc3\Data\Sound\dakota_env01.ogg", db-10, 1.0}; frequency = "1.0 min (rpm + 0.5)"; volume = "(1-camPos)*(engineOn*(rpm factor[0.85, 0]))"; }; class EngineHighIn { sound[] = {"origins_dc3\Data\Sound\dakota_engine01.ogg", db-10, 1.0}; frequency = "1"; volume = "(1-camPos)*(engineOn*(rpm factor[0.55, 1.0]))"; }; }; soundEngine[] = {"\origins_dc3\Data\Sound\dakota_engine01.ogg", 31.6228, 1}; soundEnviron[] = {"\origins_dc3\Data\Sound\dakota_env01.ogg", db-30, 1.0}; side = TCivilian; crew = "Pilot"; typicalCargo[] = {"Pilot", "Civilian5", "Civilian7"}; cargoAction[] = {"HMMWV_Cargo01", "HMMWV_Cargo01", "UAZ_Cargo01", "HMMWV_Cargo01", "HMMWV_Cargo01", "UAZ_Cargo01", "HMMWV_Cargo01", "HMMWV_Cargo01", "UAZ_Cargo01", "HMMWV_Cargo01", "HMMWV_Cargo01", "UAZ_Cargo01", "HMMWV_Cargo01", "HMMWV_Cargo01", "UAZ_Cargo01"}; driverCompartments = "Compartment1"; cargoCompartments[] = {"Compartment1"}; camouflage = 10; // how dificult to spot - bigger - better spotable audible = 8; // audible - bigger - better heard accuracy = 0.2; // accuracy needed to recognize type of this target maxSpeed = 380; // max speed on level road, km/h supplyRadius = 8; laserScanner = true; minFireTime = 10; // minimal time spent firing on single target gunAimDown = 0.05; weapons[] = {}; magazines[] = {}; extCameraPosition[] = {0, 5, -20}; // threat (VSoft, VArmor, VAir), how threatening vehicle is to unit types threat[] = {1, 1, 1}; class Reflectors { class Left { color[] = {0.8, 0.8, 1.0, 1.0}; ambient[] = {0.07, 0.07, 0.07, 1.0}; position = "L svetlo"; direction = "konec L svetla"; hitpoint = "L svetlo"; selection = "L svetlo"; size = 1; brightness = 1.0; }; class Right { color[] = {0.8, 0.8, 1.0, 1.0}; ambient[] = {0.07, 0.07, 0.07, 1.0}; position = "P svetlo"; direction = "konec P svetla"; hitpoint = "P svetlo"; selection = "P svetlo"; size = 1; brightness = 1.0; }; }; armor = 50; armorStructured = 1; envelope[] = {0.0, 0.1, 0.5, 1.5, 3.1, 4.3, 4.9, 5, 4.4, 2.8, 1.6, 0.8, 0}; landingSpeed = 145; landingAoa = 3.5*3.1415/180; flapsFrictionCoef = 2; wheelSteeringSensitivity = 0.5; aileronSensitivity = 1; // relative aileron sensitivity elevatorSensitivity = 1; // relative elevator sensitivity noseDownCoef = 1; // how much goes nose down during turns gearUpTime = 4.5; gearDownTime = 3; memoryPointsGetInDriver = "pos driver"; memoryPointsGetInDriverDir = "pos driver dir"; memoryPointsGetInCargo[] = {"pos cargo"}; memoryPointsGetInCargoDir[] = {"pos cargo dir"}; class Damage { tex[] = {}; mat[] = {"origins_dc3\data\DC3_body_01.rvmat", "origins_dc3\data\DC3_body_01.rvmat", "origins_dc3\data\DC3_body_01_destruct.rvmat", "origins_dc3\data\DC3_body_02.rvmat", "origins_dc3\data\DC3_body_02.rvmat", "origins_dc3\data\DC3_body_02_destruct.rvmat", "origins_dc3\data\DC3_cockpit.rvmat", "origins_dc3\data\DC3_cockpit.rvmat", "origins_dc3\data\DC3_cockpit_destruct.rvmat"}; }; }; };
[ "keveltv@gmail.com" ]
keveltv@gmail.com
e5c1cb11505e99b97a54a52fe9c6d513e5bbbcc6
41a380f90823525442222e74004242afc75babb3
/laser_ws/src/laser_package/src/Estimator_node.cpp
108a7c76f3c9ce10246122a3a4dc4cd47f9f22dc
[]
no_license
ywen27G/estimation_term_project_clancy
46b1938f3fc1222f830418f72fb19074e588b40d
89a03a352bfbe410ef86fbf34b4c3fef7a281f60
refs/heads/master
2021-12-14T13:26:17.133051
2015-05-01T11:42:06
2015-05-01T11:42:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,579
cpp
#include "../include/Estimator.h" class SubscribeAndPublish { public: SubscribeAndPublish(ros::NodeHandle *some_n) { ROS_INFO("Constructing SAP for Estimator"); n_handle = some_n; target_real_pub = n_handle->advertise<geometry_msgs::PointStamped>("/target_real_topic",1000); //publish targets to new topic target_sub = n_handle->subscribe<laser_package::state>("/filter_topic",1000,&SubscribeAndPublish::targetCallBack,this); kalman_pub = n_handle->advertise<laser_package::state>("/kalman_filter_topic",1000); //publish kf estimates to new topic extended_kalman_pub = n_handle->advertise<laser_package::state>("/extended_kalman_filter_topic",1000); //publish ekf estimates to new topic imm_pub = n_handle->advertise<laser_package::state>("/imm_topic",1000); //publish imm estimates to new topic msg_count = 0; setKalmanNoiseData(); setExtendedKalmanNoiseData(); } void targetCallBack(const laser_package::state::ConstPtr& msg) { rho = msg->Measured_Rho; theta = msg->Measured_Theta; real_state(XI_INDEX) = msg->Real_X; real_state(XI_DOT_INDEX) = msg->Real_X_Speed; real_state(ETA_INDEX) = msg->Real_Y; real_state(ETA_DOT_INDEX) = msg->Real_Y_Speed; real_state(OMEGA_INDEX) = msg->Real_Omega; z(RHO_INDEX) = rho; z(THETA_INDEX) = theta; if(msg_count>1) { update_time = msg->Time_Of_Measurement; //extended kalman filter ExtendedKF.updateFilter(z, update_time,real_state); ExtendedKF.updateCovariance(); updateStateMessage(&ExtendedKF,msg); extended_kalman_pub.publish(state_msg); //regular kalman filter KF.updateFilter(z, update_time, real_state); KF.updateCovariance(); updateStateMessage(&KF,msg); kalman_pub.publish(state_msg); //imm imm.update(); updateStateMessage(&imm,msg); imm_pub.publish(state_msg); } else if(msg_count == 0) { first_xi = rho*cos(theta)+SENSOR_XI; first_eta = rho*sin(theta)+SENSOR_ETA; first_time = msg->Time_Of_Measurement; msg_count++; } else if(msg_count==1) { second_time = msg->Time_Of_Measurement; T = SAMPLING_INTERVAL; initial_state(XI_INDEX) = rho*cos(theta)+SENSOR_XI; initial_state(ETA_INDEX) = rho*sin(theta)+SENSOR_ETA; initial_state(XI_DOT_INDEX) = (initial_state(XI_INDEX)-first_xi)/(T); initial_state(ETA_DOT_INDEX) = (initial_state(ETA_INDEX)-first_eta)/(T); initial_state(OMEGA_INDEX) = 0.0001; //extended kalman filter ExtendedKF = ExtendedKalmanFilter(initial_state,T , extended_kalman_noise_data,0.5,z);//instantiate Extended kalman filter updateStateMessage(&ExtendedKF,msg); extended_kalman_pub.publish(state_msg); //regular kalman filter KF = KalmanFilter(initial_state,T , kalman_noise_data, 0.5,z);//instantiate kalman filter updateStateMessage(&KF,msg); kalman_pub.publish(state_msg); //imm filters.push_back(&KF); filters.push_back(&ExtendedKF); imm = IMM(filters);//instantiate IMM with vector of filters imm.update(); msg_count++; } //These are for when we want to publish to Rviz target_point_msg.x = msg->Real_X; target_point_msg.y = msg->Real_Y; target_point_stamped_msg.point = target_point_msg; target_point_stamped_msg.header.frame_id = "/my_frame"; //The below allows us to publish values so that Rviz can plot. You decide which points to plot from the target class. target_real_pub.publish(target_point_stamped_msg); } private: ros::NodeHandle *n_handle; ros::Subscriber target_sub; ros::Publisher kalman_pub, extended_kalman_pub, imm_pub, target_real_pub; geometry_msgs::Point target_point_msg; geometry_msgs::PointStamped target_point_stamped_msg; laser_package::state state_msg; ExtendedKalmanFilter ExtendedKF; KalmanFilter KF; std::vector<Filter*> filters; IMM imm; int filterID, msg_count; double first_xi, second_xi, first_eta, second_eta, first_time, second_time,T, update_time, rho, theta, converted_xi, converted_eta; state_vector initial_state, real_state; initial_noise_vector kalman_noise_data, extended_kalman_noise_data; measurement_vector z; void setKalmanNoiseData() { kalman_noise_data(MU_W_XI_INDEX) = MU_W_SIMULATE_XI; kalman_noise_data(SIGMA_W_XI_INDEX) = SIGMA_W_SIMULATE_XI; kalman_noise_data(VAR_W_XI_INDEX) = kalman_noise_data(SIGMA_W_XI_INDEX)*kalman_noise_data(SIGMA_W_XI_INDEX); kalman_noise_data(MU_W_ETA_INDEX) = MU_W_SIMULATE_ETA; kalman_noise_data(SIGMA_W_ETA_INDEX) = SIGMA_W_SIMULATE_ETA; kalman_noise_data(VAR_W_ETA_INDEX) = kalman_noise_data(SIGMA_W_ETA_INDEX)*kalman_noise_data(SIGMA_W_ETA_INDEX); kalman_noise_data(MU_V_XI_INDEX) = 0.0; kalman_noise_data(SIGMA_V_XI_INDEX) = 0.1; kalman_noise_data(VAR_V_XI_INDEX) = kalman_noise_data(SIGMA_V_XI_INDEX)*kalman_noise_data(SIGMA_V_XI_INDEX); kalman_noise_data(MU_V_ETA_INDEX) = 0.0; kalman_noise_data(SIGMA_V_ETA_INDEX) = 0.1; kalman_noise_data(VAR_V_ETA_INDEX) = kalman_noise_data(SIGMA_V_ETA_INDEX)*kalman_noise_data(SIGMA_V_ETA_INDEX); kalman_noise_data(MU_V_OMEGA_INDEX) = 0.0; kalman_noise_data(SIGMA_V_OMEGA_INDEX) = 0.0; kalman_noise_data(VAR_V_OMEGA_INDEX) = kalman_noise_data(SIGMA_V_OMEGA_INDEX)*kalman_noise_data(SIGMA_V_OMEGA_INDEX); kalman_noise_data(SIGMA_W_RHO_INDEX) = SIGMA_W_SIMULATE_RHO; kalman_noise_data(SIGMA_W_THETA_INDEX) = SIGMA_W_SIMULATE_THETA; } void setExtendedKalmanNoiseData() { extended_kalman_noise_data(MU_W_XI_INDEX) = MU_W_SIMULATE_XI;; extended_kalman_noise_data(SIGMA_W_XI_INDEX) = SIGMA_W_SIMULATE_XI; extended_kalman_noise_data(VAR_W_XI_INDEX) = extended_kalman_noise_data(SIGMA_W_XI_INDEX)*extended_kalman_noise_data(SIGMA_W_XI_INDEX); extended_kalman_noise_data(MU_W_ETA_INDEX) = MU_W_SIMULATE_ETA; extended_kalman_noise_data(SIGMA_W_ETA_INDEX) = SIGMA_W_SIMULATE_ETA; extended_kalman_noise_data(VAR_W_ETA_INDEX) = extended_kalman_noise_data(SIGMA_W_ETA_INDEX)*extended_kalman_noise_data(SIGMA_W_ETA_INDEX); extended_kalman_noise_data(MU_V_XI_INDEX) = 0.0; //rationale: its moving pretty quickly and a change in the angular acceleration of 1 degree per second won't change the velocities too much. extended_kalman_noise_data(SIGMA_V_XI_INDEX) = 0.5; extended_kalman_noise_data(VAR_V_XI_INDEX) = extended_kalman_noise_data(SIGMA_V_XI_INDEX)*extended_kalman_noise_data(SIGMA_V_XI_INDEX); extended_kalman_noise_data(MU_V_ETA_INDEX) = 0.0; extended_kalman_noise_data(SIGMA_V_ETA_INDEX) = 0.5; extended_kalman_noise_data(VAR_V_ETA_INDEX) = extended_kalman_noise_data(SIGMA_V_ETA_INDEX)*extended_kalman_noise_data(SIGMA_V_ETA_INDEX); extended_kalman_noise_data(MU_V_OMEGA_INDEX) = 0.0; //rationale: I figure it would be reasonable for a plane to start turning 1 degree in 1 second extended_kalman_noise_data(SIGMA_V_OMEGA_INDEX) = 1*PI*DEG_TO_RAD_DENOM;//1 degree/seconds^2 extended_kalman_noise_data(VAR_V_OMEGA_INDEX) = extended_kalman_noise_data(SIGMA_V_OMEGA_INDEX)*extended_kalman_noise_data(SIGMA_V_OMEGA_INDEX); extended_kalman_noise_data(SIGMA_W_RHO_INDEX) = SIGMA_W_SIMULATE_RHO; extended_kalman_noise_data(SIGMA_W_THETA_INDEX) = SIGMA_W_SIMULATE_THETA; } void updateStateMessage(Filter *filter, const laser_package::state::ConstPtr& msg) { //Real and measured state_msg.Real_X = msg->Real_X; state_msg.Real_Y = msg->Real_Y; state_msg.Measured_X = msg->Measured_X; state_msg.Measured_Y = msg->Measured_Y; state_msg.Real_X_Speed = msg->Real_X_Speed; state_msg.Real_Y_Speed = msg->Real_Y_Speed; //Estimated state values state_msg.Estimated_X = filter->getEstimatedX(); state_msg.Estimated_X_Speed = filter->getEstimatedXSpeed(); state_msg.Estimated_Y = filter->getEstimatedY(); state_msg.Estimated_Y_Speed = filter->getEstimatedYSpeed(); //calculated velocities and accelerations state_msg.Acceleration_X = filter->getXAcceleration(); state_msg.Acceleration_Y = filter->getYAcceleration(); state_msg.Velocity_X = filter->getXVelocity(); state_msg.Velocity_Y = filter->getYVelocity(); //variances state_msg.Position_Variance_X = filter->getPositionVarianceX(); state_msg.Velocity_Variance_X = filter->getVelocityVarianceX(); state_msg.Position_Variance_Y = filter->getPositionVarianceY(); state_msg.Velocity_Variance_Y = filter->getVelocityVarianceY(); state_msg.Omega_Variance = filter->getOmegaVariance(); //gains state_msg.Position_Gain_X = filter->getPositionGainX(); state_msg.Velocity_Gain_X = filter->getVelocityGainX(); state_msg.Position_Gain_Y = filter->getPositionGainY(); state_msg.Velocity_Gain_Y = filter->getVelocityGainY(); //innovations state_msg.Innovation_X = filter->getInnovationX(); state_msg.Innovation_Y = filter->getInnovationY(); //general filter statistics state_msg.RMS_POS = sqrt(pow((state_msg.Real_X-state_msg.Estimated_X),2)+pow((state_msg.Real_Y-state_msg.Estimated_Y),2)); state_msg.RMS_SPD = sqrt(pow((state_msg.Real_X_Speed-state_msg.Estimated_X_Speed),2)+pow((state_msg.Real_Y_Speed-state_msg.Estimated_Y_Speed),2)); state_msg.Mode_1_Probability = filter->getMode1Probability(); state_msg.Mode_2_Probability = filter->getMode2Probability(); state_msg.RMS_POS_Measurements = sqrt(pow((state_msg.Real_X-rho*cos(theta)),2)+pow((state_msg.Real_Y-rho*sin(theta)),2)); } }; int main(int argc, char **argv) { //ROS stuff ros::init(argc, argv, "Estimator_node"); ros::NodeHandle n; ros::Rate r(floor(1/SIMULATE_RATE+0.5)); SubscribeAndPublish SAPekf(&n); while(ros::ok()) { ros::spinOnce(); r.sleep(); } return 0; }
[ "clancy.emanuel@uconn.edu" ]
clancy.emanuel@uconn.edu
36477e3115e116fe5ffa72f62c699c51f9eb2689
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/Trigger/TrigEvent/TrigInDetEventTPCnv/src/TrigTauTracksInfoCnv_p1.cxx
febc0e7d02d69f5910b408fba0be65ecdf3a2230
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
2,902
cxx
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ #include "TrigInDetEvent/TrigTauTracksInfo.h" #include "TrigInDetEventTPCnv/TrigTauTracksInfo_p1.h" #include "TrigInDetEventTPCnv/TrigTauTracksInfoCnv_p1.h" //----------------------------------------------------------------------------- // Persistent to transient //----------------------------------------------------------------------------- void TrigTauTracksInfoCnv_p1::persToTrans( const TrigTauTracksInfo_p1 *persObj, TrigTauTracksInfo *transObj, MsgStream &log ) { log << MSG::DEBUG << "TrigTauTracksInfoCnv_p1::persToTrans called " << endreq; transObj->setRoiId (persObj->m_roiID) ; transObj->setNCoreTracks (persObj->m_nCoreTracks) ; transObj->setNSlowTracks (persObj->m_nSlowTracks) ; transObj->setNIsoTracks (persObj->m_nIsoTracks) ; transObj->setCharge (persObj->m_charge) ; transObj->setLeadingTrackPt (persObj->m_leadingTrackPt) ; transObj->setScalarPtSumCore (persObj->m_scalarPtSumCore); transObj->setScalarPtSumIso (persObj->m_scalarPtSumIso) ; transObj->setPtBalance (persObj->m_ptBalance) ; P4PtEtaPhiM* mom = createTransFromPStore( &m_3fastestP4PtEtaPhiMCnv, persObj->m_3fastest, log ); transObj->set3fastestPtEtaPhiM (mom->pt(), mom->eta(), mom->phi(), mom->m()); delete mom; fillTransFromPStore( &m_P4PtEtaPhiMCnv, persObj->m_P4PtEtaPhiM, transObj, log ); } //----------------------------------------------------------------------------- // Transient to persistent //----------------------------------------------------------------------------- void TrigTauTracksInfoCnv_p1::transToPers( const TrigTauTracksInfo *transObj, TrigTauTracksInfo_p1 *persObj, MsgStream &log ) { log << MSG::DEBUG << "TrigTauTracksInfoCnv_p1::transToPers called " << endreq; persObj->m_roiID = transObj->roiId() ; persObj->m_nCoreTracks = transObj->nCoreTracks() ; persObj->m_nSlowTracks = transObj->nSlowTracks() ; persObj->m_nIsoTracks = transObj->nIsoTracks() ; persObj->m_charge = transObj->charge() ; persObj->m_leadingTrackPt = transObj->leadingTrackPt() ; persObj->m_scalarPtSumCore = transObj->scalarPtSumCore(); persObj->m_scalarPtSumIso = transObj->scalarPtSumIso() ; persObj->m_ptBalance = transObj->ptBalance() ; persObj->m_3fastest = toPersistent( &m_3fastestP4PtEtaPhiMCnv, &transObj->threeFastestTracks(), log ); persObj->m_P4PtEtaPhiM = baseToPersistent( &m_P4PtEtaPhiMCnv, transObj, log ); }
[ "rushioda@lxplus754.cern.ch" ]
rushioda@lxplus754.cern.ch
66c498056c287d2e5e4be6242c009aea1ed73f2c
38ed4b54f69adef90da52268b549698ceebac47f
/trollclient.cpp
3752ad1504e2179823a97702fd8f7fb82f1a7b9f
[ "WTFPL" ]
permissive
IncredibleReticulation/stimpy
59ff4c8eed8bc326fec22112ad03a1d1b601c049
d15732c3179b5bf68d8a2930bdaced6f816b7dbd
refs/heads/master
2020-05-17T05:27:46.722495
2013-05-16T12:23:44
2013-05-16T12:23:44
9,299,253
1
0
null
null
null
null
UTF-8
C++
false
false
20,596
cpp
//Course: 4050-212-02 //Authors: Alex Buie, Luke Matarazzo, Jackson Sadowski, Steven Tucker //IDE/editor: Sublime Text 2 //Compilers: mingw32-g++ //Final SMTP Project //Filename: Client.cpp client main //Purpose: #include "Status.h" #include "ClientSocket.h" //prototypes string trim(string); int main(int argc, char * argv[]) { if(argc != 3) { cout << "USAGE: " << argv[0] << " servername(ip) portnum (usually 31000)" << endl; return 1; } int port = atoi(argv[2]); //port number to connect to string ipAddress = string(argv[1]); //ip address to connect to string recMessage; //message it receives string sendMessage; //message it sends string username = ""; //will hold username char trollChoice = ' '; //will hold if they want to troll the HELO process or not int serverFlop = 0; //will hold value given by recv function and will be -1 if the server flops and shuts down //print that we're attempting to connect cout << "Connecting to: " << ipAddress << ":" << port << endl; ClientSocket sockClient; //clientsocket object instance sockClient.connectToServer(ipAddress.c_str(), port); //connect to the server using the ip and port given cout << "Do you want to connect normal and troll (Y) or troll the HELO process (N): "; cin >> trollChoice; cin.ignore(10000, '\n'); //receive the first 220 message serverFlop = sockClient.recvData(recMessage); if(toupper(trollChoice) == 'N') //if they want to mess with the HELO process { string badCommand = ""; cout << "What would you like to send them (type quit to exit): "; getline(cin, badCommand); while(badCommand != "quit" && badCommand != "QUIT" && badCommand != "Quit") { sockClient.sendData(badCommand); serverFlop = sockClient.recvData(recMessage); cout << "\nResponse: " << recMessage << endl; if(serverFlop == -1) { cout << "they flopped\n\n"; break; } cout << "\nWhat would you like to send them (type quit to exit): "; getline(cin, badCommand); } if(serverFlop != -1) { cout << "Send QUIT (Y) or hard disconnect (N): "; cin >> trollChoice; if(toupper(trollChoice) == 'Y') sockClient.sendData("QUIT"); cout << "\nHappy trolling. :3\n\n"; } sockClient.closeConnection(); //closes connection return 0; //ends program } if(recMessage.substr(0,3) == "220") { sockClient.sendData("HELO THISISTROLL69.69.69.69"); } else { cout << "Server did not indicate that they were ready to initiate a connection :(\n"; return 69; //end program } serverFlop = sockClient.recvData(recMessage); //receive next status message from server if(recMessage.substr(0,3) == "250") //prompt for login info and send it { cout << "Username: "; getline(cin, username); username = trim(username); sendMessage = "VRFY " + username; sockClient.sendData(sendMessage); } else { cout << "Server may not have gotten our 'HELO' :(\n"; return 69; //ends program } //receive server response after login serverFlop = sockClient.recvData(recMessage); if(serverFlop == -1) { cout << "They flopped.\n"; return 69; } //check if we logged in successfully if(recMessage.substr(0,3) == "550" || recMessage.substr(0,3) == "500") //if login fails, print error and end program { cout << "Invalid user...\n"; sockClient.closeConnection(); //close connection return 1; } else if(recMessage.substr(0,3) == "250") { cout << "Logon successful.\n\n"; } else { cout << "Unknown error when attempting to login to server...\n"; return -69; //ends program } //menu options string menu = "1. Send mad data\n2. Send read inbox a lot\n3. Send bad command a lot\n4. Send VRFY a lot\n"; menu += "5. Send the same email a lot (takes a little bit of time)\n6. Quit\n"; int option = 1; while(option != 6) //while they don't enter 3 for the quit option, keep prompting for selection { if(serverFlop == -1) { cout << "There's been an unknown error on the server. Try reconnecting momentarily...\n\n"; break; } if(option > 0 && option < 7) //only print menu if they entered a valid option last time { cout << menu; //print menu } //prompt for an option and get the option cout << endl << "Enter option: "; cin >> option; string recipient; //will hold the recipient int messageCount = 0; //will count how many messages we have received. for formatting purposes int lineCount = 0; //will count how many lines per message were sent. needed to know when to data is being sent int numLines = 0; //will hold number of lines of data or commands int numMessages = 0; //will hold number of emails to send char choice = ' '; //will hold the choice of whether they want to send real or garbage data for option 5 vector<string> messageHolder; //will hold the message when we send the same message multiple times vector<string> headerHolder; //will hold the header of the message when we send the same message a lot string badCommand = ""; //will hold the bad command we want to send string messBuf = ""; //will hold the entire message and act as a buffer before printing it switch(option) { case 1: //option 1, to send an email //send who the mail is from and receive response sendMessage = "MAIL FROM:<guest@" + ipAddress + ">"; //set what we're sending sockClient.sendData(sendMessage); //notify server that we're sending mail serverFlop = sockClient.recvData(recMessage); //get the response from the server //check for an error if(!sockClient.checkError(recMessage, Status::SMTP_ACTION_COMPLETE)) { //cout << recMessage << endl; break; //break if we found one } //get recipient of the email cout << "Enter the recipient's email address (user@1.2.3.4): "; //prompts for recipient cin >> recipient; //get the recipient //send recipient of the email sendMessage = "RCPT TO:<" + recipient + ">"; //set what we're sending sockClient.sendData(sendMessage); //send data serverFlop = sockClient.recvData(recMessage); //get response //check for an error if(!sockClient.checkError(recMessage, Status::SMTP_ACTION_COMPLETE)) { //cout << recMessage << endl; break; //break if we found one } //send data to the server and get a response sockClient.sendData("DATA"); //send that we're ready to send data serverFlop = sockClient.recvData(recMessage); //get the response //check for an error if(!sockClient.checkError(recMessage, Status::SMTP_BEGIN_MSG)) break; //break if we found one cout << "how many lines of garbage would you like to send? (0 means infinite): "; cin >> numLines; //set sendmessage sendMessage = "YOU ARE BEING TROLLED. TROLOLOL. YOU ARE BEING TROLLED. TROLOLOL. YOU ARE BEING TROLLED. TROLOLOL."; if(numLines == 0) { while(true) //send forever { sockClient.sendData(sendMessage); //send the data sockClient.recvData(recMessage); //receive message from server } } else { for(int i = 0; i < numLines; i++) //send for user specified amount { sockClient.sendData(sendMessage); //send the data sockClient.recvData(recMessage); //receive message from server } } Sleep(250); sockClient.sendData("."); //send final period cout << "Payload complete.\n\n"; break; //break from case case 2: //option 2, to read messages in the user's mailbox cout << "how many times would you like to send INBOX? (0 means infinite): "; cin >> numLines; if(numLines == 0) { while(true) //send forever { sockClient.sendData("INBOX"); //send the data sockClient.recvData(recMessage); //receive message from server } } else { for(int i = 0; i < numLines; i++) //send for user specified amount { sockClient.sendData("INBOX"); //send the data sockClient.recvData(recMessage); //receive message from server } } cout << "Payload complete.\n\n"; break; case 3: cout << "How many bad commands would you like to send (0 means infinite): "; cin >> numLines; cout << "What bad command would you like to send: "; cin.ignore(1000, '\n'); getline(cin, badCommand); if(numLines == 0) { while(true) { sockClient.sendData(badCommand); sockClient.recvData(recMessage); //receive message from server } } else { for(int i = 0; i < numLines; i++) { sockClient.sendData(badCommand); sockClient.recvData(recMessage); //receive message from server } } cout << "Payload complete.\n\n"; break; case 4: cout << "How many times would you like to send VRFY (0 means infinite): "; cin >> numLines; if(numLines == 0) { while(true) //send forever { sockClient.sendData((numLines++ % 2 == 0 ? "VRFY TROLL" : "VRFY ")); //send the data sockClient.recvData(recMessage); //receive message from server } } else { for(int i = 0; i < numLines; i++) //send for user specified amount { sockClient.sendData(((numLines % 2 == 0 ? "VRFY TROLL" : "VRFY "))); //send the data sockClient.recvData(recMessage); //receive message from server } } cout << "Payload complete.\n\n"; break; case 5: cout << "How many times would you like to send this email: "; cin >> numMessages; cout << "Would you like to send your own data (Y) or garbage data (N): "; cin >> choice; cout << "Who would you like this email to be from (IP optional): "; cin >> username; //send who the mail is from and receive response sendMessage = "MAIL FROM:<"; sendMessage += (username.find("@") == -1 ? username + "@" + ipAddress + ">" : username + ">"); //set what we're sending; //check to make sure it has an ip after the @ symbol if(username.find("@")+1 == username.length()) username.insert(username.length()-2, ipAddress); headerHolder.push_back(sendMessage); //get the MAIL FROM command in this vector //get recipient of the email cout << "Enter the recipient's email address (user@1.2.3.4): "; //prompts for recipient cin >> recipient; //get the recipient //send recipient of the email sendMessage = "RCPT TO:<" + recipient + ">"; //set what we're sending headerHolder.push_back(sendMessage); //put the RCPT command in this vector //send message loop for(int i = 0; i < numMessages; i++) { if(toupper(choice) == 'N') //if they want garbage data { if(i == 0) { cout << "How many lines of garbage data would you like to send: "; cin >> numLines; if(numLines == 0) numLines = 1; } sockClient.sendData(headerHolder[0]); //send mail from command serverFlop = sockClient.recvData(recMessage); //get the response from the server //check for an error if(!sockClient.checkError(recMessage, Status::SMTP_ACTION_COMPLETE)) { cout << recMessage << endl << "Trying again...\n"; continue; //break if we found one } sockClient.sendData(headerHolder[1]); //send data serverFlop = sockClient.recvData(recMessage); //get response //check for an error if(!sockClient.checkError(recMessage, Status::SMTP_ACTION_COMPLETE)) { cout << recMessage << endl << "Trying again...\n"; continue; //break if we found one } //send data to the server and get a response sockClient.sendData("DATA"); //send that we're ready to send data serverFlop = sockClient.recvData(recMessage); //get the response //check for an error if(!sockClient.checkError(recMessage, Status::SMTP_BEGIN_MSG)) continue; //break if we found one for(int j = 0; j < numLines; j++) { Sleep(500); sockClient.sendData("YOU ARE BEING TROLLED. TROLOLOL. YOU ARE BEING TROLLED. TROLOLOL."); //send data } sockClient.sendData("."); //send the period serverFlop = sockClient.recvData(recMessage); //get response from the server //check for an error if(sockClient.checkError(recMessage, Status::SMTP_ACTION_COMPLETE)) cout << "Message sent successfully! :)\n"; else cerr << "Error sending message. :(\n"; } else //if they want to put in their own data { if(i == 0) { //get data from client and put it in the messageHolder vector cout << "Enter data. Press '.' when the message is over.\n"; //prompt for data cin.ignore(10000, '\n'); //ignore any newlines //getline(cin, sendMessage); //get the message to send while(sendMessage != ".") //while user doesn't enter a period, keep sending data for message { cout << "Data > "; //prompt for data getline(cin, sendMessage); //get the message to send if(sendMessage == "") //check if it's an empty string, if so add a newline because a getline drops that sendMessage = "\n"; messageHolder.push_back(sendMessage); //put the message in our message holder vector } cout << "Data entered successfully. Now attempting to send this message " << numMessages << " times\n"; } sockClient.sendData(headerHolder[0]); //send mail from command serverFlop = sockClient.recvData(recMessage); //get the response from the server //check for an error if(!sockClient.checkError(recMessage, Status::SMTP_ACTION_COMPLETE)) { cout << recMessage << endl << "Trying again...\n"; continue; //break if we found one } sockClient.sendData(headerHolder[1]); //send data serverFlop = sockClient.recvData(recMessage); //get response //check for an error if(!sockClient.checkError(recMessage, Status::SMTP_ACTION_COMPLETE)) { cout << recMessage << endl << "Trying again...\n"; continue; //break if we found one } //send data to the server and get a response sockClient.sendData("DATA"); //send that we're ready to send data serverFlop = sockClient.recvData(recMessage); //get the response //check for an error if(!sockClient.checkError(recMessage, Status::SMTP_BEGIN_MSG)) continue; //break if we found one for(int j = 0; j < messageHolder.size(); j++) { Sleep(500); sockClient.sendData(messageHolder[j]); //send } //get response after sending data and print status message for user cout << "Sending data. Waiting for server...\n"; serverFlop = sockClient.recvData(recMessage); //get data from server //check for an error if(sockClient.checkError(recMessage, Status::SMTP_ACTION_COMPLETE)) cout << "Message " << i+1 << " sent successfully! :)\n"; else cerr << "Error sending message " << i+1 << ". :(\n"; } } cout << "\nPayload complete.\n\n"; break; case 6: //option 6, to quit //code cout << "Send QUIT (Y) or hard disconnect (N): "; cin >> choice; if(toupper(choice) == 'Y') sockClient.sendData("QUIT"); cout << "Happy trolling. :3\n\n"; break; default: cerr << "You entered an invalid command...\n"; break; } } //close the connection sockClient.closeConnection(); return 0; //ends program } //Name: trim() //Parameters: string //Purpose: removes all leading and trailing white space //Returns: the new string string trim(string s) { while(isspace(s[0])) //if the first thing is a space, erase it until it is longer a space. { s.erase(0, 1); //remove the first index because it is a space } while(isspace(s[s.length()-1])) //if the last char of the string is a space, remove it until it is no longer a space { s.erase(s.length()-1, 1); //remove that char because it is a space } return s; //return the final string }
[ "ljm3103@rit.edu" ]
ljm3103@rit.edu
bc7391ec65c47e3d473fb0afe02240f832976f5b
a3f77b31c2c634cc76d40cd4a01fd3c8187a4f3b
/sources/core/jc/util/StringUtil.cpp
390391d9f5962602de36fb2c4a87a81e81915ae2
[]
no_license
eaglesakura/jointcoding
bb1b802e7ae173ce3906eb98db1b80e33d58dda5
3857e8ea7491855592847a67644b509c21b24fb3
refs/heads/master
2020-04-04T13:35:57.973751
2013-02-22T03:18:35
2013-02-22T03:18:35
7,032,369
7
1
null
null
null
null
UTF-8
C++
false
false
1,708
cpp
/* * StringUtil.cpp * * Created on: 2012/06/28 * Author: Takeshi */ #include "jointcoding.h" #include <string> #include "jc/system/StringUtil.h" #include "boost/algorithm/string.hpp" /** * 可変長配列 * 通常はstd::vector */ #define jc_varray ::std::vector /** * 可変長リスト * 通常はstd::list */ #define jc_vlist ::std::list namespace jc { /** * ストリングを特定の文字をセパレータにして分割する。 * @param origin 分割元のURL * @param delim 分割用の文字列 * @param result 格納先のベクター */ ::jc::s32 split(String origin, String delim, jc_varray<String> *result) { const std::string &str = origin.get_native<std::string>(); const std::string &dlm = delim.get_native<std::string>(); jc_varray<std::string> temp; // 分割はboostを利用する boost::split(temp, str, boost::is_any_of(dlm)); for (int i = 0; i < (int)temp.size(); ++i) { result->push_back(temp[i].c_str()); } return temp.size(); } /** * パスを分解し、ファイル名を取り出す。 * 取り出せなかった場合はそのまま帰す。 */ const charactor* getFileName(const charactor *path) { if (strchr(path, '/')) { return strrchr(path, '/') + 1; } else if (strchr(path, '\\')) { return strrchr(path, '\\') + 1; } else { return path; } } /** * パスを分解し、ファイル名を取り出す。 * 取り出せなかった場合はそのまま帰す。 */ const charactor* getFileExt(const charactor *path) { if (strchr(path, '.')) { return strrchr(path, '.') + 1; } return NULL; } }
[ "eagle.sakura@gmail.com" ]
eagle.sakura@gmail.com
86443a6d3f54b72681ef8ab7bc10c509f1cd24dc
6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849
/sstd_boost/sstd/boost/geometry/multi/core/interior_rings.hpp
edb14edc78f27c5d14b650ff6b7312689628f907
[ "BSL-1.0" ]
permissive
KqSMea8/sstd_library
9e4e622e1b01bed5de7322c2682539400d13dd58
0fcb815f50d538517e70a788914da7fbbe786ce1
refs/heads/master
2020-05-03T21:07:01.650034
2019-04-01T00:10:47
2019-04-01T00:10:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
805
hpp
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2008-2012 Bruno Lalande, Paris, France. // Copyright (c) 2009-2012 Mateusz Loskot, London, UK. // Parts of Boost.Geometry are redesigned from Geodan's Geographic Library // (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_MULTI_CORE_INTERIOR_RINGS_HPP #define BOOST_GEOMETRY_MULTI_CORE_INTERIOR_RINGS_HPP #include <sstd/boost/geometry/core/interior_rings.hpp> #endif // BOOST_GEOMETRY_MULTI_CORE_INTERIOR_RINGS_HPP
[ "zhaixueqiang@hotmail.com" ]
zhaixueqiang@hotmail.com
309e87686ce8dda3f8adfa88bd387409ba266de8
60bd79d18cf69c133abcb6b0d8b0a959f61b4d10
/libraries/TSL260R/examples/TSL260R_plotter/TSL260R_plotter.ino
ede82d70cab020f04edf53ea0b3854ac19f66685
[ "MIT" ]
permissive
RobTillaart/Arduino
e75ae38fa6f043f1213c4c7adb310e91da59e4ba
48a7d9ec884e54fcc7323e340407e82fcc08ea3d
refs/heads/master
2023-09-01T03:32:38.474045
2023-08-31T20:07:39
2023-08-31T20:07:39
2,544,179
1,406
3,798
MIT
2022-10-27T08:28:51
2011-10-09T19:53:59
C++
UTF-8
C++
false
false
756
ino
// // FILE: TSL260R_plotter.ino // AUTHOR: Rob Tillaart // PURPOSE: demo // DATE: 2022-11-27 // // always check datasheet // // PIN 1 - GND // PIN 2 - VDD - 5V // PIN 3 - SIGNAL #include "TSL260R.h" TSL260R TSL; uint32_t lastMeasurement = 0; void setup() { Serial.begin(115200); Serial.println(); // Serial.println(__FILE__); // Serial.print(" TSL260R_LIB_VERSION: "); // Serial.println(TSL260R_LIB_VERSION); } void loop() { uint32_t now = millis(); if (now - lastMeasurement >= 100) { lastMeasurement = now; float voltage = analogRead(A0) * 5.0 / 1023; Serial.print(voltage, 3); Serial.print(" \t"); Serial.print(TSL.irradiance(voltage), 3); Serial.println(" uW/cm2"); } } // -- END OF FILE --
[ "rob.tillaart@gmail.com" ]
rob.tillaart@gmail.com
53551c8a5d6c31f31ad0f0ad5105f9fff8004255
8e92af6d348a34173200690dc374a20b690e3e9c
/board/device/device.hpp
3f76efb9514e392d738657eff67c2b312e16b4f6
[]
no_license
CrustyAuklet/apollo3-device
d836ed178a31e149200f475c40979dc373c64e93
8545c9bdb76cf34e81bd1248e59d45295050145d
refs/heads/master
2021-02-09T18:21:40.568836
2020-03-02T08:05:04
2020-03-02T08:05:04
244,312,966
1
0
null
null
null
null
UTF-8
C++
false
false
30
hpp
#include "apollo3/device.hpp"
[ "crustyauklet@gmail.com" ]
crustyauklet@gmail.com
eeaaabd85936153daad8da16e5e2ca2e1d0cc473
3dd5e05da242a43f3533791e81a1d6cfb14cea65
/src/Bank.cpp
65dcbe3e7e6cdce20a2a351934e1027686c4fb97
[]
no_license
sreejond/MoneyOrderSecurity
62a9dd4489b3990ee5b19bbe9a03e225176d6dcb
24948684b2b8385878112f14adb409d764115944
refs/heads/master
2022-07-12T11:39:26.256017
2020-05-16T20:29:13
2020-05-16T20:29:13
264,520,469
0
0
null
null
null
null
UTF-8
C++
false
false
7,203
cpp
#include "Bank.h" #include "Customer.h" #include "MoneyOrder.h" #include <openssl/sha.h> #include <iostream> #include <cstdio> #include <cstdlib> #include <ctime> #include <sstream> #include <math.h> #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #define UNIQUE_STRING_LENGTH 10 #define BANK_PUBLIC_KEY_E 227 #define BANK_PUBLIC_KEY_D 803 #define BANK_PUBLIC_KEY_N 2059 Bank::Bank(Customer* customer) : mCustomer(customer) { srand(time(0)); } Bank::~Bank() { } void Bank::setMerchant(Merchant* merchant) { mMerchant = merchant; } string Bank::toString(ull number) { stringstream ss; ss << number; string s=ss.str(); return s; } bigint Bank::stringToInt(string str) { string num = ""; for (int i = 0; i < str.size(); i++) { ull n = str[i] - '0'; num += toString(n); } return num; } void Bank::receiveMoneyOrders(vector<bigint> blindedMoneyOrders) { ull r = rand() % blindedMoneyOrders.size(); mBlinedMoneyOrder = blindedMoneyOrders[r]; blindedMoneyOrders.erase(blindedMoneyOrders.begin() + r); mNeedToUnbindMoneyOrders = blindedMoneyOrders; } void Bank::requestUnbind() { mUnblindMoneyOrders = mCustomer->unblind(mNeedToUnbindMoneyOrders); } string Bank::charArrayToString(unsigned char* charArray) { char output[41]; output[40] = NULL; for (ull i = 0; i < 20; i++) { sprintf(output+i*2, "%02x", charArray[i]); } string str( output, output + sizeof output / sizeof output[0] ); return str; } void Bank::applySHA1() { for (ull i = 0; i != mRevealIdentity.size(); i++) { ull randomNumber = mRevealIdentity[i].first.second; ull secretNumber = mRevealIdentity[i].second.second; ull r1 = mRevealIdentity[i].first.first.first; ull r2 = mRevealIdentity[i].first.first.second; string leftStr = toString(randomNumber) + toString(r1) + toString(r2); unsigned char left[leftStr.length()]; copy(leftStr.begin(), leftStr.end(), left); unsigned char leftOut[SHA_DIGEST_LENGTH]; SHA1(left, sizeof(left), leftOut); string leftHash = charArrayToString(leftOut); ull r3 = mRevealIdentity[i].second.first.first; ull r4 = mRevealIdentity[i].second.first.second; string rightStr = toString(secretNumber) + toString(r3) + toString(r4); unsigned char right[rightStr.length()]; copy(rightStr.begin(), rightStr.end(), right); unsigned char rightOut[SHA_DIGEST_LENGTH]; SHA1(right, sizeof(right), rightOut); string rightHash = charArrayToString(rightOut); mRefIdentity.push_back(make_pair(make_pair(leftHash, r1), make_pair(rightHash, r3))); } } void Bank::requestToRevealIdentity() { mRevealIdentity = mCustomer->revealIdentity(); applySHA1(); } bool Bank::verifyIdentity(std::vector<std::pair<std::pair<std::string, ull>, std::pair<std::string, ull> > > identity) { if (identity.size() != mRefIdentity.size()) return false; for (ull i = 0; i != mRefIdentity.size(); i++) { auto refId = mRefIdentity[i]; string refLeftHash = refId.first.first; ull refLeftR1 = refId.first.second; string refRightHash = refId.second.first; ull refRightR1 = refId.second.second; auto id = identity[i]; string leftHash = id.first.first; ull leftR1 = id.first.second; string rightHash = id.second.first; ull rightR1 = id.second.second; if (refLeftHash != leftHash || refLeftR1 != leftR1 || refRightHash != rightHash || refRightR1 != rightR1) return false; } return true; } bool Bank::verifyMoneyOrders() { MoneyOrder* moneyOrder = mUnblindMoneyOrders[0]; ull amountOfMoney = moneyOrder->getAmountOfMoney(); string uniqueString = moneyOrder->getUniqueString(); auto identity = moneyOrder->getIdentity(); bool isValid = verifyIdentity(identity); if (!isValid) return false; for (ull i = 1; i != mUnblindMoneyOrders.size(); i++) { MoneyOrder* moneyOrder = mUnblindMoneyOrders[i]; ull money = moneyOrder->getAmountOfMoney(); string str = moneyOrder->getUniqueString(); auto identity = moneyOrder->getIdentity(); if (money != amountOfMoney || str == uniqueString) return false; if (!verifyIdentity(identity)) return false; } return true; } void Bank::provideSignMoneyOrder() { bigint nBigInt = bigint(toString(BANK_PUBLIC_KEY_N)); bigint tBigInt = bigint("1"); for (ull i = 1; i <= BANK_PUBLIC_KEY_D; i++) { tBigInt *= mBlinedMoneyOrder; } tBigInt = tBigInt % nBigInt; mCustomer->getSignMoneyOrder(tBigInt); } bool Bank::takeMoneyOrder(bigint signUnblinedMoneyOrder, MoneyOrder* moneyOrderOrig, vector<int> halfIdentity) { bool isValid = verifySignature(signUnblinedMoneyOrder, moneyOrderOrig); if (!isValid) { cout << "BANK: SIGNATURE VERIFICATION FAILED ON MONEY ORDER\n"; return false; } string uniqueString = moneyOrderOrig->getUniqueString(); isValid = checkUniqueString(uniqueString); if (!isValid) { checkIdentity(halfIdentity); return false; } // saved mUniqueStringMap.insert(make_pair(uniqueString, true)); mHalfIdentitySaved = halfIdentity; return true; } bool Bank::checkUniqueString(string uniqueString) { auto got = mUniqueStringMap.find(uniqueString); if (got != mUniqueStringMap.end()) return false; return true; } bool Bank::verifySignature(bigint signUnblinedMoneyOrder, MoneyOrder* moneyOrder) { bigint nBigInt = bigint(toString(BANK_PUBLIC_KEY_N)); bigint tBigInt = bigint("1"); for (ull i = 1; i <= BANK_PUBLIC_KEY_E; i++) { tBigInt *= signUnblinedMoneyOrder; } bigint moneyOrderGenerated = tBigInt % nBigInt; //cout << "message generated: " << moneyOrderGenerated << endl; /*****Hashing money order start *****/ //serialize // Create an output archive std::ostringstream os; boost::archive::binary_oarchive ar(os); // Write data ar & moneyOrder; string buf = os.str(); unsigned char bufC[buf.length()]; copy(buf.begin(), buf.end(), bufC); unsigned char bufHash[SHA_DIGEST_LENGTH]; SHA1(bufC, sizeof(bufC), bufHash); string bufHashStr = charArrayToString(bufHash); //cout << "bufHash: " << bufHash << endl; //bigint bufInteger = stringToInt(bufHashStr); ull h = mHashFunction(bufHashStr) % 1013; bigint bufInteger = bigint(toString(h)); /*****Hashing money order end *****/ if (moneyOrderGenerated != bufInteger) return false; return true; } void Bank::checkIdentity(vector<int> halfIdentity) { if (halfIdentity.size() != mHalfIdentitySaved.size()) { cout << "BANK: CUSTOMER PHOTOCOPIED MONEY ORDER\n"; return; } for (int i = 0; i != halfIdentity.size(); i++) { if (halfIdentity[i] != mHalfIdentitySaved[i]) { cout << "BANK: CUSTOMER PHOTOCOPIED MONEY ORDER\n"; return; } } cout << "BANK: MERCHANT COPIED MONEY ORDER\n"; }
[ "sreejondy@gmail.com" ]
sreejondy@gmail.com
2a4c450888b0e931fb7baf605df18925de7775a7
3517fbdfe2cfe26c33e03f179dd9abe1edc9a2a7
/Webots/remote_control/remote.hpp
03ae24a9eb29efac5f76be25ac4aef56828b4a79
[]
no_license
Isaac25silva/DRLpenalty
f595fab1dfc5e07791fafab6fcd6f61f48a0bc06
ce926912115e5e0bc0d03eaae9a3e6b202c36f8c
refs/heads/master
2020-06-26T18:17:47.083473
2019-07-30T19:04:35
2019-07-30T19:04:35
199,711,028
1
0
null
null
null
null
UTF-8
C++
false
false
1,850
hpp
// Description: Remote serveur for ROBOTIS OP2 remote-control #ifndef REMOTE_HPP #define REMOTE_HPP #define NMOTORS 20 #include <webots/Robot.hpp> namespace webots { class Motor; class PositionSensor; class LED; class Camera; class Accelerometer; class Gyro; class Remote : public Robot { public: Remote(); virtual ~Remote(); void remoteStep(); const double *getRemoteAccelerometer() const; const double *getRemoteGyro() const; const unsigned char *getRemoteImage() const; double getRemotePositionSensor(int index); double getRemoteMotorTorque(int index); double getRemoteTime() const; void setRemoteLED(int index, int value); void setRemoteMotorPosition(int index, int value); void setRemoteMotorVelocity(int index, int value); void setRemoteMotorAcceleration(int index, int value); void setRemoteMotorAvailableTorque(int index, int value); void setRemoteMotorTorque(int index, int value); void setRemoteMotorControlPID(int index, int p, int i, int d); private: void wait(int ms); void myStep(); int mTimeStep; Motor *mMotors[NMOTORS]; PositionSensor *mPositionSensor[NMOTORS]; LED *mEyeLed; LED *mHeadLed; LED *mBackLedRed; LED *mBackLedGreen; LED *mBackLedBlue; Camera *mCamera; Accelerometer *mAccelerometer; Gyro *mGyro; }; }; #endif
[ "isaac25silva@yahoo.com.br" ]
isaac25silva@yahoo.com.br
13ab4caa2e98342cabf6c484e8594ae2afe6d628
ac71111a4a9657fc60b2151ac7ce1933a7374637
/src/wte/propedit/QPropertyModel.cpp
478dd7ca1ae8c6af6fe3fd5f7c9b3fb63c0cd8db
[]
no_license
spiricn/Wt
931a49140761b510a86bea4f1c53f8bd535aa35f
e77589d766d54ff46617b0f117acd2372f99ff66
refs/heads/master
2016-09-06T04:06:17.206685
2014-04-18T13:57:43
2014-04-18T13:57:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,189
cpp
#include "stdafx.h" // ************************************************************************************************* // // QPropertyEditor v 0.3 // // -------------------------------------- // Copyright (C) 2007 Volker Wiendl // Acknowledgements to Roman alias banal from qt-apps.org for the Enum enhancement // // // The QPropertyEditor Library 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 version 3 of the License // // The Horde3D Scene Editor is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // ************************************************************************************************* #include "wte/propedit/QPropertyModel.h" #include "wte/propedit/Property.h" #include "wte/propedit/EnumProperty.h" #include <QtGui/QApplication> #include <QtCore/QMetaProperty> #include <QtGui/QItemEditorFactory> struct PropertyPair { PropertyPair(const QMetaObject* obj, QMetaProperty property) : Property(property), Object(obj) {} QMetaProperty Property; const QMetaObject* Object; bool operator==(const PropertyPair& other) const {return QString(other.Property.name()) == QString(Property.name());} }; QPropertyModel::QPropertyModel(QObject* parent /*= 0*/) : QAbstractItemModel(parent) { m_rootItem = new Property("Root",0, this); } QPropertyModel::~QPropertyModel() { } QModelIndex QPropertyModel::index ( int row, int column, const QModelIndex & parent /*= QModelIndex()*/ ) const { Property *parentItem = m_rootItem; if (parent.isValid()) parentItem = static_cast<Property*>(parent.internalPointer()); if (row >= parentItem->children().size() || row < 0) return QModelIndex(); return createIndex(row, column, parentItem->children().at(row)); } QModelIndex QPropertyModel::parent ( const QModelIndex & index ) const { if (!index.isValid()) return QModelIndex(); Property *childItem = static_cast<Property*>(index.internalPointer()); Property *parentItem = qobject_cast<Property*>(childItem->parent()); if (!parentItem || parentItem == m_rootItem) return QModelIndex(); return createIndex(parentItem->row(), 0, parentItem); } int QPropertyModel::rowCount ( const QModelIndex & parent /*= QModelIndex()*/ ) const { Property *parentItem = m_rootItem; if (parent.isValid()) parentItem = static_cast<Property*>(parent.internalPointer()); return parentItem->children().size(); } int QPropertyModel::columnCount ( const QModelIndex & /*parent = QModelIndex()*/ ) const { return 2; } QVariant QPropertyModel::data ( const QModelIndex & index, int role /*= Qt::DisplayRole*/ ) const { if (!index.isValid()) return QVariant(); Property *item = static_cast<Property*>(index.internalPointer()); switch(role) { case Qt::ToolTipRole: case Qt::DecorationRole: case Qt::DisplayRole: case Qt::EditRole: if (index.column() == 0) return item->objectName().replace('_', ' '); if (index.column() == 1) return item->value(role); case Qt::BackgroundRole: if (item->isRoot()) return QApplication::palette("QTreeView").brush(QPalette::Normal, QPalette::Button).color(); break; }; return QVariant(); } // edit methods bool QPropertyModel::setData ( const QModelIndex & index, const QVariant & value, int role /*= Qt::EditRole*/ ) { if (index.isValid() && role == Qt::EditRole) { Property *item = static_cast<Property*>(index.internalPointer()); item->setValue(value); emit dataChanged(index, index); return true; } return false; } Qt::ItemFlags QPropertyModel::flags ( const QModelIndex & index ) const { if (!index.isValid()) return Qt::ItemIsEnabled; Property *item = static_cast<Property*>(index.internalPointer()); // only allow change of value attribute if (item->isRoot()) return Qt::ItemIsEnabled; else if (item->isReadOnly()) return Qt::ItemIsDragEnabled | Qt::ItemIsSelectable; else return Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable; } QVariant QPropertyModel::headerData ( int section, Qt::Orientation orientation, int role /*= Qt::DisplayRole*/ ) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { switch (section) { case 0: return tr("Name"); case 1: return tr("Value"); } } return QVariant(); } QModelIndex QPropertyModel::buddy ( const QModelIndex & index ) const { if (index.isValid() && index.column() == 0) return createIndex(index.row(), 1, index.internalPointer()); return index; } void QPropertyModel::addItem(QObject *propertyObject) { // first create property <-> class hierarchy QList<PropertyPair> propertyMap; QList<const QMetaObject*> classList; const QMetaObject* metaObject = propertyObject->metaObject(); do { int count = metaObject->propertyCount(); for (int i=0; i<count; ++i) { QMetaProperty property = metaObject->property(i); if( property.isUser() ) // Hide Qt specific properties { PropertyPair pair(metaObject, property); int index = propertyMap.indexOf(pair); if (index != -1) propertyMap[index] = pair; else propertyMap.push_back(pair); } } classList.push_front(metaObject); } while ((metaObject = metaObject->superClass())!=0); QList<const QMetaObject*> finalClassList; // remove empty classes from hierarchy list foreach(const QMetaObject* obj, classList) { bool keep = false; foreach(PropertyPair pair, propertyMap) { if (pair.Object == obj) { keep = true; break; } } if (keep) finalClassList.push_back(obj); } // finally insert properties for classes containing them int i=rowCount(); Property* propertyItem = 0; beginInsertRows( QModelIndex(), i, i + finalClassList.count() ); foreach(const QMetaObject* metaObject, finalClassList) { // Set default name of the hierarchy property to the class name QString name = metaObject->className(); // Check if there is a special name for the class int index = metaObject->indexOfClassInfo(qPrintable(name)); if (index != -1) name = metaObject->classInfo(index).value(); // Create Property Item for class node propertyItem = new Property(name, 0, m_rootItem); foreach(PropertyPair pair, propertyMap) { // Check if the property is associated with the current class from the finalClassList if (pair.Object == metaObject) { QMetaProperty property(pair.Property); Property* p = 0; if (property.type() == QVariant::UserType && !m_userCallbacks.isEmpty()) { QList<QPropertyEditorWidget::UserTypeCB>::iterator iter = m_userCallbacks.begin(); while( p == 0 && iter != m_userCallbacks.end() ) { p = (*iter)(property.name(), propertyObject, propertyItem); ++iter; } } if( p == 0){ if(property.isEnumType()){ p = new EnumProperty(property.name(), propertyObject, propertyItem); } else { p = new Property(property.name(), propertyObject, propertyItem); } } int index = metaObject->indexOfClassInfo(property.name()); if (index != -1) p->setEditorHints(metaObject->classInfo(index).value()); } } } endInsertRows(); if( propertyItem ) addDynamicProperties( propertyItem, propertyObject ); } void QPropertyModel::updateItem ( QObject* propertyObject, const QModelIndex& parent /*= QModelIndex() */ ) { Property *parentItem = m_rootItem; if (parent.isValid()) parentItem = static_cast<Property*>(parent.internalPointer()); if (parentItem->propertyObject() != propertyObject) parentItem = parentItem->findPropertyObject(propertyObject); if (parentItem) // Indicate view that the data for the indices have changed { QModelIndex itemIndex = createIndex(parentItem->row(), 0, static_cast<Property*>(parentItem)); dataChanged(itemIndex, createIndex(parentItem->row(), 1, static_cast<Property*>(parentItem))); QList<QByteArray> dynamicProperties = propertyObject->dynamicPropertyNames(); QList<QObject*> childs = parentItem->parent()->children(); int removed = 0; for(int i = 0; i < childs.count(); ++i ) { QObject* obj = childs[i]; if( !obj->property("__Dynamic").toBool() || dynamicProperties.contains( obj->objectName().toLocal8Bit() ) ) continue; beginRemoveRows(itemIndex.parent(), i - removed, i - removed); ++removed; delete obj; endRemoveRows(); } addDynamicProperties(static_cast<Property*>(parentItem->parent()), propertyObject); } } void QPropertyModel::addDynamicProperties( Property* parent, QObject* propertyObject ) { // Get dynamic property names QList<QByteArray> dynamicProperties = propertyObject->dynamicPropertyNames(); QList<QObject*> childs = parent->children(); // Remove already existing properties from list for(int i = 0; i < childs.count(); ++i ) { if( !childs[i]->property("__Dynamic").toBool() ) continue; int index = dynamicProperties.indexOf( childs[i]->objectName().toLocal8Bit() ); if( index != -1) { dynamicProperties.removeAt(index); continue; } } // Remove invalid properites and those we don't want to add for(int i = 0; i < dynamicProperties.size(); ++i ) { QString dynProp = dynamicProperties[i]; // Skip properties starting with _ (because there may be dynamic properties from Qt with _q_ and we may // have user defined hidden properties starting with _ too if( dynProp.startsWith("_") || !propertyObject->property( qPrintable(dynProp) ).isValid() ) { dynamicProperties.removeAt(i); --i; } } if( dynamicProperties.empty() ) return; QModelIndex parentIndex = createIndex(parent->row(), 0, static_cast<Property*>(parent)); int rows = rowCount(parentIndex); beginInsertRows(parentIndex, rows, rows + dynamicProperties.count() - 1 ); // Add properties left in the list foreach(QByteArray dynProp, dynamicProperties ) { QVariant v = propertyObject->property(dynProp); Property* p = 0; if( v.type() == QVariant::UserType && !m_userCallbacks.isEmpty() ) { QList<QPropertyEditorWidget::UserTypeCB>::iterator iter = m_userCallbacks.begin(); while( p == 0 && iter != m_userCallbacks.end() ) { p = (*iter)(dynProp, propertyObject, parent); ++iter; } } if( p == 0 ) p = new Property(dynProp, propertyObject, parent); p->setProperty("__Dynamic", true); } endInsertRows(); } void QPropertyModel::clear() { beginRemoveRows(QModelIndex(), 0, rowCount()); delete m_rootItem; m_rootItem = new Property("Root",0, this); endRemoveRows(); } void QPropertyModel::registerCustomPropertyCB(QPropertyEditorWidget::UserTypeCB callback) { if ( !m_userCallbacks.contains(callback) ) m_userCallbacks.push_back(callback); } void QPropertyModel::unregisterCustomPropertyCB(QPropertyEditorWidget::UserTypeCB callback) { int index = m_userCallbacks.indexOf(callback); if( index != -1 ) m_userCallbacks.removeAt(index); }
[ "nikola.spiric.ns@gmail.com" ]
nikola.spiric.ns@gmail.com
717836fa4164ebcdf6b39526ff9e01f48eff4008
34f22d45812a86a94408fe92dc2aef2a2306d6dd
/cpp/time.cpp
952e1c744bd0b4b67a9f19e8fae99db41ca2b9e2
[]
no_license
AlexDenver/lab-box
334cb2938199dc46d69c47933c528494480f2d51
a22e9188d06cfdfb742948f2cda65159d9a5dc78
refs/heads/master
2021-10-21T17:29:19.315043
2019-03-05T07:18:30
2019-03-05T07:18:30
110,310,391
0
2
null
null
null
null
UTF-8
C++
false
false
329
cpp
#include<iostream> using namespace std; typedef struct { int h,m,s; }mTime; int main(){ mTime t1; long totalsec; cout<<"Enter Time H M S:"; cin>>t1.h>>t1.m>>t1.s; cout<<"The Time Entered is: "<<t1.h<<":"<<t1.m<<":"<<t1.s<<"\n"; totalsec = 3600*t1.h + 60*t1.m + t1.s; cout<<"Total Time in Seconds: "<<totalsec<<"\n\n"; }
[ "dnvr.dsz@gmail.com" ]
dnvr.dsz@gmail.com
ae269e7b7ab39473fbd0baaf5d34d578af20ad18
9a49ef7e6bbb638f090a6710d00ba0ece94017b6
/Rendering/OldSimpleRenderer.h
44d653f083276b29424b8ada009bee2fdb38d93b
[]
no_license
Gloix/Camaron
01fe456ec734032847b6133574e77c210bc1497d
9c5c8200dcfb37be732ddd881fe919bcf6ad42e9
refs/heads/master
2021-01-17T06:12:23.777032
2020-12-01T06:52:16
2020-12-01T06:55:56
45,498,247
0
1
null
null
null
null
UTF-8
C++
false
false
282
h
#ifndef OLDSIMPLERENDERER_H #define OLDSIMPLERENDERER_H #include "Rendering/Renderer.h" class OldSimpleRenderer: public Renderer{ public: OldSimpleRenderer(); virtual ~OldSimpleRenderer(); virtual void setUpDrawing(); void draw(RModel*); }; #endif // OLDSIMPLERENDERER_H
[ "waldoc@gmail.com" ]
waldoc@gmail.com
37498d215b9eb9b1b472865513ad643721da7266
f16ca93a097425dd80012deb14fa5840b87eb650
/Common/Visualize/Shape/hkDisplayCylinder.h
4c828017003aa6c3e53d427eef37e8e2193b13ed
[]
no_license
Veryzon/havok-2013
868a4873f5254709b77a2ed8393355b89d2398af
45812e33f4bd92c428866e5e7c1b4d71a4762fb5
refs/heads/master
2021-06-25T23:48:11.919356
2021-04-17T02:12:06
2021-04-17T02:12:06
226,624,337
4
1
null
2019-12-08T06:21:56
2019-12-08T06:21:56
null
UTF-8
C++
false
false
2,149
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_VISUALIZE_SHAPE_CYLINDER_H #define HK_VISUALIZE_SHAPE_CYLINDER_H #include <Common/Visualize/Shape/hkDisplayGeometry.h> class hkDisplayCylinder : public hkDisplayGeometry { public: HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_BASE); hkDisplayCylinder( const hkVector4& top, const hkVector4& bottom, hkReal radius, int numSides = 9, int numHeightSegments = 1 ); virtual void buildGeometry(); virtual void getWireframeGeometry( hkArrayBase<hkVector4>& lines, hkMemoryAllocator& a ); const hkVector4& getTop() { return m_top; } const hkVector4& getBottom() { return m_bottom; } hkReal getRadius() { return m_radius; } inline int getNumHeightSamples() { return m_numHeightSegments; } inline int getNumSides() { return m_numSides; } protected: hkVector4 m_top; hkVector4 m_bottom; hkReal m_radius; int m_numSides; int m_numHeightSegments; }; #endif // HK_VISUALIZE_SHAPE_CYLINDER_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20130718) * * Confidential Information of Havok. (C) Copyright 1999-2013 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ "veryzon@outlook.com.br" ]
veryzon@outlook.com.br
9c20743ba50a527c60a2ebf81217e7941cd19314
91a30d86b2de62b54709dfb29045851d53fc9777
/DX12withSDL/LogUtils.cpp
0fc0a218429ff05cd93f0c7113898696d3f34c63
[]
no_license
shufflemaster/dx12withsdl
e6fa3841d81709a0c1994ba61626b7414da26987
34176f7bfe9b532e891236c506df58f634b11601
refs/heads/master
2020-03-28T11:04:10.920649
2018-11-17T14:50:57
2018-11-17T14:50:57
148,174,069
0
0
null
null
null
null
UTF-8
C++
false
false
585
cpp
// Include standard headers #include "pch.h" #include "LogUtils.h" namespace GAL { void __cdecl odprintf(const char *format, ...) { char buf[4096], *p = buf; va_list args; int n; va_start(args, format); n = _vsnprintf(p, sizeof buf - 3, format, args); // buf-3 is room for CR/LF/NUL va_end(args); p += (n < 0) ? sizeof buf - 3 : n; while (p > buf && isspace(p[-1])) *--p = '\0'; *p++ = '\r'; *p++ = '\n'; *p = '\0'; OutputDebugStringA(buf); } };
[ "shuffle_master@skyerocke.com" ]
shuffle_master@skyerocke.com
24fa3a0b67cb7432b5aa64f31de4b36d472b48f1
3da05f5769547d89fed820fa5ff4cfe5af3c5fa1
/mpmissions/Liga_Life.Altis/dialog/Liga/LigaVehMenu.hpp
4df64c48644eb5381a85037f4688dbc4f95bd075
[]
no_license
DerHirschi/Die-Liga---Altis-Life-2.0
9efb61bae9a304c69010bfbfec3fdb915971c74a
194b394b2d9df82712feb819411c7295568a1e42
refs/heads/master
2020-03-14T15:58:03.757610
2018-05-02T06:13:38
2018-05-02T06:13:38
131,688,497
0
0
null
null
null
null
ISO-8859-1
C++
false
false
8,744
hpp
/* Edit , Author: Hirschi - Die Liga 6 verf*** Stunden Arbeit .. + 5 Std .... .:-( Ich hasse Display´s */ class Liga_vInteraction_CIV { idd = 37400; movingEnabled = 1; enableSimulation = 1; class controlsBackground { class Backdrop : Life_RscPicture { idc = -1; text = "textures\Autoschluessel1e.paa"; x = safezoneW * 0.10251; y = safezoneY * -1.657; w = safezoneW * 0.20763; h = safezoneH * 0.336249; }; }; class controls { //Con BTN 7 class ButtonSeven : Liga_RscButtonMenu { idc = 37456; colorBackground[] = {0,0, 0, 0.65}; text = ""; x = safezoneW * 0.17815; y = safezoneY * -2.71379; w = safezoneW * 0.0559692; h = safezoneH * 0.0163994; }; class ButtonClose : Liga_RscButtonMenu { idc = 37460; //shortcuts[] = {0x00050000 + 2}; colorBackground[] = {0,0, 0, 0.0}; //colorSelection[] = {1,0,0,0.25}; text = ""; onButtonClick = "closeDialog 0;"; x = safezoneW * 0.18018; y = safezoneY * -2.78839; w = safezoneW * 0.0519092; h = safezoneH * 0.03699; }; // Key BTN 6 class ButtonOne : Liga_RscButtonMenuUns { idc = 37450; colorBackground[] = {1, 1, 1, 0.9}; //colorSelection[] = {1,0,0,0.25}; text = ""; x = safezoneW * 0.19186; y = safezoneY * -1.78296; w = safezoneW * 0.0286899; h = safezoneH * 0.0663795; }; // Gerät BTN 5 class ButtonTwo : Liga_RscButtonMenuUns { idc = 37451; colorBackground[] = {1, 1, 1, 0.9}; //colorSelection[] = {1,0,0,0.25}; text = ""; x = safezoneW * 0.23722; y = safezoneY * -1.95847; w = safezoneW * 0.0166898; h = safezoneH * 0.0379397; }; //tzüv But 4 class ButtonThree : Liga_RscButtonMenuUns { idc = 37452; colorBackground[] = {1, 1, 1, 0.9}; text = ""; x = safezoneW * 0.178061; y = safezoneY * -2.15458; w = safezoneW * 0.0556897; h = safezoneH * 0.0288198; }; //rep BTN 1 class ButtonFour : Liga_RscButtonMenu { idc = 37453; colorBackground[] = {0,0, 0, 0.65}; text = ""; x = safezoneW * 0.17496; y = safezoneY * -2.3034; w = safezoneW * 0.0620591; h = safezoneH * 0.0319998; }; //ziehen BTN 3 class ButtonFive : Liga_RscButtonMenu { idc = 37454; colorBackground[] = {0,0, 0, 0.65}; text = ""; x = safezoneW * 0.17583; y = safezoneY * -2.45343; w = safezoneW * 0.0600291; h = safezoneH * 0.0334397; }; //drehen BTN 2 class ButtonSix : Liga_RscButtonMenu { idc = 37455; colorBackground[] = {0,0, 0, 0.65}; text = ""; x = safezoneW * 0.17757; y = safezoneY * -2.59775; w = safezoneW * 0.0574192; h = safezoneH * 0.0272901; }; //Trunk BTN 9 class ButtonTrunk : Liga_RscButtonMenuUns { idc = 37459; colorBackground[] = {0,0, 0, 0}; text = ""; x = safezoneW * 0.159831; y = safezoneY * -1.95847; w = safezoneW * 0.0166898; h = safezoneH * 0.0379397; }; }; }; class Liga_vInteraction_ALAC { idd = 37400; movingEnabled = false; enableSimulation = false; class controlsBackground { class Backdrop : Life_RscPicture { idc = -1; text = "textures\Adacschluessel11.paa"; x = safezoneW * 0.10251; y = safezoneY * -1.657; w = safezoneW * 0.20763; h = safezoneH * 0.336249; }; }; class controls { //Con BTN 7 class ButtonSeven : Liga_RscButtonMenu { idc = 37456; colorBackground[] = {0,0, 0, 0.65}; text = ""; x = safezoneW * 0.17758; y = safezoneY * -2.75154; w = safezoneW * 0.0561801; h = safezoneH * 0.01666; }; class ButtonClose : Liga_RscButtonMenu { idc = 37460; //shortcuts[] = {0x00050000 + 2}; colorBackground[] = {0,0, 0, 0.0}; //colorSelection[] = {1,0,0,0.25}; text = ""; onButtonClick = "closeDialog 0;"; x = safezoneW * 0.17962; y = safezoneY * -2.84368; w = safezoneW * 0.0521001; h = safezoneH * 0.03196; }; // Key BTN 6 class ButtonOne : Liga_RscButtonMenuUns { idc = 37450; colorBackground[] = {1, 1, 1, 0.9}; //colorSelection[] = {1,0,0,0.25}; text = ""; x = safezoneW * 0.19118; y = safezoneY * -1.81931; w = safezoneW * 0.0286401; h = safezoneH * 0.06596; }; // Gerät BTN 5 class ButtonTwo : Liga_RscButtonMenuUns { idc = 37451; colorBackground[] = {1, 1, 1, 0.9}; //colorSelection[] = {1,0,0,0.25}; text = ""; x = safezoneW * 0.23436; y = safezoneY * -1.96584; w = safezoneW * 0.0174201; h = safezoneH * 0.0408; }; //tzüv But 4 class ButtonThree : Liga_RscButtonMenuUns { idc = 37452; colorBackground[] = {1, 1, 1, 0.9}; text = ""; x = safezoneW * 0.1786; y = safezoneY * -2.19193; w = safezoneW * 0.0541401; h = safezoneH * 0.02686; }; //rep BTN 1 class ButtonFour : Liga_RscButtonMenu { idc = 37453; colorBackground[] = {0,0, 0, 0.65}; text = ""; x = safezoneW * 0.17452; y = safezoneY * -2.332; w = safezoneW * 0.0619601; h = safezoneH * 0.034; }; //ziehen BTN 3 class ButtonFive : Liga_RscButtonMenu { idc = 37454; colorBackground[] = {0,0, 0, 0.65}; text = ""; x = safezoneW * 0.17554; y = safezoneY * -2.48296; w = safezoneW * 0.0602601; h = safezoneH * 0.03298; }; //drehen BTN 2 class ButtonSix : Liga_RscButtonMenu { idc = 37455; colorBackground[] = {0,0, 0, 0.65}; text = ""; x = safezoneW * 0.1769; y = safezoneY * -2.63085; w = safezoneW * 0.057401; h = safezoneH * 0.02788; }; //Trunk BTN 9 class ButtonTrunk : Liga_RscButtonMenuUns { idc = 37459; colorBackground[] = {0,0, 0, 0}; text = ""; x = safezoneW * 0.1599; y = safezoneY * -1.96584; w = safezoneW * 0.0174201; h = safezoneH * 0.0408; }; }; }; class Liga_vInteraction_LRK { idd = 37400; movingEnabled = false; enableSimulation = false; class controlsBackground { class Backdrop : Life_RscPicture { idc = -1; text = "textures\LRKschlussel1.paa"; x = safezoneW * 0.10251; y = safezoneY * -1.657; w = safezoneW * 0.20763; h = safezoneH * 0.336249; }; }; class controls { //Con BTN 7 class ButtonSeven : Liga_RscButtonMenu { idc = 37456; colorBackground[] = {0,0, 0, 0.65}; text = ""; x = safezoneW * 0.17812; y = safezoneY * -2.72167; w = safezoneW * 0.0559403; h = safezoneH * 0.0171397; }; class ButtonClose : Liga_RscButtonMenu { idc = 37460; //shortcuts[] = {0x00050000 + 2}; colorBackground[] = {0,0, 0, 0.0}; //colorSelection[] = {1,0,0,0.25}; text = ""; onButtonClick = "closeDialog 0;"; x = safezoneW * 0.18046; y = safezoneY * -2.79398; w = safezoneW * 0.0523003; h = safezoneH * 0.0363798; }; // Key BTN 6 class ButtonOne : Liga_RscButtonMenuUns { idc = 37450; colorBackground[] = {1, 1, 1, 0.9}; //colorSelection[] = {1,0,0,0.25}; text = ""; x = safezoneW * 0.1919; y = safezoneY * -1.78535; w = safezoneW * 0.0286403; h = safezoneH * 0.0657597; }; // Gerät BTN 5 class ButtonTwo : Liga_RscButtonMenuUns { idc = 37451; colorBackground[] = {1, 1, 1, 0.9}; //colorSelection[] = {1,0,0,0.25}; text = ""; x = safezoneW * 0.235319; y = safezoneY * -1.92601; w = safezoneW * 0.0192803; h = safezoneH * 0.0433998; }; //tzüv But 4 class ButtonThree : Liga_RscButtonMenuUns { idc = 37452; colorBackground[] = {1, 1, 1, 0.9}; text = ""; x = safezoneW * 0.17968; y = safezoneY * -2.17257; w = safezoneW * 0.0536003; h = safezoneH * 0.0218198; }; //rep BTN 1 class ButtonFour : Liga_RscButtonMenu { idc = 37453; colorBackground[] = {0,0, 0, 0.65}; text = ""; x = safezoneW * 0.17474; y = safezoneY * -2.30548; w = safezoneW * 0.0621802; h = safezoneH * 0.0332598; }; //ziehen BTN 3 class ButtonFive : Liga_RscButtonMenu { idc = 37454; colorBackground[] = {0,0, 0, 0.65}; text = ""; x = safezoneW * 0.1763; y = safezoneY * -2.45011; w = safezoneW * 0.0601002; h = safezoneH * 0.0327398; }; //drehen BTN 2 class ButtonSix : Liga_RscButtonMenu { idc = 37455; colorBackground[] = {0,0, 0, 0.65}; text = ""; x = safezoneW * 0.1776; y = safezoneY * -2.59837; w = safezoneW * 0.0575003; h = safezoneH * 0.0277998; }; //Trunk BTN 9 class ButtonTrunk : Liga_RscButtonMenuUns { idc = 37459; colorBackground[] = {0,0, 0, 0}; text = ""; x = safezoneW * 0.15706; y = safezoneY * -1.92601; w = safezoneW * 0.0192803; h = safezoneH * 0.0433998; }; }; };
[ "hirschi@saw-emusic.de" ]
hirschi@saw-emusic.de
1fc49075f37c775286351917c220b2c1b1333c34
55ad360a2f0111b9dc9fc8d351cda82cdc244401
/Programming Paradigms/Dynamic Programming/Status[k]Type/SituationStatus/BJ2579_mycode.cpp
d656c60fda95aed4122fa3b59de69a5913560c02
[]
no_license
SeungoneKim/algorithms
6afc8823d6a96f91059b97d7f1081571f66d5d90
3fdc0a808eb22dc8c92630acb87ef34fe306d9ca
refs/heads/master
2023-03-15T06:20:58.274880
2021-03-20T06:48:25
2021-03-20T06:48:25
323,091,647
8
1
null
null
null
null
UTF-8
C++
false
false
687
cpp
#include <iostream> using namespace std; int score[301]; int dp[301][2]; // status number is continuous stair number int main(){ int stairsize; cin >> stairsize; for(int k=1;k<=stairsize;k++){ cin >> score[k]; } dp[0][0] =0; dp[0][1]=0; dp[1][0] = score[1]; dp[1][1] = 0; dp[2][0] = score[2]; dp[2][1] = score[1]+score[2]; //dp[n] is maximum scoresum including nth stair for(int k=3;k<=stairsize;k++){ dp[k][0] = max(dp[k-2][0],dp[k-2][1])+score[k]; dp[k][1] = dp[k-1][0]+score[k]; } int answ = max(dp[stairsize][0],dp[stairsize][1]); cout << answ; return 0; }
[ "louisdebroglie@yonsei.ac.kr" ]
louisdebroglie@yonsei.ac.kr
c730a750a54844cfafe0880c6f8e94b288fa2c53
b2a8e29894f681a72ecf1d51a82a63bfa920e06f
/TinySTL/Alloc.h
2424d0ed870e77c97b1ff31df7ba44d9d3da146e
[]
no_license
SinnerA/TinySTL
3881aefc5349c15fc87eec11d96d9b6197ef8aa3
5b368accd62f208dc65df5721a56c4632d5f16b5
refs/heads/master
2021-01-10T20:38:31.969512
2015-10-12T07:17:30
2015-10-12T07:17:30
35,008,182
0
0
null
null
null
null
GB18030
C++
false
false
1,738
h
#ifndef _ALLOC_H_ #define _ALLOC_H_ #include <cstdlib> namespace TinySTL{ class alloc{ private: enum EAlign{ALIGN = 8}; //小型区块的上调边界 enum EMaxBytes{MAXBYTES = 128}; //小型区块的上限,超过区块由malloc分配 enum ENFreeLists{NFREELISTS = (alloc::MAXBYTES / alloc::ALIGN)}; //free-lists的个数 enum ENObjs{NOBJS = 20}; //每次增加的区块数 private: //free-list节点 union obj{ union obj* next; char clien[1]; }; static obj* free_list[alloc::NFREELISTS]; private: static char* start_free;//内存池起始位置 static char* end_free; //内存池结束位置 static size_t heap_size;//堆大小 private: //将bytes上调至8的倍数 static size_t ROUND_UP(size_t bytes){ return ((bytes + alloc::ALIGN - 1) & ~(alloc::ALIGN - 1)); } //根据需求大小,决定使用第n个free-list,n从0开始计算 static size_t FREELIST_INDEX(size_t bytes){ return ((bytes + alloc::ALIGN - 1) / (alloc::ALIGN - 1)); } //free-list没有可用区块时,将从内存池申请获得新的区块(由chunk_alloc完成) //返回一个区块给调用者,并可能在此free-list中新增一定数量新的区块 static void *refill(size_t n); //从内存池取一大块空间,可容纳nobjs个大小为size的区块 //如果配置nobjs个区块有所不便,则nobjs会减少 static char* chunk_alloc(size_t size, size_t& nobjs); public: static void *allocate(size_t bytes); static void deallocate(void *ptr, size_t bytes); static void *reallocate(void *ptr, size_t old_size, size_t new_size); }; } #endif
[ "wu181184@sina.com" ]
wu181184@sina.com
41e64e166007bf18a3d45424c7313472419a1212
f1bd4d38d8a279163f472784c1ead12920b70be2
/Editors/!old/LevelEditor/Engine/Game/ai_alife_templates.h
879b8c530555abac976c30864f7335d8787cb9c9
[]
no_license
YURSHAT/stk_2005
49613f4e4a9488ae5e3fd99d2b60fd9c6aca2c83
b68bbf136688d57740fd9779423459ef5cbfbdbb
refs/heads/master
2023-04-05T16:08:44.658227
2021-04-18T09:08:18
2021-04-18T18:35:59
361,129,668
1
0
null
null
null
null
UTF-8
C++
false
false
7,853
h
//////////////////////////////////////////////////////////////////////////// // Module : ai_alife_templates.h // Created : 21.01.2003 // Modified : 21.01.2003 // Author : Dmitriy Iassenev // Description : A-Life templates //////////////////////////////////////////////////////////////////////////// #ifndef XRAY_AI_ALIFE_TEMPLATES #define XRAY_AI_ALIFE_TEMPLATES #include "ai_alife_interfaces.h" // delete data extern void delete_data(LPSTR &tpVector); extern void delete_data(LPCSTR &tpVector); template <class T1, class T2, class T3> void delete_data(xr_map<T1,T2,T3> &tpMap) { xr_map<T1,T2,T3>::iterator I = tpMap.begin(); xr_map<T1,T2,T3>::iterator E = tpMap.end(); for ( ; I != E; ++I) { delete_data ((*I).first); delete_data ((*I).second); } tpMap.clear (); }; template <class T1, class T2> void delete_data(xr_set<T1,T2> &tpSet) { xr_set<T1,T2>::iterator I = tpMap.begin(); xr_set<T1,T2>::iterator E = tpMap.end(); for ( ; I != E; ++I) delete_data (*I); tpSet.clear (); }; template <class T> void delete_data(xr_vector<T> &tpVector) { xr_vector<T>::iterator I = tpVector.begin(); xr_vector<T>::iterator E = tpVector.end(); for ( ; I != E; ++I) delete_data (*I); tpVector.clear (); }; template <class T> void delete_data(T *&tpData) { delete_data (*tpData); xr_delete (tpData); }; template <class T> void delete_data(T &tData) { }; // save data template <class T1, class T2, class T3, class M> void save_data(xr_map<T1,T2,T3> &tpMap, M &tStream, bool bSaveCount = true) { if (bSaveCount) tStream.w_u32 ((u32)tpMap.size()); xr_map<T1,T2,T3>::iterator I = tpMap.begin(); xr_map<T1,T2,T3>::iterator E = tpMap.end(); for ( ; I != E; ++I) save_data ((*I).second,tStream,bSaveCount); }; template <class T1, class T2, class M> void save_data(xr_set<T1,T2> &tpSet, M &tStream, bool bSaveCount = true) { if (bSaveCount) tStream.w_u32 ((u32)tpSet.size()); xr_set<T1,T2>::iterator I = tpSet.begin(); xr_set<T1,T2>::iterator E = tpSet.end(); for ( ; I != E; ++I) save_data (*I,tStream,bSaveCount); }; template <class T, class M> void save_data(xr_vector<T> &tpVector, M &tStream, bool bSaveCount = true) { if (bSaveCount) tStream.w_u32 ((u32)tpVector.size()); xr_vector<T>::iterator I = tpVector.begin(); xr_vector<T>::iterator E = tpVector.end(); for ( ; I != E; ++I) save_data (*I,tStream,bSaveCount); }; template <class M> void save_data(xr_vector<bool> &baVector, M &tStream, bool bSaveCount = true) { if (bSaveCount) tStream.w_u32 ((u32)baVector.size()); xr_vector<bool>::iterator I = baVector.begin(); xr_vector<bool>::iterator E = baVector.end(); u32 dwMask = 0; if (I != E) { for (int j=0; I != E; ++I, ++j) { if (j >= 32) { tStream.w_u32(dwMask); dwMask = 0; j = 0; } if (*I) dwMask |= u32(1) << j; } tStream.w_u32 (dwMask); } }; template <class M> void save_data(IPureServerObject &tData, M &tStream,bool bSaveCount = true) { tData.UPDATE_Write (tStream); } template <typename T, class M> void save_data(T &tData, M &tStream,bool bSaveCount = true) { tStream.w (&tData,sizeof(tData)); } template <class M> void save_data(LPSTR &tData, M &tStream,bool bSaveCount = true) { tStream.w_string (tData); } template <class T, class M> void save_data(T *&tpData, M &tStream, bool bSaveCount = true) { tpData->Save (tStream); }; template <class T, class M> void save_data(T **&tpData, M &tStream, bool bSaveCount = true) { save_data (*tpData,tStream,bSaveCount); }; template <class T1, class T2, class T3, class M> void save_data(xr_map<T1,T2,T3> *&tpMap, M &tStream, bool bSaveCount = true) { save_data (*tpMap,tStream,bSaveCount); }; template <class T1, class T2, class M> void save_data(xr_set<T1,T2> *&tpSet, M &tStream, bool bSaveCount = true) { save_data (*tpSet,tStream,bSaveCount); }; template <class T, class M> void save_data(xr_vector<T> *&tpVector, M &tStream, bool bSaveCount = true) { save_data (*tpVector,tStream,bSaveCount); }; // load data template <class T1, class T2, class T3, class M, class P> void load_data(xr_map<T1,T2,T3> &tpMap, M &tStream, const P &predicate) { tpMap.clear (); u32 dwCount = tStream.r_u32(); for (int i=0 ; i<(int)dwCount; ++i) { T2 T; load_data (T,tStream); tpMap.insert (mk_pair(predicate(T),T)); } }; template <class T1, class T2, class T3, class M> void load_data(xr_map<T1,T2,T3> &tpMap, M &tStream, const T1 tfGetKey(const T2)) { tpMap.clear (); u32 dwCount = tStream.r_u32(); for (int i=0 ; i<(int)dwCount; ++i) { T2 T; load_data (T,tStream); tpMap.insert (mk_pair(tfGetKey(T),T)); } }; template <class T1, class T2, class T3, class M> void load_data(xr_map<T1,T2*,T3> &tpMap, M &tStream, const T1 tfGetKey(const T2*)) { tpMap.clear (); u32 dwCount = tStream.r_u32(); for (int i=0 ; i<(int)dwCount; ++i) { T2 *T; load_data (T,tStream); tpMap.insert (mk_pair(tfGetKey(T),T)); } }; template <class T1, class T2, class T3, class M> void load_data(xr_map<T1,T2,T3> &tpMap, M &tStream, bool bSaveCount = true) { xr_map<T1,T2,T3>::iterator I = tpMap.begin(); xr_map<T1,T2,T3>::iterator E = tpMap.end(); for ( ; I != E; ++I) load_data ((*I).second,tStream,bSaveCount); }; template <class T1, class T2, class M> void load_data(xr_set<T1,T2> &tpSet, M &tStream, bool bSaveCount = true) { xr_set<T1,T2>::iterator I = tpSet.begin(); xr_set<T1,T2>::iterator E = tpSet.end(); for ( ; I != E; ++I) load_data (*I,tStream,bSaveCount); }; template <class T, class M> void load_data(xr_vector<T> &tpVector, M &tStream, bool bSaveCount = true) { if (bSaveCount) tpVector.resize (tStream.r_u32()); xr_vector<T>::iterator I = tpVector.begin(); xr_vector<T>::iterator E = tpVector.end(); for ( ; I != E; ++I) load_data (*I,tStream,bSaveCount); }; template <class M> void load_data(xr_vector<bool> &baVector, M &tStream, bool bSaveCount = true) { if (bSaveCount) baVector.resize (tStream.r_u32()); xr_vector<bool>::iterator I = baVector.begin(); xr_vector<bool>::iterator E = baVector.end(); u32 dwMask = 0; for (int j=32; I != E; ++I, ++j) { if (j >= 32) { dwMask = tStream.r_u32(); j = 0; } *I = !!(dwMask & (u32(1) << j)); } }; template <class M> void load_data(LPSTR &tpData, M &tStream, bool bSaveCount = true) { string4096 S; tStream.r_string (S); tpData = xr_strdup(S); }; template <class T, class M> void load_data(T &tData, M &tStream, bool bSaveCount = true) { tStream.r (&tData,sizeof(tData)); } template <class T, class M> void load_data(T *&tpData, M &tStream, bool bSaveCount = true) { if (bSaveCount) tpData = xr_new<T>(); tpData->Load (tStream); }; template <class T, class M> void load_data(T **&tpData, M &tStream, bool bSaveCount = true) { if (bSaveCount) tpData = xr_new<T>(); load_data (*tpData,tStream,bSaveCount); }; template <class T1, class T2, class T3, class M> void load_data(xr_map<T1,T2,T3> *&tpMap, M &tStream, const T1 tfGetKey(const T2)) { if (bSaveCount) tpData = xr_new<T>(); load_data (*tpMap,tStream,tfGetKey); }; template <class T1, class T2, class T3, class M, class P> void load_data(xr_map<T1,T2,T3> *&tpMap, M &tStream, const P &predicate) { if (bSaveCount) tpData = xr_new<T>(); load_data (*tpMap,tStream,predicate); }; template <class T1, class T2, class T3, class M> void load_data(xr_map<T1,T2,T3> *&tpMap, M &tStream, bool bSaveCount = true) { if (bSaveCount) tpData = xr_new<T>(); load_data (*tpMap,tStream,bSaveCount); }; template <class T, class M> void load_data(xr_vector<T> *&tpVector, M &tStream, bool bSaveCount = true) { if (bSaveCount) tpData = xr_new<T>(); load_data (*tpVector,tStream,bSaveCount); }; #endif
[ "loxotron@bk.ru" ]
loxotron@bk.ru
44b7a5eef67d377c766e9031bdfa13176c5053ad
6c690da714c6c8e3857521ee0b1016bdde3246b2
/Simple-Perceptron-NAND/utility.cpp
0fabb1eaa2b7dc8480be04a0d17e0e5f93bbcf94
[]
no_license
fincht96/Simple-Perceptron-NAND
ebe8872d5585cec5b9f9fc727bd3e1609713eb26
facda8beb9c65932349dfe0a30a7bac2e63c8fb8
refs/heads/master
2020-05-17T04:50:15.268583
2019-04-30T21:46:59
2019-04-30T21:46:59
183,518,807
0
0
null
null
null
null
UTF-8
C++
false
false
573
cpp
#include "utility.hpp" float randValFloat(float minVal, float maxVal) { std::random_device dev; // generates uniformly distibuted values std::mt19937 rng(dev()); // transforms distributed values into specified range std::uniform_real_distribution<> dis(minVal, maxVal); return (float)dis(rng); } int randValInt(int minVal, int maxVal) { std::random_device dev; // generates uniformly distibuted values std::mt19937 rng(dev()); // transforms distributed values into specified range std::uniform_int_distribution<> dis(minVal, maxVal); return dis(rng); }
[ "fincht96@gmail.com" ]
fincht96@gmail.com
105eccac792abe62567d6620f48919d84a015a81
2cab4b4c27768a2e3d732d51e20a15def35c21aa
/code/Rational/rational_throw.cpp
e355e60062cb99632aadc5b30f926d3fa8b662c3
[]
no_license
tgadeliya/cpp_projects
20403058d48177a47378dc30c5c2515e6d0da8db
776c09e2726cd3f9f86be77695be733251ea5ab4
refs/heads/master
2020-05-25T06:40:32.656470
2019-05-20T16:02:40
2019-05-20T16:02:40
176,086,157
0
0
null
null
null
null
UTF-8
C++
false
false
2,045
cpp
#include <iostream> #include <exception> using namespace std; int gcd (int a, int b){ while (a != 0 && b != 0) { if (a > b) { a = a%b; } else { b = b%a; } } return a+b; } class Rational { public: Rational() { // Default constructor num = 0; den = 1; } Rational(int numerator, int denominator) : Rational() { if (denominator == 0) { throw invalid_argument(""); } if (numerator == 0) { Rational(); } else{ int GCDivisor = gcd(abs(numerator), abs(denominator)); if ((numerator * denominator) > 0){ numerator = abs(numerator); denominator = abs(denominator); } else if (denominator < 0){ numerator = -numerator; denominator = abs(denominator); } num = numerator/GCDivisor; den = denominator/GCDivisor; } } int Numerator() const { return num; } int Denominator() const { return den; } private: int num; int den; }; Rational operator* (const Rational& lhs, const Rational& rhs) { return Rational(lhs.Numerator() * rhs.Numerator(), lhs.Denominator() * rhs.Denominator()); } Rational operator/ (const Rational& lhs, const Rational& rhs) { if (rhs.Numerator() == 0) { throw domain_error(""); } return lhs * Rational(rhs.Denominator(), rhs.Numerator()); } int main() { try { Rational r(1, 0); cout << "Doesn't throw in case of zero denominator" << endl; return 1; } catch (invalid_argument&) { } try { auto x = Rational(1, 2) / Rational(0, 1); cout << "Doesn't throw in case of division by zero" << endl; return 2; } catch (domain_error&) { } cout << "OK" << endl; return 0; }
[ "tgadeliya@gmail.com" ]
tgadeliya@gmail.com
b3bf4535a19551e98eb4fbf708d08a56d6403933
e1fe38f9207053ffa1c68c050ed6dc5e63975cd4
/mediandatastream.cpp
a042db28ce164c293a6199eeee259a30d133990c
[]
no_license
dhruv2600/leet
3199c568d7296219336ede0da8238ecd094ac402
71e73e999fa689285e7a9bc2414e7536c72cdab7
refs/heads/master
2023-09-03T06:24:41.885912
2021-10-22T17:15:06
2021-10-22T17:15:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
612
cpp
class MedianFinder { private: priprity_queue<int>maxh; priprity_queue<int,greater<int>>minh; int maxL; int maxR; int sizeL; int sizeR; public: /** initialize your data structure here. */ MedianFinder() { maxL=-1; maxR=-1; sizeR=0; sizeL=0; } void addNum(int num) { if() } double findMedian() { } }; /** * Your MedianFinder object will be instantiated and called as such: * MedianFinder* obj = new MedianFinder(); * obj->addNum(num); * double param_2 = obj->findMedian(); */
[ "dhruvsharma2600@gmail.com" ]
dhruvsharma2600@gmail.com
f0f429bcfdf645f343c8140a2a4f18ce3fb6e14e
2bcfc4aec8dabc736827e9de9e02f5880ca31bcf
/G4_Research_Project_Francis_Carroll_C00226918/include/yaml-cpp-d/yaml-cpp/node/impl.h
2bace705301ccba19dd01dcb2f4250d29b42b6b6
[]
no_license
francis-carroll/G4_Research_Project_Francis_Carroll_C00226918
cf3143d1857e97aaac6e955f331bb01acdbeff66
96fa32a91b27728d0bd76f8cc2b65c547a032e87
refs/heads/master
2023-04-18T21:35:15.262903
2021-05-04T11:08:49
2021-05-04T11:08:49
309,066,678
0
0
null
null
null
null
UTF-8
C++
false
false
10,731
h
#ifndef NODE_IMPL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define NODE_IMPL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #if defined(_MSC_VER) || \ (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \ (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #pragma once #endif #include "yaml-cpp/node/node.h" #include "yaml-cpp/node/iterator.h" #include "yaml-cpp/node/detail/memory.h" #include "yaml-cpp/node/detail/node.h" #include "yaml-cpp/exceptions.h" #include <string> namespace YAML { inline Node::Node() : m_isValid(true), m_pNode(NULL) {} inline Node::Node(NodeType::value type) : m_isValid(true), m_pMemory(new detail::memory_holder), m_pNode(&m_pMemory->create_node()) { m_pNode->set_type(type); } template <typename T> inline Node::Node(const T& rhs) : m_isValid(true), m_pMemory(new detail::memory_holder), m_pNode(&m_pMemory->create_node()) { Assign(rhs); } inline Node::Node(const detail::iterator_value& rhs) : m_isValid(rhs.m_isValid), m_pMemory(rhs.m_pMemory), m_pNode(rhs.m_pNode) {} inline Node::Node(const Node& rhs) : m_isValid(rhs.m_isValid), m_pMemory(rhs.m_pMemory), m_pNode(rhs.m_pNode) {} inline Node::Node(Zombie) : m_isValid(false), m_pNode(NULL) {} inline Node::Node(detail::node& node, detail::shared_memory_holder pMemory) : m_isValid(true), m_pMemory(pMemory), m_pNode(&node) {} inline Node::~Node() {} inline void Node::EnsureNodeExists() const { if (!m_isValid) throw InvalidNode(); if (!m_pNode) { m_pMemory.reset(new detail::memory_holder); m_pNode = &m_pMemory->create_node(); m_pNode->set_null(); } } inline bool Node::IsDefined() const { if (!m_isValid) { return false; } return m_pNode ? m_pNode->is_defined() : true; } inline Mark Node::Mark() const { if (!m_isValid) { throw InvalidNode(); } return m_pNode ? m_pNode->mark() : Mark::null_mark(); } inline NodeType::value Node::Type() const { if (!m_isValid) throw InvalidNode(); return m_pNode ? m_pNode->type() : NodeType::Null; } // access // template helpers template <typename T, typename S> struct as_if { explicit as_if(const Node& node_) : node(node_) {} const Node& node; T operator()(const S& fallback) const { if (!node.m_pNode) return fallback; T t; if (convert<T>::decode(node, t)) return t; return fallback; } }; template <typename S> struct as_if<std::string, S> { explicit as_if(const Node& node_) : node(node_) {} const Node& node; const std::string operator()(const S& fallback) const { if (node.Type() != NodeType::Scalar) return fallback; return node.Scalar(); } }; template <typename T> struct as_if<T, void> { explicit as_if(const Node& node_) : node(node_) {} const Node& node; const T operator()() const { if (!node.m_pNode) throw TypedBadConversion<T>(node.Mark()); T t; //Node& rhs = t; //rhs.reset(node); if (convert<T>::decode(node, t)) return t; throw TypedBadConversion<T>(node.Mark()); } }; template <> struct as_if<std::string, void> { explicit as_if(const Node& node_) : node(node_) {} const Node& node; const std::string operator()() const { if (node.Type() != NodeType::Scalar) throw TypedBadConversion<std::string>(node.Mark()); return node.Scalar(); } }; // access functions template <typename T> inline T Node::as() const { if (!m_isValid) throw InvalidNode(); return as_if<T, void>(*this)(); } template <typename T, typename S> inline T Node::as(const S& fallback) const { if (!m_isValid) return fallback; return as_if<T, S>(*this)(fallback); } inline const std::string& Node::Scalar() const { if (!m_isValid) throw InvalidNode(); return m_pNode ? m_pNode->scalar() : detail::node_data::empty_scalar; } inline const std::string& Node::Tag() const { if (!m_isValid) throw InvalidNode(); return m_pNode ? m_pNode->tag() : detail::node_data::empty_scalar; } inline void Node::SetTag(const std::string& tag) { if (!m_isValid) throw InvalidNode(); EnsureNodeExists(); m_pNode->set_tag(tag); } inline EmitterStyle::value Node::Style() const { if (!m_isValid) throw InvalidNode(); return m_pNode ? m_pNode->style() : EmitterStyle::Default; } inline void Node::SetStyle(EmitterStyle::value style) { if (!m_isValid) throw InvalidNode(); EnsureNodeExists(); m_pNode->set_style(style); } // assignment inline bool Node::is(const Node& rhs) const { if (!m_isValid || !rhs.m_isValid) throw InvalidNode(); if (!m_pNode || !rhs.m_pNode) return false; return m_pNode->is(*rhs.m_pNode); } template <typename T> inline Node& Node::operator=(const T& rhs) { if (!m_isValid) throw InvalidNode(); Assign(rhs); return *this; } inline void Node::reset(const YAML::Node& rhs) { if (!m_isValid || !rhs.m_isValid) throw InvalidNode(); m_pMemory = rhs.m_pMemory; m_pNode = rhs.m_pNode; } template <typename T> inline void Node::Assign(const T& rhs) { if (!m_isValid) throw InvalidNode(); AssignData(convert<T>::encode(rhs)); } template <> inline void Node::Assign(const std::string& rhs) { if (!m_isValid) throw InvalidNode(); EnsureNodeExists(); m_pNode->set_scalar(rhs); } inline void Node::Assign(const char* rhs) { if (!m_isValid) throw InvalidNode(); EnsureNodeExists(); m_pNode->set_scalar(rhs); } inline void Node::Assign(char* rhs) { if (!m_isValid) throw InvalidNode(); EnsureNodeExists(); m_pNode->set_scalar(rhs); } inline Node& Node::operator=(const Node& rhs) { if (!m_isValid || !rhs.m_isValid) throw InvalidNode(); if (is(rhs)) return *this; AssignNode(rhs); return *this; } inline void Node::AssignData(const Node& rhs) { if (!m_isValid || !rhs.m_isValid) throw InvalidNode(); EnsureNodeExists(); rhs.EnsureNodeExists(); m_pNode->set_data(*rhs.m_pNode); m_pMemory->merge(*rhs.m_pMemory); } inline void Node::AssignNode(const Node& rhs) { if (!m_isValid || !rhs.m_isValid) throw InvalidNode(); rhs.EnsureNodeExists(); if (!m_pNode) { m_pNode = rhs.m_pNode; m_pMemory = rhs.m_pMemory; return; } m_pNode->set_ref(*rhs.m_pNode); m_pMemory->merge(*rhs.m_pMemory); m_pNode = rhs.m_pNode; } // size/iterator inline std::size_t Node::size() const { if (!m_isValid) throw InvalidNode(); return m_pNode ? m_pNode->size() : 0; } inline const_iterator Node::begin() const { if (!m_isValid) return const_iterator(); return m_pNode ? const_iterator(m_pNode->begin(), m_pMemory) : const_iterator(); } inline iterator Node::begin() { if (!m_isValid) return iterator(); return m_pNode ? iterator(m_pNode->begin(), m_pMemory) : iterator(); } inline const_iterator Node::end() const { if (!m_isValid) return const_iterator(); return m_pNode ? const_iterator(m_pNode->end(), m_pMemory) : const_iterator(); } inline iterator Node::end() { if (!m_isValid) return iterator(); return m_pNode ? iterator(m_pNode->end(), m_pMemory) : iterator(); } // sequence template <typename T> inline void Node::push_back(const T& rhs) { if (!m_isValid) throw InvalidNode(); push_back(Node(rhs)); } inline void Node::push_back(const Node& rhs) { if (!m_isValid || !rhs.m_isValid) throw InvalidNode(); EnsureNodeExists(); rhs.EnsureNodeExists(); m_pNode->push_back(*rhs.m_pNode, m_pMemory); m_pMemory->merge(*rhs.m_pMemory); } // helpers for indexing namespace detail { template <typename T> struct to_value_t { explicit to_value_t(const T& t_) : t(t_) {} const T& t; typedef const T& return_type; const T& operator()() const { return t; } }; template <> struct to_value_t<const char*> { explicit to_value_t(const char* t_) : t(t_) {} const char* t; typedef std::string return_type; const std::string operator()() const { return t; } }; template <> struct to_value_t<char*> { explicit to_value_t(char* t_) : t(t_) {} const char* t; typedef std::string return_type; const std::string operator()() const { return t; } }; template <std::size_t N> struct to_value_t<char[N]> { explicit to_value_t(const char* t_) : t(t_) {} const char* t; typedef std::string return_type; const std::string operator()() const { return t; } }; // converts C-strings to std::strings so they can be copied template <typename T> inline typename to_value_t<T>::return_type to_value(const T& t) { return to_value_t<T>(t)(); } } // indexing template <typename Key> inline const Node Node::operator[](const Key& key) const { if (!m_isValid) throw InvalidNode(); EnsureNodeExists(); detail::node* value = static_cast<const detail::node&>(*m_pNode) .get(detail::to_value(key), m_pMemory); if (!value) { return Node(ZombieNode); } return Node(*value, m_pMemory); } template <typename Key> inline Node Node::operator[](const Key& key) { if (!m_isValid) throw InvalidNode(); EnsureNodeExists(); detail::node& value = m_pNode->get(detail::to_value(key), m_pMemory); return Node(value, m_pMemory); } template <typename Key> inline bool Node::remove(const Key& key) { if (!m_isValid) throw InvalidNode(); EnsureNodeExists(); return m_pNode->remove(detail::to_value(key), m_pMemory); } inline const Node Node::operator[](const Node& key) const { if (!m_isValid || !key.m_isValid) throw InvalidNode(); EnsureNodeExists(); key.EnsureNodeExists(); m_pMemory->merge(*key.m_pMemory); detail::node* value = static_cast<const detail::node&>(*m_pNode).get(*key.m_pNode, m_pMemory); if (!value) { return Node(ZombieNode); } return Node(*value, m_pMemory); } inline Node Node::operator[](const Node& key) { if (!m_isValid || !key.m_isValid) throw InvalidNode(); EnsureNodeExists(); key.EnsureNodeExists(); m_pMemory->merge(*key.m_pMemory); detail::node& value = m_pNode->get(*key.m_pNode, m_pMemory); return Node(value, m_pMemory); } inline bool Node::remove(const Node& key) { if (!m_isValid || !key.m_isValid) throw InvalidNode(); EnsureNodeExists(); key.EnsureNodeExists(); return m_pNode->remove(*key.m_pNode, m_pMemory); } // map template <typename Key, typename Value> inline void Node::force_insert(const Key& key, const Value& value) { if (!m_isValid) throw InvalidNode(); EnsureNodeExists(); m_pNode->force_insert(detail::to_value(key), detail::to_value(value), m_pMemory); } // free functions inline bool operator==(const Node& lhs, const Node& rhs) { return lhs.is(rhs); } } #endif // NODE_IMPL_H_62B23520_7C8E_11DE_8A39_0800200C9A66
[ "fcarroll29@gmail.com" ]
fcarroll29@gmail.com
6d83cb129e6b10cfa6dd24a37b0314835aef6c78
8760b4035fb7824dbaba10253a5ca8bc4880325a
/src/lang/rd_parser_base_class.hpp
fc42dc46ac69eba243fe45ca5a0b68e6d777eb62
[ "MIT" ]
permissive
fl4shk/liborangepower
39c26465300433c83b8ca2ef3dce351b4d7d6f43
bfc59fa8dc68a3a3c89f6cddedb01a5303936ce8
refs/heads/master
2023-03-18T06:28:01.822623
2023-03-13T16:03:23
2023-03-13T16:03:23
80,452,622
3
1
null
null
null
null
UTF-8
C++
false
false
11,967
hpp
#ifndef liborangepower_lang_rd_parser_base_class_hpp #define liborangepower_lang_rd_parser_base_class_hpp #include "../misc/misc_includes.hpp" #include "../misc/misc_output_funcs.hpp" #include "../misc/misc_input_classes.hpp" #include "../strings/sconcat_etc.hpp" #include "file_pos_class.hpp" #include <variant> #include <optional> #include <memory> #include <fstream> #include <string> #include <map> #include <set> namespace liborangepower { using misc_output::printout; using misc_output::printerr; using misc_output::osprintout; using strings::sconcat; namespace lang { // A base class for parsing LL(1) grammars via recursive descent. template<typename LexerT, typename DerivedT> class RdParserBase { public: // types //-------- using TokT = LexerT::TokT; using LexerState = LexerT::State; using TokSet = std::set<TokT>; using ParseRet = std::optional<TokSet>; using ParseFunc = ParseRet (DerivedT::*)(); //-------- //-------- friend class PrologueAndEpilogue; class PrologueAndEpilogue final { private: // variables RdParserBase* _parser = nullptr; string _saved_parse_func_str; //TokSet _to_merge_tok_set; public: // functions inline PrologueAndEpilogue(RdParserBase* s_parser, string&& s_parse_func_str) : _parser(s_parser) { _saved_parse_func_str = std::move(_parser->_parse_func_str); _parser->_parse_func_str = std::move(s_parse_func_str); } GEN_CM_BOTH_CONSTRUCTORS_AND_ASSIGN(PrologueAndEpilogue); inline ~PrologueAndEpilogue() { _parser->_parse_func_str = std::move(_saved_parse_func_str); //_parser->_wanted_tok_set_merge(_to_merge_tok_set); } GEN_GETTER_BY_CON_REF(saved_parse_func_str); //GEN_GETTER_AND_SETTER_BY_CON_REF(to_merge_tok_set); //inline void internal_err(const std::string& msg="") const //{ // _parser->_internal_err(_parser->_parse_func_str, msg); //} }; //-------- protected: // variables std::string _filename, _text; std::unique_ptr<LexerT> _lexer; string _parse_func_str; bool _just_get_valid_tokens = false; //bool _debug = false; protected: // variables //bool _found_wanted_tok; TokSet _wanted_tok_set; public: // functions inline RdParserBase(const std::string& s_filename) : _filename(s_filename) { if (auto&& f = std::ifstream(filename()); true) { _text = misc_input::get_istream_as_str(f); } _lexer.reset(new LexerT(_filename, &_text)); _next_tok(); //_lexer.reset(new LexerT(_filename, _text)); //_next_tok(); } GEN_CM_BOTH_CONSTRUCTORS_AND_ASSIGN(RdParserBase); virtual inline ~RdParserBase() = default; inline FilePos lex_file_pos() const { return _lexer->file_pos(); } inline auto lex_tok() const { return _lexer->tok(); } inline const auto& lex_s() const { return _lexer->s(); } inline const auto& lex_n() const { return _lexer->n(); } inline auto prev_lex_tok() const { return _lexer->prev_state().tok(); } inline const auto& prev_lex_s() const { return _lexer->prev_state().s(); } inline const auto& prev_lex_n() const { return _lexer->prev_state().n(); } GEN_GETTER_BY_CON_REF(filename); GEN_GETTER_BY_VAL(just_get_valid_tokens); protected: // functions inline ParseRet _call_parse_func(const ParseFunc& parse_func) { return (_self()->*parse_func)(); } template<typename FirstArgT, typename... RemArgTs> inline void _warn(const FilePos& some_file_pos, const FirstArgT& first_arg, RemArgTs&&... rem_args) const { some_file_pos.warn(sconcat(first_arg, rem_args...)); } template<typename FirstArgT, typename... RemArgTs> inline void _lex_fp_warn(const FirstArgT& first_arg, RemArgTs&&... rem_args) const { _warn(lex_file_pos(), first_arg, rem_args...); } template<typename FirstArgT, typename... RemArgTs> inline void _err(const FilePos& some_file_pos, const FirstArgT& first_arg, RemArgTs&&... rem_args) const { some_file_pos.err(sconcat(first_arg, rem_args...)); } template<typename FirstArgT, typename... RemArgTs> inline void _lex_fp_err(const FirstArgT& first_arg, RemArgTs&&... rem_args) const { _err(lex_file_pos(), first_arg, rem_args...); } inline DerivedT* _self() { return static_cast<DerivedT*>(this); } inline auto _next_tok() { return _lexer->next_tok(); } template<typename... ArgTs> inline void _pfs_internal_err(const ArgTs&... args) const { if constexpr (sizeof...(args) > 0) { _internal_err(_parse_func_str, sconcat(args...)); } else { _internal_err(_parse_func_str); } } virtual inline void _internal_err(const std::string& func_str, const std::string& msg="") const { string full_msg = sconcat(func_str, "(): Internal error"); if (msg.size() == 0) { full_msg += "."; } else // if (msg.size() > 0) { full_msg += sconcat(": ", msg); } lex_file_pos().err(full_msg); } inline void _tok_set_merge(TokSet& tok_set, const TokSet& to_merge_from) { // Check for duplicate tokens, i.e. a non-LL(1) grammar, and // spit out an error if duplicate tokens were found. for (const auto& outer_item: tok_set) { for (const auto& inner_item: to_merge_from) { if (outer_item == inner_item) { _internal_err("_tok_set_merge", sconcat(": ", "Duplicate token \"", _lexer->tok_to_string_map() .at(outer_item), "\".")); } } } TokSet temp_to_merge_from = to_merge_from; tok_set.merge(temp_to_merge_from); } inline void _wanted_tok_set_merge(const TokSet& to_merge_from) { _tok_set_merge(_wanted_tok_set, to_merge_from); } inline void _tok_set_merge(TokSet& tok_set, const ParseRet& to_merge_from) { _tok_set_merge(tok_set, *to_merge_from); } inline void _wanted_tok_set_merge(const ParseRet& to_merge_from) { _wanted_tok_set_merge(*to_merge_from); } private: // functions inline ParseRet _inner_check_parse(TokSet& tok_set, const ParseFunc& parse_func) { const bool old_just_get_valid_tokens = just_get_valid_tokens(); _just_get_valid_tokens = true; const auto ret = _call_parse_func(parse_func); _just_get_valid_tokens = old_just_get_valid_tokens; _tok_set_merge(tok_set, ret); return ret; } template<typename... RemFuncTs> inline std::optional<ParseFunc> _check_parse(TokSet& tok_set, const ParseFunc& first_func, RemFuncTs&&... rem_funcs) { const auto parse_ret = _inner_check_parse(tok_set, first_func); if (parse_ret->count(lex_tok()) > 0) { //_found_wanted_tok = true; return first_func; } else if constexpr (sizeof...(rem_funcs) > 0) { return _check_parse(tok_set, rem_funcs...); } else { return std::nullopt; } } protected: // functions template<typename... RemFuncTs> inline std::optional<ParseFunc> _check_parse (const ParseFunc& first_func, RemFuncTs&&... rem_funcs) { return _check_parse(_wanted_tok_set, first_func, rem_funcs...); } private: // functions template<typename... RemArgTs> inline void _inner_get_valid_tok_set(TokSet& ret, const ParseFunc& first_parse_func, RemArgTs&&... rem_args) { _inner_check_parse(ret, first_parse_func); if constexpr (sizeof...(rem_args) > 0) { _inner_get_valid_tok_set(ret, rem_args...); } } protected: // functions template<typename... RemArgTs> inline TokSet _get_valid_tok_set(const ParseFunc& first_parse_func, RemArgTs&&... rem_args) { TokSet ret; _inner_get_valid_tok_set(ret, first_parse_func, rem_args...); return ret; } //private: // functions // inline bool _inner_attempt_parse(const ParseFunc& parse_func) // { // //_wanted_tok_set_merge(_get_valid_tok_set(parse_func)); // // if (_check_parse(parse_func)) // { // _call_parse_func(parse_func); // return true; // } // else // { // return false; // } // } protected: // functions //inline bool _attempt_parse_basic(const ParseFunc& parse_func) //{ // _wanted_tok_set.clear(); // return _inner_attempt_parse(parse_func); //} inline bool _attempt_parse(const ParseFunc& parse_func) { //_wanted_tok_set_merge(_get_valid_tok_set(parse_func)); //return _inner_attempt_parse(parse_func); if (_check_parse(parse_func)) { _call_parse_func(parse_func); return true; } else { return false; } } //inline bool _attempt_parse_opt(const ParseFunc& parse_func) //{ // const bool ret = _inner_attempt_parse(parse_func); // if (!ret) // { // _wanted_tok_set_merge(_get_valid_tok_set(parse_func); // } // return ret; //} //inline void _fail_if_not_found_wanted_tok() const //{ // if (!_found_wanted_tok) // { // _expect(_wanted_tok_set); // } //} private: // functions template<typename... RemArgTs> inline std::optional<TokT> _cmp_tok(TokT to_cmp, TokT first_tok, RemArgTs&&... rem_args) const { if (to_cmp == first_tok) { return first_tok; } else if constexpr (sizeof...(rem_args) > 0) { return _cmp_tok(to_cmp, rem_args...); } else { return std::nullopt; } } inline std::optional<TokT> _cmp_tok(TokT to_cmp, const TokSet& tok_set) const { for (const auto& tok: tok_set) { if (to_cmp == tok) { return tok; } } return std::nullopt; } protected: // functions template<typename... RemArgTs> inline std::optional<TokT> _cmp_lex_tok(TokT first_tok, RemArgTs&&... rem_args) const { return _cmp_tok(lex_tok, first_tok, rem_args...); } inline std::optional<TokT> _cmp_lex_tok(const TokSet& tok_set) const { return _cmp_tok(lex_tok(), tok_set); } template<typename... RemArgTs> inline std::optional<TokT> _cmp_prev_lex_tok(TokT first_tok, RemArgTs&&... rem_args) const { return _cmp_tok(prev_lex_tok, first_tok, rem_args...); } inline std::optional<TokT> _cmp_prev_lex_tok(const TokSet& tok_set) const { return _cmp_tok(prev_lex_tok(), tok_set); } void _inner_expect_fail(const TokSet& tok_set) const { std::string msg = sconcat("Expected one of the following tokens:", " {"); decltype(tok_set.size()) i = 0; for (const auto& p: tok_set) { msg += _lexer->tok_to_string_map().at(p); if ((i + 1) < tok_set.size()) { msg += ", "; } ++i; } msg += sconcat("}"); lex_file_pos().err(msg); } private: // functions template<typename... RemArgTs> bool _inner_expect(TokSet& tok_set, TokT first_tok, RemArgTs&&... rem_args) const { tok_set.insert(first_tok); if (lex_tok() == first_tok) { return true; } else if constexpr (sizeof...(rem_args) > 0) { return _inner_expect(tok_set, rem_args...); } else { return false; } } protected: // functions template<typename... RemArgTs> void _expect(TokT first_tok, RemArgTs&&... rem_args) { TokSet tok_set; if (!_inner_expect(tok_set, first_tok, rem_args...)) { _tok_set_merge(tok_set, _wanted_tok_set); _inner_expect_fail(tok_set); } _next_tok(); _wanted_tok_set.clear(); } void _expect_wanted_tok() { if (!_cmp_lex_tok(_wanted_tok_set)) { _inner_expect_fail(_wanted_tok_set); } _wanted_tok_set.clear(); } //inline void _expect_wanted_tok(const TokSet& extra_wanted_tok_set) //{ // _wanted_tok_set_merge(extra_wanted_tok_set); // _expect_wanted_tok(); //} //private: // functions // template<typename... RemArgTs> // bool _inner_sel_parse(TokSet& tok_set, TokT first_tok, // ParseFunc first_parse_func, RemArgTs&&... rem_args) // { // tok_set.insert(first_tok); // // if (_lexer->tok() == first_tok) // { // _call_parse_func(parse_func); // return true; // } // else if constexpr (sizeof...(rem_args) > 0) // { // return _inner_sel_parse(tok_set, rem_args...); // } // else // { // return false; // } // } // //protected: // functions // template<typename... RemArgTs> // void _sel_parse(TokT first_tok, ParseFunc first_parse_func, // RemArgTs&&... rem_args) // { // TokSet tok_set; // // if (!_inner_sel_parse(tok_set, first_tok, first_parse_func, // rem_args...)) // { // _inner_expect_fail(tok_set); // } // } }; } // namespace lang } // namespace liborangepower #endif // liborangepower_lang_rd_parser_base_class_hpp
[ "fl4shk@users.noreply.github.com" ]
fl4shk@users.noreply.github.com
c8e353dd36eb59e8e518eb9054fc85d6d41659ab
76bdea87d5df7add7ff9498e6075577a35832ddf
/Other/2.20.cpp
4f85d4f6e91c00f637e7d1d637c08f25440e8af9
[]
no_license
ouxu/CppRecord
fc730747ded98377c364d6edae58241ed3fef45a
7656c9502d47d71859a6216ba2767860b237ccca
refs/heads/master
2020-04-16T02:39:28.314941
2019-01-11T08:05:49
2019-01-11T08:05:49
60,455,388
2
0
null
null
null
null
UTF-8
C++
false
false
202
cpp
#include <iostream> #include <stdlib.h> using namespace std; int main() { int i=100,sum=0; for(int i=0;i!=10;++i) sum +=i; cout<<i<<" "<<sum<<endl; system("pause"); return 0; }
[ "fengcheng.xjj@alibaba-inc.com" ]
fengcheng.xjj@alibaba-inc.com
4864313a841ee8b68f66097d9e8ca97b17644f63
4fce902913aadf47bd7698775abc3bd13865be40
/datastruct/Stack/ArryStack.cpp
d4daa007e8452860e265bea4ce63ddecd0e5da91
[]
no_license
wenxueliu/data_structure
0a89f378d9d846a839a8577c4eb869c7a16c785f
9cadb4949150a1e8c0278330e6cb8ba6a808b7e2
refs/heads/master
2021-01-21T01:03:38.879433
2014-09-23T15:51:31
2014-09-23T15:51:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
744
cpp
/*----------------------------------------- FlieNaem : ArryStack.cpp Version : 0.10 Date : 9-16-2012 TIME : 00:19 comment : achieve the stack by array -----------------------------------------*/ #include <iostream> #include "ArryStack.h" using namespace std; int main() { Stack<int> stack; int i; for(i = 0; i < 10; ++i) { stack.push(i); } cout<<stack.size()<<endl; cout<<stack.capcity()<<endl; if(stack.isFull()) { cout<<"the stack is full!!"<<endl; } for(i = 10; i > 0; --i) { cout<<stack.topData()<<endl; stack.pop(); } cout<<stack.size()<<endl; cout<<stack.capcity()<<endl; if (stack.isEmpty()) { cout<<"the stack is empty!"<<endl; } return 0; }
[ "wenxueliu73@gmail.com" ]
wenxueliu73@gmail.com
f213b7bcbb3ddd8f644ca65d3bdc2e6a3d52ed3a
548140c7051bd42f12b56e8bb826074609c8b72e
/Engine/Code/Engine/Math/Transform2D.cpp
291a2381f73530a04107ba168001b0a8a8620e96
[]
no_license
etrizzo/PersonalEngineGames
3c55323ae730b6499a2d287c535c8830e945b917
6ef9db0fd4fd34c9e4e2f24a8b58540c075af280
refs/heads/master
2021-06-16T22:01:57.973833
2021-01-26T03:54:58
2021-01-26T03:54:58
135,343,718
0
0
null
null
null
null
UTF-8
C++
false
false
4,187
cpp
#include "Transform2D.hpp" Matrix44 transform2D_t::GetMatrix() const { Matrix44 mat = Matrix44(); mat.SetIdentity(); mat.Translate2D(m_position); mat.RotateDegrees2D(m_rotation); mat.Scale2D(m_scale.x, m_scale.y); return mat; } void transform2D_t::SetMatrix(Matrix44 const & mat) { m_scale = mat.GetScale().XY(); m_rotation = mat.GetEulerAngles().z; m_position = mat.GetPosition().XY(); } void transform2D_t::SetPosition(Vector2 pos) { m_position = pos; } void transform2D_t::Translate(Vector2 offset) { m_position+=offset; } Vector2 transform2D_t::GetPosition() const { return m_position; } void transform2D_t::SetRotationEuler(float euler) { m_rotation = euler; } void transform2D_t::RotateByEuler(float euler) { m_rotation+=euler; //m_euler.x = ClampFloat( m_euler.x, -90.f, 90.f ); //m_euler.y = modf( m_euler.y, 2.0f * PI ); } float transform2D_t::GetEulerAngles() const { return m_rotation; } void transform2D_t::SetScale(Vector2 s) { m_scale = s; } Vector2 transform2D_t::GetScale() const { return m_scale; } Transform2D::Transform2D() { m_transformStruct = transform2D_t(); m_localMatrix = Matrix44(); m_localMatrix.SetIdentity(); m_parent = nullptr; m_children = std::vector<Transform2D*>(); } Transform2D::~Transform2D() { m_children.clear(); } Matrix44 Transform2D::GetWorldMatrix() const { //m_worldMatrix = Matrix44(m_localMatrix); //if (m_parent != nullptr){ // Matrix44 parent = m_parent->GetWorldMatrix(); // parent.Append(m_worldMatrix); // return parent; //} return m_worldMatrix; } Matrix44 Transform2D::GetLocalMatrix() const { return m_localMatrix; } void Transform2D::SetLocalMatrix(Matrix44 const & mat) { m_transformStruct.SetMatrix(mat); SetMatrices(); } void Transform2D::SetLocalPosition(Vector2 pos) { m_transformStruct.SetPosition(pos); SetMatrices(); } void Transform2D::TranslateLocal(Vector2 offset) { m_transformStruct.Translate(offset); SetMatrices(); } Vector2 Transform2D::GetWorldPosition() const { Matrix44 world = GetWorldMatrix(); return world.GetPosition().XY(); } Vector2 Transform2D::GetLocalPosition() const { return m_transformStruct.GetPosition(); } float Transform2D::GetRotation() const { return m_transformStruct.GetEulerAngles(); } void Transform2D::SetRotationEuler(float euler) { m_transformStruct.SetRotationEuler(euler); SetMatrices(); } void Transform2D::RotateByEuler(float euler) { m_transformStruct.RotateByEuler(euler); SetMatrices(); } void Transform2D::SetScale(Vector2 s) { m_transformStruct.SetScale(s); SetMatrices(); } Vector2 Transform2D::GetScale() const { return m_transformStruct.GetScale(); } //void Transform2D::SetLocalPosition2D(Vector2 pos, float z) //{ // SetLocalPosition(Vector3(pos, z)); //} // //void Transform2D::TranslateLocal2D(Vector2 offset) //{ // TranslateLocal(Vector3(offset, 0.f)); //} // //void Transform2D::SetRotationEuler2D(float rotation) //{ // SetRotationEuler(Vector3(0.f,0.f,rotation)); //} // //void Transform2D::RotateByEuler2D(float rotationOffset) //{ // RotateByEuler(Vector3(0.f,0.f,rotationOffset)); //} // //void Transform2D::SetScale2D(Vector2 s) //{ // SetScale(Vector3(s,1.f)); //} //Vector3 Transform2D::GetForward() const //{ // return GetWorldMatrix().GetK().XYZ().GetNormalized(); //} Vector3 Transform2D::GetRight() const { return GetWorldMatrix().GetI().XYZ().XY().GetNormalized(); } Vector3 Transform2D::GetUp() const { return GetWorldMatrix().GetJ().XYZ().XY().GetNormalized(); } void Transform2D::LookAt(const Vector3 & position, const Vector3 & target, const Vector3 & up) { SetLocalMatrix(Matrix44::LookAt(position, target, up)); } void Transform2D::SetParent(Transform2D * t) { m_parent = t; t->AddChild(this); UpdateWorldMatrix(); } void Transform2D::AddChild(Transform2D * t) { m_children.push_back(t); } void Transform2D::SetMatrices() { m_localMatrix = m_transformStruct.GetMatrix(); UpdateWorldMatrix(); } void Transform2D::UpdateWorldMatrix() { m_worldMatrix = Matrix44::IDENTITY; if (m_parent != nullptr){ m_worldMatrix = m_parent->GetWorldMatrix(); } m_worldMatrix.Append(m_localMatrix); for(Transform2D* t : m_children){ t->UpdateWorldMatrix(); } }
[ "emilytrizzo@gmail.com" ]
emilytrizzo@gmail.com
5779233e6d71e62f5ec6c6af04db90d5872673b4
6b4f03decc4ae4d9bd24641e69137d9f4a98eafa
/HavokOpenGL/HavokOpenGL/HvkOGLObj.h
03d0fa19cf48ce568947c910793d3ec871f93748
[]
no_license
Desendos/PhysicsGame
fc4211ba211d15a4271728ec7d84acad2fcb682a
14082152869f1508fe8416e20ef65a4109db81b4
refs/heads/master
2020-04-06T07:03:24.373923
2014-04-28T17:21:59
2014-04-28T17:21:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
616
h
#pragma once #include <windows.h> #include <gl/gl.h> #include <gl/glu.h> #include "HavokObj.h" #include "Vector.h" /* Abstract Base Class for rendering a Havok Rigid body object in OpenGL */ class HvkOGLObj{ protected: HavokObj *hObj; float angle; //rotation angle float r, g, b; float radius; public: HvkOGLObj(HavokObj* havokObj); virtual ~HvkOGLObj(void); virtual void update(); virtual void render() = 0; //pure virtual float getAngle(){ return angle; } void setRGB(float r = 0.5f, float g = 0.5f, float b = 0.5f); //set colours. Default 0.5f for each HavokObj* getHavokObj(){ return hObj; } };
[ "rseymour8@gmail.com" ]
rseymour8@gmail.com
594b9f10443f93310b48e7ef8cb51dfc083025d5
d96ccbf8070765bc1cfdb937cf0ac058acaf23c3
/RedKid3D/RedKid3D Engine/RedKid Engine/BufferUAV.h
ea04b09dd367419dc47553531f229c892b4d2759
[]
no_license
k119-55524/Old-project
2609d67347d2f5509f0296ab78500bb0a6cb7536
8df33fb262cedb3576fffc2bb1c4a26889684a5d
refs/heads/master
2020-12-07T16:08:38.490893
2020-01-09T07:32:21
2020-01-09T07:34:27
232,747,175
0
0
null
null
null
null
UTF-8
C++
false
false
432
h
#pragma once #include "header.h" #include "LogFile.h" class CBufferUAV { public: CBufferUAV(void); ~CBufferUAV(void); void Release( void ); HRESULT Create( UINT StructureByteStride, UINT Count ); inline ID3D11Buffer* &GetBuffer( void ) { return g_pBuffer; }; inline ID3D11UnorderedAccessView* GetBufferUAV( void ) { return g_pBufferUAV; }; private: ID3D11Buffer* g_pBuffer; ID3D11UnorderedAccessView* g_pBufferUAV; };
[ "k119_55524@mail.ru" ]
k119_55524@mail.ru
b703e9601898b4c1287b00cd40c71b7578cf164b
935a397d01fba9e332f63c71d140de1a1bffe277
/fibonacci-sequence-stack.cpp
89501e03c3adf4ba16b62c99a3324128d371e699
[]
no_license
dreamzen/programming
c043b54a0a42a3fbf9cdbc804a4aa08f1dfa3dc1
a58f4449e4dfc6823ba0a2d3aa7793dec56358d2
refs/heads/master
2021-01-25T08:42:58.721002
2014-06-21T15:43:48
2014-06-21T15:43:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,446
cpp
#include <iostream> #include <stack> using namespace std; struct Element { int n;//parameter int result;//f(n)'s value int status;//1 means back from left, 2 means back from right Element(int n1, int s) : n(n1), result(0), status(s) {} }; /* when comes a 'n' if n >= 0, push it into stack when reach the end, pick one from top if e.n == 1 or 0, then give the value directly.(f(1) = 1, f(0) = 0) else if back from left, then update its value with r and update staus and push it into stack again and set num <-- num -2 to cal f(n-2) with the same method else(back from right), update its value with r and continue to pop */ class Solution { public: int FibonacciStack(int n) { stack<Element> s; int num = n; int r = 0;//save child-node's value (to plus to current f(n)) while(!s.empty() || num == n) { if(num >= 0) { Element e(num, 1);//the first time pushed into stack s.push(e); num--; } else//reach the end of tree { Element e = s.top(); s.pop(); if(e.n == 0) { e.result = 0; r = e.result; } else if(e.n == 1) { e.result = 1; r = e.result; } else { if(e.status == 1)//back from left: f(n-1) is ready --> r { e.result += r; r = e.result;//update f(n)'s value e.status = 2; s.push(e);//push f(n) num = e.n - 2;//continue to cal f(n-2) } else//back from right { e.result += r;//f(n) += f(n-2) r = e.result; num = -1;//continue to pop } } } } return r; } }; int main() { int n; Solution s; while(cin >> n) { if(n < 0) { break; } else { cout << "Fibonacci(" << n << ") = " << s.FibonacciStack(n) << endl; } } return 0; }
[ "dreamzen@163.com" ]
dreamzen@163.com
7d844e464838cad7699b4d8ef406455adac20ce6
17216697080c5afdd5549aff14f42c39c420d33a
/src/src/Share/ShareLib/LinuxPublic/ACE_wrappers/examples/Shared_Malloc/test_position_independent_malloc.cpp
572a83c663d0ce060a11762f25d2c054799c12cd
[ "MIT" ]
permissive
AI549654033/RDHelp
9c8b0cc196de98bcd81b2ccc4fc352bdc3783159
0f5f9c7d098635c7216713d7137c845c0d999226
refs/heads/master
2022-07-03T16:04:58.026641
2020-05-18T06:04:36
2020-05-18T06:04:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,193
cpp
// $Id: test_position_independent_malloc.cpp 80826 2008-03-04 14:51:23Z wotte $ // Test the capability of the "position-independent" <ACE_Malloc> to // handle a single malloc that can be rooted at different base // addresses each time it's used. The actual backing store used by // <ACE_Malloc> is located in a memory-mapped file. #include "test_position_independent_malloc.h" #include "ace/PI_Malloc.h" #include "ace/Based_Pointer_T.h" #include "ace/Get_Opt.h" #include "ace/Auto_Ptr.h" #include "ace/Process_Mutex.h" #include "ace/Malloc_T.h" #include "ace/MMAP_Memory_Pool.h" ACE_RCSID(Shared_Malloc, test_multiple_mallocs, "$Id: test_position_independent_malloc.cpp 80826 2008-03-04 14:51:23Z wotte $") #if (ACE_HAS_POSITION_INDEPENDENT_POINTERS == 1) typedef ACE_PI_Control_Block CONTROL_BLOCK; #else typedef ACE_Control_Block CONTROL_BLOCK; #endif /* ACE_HAS_POSITION_INDEPENDENT_POINTERS == 1 */ typedef ACE_Malloc_T <ACE_MMAP_MEMORY_POOL, ACE_Process_Mutex, CONTROL_BLOCK> TEST_MALLOC; // Default address for memory-mapped files. static void *base_addr = ACE_DEFAULT_BASE_ADDR; static void print (Test_Data *data) { for (Test_Data *t = data; t != 0; t = t->next_) { ACE_DEBUG ((LM_DEBUG, "<<<<\ni1_ = %d, i2_ = %d, i3_ = %d\n", t->i1_, t->i2_, t->i3_)); ACE_DEBUG ((LM_DEBUG, "*t->bpl_ = %d, t->long_test_->array_[0] = %d\n>>>>\n", *t->long_test_->bpl_, t->long_test_->array_[0])); } } static void * initialize (TEST_MALLOC *allocator) { void *ptr; ACE_ALLOCATOR_RETURN (ptr, allocator->malloc (sizeof (Test_Data)), 0); Test_Data *data1 = new (ptr) Test_Data; data1->i1_ = 111; data1->i2_ = 222; data1->i3_ = 333; void *gap = 0; ACE_ALLOCATOR_RETURN (gap, allocator->malloc (sizeof (256)), 0); allocator->free (gap); ACE_ALLOCATOR_RETURN (ptr, allocator->malloc (sizeof (Test_Data)), 0); Test_Data *data2 = new (ptr) Test_Data; data1->next_ = 0; data1->i1_ = 111; data1->i2_ = 222; data1->i3_ = 333; data2->next_ = data1; data2->i1_ = -111; data2->i2_ = -222; data2->i3_ = -333; // Test in shared memory using long (array/pointer) ACE_ALLOCATOR_RETURN (ptr, allocator->malloc (sizeof (Long_Test)), 0); Long_Test *lt = new (ptr) Long_Test; lt->array_[0] = 1000; lt->array_[1] = 1001; lt->array_[2] = 1002; lt->array_[3] = 1003; lt->array_[4] = 1004; lt->bpl_ = lt->array_; data1->long_test_= lt; ACE_ASSERT (*lt->bpl_ == 1000); ACE_ASSERT (lt->bpl_[3] == 1003); ACE_ALLOCATOR_RETURN (ptr, allocator->malloc (sizeof (Long_Test)), 0); lt = new (ptr) Long_Test; lt->array_[0] = 2000; lt->array_[1] = 2001; lt->array_[2] = 2002; lt->array_[3] = 2003; lt->array_[4] = 2004; lt->bpl_ = lt->array_; data2->long_test_= lt; ACE_ASSERT (*lt->bpl_ == 2000); ACE_ASSERT (lt->bpl_[4] == 2004); return data2; } static void parse_args (int argc, ACE_TCHAR *argv[]) { ACE_Get_Opt get_opt (argc, argv, ACE_TEXT("a:T")); for (int c; (c = get_opt ()) != -1; ) { switch (c) { case 'a': // Override the default base address. base_addr = reinterpret_cast<void *> (static_cast<intptr_t> (ACE_OS::atoi (get_opt.opt_arg ()))); break; case 'T': #if defined (ACE_HAS_TRACE) ACE_Trace::start_tracing (); #endif /* ACE_HAS_TRACE */ break; } } } int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { parse_args (argc, argv); ACE_MMAP_Memory_Pool_Options options (base_addr); // Create an allocator. TEST_MALLOC *ptr = 0; ACE_NEW_RETURN (ptr, TEST_MALLOC (ACE_TEXT("test_file"), ACE_TEXT("test_lock"), &options), 1); auto_ptr <TEST_MALLOC> allocator (ptr); void *data = 0; // This is the first time in, so we allocate the memory and bind it // to the name "foo". if (allocator->find ("foo", data) == -1) { data = initialize (allocator.get ()); if (allocator->bind ("foo", data) == -1) ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "bind"), 1); ACE_DEBUG ((LM_DEBUG, "Run again to see results and release resources.\n")); } // If we find "foo" then we're running the "second" time, so we must // release the resources. else { print ((Test_Data *) data); allocator->free (data); allocator->remove (); ACE_DEBUG ((LM_DEBUG, "all resources released\n")); } return 0; }
[ "jim_xie@trendmicro.com" ]
jim_xie@trendmicro.com
80768a624a1c8ec9c8f97f14b2aa1602b3a8307b
bad44a92fb338260f9c077689d7fa5472526c3fe
/src/nnfusion/core/operators/op_define/select.cpp
3977b4f5d7d834b5f086e03cdf27f211d842f317
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
microsoft/nnfusion
ebc4c06331b8e93dbf5e176e5ecd3382e322ff21
bd4f6feed217a43c9ee9be16f02fa8529953579a
refs/heads/main
2023-08-25T17:41:37.517769
2022-09-16T05:59:01
2022-09-16T05:59:01
252,069,995
872
157
MIT
2023-07-19T03:06:21
2020-04-01T04:15:38
C++
UTF-8
C++
false
false
2,161
cpp
//***************************************************************************** // Copyright 2017-2020 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** // Microsoft (c) 2019, NNFusion Team #include "select.hpp" #include "nnfusion/core/graph/gnode.hpp" using namespace std; using namespace nnfusion::op; Select::Select() : Op("Select") { } void Select::validate_and_infer_types(std::shared_ptr<graph::GNode> gnode) { OP_VALIDATION(this, gnode->get_input_element_type(0).is_dynamic() || gnode->get_input_element_type(0) == element::boolean) << "Argument 0 does not have boolean element type (element type: " << gnode->get_input_element_type(0) << ")."; nnfusion::PartialShape result_shape = gnode->get_input_partial_shape(0); OP_VALIDATION( this, nnfusion::PartialShape::merge_into(result_shape, gnode->get_input_partial_shape(1))) << "Argument shapes are inconsistent."; OP_VALIDATION( this, nnfusion::PartialShape::merge_into(result_shape, gnode->get_input_partial_shape(2))) << "Argument shapes are inconsistent."; nnfusion::element::Type result_et; OP_VALIDATION(this, nnfusion::element::Type::merge(result_et, gnode->get_input_element_type(1), gnode->get_input_element_type(2))) << "Argument 1 and 2 element types are inconsistent."; gnode->set_output_type_and_shape(0, result_et, result_shape); }
[ "Wenxiang.Hu@microsoft.com" ]
Wenxiang.Hu@microsoft.com
95ebdc8c594232bcbd68f374935f920060adb29c
1810e89df8f69865362e35994c5cd970eb4b76e5
/BpTree.h
58bd673acb682f1ba3b5f2bbd69b5b9b88b049dc
[]
no_license
knishibe/bptree
282ba9514240d90dda97c5362f65977b1ac1e0d3
6150c0a6d856ad00af390879d796619510dda5fa
refs/heads/master
2022-01-04T14:59:16.360765
2020-02-26T21:51:15
2020-02-26T21:51:15
242,602,728
0
0
null
null
null
null
UTF-8
C++
false
false
543
h
#ifndef BPTREE_H #define BPTREE_H #include <iostream> #include "Node.h" using namespace std; class BpTree { private: Node* root; int height; public: // constructors BpTree(unsigned nodeSize); BpTree(BpTree* tree); // destructor ~BpTree(); // overloaded operators BpTree & operator=(BpTree &tree); // main functions bool insert(int key, string value); bool remove(int key); void printKeys(); void printValues(); string find(int key); // getters int getHeight(); Node* getRoot(); }; #endif
[ "32073936+knishibe@users.noreply.github.com" ]
32073936+knishibe@users.noreply.github.com
d60def3d14149491d6efe1940cbe8b175be6c708
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function14024/function14024_schedule_33/function14024_schedule_33_wrapper.cpp
3662e3150002dd4984498bc224f72a4b3bcb39e9
[]
no_license
IsraMekki/tiramisu_code_generator
8b3f1d63cff62ba9f5242c019058d5a3119184a3
5a259d8e244af452e5301126683fa4320c2047a3
refs/heads/master
2020-04-29T17:27:57.987172
2019-04-23T16:50:32
2019-04-23T16:50:32
176,297,755
1
2
null
null
null
null
UTF-8
C++
false
false
1,558
cpp
#include "Halide.h" #include "function14024_schedule_33_wrapper.h" #include "tiramisu/utils.h" #include <cstdlib> #include <iostream> #include <time.h> #include <fstream> #include <chrono> #define MAX_RAND 200 int main(int, char **){ Halide::Buffer<int32_t> buf00(64, 64); Halide::Buffer<int32_t> buf01(64, 128, 64); Halide::Buffer<int32_t> buf02(64, 64); Halide::Buffer<int32_t> buf03(64); Halide::Buffer<int32_t> buf04(64, 64); Halide::Buffer<int32_t> buf05(64, 128); Halide::Buffer<int32_t> buf06(128, 64, 64); Halide::Buffer<int32_t> buf07(128); Halide::Buffer<int32_t> buf08(64, 128, 64); Halide::Buffer<int32_t> buf09(64, 64); Halide::Buffer<int32_t> buf0(64, 128, 64, 64); init_buffer(buf0, (int32_t)0); auto t1 = std::chrono::high_resolution_clock::now(); function14024_schedule_33(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf04.raw_buffer(), buf05.raw_buffer(), buf06.raw_buffer(), buf07.raw_buffer(), buf08.raw_buffer(), buf09.raw_buffer(), buf0.raw_buffer()); auto t2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> diff = t2 - t1; std::ofstream exec_times_file; exec_times_file.open("../data/programs/function14024/function14024_schedule_33/exec_times.txt", std::ios_base::app); if (exec_times_file.is_open()){ exec_times_file << diff.count() * 1000000 << "us" <<std::endl; exec_times_file.close(); } return 0; }
[ "ei_mekki@esi.dz" ]
ei_mekki@esi.dz
f6b4bf983a1055af3e7e0c792138336af6271fea
63266a4b1f531bea61dabfcb75618f002f9b86ce
/lib/Dialect/SV/Dialect.cpp
95765a85b88fcba469774c1d24e3f3c3345749e0
[ "LLVM-exception", "Apache-2.0" ]
permissive
shibizhao/circt
5fa019ad10da67a42a1b1845492cfb57c4bec459
74b446f60b1c22d27516de4481b6915823a3c56e
refs/heads/master
2022-12-05T15:12:46.401350
2020-08-27T19:49:47
2020-08-27T19:49:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
707
cpp
//===- Dialect.cpp - Implement the SV dialect -----------------------------===// // //===----------------------------------------------------------------------===// #include "circt/Dialect/SV/Dialect.h" #include "circt/Dialect/SV/Ops.h" using namespace circt; using namespace sv; //===----------------------------------------------------------------------===// // Dialect specification. //===----------------------------------------------------------------------===// SVDialect::SVDialect(MLIRContext *context) : Dialect(getDialectNamespace(), context) { // Register operations. addOperations< #define GET_OP_LIST #include "circt/Dialect/SV/SV.cpp.inc" >(); } SVDialect::~SVDialect() {}
[ "clattner@nondot.org" ]
clattner@nondot.org
f2933693dc896d660f2d0ab6b13d033d6960b63d
c747cfbe51cc24d15e49a888072d34635833d90a
/846_HandOfStraights.cpp
3cf7b8a8942d28e780cdc9470a100ebe97199f84
[]
no_license
bigship/leetcode_solutions
18921508a8acba25013ae65864168c4c084bef37
45edfab5f1696fa9b3b59b63663aa9524de209cd
refs/heads/master
2022-08-22T05:42:37.462263
2022-08-02T20:14:50
2022-08-02T20:14:50
13,472,667
0
0
null
null
null
null
UTF-8
C++
false
false
1,803
cpp
// 846. Hand of Straights /* * Alice has a hand of cards, given as an array of integers. Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards. Return true if and only if she can. Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/ Example 1: Input: hand = [1,2,3,6,2,3,4,7,8], W = 3 Output: true Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8] Example 2: Input: hand = [1,2,3,4,5], W = 4 Output: false Explanation: Alice's hand can't be rearranged into groups of 4. Constraints: 1 <= hand.length <= 10000 0 <= hand[i] <= 10^9 1 <= W <= hand.length */ // 把牌分成W份, 每份W张牌 class Solution { public: bool isNStraightHand(vector<int>& hand, int W) { const int len = hand.size(); // W不能被牌的总数整除, 一定不满足条件 if (len % W != 0) return false; // 统计牌出现的次数, 使用平衡二叉树 std::map<int, int> cntmap; for (auto& card : hand) { cntmap[card]++; } // 从最小的牌开始算. 看是否能凑出W张牌, 每张牌顺序加1 // 如果这个过程无法满足, 表示无法凑出返回false // 每次使用过的牌把它出现的次数减去1, 如果次数为0就从cntmap中删除这张牌 // 表示这张牌不会再被使用到了 while (!cntmap.empty()) { auto it = cntmap.begin(); int start = it->first; for (int i = 0; i < W; i++) { if (cntmap.find(start + i) == cntmap.end()) return false; else { cntmap[start + i]--; if (cntmap[start + i] == 0) { cntmap.erase(start + i); } } } } return true; } };
[ "colinchen1984@gmail.com" ]
colinchen1984@gmail.com
60ff709593a848f6a87fafeb717eace00e60a048
d92304badb95993099633c5989f6cd8af57f9b1f
/Codeforces/591-CBF.cpp
bddcd086d3e498e5dc5d34fae9d78677aaf11f82
[]
no_license
tajirhas9/Problem-Solving-and-Programming-Practice
c5e2b77c7ac69982a53d5320cebe874a7adec750
00c298233a9cde21a1cdca1f4a2b6146d0107e73
refs/heads/master
2020-09-25T22:52:00.716014
2019-12-05T13:04:40
2019-12-05T13:04:40
226,103,342
0
0
null
null
null
null
UTF-8
C++
false
false
1,905
cpp
#include <bits/stdc++.h> using namespace std; #define MAX 1000000007 #define rep(i,a,b) for(i=a;i<=b;i++) #define repR(i,a,b) for(i=a;i>=b;i--) #define mp(x,y) make_pair(x,y) #define pb(x) push_back(x) #define RESET(a,b) memset(a,b,sizeof(a)) #define lcm(a,b) (a*(b/gcd(a,b))) #define gcd(a,b) __gcd)(a,b) typedef long long ll; typedef string string; typedef pair<ll,ll> pii; typedef vector<ll> vl; typedef vector<string> vs; typedef set<ll> setl; typedef set<string> sets; typedef set<ll>::iterator setl_it; typedef set<string>::iterator sets_it; typedef vector<ll>::iterator vl_it; typedef vector<string>::iterator vs_it; inline bool isLeapYear(ll y) { return ((y%400==0) || (y%4==0 && y%100!=0)); } inline void optimize(void) { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); } inline bool isInside(pii p,ll n,ll m) { return (p.first>=0&&p.first<n&&p.second>=0&&p.second<m); }; inline bool isInside(pii p,ll n) { return (p.first>=0&&p.first<n&&p.second>=0&&p.second<n); }; const ll mod = 1e9+7; const double pi = acos(-1.0); struct func { //this is a sample overloading function for sorting stl bool operator()(pii const &a, pii const &b) { if(a.first==b.first) return (a.second<b.second); return (a.first>b.first); } }; ll fx[] = {1,1,-1,-1}; ll fy[] = {1,-1,1,-1}; char cur[512345],p[512345]; int main() { optimize(); ll i,j,k,n,step=0; cin >> n; rep(i,0,n-1) { cin >> k; cur[i] = k+'0'; p[i] = '2'; } cur[n] = p[n] = '\0'; p[0] = cur[0]; p[n-1] = cur[n-1]; //cout << cur << " " << p << endl; while(p != cur) { i=0; strcpy(p,cur); rep(i,1,n-2) { ll z=0,o=0; rep(j,i-1,i+1) (p[j]=='0') ? z++ : o++; (z>o) ? cur[i] = '0' : cur[i] = '1'; } //cout << p << endl; //cout << cur << endl; if(!strcmp(cur,p)) break; step++; //cout << step << endl; } cout << step << endl; rep(i,0,n-1) cout << cur[i] << " "; return 0; } //?
[ "tajircuet@gmail.com" ]
tajircuet@gmail.com
42520ffccf8523dfbc7e49c7a7fc503147c373e7
ad4a3300a1720a0c4ad7b97e2b8cbaf670b69146
/spoj/LITE.cpp
8d6147f68164a8a8382a3a863f8346c914300d83
[]
no_license
arpituppal/competitive-programming-codes
4cf98279ffefb437b40fd412f4cbda3f519d4f3a
ca543259e6e8fd8b1b963ca5a54fccea4083860c
refs/heads/master
2022-12-08T11:23:21.927150
2020-08-29T21:20:19
2020-08-29T21:20:19
104,647,687
0
0
null
null
null
null
UTF-8
C++
false
false
2,893
cpp
/*Range update in segment tree Lazy propogation */ #include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <queue> #include <algorithm> #include <vector> #include <cstring> #include <stack> #include <cctype> #include <utility> #include <map> #include <string> #include <climits> #include <set> #include <sstream> #include <utility> #include <ctime> #include <cassert> #include <fstream> using namespace std; typedef long long LL; #define MS(A) memset(A, 0, sizeof(A)) #define MSV(A,a) memset(A, a, sizeof(A)) #define MAX(a,b) ((a >= b) ? (a) : (b)) #define MIN(a,b) ((a >= b) ? (b) : (a)) #define ABS(a) (((a) > 0) ? (a) : (-a)) #define MP make_pair #define PB push_back #define getcx getchar_unlocked #define INF (int(1e9)) #define INFL (LL(1e18)) #define EPS 1e-12 #define chkbit(s, b) (s & (1<<b)) #define setbit(s, b) (s |= (1<<b)) #define clrbit(s, b) (s &= ~(1<<b)) inline void inp( int &n ) { n=0; int ch=getcx();int sign=1; while( ch < '0' || ch > '9' ){if(ch=='-')sign=-1; ch=getcx();} while( ch >= '0' && ch <= '9' ) n = (n<<3)+(n<<1) + ch-'0', ch=getcx(); n=n*sign; } inline void inp1( LL &n ) { n=0; LL ch=getcx();LL sign=1; while( ch < '0' || ch > '9' ){if(ch=='-')sign=-1; ch=getcx();} while( ch >= '0' && ch <= '9' ) n = (n<<3)+(n<<1) + ch-'0', ch=getcx(); n=n*sign; } int seg[400005],flag[400005],arr[100005]; void build(int node,int st,int end) { if(st==end) { seg[node]=0; flag[node]=0; //false return ; } int mid=(st+end)>>1; build(2*node,st,mid); build(1*node+1,mid+1,end); seg[node]=0; //initially all switches are off flag[node]=0; } void flag_resolve(int node,int st,int end) { if(flag[node]==1) //pending update { flag[node]=0; //update done seg[node]=(end-st+1)-seg[node]; //on switches become off , off become on now push this in children if(st!=end) { flag[2*node]=!flag[2*node]; flag[2*node+1]=!flag[2*node+1]; } } } void update(int node,int st,int end,int i,int j) { if(i>end || j<st || st>end) { flag_resolve(node,st,end); return ; } if(i<=st && j>=end) { flag[node]=!flag[node]; flag_resolve(node,st,end); return ; } flag_resolve(node,st,end); int mid=(st+end)>>1; update(2*node,st,mid,i,j); update(2*node+1,mid+1,end,i,j); if(st!=end) seg[node]=seg[2*node]+seg[2*node+1]; } int query(int node,int st,int end,int i,int j) { if(st>end || i>end || j<st) return 0; flag_resolve(node,st,end); // resolve the flag coz this node will be answer or this plus some child value will contain if(i<=st && j>=end) return seg[node]; int mid=(st+end)>>1; return (query(2*node,st,mid,i,j) + query(2*node+1,mid+1,end,i,j)); } int main() { int n,m,i,j,k,l,r; inp(n); inp(m); build(1,0,n-1); while(m--) { inp(k); inp(l); inp(r); l--; r--; if(k==0) update(1,0,n-1,l,r); else printf("%d\n",query(1,0,n-1,l,r)); } return 0; }
[ "arpit.uppal@walmart.com" ]
arpit.uppal@walmart.com
3a7282e423b3b57292a569a99cff2cc3967ff803
a49e51fec5ca20ebcf66d717b0af82ea326d1d4c
/src/barrier.cpp
94b0646f9493c735a89a46d3a68192164eefb97b
[]
no_license
PetarMihalj/cppc_lib
81de7699f131e098422685c0fae0564ef8517cdf
992903c3d24eb9f84686837bb212f5fd8d73c728
refs/heads/master
2023-07-20T07:42:39.919704
2021-09-04T10:39:24
2021-09-04T10:39:24
399,514,409
2
0
null
null
null
null
UTF-8
C++
false
false
1,244
cpp
#include "cppc.h" #include "rule_traits.h" #include <iostream> #include <memory> #include <vector> static_assert(rule_traits::is_no_copy_move<cppc::barrier>::value); cppc::barrier::barrier(const std::size_t reset_point) : _reset_point{reset_point}, _current_cnt{reset_point}, _ind{std::make_shared<bool>(false)} {}; void cppc::barrier::decrement() { _mm.lock(); _current_cnt--; if (_current_cnt == 0) { *_ind = true; _ind = std::shared_ptr<bool>(); _current_cnt = _reset_point; _cv.notify_all(); } _mm.unlock(); } void cppc::barrier::wait() { _mm.lock(); auto my_ind = _ind; while (true) { _cv.wait(_mm); if (*my_ind) { _mm.unlock(); break; } } } void cppc::barrier::decrement_and_wait() { _mm.lock(); _current_cnt--; if (_current_cnt == 0) { *_ind = true; _ind = std::make_shared<bool>(false); _current_cnt = _reset_point; _cv.notify_all(); _mm.unlock(); } else { auto my_ind = _ind; while (true) { _cv.wait(_mm); if (*my_ind) { _mm.unlock(); break; } } } }
[ "git@pmihalj.com" ]
git@pmihalj.com
1c771f48ec2a460d440f48023cabbd3a406254c8
7ec75f987f54d30276b915d9abcaab3b82f7bdb3
/src/Locators/GameLogicLocator.cpp
7dd4aa1847bfd60e42f8eeb5766fb5cfafc5e470
[]
no_license
RyanSwann1/Snake---Uni-Work
a3f20b33cb435f32590e33234fb8402df7603a90
a7be655cc8b0339d38ac32566cc9f8a98995669f
refs/heads/master
2020-03-07T15:44:53.088229
2018-04-26T08:56:07
2018-04-26T08:56:07
127,563,624
0
0
null
null
null
null
UTF-8
C++
false
false
90
cpp
#include <Locators\GameLogicLocator.h> GameLogic* GameLogicLocator::m_gameLogic = nullptr;
[ "RyanSwann1992@gmail.com" ]
RyanSwann1992@gmail.com
50a1917e29dad9f9785c47e88cb412e87a89ff9e
487fd495fec491acb04453255c870808d037f889
/src/qt/gsa/mninfodialog.cpp
4b9a63b2a5d6bff2747ac2c4b19a364c7bd2da1a
[ "MIT" ]
permissive
TechDude2u/GSAcoin
58b94eba767f6e17c8a88bcf0ee3b4cea719657a
c0a64da39501a52f25e709368a869d743f77221d
refs/heads/main
2023-08-08T04:03:42.198250
2021-09-21T16:27:42
2021-09-21T16:27:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,822
cpp
// Copyright (c) 2019-2020 The PIVX developers // Copyright (c) 2021 The GLOBALSMARTASSET Core Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "qt/gsa/mninfodialog.h" #include "qt/gsa/forms/ui_mninfodialog.h" #include "walletmodel.h" #include "wallet/wallet.h" #include "guiutil.h" #include "qt/gsa/qtutils.h" #include <QDateTime> MnInfoDialog::MnInfoDialog(QWidget *parent) : FocusedDialog(parent), ui(new Ui::MnInfoDialog) { ui->setupUi(this); this->setStyleSheet(parent->styleSheet()); setCssProperty(ui->frame, "container-dialog"); setCssProperty(ui->labelTitle, "text-title-dialog"); setCssTextBodyDialog({ui->labelAmount, ui->labelSend, ui->labelInputs, ui->labelFee, ui->labelId}); setCssProperty({ui->labelDivider1, ui->labelDivider4, ui->labelDivider6, ui->labelDivider7, ui->labelDivider8, ui->labelDivider9}, "container-divider"); setCssTextBodyDialog({ui->textAmount, ui->textAddress, ui->textInputs, ui->textStatus, ui->textId, ui->textExport}); setCssProperty({ui->pushCopy, ui->pushCopyId, ui->pushExport}, "ic-copy-big"); setCssProperty(ui->btnEsc, "ic-close"); connect(ui->btnEsc, &QPushButton::clicked, this, &MnInfoDialog::close); connect(ui->pushCopy, &QPushButton::clicked, [this](){ copyInform(pubKey, tr("Masternode public key copied")); }); connect(ui->pushCopyId, &QPushButton::clicked, [this](){ copyInform(txId, tr("Collateral tx id copied")); }); connect(ui->pushExport, &QPushButton::clicked, [this](){ exportMN = true; accept(); }); } void MnInfoDialog::setData(QString pubKey, QString name, QString address, QString txId, QString outputIndex, QString status) { this->pubKey = pubKey; this->txId = txId; QString shortPubKey = pubKey; QString shortTxId = txId; if (shortPubKey.length() > 20) { shortPubKey = shortPubKey.left(13) + "..." + shortPubKey.right(13); } if (shortTxId.length() > 20) { shortTxId = shortTxId.left(12) + "..." + shortTxId.right(12); } ui->textId->setText(shortPubKey); ui->textAddress->setText(address); ui->textAmount->setText(shortTxId); ui->textInputs->setText(outputIndex); ui->textStatus->setText(status); } void MnInfoDialog::copyInform(QString& copyStr, QString message) { GUIUtil::setClipboard(copyStr); if (!snackBar) snackBar = new SnackBar(nullptr, this); snackBar->setText(tr(message.toStdString().c_str())); snackBar->resize(this->width(), snackBar->height()); openDialog(snackBar, this); } void MnInfoDialog::reject() { if (snackBar && snackBar->isVisible()) snackBar->hide(); QDialog::reject(); } MnInfoDialog::~MnInfoDialog() { if (snackBar) delete snackBar; delete ui; }
[ "gsasset24@gmail.com" ]
gsasset24@gmail.com
75643db7e6502ac9548f75822c9a1e2fbd9ded9a
10821e85ce5ab62b2000e2cc893dc6ebc946c35a
/plugins/robots/generators/ev3/ev3GeneratorBase/src/simpleGenerators/lineLeader/calibratePIDGenerator.cpp
0131c16af95bf73c29e08dcabfa2edd56d06a624
[ "BSD-3-Clause", "MIT", "CC-BY-4.0", "GPL-3.0-only", "GPL-1.0-or-later", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
trikset/trik-studio
aa65b6cee085ca34c875ac488f7ec45ff47efbfd
2913f54d43e32f82c86e21dc9d0b22dbd1388086
refs/heads/master
2023-08-18T05:09:14.748955
2023-07-20T19:26:38
2023-07-20T19:26:38
143,976,458
21
22
Apache-2.0
2023-09-12T09:39:43
2018-08-08T07:24:14
C++
UTF-8
C++
false
false
2,052
cpp
/* Copyright 2017 CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "calibratePIDGenerator.h" #include <generatorBase/generatorCustomizer.h> #include "ev3GeneratorBase/ev3GeneratorFactory.h" using namespace ev3::simple::lineLeader; using namespace generatorBase::simple; using namespace qReal; CalibratePIDGenerator::CalibratePIDGenerator(const qrRepo::RepoApi &repo , generatorBase::GeneratorCustomizer &customizer , const Id &id , QObject *parent) : BindingGenerator(repo, customizer, id, "sensors/lineLeader/calibratePID.t", QList<Binding *>() << Binding::createConverting("@@PORT@@", "Port" , static_cast<Ev3GeneratorFactory *>(customizer.factory())->portNameConverter()) << Binding::createConverting("@@SET_POINT@@", "SetPoint" , customizer.factory()->intPropertyConverter(id, "SetPoint")) << Binding::createConverting("@@P@@", "P" , customizer.factory()->intPropertyConverter(id, "P")) << Binding::createConverting("@@K@@", "I" , customizer.factory()->intPropertyConverter(id, "I")) << Binding::createConverting("@@D@@", "D" , customizer.factory()->intPropertyConverter(id, "D")) << Binding::createConverting("@@KPF@@", "PFactor" , customizer.factory()->intPropertyConverter(id, "PFactor")) << Binding::createConverting("@@KIF@@", "IFactor" , customizer.factory()->intPropertyConverter(id, "IFactor")) << Binding::createConverting("@@KDF@@", "DFactor" , customizer.factory()->intPropertyConverter(id, "DFactor")) , parent) { }
[ "lahmatbiy@gmail.com" ]
lahmatbiy@gmail.com
d87f387cf448c836d98bfe1b96546947eeb56d4f
3d4f601fee634723f25f739f755bd0aca2b3a489
/plugins/UFEM/src/UFEM/SSTKOmega.hpp
b57e7af936974f73b923c81c9e77a73bcd6e958f
[]
no_license
barche/coolfluid3
69d8701a840377e83bb46b158300da6d4d8f3bc5
688173daa1a7cf32929b43fc1a0d9c0655e20660
refs/heads/master
2021-07-16T18:09:42.818240
2020-08-06T11:55:11
2020-08-06T11:55:11
2,173,454
2
7
null
2020-09-20T20:57:29
2011-08-08T13:37:11
C++
UTF-8
C++
false
false
2,287
hpp
//#ifndef SSTKOmega_H //#define SSTKOmega_H //#endif // SSTKOmega_H // Copyright (C) 2010-2011 von Karman Institute for Fluid Dynamics, Belgium // // This software is distributed under the terms of the // GNU Lesser General Public License version 3 (LGPLv3). // See doc/lgpl.txt and doc/gpl.txt for the license text. #ifndef cf3_UFEM_SSTKOmega_hpp #define cf3_UFEM_SSTKOmega_hpp #include "common/CF.hpp" #include "mesh/LagrangeP1/ElementTypes.hpp" #include "solver/Action.hpp" #include "solver/actions/Proto/ProtoAction.hpp" #include "LibUFEM.hpp" #include "SUPG.hpp" #include "LSSActionUnsteady.hpp" #include "CrossWindDiffusion.hpp" namespace cf3 { namespace UFEM { /// solver for SSTKOmega turbulence model class UFEM_API SSTKOmega : public solver::Action { public: // functions /// Contructor /// @param name of the component SSTKOmega ( const std::string& name ); /// Get the class name static std::string type_name () { return "SSTKOmega"; } virtual void execute(); virtual ~SSTKOmega(); protected: virtual void do_set_expressions(LSSActionUnsteady& lss_action, solver::actions::Proto::ProtoAction& update_nut, solver::actions::Proto::ProtoAction& compute_vorticity, FieldVariable<2, VectorField>& u); void trigger_set_expression(); virtual void on_regions_set(); boost::mpl::vector5< mesh::LagrangeP1::Quad2D, mesh::LagrangeP1::Triag2D, mesh::LagrangeP1::Hexa3D, mesh::LagrangeP1::Tetra3D, mesh::LagrangeP1::Prism3D > allowed_elements; FieldVariable<0, ScalarField> k; FieldVariable<1, ScalarField> omega; FieldVariable<3, ScalarField> nu_eff; FieldVariable<4, ScalarField> d; FieldVariable<5, ScalarField> vorticity; // Magnitude of the vorticity Real m_nu_lam = 0; // SUPG helpers ComputeTau compute_tau; Real tau_su; // Parameter for the theta scheme Real m_theta = 0.5; // Physics constants Real m_rho = 1.2; // K-Omega model constants Real m_beta_s = 0.09; Real m_sigma_k1 = 0.85; Real m_sigma_k2 = 1.; Real m_sigma_omega1 = 0.5; Real m_sigma_omega2 = 0.856; Real m_beta_1 = 0.075; Real m_beta_2 = 0.0828; Real m_gamma_1; Real m_gamma_2; Real m_kappa; Real m_a1 = 0.31; CrosswindDiffusion cw; }; } // UFEM } // cf3 #endif // cf3_UFEM_NavierStokes_hpp
[ "bart@bartjanssens.org" ]
bart@bartjanssens.org
ec6fb8d8df8b618813973b921262379d8d768752
775acebaa6559bb12365c930330a62365afb0d98
/source/public/interfaces/architecture/IHTTPServerInfo.h
0d491528319bff17b27811d6f4d4a9f58e0fce7e
[]
no_license
Al-ain-Developers/indesing_plugin
3d22c32d3d547fa3a4b1fc469498de57643e9ee3
36a09796b390e28afea25456b5d61597b20de850
refs/heads/main
2023-08-14T13:34:47.867890
2021-10-05T07:57:35
2021-10-05T07:57:35
339,970,603
1
1
null
2021-10-05T07:57:36
2021-02-18T07:33:40
C++
UTF-8
C++
false
false
2,118
h
//======================================================================================== // // $File: //depot/devtech/16.0.x/plugin/source/public/interfaces/architecture/IHTTPServerInfo.h $ // // Owner: Arvinder Singh // // $Author: pmbuilder $ // // $DateTime: 2020/11/06 13:08:29 $ // // $Revision: #2 $ // // $Change: 1088580 $ // // ADOBE CONFIDENTIAL // // Copyright 2016 Adobe // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file in // accordance with the terms of the Adobe license agreement accompanying // it. If you have received this file from a source other than Adobe, // then your use, modification, or distribution of it requires the prior // written permission of Adobe. // //======================================================================================== #pragma once #ifndef __IHTTPServerInfo__ #define __IHTTPServerInfo__ #include "IPMUnknown.h" #include "LinksID.h" #include "URI.h" /* AdobePatentID="P7137-US" AdobePatentID="P7225-US" AdobePatentID="P7609-US" */ /** This interface contains URI related function for the connection. */ class IHTTPServerInfo : public IPMUnknown { public: enum { kDefaultIID = IID_IHTTPSERVERINFO }; /** Initializion function @param inAssetUri [IN] uri of the asset. @return kTrue if initialization is successful else kFalse */ virtual bool16 Init(const URI& inAssetUri) = 0; /** Fetches the full server URI @return server URI */ virtual URI GetServerURI() const = 0; /** Fetches the authority of server URI @return server URI authority */ virtual WideString GetAuthority() const = 0; /** Fetches the protocol/scheme of server URI @return server URI scheme/protocol */ virtual WideString GetProtocol() const = 0; /* Fetches the complete asset URI for the given relative path of the asset @param inRelativeAssetPath [IN] asset path to get the complete uri. @return complete uri from the asset relative path. */ virtual URI GetCompleteAssetURI(const WideString& inRelativeAssetPath) const = 0; }; #endif // __IHTTPServerInfo__
[ "75730278+Tarekhesham10@users.noreply.github.com" ]
75730278+Tarekhesham10@users.noreply.github.com
935b4d5f8368809e3a7516a8a916dc38ba686242
0014fb5ce4aa3a6f460128bb646a3c3cfe81eb9e
/testdata/9/18/src/node7.cpp
008c1623d51b66388eea93e9c5e318e2425fd1b2
[]
no_license
yps158/randomGraph
c1fa9c531b11bb935d112d1c9e510b5c02921df2
68f9e2e5b0bed1f04095642ee6924a68c0768f0c
refs/heads/master
2021-09-05T05:32:45.210171
2018-01-24T11:23:06
2018-01-24T11:23:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,587
cpp
#include "ros/ros.h" #include "std_msgs/String.h" #include "unistd.h" #include <sstream> #include <random> std::random_device rd; std::mt19937 gen(rd()); std::normal_distribution<> d(0.022465, 0.005); class Node7{ public: Node7(){ sub_3_7_flag = 0; sub_3_7 = n.subscribe("topic_3_7", 1, &Node7::middlemanCallback3,this); sub_6_7_flag = 0; sub_6_7 = n.subscribe("topic_6_7", 1, &Node7::middlemanCallback6,this); pub_7_8 = n.advertise<std_msgs::String>("topic_7_8", 1); } void middlemanCallback3(const std_msgs::String::ConstPtr& msg){ if(sub_6_7_flag == 1 && true){ usleep(d(gen)*1000000); ROS_INFO("I'm node7 last from node3, intercepted: [%s]", msg->data.c_str()); pub_7_8.publish(msg); sub_6_7_flag = 0; } else{ ROS_INFO("I'm node7, from node3 intercepted: [%s]", msg->data.c_str()); sub_3_7_flag = 1; } } void middlemanCallback6(const std_msgs::String::ConstPtr& msg){ if(sub_3_7_flag == 1 && true){ usleep(d(gen)*1000000); ROS_INFO("I'm node7 last from node6, intercepted: [%s]", msg->data.c_str()); pub_7_8.publish(msg); sub_3_7_flag = 0; } else{ ROS_INFO("I'm node7, from node6 intercepted: [%s]", msg->data.c_str()); sub_6_7_flag = 1; } } private: ros::NodeHandle n; ros::Publisher pub_7_8; int sub_3_7_flag; ros::Subscriber sub_3_7; int sub_6_7_flag; ros::Subscriber sub_6_7; }; int main(int argc, char **argv){ ros::init(argc, argv, "node7"); Node7 node7; ros::spin(); return 0; }
[ "sasaki@thinkingreed.co.jp" ]
sasaki@thinkingreed.co.jp
52ee105a67e5177765b1e6fb773b43fb53f45273
65d7747f70c8a0d31e5e1ba6b0a41479014e19b1
/gams/docs/bigdocs/gams2002/medium.inc
34718ac650c299a5124bcc63b7400fda5e82912e
[]
no_license
afbwilliam/Dutties
8e2995f2376525253d35aad11df19b5177ebd446
76aa48a4de4c0f3fcf040ffb04c343a403ee2c5a
refs/heads/master
2020-03-20T02:40:30.341067
2013-08-30T09:00:44
2013-08-30T09:00:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
8
inc
*medium
[ "antwort7@gmail.com" ]
antwort7@gmail.com
55ef82de85faf6287a6ed59096f17a1c3138f636
9dd383f0a7770ab158ca2a91d7f75ac2aa4d4582
/Rcpp/test.cpp
ce53c0d388bde960bf0b4ba62141a57b9d937e69
[]
no_license
alenabelium/OJS-analysis
c69a6b162d64855dc8db2dca609abbfb63d63304
e405e034c6f7a68297a97a9b0cd8347b1a090592
refs/heads/main
2023-04-15T16:57:11.218098
2021-04-21T09:52:19
2021-04-21T09:52:19
360,113,791
0
0
null
null
null
null
UTF-8
C++
false
false
744
cpp
#include <Rcpp.h> #include <stdio.h> using namespace Rcpp; // This is a simple example of exporting a C++ function to R. You can // source this function into an R session using the Rcpp::sourceCpp // function (or via the Source button on the editor toolbar). Learn // more about Rcpp at: // // http://www.rcpp.org/ // http://adv-r.had.co.nz/Rcpp.html // http://gallery.rcpp.org/ // // [[Rcpp::export]] SEXP timesTwo(SEXP x) { printf("%p\n", x); return x; } // You can include R code blocks in C++ files processed with sourceCpp // (useful for testing and development). The R code will be automatically // run after the compilation. // /*** R v <- c(1L,2L,3L) .Internal(inspect(v)) res <- timesTwo(v) .Internal(inspect(res)) */
[ "alen@abelium.eu" ]
alen@abelium.eu
b29ec14b053f58329352505c084459e2b1dae1a5
2dffb470380197df72be0edad83c881914681dff
/wrappers/writing_client.cpp
ca699275af260ce86656af239b55819c4de50c78
[]
no_license
fenix31415/Serv
45cc5502b33cea716c259d95e9e577146a3ef43f
3e6981d518b10dec92d822f5e508f3722408ecb6
refs/heads/master
2020-12-01T07:55:46.060804
2020-01-14T00:30:12
2020-01-14T00:30:12
230,587,105
0
0
null
null
null
null
UTF-8
C++
false
false
1,544
cpp
#include "writing_client.h" #include <cstring> #include <unistd.h> writing_client::writing_client(int fd) : file_descriptor(fd), st_buffer(BUFSIZ) { } ssize_t writing_client::read_from_client(size_t count) { ssize_t ret = read_tobuf(count); markWokedUp(); return ret; } char writing_client::at(size_t i) { return st_buffer.buffer[i]; } void writing_client::shl(size_t val) { return st_buffer.shl(val); } ssize_t writing_client::read_c(void *src, size_t len) { return read(fd_val, src, len); } writing_client::~writing_client() {} writing_client::storing_buffer::~storing_buffer() { delete[] buffer; } void writing_client::storing_buffer::shl(size_t val) { filled -= val; std::memmove(buffer, buffer + val, filled); } size_t writing_client::get_filled() { return st_buffer.filled; } bool writing_client::isAlive() { return alive; } void writing_client::markSleeping() { alive = false; } void writing_client::markWokedUp() { alive = true; } ssize_t writing_client::read_tobuf(size_t count) { ssize_t r = read_c((void *) (st_buffer.buffer + get_filled()), count); utils::ensure(r, utils::is_not_negative, r != 0 ? std::to_string(r) + " bytes read and put in buffer" : ""); st_buffer.filled += r; return r; } writing_client::writing_client(writing_client &&arg) noexcept : file_descriptor(arg.fd_val), st_buffer(BUFSIZ) { arg.fd_val = -1; } ssize_t writing_client::write_c(const void *src, size_t len) { return write(fd_val, src, len); }
[ "dimkakirov43@mail.ru" ]
dimkakirov43@mail.ru