blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f9ddc397d06a42e9edcb726243966dc31239ae7c | ce497b404b38bdf2e2708fdfb870edcdef81866b | /cpp/sdl/multipleInput.cpp | 8a3024609bcb12d56392ba655135c9f286b07904 | [] | no_license | rjrivera/code-dojo | 00e8c9ef5e2d3b1912c74c3afa0de66624eaa0e7 | 083bf5a4a41e9055dd78bc9be0a2d3b6f29651c3 | refs/heads/master | 2020-04-06T05:42:06.276739 | 2020-03-08T20:57:30 | 2020-03-08T20:57:30 | 28,792,381 | 0 | 3 | null | 2017-02-01T07:17:18 | 2015-01-05T01:35:42 | C++ | UTF-8 | C++ | false | false | 4,998 | cpp | #include<stdlib.h>
#include<SDL2/SDL.h>
#include<string>
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
//Key press surfaces constants
//
enum KeyPressSurfaces
{
KEY_PRESS_SURFACE_DEFAULT,
KEY_PRESS_SURFACE_UP,
KEY_PRESS_SURFACE_DOWN,
KEY_PRESS_SURFACE_LEFT,
KEY_PRESS_SURFACE_RIGHT,
KEY_PRESS_SURFACE_TOTAL
};
bool init();
bool loadMedia();
void close();
SDL_Surface* loadSurface(std::string path);
SDL_Window* gWindow = NULL;
SDL_Surface* gScreenSurface = NULL;
SDL_Surface* gKeyPressSurfaces[ KEY_PRESS_SURFACE_TOTAL];
SDL_Surface* gCurrentSurface = NULL;
SDL_Surface* loadSurface(std::string path)
{
//load image at specified path
SDL_Surface* loadedSurface = SDL_LoadBMP(path.c_str());
if(loadedSurface == NULL)
{
printf( "Unable to load image %s! SDL Error: %s\n", path.c_str(), SDL_GetError() );
}
return loadedSurface;
}
bool init()
{
//Initialization flag
bool success = true;
//Initialize SDL
if(SDL_Init( SDL_INIT_VIDEO) < 0)
{
printf("sdl could not initialize! sdl_Error: %s\n", SDL_GetError());
success = false;
}
else
{
//Get window surface
gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if( gWindow == NULL){
printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
success = false;
}
else{
gScreenSurface = SDL_GetWindowSurface(gWindow);
}
}
return success;
}
bool loadMedia()
{
//Loading success flag
bool success = true;
//Load splash image
gKeyPressSurfaces[KEY_PRESS_SURFACE_DEFAULT ] = loadSurface( "Content/sprites/press.bmp" );
if(gKeyPressSurfaces[KEY_PRESS_SURFACE_DEFAULT] == NULL)
{
printf( "Unable to load default image %s! SDL Error: %s\n", "Content/sprites/press.bmp", SDL_GetError());
success = false;
}
//Load up surface
gKeyPressSurfaces[KEY_PRESS_SURFACE_UP] = loadSurface("Content/sprites/up.bmp");
if(gKeyPressSurfaces[KEY_PRESS_SURFACE_UP] == NULL )
{
printf("Failed to load up image! \n");
success = false;
}
gKeyPressSurfaces[KEY_PRESS_SURFACE_DOWN] = loadSurface("Content/sprites/down.bmp");
if(gKeyPressSurfaces[KEY_PRESS_SURFACE_DOWN] == NULL )
{
printf("Failed to load down image! \n");
success = false;
}
gKeyPressSurfaces[KEY_PRESS_SURFACE_LEFT] = loadSurface("Content/sprites/left.bmp");
if(gKeyPressSurfaces[KEY_PRESS_SURFACE_LEFT] == NULL )
{
printf("Failed to load left image! \n");
success = false;
}
gKeyPressSurfaces[KEY_PRESS_SURFACE_RIGHT] = loadSurface("Content/sprites/right.bmp");
if(gKeyPressSurfaces[KEY_PRESS_SURFACE_RIGHT] == NULL)
{
printf("Failed to load right image! \n");
success = false;
}
return success;
}
void close()
{
//Deallocate surface
for(int i = 0; i < KEY_PRESS_SURFACE_TOTAL; ++i)
{
SDL_FreeSurface(gKeyPressSurfaces[i]);
gKeyPressSurfaces[i] = NULL;
}
//Destroy window
SDL_DestroyWindow(gWindow);
gWindow = NULL;
//Quit SDL subsystems
SDL_Quit();
}
int main(int argc, char* args[]){
//Main loop flag
bool quit = false;
//Event handler
SDL_Event e;
//Start up SDL and create window
if(!init())
{
printf("Failed to initialize!\n");
}
else
{
bool quit = false;
SDL_Event e;
gCurrentSurface = gKeyPressSurfaces[KEY_PRESS_SURFACE_DEFAULT];
while(!quit)
{
while( SDL_PollEvent( &e ) != 0)
{
//User requests quit
if( e.type == SDL_QUIT)
{
quit = true;
}
else if(e.type == SDL_KEYDOWN)
{
switch(e.key.keysym.sym){
case SDLK_UP:
gCurrentSurface = gKeyPressSurfaces[KEY_PRESS_SURFACE_UP];
break;
case SDLK_DOWN:
gCurrentSurface = gKeyPressSurfaces[KEY_PRESS_SURFACE_DOWN];
break;
case SDLK_RIGHT:
gCurrentSurface = gKeyPressSurfaces[KEY_PRESS_SURFACE_RIGHT];
break;
case SDLK_LEFT:
gCurrentSurface = gKeyPressSurfaces[KEY_PRESS_SURFACE_LEFT];
break;
default:
gCurrentSurface[KEY_PRESS_SURFACE_DEFAULT];
break;
}
}
SDL_BlitSurface(gCurrentSurface, NULL, gScreenSurface, NULL);
SDL_UpdateWindowSurface(gWindow);
}
}
}
close();
return(0);
}
| [
"harby@harby-VirtualBox.(none)"
] | harby@harby-VirtualBox.(none) |
dcebc5541fc92087bbe835798abd034511caccd5 | 9f8e57c20f9287b8517f825088882c4aa304ed52 | /src/KafkaConnection.cpp | 917ff155ffaac1c1316bf774ab56bbff569def09 | [] | no_license | chrisreis53/gmsec_kafka | a1030362d57d104e54bd3a71acd3a3794443f409 | ec260db46bd88ec770ccfc0ca8b21c7831b08d07 | refs/heads/master | 2021-01-12T01:22:34.753501 | 2017-03-22T15:58:31 | 2017-03-22T15:58:31 | 78,378,547 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,073 | cpp | /*
* Copyright 2007-2016 United States Government as represented by the
* Administrator of The National Aeronautics and Space Administration.
* No copyright is claimed in the United States under Title 17, U.S. Code.
* All Rights Reserved.
*/
/* @file KafkaConnection.cpp
* This file provides a template for implementing a middleware wrapper.
*/
#include <gmsec_kafka.h>
#include <KafkaConnection.h>
#include <gmsec4/internal/InternalConnection.h>
#include <gmsec4/internal/MessageBuddy.h>
#include <gmsec4/internal/Rawbuf.h>
#include <gmsec4/internal/SystemUtil.h>
#include <gmsec4/Connection.h>
#include <gmsec4/Errors.h>
#include <gmsec4/util/Buffer.h>
#include <gmsec4/util/Condition.h>
#include <gmsec4/util/Log.h>
#include <gmsec4/util/Mutex.h>
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <csignal>
#include <cstring>
#include <regex>
#include <gmsec_version.h>
#include <librdkafka/rdkafkacpp.h>
using namespace gmsec::api;
using namespace gmsec::api::internal;
using namespace gmsec::api::util;
using namespace std;
// Constants
#define TOPIC_PREFIX ""
static bool run = true;
static bool exit_eof = false;
int use_ccb = 0;
//Kafka base objects
RdKafka::Producer *producer;
RdKafka::Consumer *consumer;
RdKafka::Queue *rkqu;
//Kafka vector objects
//Vector variables
std::vector<std::string> subscribed_topics;
static void sigterm (int sig) {
run = false;
}
const char* msgClean(std::string msg_str){
//TODO clean messages to prevent program crashes
std::string end = "</MESSAGE>";
if(msg_str.compare(msg_str.length() - end.length(), end.length(), end) == 0){
GMSEC_DEBUG << "Message did not have to be Cleaned!" << '\n';
return msg_str.c_str();
} else {
GMSEC_DEBUG << "Message had to be Cleaned" << '\n';
while(msg_str.compare(msg_str.length() - end.length(), end.length(), end) != 0){
msg_str.pop_back();
GMSEC_DEBUG << "Cleaning:\n" << msg_str.c_str() << '\n';
}
return msg_str.c_str();
}
}
void msg_consume(RdKafka::Message* message, void* opaque) {
switch (message->err()) {
case RdKafka::ERR__TIMED_OUT:
break;
case RdKafka::ERR_NO_ERROR:
/* Real message */
std::cout << "Read msg at offset " << message->offset() << std::endl;
if (message->key()) {
std::cout << "Key: " << *message->key() << std::endl;
}
printf("%.*s\n",
static_cast<int>(message->len()),
static_cast<const char *>(message->payload()));
break;
case RdKafka::ERR__PARTITION_EOF:
/* Last message */
if (exit_eof) {
run = false;
}
break;
case RdKafka::ERR__UNKNOWN_TOPIC:
case RdKafka::ERR__UNKNOWN_PARTITION:
std::cerr << "Consume failed: " << message->errstr() << std::endl;
run = false;
break;
default:
/* Errors */
std::cerr << "Consume failed: " << message->errstr() << std::endl;
run = false;
}
}
std::vector<std::string> list_topics(std::string input_topic){
std::vector<std::string> str_vec;
RdKafka::Topic *topic = NULL;
class RdKafka::Metadata *metadata;
/* Fetch metadata */
RdKafka::ErrorCode err = producer->metadata(topic!=NULL, topic, &metadata, 5000);
if (err != RdKafka::ERR_NO_ERROR) {
std::cerr << "%% Failed to acquire metadata: " << RdKafka::err2str(err) << std::endl;
}
std::cout << metadata->topics()->size() << " topics:" << std::endl;
RdKafka::Metadata::TopicMetadataIterator it;
for (it = metadata->topics()->begin(); it != metadata->topics()->end(); ++it) {
std::string t = (*it)->topic();
std::regex re(input_topic);
if (regex_match(t,re)) {
str_vec.push_back(t);
std::cout << "Found: " << t << '\n';
}
}
return str_vec;
}
class ExampleDeliveryReportCb : public RdKafka::DeliveryReportCb {
public:
void dr_cb (RdKafka::Message &message) {
GMSEC_INFO << "TEST" << '\n';
std::cout << "Message delivery for (" << message.len() << " bytes): " <<
message.errstr() << '\n';
if (message.key())
std::cout << "Key: " << *(message.key()) << ";" << '\n';
}
};
class ExampleConsumeCb : public RdKafka::ConsumeCb {
public:
void consume_cb (RdKafka::Message &msg, void *opaque) {
msg_consume(&msg, opaque);
}
};
std::string KafkaConnection::generateUniqueId(long id)
{
std::ostringstream strm;
strm << getExternal().getID() << "_" << SystemUtil::getProcessID() << "_" << ++uniquecounter << "_" << id;
std::string topic = TOPIC_PREFIX;
topic.append(strm.str());
return topic;
}
KafkaConnection::KafkaConnection(const Config& config)
:
requestCounter(0),
uniquecounter(0),
mw_test(false),
mwInfo(""),
mw_brokers("localhost"),
mw_errstr(""),
mw_debug("")
{
GMSEC_INFO << '\n' << config.toXML() << '\n';
if(config.getValue("server") != NULL){
mw_brokers = config.getValue("server");
}
GMSEC_DEBUG << "Brokers: " << mw_brokers.c_str() << '\n';
/*
* Create producer using accumulated global configuration.
*/
RdKafka::Conf *pub_conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
pub_conf->set("metadata.broker.list", mw_brokers, mw_errstr);
ExampleDeliveryReportCb ex_dr_cb;
//TODO Fix callback issues
//conf->set("dr_cb", &ex_dr_cb, mw_errstr);
producer = RdKafka::Producer::create(pub_conf, mw_errstr);
if (!producer) {
std::cerr << "Failed to create producer: " << mw_errstr << std::endl;
exit(1);
}
std::cout << "% Created producer " << producer->name() << std::endl;
RdKafka::Conf *sub_conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
sub_conf->set("metadata.broker.list", mw_brokers, mw_errstr);
consumer = RdKafka::Consumer::create(sub_conf, mw_errstr);
if (!consumer) {
std::cerr << "Failed to create consumer: " << mw_errstr << std::endl;
exit(1);
}
std::cout << "% Created consumer " << consumer->name() << std::endl;
rkqu = RdKafka::Queue::create(consumer);
}
KafkaConnection::~KafkaConnection()
{
GMSEC_DEBUG << "~Connection" << '\n';
}
const char* KafkaConnection::getLibraryVersion()
{
return "v0.10.1";
}
const char* KafkaConnection::getMWInfo()
{
if (mwInfo.empty())
{
mwInfo = getLibraryRootName();
}
return mwInfo.c_str();
}
void KafkaConnection::mwConnect()
{
GMSEC_DEBUG << "gmsec_kafka:KafkaConnection::mwConnect()";
}
void KafkaConnection::mwDisconnect()
{
GMSEC_DEBUG << "gmsec_kafka:KafkaConnection::mwDisconnect()";
}
void KafkaConnection::mwSubscribe(const char* subject, const Config& config)
{
GMSEC_DEBUG << "gmsec_kafka:KafkaConnection::mwSubscribe(" << subject << ')' << '\n';
std::string topic_str = subject;
std::vector<std::string> topic_vec;
if (topic_str.find("*") != string::npos) {
GMSEC_DEBUG << "Found Wildcard in " << topic_str.c_str() << '\n';
topic_vec = list_topics(topic_str);
for (std::vector<std::string>::const_iterator i = topic_vec.begin(); i != topic_vec.end(); ++i) {
std::string it_str = *i;
GMSEC_DEBUG << "Subscribing to: " << it_str.c_str() << '\n';
subscribed_topics.push_back(it_str.c_str());
RdKafka::Conf *tconf = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);
RdKafka::Conf *sub_conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
sub_conf->set("metadata.broker.list", mw_brokers, mw_errstr);
RdKafka::Consumer *t_consumer = RdKafka::Consumer::create(sub_conf, mw_errstr);
/*
* Create topic handle.
*/
RdKafka::Topic *topic = RdKafka::Topic::create(consumer, it_str, tconf, mw_errstr);
if (!topic) {
std::cerr << "Failed to create topic: " << mw_errstr << std::endl;
exit(1);
}
/*
* Start consumer for topic+partition at start offset
*/
int32_t partition = 0;
int64_t start_offset = RdKafka::Topic::OFFSET_BEGINNING;
RdKafka::ErrorCode resp = consumer->start(topic, partition, start_offset, rkqu);
if (resp != RdKafka::ERR_NO_ERROR) {
std::cerr << "Failed to start consumer: " <<
RdKafka::err2str(resp) << std::endl;
exit(1);
}
}
} else {
GMSEC_DEBUG << "No Wildcard; Subscribing to: " << subject << '\n';
subscribed_topics.push_back(subject);
RdKafka::Conf *tconf = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);
RdKafka::Conf *sub_conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
sub_conf->set("metadata.broker.list", mw_brokers, mw_errstr);
RdKafka::Consumer *t_consumer = RdKafka::Consumer::create(sub_conf, mw_errstr);
/*
* Create topic handle.
*/
RdKafka::Topic *topic = RdKafka::Topic::create(t_consumer, topic_str, tconf, mw_errstr);
if (!topic) {
std::cerr << "Failed to create topic: " << mw_errstr << std::endl;
exit(1);
}
/*
* Start consumer for topic+partition at start offset
*/
int32_t partition = 0;
int64_t start_offset = RdKafka::Topic::OFFSET_BEGINNING;
RdKafka::ErrorCode resp = t_consumer->start(topic, partition, start_offset, rkqu);
if (resp != RdKafka::ERR_NO_ERROR) {
std::cerr << "Failed to start consumer: " <<
RdKafka::err2str(resp) << std::endl;
exit(1);
}
}
}
void KafkaConnection::mwUnsubscribe(const char *subject)
{
int32_t partition = 0;
std::string topic_str = subject;
RdKafka::Conf *tconf = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);
if (topic_str.find("*") != string::npos) {
GMSEC_DEBUG << "Found Wildcard in " << subject << '\n';
std::vector<std::string> topic_vec = list_topics(topic_str);
for (std::vector<std::string>::const_iterator i = topic_vec.begin(); i != topic_vec.end(); ++i) {
std::string it_str = *i;
GMSEC_DEBUG << "gmsec_kafka:KafkaConnection::mwUnSubscribe(" << it_str.c_str() << ')';
RdKafka::Topic *topic = RdKafka::Topic::create(consumer, it_str, tconf, mw_errstr);
consumer->stop(topic, partition);
}
}
GMSEC_DEBUG << "gmsec_kafka:KafkaConnection::mwUnSubscribe(" << subject << ')';
RdKafka::Topic *topic = RdKafka::Topic::create(consumer, subject, tconf, mw_errstr);
if (!topic) {
std::cerr << "Failed to create topic: " << mw_errstr << std::endl;
exit(1);
}
consumer->stop(topic, partition);
}
void KafkaConnection::mwPublish(const Message& message, const Config& config)
{
Message test_message(message);
std::string topic_str = message.getSubject();
std::string line = message.toXML();
RdKafka::Conf *tconf = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);
/*
* Create topic handle.
*/
RdKafka::Topic *topic = RdKafka::Topic::create(producer, topic_str,
tconf, mw_errstr);
if (!topic) {
std::cerr << "Failed to create topic: " << mw_errstr << std::endl;
exit(1);
}
/*
* Publish Message
*/
int32_t partition = RdKafka::Topic::PARTITION_UA;
RdKafka::ErrorCode resp = producer->produce(topic, partition, RdKafka::Producer::RK_MSG_COPY, const_cast<char *>(line.c_str()), line.size(), NULL, NULL);
if (resp != RdKafka::ERR_NO_ERROR){
std::cerr << "% Produce failed: " <<
RdKafka::err2str(resp) << std::endl;
}else{
std::cerr << "% Produced message (" << line.size() << " bytes)" << std::endl;
producer->poll(0);
}
// while (run && producer->outq_len() > 0) {
// std::cerr << "Waiting for " << producer->outq_len() << std::endl;
// producer->poll(250);
// }
GMSEC_DEBUG << "gmsec_kafka:KafkaConnection::Publish(things)" << '\n' << message.toXML() ;
}
void KafkaConnection::mwRequest(const Message& request, std::string& id)
{
GMSEC_DEBUG << "gmsec_kafka:KafkaConnection::mwRequest(" << ')';
id = generateUniqueId(++requestCounter);
MessageBuddy::getInternal(request).addField(REPLY_UNIQUE_ID_FIELD, id.c_str());
MessageBuddy::getInternal(request).getDetails().setBoolean(OPT_REQ_RESP, true);
mwPublish(request, getExternal().getConfig());
GMSEC_DEBUG << "[Request sent successfully: " << request.getSubject() << "]";
}
void KafkaConnection::mwReply(const Message& request, const Message& reply)
{
const StringField* uniqueID = dynamic_cast<const StringField*>(request.getField(REPLY_UNIQUE_ID_FIELD));
if (uniqueID == NULL)
{
throw Exception(CONNECTION_ERROR, INVALID_MSG, "Request does not contain unique ID field");
}
MessageBuddy::getInternal(reply).addField(REPLY_UNIQUE_ID_FIELD, uniqueID->getValue());
// Publish the reply
mwPublish(reply, getExternal().getConfig());
GMSEC_DEBUG << "[Reply sent successfully: " << reply.getSubject() << "]";
}
void KafkaConnection::mwReceive(Message*& message, GMSEC_I32 timeout)
{
GMSEC_DEBUG << "gmsec_kafka:KafkaConnection::mwReceive";
message = NULL;
RdKafka::Message *msg = consumer->consume(rkqu, (int)timeout);
std::string msg_str = static_cast<const char *>(msg->payload());
if(msg_str.find("Broker:") != string::npos) {
//GMSEC_INFO << msg_str.c_str();
} else {
GMSEC_DEBUG << '\n' << msg_str.c_str();
message = new Message(msgClean(msg_str));
}
//msg_consume(msg, NULL);
delete msg;
}
// EOF KafkaConnection.cpp
| [
"chrisreis53@gmail.com"
] | chrisreis53@gmail.com |
1e3395082208a53aebf6925efd8a586a275aeebc | b1098a2540fd27d05f33219e6bb2868cdda04c89 | /src/custom/include/megbrain/custom/data_adaptor.h | 1d484e2d6481b8ad330cb3a81f99efdd4b18d6c6 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | chenjiahui0131/MegEngine | de5f96a8a855a7b2d324316e79ea071c34f8ab6a | 6579c984704767086d2721ba3ec3881a3ac24f83 | refs/heads/master | 2023-08-23T21:56:30.765344 | 2021-10-20T10:03:29 | 2021-10-20T10:03:29 | 400,480,179 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,373 | h | /**
* \file src/custom/include/megbrain/custom/data_adaptor.h
* MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
*
* Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#pragma once
#include "megdnn/thin/small_vector.h"
namespace custom {
template <typename BuiltinT, typename CustomT>
BuiltinT to_builtin(const CustomT &custom) {
return *reinterpret_cast<const BuiltinT*>(custom.impl());
}
template <typename BuiltinT, typename CustomT>
CustomT to_custom(const BuiltinT &builtin) {
return std::move(CustomT(&builtin));
}
template <typename BuiltinT, typename CustomT>
megdnn::SmallVector<BuiltinT> to_builtin(const std::vector<CustomT> &customs) {
megdnn::SmallVector<BuiltinT> builtins;
for (size_t i=0; i<customs.size(); ++i) {
builtins.push_back(std::move(to_builtin<BuiltinT, CustomT>(customs[i])));
}
return std::move(builtins);
}
template <typename BuiltinT, typename CustomT>
std::vector<CustomT> to_custom(
const megdnn::SmallVector<BuiltinT> &builtins) {
std::vector<CustomT> customs;
for (size_t i=0; i<builtins.size(); ++i) {
customs.push_back(std::move(to_custom<BuiltinT, CustomT>(builtins[i])));
}
return std::move(customs);
}
}
#define to_custom_device(expr) custom::to_custom<CompNode, custom::Device>(expr)
#define to_builtin_device(expr) custom::to_builtin<CompNode, custom::Device>(expr)
#define to_custom_shape(expr) custom::to_custom<megdnn::TensorShape, custom::Shape>(expr)
#define to_builtin_shape(expr) custom::to_builtin<megdnn::TensorShape, custom::Shape>(expr)
#define to_custom_dtype(expr) custom::to_custom<megdnn::DType, custom::DType>(expr)
#define to_builtin_dtype(expr) custom::to_builtin<megdnn::DType, custom::DType>(expr)
#define to_custom_format(expr) custom::to_custom<megdnn::TensorLayout::Format, custom::Format>(expr)
#define to_builtin_format(expr) custom::to_builtin<megdnn::TensorLayout::Format, custom::Format>(expr)
#define to_custom_tensor(expr) custom::to_custom<DeviceTensorND, custom::Tensor>(expr)
#define to_builtin_tensor(expr) custom::to_builtin<DeviceTensorND, custom::Tensor>(expr)
| [
"megengine@megvii.com"
] | megengine@megvii.com |
1c511765c96bf06e2d73db419f01df7d9a0f40d1 | 0b45aa221f069d9cd781dafa14bc2099b20fb03e | /tags/2.21.1/sdk/tests/test_feature/source/test_import.cpp | c8fb29424c9ce91faa2b3ddbd9b341791150cab9 | [] | no_license | svn2github/angelscript | f2d16c2f32d89a364823904d6ca3048222951f8d | 6af5956795e67f8b41c6a23d20e369fe2c5ee554 | refs/heads/master | 2023-09-03T07:42:01.087488 | 2015-01-12T00:00:30 | 2015-01-12T00:00:30 | 19,475,268 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,231 | cpp | //
// Tests importing functions from other modules
//
// Test author: Andreas Jonsson
//
#include "utils.h"
namespace TestImport
{
static const char * const TESTNAME = "TestImport";
static const char *script1 =
"import string Test(string s) from \"DynamicModule\"; \n"
"void main() \n"
"{ \n"
" Test(\"test\"); \n"
"} \n";
static const char *script2 =
"string Test(string s) \n"
"{ \n"
" number = 1234567890; \n"
" return \"blah\"; \n"
"} \n";
static const char *script3 =
"class A \n"
"{ \n"
" int a; \n"
"} \n"
"import void Func(A&out) from \"DynamicModule\"; \n"
"import A@ Func2() from \"DynamicModule\"; \n";
static const char *script4 =
"class A \n"
"{ \n"
" int a; \n"
"} \n"
"void Func(A&out) {} \n"
"A@ Func2() {return null;} \n";
bool Test()
{
bool fail = false;
int number = 0;
int r;
asIScriptEngine *engine = 0;
COutStream out;
// Test 1
// Importing a function from another module
engine = asCreateScriptEngine(ANGELSCRIPT_VERSION);
engine->SetMessageCallback(asMETHOD(COutStream,Callback), &out, asCALL_THISCALL);
RegisterScriptString_Generic(engine);
engine->RegisterGlobalProperty("int number", &number);
asIScriptModule *mod = engine->GetModule(0, asGM_ALWAYS_CREATE);
mod->AddScriptSection(":1", script1, strlen(script1), 0);
mod->Build();
mod = engine->GetModule("DynamicModule", asGM_ALWAYS_CREATE);
mod->AddScriptSection(":2", script2, strlen(script2), 0);
mod->Build();
// Bind all functions that the module imports
r = engine->GetModule(0)->BindAllImportedFunctions(); assert( r >= 0 );
ExecuteString(engine, "main()", engine->GetModule(0));
engine->Release();
if( number != 1234567890 )
{
printf("%s: Failed to set the number as expected\n", TESTNAME);
TEST_FAILED;
}
// Test 2
// Two identical structures declared in different modules are not the same
engine = asCreateScriptEngine(ANGELSCRIPT_VERSION);
engine->SetMessageCallback(asMETHOD(COutStream,Callback), &out, asCALL_THISCALL);
RegisterScriptString_Generic(engine);
mod = engine->GetModule(0, asGM_ALWAYS_CREATE);
mod->AddScriptSection(":3", script3, strlen(script3), 0);
r = mod->Build(); assert( r >= 0 );
mod = engine->GetModule("DynamicModule", asGM_ALWAYS_CREATE);
mod->AddScriptSection(":4", script4, strlen(script4), 0);
r = mod->Build(); assert( r >= 0 );
// Bind all functions that the module imports
r = engine->GetModule(0)->BindAllImportedFunctions(); assert( r < 0 );
{
const char *script =
"import int test(void) from 'mod1'; \n"
"void main() \n"
"{ \n"
" int str; \n"
" str = test(); \n"
"}\n";
mod->AddScriptSection("4", script);
r = mod->Build();
if( r < 0 )
TEST_FAILED;
}
engine->Release();
// Test building the same script twice, where both imports from another pre-existing module
{
engine = asCreateScriptEngine(ANGELSCRIPT_VERSION);
mod = engine->GetModule("m0", asGM_ALWAYS_CREATE);
mod->AddScriptSection("script1", "interface I3{};void F(I3@){}");
r = mod->Build();
if( r < 0 )
TEST_FAILED;
mod = engine->GetModule("m1", asGM_ALWAYS_CREATE);
mod->AddScriptSection("script2", "interface I1{void f(I2@);};interface I2{};interface I3{};import void F(I3@) from 'm0';");
r = mod->Build();
if( r < 0 )
TEST_FAILED;
r = mod->BindAllImportedFunctions();
if( r < 0 )
TEST_FAILED;
mod = engine->GetModule("m2", asGM_ALWAYS_CREATE);
mod->AddScriptSection("script2", "interface I1{void f(I2@);};interface I2{};interface I3{};import void F(I3@) from 'm0';");
r = mod->Build();
if( r < 0 )
TEST_FAILED;
r = mod->BindAllImportedFunctions();
if( r < 0 )
TEST_FAILED;
engine->Release();
}
// Success
return fail;
}
} // namespace
| [
"angelcode@404ce1b2-830e-0410-a2e2-b09542c77caf"
] | angelcode@404ce1b2-830e-0410-a2e2-b09542c77caf |
b34a938645eec7c969a8a354b9e27524f9c0abc4 | 443a77967733786dace6c8d67bae940d1b8bfdbc | /mapEditor/src/scene/controller/SceneControllerWidget.cpp | 1bdf5f453c25521468ee7347c7c18fbbf59f9f27 | [
"MIT"
] | permissive | whztt1989/UrchinEngine | c3f754d075e2c2ff8f85cf775fcca27eaa2dcb11 | f90ba990b09f3792899db63fb1cbd8adfe514373 | refs/heads/master | 2021-01-13T08:17:59.441361 | 2016-10-23T18:33:11 | 2016-10-23T18:33:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,199 | cpp | #include "SceneControllerWidget.h"
namespace urchin
{
SceneControllerWidget::SceneControllerWidget(QWidget *parent) :
QTabWidget(parent),
sceneController(nullptr)
{
tabObjects = new ObjectControllerWidget();
addTab(tabObjects, "Objects");
tabLights = new LightControllerWidget();
addTab(tabLights, "Lights");
tabSounds = new SoundControllerWidget();
addTab(tabSounds, "Sounds");
setCurrentIndex(0);
setEnabled(false);
}
SceneControllerWidget::~SceneControllerWidget()
{
delete sceneController;
}
ObjectControllerWidget *SceneControllerWidget::getObjectControllerWidget() const
{
return tabObjects;
}
LightControllerWidget *SceneControllerWidget::getLightControllerWidget() const
{
return tabLights;
}
SoundControllerWidget *SceneControllerWidget::getSoundControllerWidget() const
{
return tabSounds;
}
bool SceneControllerWidget::isModified() const
{
return hasMapOpen() && sceneController->isModified();
}
bool SceneControllerWidget::hasMapOpen() const
{
return sceneController!=nullptr;
}
void SceneControllerWidget::newMap(MapHandler *mapHandler, const std::string &relativeWorkingDirectory)
{
closeMap();
sceneController = new SceneController(mapHandler);
sceneController->setRelativeWorkingDirectory(relativeWorkingDirectory);
setEnabled(true);
tabObjects->load(sceneController->getObjectController());
tabLights->load(sceneController->getLightController());
tabSounds->load(sceneController->getSoundController());
}
void SceneControllerWidget::openMap(MapHandler *mapHandler)
{
closeMap();
sceneController = new SceneController(mapHandler);
setEnabled(true);
tabObjects->load(sceneController->getObjectController());
tabLights->load(sceneController->getLightController());
tabSounds->load(sceneController->getSoundController());
}
void SceneControllerWidget::saveMap(const std::string &mapFilename)
{
if(sceneController!=nullptr)
{
sceneController->saveMapOnFile(mapFilename);
}
}
void SceneControllerWidget::closeMap()
{
tabObjects->unload();
tabLights->unload();
tabSounds->unload();
setEnabled(false);
delete sceneController;
sceneController=nullptr;
}
}
| [
"petitg1987@gmail.com"
] | petitg1987@gmail.com |
bea2734ad103d31f63e810973a23d6518b5644aa | 6336c5b5ea6e1892eaf76e5cf9b2968349d5babb | /Skyrim/Destruction.h | 71fda90b32235c9368c5195eba491963625cbb4b | [] | no_license | IlijaBruh/Skyrim-project | 0d4c777e957b8dabc0c9dbdd6ede255864a9937f | d705e00c6b94d48068d92912b18e37374dfe5dd9 | refs/heads/master | 2021-05-15T02:22:18.025759 | 2020-05-15T14:05:24 | 2020-05-15T14:05:24 | 250,260,478 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 301 | h | #ifndef DESTRUCTION_H
#define DESTRUCTION_H
#include <iostream>
#include "Spell.h"
using namespace std;
class Destruction
{
private:
int dmg;
Spell destructionSpell;
public:
Destruction(int dm, Spell ds);
void printDestruction();
};
#endif // DESTRUCTION_H
| [
"krivokuca.ilija@jjzmaj.edu.rs"
] | krivokuca.ilija@jjzmaj.edu.rs |
12c5063c8aeb9adf01da3605adf0169519b6f096 | f1d36e1a329df403bda0b856296695225a4018b7 | /1_Servo_ESP/LedControl.h | d2c7bac43eada74cc99250262a9caf3dc849d833 | [] | no_license | aslamahrahman/Mechatronics-Combat-Bot-Arduino | ba85aa4e4510085d00353259e1136fef65224079 | d0e2d0cf0b4be187aadf85b325c27e0b4648293d | refs/heads/master | 2020-04-20T23:39:48.111204 | 2019-02-05T02:51:43 | 2019-02-05T02:51:43 | 169,174,168 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,173 | h | /*
* LedControl.h - A library for controling Leds with a MAX7219/MAX7221
* Copyright (c) 2007 Eberhard Fahle
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* This permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef LedControl_h
#define LedControl_h
#include <pgmspace.h>
#if (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
/*
* Segments to be switched on for characters and digits on
* 7-Segment Displays
*/
const static byte charTable [] PROGMEM = {
B01111110,B00110000,B01101101,B01111001,B00110011,B01011011,B01011111,B01110000,
B01111111,B01111011,B01110111,B00011111,B00001101,B00111101,B01001111,B01000111,
B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,
B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,
B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,
B00000000,B00000000,B00000000,B00000000,B10000000,B00000001,B10000000,B00000000,
B01111110,B00110000,B01101101,B01111001,B00110011,B01011011,B01011111,B01110000,
B01111111,B01111011,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,
B00000000,B01110111,B00011111,B00001101,B00111101,B01001111,B01000111,B00000000,
B00110111,B00000000,B00000000,B00000000,B00001110,B00000000,B00000000,B00000000,
B01100111,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,
B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00001000,
B00000000,B01110111,B00011111,B00001101,B00111101,B01001111,B01000111,B00000000,
B00110111,B00000000,B00000000,B00000000,B00001110,B00000000,B00010101,B00011101,
B01100111,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,
B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000
};
class LedControl {
private :
/* The array for shifting the data to the devices */
byte spidata[16];
/* Send out a single command to the device */
void spiTransfer(int addr, byte opcode, byte data);
/* We keep track of the led-status for all 8 devices in this array */
byte status[64];
/* Data is shifted out of this pin*/
int SPI_MOSI;
/* The clock is signaled on this pin */
int SPI_CLK;
/* This one is driven LOW for chip selectzion */
int SPI_CS;
/* The maximum number of devices we use */
int maxDevices;
public:
/*
* Create a new controler
* Params :
* dataPin pin on the Arduino where data gets shifted out
* clockPin pin for the clock
* csPin pin for selecting the device
* numDevices maximum number of devices that can be controled
*/
LedControl(int dataPin, int clkPin, int csPin, int numDevices=1);
/*
* Gets the number of devices attached to this LedControl.
* Returns :
* int the number of devices on this LedControl
*/
int getDeviceCount();
/*
* Set the shutdown (power saving) mode for the device
* Params :
* addr The address of the display to control
* status If true the device goes into power-down mode. Set to false
* for normal operation.
*/
void shutdown(int addr, bool status);
/*
* Set the number of digits (or rows) to be displayed.
* See datasheet for sideeffects of the scanlimit on the brightness
* of the display.
* Params :
* addr address of the display to control
* limit number of digits to be displayed (1..8)
*/
void setScanLimit(int addr, int limit);
/*
* Set the brightness of the display.
* Params:
* addr the address of the display to control
* intensity the brightness of the display. (0..15)
*/
void setIntensity(int addr, int intensity);
/*
* Switch all Leds on the display off.
* Params:
* addr address of the display to control
*/
void clearDisplay(int addr);
/*
* Set the status of a single Led.
* Params :
* addr address of the display
* row the row of the Led (0..7)
* col the column of the Led (0..7)
* state If true the led is switched on,
* if false it is switched off
*/
void setLed(int addr, int row, int col, boolean state);
/*
* Set all 8 Led's in a row to a new state
* Params:
* addr address of the display
* row row which is to be set (0..7)
* value each bit set to 1 will light up the
* corresponding Led.
*/
void setRow(int addr, int row, byte value);
/*
* Set all 8 Led's in a column to a new state
* Params:
* addr address of the display
* col column which is to be set (0..7)
* value each bit set to 1 will light up the
* corresponding Led.
*/
void setColumn(int addr, int col, byte value);
/*
* Display a hexadecimal digit on a 7-Segment Display
* Params:
* addr address of the display
* digit the position of the digit on the display (0..7)
* value the value to be displayed. (0x00..0x0F)
* dp sets the decimal point.
*/
void setDigit(int addr, int digit, byte value, boolean dp);
/*
* Display a character on a 7-Segment display.
* There are only a few characters that make sense here :
* '0','1','2','3','4','5','6','7','8','9','0',
* 'A','b','c','d','E','F','H','L','P',
* '.','-','_',' '
* Params:
* addr address of the display
* digit the position of the character on the display (0..7)
* value the character to be displayed.
* dp sets the decimal point.
*/
void setChar(int addr, int digit, char value, boolean dp);
};
#endif //LedControl.h
| [
"aslamahrahiman@gmail.com"
] | aslamahrahiman@gmail.com |
1db1f1b7cba871cbea5931f111828fdb4a3f62e9 | 4f37a2544e5c665dc5a505f009b62aed78afc455 | /2022/sem2/lecture_2_compilation_linking/ex1_objfiles/main.cpp | 55308fab3b0fbc7cb05336bb96e8786b2d186b4c | [
"MIT"
] | permissive | broniyasinnik/cpp_shad_students | b6ccab3c61943f4167e0621f78fde9b35af39156 | eaff4d24d18afa08ecf8c0c52dfd3acc74e370d0 | refs/heads/master | 2022-10-31T13:49:31.901463 | 2022-10-13T11:08:42 | 2022-10-13T11:08:42 | 250,561,827 | 1 | 0 | MIT | 2020-03-27T14:53:02 | 2020-03-27T14:53:01 | null | UTF-8 | C++ | false | false | 766 | cpp | #include "math_utils.h"
#include "string_utils.h"
#include <cstdio>
#include <cstring>
void print_help() noexcept
{
std::puts("USAGE:");
std::puts(" exmaple.bin mmul 3 4");
std::puts(" 12");
std::puts(" exmaple.bin smul 3 4");
std::puts(" 3333");
std::puts("");
std::puts("Errors processing is not implemented in order to simplify example");
}
int main(int argc, char** argv)
{
if (argc != 4)
{
print_help();
return 1;
}
const char* const op = argv[1];
const char* const a1 = argv[2];
const char* const a2 = argv[3];
if (!std::strcmp(op, "mmul"))
math_utils::mul(a1, a2);
else if (!std::strcmp(op, "smul"))
string_utils::mul(a1, a2);
return 0;
}
| [
"ivafanas@gmail.com"
] | ivafanas@gmail.com |
4d1c409fe1795bdd6272be6ac3515b4d28a0a43f | 99bb7246a5577376694968cc320e34b4b8db1693 | /CommonLibF4/include/RE/Bethesda/BSTimer.h | c5ea62c810a69cf9e2a5cbd2d93f150d4ef12192 | [
"MIT"
] | permissive | Ryan-rsm-McKenzie/CommonLibF4 | 0d8f3baa4e3c18708e6427959f1d4f88bcf3d691 | cdd932ad1f4e37f33c28ea7d7e429428f5be43dd | refs/heads/master | 2023-07-26T23:24:09.615310 | 2023-07-16T22:53:24 | 2023-07-16T22:53:24 | 194,604,556 | 50 | 21 | MIT | 2023-07-20T22:20:02 | 2019-07-01T05:20:18 | C++ | UTF-8 | C++ | false | false | 611 | h | #pragma once
namespace RE
{
class BSTimer
{
public:
// members
std::int64_t highPrecisionInitTime; // 00
float clamp; // 08
float clampRemainder; // 0C
float delta; // 10
float realTimeDelta; // 14
std::uint64_t lastTime; // 18
std::uint64_t firstTime; // 20
std::uint64_t disabledLastTime; // 28
std::uint64_t disabledFirstTime; // 30
std::uint32_t disableCounter; // 38
bool useGlobalTimeMultiplierTarget; // 3C
};
static_assert(sizeof(BSTimer) == 0x40);
}
| [
"ryan__mckenzie@hotmail.com"
] | ryan__mckenzie@hotmail.com |
aca17cdad5a909b36a29711a4764c0f7ac5e4c4d | b690baf6e48d1dd76c18a4a28254a0daaff5f64c | /LeetCode/Search a 2D Matrix/Solution O(Mlg(N)).cpp | d43e04ffd1522644b9a97db8af398ba6ac92cf96 | [] | no_license | sorablaze11/Solved-Programming-Problems- | 3262c06f773d2a37d72b7df302a49efb7d355842 | b91ecbd59f6db85cc6a289f76563ed58baa1393d | refs/heads/master | 2020-08-22T06:49:07.754044 | 2020-01-25T10:35:21 | 2020-01-25T10:35:21 | 216,341,201 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 265 | cpp | class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
for(int i = 0; i < matrix.size(); i++){
if(binary_search(matrix[i].begin(), matrix[i].end(), target)) return true;
}
return false;
}
}; | [
"limburaj65@gmail.com"
] | limburaj65@gmail.com |
779de7f04cc812d2cc3f1a7cb146a6ef71428cb0 | 655e13a7206de3cb5f143e2d7f737ea9862657fa | /ms.cpp | c6a06156cc8029b6c2aa04de9203d520a0e41f4a | [] | no_license | slphyx/measles | cbf19a0ff1204693f3c6e98fff7768504ebca033 | dada0ff4664ae3e7d34b5ca17f4d8b969f1d758a | refs/heads/master | 2020-03-28T01:12:16.997109 | 2018-09-10T08:13:23 | 2018-09-10T08:13:23 | 147,486,518 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,761 | cpp | //saralamba@gmail.com
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
SEXP getVar(std::string varname){
Environment glob = Environment::global_env();
SEXP var = glob[varname];
return var;
}
Function getFunc(std::string funcname){
Environment glob = Environment::global_env();
Function fnc = glob[funcname];
return fnc;
}
// [[Rcpp::export]]
List measlesmod(double t, arma::vec y, List parms){
Function tfun = getFunc("tfun");
Function tfun2 = getFunc("tfun2");
Function tfun3 = getFunc("tfun3");
Function birthfunc2 = getFunc("birth.func2");
arma::vec S = y.subvec(0,100);
arma::vec I = y.subvec(101,201);
arma::vec R = y.subvec(202,302);
arma::vec V1S = y.subvec(303,403);
arma::vec V1I = y.subvec(404,504);
arma::vec V1R = y.subvec(505,605);
arma::vec V2S = y.subvec(606,706);
arma::vec V2I = y.subvec(707,807);
arma::vec V2R = y.subvec(808,908);
arma::vec V3S = y.subvec(909,1009);
arma::vec V3I = y.subvec(1010,1110);
arma::vec V3R = y.subvec(1111,1211);
arma::vec newcaseindex = y.subvec(1212,1312);
//I[I<0] = 0;
I.elem(find(I<0)).fill(0);
//R[R<0] = 0;
R.elem(find(R<0)).fill(0);
//V1I[V1I<0] = 0;
V1I.elem(find(V1I<0)).fill(0);
//V1R[V1R<0] = 0;
V1R.elem(find(V1R<0)).fill(0);
//V2I[V2I<0] = 0;
V2I.elem(find(V2I<0)).fill(0);
//V2R[V2R<0] = 0;
V2R.elem(find(V2R<0)).fill(0);
//V3I[V3I<0] = 0;
V3I.elem(find(V3I<0)).fill(0);
//V3R[V3R<0] = 0;
V3R.elem(find(V3R<0)).fill(0);
List ff = getVar("ff");
arma::vec mort = as<arma::vec>(ff["m1970"]);
double N = arma::sum(S+I+R+V1S+V1I+V1R+V2S+V2I+V2R+V3S+V3I+V3R);
double inf = as<double>(getVar("inf"));
//#infectious persons
arma::vec II = inf*(I+V1I+V2I+V3I);
double newborn = as<double>(birthfunc2(t));
newborn = (newborn/365)*N;
//NumericMatrix contact = getVar("contact");
arma::mat contact = as<arma::mat>(getVar("contact"));
arma::mat lambda = contact * II/N;
//#coverage of measles immunization
double v1cov = as<double>(tfun(1955+t/365));
v1cov = v1cov/100;
double v2cov = as<double>(tfun2(1955+t/365));
v2cov = v2cov/100;
//v1cov[Rcpp::is_na(v1cov)] = 0;
//v1cov.replace(arma::datum::nan,0);
//v2cov[Rcpp::is_na(v2cov)] = 0;
//v2cov.replace(arma::datum::nan,0);
if(R_IsNA(v1cov)) v1cov=0;
if(R_IsNA(v2cov)) v2cov=0;
double v3cov = as<double>(tfun3(1955+t/365));
v3cov = v3cov/100;
//v3cov[Rcpp::is_na(v3cov)] = 0;
//v3cov.replace(arma::datum::nan,0);
if(R_IsNA(v3cov)) v3cov=0;
// NumericVector v1doset = NumericVector::create(0.,-log(1-v1cov)/30,rep(0.0,99));
// NumericVector v2doset = NumericVector::create(0.,0.,0.,0.,-log(1.-v2cov)/30,rep(0.0,96));
// NumericVector v3doset = NumericVector::create(rep(-log(1-v2.cov)/30,40),rep(0.0,61));
arma::vec v1dose = {0,-log(1-v1cov)/30,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0. };
arma::vec v2dose = {0,0,0,0,-log(1.-v2cov)/30,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.};
arma::vec v3dose = {-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,
-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,
-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,
-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,
-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,
-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30,-log(1-v2cov)/30, 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.};
arma::mat aging = as<arma::mat>(getVar("aging"));
double w1 = as<double>(getVar("w1"));
double w2 = as<double>(getVar("w2"));
double w3 = as<double>(getVar("w3"));
double eff1 = as<double>(getVar("eff1"));
double eff2 = as<double>(getVar("eff2"));
double eff3 = as<double>(getVar("eff3"));
double gamma = as<double>(getVar("gamma"));
arma::vec dS = -lambda%S-mort%S+aging*S-v1dose%S+w1*(V1S+V1I+V1R)+w2*(V2S+V2I+V2R)-v3dose%S+w3*(V3S+V3I+V3R);
arma::vec dI = lambda%S-mort%I+aging*I-gamma*I-v1dose%I-v3dose%I;
arma::vec dR = gamma*I-mort%R+aging*R-v1dose%R-v3dose%R;
arma::vec dV1S = -lambda%V1S-mort%V1S+aging*V1S+(1-eff1)*v1dose%S-v2dose%V1S-w1*V1S-v3dose%V1S;
arma::vec dV1I = lambda%V1S-mort%V1I+aging*V1I-gamma*V1I+(1-eff1)*v1dose%I-v2dose%V1I-w1*V1I-v3dose%V1I;
arma::vec dV1R = gamma*V1I-mort%V1R+aging*V1R+eff1*v1dose%(S+I)+v1dose%R-v2dose%V1R-w1*V1R-v3dose%V1R;
arma::vec dV2S = -lambda%V2S-mort%V2S+aging*V2S+(1-eff2)*v2dose%V1S-w2*V2S-v3dose%V2S;
arma::vec dV2I = lambda%V2S-mort%V2I+aging*V2I-gamma*V2I+(1-eff2)*v2dose%V1I-v2dose%V1I-w2*V2I-v3dose%V2I;
arma::vec dV2R = gamma*V2I-mort%V2R+aging*V2R+eff2*v2dose%(V1S+V1I)+v2dose%V1R-w2*V2R-v3dose%V2R;
arma::vec dV3S = -lambda%V3S-mort%V3S+aging*V3S+(1-eff3)*v3dose%(V1S+V2S+S)-w3*V3S;
arma::vec dV3I = lambda%V3S-mort%V3I+aging*V3I-gamma*V3I+(1-eff3)*v3dose%(V1I+V2I+I)-w3*V3I;
arma::vec dV3R = gamma*V3I-mort%V3R+aging*V3R+eff3*v3dose%(V1S+V1I+V2S+V2I+S+I)+v3dose%(V1R+V2R+R)-w3*V3R;
arma::vec dnewcase = lambda%(S+V1S+V2S);
dS[0] = dS[0]+newborn;
arma::vec outvec = dS;
outvec = arma::join_cols(outvec,dI);
outvec = arma::join_cols(outvec,dR);
outvec = arma::join_cols(outvec,dV1S);
outvec = arma::join_cols(outvec,dV1I);
outvec = arma::join_cols(outvec,dV1R);
outvec = arma::join_cols(outvec,dV2S);
outvec = arma::join_cols(outvec,dV2I);
outvec = arma::join_cols(outvec,dV2R);
outvec = arma::join_cols(outvec,dV3S);
outvec = arma::join_cols(outvec,dV3I);
outvec = arma::join_cols(outvec,dV3R);
outvec = arma::join_cols(outvec,dnewcase);
List output(5);
//output[""] = NumericVector::create(dS,dI,dR,dV1S,dV1I,dV1R,dV2S,dV2I,dV2R,dV3S,dV3I,dV3R,dnewcase);
output[0] = NumericVector(outvec.begin(),outvec.end());
output[1]=v1cov;
output[2]=v2cov;
output[3]=v3cov;
output[4]=N;
//list(c(dS,dI,dR,dV1S,dV1I,dV1R,dV2S,dV2I,dV2R,dV3S,dV3I,dV3R,dnewcase),v1.cov,v2.cov,v3.cov,N)
return output;
}
/*** R
*/
| [
"noreply@github.com"
] | noreply@github.com |
644956f0eaea72cd4635e7f5eb36ca431af66752 | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /chrome/common/chrome_utility_printing_messages.h | fa7702857f75b75dd13e276f1d959ab4e4b50871 | [
"BSD-3-Clause"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 6,605 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Multiply-included message file, so no include guard.
#include <string>
#include <vector>
#include "base/strings/string16.h"
#include "build/build_config.h"
#include "components/printing/common/printing_param_traits_macros.h"
#include "ipc/ipc_message_macros.h"
#include "ipc/ipc_param_traits.h"
#include "ipc/ipc_platform_file.h"
#include "printing/backend/print_backend.h"
#include "printing/features/features.h"
#include "printing/page_range.h"
#include "printing/pdf_render_settings.h"
#include "printing/pwg_raster_settings.h"
#if defined(OS_WIN)
#include <windows.h>
#endif
#define IPC_MESSAGE_START ChromeUtilityPrintingMsgStart
// Preview and Cloud Print messages.
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
IPC_ENUM_TRAITS_MAX_VALUE(printing::PdfRenderSettings::Mode,
printing::PdfRenderSettings::Mode::LAST)
IPC_STRUCT_TRAITS_BEGIN(printing::PdfRenderSettings)
IPC_STRUCT_TRAITS_MEMBER(area)
IPC_STRUCT_TRAITS_MEMBER(offsets)
IPC_STRUCT_TRAITS_MEMBER(dpi)
IPC_STRUCT_TRAITS_MEMBER(autorotate)
IPC_STRUCT_TRAITS_MEMBER(mode)
IPC_STRUCT_TRAITS_END()
IPC_STRUCT_TRAITS_BEGIN(printing::PrinterCapsAndDefaults)
IPC_STRUCT_TRAITS_MEMBER(printer_capabilities)
IPC_STRUCT_TRAITS_MEMBER(caps_mime_type)
IPC_STRUCT_TRAITS_MEMBER(printer_defaults)
IPC_STRUCT_TRAITS_MEMBER(defaults_mime_type)
IPC_STRUCT_TRAITS_END()
IPC_ENUM_TRAITS_MAX_VALUE(printing::ColorModel, printing::PROCESSCOLORMODEL_RGB)
IPC_STRUCT_TRAITS_BEGIN(printing::PrinterSemanticCapsAndDefaults::Paper)
IPC_STRUCT_TRAITS_MEMBER(display_name)
IPC_STRUCT_TRAITS_MEMBER(vendor_id)
IPC_STRUCT_TRAITS_MEMBER(size_um)
IPC_STRUCT_TRAITS_END()
IPC_STRUCT_TRAITS_BEGIN(printing::PrinterSemanticCapsAndDefaults)
IPC_STRUCT_TRAITS_MEMBER(collate_capable)
IPC_STRUCT_TRAITS_MEMBER(collate_default)
IPC_STRUCT_TRAITS_MEMBER(copies_capable)
IPC_STRUCT_TRAITS_MEMBER(duplex_capable)
IPC_STRUCT_TRAITS_MEMBER(duplex_default)
IPC_STRUCT_TRAITS_MEMBER(color_changeable)
IPC_STRUCT_TRAITS_MEMBER(color_default)
IPC_STRUCT_TRAITS_MEMBER(color_model)
IPC_STRUCT_TRAITS_MEMBER(bw_model)
IPC_STRUCT_TRAITS_MEMBER(papers)
IPC_STRUCT_TRAITS_MEMBER(default_paper)
IPC_STRUCT_TRAITS_MEMBER(dpis)
IPC_STRUCT_TRAITS_MEMBER(default_dpi)
IPC_STRUCT_TRAITS_END()
//------------------------------------------------------------------------------
// Utility process messages:
// These are messages from the browser to the utility process.
// Tells the utility process to get capabilities and defaults for the specified
// printer. Used on Windows to isolate the service process from printer driver
// crashes by executing this in a separate process. This does not run in a
// sandbox.
IPC_MESSAGE_CONTROL1(ChromeUtilityMsg_GetPrinterCapsAndDefaults,
std::string /* printer name */)
// Tells the utility process to get capabilities and defaults for the specified
// printer. Used on Windows to isolate the service process from printer driver
// crashes by executing this in a separate process. This does not run in a
// sandbox. Returns result as printing::PrinterSemanticCapsAndDefaults.
IPC_MESSAGE_CONTROL1(ChromeUtilityMsg_GetPrinterSemanticCapsAndDefaults,
std::string /* printer name */)
#endif // ENABLE_PRINT_PREVIEW
// Windows uses messages for printing even without preview. crbug.com/170859
// Primary user of Windows without preview is CEF. crbug.com/417967
#if BUILDFLAG(ENABLE_PRINTING) && defined(OS_WIN)
// Tell the utility process to start rendering the given PDF into a metafile.
// Utility process would be alive until
// ChromeUtilityMsg_RenderPDFPagesToMetafiles_Stop message.
IPC_MESSAGE_CONTROL2(ChromeUtilityMsg_RenderPDFPagesToMetafiles,
IPC::PlatformFileForTransit /* input_file */,
printing::PdfRenderSettings /* settings */)
// Requests conversion of the next page.
IPC_MESSAGE_CONTROL2(ChromeUtilityMsg_RenderPDFPagesToMetafiles_GetPage,
int /* page_number */,
IPC::PlatformFileForTransit /* output_file */)
// Requests utility process to stop conversion and exit.
IPC_MESSAGE_CONTROL0(ChromeUtilityMsg_RenderPDFPagesToMetafiles_Stop)
#endif // BUILDFLAG(ENABLE_PRINTING) && defined(OS_WIN)
//------------------------------------------------------------------------------
// Utility process host messages:
// These are messages from the utility process to the browser.
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
// Reply when the utility process has succeeded in obtaining the printer
// capabilities and defaults.
IPC_MESSAGE_CONTROL2(ChromeUtilityHostMsg_GetPrinterCapsAndDefaults_Succeeded,
std::string /* printer name */,
printing::PrinterCapsAndDefaults)
// Reply when the utility process has succeeded in obtaining the printer
// semantic capabilities and defaults.
IPC_MESSAGE_CONTROL2(
ChromeUtilityHostMsg_GetPrinterSemanticCapsAndDefaults_Succeeded,
std::string /* printer name */,
printing::PrinterSemanticCapsAndDefaults)
// Reply when the utility process has failed to obtain the printer
// capabilities and defaults.
IPC_MESSAGE_CONTROL1(ChromeUtilityHostMsg_GetPrinterCapsAndDefaults_Failed,
std::string /* printer name */)
// Reply when the utility process has failed to obtain the printer
// semantic capabilities and defaults.
IPC_MESSAGE_CONTROL1(
ChromeUtilityHostMsg_GetPrinterSemanticCapsAndDefaults_Failed,
std::string /* printer name */)
#endif // ENABLE_PRINT_PREVIEW
#if BUILDFLAG(ENABLE_PRINTING) && defined(OS_WIN)
// Reply when the utility process loaded PDF. |page_count| is 0, if loading
// failed.
IPC_MESSAGE_CONTROL1(ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageCount,
int /* page_count */)
// Reply when the utility process rendered the PDF page.
IPC_MESSAGE_CONTROL2(ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageDone,
bool /* success */,
float /* scale_factor */)
// Request that the given font characters be loaded by the browser so it's
// cached by the OS. Please see
// PdfToEmfUtilityProcessHostClient::OnPreCacheFontCharacters for details.
IPC_SYNC_MESSAGE_CONTROL2_0(ChromeUtilityHostMsg_PreCacheFontCharacters,
LOGFONT /* font_data */,
base::string16 /* characters */)
#endif // ENABLE_PRINTING && OS_WIN
| [
"jacob-chen@iotwrt.com"
] | jacob-chen@iotwrt.com |
03a27d7fa39477821cc57be80cd6250a1b83962c | bb7d0b2f5675fc280cae199f08be3744acb6b5f9 | /template/cpp/gcj.cpp | e026f4b9d95f2f37faa9a2b82492547ababb4515 | [] | no_license | fro11o/contest_helper | 4e967acf77e96a65ace7d4a6678f7443a7bce85b | 5478eae2a2eaa904a45620e07ef08294ba44e003 | refs/heads/master | 2021-08-17T02:19:58.327820 | 2021-07-13T02:58:18 | 2021-07-13T02:58:18 | 244,682,207 | 0 | 0 | null | 2020-03-03T16:11:08 | 2020-03-03T16:11:07 | null | UTF-8 | C++ | false | false | 251 | cpp | #include <bits/stdc++.h>
typedef long long int LL;
typedef unsigned long long int ULL;
using namespace std;
// 插入此處
int main() {
int t;
scanf("%d", &t);
for (int ca = 1; ca <= t; ca++) {
printf("Case #%d: ", ca);
}
}
| [
"yc1043@gmail.com"
] | yc1043@gmail.com |
c733ecc1300fc0f6295c651480e0975ece8563d8 | 594ec845e9308c3700a8b931ee97fc1fa0081f18 | /Project3/Project3/Origem.cpp | 42e39fb75e6be7d98a3d485d969571eb784df969 | [
"Apache-2.0"
] | permissive | arnaldorocha/AtividadeUNINTER | 7da3a65e80d57d2ce0a8134f7c36308e0a2a469e | 4275adbeeb323be55f61902c374869cc1ee352ec | refs/heads/main | 2023-04-06T12:04:37.567627 | 2021-04-20T17:13:01 | 2021-04-20T17:13:01 | 309,802,598 | 0 | 0 | null | 2020-11-11T13:23:50 | 2020-11-03T20:43:42 | C++ | ISO-8859-1 | C++ | false | false | 2,665 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>
#include <ctype.h> //biblioteca para acerrar o toupper
int main()
{
setlocale(LC_ALL, "Portuguese"); // com isso, ele faz funcionar todas as funções da lingua portuguesa, assim ele aceita todas acentuações
printf("\n\n\nOlá! Meu nome é Arnaldo Rocha Filho, sou aluno da UNINTER, do curso de engenharia da computação.\n\n\n");
system("pause");
system("cls"); //limpa a janela para ficar mais bonito
printf("\n\n\nNeste programa vamos converter 5 frases informadas pelo usuário em letra maíuscula.\n\n\n ");
system("pause");
system("cls");
char letras[50], frase1[50], frase2[50], frase3[50], frase4[50], frase5[50]; //variaveis string para ler e imprimir as frases
int tamanho; //variavel inteira para acessar a matriz
printf("\n\n\nDigite a primeira frase para ser convertida em letra maíscula: ");
gets_s(letras);
for (tamanho = 0; tamanho < 50; tamanho++)
{
frase1[tamanho] = toupper(letras[tamanho]); //laço de repetição para acessar todas as letras da string
}
printf("\n\n\nSua primeira frase em letra maíscula fica: %s\n\n\n", frase1); //imprime o resultado
system("pause");
system("cls");
printf("\n\n\nDigite a segunda frase para ser convertida em letra maíscula: ");
gets_s(letras);
for (tamanho = 0; tamanho < 50; tamanho++)
{
frase2[tamanho] = toupper(letras[tamanho]);
}
printf("\n\n\nSua segunda frase em letra maíscula fica: %s\n\n\n", frase2);
system("pause");
system("cls");
printf("\n\n\nDigite a terceira frase para ser convertida em letra maíscula: ");
gets_s(letras);
for (tamanho = 0; tamanho < 50; tamanho++)
{
frase3[tamanho] = toupper(letras[tamanho]);
}
printf("\n\n\nSua terceira frase em letra maíscula fica: %s\n\n\n", frase3);
system("pause");
system("cls");
printf("\n\n\nDigite a quarta frase para ser convertida em letra maíscula: ");
gets_s(letras);
for (tamanho = 0; tamanho < 50; tamanho++)
{
frase4[tamanho] = toupper(letras[tamanho]);
}
printf("\n\n\nSua quarta frase em letra maíscula fica: %s\n\n\n", frase4);
system("pause");
system("cls");
printf("\n\n\nDigite a quinta frase para ser convertida em letra maíscula: ");
gets_s(letras);
for (tamanho = 0; tamanho < 50; tamanho++)
{
frase5[tamanho] = toupper(letras[tamanho]);
}
printf("\n\n\nSua quinta frase em letra maíscula fica: %s\n\n\n", frase5);
system("pause");
system("cls");
printf("\n\n\nTodas as frases juntas em letra maiscula ficam assim: %s %s %s %s %s\n\n\n", frase1, frase2, frase3, frase4, frase5); //imprime o resultado
system("pause");
return(0);
}
| [
"arnaldorochafilho@gmail.com"
] | arnaldorochafilho@gmail.com |
fb9ca54be7700993e36c6e0787311ce265444f4b | c6b920f08a4615a7471d026005c2ecc3267ddd71 | /sniffers/Lammps/src/Glue/LammpsInitialization.h | 7510ddf0e0dc1305ff1518b8c4c0914d8c8e699c | [] | no_license | etomica/legacy-api | bcbb285395f27aa9685f02cc7905ab75f87b017c | defcfb6650960bf6bf0a3e55cb5ffabb40d76d8b | refs/heads/master | 2021-01-20T14:07:57.547442 | 2010-04-22T21:19:19 | 2010-04-22T21:19:19 | 82,740,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,129 | h | /*
* LammpsInitialization.h
* API Glue
*
*/
#ifndef LAMMPS_INIT_WRAPPER_H
#define LAMMPS_INIT_WRAPPER_H
#include <map>
#include <vector>
#include "LammpsAtomType.h"
#include "LammpsMolecule.h"
#include "LammpsSimulation.h"
#include "LammpsSpecies.h"
using namespace molesimAPI;
namespace lammpssnifferwrappers
{
class LammpsInitialization {
public:
LammpsInitialization(LammpsSimulation *sim);
void init();
std::vector<LammpsMolecule *>getMolecules();
std::vector<LammpsSpecies *>getSpecies();
private:
void initAtomTypes();
void initMoleculeData();
void initSpecieDataLevel0();
LammpsSimulation *mSim;
LammpsAtomType **atomType;
int moleculeCount;
std::map<int, int> atomTypeIndexToNativeIndex; // glue layer index, native type index
std::map<int, LammpsAtomType *> nativeIndexToAtomType; // native type index, LammpsAtomType
std::vector<LammpsMolecule *> molecules;
std::vector<LammpsSpecies *> species;
};
}
#endif
| [
"rrassler@buffalo.edu"
] | rrassler@buffalo.edu |
d2e0c6d4e975ed7febda754e43a140724c91ab41 | 1ee90596d52554cb4ef51883c79093897f5279a0 | /Sisteme/[C++]Offline Shop - Koray/Ready-made files/Server source/game/src/char_manager.h | 4947be7fb90cfb304564f083f6e55be9050337ff | [] | no_license | Reizonr1/metin2-adv | bf7ecb26352b13641cd69b982a48a6b20061979a | 5c2c096015ef3971a2f1121b54e33358d973c694 | refs/heads/master | 2022-04-05T20:50:38.176241 | 2020-03-03T18:20:58 | 2020-03-03T18:20:58 | 233,462,795 | 1 | 1 | null | null | null | null | UHC | C++ | false | false | 6,722 | h | #ifndef __INC_METIN_II_GAME_CHARACTER_MANAGER_H__
#define __INC_METIN_II_GAME_CHARACTER_MANAGER_H__
#ifdef M2_USE_POOL
#include "pool.h"
#endif
#include "../../common/stl.h"
#include "../../common/length.h"
#include "vid.h"
class CDungeon;
class CHARACTER;
class CharacterVectorInteractor;
class CHARACTER_MANAGER : public singleton<CHARACTER_MANAGER>
{
public:
typedef TR1_NS::unordered_map<std::string, LPCHARACTER> NAME_MAP;
CHARACTER_MANAGER();
virtual ~CHARACTER_MANAGER();
void Destroy();
void GracefulShutdown(); // 정상적 셧다운할 때 사용. PC를 모두 저장시키고 Destroy 한다.
DWORD AllocVID();
LPCHARACTER CreateCharacter(const char * name, DWORD dwPID = 0);
#ifdef __OFFLINE_SHOP__
LPCHARACTER CreateCharacterOffShop(const char * name);
#endif
#ifndef DEBUG_ALLOC
void DestroyCharacter(LPCHARACTER ch);
#else
void DestroyCharacter(LPCHARACTER ch, const char* file, size_t line);
#endif
void Update(int iPulse);
LPCHARACTER SpawnMob(DWORD dwVnum, long lMapIndex, long x, long y, long z, bool bSpawnMotion = false, int iRot = -1, bool bShow = true);
#ifdef __OFFLINE_SHOP__
LPCHARACTER SpawnOffShop(DWORD dwVnum, const char* szName, long lMapIndex, long x, long y, long z, bool bSpawnMotion = false, int iRot = -1, bool bShow = true);
#endif
LPCHARACTER SpawnMobRange(DWORD dwVnum, long lMapIndex, int sx, int sy, int ex, int ey, bool bIsException=false, bool bSpawnMotion = false , bool bAggressive = false);
#ifdef __OFFLINE_SHOP__
LPCHARACTER SpawnOffShopRange(DWORD dwVnum, const char* szName, long lMapIndex, int sx, int sy, int ex, int ey, bool bIsException = false, bool bSpawnMotion = false, bool bAggressive = false);
#endif
LPCHARACTER SpawnGroup(DWORD dwVnum, long lMapIndex, int sx, int sy, int ex, int ey, LPREGEN pkRegen = NULL, bool bAggressive_ = false, LPDUNGEON pDungeon = NULL);
bool SpawnGroupGroup(DWORD dwVnum, long lMapIndex, int sx, int sy, int ex, int ey, LPREGEN pkRegen = NULL, bool bAggressive_ = false, LPDUNGEON pDungeon = NULL);
bool SpawnMoveGroup(DWORD dwVnum, long lMapIndex, int sx, int sy, int ex, int ey, int tx, int ty, LPREGEN pkRegen = NULL, bool bAggressive_ = false);
LPCHARACTER SpawnMobRandomPosition(DWORD dwVnum, long lMapIndex);
void SelectStone(LPCHARACTER pkChrStone);
NAME_MAP & GetPCMap() { return m_map_pkPCChr; }
LPCHARACTER Find(DWORD dwVID);
LPCHARACTER Find(const VID & vid);
LPCHARACTER FindPC(const char * name);
LPCHARACTER FindByPID(DWORD dwPID);
bool AddToStateList(LPCHARACTER ch);
void RemoveFromStateList(LPCHARACTER ch);
// DelayedSave: 어떠한 루틴 내에서 저장을 해야 할 짓을 많이 하면 저장
// 쿼리가 너무 많아지므로 "저장을 한다" 라고 표시만 해두고 잠깐
// (예: 1 frame) 후에 저장시킨다.
void DelayedSave(LPCHARACTER ch);
bool FlushDelayedSave(LPCHARACTER ch); // Delayed 리스트에 있다면 지우고 저장한다. 끊김 처리시 사용 됨.
void ProcessDelayedSave();
template<class Func> Func for_each_pc(Func f);
void RegisterForMonsterLog(LPCHARACTER ch);
void UnregisterForMonsterLog(LPCHARACTER ch);
void PacketMonsterLog(LPCHARACTER ch, const void* buf, int size);
void KillLog(DWORD dwVnum);
void RegisterRaceNum(DWORD dwVnum);
void RegisterRaceNumMap(LPCHARACTER ch);
void UnregisterRaceNumMap(LPCHARACTER ch);
bool GetCharactersByRaceNum(DWORD dwRaceNum, CharacterVectorInteractor & i);
LPCHARACTER FindSpecifyPC(unsigned int uiJobFlag, long lMapIndex, LPCHARACTER except=NULL, int iMinLevel = 1, int iMaxLevel = PLAYER_MAX_LEVEL_CONST);
void SetMobItemRate(int value) { m_iMobItemRate = value; }
void SetMobDamageRate(int value) { m_iMobDamageRate = value; }
void SetMobGoldAmountRate(int value) { m_iMobGoldAmountRate = value; }
void SetMobGoldDropRate(int value) { m_iMobGoldDropRate = value; }
void SetMobExpRate(int value) { m_iMobExpRate = value; }
void SetMobItemRatePremium(int value) { m_iMobItemRatePremium = value; }
void SetMobGoldAmountRatePremium(int value) { m_iMobGoldAmountRatePremium = value; }
void SetMobGoldDropRatePremium(int value) { m_iMobGoldDropRatePremium = value; }
void SetMobExpRatePremium(int value) { m_iMobExpRatePremium = value; }
void SetUserDamageRatePremium(int value) { m_iUserDamageRatePremium = value; }
void SetUserDamageRate(int value ) { m_iUserDamageRate = value; }
int GetMobItemRate(LPCHARACTER ch);
int GetMobDamageRate(LPCHARACTER ch);
int GetMobGoldAmountRate(LPCHARACTER ch);
int GetMobGoldDropRate(LPCHARACTER ch);
int GetMobExpRate(LPCHARACTER ch);
int GetUserDamageRate(LPCHARACTER ch);
void SendScriptToMap(long lMapIndex, const std::string & s);
bool BeginPendingDestroy();
void FlushPendingDestroy();
private:
int m_iMobItemRate;
int m_iMobDamageRate;
int m_iMobGoldAmountRate;
int m_iMobGoldDropRate;
int m_iMobExpRate;
int m_iMobItemRatePremium;
int m_iMobGoldAmountRatePremium;
int m_iMobGoldDropRatePremium;
int m_iMobExpRatePremium;
int m_iUserDamageRate;
int m_iUserDamageRatePremium;
int m_iVIDCount;
TR1_NS::unordered_map<DWORD, LPCHARACTER> m_map_pkChrByVID;
TR1_NS::unordered_map<DWORD, LPCHARACTER> m_map_pkChrByPID;
NAME_MAP m_map_pkPCChr;
char dummy1[1024]; // memory barrier
CHARACTER_SET m_set_pkChrState; // FSM이 돌아가고 있는 놈들
CHARACTER_SET m_set_pkChrForDelayedSave;
CHARACTER_SET m_set_pkChrMonsterLog;
LPCHARACTER m_pkChrSelectedStone;
std::map<DWORD, DWORD> m_map_dwMobKillCount;
std::set<DWORD> m_set_dwRegisteredRaceNum;
std::map<DWORD, CHARACTER_SET> m_map_pkChrByRaceNum;
bool m_bUsePendingDestroy;
CHARACTER_SET m_set_pkChrPendingDestroy;
#ifdef M2_USE_POOL
ObjectPool<CHARACTER> pool_;
#endif
};
template<class Func>
Func CHARACTER_MANAGER::for_each_pc(Func f)
{
TR1_NS::unordered_map<DWORD, LPCHARACTER>::iterator it;
for (it = m_map_pkChrByPID.begin(); it != m_map_pkChrByPID.end(); ++it)
f(it->second);
return f;
}
class CharacterVectorInteractor : public CHARACTER_VECTOR
{
public:
CharacterVectorInteractor() : m_bMyBegin(false) { }
CharacterVectorInteractor(const CHARACTER_SET & r);
virtual ~CharacterVectorInteractor();
private:
bool m_bMyBegin;
};
#ifndef DEBUG_ALLOC
#define M2_DESTROY_CHARACTER(ptr) CHARACTER_MANAGER::instance().DestroyCharacter(ptr)
#else
#define M2_DESTROY_CHARACTER(ptr) CHARACTER_MANAGER::instance().DestroyCharacter(ptr, __FILE__, __LINE__)
#endif
#endif
| [
"59807064+Reizonr1@users.noreply.github.com"
] | 59807064+Reizonr1@users.noreply.github.com |
e56e0864927a2796be602b8581d60a764b69973a | 1556f92f41543782ab48caf765bb16f5a44614c0 | /Graphics/light.cpp | efecae2763f10c0913d7b272b8c5d0611ad09105 | [] | no_license | gage-black/Graphics | 3dd28d2350fa524f265c05f1b022f7e12a8e4773 | 03e5ae946abcee654cd065a7a4ac2ed8ec7ca3a6 | refs/heads/master | 2021-05-27T03:04:36.258571 | 2014-11-25T06:26:06 | 2014-11-25T06:26:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 268 | cpp | #include "light.h"
Light::Light(vector center, vector lap, int w, int h) {
float hfov = 55.0f;
L = new PPC(hfov, w, h);
L->PositionAndOrient(center, lap, vector(0.0f, 1.0f, 0.0f));
on = true;
sm = new FrameBuffer(0,0, w, h);
sm->Clear(0xFFFFFFFF, 0.0f);
}
| [
"0gageblack0@gmail.com"
] | 0gageblack0@gmail.com |
eb46df175cc3661b69f5b964147752d99459c130 | 0e330acab757857fb0855b8a03e4f1c113e64b13 | /include/latmrg/Rank1Lattice.h | f16a4bae8460478d6864ef0ca07e12a9763b3771 | [] | no_license | erwanbou/LatMRG | 8ce14730ac68feba840f1c04d45a0ce251bff8f1 | 8ecc3a9c95c211f0fe534de54c4217f1baaf1a63 | refs/heads/master | 2021-01-23T12:33:45.686517 | 2017-09-01T22:09:56 | 2017-09-01T22:09:56 | 93,171,349 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,768 | h | #ifndef RANK1LATTICE_H
#define RANK1LATTICE_H
#include "latticetester/Types.h"
#include "latticetester/Const.h"
#include "latmrg/IntLattice.h"
namespace LatMRG {
/**
* This class implements a general rank 1 lattice basis. For the values
* \f$a_1, a_2, …, a_d\f$ given, the \f$d\f$-dimensional lattice basis is
* formed as:
* \f[
* \mathbf{b_1} = (a_1, a_2, …, a_d),\quad\mathbf{b_2} = (0, n, 0, …, 0),\quad…, \quad\mathbf{b_d} = (0, …, 0, n)
* \f]
* Without loss of generality, one may choose \f$a_1 = 1\f$.
*
* \warning There is some code duplication with LatticeTester::Rank1Lattice. This
* should be fixed in the future.
*
*/
class Rank1Lattice: public LatMRG::IntLattice {
public:
/**
* Constructor. \f$d\f$ represents the number of multipliers in the array
* `a`.
*/
Rank1Lattice (const MScal & n, const MVect & a, int d,
LatticeTester::NormType norm = LatticeTester::L2NORM);
/**
* Copy constructor.
*/
Rank1Lattice (const Rank1Lattice & Lat);
/**
* Assigns `Lat` to this object.
*/
Rank1Lattice & operator= (const Rank1Lattice & Lat);
/**
* Destructor.
*/
~Rank1Lattice();
/**
* Returns the vector of multipliers \f$a\f$ as a string.
*/
std::string toStringCoef() const;
/**
* Builds the basis in dimension \f$d\f$.
*/
void buildBasis (int d);
/**
* Dualize the matrix. The matrix entered need to have
* the particular shape describe ERWAN
*/
void dualize ();
/**
* Increases the dimension by 1.
*/
void incDim ();
protected:
/**
* Initializes the rank 1 lattice.
*/
void init();
/**
* The multipliers of the rank 1 lattice rule.
*/
MVect m_a;
};
}
#endif
| [
"ebourceret@hotmail.fr"
] | ebourceret@hotmail.fr |
eee3d36f31559d8e0575406875664b34cf1a6aed | 79143151a5f5c246a304fc4ee601e144f323fa97 | /CodeForces/680A/12278767_AC_15ms_2124kB.cpp | 8fd90b1277686e9f894ff8d25a8f8ecd9675dd5e | [] | no_license | 1468362286/Algorithm | 919ab70d1d26a4852edc27b6ece39f3aec8329eb | 571e957e369f5dc5644717371efcc3f4578a922d | refs/heads/master | 2020-06-01T23:56:22.808465 | 2019-06-09T08:44:55 | 2019-06-09T08:44:55 | 190,970,478 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 499 | cpp | #include <stdio.h>
int max(int a,int b){return a>b?a:b;}
int Hash[101];
int vist[101];
int main()
{
//freopen("in.txt","r",stdin);
int a[5];
int i;
int maxi=-1;
int sum=0;
for( i = 0 ; i < 5 ; i++)
scanf("%d",&a[i]),Hash[a[i]]++,sum+=a[i];
for( i = 0 ; i < 5 ; i++)
if(Hash[a[i]]==2&&!vist[a[i]])
{
vist[a[i]]=1;
maxi=max(maxi,2*a[i]);
}
else if(Hash[a[i]]>=3)
{
maxi=max(maxi,3*a[i]);
}
if(maxi==-1)
printf("%d\n",sum);
else
printf("%d\n",sum-maxi);
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
828336e0b18362b823355df799ff22a4f328e3bf | 3b85f64a06790911ca9bd3e8cf8e946d576c1e1a | /Source/WebKit2/WebProcess/WebPage/WebPageOverlay.cpp | 4052030ddcd2c9ce29b42cef23bc957add56f843 | [] | no_license | johnrobinsn/WebKitForWayland | 5f229bdca2af675c5e4923aa3a1a4d92d0eeafaf | 1a47212600d2f818b3b0644f8a7deb5f858cb415 | refs/heads/master | 2023-03-18T01:12:52.258376 | 2015-05-21T12:06:53 | 2015-05-21T12:06:53 | 36,015,114 | 1 | 0 | null | 2015-05-21T13:43:50 | 2015-05-21T13:43:49 | null | UTF-8 | C++ | false | false | 4,958 | cpp | /*
* Copyright (C) 2014 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 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 SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebPageOverlay.h"
#include "WebFrame.h"
#include "WebPage.h"
#include <WebCore/GraphicsLayer.h>
#include <WebCore/PageOverlay.h>
#include <wtf/NeverDestroyed.h>
using namespace WebCore;
namespace WebKit {
static HashMap<PageOverlay*, WebPageOverlay*>& overlayMap()
{
static NeverDestroyed<HashMap<PageOverlay*, WebPageOverlay*>> map;
return map;
}
PassRefPtr<WebPageOverlay> WebPageOverlay::create(std::unique_ptr<WebPageOverlay::Client> client, PageOverlay::OverlayType overlayType)
{
return adoptRef(new WebPageOverlay(WTF::move(client), overlayType));
}
WebPageOverlay::WebPageOverlay(std::unique_ptr<WebPageOverlay::Client> client, PageOverlay::OverlayType overlayType)
: m_overlay(PageOverlay::create(*this, overlayType))
, m_client(WTF::move(client))
{
ASSERT(m_client);
overlayMap().add(m_overlay.get(), this);
}
WebPageOverlay::~WebPageOverlay()
{
if (!m_overlay)
return;
overlayMap().remove(m_overlay.get());
m_overlay = nullptr;
}
WebPageOverlay* WebPageOverlay::fromCoreOverlay(PageOverlay& overlay)
{
return overlayMap().get(&overlay);
}
void WebPageOverlay::setNeedsDisplay(const IntRect& dirtyRect)
{
m_overlay->setNeedsDisplay(dirtyRect);
}
void WebPageOverlay::setNeedsDisplay()
{
m_overlay->setNeedsDisplay();
}
void WebPageOverlay::clear()
{
m_overlay->clear();
}
void WebPageOverlay::pageOverlayDestroyed(PageOverlay&)
{
if (m_overlay) {
overlayMap().remove(m_overlay.get());
m_overlay = nullptr;
}
m_client->pageOverlayDestroyed(*this);
}
void WebPageOverlay::willMoveToPage(PageOverlay&, Page* page)
{
m_client->willMoveToPage(*this, page ? WebPage::fromCorePage(page) : nullptr);
}
void WebPageOverlay::didMoveToPage(PageOverlay&, Page* page)
{
m_client->didMoveToPage(*this, page ? WebPage::fromCorePage(page) : nullptr);
}
void WebPageOverlay::drawRect(PageOverlay&, GraphicsContext& context, const IntRect& dirtyRect)
{
m_client->drawRect(*this, context, dirtyRect);
}
bool WebPageOverlay::mouseEvent(PageOverlay&, const PlatformMouseEvent& event)
{
return m_client->mouseEvent(*this, event);
}
void WebPageOverlay::didScrollFrame(PageOverlay&, Frame& frame)
{
m_client->didScrollFrame(*this, WebFrame::fromCoreFrame(frame));
}
#if PLATFORM(MAC)
DDActionContext *WebPageOverlay::actionContextForResultAtPoint(FloatPoint location, RefPtr<WebCore::Range>& rangeHandle, bool forImmediateAction)
{
return m_client->actionContextForResultAtPoint(*this, location, rangeHandle, forImmediateAction);
}
void WebPageOverlay::dataDetectorsDidPresentUI()
{
m_client->dataDetectorsDidPresentUI(*this);
}
void WebPageOverlay::dataDetectorsDidChangeUI()
{
m_client->dataDetectorsDidChangeUI(*this);
}
void WebPageOverlay::dataDetectorsDidHideUI()
{
m_client->dataDetectorsDidHideUI(*this);
}
#endif // PLATFORM(MAC)
bool WebPageOverlay::copyAccessibilityAttributeStringValueForPoint(PageOverlay&, String attribute, FloatPoint parameter, String& value)
{
return m_client->copyAccessibilityAttributeStringValueForPoint(*this, attribute, parameter, value);
}
bool WebPageOverlay::copyAccessibilityAttributeBoolValueForPoint(PageOverlay&, String attribute, FloatPoint parameter, bool& value)
{
return m_client->copyAccessibilityAttributeBoolValueForPoint(*this, attribute, parameter, value);
}
Vector<String> WebPageOverlay::copyAccessibilityAttributeNames(PageOverlay&, bool parameterizedNames)
{
return m_client->copyAccessibilityAttributeNames(*this, parameterizedNames);
}
} // namespace WebKit
| [
"timothy_horton@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc"
] | timothy_horton@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc |
2bf632f65fed73fcf75a125c14523997b14b05b4 | d0bd359c088d643d6b367cbfc6ca61af3d8a0781 | /codeforces/999C : Alphabetic Removals.cpp | 2fc40991cfc1e65acb5d282924ae6d42a90d8767 | [
"MIT"
] | permissive | him1411/algorithmic-coding-and-data-structures | 3ad7aefeb442e8b57e38dee00a62c65fccfebfdd | 685aa95539692daca68ce79c20467c335aa9bb7f | refs/heads/master | 2021-03-19T18:01:14.157771 | 2019-02-19T17:43:04 | 2019-02-19T17:43:04 | 112,864,817 | 0 | 2 | MIT | 2018-10-05T09:18:46 | 2017-12-02T18:05:57 | C++ | UTF-8 | C++ | false | false | 1,256 | cpp | #include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define int long long
#define Max(x,y,z) max(x,max(y,z))
#define Min(x,y,z) min(x,min(y,z))
#define trace1(x) cerr<<#x<<": "<<x<<endl
#define trace2(x, y) cerr<<#x<<": "<<x<<" | "<<#y<<": "<<y<<endl
#define trace3(x, y, z) cerr<<#x<<":" <<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl
const int MOD=1e9+7;
template<typename T> T gcd(T a,T b)
{
if(a==0)
return b;
return gcd(b%a,a);
}
template<typename T> T pow(T a,T b, long long m)
{
T ans=1;
while(b>0)
{
if(b%2==1)
ans=(ans*a)%m;
b/=2;
a=(a*a)%m;
}
return ans%m;
}
int32_t main()
{
IOS;
int n,k;
cin>>n>>k;
string str;
cin>>str;
char ch ='a';
for (int i = 0; i < 26; ++i)
{
for (int j = 0; j < n; ++j)
{
if (str[j]==ch && k>0)
{
str[j] = ' ';
k--;
}
}
ch++;
//trace2(str,ch);
}
for (int i = 0; i < n; ++i)
{
if (str[i] != ' ')
{
cout<<str[i];
}
}
cout<<endl;
return 0;
} | [
"him141195@gmail.com"
] | him141195@gmail.com |
5b6d1c296798d6012ed23dba8d5906127686d5be | b989b147ff6fd7711c914c1b4a0c9deb4ccdebec | /src/test/evhttp/evhttp_test.cpp | cb92b9b3bc2bf3458266057b9e2fd75a6d49d9b3 | [] | no_license | weoirp/libevent_study | dc78d7650381f0f6f6c35963a208f61d84cb9c23 | 95c88af6fb611f6609cb2aa3d98a8ffdc5687e6c | refs/heads/master | 2021-09-18T18:17:41.975644 | 2018-07-18T06:11:45 | 2018-07-18T06:11:45 | 114,469,310 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,570 | cpp | #include <string.h>
#include <event.h>
#include <evdns.h>
void readcb(struct bufferevent *bev, void *ptr)
{
char buff[1024];
int n;
struct evbuffer *input = bufferevent_get_input(bev);
while((n = evbuffer_remove(input, buff, sizeof(buff))) > 0)
{
fwrite(buff, 1, n, stdout);
}
}
void eventcb(struct bufferevent *bev, short events, void *ptr)
{
if (events & BEV_EVENT_CONNECTED)
{
printf("Connect okay.\n");
}
else if (events & (BEV_EVENT_ERROR | BEV_EVENT_EOF))
{
struct event_base *base = (struct event_base *)ptr;
if (events & BEV_EVENT_ERROR)
{
int err = bufferevent_socket_get_dns_error(bev);
if (err)
{
printf("DNS error: %s\n", evutil_gai_strerror(err));
}
printf("Closing\n");
bufferevent_free(bev);
event_base_loopexit(base, NULL);
}
}
}
int main(int argc, char **argv)
{
struct event_base *base;
struct evdns_base *dns_base;
struct bufferevent *bev;
if (argc != 3)
{
printf("Trivial HTTP 0.x client\n"
"Syntax: %s [hostname] [resource]\n"
"Example: %s www.google.com \n", argv[0], argv[0]);
return 1;
}
base = event_base_new();
dns_base = evdns_base_new(base, 1);
bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(bev, readcb, NULL, eventcb, base);
bufferevent_enable(bev, EV_READ | EV_WRITE);
evbuffer_add_printf(bufferevent_get_output(bev), "GET %s\r\n", argv[2]);
bufferevent_socket_connect_hostname(bev, dns_base, AF_UNSPEC, argv[1], 80);
event_base_dispatch(base);
return 0;
} | [
"zone.chen@idreamsky.com"
] | zone.chen@idreamsky.com |
e8b393801d1f4ed4bc605492b369cbd8ca69903b | 3ba78433d94a04ae7df759c108f170a1a5ad5d01 | /codeforces/229b.cpp | 4199b6e66d8f62294440df0607b50f012e86b109 | [
"MIT"
] | permissive | jffifa/algo-solution | b9820ed8246af637d9083d8c9b9844a7a1938ee3 | af2400d6071ee8f777f9473d6a34698ceef08355 | refs/heads/master | 2021-07-25T02:36:05.788242 | 2021-07-09T06:36:55 | 2021-07-09T06:36:55 | 15,706,740 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,857 | cpp | #include<cstdio>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<cstring>
#include<string>
#include<ctime>
#include<cmath>
using namespace std;
typedef long long ll;
struct Node
{
map<int,int> hash;
vector<int> rel,dis;
}P[111111];
int N, M;
int dis[111111];
queue<int> q;
bool inq[111111];
void spfa() {
int i, j, k, u, v;
for (u = 1; u <= N; ++u)
dis[u] = 0x3fffffff;
memset(inq, 0, sizeof inq);
dis[1] = 0;
q.push(1);
inq[1] = 1;
while (!q.empty()) {
u = q.front();
q.pop();
inq[u] = 0;
for (i = 0; i < P[u].rel.size(); ++i) {
v = P[u].rel[i];
int d = P[u].hash.find(dis[u])==P[u].hash.end()?dis[u]:P[u].hash[dis[u]];
if (dis[v]>d+P[u].dis[i]) {
dis[v] = d+P[u].dis[i];
if (!inq[v]) {
q.push(v);
inq[v] = 1;
}
}
}
}
}
int V[111111];
int main()
{
int x, y, i, j, c;
while (~scanf("%d%d",&N,&M))
{
for (i=1;i<=N;i++)
{
P[i].hash.clear();
P[i].rel.clear();
P[i].dis.clear();
}
for (i=0;i<M;i++)
{
scanf("%d%d%d",&x,&y,&c);
P[x].rel.push_back(y);
P[y].rel.push_back(x);
P[x].dis.push_back(c);
P[y].dis.push_back(c);
}
for (i=1;i<=N;i++)
{
scanf("%d",&x);
for (j=0;j<x;j++)
scanf("%d",&V[j]);
if (x>0)
{
P[i].hash[V[x-1]]=V[x-1]+1;
for (j=x-2;j>=0;j--)
{
if (V[j]+1==V[j+1])
P[i].hash[V[j]]=P[i].hash[V[j+1]];
else P[i].hash[V[j]]=V[j]+1;
}
}
}
spfa();
printf("%d\n", dis[N]<0x3fffffff?dis[N]:-1);
}
}
| [
"jffifa@gmail.com"
] | jffifa@gmail.com |
97d7c188c8c45cd8f20bdf8f5dfca6010ab921dc | 71dd3dca26e2ecedae75dd06bfe1ab48481262a7 | /Gafo arbol libre/Source.cpp | ee250c0bedd85d28cb3157df8379fd5d3fbc53a6 | [] | permissive | vicvelaz/TAIS | 1c3c2ae8d50c8ce6810a1b5dfcba9fa8054959dd | 06f035029cf5430890245d8202f3dd73d5bf05cf | refs/heads/main | 2021-06-27T04:55:55.334323 | 2021-03-09T21:06:45 | 2021-03-09T21:06:45 | 222,808,309 | 1 | 0 | MIT | 2019-11-19T23:15:55 | 2019-11-19T23:15:54 | null | UTF-8 | C++ | false | false | 1,610 | cpp | //Victor Velazquez Cabrera
//TAIS70
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <stack>
#include "Grafo.h"
using namespace std;
class GrafoArbolLibre {
private:
vector<bool> marked;
bool correcto = true;
void dfs(Grafo const& g, int v, int parent) {
marked[v] = true;
for (int w : g.ady(v)) {
if (!marked[w])
dfs(g, w, v);
else if (w != parent)
correcto = false;
}
}
public:
GrafoArbolLibre(Grafo const& g) : marked(g.V(),false) {
dfs(g, 0, -1);
}
bool esLibre() {
return correcto && isConexo();
}
bool isConexo() {
bool conexo = true;
for (bool marcado : marked) {
if (!marcado)
conexo = false;
}
return conexo;
}
};
bool resuelveCaso() {
int V, E;
cin >> V >> E;
if (!std::cin)
return false;
Grafo g(V);
for (int i = 0; i < E; ++i) {
int a, b;
cin >> a >> b;
g.ponArista(a,b);
}
GrafoArbolLibre grafoArbolLibre(g);
if (grafoArbolLibre.esLibre())
cout << "SI\n";
else
cout << "NO\n";
return true;
}
int main() {
#ifndef DOMJUDGE
std::ifstream in("datos.txt");
auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save old buf and redirect std::cin to casos.txt
#endif
while (resuelveCaso())
;
#ifndef DOMJUDGE // para dejar todo como estaba al principio
std::cin.rdbuf(cinbuf);
system("PAUSE");
#endif
return 0;
} | [
"vicvelaz@ucm.es"
] | vicvelaz@ucm.es |
8a5241407d1d6f78efa19cf368fb39d087132cc8 | 1ecd98c74a7517decd0b051483f008a76e44698e | /src/batcher.cc | f9a8e4fa0b2e0adf65172de80ebc0d80d2905cde | [
"MIT"
] | permissive | dozoisch/node-crc32c | a8160d2d955dcc3ce605c2ca4aa8f6fa213cb862 | 4bd3c589edf02eb2ccdbf87ea105c8e957517b4c | refs/heads/master | 2016-09-06T12:05:20.630611 | 2015-05-08T03:00:06 | 2015-05-08T03:00:06 | 14,193,305 | 2 | 1 | null | 2015-05-08T03:00:20 | 2013-11-07T03:35:38 | JavaScript | UTF-8 | C++ | false | false | 3,668 | cc | #include "batcher.h"
#include <node_buffer.h>
#include <string>
#include <sstream>
// Check if cstdint is supported
#if defined(__GXX_EXPERIMENTAL_CXX0X) || __cplusplus >= 201103L
#include <cstdint>
#else // Include the old lib
#include <stdint.h>
#endif
#include "impl.h"
#include "utils.h"
#include "status.h"
using v8::FunctionTemplate;
using v8::Handle;
using v8::Object;
using v8::String;
using v8::Integer;
using v8::Local;
v8::Persistent<v8::FunctionTemplate> Batcher::constructor;
Batcher::Batcher()
{
_sockets[0] = -1;
_sockets[1] = -1;
}
Batcher::~Batcher()
{
}
void Batcher::Init( Handle<Object> target )
{
Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>( Batcher::New );
tpl->SetClassName( NanNew<String>( "Batcher" ) );
tpl->InstanceTemplate()->SetInternalFieldCount( 1 );
NODE_SET_PROTOTYPE_METHOD( tpl, "openSocket", Batcher::OpenSocket );
NODE_SET_PROTOTYPE_METHOD( tpl, "closeSocket", Batcher::CloseSocket );
NODE_SET_PROTOTYPE_METHOD( tpl, "compute", Batcher::Compute );
NanAssignPersistent( constructor, tpl );
target->Set( NanNew<String>( "Batcher" ), tpl->GetFunction() );
}
v8::Handle<v8::Value> Batcher::NewInstance()
{
NanScope();
v8::Local<v8::FunctionTemplate> constructorHandle = NanNew(constructor);
return constructorHandle->GetFunction()->NewInstance(0, NULL);
}
NAN_METHOD(Batcher::New)
{
NanScope();
Batcher* obj = new Batcher();
obj->Wrap( args.This() );
NanReturnValue(args.This());
}
NAN_METHOD(Batcher::OpenSocket)
{
NanScope();
Batcher* obj = node::ObjectWrap::Unwrap<Batcher>( args.This() );
CRC32C_Status status;
status = crc32c_init( obj->_sockets );
if ( status == ST_SUCCESS )
{
NanReturnValue( NanTrue() );
}
else
{
NanThrowError( utils::GetErrorMessage( status ).c_str() );
NanReturnUndefined();
}
}
NAN_METHOD(Batcher::CloseSocket)
{
NanScope();
Batcher* obj = node::ObjectWrap::Unwrap<Batcher>( args.This() );
CRC32C_Status status;
status = crc32c_close( obj->_sockets );
if ( status == ST_SUCCESS )
{
NanReturnValue( NanTrue() );
}
else
{
NanThrowError( utils::GetErrorMessage( status ).c_str() );
NanReturnUndefined();
}
}
NAN_METHOD(Batcher::Compute)
{
NanScope();
if( args.Length() < 1 )
{
NanThrowError( "Expected 1 argument" );
NanReturnUndefined();
}
Batcher* obj = node::ObjectWrap::Unwrap<Batcher>( args.This() );
CRC32C_Status status;
uint32_t result = 0x00000000;
if ( args[0]->IsString() || args[0]->IsStringObject() ) {
std::string input( *String::Utf8Value( args[0] ) );
status = crc32c_compute( obj->_sockets, input.c_str(), input.length(), &result );
}
else if ( node::Buffer::HasInstance( args[0] ) )
{
Local<Object> buf = args[0]->ToObject();
status = crc32c_compute( obj->_sockets, node::Buffer::Data( buf ), (uint32_t) node::Buffer::Length( buf ), &result );
}
else if ( args[0]->IsObject() )
{
NanThrowError( "Invalid input. Cannot compute objects. The Input has to be of String, StringObject or Buffer, Number" ) ;
NanReturnUndefined();
}
else // Numbers mainly
{
std::string input( *String::Utf8Value( args[0] ) );
status = crc32c_compute( obj->_sockets, input.c_str(), input.length(), &result );
}
if ( status == ST_SUCCESS )
{
NanReturnValue( NanNew<Integer>( result ) );
}
else
{
NanThrowError( utils::GetErrorMessage( status ).c_str() );
NanReturnUndefined();
}
}
| [
"hugo@dozoisch.com"
] | hugo@dozoisch.com |
5cbb4ef93632535fcf5b1d40c6f6d60d4c6f75b0 | 44ab57520bb1a9b48045cb1ee9baee8816b44a5b | /EngineTesting/Code/CoreTools/CoreToolsTesting/HelperSuite/Detail/MemberFunctionNoexceptMacroImpl.cpp | a914e2fb88eff27cd43f2352be16d5f9d0409395 | [
"BSD-3-Clause"
] | permissive | WuyangPeng/Engine | d5d81fd4ec18795679ce99552ab9809f3b205409 | 738fde5660449e87ccd4f4878f7bf2a443ae9f1f | refs/heads/master | 2023-08-17T17:01:41.765963 | 2023-08-16T07:27:05 | 2023-08-16T07:27:05 | 246,266,843 | 10 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,964 | cpp | /// Copyright (c) 2010-2023
/// Threading Core Render Engine
///
/// 作者:彭武阳,彭晔恩,彭晔泽
/// 联系作者:94458936@qq.com
///
/// 标准:std:c++20
/// 引擎测试版本:0.9.0.6 (2023/04/11 21:03)
#include "MemberFunctionNoexceptMacroImpl.h"
#include "System/Helper/Tools.h"
#include "CoreTools/Helper/ClassInvariant/CoreToolsClassInvariantMacro.h"
CoreTools::MemberFunctionNoexceptMacroImpl::MemberFunctionNoexceptMacroImpl() noexcept
{
CORE_TOOLS_SELF_CLASS_IS_VALID_9;
}
CLASS_INVARIANT_STUB_DEFINE(CoreTools, MemberFunctionNoexceptMacroImpl)
void CoreTools::MemberFunctionNoexceptMacroImpl::ConstMemberFunction() const noexcept
{
CORE_TOOLS_CLASS_IS_VALID_CONST_9;
}
void CoreTools::MemberFunctionNoexceptMacroImpl::ConstMemberFunction(int value) const noexcept
{
CORE_TOOLS_CLASS_IS_VALID_CONST_9;
System::UnusedFunction(value);
}
void CoreTools::MemberFunctionNoexceptMacroImpl::ConstMemberFunction(const std::string& character) const noexcept
{
CORE_TOOLS_CLASS_IS_VALID_CONST_9;
System::UnusedFunction(character);
}
void CoreTools::MemberFunctionNoexceptMacroImpl::ConstMemberFunction(const std::string* character) const noexcept
{
CORE_TOOLS_CLASS_IS_VALID_CONST_9;
System::UnusedFunction(character);
}
void CoreTools::MemberFunctionNoexceptMacroImpl::NonConstCopyMemberFunction() noexcept
{
CORE_TOOLS_CLASS_IS_VALID_9;
}
void CoreTools::MemberFunctionNoexceptMacroImpl::NonConstCopyMemberFunction(int value) noexcept
{
CORE_TOOLS_CLASS_IS_VALID_9;
System::UnusedFunction(value);
}
void CoreTools::MemberFunctionNoexceptMacroImpl::NonConstCopyMemberFunction(const std::string& character) noexcept
{
CORE_TOOLS_CLASS_IS_VALID_9;
System::UnusedFunction(character);
}
void CoreTools::MemberFunctionNoexceptMacroImpl::NonConstCopyMemberFunction(const std::string* character) noexcept
{
CORE_TOOLS_CLASS_IS_VALID_9;
System::UnusedFunction(character);
}
| [
"94458936@qq.com"
] | 94458936@qq.com |
04dea7e601fc3c7b43302159251297f9febf9242 | 45d73de830a7030222f5f5c3278bfd88ff63dd09 | /src/qt/overviewpage.h | f62bb5ee363a5c897dbcaa621380175a48e48380 | [
"MIT"
] | permissive | realcaesar/skicoinBeta | 36d84412e9c5ba62911abf27a417c0699de1ea51 | a35cbfda4f70cfa41daa3e80fba95d737ef64449 | refs/heads/master | 2023-03-11T22:07:59.964255 | 2021-03-04T19:27:23 | 2021-03-04T19:27:23 | 309,057,031 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,449 | h | // Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2014-2020 The Skicoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef SKICOIN_QT_OVERVIEWPAGE_H
#define SKICOIN_QT_OVERVIEWPAGE_H
#include "amount.h"
#include <QWidget>
#include <memory>
class ClientModel;
class TransactionFilterProxy;
class TxViewDelegate;
class PlatformStyle;
class WalletModel;
namespace Ui {
class OverviewPage;
}
QT_BEGIN_NAMESPACE
class QModelIndex;
QT_END_NAMESPACE
/** Overview ("home") page widget */
class OverviewPage : public QWidget
{
Q_OBJECT
public:
explicit OverviewPage(const PlatformStyle *platformStyle, QWidget *parent = 0);
~OverviewPage();
void setClientModel(ClientModel *clientModel);
void setWalletModel(WalletModel *walletModel);
void showOutOfSyncWarning(bool fShow);
public Q_SLOTS:
void privateSendStatus();
void setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& anonymizedBalance,
const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance);
Q_SIGNALS:
void transactionClicked(const QModelIndex &index);
void outOfSyncWarningClicked();
private:
QTimer *timer;
Ui::OverviewPage *ui;
ClientModel *clientModel;
WalletModel *walletModel;
CAmount currentBalance;
CAmount currentUnconfirmedBalance;
CAmount currentImmatureBalance;
CAmount currentAnonymizedBalance;
CAmount currentWatchOnlyBalance;
CAmount currentWatchUnconfBalance;
CAmount currentWatchImmatureBalance;
int nDisplayUnit;
bool fShowAdvancedPSUI;
TxViewDelegate *txdelegate;
std::unique_ptr<TransactionFilterProxy> filter;
void SetupTransactionList(int nNumItems);
void DisablePrivateSendCompletely();
private Q_SLOTS:
void togglePrivateSend();
void privateSendAuto();
void privateSendReset();
void privateSendInfo();
void updateDisplayUnit();
void updatePrivateSendProgress();
void updateAdvancedPSUI(bool fShowAdvancedPSUI);
void handleTransactionClicked(const QModelIndex &index);
void updateAlerts(const QString &warnings);
void updateWatchOnlyLabels(bool showWatchOnly);
void handleOutOfSyncWarningClicks();
};
#endif // SKICOIN_QT_OVERVIEWPAGE_H
| [
"63470989+caesar-ski@users.noreply.github.com"
] | 63470989+caesar-ski@users.noreply.github.com |
9d189e4360901f8f41f8e09cc5a9107d16965cde | c37126fbdbf55155c0fd73b16fcea60bf3887627 | /acmicpc.net July 2017/20170716/2797.cpp | c36856d07d86d6bd4e21db31fe676c79396b288d | [] | no_license | Jyunpp/Algorithm | b95dfc1328be931a97def8e6f17058aece99fe5e | a26d9c4e305b0d80bce99302886ce8411e5470e5 | refs/heads/master | 2021-07-02T03:59:50.085470 | 2019-05-29T00:43:10 | 2019-05-29T00:43:10 | 83,957,639 | 3 | 1 | null | null | null | null | UHC | C++ | false | false | 1,661 | cpp | //20170716
#include <iostream>
#include <algorithm>
using namespace std;
#define sz 300001
int h[sz], moveL[sz], moveR[sz];
char t[sz];
int n, k;
int main() {
cin >> n >> k; k--;
for (int i = 0; i < n; i++)
cin >> h[i];
cin >> t;
//왼쪽으로 이동 할 수 있는 경우,
//왼쪽으로 이동 가능 길이를 늘려가며 저장,
//왼쪽이 T라면(T인 상태 : T이거나 왼쪽 방향에 T인 곳으로 갈 수 있다.) 이번도 T인 상태로.
for (int i = 1; i < n; i++) {
if (h[i] < h[i - 1]) continue;
if (t[i - 1] == 'T') t[i] = 'T';
moveL[i] = 1 + moveL[i - 1];
}
//오른쪽도 같다.
for (int i = n - 2; i >= 0; i--) {
if (h[i] < h[i + 1]) continue;
if (t[i + 1] == 'T') t[i] = 'T';
moveR[i] = 1 + moveR[i + 1];
}
//T의 갯수와, T가 없는 라인 중 최대 길이를 구한다.
int T = 0, best = 0;
for (int i = 0; i < n; i++) {
if (t[i] == 'T') T++;
else best = max(best, 1 + max(moveL[i], moveR[i]));
}
//시작 점이 T라는 것은, 시작점을 포함한 이어진 라인은 모두 갈 수 있으며
//점프를 통해 모든 T가 이어진 각각의 라인들을 갈 수 있다.
//=> T의 갯수 + T가 없는 라인의 최대 길이 출력
if (t[k] == 'T')
cout << T + best << endl;
//시작 점이 T가 아니라면, 시작점과 같은 높이의 양 끝 중 최대 이동 가능 + 같은높이 출력
else {
int l = k, r = k;
//좌우측으로 평행한 높이 까지는 갈 수 있으므로 계산해줌.
while (l > 0 && h[l - 1] == h[k]) l--;
while (r < n - 1 && h[r + 1] == h[k]) r++;
cout << r - l + 1 + max(moveL[l], moveR[r]) << endl;
}
system("pause");
return 0;
} | [
"kcjohnnykim@gmail.com"
] | kcjohnnykim@gmail.com |
8f624637052c326b4f0d7753ebbe225dbc5358b6 | c93a6079715259cfd8bfaf03aa154dc08c5de030 | /The third semester(Algorithms)/Segments tree/SegmentsTree.h | 8c10887cad3345b68e593d368c432e6cdc87893e | [] | no_license | VProv/University-Programming | d17dfb57cf4a22e0c7ce077e59673eb2c5a59820 | 303c33e08f80421dfc86ca2e6607f0a1174c9291 | refs/heads/master | 2022-09-25T20:47:37.113097 | 2017-04-30T22:16:16 | 2017-04-30T22:16:16 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,508 | h | #pragma once
// Класс решающий задачу нахождения 2й порядковой статистики на отрезке, с помощью дерева отрезков.
// Провилков Иван. гр.593.
#include <vector>
#include <cmath>
#include <algorithm>
using std::vector;
// Класс дерева отрезков.
class CSegmentsTree {
public:
// Вершинами нашего дерева будут структуры с двумя минимумами на отрезке.
// min1 <= min2.
struct node {
int min1;
int min2;
node( int _min1, int _min2 ) :min1(_min1),min2(_min2) {};
};
// Конструктор, строит дерево отрезков по заданному массиву a.
CSegmentsTree( vector<int>& a );
// Вычисляет 2ю порядковую статистику на отрезке от l до r.
int RMQUp( int l, int r );
private:
// Функция рекурсивного построения дерева отрезков.
void treeBuild( int i, int l, int r );
// Возвращает node с минимумами min1 и min2, из 2х node.
node myMin( const node& l, const node& r )const;
// Ссылка на входной массив с которым мы работаем.
vector<int>& arr;
// Вектор, содержащий наше дерево.
vector<node> tree;
const static int infinity = 100000000;
}; | [
"Иван Провилков"
] | Иван Провилков |
1de7260772b268794281891c133fe77caa0a5962 | f88d20202de8a9430886950b6efdc405057e1676 | /src/view/dicom2d/modalityproperty.h | 0c29b6afca904a44792aa502e4e7ad884946878c | [] | no_license | zhaohh1985/KISS-Dicom-Viewer | f8388fdc8c4948491eae7e092d4d4f689ff38bf3 | 2938d0af718d37703f2083d439c4f082d7753f77 | refs/heads/master | 2023-04-20T08:10:04.140316 | 2021-05-10T01:25:16 | 2021-05-10T01:25:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,717 | h | #ifndef MODALITYPROPERTY_H
#define MODALITYPROPERTY_H
#include <QList>
#include <QString>
#include <QXmlStreamReader>
#include "dcmtk/dcmdata/dctagkey.h"
#include <global/KissGlobal>
typedef struct AnnoItem {
QString text;
QList<DcmTagKey> keys;
} AnnoItem;
typedef struct AnnoItemGroup {
QString pos;
QList<AnnoItem *> items;
AnnoItemGroup() {}
~AnnoItemGroup() {
qDeleteAll(items);
}
private:
Q_DISABLE_COPY(AnnoItemGroup)
} AnnoItemGroup;
typedef struct ModalityPref {
double adjust_factor;
double zoom_factor;
double zoom_max;
double zoom_min;
double magnifier_inc;
double magnifier_max;
double magnifier_min;
ModalityPref(): adjust_factor(16.0), zoom_factor(0.02), zoom_max(32.0),
zoom_min(0.05), magnifier_inc(1.0), magnifier_max(32.0), magnifier_min(2.0) {}
} ModalityPref;
typedef struct ModalityProp {
QString name;
QList<AnnoItemGroup *> groups;
ModalityPref pref;
ModalityProp() {}
~ModalityProp() {
qDeleteAll(groups);
}
private:
Q_DISABLE_COPY(ModalityProp)
} ModalityProp;
class ModalityProperty {
public:
static ModalityProperty *Instance();
ModalityProperty();
~ModalityProperty();
const ModalityProp *getModalityProp(const QString &modality) const;
bool IsNormal() const;
QString ErrorStr() const;
void ReadProperty();
private:
void ReadModality(ModalityProp &m);
void ReadPref(ModalityPref &p);
void ReadAnnoGroup(AnnoItemGroup &g);
private:
static ModalityProperty *instance;
QXmlStreamReader m_xml_;
QList<ModalityProp *> m_props_;
Q_DISABLE_COPY(ModalityProperty)
};
#endif // MODALITYPROPERTY_H
| [
"779354187@qq.com"
] | 779354187@qq.com |
3adf4559dd481b3bcc910fcb74fe3e40f9fa82f0 | 93a0e82d8cc5695cf184dffb050e2f0fb755b41d | /dt_osx_cocoa/src/dt_sequencer.cpp | d742d9938a5d330c95d046d67f91fa27e0ac2174 | [] | no_license | hiroMTB/dt_ | 0119a70c6c79d020e0a0179fc217b76c5b1e383e | 3940e5db9622facc29536da6a702c7afa9c957f3 | refs/heads/master | 2020-06-06T18:53:03.138622 | 2014-09-26T19:15:15 | 2014-09-26T19:15:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,798 | cpp | //
// dt_sequencer.cpp
// dial_t
//
// Created by mtb on 5/5/14.
//
//
#include "dt_sequencer.h"
#include "dt_sequence_thread.h"
#include "ofApp.h"
#include "dt_rhythm_lib.h"
dt_sequencer::dt_sequencer()
:indicator(0),
bCounter_clockwise(true),
total_beats(-1),
rhythm_shape_type(0){
app = ofApp::getInstance();
beat_resolution = DT_BEAT_RESOLUTION;
}
void dt_sequencer::setup(float _total_beats){
total_beats = _total_beats;
total_steps = total_beats * beat_resolution;
}
void dt_sequencer::updateIndicator(){
updateIndicator(bCounter_clockwise);
}
void dt_sequencer::updateIndicator(bool forward){
if(forward){
indicator++;
if(indicator >= total_steps){
indicator = 0;
}
}else{
indicator--;
if (indicator >= total_steps) {
indicator = total_steps-1;
}
}
}
void dt_sequencer::setRhythmShape(int type){
int rsize = app->rhythm_lib.getRhythmSize(total_beats);
if(0 <= type){
rhythm_shape_type = type % rsize;
}else{
if(type%rsize == 0){
rhythm_shape_type = 0;
}else{
rhythm_shape_type = rsize + type%rsize;
}
}
}
void dt_sequencer::incRhythmShape(int n){
setRhythmShape(rhythm_shape_type + n);
}
int dt_sequencer::getCurrentBeat(){
return (indicator / beat_resolution);
}
bool dt_sequencer::isOnBeat(){
return indicator%beat_resolution == 0;
}
bool dt_sequencer::getDataFromBeat(int beat){
return app->rhythm_lib.getRhythm((int)total_beats, rhythm_shape_type)[beat];
}
bool dt_sequencer::getDataFromStep(int step){
int beat = step % beat_resolution;
if(beat == 0)
return getDataFromBeat(beat);
return false;
}
bool dt_sequencer::getDataNow(){
if(indicator%beat_resolution==0) {
return app->rhythm_lib.getRhythm((int)total_beats, rhythm_shape_type)[((int)indicator/beat_resolution)];
}
return false;
}
| [
"matobahiroshi@gmail.com"
] | matobahiroshi@gmail.com |
494eb724c1a16dc1788f3edef9a68788a8039cd2 | 5a79b4f2751e29d38cf72e988b7ae88e3089f766 | /src/ofxTILEvent.h | 6fb479d780ca4fb2f53a304633bd756dc401f1de | [] | no_license | armdz/ofxEventThreadedImageLoader | 5ff0b84221887fdebf01b9f5a12c5a4579dd9f60 | 99dc118f053fd1070cd571c2df7f824c48131fcd | refs/heads/master | 2020-03-18T02:09:47.177388 | 2019-06-22T21:48:51 | 2019-06-22T21:48:51 | 134,177,365 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 422 | h | //
// ofxTILEvent.h
//
// Created by lolo on 3/20/17.
//
//
#ifndef ofxTILEvent_h
#define ofxTILEvent_h
#include "ofMain.h"
// TIL is for ofxThreadedImageLoader
class ofxTILEvent : public ofEventArgs{
public:
ofxTILEvent()
{
loaded = false;
error_msg = "";
};
~ofxTILEvent()
{
};
bool loaded;
string error_msg;
static ofEvent <ofxTILEvent> events;
};
#endif /* ofxTILEvent_h */
| [
"lolo@armdz.com"
] | lolo@armdz.com |
c75b3fe0de4a4ba07dd6b7939503d03ac20ce324 | 0543967d1fcd1ce4d682dbed0866a25b4fef73fd | /Midterm/solutions/midterm2017_118/H/001287-midterm2017_118-H.cpp | 08f33cc6b766e869b16cbe8a2328e0825dfd3016 | [] | no_license | Beisenbek/PP12017 | 5e21fab031db8a945eb3fa12aac0db45c7cbb915 | 85a314d47cd067f4ecbbc24df1aa7a1acd37970a | refs/heads/master | 2021-01-19T18:42:22.866838 | 2017-11-25T12:13:24 | 2017-11-25T12:13:24 | 101,155,127 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 327 | cpp | #include <iostream>
#include <cmath>
using namespace std;
int main (){
int n,max=0,k=0;
cin >> n;
int a[n];
for (int i=0;i < n; i++){
cin >> a[i];
}
for (int i=0;i < n; i++){
if (a[i]>max){
max=a[i];
}
}
for (int i=0;i < n; i++){
if (a[i]==max){
k++;
}
}
cout <<k;
return 0;
}
| [
"beysenbek@gmail.com"
] | beysenbek@gmail.com |
814849850592b4992a5432d13ed983ccb1b1f6ca | 317b675cb5fb2b81903368ac65de2778025acc15 | /Contests/Div2_694/D.cpp | 5ad6e2ae4f8032fca439003dd5a58c8e62d69dd4 | [] | no_license | BarSaguy/Competitive-Programming | 7f795b12214677b4b00d51eb0270ac794f1656f9 | 7a8e62426c6d58a8214808ce8a1972ef3aeb80a6 | refs/heads/master | 2023-03-20T04:12:18.388238 | 2021-03-06T09:17:54 | 2021-03-06T09:17:54 | 307,996,119 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,071 | cpp | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define vi vector<int>
#define vvi vector<vi>
#define vvvi vector<vvi>
#define ii pair<int,int>
#define vii vector<ii>
#define pqi priority_queue<int>
#define pqii priority_queue<ii>
#define all(arr) arr.begin(), arr.end()
#define si stack<int>
#define qi queue<int>
#define GET_MACRO(_1,_2,_3,NAME,...) NAME
#define rep(...) GET_MACRO(__VA_ARGS__, rep3, rep2, rep1)(__VA_ARGS__)
#define rep1(n) for (int i = 0; i < (n); i++)
#define rep2(i, n) for (int i = 0; i < (n); i++)
#define rep3(i, s, n) for (int i = (s); i < (n); i++)
#define repr(...) GET_MACRO(__VA_ARGS__, repr3, repr2, repr1)(__VA_ARGS__)
#define repr1(n) for (int i = (n)-1; i >= 0; i--)
#define repr2(i, n) for (int i = (n)-1; i >= 0; i--)
#define repr3(i, n, s) for (int i = (n)-1; i >= (s); i--)
#define x first
#define y second
#define pb push_back
const int INF = 1e18;
void solve(){
}
int32_t main(){
// ios_base::sync_with_stdio(false); cin.tie(0);
int t=1;
//cin >> t;
while(t--) solve();
return 0;
} | [
"bar.saguy@gmail.com"
] | bar.saguy@gmail.com |
eb421fc722226a77c5cba8d308dc5f83f47a0464 | 6f506efdb1dd018767443229d96b51f1886ba269 | /doc/referece_code/camera/muonpath.h | 998794d7e0eb12d40fb3b9c7b113b5806cfab221 | [] | no_license | folguera/DTTrigger | 48ef4b3e06fbd9a25f7522ebe768f11aa218a1c9 | 1cb0c37b1761a0e2f9a8af0b4f2695ab453c22f1 | refs/heads/master | 2020-04-18T11:52:48.907384 | 2018-12-13T13:16:47 | 2018-12-13T13:16:47 | 167,515,824 | 0 | 0 | null | 2019-01-25T08:51:10 | 2019-01-25T08:50:59 | C++ | UTF-8 | C++ | false | false | 4,157 | h | /**
* Project:
* Subproject: tracrecons
* File name: muonpath.h
* Language: C++
*
* *********************************************************************
* Description:
*
*
* To Do:
*
* Author: Jose Manuel Cela <josemanuel.cela@ciemat.es>
*
* *********************************************************************
* Copyright (c) 2015-02-10 Jose Manuel Cela <josemanuel.cela@ciemat.es>
*
* For internal use, all rights reserved.
* *********************************************************************
*/
#ifndef MUONPATH_H
#define MUONPATH_H
#include "i_object.h"
#include "dtprimitive.h"
#include "cexception.h"
#include "analtypedefs.h"
using namespace CIEMAT;
namespace CMS {
class MuonPath : public I_Object {
public:
MuonPath(DTPrimitive *ptrPrimitive[4]) throw (CException);
MuonPath(MuonPath *ptr);
virtual ~MuonPath();
void setPrimitive(DTPrimitive *ptr, int layer) throw (CException);
DTPrimitive *getPrimitive(int layer);
void setCellHorizontalLayout(int layout[4]);
void setCellHorizontalLayout(const int *layout);
const int* getCellHorizontalLayout(void);
int getBaseChannelId(void);
void setBaseChannelId(int bch);
void setQuality(MP_QUALITY qty);
MP_QUALITY getQuality(void);
bool isEqualTo(MuonPath *ptr);
/* El MuonPath debe ser analizado si hay al menos 3 Primitivas válidas */
bool isAnalyzable(void);
/* Indica que hay 4 Primitivas con dato válido */
bool completeMP(void);
void setBxTimeValue(int time);
int getBxTimeValue(void);
int getBxNumId(void);
void setLateralComb(LATERAL_CASES latComb[4]);
void setLateralComb(const LATERAL_CASES *latComb);
const LATERAL_CASES* getLateralComb(void);
void setHorizPos(float pos);
float getHorizPos(void);
void setTanPhi(float tanPhi);
float getTanPhi(void);
void setChiSq(float chi);
float getChiSq(void);
void setXCoorCell(float x, int cell);
float getXCoorCell(int cell);
void setDriftDistance(float dx, int cell);
float getDriftDistance(int cell);
private:
//------------------------------------------------------------------
//--- Datos del MuonPath
//------------------------------------------------------------------
/*
Primitivas que forman el path. En posición 0 está el dato del canal de la
capa inferior, y de ahí hacia arriba. El orden es crítico.
*/
DTPrimitive *prim[4];
/* Posiciones horizontales de cada celda (una por capa), en unidades de
semilongitud de celda, relativas a la celda de la capa inferior
(capa 0). Pese a que la celda de la capa 0 siempre está en posición
0 respecto de sí misma, se incluye en el array para que el código que
hace el procesamiento sea más homogéneo y sencillo.
Estos parámetros se habían definido, en la versión muy preliminar del
código, en el 'PathAnalyzer'. Ahora se trasladan al 'MuonPath' para
que el 'PathAnalyzer' sea un único componente (y no uno por posible
ruta, como en la versión original) y se puede disponer en arquitectura
tipo pipe-line */
int cellLayout[4];
int baseChannelId;
//------------------------------------------------------------------
//--- Resultados tras cálculos
//------------------------------------------------------------------
/* Calidad del path */
MP_QUALITY quality;
/* Combinación de lateralidad */
LATERAL_CASES lateralComb[4];
/* Tiempo del BX respecto del BX0 de la órbita en curso */
int bxTimeValue;
/* Número del BX dentro de una órbita */
int bxNumId;
/* Parámetros de celda */
float xCoorCell[4]; // Posicion horizontal del hit en la cámara
float xDriftDistance[4]; // Distancia de deriva en la celda (sin signo)
/* Parámetros de trayectoria */
float tanPhi;
float horizPos;
/* Estimador de calidad de trayectoria */
float chiSquare;
};
}
#endif
| [
"ccarrillom@gmail.com"
] | ccarrillom@gmail.com |
228c342b15df7217fb1ab263c3345f333de8ea99 | 6e665dcd74541d40647ebb64e30aa60bc71e610c | /800/VPBX_Support/stacks/sipstack/ByeMsg.cxx | 0c2c742f12c4ba2fda4fbee52d3eab8a3ceab7b5 | [] | no_license | jacklee032016/pbx | b27871251a6d49285eaade2d0a9ec02032c3ec62 | 554149c134e50db8ea27de6a092934a51e156eb6 | refs/heads/master | 2020-03-24T21:52:18.653518 | 2018-08-04T20:01:15 | 2018-08-04T20:01:15 | 143,054,776 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,076 | cxx | /*
* $Log: ByeMsg.cxx,v $
* Revision 1.1.1.1 2006/11/30 16:27:09 lizhijie
* AS800 VPBX_Support
*
* Revision 1.1.1.1 2006/06/03 11:55:33 lizhijie
* build a independent directory for VPBX support libraris
*
* $Id: ByeMsg.cxx,v 1.1.1.1 2006/11/30 16:27:09 lizhijie Exp $
*/
#include "global.h"
#include "ByeMsg.hxx"
#include "SipAuthorization.hxx"
#include "SipContact.hxx"
#include "SipContentDisposition.hxx"
#include "SipEncryption.hxx"
#include "SipFrom.hxx"
#include "SipHide.hxx"
#include "SipMaxForwards.hxx"
#include "SipProxyAuthorization.hxx"
#include "SipProxyRequire.hxx"
#include "SipRequire.hxx"
#include "SipRecordRoute.hxx"
#include "SipRoute.hxx"
#include "SipVia.hxx"
#include "StatusMsg.hxx"
using namespace Assist;
//ByeMsg::ByeMsg(const SipCommand& ackCommand)
/* If this is the caller(issued INVITE, then the Bye Msg should be
sent to the Contact obtained in the 200 Status msg. If this is the
callee, then the Bye Msg should be sent to the Contact obtained in the
INVITE msg , or the ACK msg. It is up to the User Agent to send the
corrent SipMsg from which the Contact will be taken */
ByeMsg::ByeMsg() : SipCommand()
{
myRequestLine.setMethod(BYE_METHOD);
SipCSeq cseq( SIP_BYE, 0 );
setCSeq( cseq );
}
ByeMsg::ByeMsg(const ByeMsg& src) : SipCommand(src)
{
}
ByeMsg::ByeMsg(const SipCommand& src)
: SipCommand(src)
{
myRequestLine.setMethod(BYE_METHOD);
SipCSeq cseq = src.getCSeq();
int value = cseq.getCSeqData().convertInt();
value++;
SipCSeq newcseq(SIP_BYE, Data(value));
setCSeq(newcseq);
// Flip To & From when using ACK to generate BYE
const SipFrom& srcfrom = src.getFrom();
const SipTo& srcto = src.getTo();
//set the To header.
SipTo to(srcfrom.getUrl());
to.setDisplayName( srcfrom.getDisplayName() );
to.setTag( srcfrom.getTag() );
to.setToken( srcfrom.getToken() );
to.setQstring( srcfrom.getQstring() );
setTo(to);
//set the From header.
SipFrom from(srcto.getUrl());
from.setDisplayName( srcto.getDisplayName() );
from.setTag( srcto.getTag() );
from.setToken( srcto.getToken() );
from.setQstring( srcto.getQstring() );
setFrom(from);
}
ByeMsg::ByeMsg(const SipCommand& src, const SipVia& via, const SipCSeq& cseq)
: SipCommand(src, via, cseq)
{
myRequestLine.setMethod(BYE_METHOD);
}
ByeMsg::ByeMsg(const StatusMsg& statusMsg)
: SipCommand(statusMsg)
{
myRequestLine.setMethod(BYE_METHOD);
SipCSeq cseq = statusMsg.getCSeq();
int value = cseq.getCSeqData().convertInt();
value++;
SipCSeq newcseq(SIP_BYE, Data(value));
setCSeq(newcseq);
}
ByeMsg::ByeMsg(const ByeMsg& msg, enum ByeMsgForward)
{
*this = msg;
Sptr<BaseUrl> dest = getTo().getUrl();
int numRoute = getNumRoute();
if ( numRoute )
{
dest = getRoute(0).getUrl();
//remove that route.
removeRoute(0);
}
else
{
dest = getTo().getUrl();
}
myRequestLine.setUrl(dest);
}
ByeMsg& ByeMsg::operator=(const ByeMsg& src)
{
if ( &src != this)
{
*static_cast < SipCommand* > (this) = src;
}
return (*this);
}
bool ByeMsg::operator ==(const ByeMsg& src)
{
return ( *static_cast < SipCommand* > (this) == src);
}
ByeMsg::ByeMsg(const Data& data)
: SipCommand()
{
SipCommand::decode(data);
}
void ByeMsg::setByeDetails( const SipMsg& sipMessage)
{
// TODO: what should listenPort mean???
//We will use the default port:5060.
/*** swap from and to only if callee(got INVITE or ACK) . If
* caller, then don't swap */
//check the Url for the Method.
if ( dynamic_cast < const SipCommand* > (&sipMessage) )
{
const SipFrom& srcfrom = sipMessage.getFrom();
const SipTo& srcto = sipMessage.getTo();
//set the To header.
SipTo to(srcfrom.getUrl());
to.setDisplayName( srcfrom.getDisplayName() );
to.setTag( srcfrom.getTag() );
to.setToken( srcfrom.getToken() );
to.setQstring( srcfrom.getQstring() );
setTo(to);
//set the From header.
SipFrom from(srcto.getUrl());
from.setDisplayName( srcto.getDisplayName() );
from.setTag( srcto.getTag() );
from.setToken( srcto.getToken() );
from.setQstring( srcto.getQstring() );
setFrom(from);
}
else if ( dynamic_cast < const StatusMsg* > (&sipMessage) )
{
setTo(sipMessage.getTo());
setFrom(sipMessage.getFrom());
}
Sptr<BaseUrl> url = getTo().getUrl();
SipVia sipvia;
//create the via header. This contains details present in the toUrl.
Sptr <BaseUrl> toUrl = getFrom().getUrl();
//construct the request line.
SipRequestLine siprequestline(SIP_BYE, url);
setRequestLine(siprequestline);
//assign the CallId.
setCallId(sipMessage.getCallId());
//create the CSeq header
SipCSeq cseq = sipMessage.getCSeq();
int value = cseq.getCSeqData().convertInt();
//increment cseq.
value++;
SipCSeq newcseq(SIP_BYE, Data(value));
setCSeq(newcseq);
if ( dynamic_cast < const StatusMsg* > (&sipMessage) )
{
//construct the route list, based on the record route.
int numRecordRoute = sipMessage.getNumRecordRoute();
if (numRecordRoute)
{
for (int i = numRecordRoute - 1; i >= 0; i--)
// for(int i = 0; i < numRecordRoute; i++)
{
const SipRecordRoute& recordroute = sipMessage.getRecordRoute(i);
SipRoute route;
route.setUrl(recordroute.getUrl());
setRoute(route);
}
}
if (sipMessage.getNumContact() == 1)
{
SipRoute route;
route.setUrl(sipMessage.getContact().getUrl());
setRoute(route);
//remove the contact header.
setNumContact(0);
}
}
else
{
if ( dynamic_cast < const SipCommand* > (&sipMessage) )
{
//construct the route list, based on the record route.
int numRecordRoute = sipMessage.getNumRecordRoute();
if (numRecordRoute)
{
//for(int i = numRecordRoute-1; i >= 0; i--)
for (int i = 0 ; i < numRecordRoute; i++)
{
const SipRecordRoute& recordroute = sipMessage.getRecordRoute(i);
SipRoute route;
route.setUrl(recordroute.getUrl());
setRoute(route);
}
}
if (sipMessage.getNumContact() == 1)
{
SipRoute route;
route.setUrl(sipMessage.getContact().getUrl());
setRoute(route);
//remove the contact header.
setNumContact(0);
}
}
else
{
assert(0);
}
}
// set up the URI
Sptr <BaseUrl> dest;
dest = getTo().getUrl();
assert( getNumContact() == 0);
int numRoute = getNumRoute();
if (numRoute != 0 )
{
dest = getRoute(0).getUrl();
//remove that route.
removeRoute(0);
}
else
{
dest = getTo().getUrl();
}
setContentLength(ZERO_CONTENT_LENGTH);
myRequestLine.setUrl(dest);
//Set the transport of Request line.
sipvia.setprotoVersion("2.0");
if (toUrl.getPtr() != 0)
{
if (toUrl->getType() == SIP_URL)
{
Sptr<SipUrl> sipUrl;
sipUrl.dynamicCast(toUrl);
sipvia.setHost(sipUrl->getHost());
sipvia.setPort(sipUrl->getPort().convertInt());
if(myRequestLine.getTransportParam().length())
{
if(myRequestLine.getTransportParam() == "tcp")
{
sipvia.setTransport("TCP");
}
}
}
}
//add via to the top
setVia(sipvia, 0);
}
ByeMsg::~ByeMsg()
{}
Method ByeMsg::getType() const
{
return SIP_BYE;
}
| [
"jacklee032016@gmail.com"
] | jacklee032016@gmail.com |
c3211c7a8cbd7f9bb9e83fe658fdd9c74daccbad | a6a6eb1a0eb89287c92c2e9114987c115087da0b | /CPW/parallel_for.inl | 00841db5ac1dd5602e0272fda9c598dd147fa37a | [
"MIT"
] | permissive | jeffamstutz/CPW | 72de5007a047df42d325ff779c3f66d1824f8b7e | 0f703b2d969f13a1fb50f758b0d7b6c2b98fac6b | refs/heads/master | 2020-12-25T06:34:47.679730 | 2018-01-15T18:52:44 | 2018-01-15T18:52:44 | 59,922,104 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,029 | inl | // ========================================================================== //
// The MIT License (MIT) //
// //
// Copyright (c) 2016-2017 Jefferson Amstutz //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// in all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER //
// DEALINGS IN THE SOFTWARE. //
// ========================================================================== //
#pragma once
#include <utility>
#ifdef CPW_TASKING_TBB
# include <tbb/parallel_for.h>
#elif defined(CPW_TASKING_CILK)
# include <cilk/cilk.h>
#elif defined(CPW_TASKING_INTERNAL)
# include "ospcommon/tasking/TaskSys.h"
#endif
namespace CPW {
template<typename TASK_T>
inline void parallel_for_impl(int nTasks, TASK_T&& fcn)
{
#ifdef CPW_TASKING_TBB
tbb::parallel_for(0, nTasks, 1, fcn);
#elif defined(CPW_TASKING_CILK)
cilk_for (int taskIndex = 0; taskIndex < nTasks; ++taskIndex) {
fcn(taskIndex);
}
#elif defined(CPW_TASKING_OMP)
# pragma omp parallel for schedule(dynamic)
for (int taskIndex = 0; taskIndex < nTasks; ++taskIndex) {
fcn(taskIndex);
}
#elif defined(CPW_TASKING_INTERNAL)
struct LocalTask : public Task {
const TASK_T &t;
LocalTask(const TASK_T& fcn) : Task("LocalTask"), t(fcn) {}
void run(size_t taskIndex) override { t(taskIndex); }
};
Ref<LocalTask> task = new LocalTask(fcn);
task->scheduleAndWait(nTasks);
#else // Debug (no tasking system)
for (int taskIndex = 0; taskIndex < nTasks; ++taskIndex) {
fcn(taskIndex);
}
#endif
}
} // namespace CPW
| [
"jefferson.d.amstutz@intel.com"
] | jefferson.d.amstutz@intel.com |
f3e5829d3348680d3499ddaf3af1221c8c629572 | 40339ce37f9591d2d69828a120582628366f785f | /BabyUniverseRemover.cpp | 4f4f2e4976333936fca0dab4b3e7816d7b2f2903 | [] | no_license | tgbudd/DT | 2ab4104a9f0cee93327534e21f75df886ee746b5 | bd552b750f6b95dcd75094394ee47b842346a056 | refs/heads/master | 2021-05-01T10:29:30.865548 | 2016-11-08T14:37:08 | 2016-11-08T14:39:40 | 22,206,308 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,906 | cpp | #include <map>
#include <queue>
#include "BabyUniverseRemover.h"
#include "Vertex.h"
#include "Edge.h"
BabyUniverseRemover::BabyUniverseRemover(Triangulation * triangulation)
: triangulation_(triangulation),
cohomologybasis_(NULL),
genus_(triangulation_->CalculateGenus())
{
}
BabyUniverseRemover::BabyUniverseRemover(Triangulation * triangulation, CohomologyBasis * cohomologybasis)
: triangulation_(triangulation),
cohomologybasis_(cohomologybasis),
genus_(triangulation_->CalculateGenus())
{
}
void BabyUniverseRemover::RemoveBabyUniverses(Triangle * triangle)
{
if( genus_ == 0 )
{
RemoveBabyUniversesSpherical(triangle);
} else
{
RemoveBabyUniversesHigherGenus();
}
}
void BabyUniverseRemover::RemoveBabyUniversesSpherical(Triangle * triangle)
{
// Identify all pairs of edges that form a neck of length 2
std::vector<boost::array<Edge *,3> > newNbr(triangulation_->NumberOfTriangles());
for(int i=0;i<triangulation_->NumberOfVertices();i++)
{
Vertex * vertex = triangulation_->getVertex(i);
std::map<Vertex*,Edge*> edgeToVertex;
Edge * edge = vertex->getParent()->getPrevious();
bool firstround = true;
while(true)
{
if( edge->getPrevious()->getOpposite() == vertex )
{
newNbr[edge->getParent()->getId()][edge->getId()] = edge->getAdjacent();
} else
{
std::pair<std::map<Vertex*,Edge*>::iterator,bool> ret = edgeToVertex.insert(std::pair<Vertex*,Edge*>(edge->getPrevious()->getOpposite(),edge));
if( !ret.second )
{
newNbr[ret.first->second->getAdjacent()->getParent()->getId()][ret.first->second->getAdjacent()->getId()] = edge;
newNbr[edge->getParent()->getId()][edge->getId()] = ret.first->second->getAdjacent();
ret.first->second = edge;
}
}
edge = edge->getAdjacent()->getNext();
if( edge == vertex->getParent()->getPrevious() )
{
if( firstround )
{
firstround = false;
} else
{
break;
}
}
}
}
bool useLargest = ( triangle == NULL );
// Determine largest component
std::vector<int> flag(triangulation_->NumberOfTriangles(),-1);
int largest = 0;
int largestFlag = 0;
std::queue<Triangle *> q;
for(int i=0;i<triangulation_->NumberOfTriangles();i++)
{
if( flag[i] != -1 )
continue;
int size = 0;
q.push(triangulation_->getTriangle(i));
flag[i] = i;
while( !q.empty() )
{
Triangle * t = q.front();
q.pop();
if( !useLargest && t == triangle )
{
largestFlag = flag[t->getId()];
}
size++;
for(int j=0;j<3;j++)
{
Triangle * nbr = newNbr[t->getId()][j]->getParent();
BOOST_ASSERT( flag[nbr->getId()] == -1 || flag[nbr->getId()] == i );
if( flag[nbr->getId()] == -1 )
{
flag[nbr->getId()] = i;
q.push(nbr);
}
}
}
if( useLargest && size > largest )
{
largest = size;
largestFlag = i;
}
}
// Update neighbour info
for(int i=0;i<triangulation_->NumberOfTriangles();i++)
{
Triangle * triangle = triangulation_->getTriangle(i);
if( flag[i] == largestFlag )
{
for(int j=0;j<3;j++)
{
triangle->getEdge(j)->setAdjacent(newNbr[i][j]);
}
}
}
// Delete all triangles that do not have flag=largestFlag
std::vector<Triangle *> tmpTriangles;
for(int i=0;i<triangulation_->NumberOfTriangles();i++)
{
tmpTriangles.push_back(triangulation_->getTriangle(i));
}
for(int i=0,endi=tmpTriangles.size();i<endi;i++)
{
if( flag[i] != largestFlag )
{
triangulation_->DeleteTriangle(tmpTriangles[i]);
}
}
triangulation_->DetermineVertices();
}
void BabyUniverseRemover::RemoveBabyUniversesHigherGenus()
{
// Identify all pairs of edges that form a neck of length 2
std::vector<boost::array<Edge *,3> > newNbr(triangulation_->NumberOfTriangles());
for(int i=0;i<triangulation_->NumberOfVertices();i++)
{
Vertex * vertex = triangulation_->getVertex(i);
std::map<std::pair<IntForm2D,Vertex*>,Edge*> edgeToVertex;
Edge * edge = vertex->getParent()->getPrevious();
bool firstround = true;
while(true)
{
if( edge->getPrevious()->getOpposite() == vertex )
{
newNbr[edge->getParent()->getId()][edge->getId()] = edge->getAdjacent();
} else
{
IntForm2D form = cohomologybasis_->getOmega(edge);
std::pair<std::map<std::pair<IntForm2D,Vertex*>,Edge*>::iterator,bool> ret = edgeToVertex.insert(std::pair<std::pair<IntForm2D,Vertex*>,Edge*>(std::pair<IntForm2D,Vertex*>(form,edge->getPrevious()->getOpposite()),edge));
if( !ret.second )
{
newNbr[ret.first->second->getAdjacent()->getParent()->getId()][ret.first->second->getAdjacent()->getId()] = edge;
newNbr[edge->getParent()->getId()][edge->getId()] = ret.first->second->getAdjacent();
ret.first->second = edge;
}
}
edge = edge->getAdjacent()->getNext();
if( edge == vertex->getParent()->getPrevious() )
{
if( firstround )
{
firstround = false;
} else
{
break;
}
}
}
}
// Update neighbour info
for(int i=0;i<triangulation_->NumberOfTriangles();i++)
{
Triangle * triangle = triangulation_->getTriangle(i);
for(int j=0;j<3;j++)
{
triangle->getEdge(j)->setAdjacent(newNbr[i][j]);
}
}
triangulation_->DetermineVertices();
// Determine which component is the torus
std::vector<int> flag(triangulation_->NumberOfTriangles(),-1);
std::vector<int> visited(triangulation_->NumberOfVertices(),false);
int torusFlag = 0;
std::queue<Triangle *> q;
for(int i=0;i<triangulation_->NumberOfTriangles();i++)
{
if( flag[i] != -1 )
continue;
int nTriangles = 0;
int nVertices = 0;
q.push(triangulation_->getTriangle(i));
flag[i] = i;
while( !q.empty() )
{
Triangle * t = q.front();
q.pop();
nTriangles++;
for(int j=0;j<3;j++)
{
Vertex * vertex = t->getEdge(j)->getOpposite();
if( !visited[vertex->getId()] )
{
visited[vertex->getId()] = true;
nVertices++;
}
Triangle * nbr = t->getEdge(j)->getAdjacent()->getParent();
BOOST_ASSERT( flag[nbr->getId()] == -1 || flag[nbr->getId()] == i );
if( flag[nbr->getId()] == -1 )
{
flag[nbr->getId()] = i;
q.push(nbr);
}
}
}
BOOST_ASSERT( nTriangles - 2 * nVertices == 0 || nTriangles - 2 * nVertices == -4 );
if( nTriangles - 2 * nVertices == 0 )
{
torusFlag = i;
break;
}
}
// Delete all triangles that do not have flag=torusFlag
std::vector<Triangle *> tmpTriangles;
for(int i=0;i<triangulation_->NumberOfTriangles();i++)
{
tmpTriangles.push_back(triangulation_->getTriangle(i));
}
for(int i=0,endi=tmpTriangles.size();i<endi;i++)
{
if( flag[i] != torusFlag )
{
triangulation_->DeleteTriangle(tmpTriangles[i]);
}
}
triangulation_->DetermineVertices();
} | [
"timothygbudd@gmail.com"
] | timothygbudd@gmail.com |
ac2b7423bc672969172d6c0890e9d17e81111ea8 | a0be71e84272af17e3f9c71b182f782c35a56974 | /Inspection/App/AppInspectionPy.cpp | f5adb3c14d8367d108ff167c3b6ebe6449cf062f | [] | no_license | PrLayton/SeriousFractal | 52e545de2879f7260778bb41ac49266b34cec4b2 | ce3b4e98d0c38fecf44d6e0715ce2dae582c94b2 | refs/heads/master | 2021-01-17T19:26:33.265924 | 2016-07-22T14:13:23 | 2016-07-22T14:13:23 | 60,533,401 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,902 | cpp | /***************************************************************************
* Copyright (c) YEAR YOUR NAME <Your e-mail address> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <Python.h>
#include <Base/Console.h>
#include <Base/PyObjectBase.h>
#include <Base/Exception.h>
/* registration table */
struct PyMethodDef Inspection_methods[] = {
{NULL, NULL} /* end of table marker */
};
| [
"gogokoko3@hotmail.fr"
] | gogokoko3@hotmail.fr |
bb55149e0b7686fba6e50f7fb0b89871811eca24 | 8734b6d1fffc077dbb6b351c794e1557f134ab2e | /Game/SNPC.cpp | c91322b3f8f8b86952bb220ffc91030a10ada517 | [] | no_license | hixio-mh/Sung | 2a23c8c96e75f95c203c28afc9e6485fc84d0c46 | 384e601ea47432a4a263bb4d646fc835a7c888e8 | refs/heads/master | 2021-06-04T23:41:36.928822 | 2012-10-14T08:06:40 | 2012-10-14T08:07:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 575 | cpp | //
// SNPC.cpp
//
#include "SNPC.h"
using namespace Sung;
//----------------------------------------------------------------------------
NPC::NPC()
{
mID = 0;
}
//----------------------------------------------------------------------------
NPC::NPC(int ID)
{
mID = ID;
}
//----------------------------------------------------------------------------
NPC::NPC(const NPC &npc)
{
(*this) = npc;
}
//----------------------------------------------------------------------------
NPC::~NPC()
{
}
//---------------------------------------------------------------------------- | [
"realmany@163.com"
] | realmany@163.com |
7eb649a30f2955fe2c63617cdb4ecbdf89028369 | 82091fc56c850906f3a36e8cb20fbb69c9b50e96 | /ucm/NetCmdServer.cpp | c8036117a5f5a057f61e763aeb016a8800ba96a4 | [
"MIT"
] | permissive | inbei/libutl | 97a57b865b4ab2331d66545fa2bb48ddf928ac2b | e55c2af091ba1101a1d0608db2830e279ec95d16 | refs/heads/master | 2023-07-22T15:35:51.113701 | 2021-08-26T09:28:22 | 2021-08-26T09:28:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 838 | cpp | #include <libutl/libutl.h>
#include <libutl/LogMgr.h>
#include <libutl/NetCmdServer.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
UTL_CLASS_IMPL_ABC(utl::NetCmdServer);
////////////////////////////////////////////////////////////////////////////////////////////////////
UTL_NS_BEGIN;
////////////////////////////////////////////////////////////////////////////////////////////////////
void
NetCmdServer::clientReadMsg(NetServerClient* client)
{
SCOPE_FAIL
{
clientDisconnect(client);
};
Array cmd;
cmd.serializeIn(client->socket());
if (cmd.empty())
{
throw StreamSerializeEx();
}
handleCmd(client, cmd);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
UTL_NS_END;
| [
"prof.hate@gmail.com"
] | prof.hate@gmail.com |
7d1694f34fc562b663f1ae0a7860feff03274d28 | 482891b0c9b2a023a447d88c5ae70a7ce198c7ac | /StRoot/StTriggerUtilities/StDSMUtilities/y2013/DSMAlgo_EE001_2013.cc | 07dd29af06d1292c314e2385cf3d617b4ba07c10 | [
"MIT"
] | permissive | xiaohaijin/RHIC-STAR | 7aed3075035f4ceaba154718b0660c74c1355a82 | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | refs/heads/master | 2020-03-28T12:31:26.190991 | 2018-10-28T16:07:06 | 2018-10-28T16:07:06 | 148,306,863 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 866 | cc | #include "../DSM.hh"
#include "../sumTriggerPatchChannels.hh"
#include "DSMAlgo_EE001_2013.hh"
void DSMAlgo_EE001_2013::operator()(DSM& dsm)
{
// INPUT:
// 10 x 12-bit EEMC channels
// (0-5) high tower
// (6-11) trigger patch
// REGISTERS:
// R0: EEMC-High-Tower-Th0 (6)
// R1: EEMC-High-Tower-Th1 (6)
// ACTION:
int lowEtaSum = 0;
int highEtaSum = 0;
int highTowerBits = 0;
// Args: dsm, chMin, chMax, step, targetPedestal, sum, highTowerBits
sumTriggerPatchChannels(dsm, 0, 8, 2, 3, lowEtaSum, highTowerBits);
sumTriggerPatchChannels(dsm, 1, 9, 2, 2, highEtaSum, highTowerBits);
// OUTPUT (14):
// (0-5) TP sum for low-eta group (6)
// (6-11) TP sum for high-eta group (6)
// (12-13) HT bits (2)
int out = 0;
out |= lowEtaSum;
out |= highEtaSum << 6;
out |= highTowerBits << 12;
dsm.output = out;
}
| [
"xiaohaijin@outlook.com"
] | xiaohaijin@outlook.com |
b633881df65e3e3988331be96829c699a90f7e2d | 1463abcfbe949dcf409613518ea8fc0815499b7b | /libs/algorithm/test/find_if.cpp | 45552b0f9536661321f70d424e25d0587ba62617 | [
"BSL-1.0"
] | permissive | osyo-manga/Sprout | d445c0d2e59a2e32f91c03fceb35958dcfb2c0ce | 8885b115f739ef255530f772067475d3bc0dcef7 | refs/heads/master | 2021-01-18T11:58:21.604326 | 2013-04-09T10:27:06 | 2013-04-09T10:27:06 | 4,191,046 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,936 | cpp | #ifndef SPROUT_LIBS_ALGORITHM_TEST_FIND_IF_CPP
#define SPROUT_LIBS_ALGORITHM_TEST_FIND_IF_CPP
#include <sprout/algorithm/find_if.hpp>
#include <sprout/array.hpp>
#include <sprout/container.hpp>
#include <testspr/tools.hpp>
namespace testspr {
static void algorithm_find_if_test() {
using namespace sprout;
{
SPROUT_STATIC_CONSTEXPR auto arr1 = array<int, 10>{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}};
{
SPROUT_STATIC_CONSTEXPR auto found = sprout::find_if(
sprout::begin(arr1),
sprout::end(arr1),
testspr::greater_than<int>(7)
);
TESTSPR_BOTH_ASSERT(found == sprout::begin(arr1) + 7);
}
{
SPROUT_STATIC_CONSTEXPR auto found = sprout::find_if(
sprout::begin(arr1),
sprout::end(arr1),
testspr::greater_than<int>(10)
);
TESTSPR_BOTH_ASSERT(found == sprout::end(arr1));
}
{
SPROUT_STATIC_CONSTEXPR auto found = sprout::find_if(
sprout::begin(arr1),
sprout::begin(arr1) + 5,
testspr::greater_than<int>(7)
);
TESTSPR_BOTH_ASSERT(found == sprout::begin(arr1) + 5);
}
{
SPROUT_STATIC_CONSTEXPR auto found = sprout::find_if(
sprout::begin(arr1),
sprout::begin(arr1) + 5,
testspr::greater_than<int>(10)
);
TESTSPR_BOTH_ASSERT(found == sprout::begin(arr1) + 5);
}
{
SPROUT_STATIC_CONSTEXPR auto found = sprout::find_if(
testspr::reduct_input(sprout::begin(arr1)),
testspr::reduct_input(sprout::end(arr1)),
testspr::greater_than<int>(7)
).base();
TESTSPR_BOTH_ASSERT(found == sprout::begin(arr1) + 7);
}
{
SPROUT_STATIC_CONSTEXPR auto found = sprout::find_if(
testspr::reduct_input(sprout::begin(arr1)),
testspr::reduct_input(sprout::end(arr1)),
testspr::greater_than<int>(10)
).base();
TESTSPR_BOTH_ASSERT(found == sprout::end(arr1));
}
{
SPROUT_STATIC_CONSTEXPR auto found = sprout::find_if(
testspr::reduct_input(sprout::begin(arr1)),
testspr::reduct_input(sprout::begin(arr1) + 5),
testspr::greater_than<int>(7)
).base();
TESTSPR_BOTH_ASSERT(found == sprout::begin(arr1) + 5);
}
{
SPROUT_STATIC_CONSTEXPR auto found = sprout::find_if(
testspr::reduct_input(sprout::begin(arr1)),
testspr::reduct_input(sprout::begin(arr1) + 5),
testspr::greater_than<int>(10)
).base();
TESTSPR_BOTH_ASSERT(found == sprout::begin(arr1) + 5);
}
#if defined(__clang__)
{
SPROUT_STATIC_CONSTEXPR auto found = sprout::find_if(
testspr::reduct_random_access(sprout::begin(arr1)),
testspr::reduct_random_access(sprout::end(arr1)),
testspr::greater_than<int>(7)
).base();
TESTSPR_BOTH_ASSERT(found == sprout::begin(arr1) + 7);
}
{
SPROUT_STATIC_CONSTEXPR auto found = sprout::find_if(
testspr::reduct_random_access(sprout::begin(arr1)),
testspr::reduct_random_access(sprout::end(arr1)),
testspr::greater_than<int>(10)
).base();
TESTSPR_BOTH_ASSERT(found == sprout::end(arr1));
}
{
SPROUT_STATIC_CONSTEXPR auto found = sprout::find_if(
testspr::reduct_random_access(sprout::begin(arr1)),
testspr::reduct_random_access(sprout::begin(arr1) + 5),
testspr::greater_than<int>(7)
).base();
TESTSPR_BOTH_ASSERT(found == sprout::begin(arr1) + 5);
}
{
SPROUT_STATIC_CONSTEXPR auto found = sprout::find_if(
testspr::reduct_random_access(sprout::begin(arr1)),
testspr::reduct_random_access(sprout::begin(arr1) + 5),
testspr::greater_than<int>(10)
).base();
TESTSPR_BOTH_ASSERT(found == sprout::begin(arr1) + 5);
}
#endif
}
}
} // namespace testspr
#ifndef TESTSPR_CPP_INCLUDE
# define TESTSPR_TEST_FUNCTION testspr::algorithm_find_if_test
# include <testspr/include_main.hpp>
#endif
#endif // #ifndef SPROUT_LIBS_ALGORITHM_TEST_FIND_IF_CPP
| [
"bolero.murakami@gmail.com"
] | bolero.murakami@gmail.com |
42c5bea02aa02f4baa1407e87896781b0928c924 | ba0cbdae81c171bd4be7b12c0594de72bd6d625a | /MyToontown/Panda3D-1.9.0/include/lwoBoundingBox.h | a9d4b822119d576a1f552db4d6cbfd1544e1266c | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | sweep41/Toontown-2016 | 65985f198fa32a832e762fa9c59e59606d6a40a3 | 7732fb2c27001264e6dd652c057b3dc41f9c8a7d | refs/heads/master | 2021-01-23T16:04:45.264205 | 2017-06-04T02:47:34 | 2017-06-04T02:47:34 | 93,279,679 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,600 | h | // Filename: lwoBoundingBox.h
// Created by: drose (24Apr01)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#ifndef LWOBOUNDINGBOX_H
#define LWOBOUNDINGBOX_H
#include "pandatoolbase.h"
#include "lwoChunk.h"
#include "luse.h"
////////////////////////////////////////////////////////////////////
// Class : LwoBoundingBox
// Description : Stores the bounding box for the vertex data in a
// layer. Optional.
////////////////////////////////////////////////////////////////////
class LwoBoundingBox : public LwoChunk {
public:
LVecBase3 _min;
LVecBase3 _max;
public:
virtual bool read_iff(IffInputFile *in, size_t stop_at);
virtual void write(ostream &out, int indent_level = 0) const;
public:
virtual TypeHandle get_type() const {
return get_class_type();
}
virtual TypeHandle force_init_type() {init_type(); return get_class_type();}
static TypeHandle get_class_type() {
return _type_handle;
}
static void init_type() {
LwoChunk::init_type();
register_type(_type_handle, "LwoBoundingBox",
LwoChunk::get_class_type());
}
private:
static TypeHandle _type_handle;
};
#endif
| [
"sweep14@gmail.com"
] | sweep14@gmail.com |
455ce31ce7424bebda4457ac0b7045f5dd11aa86 | aae110c027f85e0ed999bf3942cb0efa9b31d923 | /gautam-gupta-1322_Gautam/vignere cipher/solution.cpp | 44e5d4d83042a3e66b697f1ad2aaab9450b6269b | [] | no_license | akshit-g/21DaysOfCode-2021 | bc7373d3155b5bdcf12b470c1d5687c58b5ab23d | f61fd81b07f323a297e11e2b849ccf9f80fbe55e | refs/heads/master | 2023-06-20T09:51:02.654194 | 2021-07-07T08:47:33 | 2021-07-07T08:47:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,468 | cpp | #include<stdio.h>
#include<string.h>
int main()
{
char pt[100],k[20],rk[100],ct[100],ch;
int i,j,c,x,y;
printf("Enter the plain text -> ");
scanf("%[^\n]s",pt);
printf("\nEnter key -> ");
scanf(" %[^\n]s",k);
x=strlen(pt);
y=strlen(k);
for(i=0,j=0;i<=x;i++,j++)
{
{
if(i==x)
{
rk[i]=0;
break;
}
else if(pt[i]==' ')
{
rk[i]=' ';
j--;
continue;
}
else
{
rk[i]=k[j];
}
}
if(j==y-1)
j=-1;
}
printf("\nDo you want to encrypt(e) or decrypt(d) -> ");
scanf(" %c",&ch);
if(ch=='e')
{
for(i=0;i<=x;i++)
{
c=(pt[i]-97)+(rk[i]-97);
if(c>=26)
c=c-26;
if(pt[i]==' ')
ct[i]=' ';
else if(i==x)
ct[i]=0;
else
ct[i]=c+97;
}
printf("\nCipher text -> %s",ct);
}
else
{
for(i=0;i<=x;i++)
{
c=(pt[i]-97)-(rk[i]-97);
if(c<0)
c=c+26;
if(c>=26)
c=c-26;
if(pt[i]==' ')
ct[i]=' ';
else if(i==x)
ct[i]=0;
else
ct[i]=c+97;
}
printf("\ndecrypted text -> %s",ct);
}
return 0;
} | [
"gautamgupta2001dec@gmail.com"
] | gautamgupta2001dec@gmail.com |
de22dd6460475084c49af965259bf17d60585710 | c3805708c63d3dd3a7a85e02fc2535b39fc0a7fa | /src/placement/persistent_constraint_updater.cpp | 8ef58691290a77e58183b9928f5ea6e4a9467095 | [
"MIT"
] | permissive | Christof/voly-labeller | 68c49424bfd56cb3190c003b00d3dc52d83b9eb0 | 68ddb4681b200aac7f7cf6a328ac42e3562257ec | refs/heads/master | 2021-01-19T18:38:46.504357 | 2017-05-28T15:36:41 | 2017-05-28T20:07:43 | 31,907,641 | 3 | 0 | null | 2017-05-28T20:07:44 | 2015-03-09T15:51:50 | C++ | UTF-8 | C++ | false | false | 2,045 | cpp | #include "./persistent_constraint_updater.h"
#include <QLoggingCategory>
#include <chrono>
#include <vector>
#include "./constraint_updater.h"
QLoggingCategory pcuChan("Placement.PersistentConstraintUpdater");
PersistentConstraintUpdater::PersistentConstraintUpdater(
std::shared_ptr<ConstraintUpdater> constraintUpdater)
: constraintUpdater(constraintUpdater)
{
}
void PersistentConstraintUpdater::setAnchorPositions(
std::vector<Eigen::Vector2f> anchorPositions)
{
this->anchorPositions = anchorPositions;
}
void PersistentConstraintUpdater::updateConstraints(
int labelId, Eigen::Vector2i anchorForBuffer,
Eigen::Vector2i labelSizeForBuffer)
{
auto startTime = std::chrono::high_resolution_clock::now();
constraintUpdater->clear();
constraintUpdater->drawRegionsForAnchors(anchorPositions, labelSizeForBuffer);
for (auto &placedLabelPair : placedLabels)
{
auto &placedLabel = placedLabelPair.second;
constraintUpdater->drawConstraintRegionFor(
anchorForBuffer, labelSizeForBuffer, placedLabel.anchorPosition,
placedLabel.labelPosition, placedLabel.size);
}
constraintUpdater->finish();
if (saveConstraints)
constraintUpdater->save("constraints_" + std::to_string(index++) + "_" +
std::to_string(labelId) + ".png");
placedLabels[labelId] = PlacedLabelInfo{ labelSizeForBuffer, anchorForBuffer,
Eigen::Vector2i(-1, -1) };
auto endTime = std::chrono::high_resolution_clock::now();
std::chrono::duration<float, std::milli> diff = endTime - startTime;
qCDebug(pcuChan) << "updateConstraints took" << diff.count() << "ms";
}
void PersistentConstraintUpdater::setPosition(int labelId,
Eigen::Vector2i position)
{
placedLabels[labelId].labelPosition = position;
}
void PersistentConstraintUpdater::clear()
{
saveConstraints = false;
index = 0;
placedLabels.clear();
}
void PersistentConstraintUpdater::save()
{
saveConstraints = true;
}
| [
"christof.sirk@gmail.com"
] | christof.sirk@gmail.com |
d093e29d3ba98ca8fcefad46642140fc42441019 | 27bb5ed9eb1011c581cdb76d96979a7a9acd63ba | /aws-cpp-sdk-glacier/source/model/SetVaultNotificationsRequest.cpp | 018434c03f2cc3e4c6e103c1541537a205550f56 | [
"Apache-2.0",
"JSON",
"MIT"
] | permissive | exoscale/aws-sdk-cpp | 5394055f0876a0dafe3c49bf8e804d3ddf3ccc54 | 0876431920136cf638e1748d504d604c909bb596 | refs/heads/master | 2023-08-25T11:55:20.271984 | 2017-05-05T17:32:25 | 2017-05-05T17:32:25 | 90,744,509 | 0 | 0 | null | 2017-05-09T12:43:30 | 2017-05-09T12:43:30 | null | UTF-8 | C++ | false | false | 1,220 | cpp | /*
* Copyright 2010-2016 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.
*/
#include <aws/glacier/model/SetVaultNotificationsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Glacier::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
SetVaultNotificationsRequest::SetVaultNotificationsRequest() :
m_accountIdHasBeenSet(false),
m_vaultNameHasBeenSet(false),
m_vaultNotificationConfigHasBeenSet(false)
{
}
Aws::String SetVaultNotificationsRequest::SerializePayload() const
{
JsonValue payload;
if(m_vaultNotificationConfigHasBeenSet)
{
payload = m_vaultNotificationConfig.Jsonize();
}
return payload.WriteReadable();
}
| [
"henso@amazon.com"
] | henso@amazon.com |
803135551a01d4e642dbd43ab5e292d6dca9d9b9 | 8cee573229f7d946569059ed0c1a3dcb29f132dd | /Common/userconsumer.cpp | 986b1d93c0be8e6cc7781f512d1d18fa487827e6 | [] | no_license | tokiInBUPT/xshop | e9b0af98a87cccef66cfd4eeb2a5c56e67707fda | e5015cc9c5b821ac33bdf737dd06f4954a2f649f | refs/heads/main | 2023-06-28T07:13:54.869327 | 2021-05-26T16:13:33 | 2021-05-26T16:13:33 | 389,967,774 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 122 | cpp | #include "userconsumer.h"
UserConsumer::UserConsumer()
{
}
USERTYPE UserConsumer::getUserType()
{
return CONSUMER;
} | [
"7547189+xytoki@users.noreply.github.com"
] | 7547189+xytoki@users.noreply.github.com |
8085aa753cab678c0eee301ca6c2f4a8a4c78170 | 5c07f1efece21e2a7ad6508b1df3b29072ce9ac7 | /RTSproj/Source/RTSproj/ChaseAndShootFugitive.cpp | ad9c8826280a523bc79d0766afd703c1d8b5a107 | [] | no_license | mosipa/RTSproj | bc18145bdbf08e0ca794d1803a051848f3e485c8 | bae534ac5917a5bd3db802099eccb9dc348727af | refs/heads/master | 2020-04-07T07:43:39.704396 | 2019-03-05T17:34:14 | 2019-03-05T17:34:14 | 158,186,510 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,762 | cpp | // MOsipa 2018
#include "ChaseAndShootFugitive.h"
#include "EnemyAIController.h"
#include "AIModule/Classes/BehaviorTree/BlackboardComponent.h"
#include "Engine/Classes/GameFramework/CharacterMovementComponent.h"
#include "RTSEnemyUnit.h"
#include "Engine/Classes/Kismet/KismetMathLibrary.h"
#include "AIModule/Classes/Blueprint/AIBlueprintHelperLibrary.h"
#include "RTSPlayerUnit.h"
#include "MyMathClass.h"
EBTNodeResult::Type UChaseAndShootFugitive::ExecuteTask(UBehaviorTreeComponent & OwnerComp, uint8 * NodeMemory)
{
BlackboardComponent = OwnerComp.GetBlackboardComponent();
Pawn = Cast<AEnemyAIController>(OwnerComp.GetOwner())->GetPawn();
if (!Pawn) { return EBTNodeResult::Failed; }
auto Target = Cast<ARTSPlayerUnit>(BlackboardComponent->GetValueAsObject("PlayerUnitKey"));
FVector TargetLocation = Target->GetActorLocation();
float Distance = MyMathClass::GetDistance(Pawn->GetActorLocation(), TargetLocation);
//Start chasing fugitive
UAIBlueprintHelperLibrary::SimpleMoveToLocation(Cast<AEnemyAIController>(OwnerComp.GetOwner()), TargetLocation);
//If close enough start shooting
//TODO shooting = 100% death of unit - make some sort of adjustment so playerunit has a chance to survive
if (Distance <= 400.f)
{
BlackboardComponent->SetValueAsBool("PlayerInRange", true);
}
else
{
BlackboardComponent->SetValueAsBool("PlayerInRange", false);
}
bool bInRange = BlackboardComponent->GetValueAsBool("PlayerInRange");
bool bInSight = BlackboardComponent->GetValueAsBool("PlayerInSight");
if (bInSight && bInRange && !Target->IsCharacterInBuilding())
{
//Rotate AI to face Enemy
FRotator BodyRotation = UKismetMathLibrary::FindLookAtRotation(Pawn->GetActorLocation(), Target->GetActorLocation());
Pawn->SetActorRotation(BodyRotation);
Pawn->GetMovementComponent()->StopMovementImmediately();
//Shooting
Cast<ARTSEnemyUnit>(Pawn)->Shoot();
}
else if (!bInSight)
{
BlackboardComponent->SetValueAsVector("LastKnownLocation", Target->GetActorLocation());
BlackboardComponent->SetValueAsBool("LocationIsSet", true);
BlackboardComponent->ClearValue("PlayerUnitKey");
}
//If fugitive dies clear all keys
//Or it enters building
if (Target->IsCharacterDead()
|| Target->IsCharacterInBuilding())
{
BlackboardComponent->ClearValue("PlayerUnitKey");
BlackboardComponent->ClearValue("PlayerUnitOnMove");
BlackboardComponent->ClearValue("LastKnownLocation");
BlackboardComponent->ClearValue("PlayerInRange");
BlackboardComponent->ClearValue("PlayerInSight");
BlackboardComponent->ClearValue("LocationIsSet");
//Additionaly if player's unit died - call off alarm
if (Target->IsCharacterDead())
{
BlackboardComponent->ClearValue("Alarm");
}
}
return EBTNodeResult::Succeeded;
} | [
"manisiek@gmail.com"
] | manisiek@gmail.com |
1b1992d50671e105143907362da0bacb36172805 | 5d6da72796ea590ed23128340f29bce89c7ad0e2 | /test dll/test.h | 5f53927bd62a413012a64af64134fa8323d33a41 | [] | no_license | svaningelgem/RE | 83fc283092c38a48f8853b1db4043e1a7b6b5f12 | 181c06c9dc87b456d97d59feab986f4eeb70dd83 | refs/heads/master | 2021-01-19T23:20:14.300636 | 2017-04-24T06:59:15 | 2017-04-24T06:59:15 | 88,965,663 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,979 | h | #pragma once
#include <string>
using namespace std;
#define BASE(X, name, VIRTUAL) \
class LIBRARY_API name##Base##X { \
public: \
name##Base##X() \
: X##publicVar1(1), \
X##publicVar2(2), \
X##protectedVar1(3), \
X##protectedVar2(4), \
X##privateVar1(5), \
X##privateVar2(6) \
{ } \
\
VIRTUAL ~name##Base##X() { \
X##publicVar1 = 999; \
} \
\
int X##publicVar1; \
int X##publicVar2; \
int X##publicFunc1( int a ) const { return 0; } \
VIRTUAL const char* X##publicFunc2( const char* a, long b ) { return 0; } \
static int doSomething() { return 1; } \
\
protected: \
int X##protectedVar1; \
int X##protectedVar2; \
void * X##protectedFunc1( string a ) { return 0; } \
VIRTUAL void X##protectedFunc2( double a ) { return; } \
\
private: \
int X##privateVar1; \
int X##privateVar2; \
VIRTUAL string X##privateFunc1( short a ) { return ""; } \
const string& X##privateFunc2( const string& b ) { static string a; return a; } \
\
static double staticVar##X; \
}
#define SUBCLASS(X, Y) \
class LIBRARY_API Class##X { \
public: \
class LIBRARY_API SubClass##Y { \
public: \
int a; \
int func() { return 0; } \
}; \
struct LIBRARY_API SubStruct##Y { \
int a; \
int func() { return 0; } \
}; \
\
int pub; \
int pubFunc() { return 0; } \
static const Class##X Default() { return Class##X(); }\
static const Class##X DefaultObj; \
\
protected: \
int prot; \
int protFunc() { return 0; } \
\
private: \
int priv; \
int privFunc() { return 0; } \
}
#define SUBCLASSDEF(X, Y) \
const Class##X Class##X::DefaultObj
#define BASECLASS(X, name) \
{\
public: \
name() \
: X##pubVar( 1 ) { \
} \
~name() { \
X##pubVar = 999; \
} \
\
int X##pubVar; \
int X##pubFunc() { return 0; } \
}
#define SINGLEDERIVED(X, name, Y, Y1) \
class LIBRARY_API Single##name##Derived##Y##X : Y Y1 \
BASECLASS(X, Single##name##Derived##Y##X)
#define MULTIDERIVED(X, name, Y, Y1, Z, Z1) \
class LIBRARY_API Multi##name##Derived##Y##Z##X : Y Y1, Z Z1 \
BASECLASS(X, Multi##name##Derived##Y##Z##X)
BASE( A, Normal, );
BASE( B, Normal, );
SUBCLASS(MAIN, SUB);
SINGLEDERIVED( C, , public, NormalBaseA );
SINGLEDERIVED( D, , protected, NormalBaseA );
SINGLEDERIVED( E, , private, NormalBaseA );
MULTIDERIVED( F, , public, NormalBaseA, public, NormalBaseB );
MULTIDERIVED( G, , public, NormalBaseA, protected, NormalBaseB );
MULTIDERIVED( H, , public, NormalBaseA, private, NormalBaseB );
MULTIDERIVED( I, , protected, NormalBaseA, public, NormalBaseB );
MULTIDERIVED( J, , protected, NormalBaseA, protected, NormalBaseB );
MULTIDERIVED( K, , protected, NormalBaseA, private, NormalBaseB );
MULTIDERIVED( L, , private, NormalBaseA, public, NormalBaseB );
MULTIDERIVED( M, , private, NormalBaseA, protected, NormalBaseB );
MULTIDERIVED( N, , private, NormalBaseA, private, NormalBaseB );
BASE( A, Virtual, virtual );
BASE( B, Virtual, virtual );
SINGLEDERIVED( C, Virtual, public, VirtualBaseA );
SINGLEDERIVED( D, Virtual, protected, VirtualBaseA );
SINGLEDERIVED( E, Virtual, private, VirtualBaseA );
MULTIDERIVED( F, Virtual, public, virtual VirtualBaseA, public, VirtualBaseB );
MULTIDERIVED( G, Virtual, public, virtual VirtualBaseA, protected, VirtualBaseB );
MULTIDERIVED( H, Virtual, public, virtual VirtualBaseA, private, VirtualBaseB );
MULTIDERIVED( I, Virtual, protected, virtual VirtualBaseA, public, VirtualBaseB );
MULTIDERIVED( J, Virtual, protected, virtual VirtualBaseA, protected, VirtualBaseB );
MULTIDERIVED( K, Virtual, protected, virtual VirtualBaseA, private, VirtualBaseB );
MULTIDERIVED( L, Virtual, private, virtual VirtualBaseA, public, VirtualBaseB );
MULTIDERIVED( M, Virtual, private, virtual VirtualBaseA, protected, VirtualBaseB );
MULTIDERIVED( N, Virtual, private, virtual VirtualBaseA, private, VirtualBaseB );
| [
"steven@vaningelgem.be"
] | steven@vaningelgem.be |
54cf004123feffa2110f5f8c281911b9636b05cf | 2e280ea27615e1c4b03e6c15e0ba3ec6b260d944 | /include/GridCtrl/NewCellTypes/GridCellDateTime.cpp | 01eb2a53a57fe234ee18aa60c2b04d00279cc955 | [] | no_license | TonyJZ/IntegratedPhotogrammetry | afeaa54f0b1e5dcd2c677980ec7bba35a1756b29 | 226fbb02bf851ff17839929e3b5e3e25efae3888 | refs/heads/master | 2021-01-12T14:35:10.317687 | 2016-10-26T16:51:45 | 2016-10-26T16:51:45 | 72,024,771 | 1 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 6,186 | cpp | ///////////////////////////////////////////////////////////////////////////
//
// GridCellDateTime.cpp: implementation of the CGridCellDateTime class.
//
// Provides the implementation for a datetime picker cell type of the
// grid control.
//
// Written by Podsypalnikov Eugen 15 Mar 2001
// Modified:
// 31 May 2001 Fixed m_cTime bug (Chris Maunder)
//
// For use with CGridCtrl v2.22+
//
///////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "../GridCtrl_src/GridCtrl.h"
#include "../GridCtrl_src/GridCell.h"
#include "GridCellDateTime.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// CGridCellDateTime
IMPLEMENT_DYNCREATE(CGridCellDateTime, CGridCell)
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CGridCellDateTime::CGridCellDateTime() : CGridCell()
{
m_dwStyle = 0;
m_cTime = CTime::GetCurrentTime();
}
CGridCellDateTime::CGridCellDateTime(DWORD dwStyle) : CGridCell()
{
Init(dwStyle);
}
CGridCellDateTime::~CGridCellDateTime()
{
}
CSize CGridCellDateTime::GetCellExtent(CDC* pDC)
{
CSize sizeScroll (GetSystemMetrics(SM_CXVSCROLL), GetSystemMetrics(SM_CYHSCROLL));
CSize sizeCell (CGridCell::GetCellExtent(pDC));
sizeCell.cx += sizeScroll.cx;
sizeCell.cy = sizeCell.cy>sizeScroll.cy?sizeCell.cy:sizeScroll.cy;
//max(sizeCell.cy,sizeScroll.cy);
return sizeCell;
}
BOOL CGridCellDateTime::Edit(int nRow, int nCol, CRect rect, CPoint /* point */,
UINT nID, UINT nChar)
{
m_bEditing = TRUE;
// CInPlaceDateTime auto-deletes itself
m_pEditWnd = new CInPlaceDateTime(GetGrid(), rect,
m_dwStyle|DTS_UPDOWN, nID, nRow, nCol,
GetTextClr(), GetBackClr(), GetTime(), nChar);
return TRUE;
}
CWnd* CGridCellDateTime::GetEditWnd() const
{
return m_pEditWnd;
}
void CGridCellDateTime::EndEdit()
{
if (m_pEditWnd) ((CInPlaceDateTime*)m_pEditWnd)->EndEdit();
}
void CGridCellDateTime::Init(DWORD dwStyle)
{
m_dwStyle = dwStyle;
SetTime(CTime::GetCurrentTime());
SetFormat(DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX
#ifndef _WIN32_WCE
|DT_END_ELLIPSIS
#endif
);
}
// Should be changed to use locale settings
void CGridCellDateTime::SetTime(CTime time)
{
m_cTime = time;
if (DTS_TIMEFORMAT == m_dwStyle)
{
#ifdef _WIN32_WCE
CString strTemp;
strTemp.Format(_T("%02d:%02d:%02d"),
m_cTime.GetHour(), m_cTime.GetMinute(), m_cTime.GetSecond());
SetText(strTemp);
#else
// SetText(m_cTime.Format(_T("%H:%M:%S")));
SetText(m_cTime.Format(_T("%X")));
#endif
}
else if (DTS_SHORTDATEFORMAT == m_dwStyle)
{
#ifdef _WIN32_WCE
CString strTemp;
strTemp.Format(_T("%02d/%02d/%02d"),
m_cTime.GetMonth(), m_cTime.GetDay(), m_cTime.GetYear());
SetText(strTemp);
#else
// SetText(m_cTime.Format(("%d/%m/%Y")));
SetText(m_cTime.Format(("%x")));
#endif
}
}
/////////////////////////////////////////////////////////////////////////////
// CInPlaceDateTime
CInPlaceDateTime::CInPlaceDateTime(CWnd* pParent, CRect& rect, DWORD dwStyle, UINT nID,
int nRow, int nColumn,
COLORREF crFore, COLORREF crBack,
CTime* pcTime,
UINT nFirstChar)
{
m_crForeClr = crFore;
m_crBackClr = crBack;
m_nRow = nRow;
m_nCol = nColumn;
m_nLastChar = 0;
m_bExitOnArrows = FALSE;
m_pcTime = pcTime;
DWORD dwStl = WS_BORDER|WS_VISIBLE|WS_CHILD|dwStyle;
if (!Create(dwStl, rect, pParent, nID)) {
return;
}
SetTime(m_pcTime);
SetFont(pParent->GetFont());
SetFocus();
switch (nFirstChar)
{
case VK_LBUTTON:
case VK_RETURN: return;
case VK_BACK: break;
case VK_DOWN:
case VK_UP:
case VK_RIGHT:
case VK_LEFT:
case VK_NEXT:
case VK_PRIOR:
case VK_HOME:
case VK_END: return;
default: break;
}
SendMessage(WM_CHAR, nFirstChar);
}
CInPlaceDateTime::~CInPlaceDateTime()
{
}
void CInPlaceDateTime::EndEdit()
{
CString str;
if (::IsWindow(m_hWnd))
{
GetWindowText(str);
GetTime(*m_pcTime);
}
// Send Notification to parent
GV_DISPINFO dispinfo;
dispinfo.hdr.hwndFrom = GetSafeHwnd();
dispinfo.hdr.idFrom = GetDlgCtrlID();
dispinfo.hdr.code = GVN_ENDLABELEDIT;
dispinfo.item.mask = LVIF_TEXT|LVIF_PARAM;
dispinfo.item.row = m_nRow;
dispinfo.item.col = m_nCol;
dispinfo.item.strText = str;
dispinfo.item.lParam = (LPARAM) m_nLastChar;
CWnd* pOwner = GetOwner();
if (IsWindow(pOwner->GetSafeHwnd())) {
pOwner->SendMessage(WM_NOTIFY, GetDlgCtrlID(), (LPARAM)&dispinfo);
}
// Close this window (PostNcDestroy will delete this)
if (::IsWindow(m_hWnd)) {
PostMessage(WM_CLOSE, 0, 0);
}
}
void CInPlaceDateTime::PostNcDestroy()
{
CDateTimeCtrl::PostNcDestroy();
delete this;
}
BEGIN_MESSAGE_MAP(CInPlaceDateTime, CDateTimeCtrl)
//{{AFX_MSG_MAP(CInPlaceDateTime)
ON_WM_KILLFOCUS()
ON_WM_KEYDOWN()
ON_WM_KEYUP()
ON_WM_GETDLGCODE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CInPlaceDateTime message handlers
void CInPlaceDateTime::OnKillFocus(CWnd* pNewWnd)
{
CDateTimeCtrl::OnKillFocus(pNewWnd);
if (GetSafeHwnd() == pNewWnd->GetSafeHwnd()) {
return;
}
EndEdit();
}
UINT CInPlaceDateTime::OnGetDlgCode()
{
return DLGC_WANTALLKEYS;
}
void CInPlaceDateTime::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
if (( nChar == VK_PRIOR || nChar == VK_NEXT ||
nChar == VK_DOWN || nChar == VK_UP ||
nChar == VK_RIGHT || nChar == VK_LEFT) &&
(m_bExitOnArrows || GetKeyState(VK_CONTROL) < 0))
{
m_nLastChar = nChar;
GetParent()->SetFocus();
return;
}
CDateTimeCtrl::OnKeyDown(nChar, nRepCnt, nFlags);
}
void CInPlaceDateTime::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
{
if (nChar == VK_TAB || nChar == VK_RETURN || nChar == VK_ESCAPE)
{
m_nLastChar = nChar;
GetParent()->SetFocus(); // This will destroy this window
return;
}
CDateTimeCtrl::OnKeyUp(nChar, nRepCnt, nFlags);
}
| [
"zhangjingwh@gmail.com"
] | zhangjingwh@gmail.com |
a674d5ce42ad7682ce11341862f3ee718c0891e5 | 562cda07bcb76b88377a19c5831f1f879c38b4ad | /flowmgr/utility.hpp | ea7f774280f5be84f8407f42e4f639b5440addb9 | [
"Apache-2.0"
] | permissive | flowgrammable/freeflow-c | f1c02f2504b00b8c0bcb58e1dee70331dbe83323 | 7ca602be2383283edf00bd08838aef2a282fcd9b | refs/heads/master | 2021-01-15T15:15:14.782837 | 2015-08-16T21:08:39 | 2015-08-16T21:08:39 | 39,893,758 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,412 | hpp | // Copyright (c) 2014-2015 Flowgrammable.org
// All rights reserved
#ifndef FLOWMGR_UTILITY_HPP
#define FLOWMGR_UTILITY_HPP
// A collection of useful facilities.
#include "freeflow/async.hpp"
#include "freeflow/socket.hpp"
#include "freeflow/json.hpp"
#include "freeflow/format.hpp"
struct Control_channel;
struct Switch_channel;
// Returns a string-valued argument or nullptr if the argument
// is either not in the argument map or not a string.
inline ff::json::String const*
get_string_arg(ff::json::Map const& args, char const* arg)
{
using ff::json::as;
auto iter = args.find(arg);
if (iter != args.end())
return as<ff::json::String>(iter->second);
else
return nullptr;
}
// Send a response to the client.
template<typename... Args>
inline void
send(ff::Io_handler& io, char const* msg, Args const&... args)
{
ff::send(io.fd(), ff::format(msg, args...));
}
// Send a JSON-formatted error message to the IO handler.
inline void
send_error(ff::Io_handler& io, char const* msg)
{
std::string json = ff::json::make_object({
{"status", "error"},
{"messsage", msg}
});
ff::send(io.fd(), json);
}
// Send a JSON-formatted error message to the IO handler.
inline void
send_error(ff::Io_handler& io, std::string const& msg)
{
send_error(io, msg.c_str());
}
Control_channel* require_control(ff::Io_handler&);
Switch_channel* require_switch(ff::Io_handler&);
#endif
| [
"andrew.n.sutton@gmail.com"
] | andrew.n.sutton@gmail.com |
5363f10be247db6ec3d3b8890bea09d9bde7dd96 | 35b929181f587c81ad507c24103d172d004ee911 | /SrcLib/core/fwComEd/src/fwComEd/InteractionMsg.cpp | 2eb82131c5ee1819511d663a26696c0da76de322 | [] | no_license | hamalawy/fw4spl | 7853aa46ed5f96660123e88d2ba8b0465bd3f58d | 680376662bf3fad54b9616d1e9d4c043d9d990df | refs/heads/master | 2021-01-10T11:33:53.571504 | 2015-07-23T08:01:59 | 2015-07-23T08:01:59 | 50,699,438 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,795 | cpp | /* ***** BEGIN LICENSE BLOCK *****
* FW4SPL - Copyright (C) IRCAD, 2009-2012.
* Distributed under the terms of the GNU Lesser General Public License (LGPL) as
* published by the Free Software Foundation.
* ****** END LICENSE BLOCK ****** */
#include <limits>
#include <fwCore/base.hpp>
#include <fwServices/registry/message/macros.hpp>
#include "fwComEd/InteractionMsg.hpp"
fwServicesMessageRegisterMacro( ::fwComEd::InteractionMsg );
namespace fwComEd
{
std::string InteractionMsg::MOUSE_LEFT_UP = "MOUSE_LEFT_UP";
std::string InteractionMsg::MOUSE_RIGHT_UP = "MOUSE_RIGHT_UP";
std::string InteractionMsg::MOUSE_MIDDLE_UP = "MOUSE_MIDDLE_UP";
std::string InteractionMsg::MOUSE_WHEELFORWARD_UP = "MOUSE_WHEELFORWARD_UP";
std::string InteractionMsg::MOUSE_WHEELBACKWARD_UP = "MOUSE_WHEELBACKWARD_UP";
std::string InteractionMsg::MOUSE_LEFT_DOWN = "MOUSE_LEFT_DOWN";
std::string InteractionMsg::MOUSE_RIGHT_DOWN = "MOUSE_RIGHT_DOWN";
std::string InteractionMsg::MOUSE_MIDDLE_DOWN = "MOUSE_MIDDLE_DOWN";
std::string InteractionMsg::MOUSE_WHEELFORWARD_DOWN = "MOUSE_WHEELFORWARD_DOWN";
std::string InteractionMsg::MOUSE_WHEELBACKWARD_DOWN = "MOUSE_WHEELBACKWARD_DOWN";
std::string InteractionMsg::MOUSE_MOVE = "MOUSE_MOVE";
//-----------------------------------------------------------------------------
InteractionMsg::InteractionMsg(::fwServices::ObjectMsg::Key key) :
m_eventPoint(::fwData::Point::New()),
m_modifiersStatus(NONE),
m_eventTimestamp(0.)
{
}
//-----------------------------------------------------------------------------
InteractionMsg::~InteractionMsg() throw()
{}
//-----------------------------------------------------------------------------
void InteractionMsg::setEvent(std::string event)
{
SLM_ASSERT("InteractionMsg cannot handle several events in the same message",
m_eventId2DataInfo.size()==0 );
addEvent(event);
}
//-----------------------------------------------------------------------------
void InteractionMsg::setModifiersStatus(Modifiers k, bool state)
{
if (state)
{
m_modifiersStatus = static_cast<unsigned char>(m_modifiersStatus | k);
}
else
{
m_modifiersStatus = static_cast<unsigned char>( m_modifiersStatus & (std::numeric_limits<unsigned char>::max() - k));
}
}
//-----------------------------------------------------------------------------
bool InteractionMsg::getModifiersStatus(Modifiers k) const
{
return m_modifiersStatus & k;
}
//-----------------------------------------------------------------------------
void InteractionMsg::setEventPoint(::fwData::Point::csptr point)
{
SLM_ASSERT("Null point pointer", point);
m_eventPoint = ::fwData::Object::copy(point);
}
//-----------------------------------------------------------------------------
void InteractionMsg::setEventPoint(PointCoordType x, PointCoordType y, PointCoordType z)
{
::fwData::Point::PointCoordArrayType &coords = m_eventPoint->getRefCoord();
coords[0] = x;
coords[1] = y;
coords[2] = z;
}
//-----------------------------------------------------------------------------
::fwData::Point::csptr InteractionMsg::getEventPoint() const
{
return m_eventPoint;
}
//-----------------------------------------------------------------------------
void InteractionMsg::setEventTimestamp(::fwCore::HiResClock::HiResClockType timestamp)
{
m_eventTimestamp = timestamp;
}
//-----------------------------------------------------------------------------
::fwCore::HiResClock::HiResClockType InteractionMsg::getEventTimestamp() const
{
return m_eventTimestamp;
}
//-----------------------------------------------------------------------------
} // namespace fwComEd
| [
"emilie.harquel@localhost"
] | emilie.harquel@localhost |
2b14f6037d07631e4721fd6c3de5cb9a4754f352 | b209f657817b2252934dd5fba2601d3f8fb8ab04 | /app/src/main/cpp/main/rendering_engine/ShaderCreationParams.h | 4fe9443917f7d8472ce028b23472a778eeee57a8 | [] | no_license | raynor73/AndroidNDKOpenGLResearch | 4faa8d7cd618e2194ab7396af28e83fb7fd84444 | 34d4292d1bcaaa72e7a4836d7e38568e31183e46 | refs/heads/master | 2023-01-31T12:54:35.325233 | 2020-12-10T09:37:55 | 2020-12-10T09:37:55 | 268,936,661 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 559 | h | //
// Created by Igor Lapin on 09/07/2020.
//
#ifndef RENDERING_ENGINE_SHADER_CREATION_PARAMS_H
#define RENDERING_ENGINE_SHADER_CREATION_PARAMS_H
#include <string>
struct ShaderCreationParams {
std::string name;
std::string source;
};
struct VertexShaderCreationParams : ShaderCreationParams {};
struct FragmentShaderCreationParams : ShaderCreationParams {};
struct ShaderProgramCreationParams {
std::string name;
std::string vertexShaderName;
std::string fragmentShaderName;
};
#endif //RENDERING_ENGINE_SHADER_CREATION_PARAMS_H
| [
"raynor73@gmail.com"
] | raynor73@gmail.com |
d1646a91a3646038f526e5c78be9f429c525a3c5 | f28a6da7ee5ca1c7cc4b3d0a59729ba77dc4f3e5 | /next_steps/projects/p2/book_store.cpp | e58778fd3037c1ec3a7bcdda08448c603c0154e9 | [] | no_license | gattonic/google-cpp-class | 9a27b70ebc0b8bdb500b2abc4646d1be709b9de1 | fa9222e987ab0fb7724b355f61eb64420b0f45f8 | refs/heads/master | 2020-07-15T01:53:26.093020 | 2019-09-12T21:58:21 | 2019-09-12T21:58:21 | 205,453,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,415 | cpp | // book_store.cpp: Nicola Gatto
// Description: Calculates
#include <iostream>
#include <vector>
using namespace std;
static const float kSaleRateNewAndRequired = .9f;
static const float kSaleRateUsedAndRequired = .65f;
static const float kSaleRateNewAndOptional = .4f;
static const float kSaleRateUsedAndOptional = .2f;
static const float kListPriceCut = .8f;
struct Book {
int book_code;
float price;
int on_hand;
int prospective_enrollment;
bool required;
bool new_book;
};
struct BookOrder {
Book book;
int amount_order;
float total_cost;
};
Book TakeBookInput() {
Book book;
int required = 0;
int new_book = 0;
cout << "Please enter the book code: ";
cin >> book.book_code;
cout << " single copy price: ";
cin >> book.price;
cout << " number on hand: ";
cin >> book.on_hand;
cout << " prospective enrollment: ";
cin >> book.prospective_enrollment;
cout << " 1 for required / 0 for optional: ";
cin >> required;
book.required = (required == 1);
cout << " 1 for new / 0 for used: ";
cin >> new_book;
book.new_book = (new_book == 1);
return book;
}
void ShowBook(Book book) {
cout << "Book: " << book.book_code << endl;
cout << "Price: $" << book.price << endl;
cout << "Inventory: " << book.on_hand << endl;
cout << "Enrollment: " << book.prospective_enrollment << endl;
cout << "This book is " << (book.required ? "required" : "optional")
<< " and " << (book.new_book ? "new" : "used") << "." << endl;
}
void PrintSeperator() {
cout << "*************************************************************" << endl;
}
float CalculateOrderAmount(bool new_book, bool required, int prospective_enrollment) {
float sale_rate = 0.0;
if (new_book && required) {
sale_rate = kSaleRateNewAndRequired;
} else if (new_book && !required) {
sale_rate = kSaleRateNewAndOptional;
} else if (!new_book && required) {
sale_rate = kSaleRateUsedAndRequired;
} else {
sale_rate = kSaleRateUsedAndOptional;
}
return sale_rate * prospective_enrollment;
}
BookOrder CalculateOrder(Book book) {
BookOrder bookOrder;
bookOrder.book = book;
bookOrder.amount_order = CalculateOrderAmount(book.new_book, book.required, book.prospective_enrollment) - book.on_hand;
bookOrder.total_cost = bookOrder.amount_order * book.price;
return bookOrder;
}
void ShowBookOrder(BookOrder order) {
cout << "Need to order: " << order.amount_order << endl;
cout << "Total Cost: $" << order.total_cost << endl;
}
void ShowAllOrders(vector<BookOrder> orders) {
float total_cost = 0.0;
float profit = 0.0;
for (BookOrder order : orders) {
total_cost += order.total_cost;
}
cout << "Total for all orders: $" << total_cost << endl;
cout << "Profit: $" << total_cost * (1.0 - kListPriceCut) << endl;
}
int main() {
int done;
vector<BookOrder> orders;
do {
Book book = TakeBookInput();
PrintSeperator();
ShowBook(book);
PrintSeperator();
BookOrder order = CalculateOrder(book);
ShowBookOrder(order);
PrintSeperator();
orders.push_back(order);
cout << "Enter 1 to do another book, 0 to stop.";
cin >> done;
} while (done == 1);
PrintSeperator();
ShowAllOrders(orders);
PrintSeperator();
} | [
"nicola.gatto@rwth-aachen.de"
] | nicola.gatto@rwth-aachen.de |
0e4e7b96fd63e86c10248a457d2baa5c3c881898 | 5f3ccb6cb140b203c048e173693a081cbd8abf13 | /source/pkt.cpp | 6446f57d768431b172fdfac09a4d766c41f068ab | [] | no_license | sndae/casimir-companion | 6380483968fb5002447d4e5d8155fec998421527 | e7ce8bce3b6cdc38141e00bfa4d4f5b1457a5758 | refs/heads/master | 2021-01-25T07:08:28.877173 | 2010-09-10T13:09:45 | 2010-09-10T13:09:45 | 38,293,398 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,365 | cpp | /*
DIGIREC
Copyright (C) 2010:
Daniel Roggen, droggen@gmail.com
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <QFile>
#include "pkt.h"
//template <typename DATATYPE>
//void PacketClear(STREAM_GENERIC<DATATYPE> &p)
void StreamClear(STREAM_GENERIC &p,unsigned time_offset)
{
// p.nan.clear();
p.timetick.clear();
p.time.clear();
p.data.clear();
p.nans.clear();
p.time_offset=time_offset;
}
//template <typename DATATYPE>
//void PacketAddSample(STREAM_GENERIC<DATATYPE> &p,DATATYPE data,unsigned t,unsigned dt)
void StreamAddSample(STREAM_GENERIC &p,std::vector<int> data,unsigned t,unsigned dt)
{
// First check whether there are missing samples, and inserts NANs
// Check continuity between last sample (if any) and current sample
// Assumptions: packets are stored in increasing time order. Packets can be missing, but are not temporally shuffled.
if(p.data.size())
{
// At least one previous sample - check continuity
if(p.timetick.back()+dt<t)
{
// Discontinuity... compute number of nan samples to add
unsigned add = (t-dt-p.timetick.back())/dt;
printf("Missing samples! Inserting %d NANs\n",add);
for(unsigned mi=0;mi<add;mi++)
{
// p.nan.push_back(true);
p.nans.push_back(std::vector<bool>(data.size(),true));
p.timetick.push_back(p.timetick.back()+dt);
p.time.push_back(0);
p.data.push_back(p.data.back()); // Repeat the data (when saving to file, the user can dump NANs instead)
}
}
}
// Dummy thing
// p.nan.push_back(false);
p.nans.push_back(std::vector<bool>(data.size(),false));
p.timetick.push_back(t);
p.time.push_back(0);
p.data.push_back(data);
p.dt = dt;
}
//template <typename DATATYPE>
void StreamDump(STREAM_GENERIC &p,QTextStream &out,bool nan)
{
for(unsigned i=0;i<p.data.size();i++)
{
QString str,str2;
//str.sprintf("%c %010u ",p.nan[i]?'X':'V',p.timetick[i]);
str.sprintf("%010u ",p.timetick[i]);
for(unsigned j=0;j<p.data[i].size();j++)
{
if(nan && p.nans[i][j])
str2.sprintf(" NaN ");
else
str2.sprintf("% 10d ",p.data[i][j]);
str+=str2;
}
str+="\n";
//printf("%s",str.toStdString().c_str());
out << str;
}
}
void StreamAddPacketV1(STREAM_GENERIC &stream,PREAMBLE &pre,const char *packet)
{
for(unsigned s=0;s<pre.ns;s++)
{
int sample = *(const unsigned short*)(packet+PACKET_PREAMBLE+2*s);
StreamAddSample(stream,std::vector<int>(1,sample),pre.time+s*pre.dt,pre.dt);
}
}
void StreamAddPacketV6(STREAM_GENERIC &stream,PREAMBLE &pre,const char *packet)
{
for(unsigned s=0;s<pre.ns;s++)
{
std::vector<int> v(3,0);
for(unsigned i=0;i<3;i++)
{
v[i] = *(const signed short*)(packet+PACKET_PREAMBLE+(s*3+i)*2);
}
StreamAddSample(stream,v,pre.time+s*pre.dt,pre.dt);
}
}
// Assumes there is enough data at the pointer location to read the preamble
void data2preamble(const char *data,PREAMBLE &pre)
{
//for(unsigned i=0;i<4;i++)
//pre.preamble[i]=data[i];
pre.preamble=*(unsigned int*)data;
pre.type=data[4];
pre.time=*(unsigned int*)(data+5);
pre.id=*(unsigned int*)(data+9);
pre.entry=data[13];
pre.ns=data[14];
pre.dt=*(unsigned short*)(data+15);
pre.opt=data[17];
pre.zero[0]=data[18];
pre.zero[1]=data[19];
}
void printpreamble(const PREAMBLE &pre)
{
printf("Preamble: %08X\n",pre.preamble);
printf("Type: %d ",pre.type);
switch(pre.type){ case PACKET_TYPE_AUDIO: printf("(audio)\n"); break;
case PACKET_TYPE_ACC: printf("(acc)\n"); break;
case PACKET_TYPE_SYSTEM: printf("(sys)\n"); break;
case PACKET_TYPE_LIGHT: printf("(lit)\n"); break;
case PACKET_TYPE_TMP: printf("(tmp)\n"); break;
case PACKET_TYPE_HMC: printf("(hmc)\n"); break;
default: printf("unk\n");
}
printf("Time: %u\n",pre.time);
printf("ID: %08X\n",pre.id);
printf("#logs: %u\n",(unsigned)pre.entry);
printf("ns: %d\n",(unsigned)pre.ns);
printf("dt: %08X\n",(unsigned)pre.dt);
printf("opt: %02X\n",(unsigned)pre.opt);
printf("zero: %02X %02X\n",(unsigned)pre.zero[0],(unsigned)pre.zero[1]);
}
// Returns the numbers of bytes required
unsigned packetbytesize(const PREAMBLE &pre)
{
switch(pre.type)
{
case PACKET_TYPE_AUDIO:
return 2+PACKET_PREAMBLE+pre.ns*2;
case PACKET_TYPE_ACC:
return 2+PACKET_PREAMBLE+pre.ns*2*3;
case PACKET_TYPE_SYSTEM:
return 2+PACKET_PREAMBLE+pre.ns*2;
case PACKET_TYPE_LIGHT:
return 2+PACKET_PREAMBLE+pre.ns*2;
case PACKET_TYPE_TMP:
return 2+PACKET_PREAMBLE+pre.ns*2;
case PACKET_TYPE_HMC:
return 2+PACKET_PREAMBLE+pre.ns*2*3;
}
return 0;
}
void demux(QByteArray &data,unsigned time_offset,STREAM_GENERIC &stream_audio,STREAM_GENERIC &stream_acc,STREAM_GENERIC &stream_hmc,STREAM_GENERIC &stream_sys,STREAM_GENERIC &stream_light,STREAM_GENERIC &stream_tmp)
{
//STREAM_GENERIC<unsigned short> packet_audio;
StreamClear(stream_audio,time_offset);
StreamClear(stream_acc,time_offset);
StreamClear(stream_hmc,time_offset);
StreamClear(stream_sys,time_offset);
StreamClear(stream_light,time_offset);
StreamClear(stream_tmp,time_offset);
printf("Demultiplexing %d bytes\n",data.size());
unsigned ptr=0;
unsigned decodepackets=0;
printf("Sizeof preamble: %d. packet_preamble: %d\n",sizeof(PREAMBLE),PACKET_PREAMBLE);
//for(unsigned _i=0;_i<360;_i++)
while(ptr<data.size())
{
// Check if enough data to contain a packet preamble
if(ptr+PACKET_PREAMBLE>=data.size())
{
printf("some bytes left, but not enough for a packet preamble. ptr: %u. size: %u\n",ptr,data.size());
break;
}
PREAMBLE pre;
data2preamble(data.constData()+ptr,pre);
//memcpy(&pre,data.constData()+ptr,)
if(pre.preamble==0xFF00AA55)
{
// This could be a packet...
unsigned size = packetbytesize(pre);
// Check that we have enough data to decode this packet
if(ptr+size>=data.size())
{
printf("Packet preamble detected, but not enough data left for the complete packet\n");
break;
}
//printf("Found a packet at %d - %d. Type %d\n",ptr,ptr+size-1,pre.type);
//printpreamble(pre);
//if(!((decodepackets%7)==0 || (decodepackets%9)==0)) // Simulation of packet loss
if(1)
{
// Now decode the packet
switch(pre.type)
{
case PACKET_TYPE_AUDIO:
StreamAddPacketV1(stream_audio,pre,data.constData()+ptr);
break;
case PACKET_TYPE_ACC:
StreamAddPacketV6(stream_acc,pre,data.constData()+ptr);
break;
case PACKET_TYPE_SYSTEM:
StreamAddPacketV1(stream_sys,pre,data.constData()+ptr);
break;
case PACKET_TYPE_LIGHT:
StreamAddPacketV1(stream_light,pre,data.constData()+ptr);
break;
case PACKET_TYPE_TMP:
StreamAddPacketV1(stream_tmp,pre,data.constData()+ptr);
break;
case PACKET_TYPE_HMC:
StreamAddPacketV6(stream_hmc,pre,data.constData()+ptr);
break;
default:
printf("Unknown packet type, skipping\n");
}
} // Simulation of packet loss
// Skip the packet
ptr += size;
decodepackets++;
}
else
{
// Skip one byte
ptr++;
}
}
printf("Demux terminated. ptr: %u. size: %u. Decoded %d packets.\n",ptr,data.size(),decodepackets);
// Dump the data...
//printf("Audio\n");
//StreamDump(stream_audio);
//printf("Acceleration\n");
//StreamDump(stream_acc);
//printf("HMC\n");
//StreamDump(stream_hmc);
//printf("System\n");
//StreamDump(stream_sys);
//printf("Light\n");
//StreamDump(stream_light);
//printf("TMP\n");
//StreamDump(stream_tmp,out);
}
bool StreamSave(STREAM_GENERIC &stream,QString filename)
{
QFile file(filename);
file.open(QIODevice::WriteOnly|QIODevice::Truncate| QIODevice::Text);
QTextStream out(&file);
StreamDump(stream,out);
file.close();
}
/******************************************************************************
Merge multiple streams
*******************************************************************************
In order to merge the streams the function must:
1. Identify which is the smallest time delta among the streams
2. Identify the stream starting the earliest
3. Identify the stream finishing the latest
******************************************************************************/
void StreamMerge(std::vector<STREAM_GENERIC *> streams,STREAM_GENERIC &streamout)
{
unsigned dt; // dt of the merged stream
unsigned start,stop; // Start/stop time of the merged stream
std::vector<unsigned> dts; // dt of each stream
std::vector<unsigned> starts; // Start time of each stream
std::vector<unsigned> stops; // Stop time of each stream
std::vector<unsigned> numchans; // Number of channels of each stream
std::vector<unsigned> channeloffset;
// Dump some quick infos
for(unsigned i=0;i<streams.size();i++)
{
printf("Stream %d. dt: %u. start: %u. end: %u. Num samples: %u\n",i,streams[i]->dt,streams[i]->timetick.front(),streams[i]->timetick.back(),streams[i]->data.size());
}
// Find the smallest delta among the streams.
dts.resize(streams.size(),0);
for(unsigned i=0;i<streams.size();i++)
dts[i] = streams[i]->dt;
for(unsigned i=0;i<streams.size();i++)
{
if(i==0)
dt = streams[i]->dt;
else
{
if(streams[i]->dt<dt)
dt = streams[i]->dt;
}
}
printf("Smallest dt: %d\n",dt);
// Find the stream starting the earliest
starts.resize(streams.size(),0);
for(unsigned i=0;i<streams.size();i++)
starts[i] = streams[i]->timetick.front();
for(unsigned i=0;i<streams.size();i++)
{
if(i==0)
start = streams[i]->timetick.front();
else
{
if(streams[i]->timetick.front()<start)
start = streams[i]->timetick.front();
}
}
printf("Start timetick: %d\n",start);
// Find the stream finishing the latest
stops.resize(streams.size(),0);
for(unsigned i=0;i<streams.size();i++)
stops[i] = streams[i]->timetick.back();
for(unsigned i=0;i<streams.size();i++)
{
if(i==0)
stop = streams[i]->timetick.back();
else
{
if(streams[i]->timetick.back()>stop)
stop = streams[i]->timetick.back();
}
}
printf("Stop timetick: %d\n",stop);
// Count the number of channels
numchans.resize(streams.size(),0);
for(unsigned i=0;i<streams.size();i++)
numchans[i] = streams[i]->data.front().size();
unsigned channels=0;
for(unsigned i=0;i<streams.size();i++)
channels += streams[i]->data.front().size();
printf("Total number of channels: %u\n",channels);
// Number of samples
unsigned samples = (stop-start+dt)/dt;
printf("Number of samples to generate: %d\n",samples);
// Generate the merged data structure
StreamClear(streamout,0);
streamout.nans.resize(samples,std::vector<bool>(channels,false));
streamout.time.resize(samples,0.0);
streamout.timetick.resize(samples,0);
streamout.data.resize(samples,std::vector<int>(channels,0));
streamout.dt=dt;
// Comput the channel offsets (positions) in the new structure
channeloffset.resize(streams.size(),0);
for(unsigned i=1;i<streams.size();i++)
channeloffset[i]=channeloffset[i-1]+streams[i-1]->data.front().size();
printf("Position of the data in the new structure: ");
for(unsigned i=0;i<streams.size();i++)
printf("%u ",channeloffset[i]);
printf("\n");
printf("New data: samples: %u channels: %u\n",streamout.data.size(),streamout.data.front().size());
// Copy the data in the new structure...
for(unsigned ti=0;ti<samples;ti++)
//for(unsigned ti=0;ti<=10;ti++)
{
unsigned t = ti*dt+start;
streamout.timetick[ti]=t;
for(unsigned s=0;s<streams.size();s++)
{
// Need to find the index in stream s of the sample at time t (if any)
if(t<starts[s] || t>stops[s])
{
// The time is outside of what this channel provides. We set nans in the channel
for(unsigned c=0;c<numchans[s];c++)
{
streamout.nans[ti][c+channeloffset[s]]=true;
//streamout.data[t][c+channeloffset[s]]=0;
}
}
else
{
unsigned i=(t-starts[s])/dts[s];
//printf("time %u maps to time %u on stream %u\n",t,streams[s]->timetick[i],s);
for(unsigned c=0;c<numchans[s];c++)
{
streamout.nans[ti][c+channeloffset[s]]=streams[s]->nans[i][c];
streamout.data[ti][c+channeloffset[s]]=streams[s]->data[i][c];
}
}
}
}
printf("Merge completed\n");
}
/*
//QFile file;
QTextStream out;
QFile file("dat_audio.dat");
file.open(QIODevice::WriteOnly|QIODevice::Truncate| QIODevice::Text);
out = QTextStream(&file);
StreamDump(stream_audio,out);
file.close();
}
*/
| [
"droggen@1fa3586f-ae1d-b4ea-cc5f-ffa2b2774cd0"
] | droggen@1fa3586f-ae1d-b4ea-cc5f-ffa2b2774cd0 |
a92972c8af34972eb5a3ade703644a9a7f07b3e7 | e2d18cd753caae30e9b41c538d99ebe95154499f | /include/Agents/Agent.h | 5a2c36ed2021d5be027717a5cd00ba35cdeb932f | [
"MIT"
] | permissive | eklinkhammer/aadil | 8dc019b2f7d9f23107a72628e16eb573106897c8 | 9bc744119a64c9339660646d82f2e63e6cb20ba4 | refs/heads/master | 2021-01-19T16:13:11.262980 | 2017-11-13T21:01:06 | 2017-11-13T21:01:06 | 100,990,918 | 0 | 0 | null | 2017-10-19T21:31:15 | 2017-08-21T20:41:16 | C++ | UTF-8 | C++ | false | false | 5,659 | h | /*******************************************************************************
Agent.h
Agent class header. Agent is the base class for different types of rovers that
calculate their input vectors differently.
Authors: Eric Klinkhammer
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*******************************************************************************/
#ifndef AGENT_H_
#define AGENT_H_
#include <algorithm>
#include <fstream>
#include <sstream>
#include <string>
#include <iostream>
#include <list>
#include <vector>
#include <math.h>
#include <float.h>
#include <Eigen/Eigen>
#include "Learning/NeuroEvo.h"
#include "Utilities/Utilities.h"
#include "Domains/Target.h"
#include "Domains/State.h"
#ifndef PI
#define PI 3.14159265358979323846264338328
#endif
using std::string;
using std::vector;
using std::list;
using std::max;
using easymath::pi_2_pi;
enum class Fitness {G, D};
class Agent {
public:
Agent(size_t n, size_t nPop, size_t nInput, size_t nHidden, size_t nOutput,
Fitness f);
virtual ~Agent();
// Computes the input to the neural network using a list of actor joint states
//
// The returned VectorXd will be the same size as nInput
//
// This function is a pure virtual function.
virtual VectorXd ComputeNNInput(vector<Vector2d> jointState) const = 0;
vector< double > getVectorState(vector<State>);
// Calculates the new State from the ith neural network in the CCEA pool
// using the result of ComputeNNInput with the jointstate as input.
//
// Updates both currentXY and currentPsi
//
// Is implemented. Should only be overriden when the NN does not directly return
// a new position (ie, when it chooses between two other networks).
virtual State executeNNControlPolicy(size_t, vector<State>);
virtual State getNextState(size_t, vector<State>) const;
void move(State);
// Sets initial simulation parameters, including rover positions. Clears
// evaluation storage vector.
virtual void initialiseNewLearningEpoch(State s);
// Sets initial simulation parameters, including rover positions. Clears
// evaluation storage vector. Intended for use with POIs
//
// Base functionality is to ignore the first argument.
virtual void initialiseNewLearningEpoch(State s, vector<Target>);
virtual void DifferenceEvaluationFunction(vector<Vector2d>, double) = 0;
// The Reward an agent receives at a given time step.
virtual double getReward() { return 0.0; }
// Returns a jointstate that has the agent's state replaced with a
// counterfactual state. The default is the intial state (ie, if the
// agent had not moved at all).
vector<Vector2d> substituteCounterfactual(vector<Vector2d> jointState);
vector<Vector2d> substituteCounterfactual(vector<Vector2d>, double, double);
// Evolves the NeuroEvo, using the epochEvals score. When init is true,
// only mutates the population.
void EvolvePolicies(bool init = false);
// Writes the neural networks to file
void OutputNNs(std::string);
// Sets the epoch values to 0 (for new scenario)
void ResetEpochEvals();
// Sets the performance for the epoch and position i to either G or stepwise D
void SetEpochPerformance(double G, size_t i);
vector<double> GetEpochEvals() const{ return epochEvals; }
double getCurrentPsi() const { return currentState.psi(); }
double getInitialPsi() const { return initialState.psi(); }
Vector2d getCurrentXY() const { return currentState.pos(); }
Vector2d getInitialXY() const { return initialState.pos(); }
State getCurrentState() const { return currentState; }
State getInitialState() const { return initialState; }
NeuroEvo * GetNEPopulation() const { return AgentNE; }
void setOutputBool(bool toggle) { printOutput = toggle; }
void openOutputFile(std::string filename);
virtual Agent* copyAgent() const = 0;
friend std::ostream& operator<<(std::ostream&, const Agent&);
private:
size_t nSteps;
size_t popSize;
size_t numHidden;
size_t numOut;
NeuroEvo* AgentNE;
std::vector<double> epochEvals;
void ResetStepwiseEval();
unsigned id;
protected:
Matrix2d RotationMatrix(double psi) const;
Fitness fitness;
State initialState;
State currentState;
size_t numIn;
double stepwiseD;
// Determines the index of this agent's position in a jointState vector
size_t selfIndex(vector<Vector2d> jointState) const;
bool printOutput;
std::ofstream outputFile;
void setNets(NeuroEvo* nets) { AgentNE = nets; }
size_t getSteps() const { return nSteps; }
size_t getPop() const { return popSize; }
Fitness getFitness() const { return fitness; }
};
#endif // AGENT_H_
| [
"klinkhae@oregonstate.edu"
] | klinkhae@oregonstate.edu |
c649ecaf23c4ca1768d403c247afd0a70a745ebd | 7711d649865cbb05d86b5985e6a1ee99a38df3b3 | /thirdparty-cpp/boost_1_62_0/libs/optional/test/optional_xconfig_NO_LEGAL_CONVERT_FROM_REF_fail.cpp | 7f294907d6dd3b338c225c78c69d932c4ec75f7d | [
"Apache-2.0",
"BSL-1.0"
] | permissive | nxplatform/nx-mobile | 0ae4ba8b5b20cf06a9396d685a35b4651c0eab02 | 0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5 | refs/heads/master | 2021-01-17T07:35:33.860681 | 2017-04-25T10:12:30 | 2017-04-25T10:12:30 | 83,760,335 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 876 | cpp | // Copyright (C) 2015 Andrzej Krzemienski.
//
// 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)
//
// See http://www.boost.org/lib/optional for documentation.
//
// You are welcome to contact the author at:
// akrzemi1@gmail.com
#include "boost/core/ignore_unused.hpp"
#include "boost/core/lightweight_test.hpp"
#include "boost/optional/detail/optional_config.hpp"
#if (defined BOOST_NO_CXX11_RVALUE_REFERENCES) || (!defined BOOST_OPTIONAL_CONFIG_NO_LEGAL_CONVERT_FROM_REF)
static_assert(false, "failed as requested");
#else
struct S {};
struct Binder
{
S& ref_;
template <typename R> Binder (R&&r) : ref_(r) {}
};
int main()
{
S s ;
Binder b = s;
boost::ignore_unused(b);
}
#endif
| [
"narongrit@3dsinteractive.com"
] | narongrit@3dsinteractive.com |
eb779b80f0837979c45b80affb6e8d6046f7856b | 4b2431b9dcc77260f38a3d179d35a1e38ec4d2f6 | /CC++/LowerLayer/Union_Serial/src/Union_Serial.cpp | 845efc3c212fbde7395f85e78d50e9fce7803446 | [
"MIT"
] | permissive | Peterinor/Coding | a6ee0d23b7213fd390d71bfe3130fee468ea8492 | 3ac4908b3c6ae5df96390332e5452da934d12c3b | refs/heads/master | 2016-09-03T06:44:49.113899 | 2015-04-15T11:30:52 | 2015-04-15T11:30:52 | 21,445,725 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 903 | cpp | //============================================================================
// Name : Union.cpp
// Author : ty
// Version :1.0
// Description : 使用Union结构进行的串行通信数据结构,更方便数据传输。
//============================================================================
#include <iostream>
using namespace std;
union sdata
{
float fdata;
struct
{
unsigned char b1,b2,b3,b4;
}bdata;
};
int main()
{
sdata serial;
serial.fdata=3.14159;
float fserial;
unsigned char * pdata=&serial.bdata.b1;
fserial=*(float *)pdata;
cout<<"转换后的结果为:"<<endl;
cout<<fserial<<endl;
char ch_flo[4];
ch_flo[0] = serial.bdata.b1;
ch_flo[1] = serial.bdata.b2;
ch_flo[2] = serial.bdata.b3;
ch_flo[3] = serial.bdata.b4;
float * pflo = (float *)ch_flo;
cout<<"转换结果为:"<<endl;
cout<<*pflo<<endl;
return 0;
}
| [
"tangyutianbulao@qq.com"
] | tangyutianbulao@qq.com |
63c15b4db2002bfb4002208125021da457271ab9 | c1aac9198adaa59be9719c8044a2e0a1242d88fc | /src/cs-b-Assignment4-Pythagora-Tree.cpp | 2814a590f09c7b294385022968e3b16ad05e00a0 | [] | no_license | shpp-nbezai/cs-b-Assignment4-Pythagora-Tree | ea098fbc9cbdd28c6b05a51463669d566089584d | 8ffe9b9df30a8c1d58d3c26a70772bfd472767f3 | refs/heads/master | 2021-01-10T03:50:09.954824 | 2016-01-22T21:47:16 | 2016-01-22T21:47:16 | 50,208,739 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,468 | cpp | #include <iostream>
#include "console.h"
#include "simpio.h"
#include "vector.h"
#include "gtypes.h"
#include <cmath>
#include "gwindow.h"
#include "gobjects.h"
using namespace std;
/*
* Constants display settings
*/
const int WINDOW_WIDTH = 600;
const int WINDOW_HEIGHT = 350;
/*
*Constant density of the rendering tree
*/
const int COUNT = 11;
const double Pi = 3.14159;
/*
*The function recursively draws Pythagoras Tree with a given density.
*function used to display the polar line
*@param gw - object reference of the graphics window
*@param leftPoint - object starting point of the left line
*@param rightPoint - object starting point of the right line
*@param startLench - starting line length
*@param angle - starting angle of slope line
*@param count - count the recursion depth
*/
void recursivTree(GWindow &gw,
GPoint leftPoint,
GPoint rightPoint,
double startLench,
double angle,
int count){
if (count == 0) return;
double newLineLench = startLench * cos( 45 * Pi / 180);
gw.setColor("BLUE");
GPoint lineLeft = gw.drawPolarLine(leftPoint, newLineLench, angle +45);
GPoint longLineLeft = gw.drawPolarLine(leftPoint, newLineLench * 2, angle -45);
gw.drawLine(rightPoint, leftPoint);
GPoint longLineRight = gw.drawPolarLine(rightPoint, newLineLench * 2, angle +45);
GPoint lineRight = gw.drawPolarLine(rightPoint, newLineLench, angle -45);
GPoint newleftPoint1(lineLeft.getX(),
lineLeft.getY());
GPoint newrightPoint1(longLineRight.getX(),
longLineRight.getY());
GPoint newleftPoint2(longLineLeft.getX(),
longLineLeft.getY());
GPoint newrightPoint2(lineRight.getX(),
lineRight.getY());
gw.drawLine(newleftPoint1, newrightPoint1);
gw.drawLine(newleftPoint2, newrightPoint2);
count--;
recursivTree(gw,
newleftPoint1,
newrightPoint1,
newLineLench,
angle+45, count);
recursivTree(gw,
newleftPoint2,
newrightPoint2,
newLineLench,
angle-45, count);
}
/*
*Function sets and draws start parameters for drawing Pythagoras Tree
*Also runs the a recursive drawing the Pythagorean tree entirely.
*/
void drawPythagorTree(){
GWindow graphicsWindow(WINDOW_WIDTH,WINDOW_HEIGHT);
graphicsWindow.setColor("BLUE");
double angle = 90;
double startLineLength = graphicsWindow.getHeight() / 4;
GPoint leftPoint((graphicsWindow.getWidth() - startLineLength) / 2,
graphicsWindow.getHeight());
GPoint rightPoint((graphicsWindow.getWidth() + startLineLength) / 2,
graphicsWindow.getHeight());
GPoint treeLineLeft = graphicsWindow.drawPolarLine(leftPoint, startLineLength, angle);
GPoint treeLineRight = graphicsWindow.drawPolarLine(rightPoint, startLineLength, angle);
GPoint leftTopPoint(treeLineLeft.getX(),
treeLineLeft.getY());
GPoint rightTopPoint(treeLineRight.getX(),
treeLineRight.getY());
recursivTree(graphicsWindow,
leftTopPoint,
rightTopPoint,
startLineLength,
angle, COUNT);
}
int main()
{
drawPythagorTree();
return 0;
}
| [
"nikolaybezay@gmail.com"
] | nikolaybezay@gmail.com |
bd16b22e2959b8bd97a6e27cdaebe4f600cf3cdd | 4943e45e359035d78585c82b5aa55f4f470fb76e | /src/qt/transactionrecord.h | 077d8a715fd71e5d1508720879f7c39336f7eb4f | [
"MIT"
] | permissive | RevolverCoin/revolvercoin | a07ae49e328079ed37f4c2750dc7eabad8b99ae6 | 05098f04e56afe6f4e72a7a2ecc514a8a38c499d | refs/heads/master | 2020-05-29T14:41:35.519609 | 2016-08-05T14:54:26 | 2016-08-05T14:54:26 | 59,888,865 | 9 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 4,430 | h | // Copyright (c) 2011-2013 The RevolverCoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef REVOLVERCOIN_QT_TRANSACTIONRECORD_H
#define REVOLVERCOIN_QT_TRANSACTIONRECORD_H
#include "amount.h"
#include "uint256.h"
#include <QList>
#include <QString>
class CWallet;
class CWalletTx;
/** UI model for transaction status. The transaction status is the part of a transaction that will change over time.
*/
class TransactionStatus
{
public:
TransactionStatus():
countsForBalance(false), sortKey(""),
matures_in(0), status(Offline), depth(0), open_for(0), cur_num_blocks(-1)
{ }
enum Status {
Confirmed, /**< Have 6 or more confirmations (normal tx) or fully mature (mined tx) **/
/// Normal (sent/received) transactions
OpenUntilDate, /**< Transaction not yet final, waiting for date */
OpenUntilBlock, /**< Transaction not yet final, waiting for block */
Offline, /**< Not sent to any other nodes **/
Unconfirmed, /**< Not yet mined into a block **/
Confirming, /**< Confirmed, but waiting for the recommended number of confirmations **/
Conflicted, /**< Conflicts with other transaction or mempool **/
/// Generated (mined) transactions
Immature, /**< Mined but waiting for maturity */
MaturesWarning, /**< Transaction will likely not mature because no nodes have confirmed */
NotAccepted /**< Mined but not accepted */
};
/// Transaction counts towards available balance
bool countsForBalance;
/// Sorting key based on status
std::string sortKey;
/** @name Generated (mined) transactions
@{*/
int matures_in;
/**@}*/
/** @name Reported status
@{*/
Status status;
qint64 depth;
qint64 open_for; /**< Timestamp if status==OpenUntilDate, otherwise number
of additional blocks that need to be mined before
finalization */
/**@}*/
/** Current number of blocks (to know whether cached status is still valid) */
int cur_num_blocks;
};
/** UI model for a transaction. A core transaction can be represented by multiple UI transactions if it has
multiple outputs.
*/
class TransactionRecord
{
public:
enum Type
{
Other,
Generated,
SendToAddress,
SendToOther,
RecvWithAddress,
RecvFromOther,
SendToSelf
};
/** Number of confirmation recommended for accepting a transaction */
static const int RecommendedNumConfirmations = 6;
TransactionRecord():
hash(), time(0), type(Other), address(""), debit(0), credit(0), idx(0)
{
}
TransactionRecord(uint256 hash, qint64 time):
hash(hash), time(time), type(Other), address(""), debit(0),
credit(0), idx(0)
{
}
TransactionRecord(uint256 hash, qint64 time,
Type type, const std::string &address,
const CAmount& debit, const CAmount& credit):
hash(hash), time(time), type(type), address(address), debit(debit), credit(credit),
idx(0)
{
}
/** Decompose CWallet transaction to model transaction records.
*/
static bool showTransaction(const CWalletTx &wtx);
static QList<TransactionRecord> decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx);
/** @name Immutable transaction attributes
@{*/
uint256 hash;
qint64 time;
Type type;
std::string address;
CAmount debit;
CAmount credit;
/**@}*/
/** Subtransaction index, for sort key */
int idx;
/** Status: can change with block chain update */
TransactionStatus status;
/** Whether the transaction was sent/received with a watch-only address */
bool involvesWatchAddress;
/** Return the unique identifier for this transaction (part) */
QString getTxID() const;
/** Format subtransaction id */
static QString formatSubTxId(const uint256 &hash, int vout);
/** Update status from core wallet tx.
*/
void updateStatus(const CWalletTx &wtx);
/** Return whether a status update is needed.
*/
bool statusUpdateNeeded();
};
#endif // REVOLVERCOIN_QT_TRANSACTIONRECORD_H
| [
"andy.sevens.777@gmail.com"
] | andy.sevens.777@gmail.com |
993def421df4590a34724d81a63580cb7e0106eb | fbf97ead629f3e17a0763775d139c8c81c58e137 | /gearmand/gearmand.cc | bad6f806803c00663d64a72a1543886745446149 | [
"BSD-3-Clause"
] | permissive | xuyanjun/gearman | 6f0b30db38ec89c2140b0330107151d0d3329555 | 36af368d6a0628f30f0654cc3ce2801c758ba292 | refs/heads/master | 2021-06-08T07:56:48.118138 | 2019-09-12T04:36:56 | 2019-09-12T04:36:56 | 5,254,592 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,803 | cc | /* Gearman server and library
*
* Copyright (C) 2011 Data Differential LLC
* Copyright (C) 2008 Brian Aker, Eric Day
* All rights reserved.
*
* Use and distribution licensed under the BSD license. See
* the COPYING file in the parent directory for full text.
*/
#include <config.h>
#include <configmake.h>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <fstream>
#include <pwd.h>
#include <signal.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <syslog.h>
#include <unistd.h>
#ifdef TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
#endif
#include <libgearman-server/gearmand.h>
#include <libgearman-server/plugins.h>
#include <libgearman-server/queue.hpp>
#define GEARMAND_LOG_REOPEN_TIME 60
#include "util/daemon.hpp"
#include "util/pidfile.hpp"
#include <boost/program_options.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/token_functions.hpp>
#include <boost/tokenizer.hpp>
#include <iostream>
#include "gearmand/error.hpp"
#include "gearmand/log.hpp"
using namespace datadifferential;
using namespace gearmand;
static bool _set_fdlimit(rlim_t fds);
static bool _switch_user(const char *user);
extern "C" {
static bool _set_signals(void);
}
static void _log(const char *line, gearmand_verbose_t verbose, void *context);
int main(int argc, char *argv[])
{
int backlog;
rlim_t fds= 0;
uint32_t job_retries;
uint32_t worker_wakeup;
std::string host;
std::string user;
std::string log_file;
std::string pid_file;
std::string protocol;
std::string queue_type;
std::string verbose_string= "ERROR";
std::string config_file;
uint32_t threads;
bool opt_round_robin;
bool opt_daemon;
bool opt_check_args;
bool opt_syslog;
boost::program_options::options_description general("General options");
general.add_options()
("backlog,b", boost::program_options::value(&backlog)->default_value(32),
"Number of backlog connections for listen.")
("daemon,d", boost::program_options::bool_switch(&opt_daemon)->default_value(false),
"Daemon, detach and run in the background.")
("file-descriptors,f", boost::program_options::value(&fds),
"Number of file descriptors to allow for the process (total connections will be slightly less). Default is max allowed for user.")
("help,h", "Print this help menu.")
("job-retries,j", boost::program_options::value(&job_retries)->default_value(0),
"Number of attempts to run the job before the job server removes it. This is helpful to ensure a bad job does not crash all available workers. Default is no limit.")
("log-file,l", boost::program_options::value(&log_file)->default_value(LOCALSTATEDIR"/log/gearmand.log"),
"Log file to write errors and information to. If the log-file paramater is specified as 'stderr', then output will go to stderr. If 'none', then no logfile will be generated.")
("listen,L", boost::program_options::value(&host),
"Address the server should listen on. Default is INADDR_ANY.")
("pid-file,P", boost::program_options::value(&pid_file)->default_value(GEARMAND_PID),
"File to write process ID out to.")
("protocol,r", boost::program_options::value(&protocol),
"Load protocol module.")
("round-robin,R", boost::program_options::bool_switch(&opt_round_robin)->default_value(false),
"Assign work in round-robin order per worker connection. The default is to assign work in the order of functions added by the worker.")
("queue-type,q", boost::program_options::value(&queue_type)->default_value("builtin"),
"Persistent queue type to use.")
("config-file", boost::program_options::value(&config_file)->default_value(GEARMAND_CONFIG),
"Can be specified with '@name', too")
("syslog", boost::program_options::bool_switch(&opt_syslog)->default_value(false),
"Use syslog.")
("threads,t", boost::program_options::value(&threads)->default_value(4),
"Number of I/O threads to use. Default=4.")
("user,u", boost::program_options::value(&user),
"Switch to given user after startup.")
("verbose", boost::program_options::value(&verbose_string)->default_value(verbose_string),
"Set verbose level (FATAL, ALERT, CRITICAL, ERROR, WARNING, NOTICE, INFO, DEBUG).")
("version,V", "Display the version of gearmand and exit.")
("worker-wakeup,w", boost::program_options::value(&worker_wakeup)->default_value(0),
"Number of workers to wakeup for each job received. The default is to wakeup all available workers.")
;
boost::program_options::options_description all("Allowed options");
all.add(general);
gearmand::protocol::HTTP http;
all.add(http.command_line_options());
gearmand::protocol::Gear gear;
all.add(gear.command_line_options());
gearmand::plugins::initialize(all);
boost::program_options::positional_options_description positional;
positional.add("provided", -1);
// Now insert all options that we want to make visible to the user
boost::program_options::options_description visible("Allowed options");
visible.add(all);
boost::program_options::options_description hidden("Hidden options");
hidden.add_options()
("check-args", boost::program_options::bool_switch(&opt_check_args)->default_value(false),
"Check command line and configuration file argments and then exit.");
all.add(hidden);
boost::program_options::variables_map vm;
try {
// Disable allow_guessing
int style= boost::program_options::command_line_style::default_style ^ boost::program_options::command_line_style::allow_guessing;
boost::program_options::parsed_options parsed= boost::program_options::command_line_parser(argc, argv)
.options(all)
.positional(positional)
.style(style)
.run();
store(parsed, vm);
notify(vm);
if (config_file.empty() == false)
{
// Load the file and tokenize it
std::ifstream ifs(config_file.c_str());
if (ifs)
{
// Read the whole file into a string
std::stringstream ss;
ss << ifs.rdbuf();
// Split the file content
boost::char_separator<char> sep(" \n\r");
std::string sstr= ss.str();
boost::tokenizer<boost::char_separator<char> > tok(sstr, sep);
std::vector<std::string> args;
std::copy(tok.begin(), tok.end(), back_inserter(args));
for (std::vector<std::string>::iterator iter= args.begin();
iter != args.end();
++iter)
{
std::cerr << *iter << std::endl;
}
// Parse the file and store the options
store(boost::program_options::command_line_parser(args).options(visible).run(), vm);
}
else if (config_file.compare(GEARMAND_CONFIG))
{
error::message("Could not open configuration file.");
return EXIT_FAILURE;
}
}
notify(vm);
}
catch(boost::program_options::validation_error &e)
{
error::message(e.what());
return EXIT_FAILURE;
}
catch(std::exception &e)
{
if (e.what() and strncmp("-v", e.what(), 2) == 0)
{
error::message("Option -v has been deprecated, please use --verbose");
}
else
{
error::message(e.what());
}
return EXIT_FAILURE;
}
gearmand_verbose_t verbose= GEARMAND_VERBOSE_ERROR;
if (gearmand_verbose_check(verbose_string.c_str(), verbose) == false)
{
error::message("Invalid value for --verbose supplied");
return EXIT_FAILURE;
}
if (opt_check_args)
{
return EXIT_SUCCESS;
}
if (vm.count("help"))
{
std::cout << visible << std::endl;
return EXIT_SUCCESS;
}
if (vm.count("version"))
{
std::cout << std::endl << "gearmand " << gearmand_version() << " - " << gearmand_bugreport() << std::endl;
return EXIT_SUCCESS;
}
if (fds > 0 && _set_fdlimit(fds))
{
return EXIT_FAILURE;
}
if (not user.empty() and _switch_user(user.c_str()))
{
return EXIT_FAILURE;
}
if (opt_daemon)
{
util::daemonize(false, true);
}
if (_set_signals())
{
return EXIT_FAILURE;
}
util::Pidfile _pid_file(pid_file);
if (_pid_file.create() == false and pid_file.compare(GEARMAND_PID))
{
error::perror(_pid_file.error_message().c_str());
return EXIT_FAILURE;
}
gearmand::gearmand_log_info_st log_info(log_file, opt_syslog);
if (log_info.initialized() == false)
{
return EXIT_FAILURE;
}
gearmand_st *_gearmand= gearmand_create(host.empty() ? NULL : host.c_str(),
threads, backlog,
static_cast<uint8_t>(job_retries),
static_cast<uint8_t>(worker_wakeup),
_log, &log_info, verbose,
opt_round_robin);
if (_gearmand == NULL)
{
error::message("Could not create gearmand library instance.");
return EXIT_FAILURE;
}
if (queue_type.empty() == false)
{
gearmand_error_t rc;
if ((rc= gearmand::queue::initialize(_gearmand, queue_type.c_str())) != GEARMAN_SUCCESS)
{
error::message("Error while initializing the queue", queue_type.c_str());
gearmand_free(_gearmand);
return EXIT_FAILURE;
}
}
if (gear.start(_gearmand) != GEARMAN_SUCCESS)
{
error::message("Error while enabling Gear protocol module");
gearmand_free(_gearmand);
return EXIT_FAILURE;
}
if (protocol.compare("http") == 0)
{
if (http.start(_gearmand) != GEARMAN_SUCCESS)
{
error::message("Error while enabling protocol module", protocol.c_str());
gearmand_free(_gearmand);
return EXIT_FAILURE;
}
}
else if (protocol.empty() == false)
{
error::message("Unknown protocol module", protocol.c_str());
gearmand_free(_gearmand);
return EXIT_FAILURE;
}
if (opt_daemon)
{
if (util::daemon_is_ready(true) == false)
{
return EXIT_FAILURE;
}
}
gearmand_error_t ret= gearmand_run(_gearmand);
gearmand_free(_gearmand);
return (ret == GEARMAN_SUCCESS || ret == GEARMAN_SHUTDOWN) ? 0 : 1;
}
static bool _set_fdlimit(rlim_t fds)
{
struct rlimit rl;
if (getrlimit(RLIMIT_NOFILE, &rl) == -1)
{
error::perror("Could not get file descriptor limit");
return true;
}
rl.rlim_cur= fds;
if (rl.rlim_max < rl.rlim_cur)
{
rl.rlim_max= rl.rlim_cur;
}
if (setrlimit(RLIMIT_NOFILE, &rl) == -1)
{
error::perror("Failed to set limit for the number of file "
"descriptors. Try running as root or giving a "
"smaller value to -f.");
return true;
}
return false;
}
static bool _switch_user(const char *user)
{
if (getuid() == 0 or geteuid() == 0)
{
struct passwd *pw= getpwnam(user);
if (not pw)
{
error::message("Could not find user", user);
return EXIT_FAILURE;
}
if (setgid(pw->pw_gid) == -1 || setuid(pw->pw_uid) == -1)
{
error::message("Could not switch to user", user);
return EXIT_FAILURE;
}
}
else
{
error::message("Must be root to switch users.");
return true;
}
return false;
}
static void _shutdown_handler(int signal_arg)
{
if (signal_arg == SIGUSR1)
{
gearmand_wakeup(Gearmand(), GEARMAND_WAKEUP_SHUTDOWN_GRACEFUL);
}
else
{
gearmand_wakeup(Gearmand(), GEARMAND_WAKEUP_SHUTDOWN);
}
}
static void _reset_log_handler(int signal_arg)
{
gearmand_log_info_st *log_info= static_cast<gearmand_log_info_st *>(Gearmand()->log_context);
log_info->reset();
}
extern "C" {
static bool _set_signals(void)
{
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler= SIG_IGN;
if (sigemptyset(&sa.sa_mask) == -1 or
sigaction(SIGPIPE, &sa, 0) == -1)
{
error::perror("Could not set SIGPIPE handler.");
return true;
}
sa.sa_handler= _shutdown_handler;
if (sigaction(SIGTERM, &sa, 0) == -1)
{
error::perror("Could not set SIGTERM handler.");
return true;
}
if (sigaction(SIGINT, &sa, 0) == -1)
{
error::perror("Could not set SIGINT handler.");
return true;
}
if (sigaction(SIGUSR1, &sa, 0) == -1)
{
error::perror("Could not set SIGUSR1 handler.");
return true;
}
sa.sa_handler= _reset_log_handler;
if (sigaction(SIGHUP, &sa, 0) == -1)
{
error::perror("Could not set SIGHUP handler.");
return true;
}
return false;
}
}
static void _log(const char *mesg, gearmand_verbose_t verbose, void *context)
{
gearmand_log_info_st *log_info= static_cast<gearmand_log_info_st *>(context);
log_info->write(verbose, mesg);
}
| [
"yanjun.xu@samsung.com"
] | yanjun.xu@samsung.com |
1ef08d08aafd3ded5022afa7998f38abd428c401 | e1de1cc63a9325519ac1e070250bead0f22823ea | /textmagic-rest-cpp-v2/HttpContent.cpp | d365f9b080d37de3adb5e1eacc553dc427e55516 | [
"MIT"
] | permissive | WeilerWebServices/textmagic | 03abd875726a0d548f789aa06f6d1b392c1f4a2b | f7ad8cb2989bccb7afba9e30915f8575dd1b0b81 | refs/heads/master | 2023-01-28T03:55:52.739564 | 2020-12-14T04:17:59 | 2020-12-14T04:17:59 | 321,150,541 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,501 | cpp | /**
* TextMagic API
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 2
*
*
* NOTE: This class is auto generated by the swagger code generator 2.4.8.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "HttpContent.h"
namespace com {
namespace textmagic {
namespace client {
namespace model {
HttpContent::HttpContent()
{
}
HttpContent::~HttpContent()
{
}
utility::string_t HttpContent::getContentDisposition()
{
return m_ContentDisposition;
}
void HttpContent::setContentDisposition( const utility::string_t & value )
{
m_ContentDisposition = value;
}
utility::string_t HttpContent::getName()
{
return m_Name;
}
void HttpContent::setName( const utility::string_t & value )
{
m_Name = value;
}
utility::string_t HttpContent::getFileName()
{
return m_FileName;
}
void HttpContent::setFileName( const utility::string_t & value )
{
m_FileName = value;
}
utility::string_t HttpContent::getContentType()
{
return m_ContentType;
}
void HttpContent::setContentType( const utility::string_t & value )
{
m_ContentType = value;
}
std::shared_ptr<std::istream> HttpContent::getData()
{
return m_Data;
}
void HttpContent::setData( std::shared_ptr<std::istream> value )
{
m_Data = value;
}
void HttpContent::writeTo( std::ostream& stream )
{
m_Data->seekg( 0, m_Data->beg );
stream << m_Data->rdbuf();
}
}
}
}
}
| [
"nateweiler84@gmail.com"
] | nateweiler84@gmail.com |
3fa6d81a5f8ae7bb8268991ea577ccfee0b6d18b | 47b29e8883db097fb4b1e8d424757e4f1b4046fc | /cc/dual_net_test.cc | 901a391c4cc526e849769bb5da8ee21602852913 | [
"Apache-2.0"
] | permissive | lukw00heck/minigo | f0d50bd689d78326262d860ae7b850fb0ee5b0fb | 21b891c0642566400c4ec5d2992aab54532425ba | refs/heads/master | 2020-03-07T14:42:47.949945 | 2018-03-28T21:10:49 | 2018-03-28T21:10:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,264 | cc | // Copyright 2018 Google LLC
//
// 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 "cc/dual_net.h"
#include <array>
#include "cc/position.h"
#include "cc/test_utils.h"
#include "gtest/gtest.h"
namespace minigo {
namespace {
using StoneFeatures = DualNet::StoneFeatures;
using BoardFeatures = DualNet::BoardFeatures;
StoneFeatures GetStoneFeatures(const BoardFeatures& features, Coord c) {
StoneFeatures result;
for (int i = 0; i < DualNet::kNumStoneFeatures; ++i) {
result[i] = features[c * DualNet::kNumStoneFeatures + i];
}
return result;
}
// Verifies InitializeFeatures for an empty board with black to play.
TEST(DualNetTest, TestInitializeFeaturesBlackToPlay) {
TestablePosition board("", 0, Color::kBlack);
BoardFeatures features;
DualNet::InitializeFeatures(board, &features);
for (int c = 0; c < kN * kN; ++c) {
auto f = GetStoneFeatures(features, c);
for (int i = 0; i < DualNet::kPlayerFeature; ++i) {
EXPECT_EQ(0, f[i]);
}
EXPECT_EQ(1, f[DualNet::kPlayerFeature]);
}
}
// Verifies InitializeFeatures for an empty board with white to play.
TEST(DualNetTest, TestInitializeFeaturesWhiteToPlay) {
TestablePosition board("", 0, Color::kWhite);
BoardFeatures features;
DualNet::InitializeFeatures(board, &features);
for (int c = 0; c < kN * kN; ++c) {
auto f = GetStoneFeatures(features, c);
for (int i = 0; i < DualNet::kPlayerFeature; ++i) {
EXPECT_EQ(0, f[i]);
}
EXPECT_EQ(0, f[DualNet::kPlayerFeature]);
}
}
// Verifies UpdateFeatures.
TEST(DualNetTest, TestUpdateFeatures) {
TestablePosition board("");
BoardFeatures features;
DualNet::InitializeFeatures(board, &features);
std::vector<std::string> moves = {"B9", "H9", "A8", "J9"};
for (const auto& move : moves) {
board.PlayMove(move);
DualNet::UpdateFeatures(features, board, &features);
}
// B0 W0 B1 W1 B2 W2 B3 W3 B4 W4 B5 W5 B6 W6 B7 W7 P
StoneFeatures b9 = {1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
StoneFeatures h9 = {0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
StoneFeatures a8 = {1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
StoneFeatures j9 = {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
EXPECT_EQ(b9, GetStoneFeatures(features, Coord::FromString("B9")));
EXPECT_EQ(h9, GetStoneFeatures(features, Coord::FromString("H9")));
EXPECT_EQ(a8, GetStoneFeatures(features, Coord::FromString("A8")));
EXPECT_EQ(j9, GetStoneFeatures(features, Coord::FromString("J9")));
}
// Verfies that features work as expected when capturing.
TEST(DualNetTest, TestStoneFeaturesWithCapture) {
TestablePosition board("");
BoardFeatures features;
DualNet::InitializeFeatures(board, &features);
std::vector<std::string> moves = {"J3", "pass", "H2", "J2",
"J1", "pass", "J2"};
for (const auto& move : moves) {
board.PlayMove(move);
DualNet::UpdateFeatures(features, board, &features);
}
// W0 B0 W1 B1 W2 B2 W3 B3 W4 B4 W5 B5 W6 B6 W7 B7 P
StoneFeatures j2 = {0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
EXPECT_EQ(j2, GetStoneFeatures(features, Coord::FromString("J2")));
}
// Verifies that UpdateFeatures generates the correct features when the same
// object is passed for both old_features and new_features.
TEST(DualNetTest, TestUpdateFeaturesSameObject) {
TestablePosition board("");
BoardFeatures a, b;
DualNet::InitializeFeatures(board, &a);
std::vector<std::string> moves = {"A9", "B9", "A8", "D3"};
for (const auto& move : moves) {
board.PlayMove(move);
DualNet::UpdateFeatures(a, board, &b);
DualNet::UpdateFeatures(a, board, &a);
ASSERT_EQ(a, b);
}
}
} // namespace
} // namespace minigo
| [
"noreply@github.com"
] | noreply@github.com |
5a1dd80ebbb29f9260438262391ef15f0b5caf77 | 7797740f06f9e6d6729fd49697d8917e28c172d1 | /lite/model_parser/pb/program_desc.h | 4827cf10d6b81b6dcd33a94fb216719027110c2b | [
"Apache-2.0"
] | permissive | AnBaolei1984/Paddle-Lite | 508f567f27403dabd097c69f3cc4cc239d3fe933 | db4bd998d5fdabddbcf0eb28951787eb008eeb19 | refs/heads/develop | 2021-11-21T12:18:38.346264 | 2021-01-28T02:57:01 | 2021-01-28T02:57:01 | 333,635,248 | 2 | 1 | Apache-2.0 | 2021-07-27T02:52:39 | 2021-01-28T03:33:20 | null | UTF-8 | C++ | false | false | 2,293 | h | // Copyright (c) 2019 PaddlePaddle 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.
#pragma once
#include <map>
#include <string>
#include <vector>
#include "lite/core/framework.pb.h"
#include "lite/model_parser/base/apis.h"
#include "lite/utils/cp_logging.h"
namespace paddle {
namespace lite {
namespace pb {
class ProgramDesc : public ProgramDescAPI {
public:
ProgramDesc() = delete;
explicit ProgramDesc(framework::proto::ProgramDesc *desc) : desc_(desc) {
CHECK(desc_);
}
framework::proto::ProgramDesc *Proto() { return desc_; }
const framework::proto::ProgramDesc &ReadonlyProto() const { return *desc_; }
size_t BlocksSize() const override { return desc_->blocks_size(); }
void ClearBlocks() override { desc_->clear_blocks(); }
template <typename T>
T *GetBlock(int32_t idx);
template <typename T>
T const *GetBlock(int32_t idx) const {
return GetBlock<T>(idx);
}
template <typename T>
T *AddBlock();
/////////////////////////////////////////////////////////////////
// Name: OpVersionMap
// Description: a map that strores paddle ops version
/////////////////////////////////////////////////////////////////
bool HasOpVersionMap() const override { return desc_->has_op_version_map(); }
template <typename T>
T *GetOpVersionMap();
void SetOpVersionMap(std::map<std::string, int32_t> op_version_map) {}
bool HasVersion() const override { return desc_->has_version(); }
int64_t Version() const override { return desc_->version().version(); }
void SetVersion(int64_t version) override {
desc_->mutable_version()->set_version(version);
}
private:
framework::proto::ProgramDesc *desc_; // not_own
};
} // namespace pb
} // namespace lite
} // namespace paddle
| [
"noreply@github.com"
] | noreply@github.com |
f3c62257a455e7fc5a411939f01eb895b4da6177 | dd8177d820f8ca354ae2827ee8d12c9651bfc6c8 | /SquareRoot/SquareRoot.cpp | 1b13fa48c8269b4728b481e76790553944400b7c | [] | no_license | suresh-yetukuri/SI-Practice | d53d9d26e3d9497244f7915eed96f35349b18587 | ba11d3f71463681b849d2f127a6967833fe98b29 | refs/heads/master | 2022-10-11T21:37:55.516778 | 2020-06-08T23:54:54 | 2020-06-08T23:54:54 | 245,960,273 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,344 | cpp | // SquareRoot.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
using namespace std;
namespace PerfectSquare
{
/*
N^(1/2), 1
*/
namespace BruteForce
{
int SquareRoot(int K)
{
for (int iCounter = 0; iCounter <= K; ++iCounter)
{
if ((static_cast<long long int>(iCounter)* iCounter) == K)
return iCounter;
}
return -1;
}
}
/*
LogN, 1
*/
namespace BinarySearch
{
int SquareRoot(int K)
{
int Low = 0;
int High = K;
while (Low <= High)
{
int Mid = Low + ((High - Low) >> 1);
long long int oSquare = static_cast<long long int>(Mid)* Mid;
if (oSquare < K)
Low = Mid + 1;
else if (oSquare > K)
High = Mid - 1;
else
return Mid;
}
return -1;
}
}
}
namespace NonPerfectSquare
{
/*
N^(1/2), 1
*/
namespace BruteForce
{
int SquareRoot(int K)
{
for (int iCounter = 0; iCounter <= K; ++iCounter)
{
long long int oSquare = static_cast<long long int>(iCounter)* iCounter;
if (oSquare == K)
return iCounter;
if (oSquare > K)
return iCounter - 1;
}
return -1;
}
}
/*
LogN, 1
*/
namespace BinarySearch
{
int SquareRoot(int K)
{
long long int Low = 0;
long long int High = K;
// Why do we need long long int for Mid. This is because if K = INT_MAX, then expression for
// calculation of Mid would overflow
while (Low < High)
{
long long int Mid = Low + ((static_cast<long long int>(High) - Low + 1) >> 1);
long long int oSquare = Mid*Mid;
if (oSquare <= K)
Low = Mid;
else if (oSquare > K)
High = Mid - 1;
}
return static_cast<int>(Low);
}
}
}
int main()
{
cout << NonPerfectSquare::BinarySearch::SquareRoot(2147483647) << endl;
cout << NonPerfectSquare::BinarySearch::SquareRoot(24)<<endl;
cout << NonPerfectSquare::BinarySearch::SquareRoot(25)<<endl;
cout << NonPerfectSquare::BinarySearch::SquareRoot(40)<<endl;
cout << NonPerfectSquare::BinarySearch::SquareRoot((int)1e9)<<endl;
return 0;
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| [
"Suresh.Yetukuri@kofax.com"
] | Suresh.Yetukuri@kofax.com |
c66d6b5ae16e1c028b8590b56d30a58e30fcb81c | f51f6c330279d5005a8117a8ecad12d6924b1c73 | /fmSensors/src/odometry_feedback/ll_encoder_node.cpp | 45de84f8fa4ab8b185c080461945983082b8786c | [] | no_license | rsdgroup3/FroboMind-Fuerte | 14c8d197f26ae5c14a59ed30a8ece7a81d395f60 | 3b6891fe06d6953a510c3dd3ad7e733b3165459b | refs/heads/master | 2021-01-17T22:56:50.237070 | 2013-01-17T11:57:06 | 2013-01-17T11:57:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,806 | cpp | /*
* ll_encoder_node.cpp
*
* Created on: Feb 22, 2012
* Author: molar
*/
#include "LeineLindeEncoder.h"
#include <ros/ros.h>
#include <ros/console.h>
#include <fmMsgs/can.h>
#include <fmMsgs/encoder.h>
int main(int argc, char **argv)
{
ros::init(argc, argv, "encoder_node");
ros::NodeHandle nh("~");
ros::NodeHandle n;
ROS_INFO("Started!");
LeineLindeEncoder ll;
//returned objects needs to be stored
ros::Timer t;
ros::Subscriber sub;
bool invert,read_offset;
std::string enc_publisher_topic;
std::string publisher_topic;
std::string subscriber_topic;
int encoder_id,publish_rate,poll_interval_ms;
nh.param<std::string>("publisher_topic", publisher_topic, "/fmSensors/can0_tx");
nh.param<std::string>("subscriber_topic", subscriber_topic, "/fmSensors/can0_rx");
nh.param<std::string>("enc_publisher_topic", enc_publisher_topic, "/fmSensors/encoder");
nh.param<int>("encoder_id", encoder_id, 11);
nh.param<int>("publish_rate",publish_rate,10);
nh.param<int>("poll_interval_ms",poll_interval_ms,20);
nh.param<bool>("invert_output",invert,false);
nh.param<bool>("use_current_position_as_offset",read_offset,true);
ll.setID(encoder_id);
ll.setPollInterval(poll_interval_ms);
ll.invert = invert;
ll.read_encoder_offset = read_offset;
ll.setCanPub(nh.advertise<fmMsgs::can> (publisher_topic.c_str(), 5));
ll.setEncoderPub(nh.advertise<fmMsgs::encoder> (enc_publisher_topic.c_str(), 5));
sub = nh.subscribe<fmMsgs::can> (subscriber_topic.c_str(), 100, &LeineLindeEncoder::processRXEvent, &ll);
t= nh.createTimer(ros::Duration(1.0/publish_rate),&LeineLindeEncoder::processStateMachine,&ll);
ROS_INFO("Running with: rate %d interval %d, enc_id: %d",publish_rate,poll_interval_ms,encoder_id);
ros::spin();
return 0;
}
| [
"mortenlarsens@gmail.com"
] | mortenlarsens@gmail.com |
2e93c3cce5016ec6658d54d6c1f00bad114f59ae | 03dbf243e7877023f82232872a9886ff253b3829 | /lib/asan/asan_descriptions.cc | c1578ba632f5b6e398fe32bbb5b55370bbeee1f2 | [
"NCSA",
"MIT"
] | permissive | linux-on-ibm-z/compiler-rt | a93f04406d49f5e7bc5d3c77e7a78874a8a4552c | d4837a858b3522434619b7a424f48342bbb6ed2d | refs/heads/master | 2020-12-25T16:35:49.619336 | 2016-09-14T07:37:20 | 2016-09-14T07:37:20 | 68,209,109 | 0 | 0 | null | 2016-09-14T13:33:11 | 2016-09-14T13:33:10 | null | UTF-8 | C++ | false | false | 16,538 | cc | //===-- asan_descriptions.cc ------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// ASan functions for getting information about an address and/or printing it.
//===----------------------------------------------------------------------===//
#include "asan_descriptions.h"
#include "asan_mapping.h"
#include "asan_report.h"
#include "asan_stack.h"
#include "sanitizer_common/sanitizer_stackdepot.h"
namespace __asan {
// Return " (thread_name) " or an empty string if the name is empty.
const char *ThreadNameWithParenthesis(AsanThreadContext *t, char buff[],
uptr buff_len) {
const char *name = t->name;
if (name[0] == '\0') return "";
buff[0] = 0;
internal_strncat(buff, " (", 3);
internal_strncat(buff, name, buff_len - 4);
internal_strncat(buff, ")", 2);
return buff;
}
const char *ThreadNameWithParenthesis(u32 tid, char buff[], uptr buff_len) {
if (tid == kInvalidTid) return "";
asanThreadRegistry().CheckLocked();
AsanThreadContext *t = GetThreadContextByTidLocked(tid);
return ThreadNameWithParenthesis(t, buff, buff_len);
}
void DescribeThread(AsanThreadContext *context) {
CHECK(context);
asanThreadRegistry().CheckLocked();
// No need to announce the main thread.
if (context->tid == 0 || context->announced) {
return;
}
context->announced = true;
char tname[128];
InternalScopedString str(1024);
str.append("Thread T%d%s", context->tid,
ThreadNameWithParenthesis(context->tid, tname, sizeof(tname)));
if (context->parent_tid == kInvalidTid) {
str.append(" created by unknown thread\n");
Printf("%s", str.data());
return;
}
str.append(
" created by T%d%s here:\n", context->parent_tid,
ThreadNameWithParenthesis(context->parent_tid, tname, sizeof(tname)));
Printf("%s", str.data());
StackDepotGet(context->stack_id).Print();
// Recursively described parent thread if needed.
if (flags()->print_full_thread_history) {
AsanThreadContext *parent_context =
GetThreadContextByTidLocked(context->parent_tid);
DescribeThread(parent_context);
}
}
// Shadow descriptions
static bool GetShadowKind(uptr addr, ShadowKind *shadow_kind) {
CHECK(!AddrIsInMem(addr));
if (AddrIsInShadowGap(addr)) {
*shadow_kind = kShadowKindGap;
} else if (AddrIsInHighShadow(addr)) {
*shadow_kind = kShadowKindHigh;
} else if (AddrIsInLowShadow(addr)) {
*shadow_kind = kShadowKindLow;
} else {
CHECK(0 && "Address is not in memory and not in shadow?");
return false;
}
return true;
}
bool DescribeAddressIfShadow(uptr addr) {
ShadowAddressDescription descr;
if (!GetShadowAddressInformation(addr, &descr)) return false;
descr.Print();
return true;
}
bool GetShadowAddressInformation(uptr addr, ShadowAddressDescription *descr) {
if (AddrIsInMem(addr)) return false;
ShadowKind shadow_kind;
if (!GetShadowKind(addr, &shadow_kind)) return false;
if (shadow_kind != kShadowKindGap) descr->shadow_byte = *(u8 *)addr;
descr->addr = addr;
descr->kind = shadow_kind;
return true;
}
// Heap descriptions
static void GetAccessToHeapChunkInformation(ChunkAccess *descr,
AsanChunkView chunk, uptr addr,
uptr access_size) {
descr->bad_addr = addr;
if (chunk.AddrIsAtLeft(addr, access_size, &descr->offset)) {
descr->access_type = kAccessTypeLeft;
} else if (chunk.AddrIsAtRight(addr, access_size, &descr->offset)) {
descr->access_type = kAccessTypeRight;
if (descr->offset < 0) {
descr->bad_addr -= descr->offset;
descr->offset = 0;
}
} else if (chunk.AddrIsInside(addr, access_size, &descr->offset)) {
descr->access_type = kAccessTypeInside;
} else {
descr->access_type = kAccessTypeUnknown;
}
descr->chunk_begin = chunk.Beg();
descr->chunk_size = chunk.UsedSize();
descr->alloc_type = chunk.GetAllocType();
}
static void PrintHeapChunkAccess(uptr addr, const ChunkAccess &descr) {
Decorator d;
InternalScopedString str(4096);
str.append("%s", d.Location());
switch (descr.access_type) {
case kAccessTypeLeft:
str.append("%p is located %zd bytes to the left of",
(void *)descr.bad_addr, descr.offset);
break;
case kAccessTypeRight:
str.append("%p is located %zd bytes to the right of",
(void *)descr.bad_addr, descr.offset);
break;
case kAccessTypeInside:
str.append("%p is located %zd bytes inside of", (void *)descr.bad_addr,
descr.offset);
break;
case kAccessTypeUnknown:
str.append(
"%p is located somewhere around (this is AddressSanitizer bug!)",
(void *)descr.bad_addr);
}
str.append(" %zu-byte region [%p,%p)\n", descr.chunk_size,
(void *)descr.chunk_begin,
(void *)(descr.chunk_begin + descr.chunk_size));
str.append("%s", d.EndLocation());
Printf("%s", str.data());
}
bool GetHeapAddressInformation(uptr addr, uptr access_size,
HeapAddressDescription *descr) {
AsanChunkView chunk = FindHeapChunkByAddress(addr);
if (!chunk.IsValid()) {
return false;
}
descr->addr = addr;
GetAccessToHeapChunkInformation(&descr->chunk_access, chunk, addr,
access_size);
CHECK_NE(chunk.AllocTid(), kInvalidTid);
descr->alloc_tid = chunk.AllocTid();
descr->alloc_stack_id = chunk.GetAllocStackId();
descr->free_tid = chunk.FreeTid();
if (descr->free_tid != kInvalidTid)
descr->free_stack_id = chunk.GetFreeStackId();
return true;
}
static StackTrace GetStackTraceFromId(u32 id) {
CHECK(id);
StackTrace res = StackDepotGet(id);
CHECK(res.trace);
return res;
}
bool DescribeAddressIfHeap(uptr addr, uptr access_size) {
HeapAddressDescription descr;
if (!GetHeapAddressInformation(addr, access_size, &descr)) {
Printf(
"AddressSanitizer can not describe address in more detail "
"(wild memory access suspected).\n");
return false;
}
descr.Print();
return true;
}
// Stack descriptions
bool GetStackAddressInformation(uptr addr, uptr access_size,
StackAddressDescription *descr) {
AsanThread *t = FindThreadByStackAddress(addr);
if (!t) return false;
descr->addr = addr;
descr->tid = t->tid();
// Try to fetch precise stack frame for this access.
AsanThread::StackFrameAccess access;
if (!t->GetStackFrameAccessByAddr(addr, &access)) {
descr->frame_descr = nullptr;
return true;
}
descr->offset = access.offset;
descr->access_size = access_size;
descr->frame_pc = access.frame_pc;
descr->frame_descr = access.frame_descr;
#if SANITIZER_PPC64V1
// On PowerPC64 ELFv1, the address of a function actually points to a
// three-doubleword data structure with the first field containing
// the address of the function's code.
descr->frame_pc = *reinterpret_cast<uptr *>(descr->frame_pc);
#endif
descr->frame_pc += 16;
return true;
}
static void PrintAccessAndVarIntersection(const StackVarDescr &var, uptr addr,
uptr access_size, uptr prev_var_end,
uptr next_var_beg) {
uptr var_end = var.beg + var.size;
uptr addr_end = addr + access_size;
const char *pos_descr = nullptr;
// If the variable [var.beg, var_end) is the nearest variable to the
// current memory access, indicate it in the log.
if (addr >= var.beg) {
if (addr_end <= var_end)
pos_descr = "is inside"; // May happen if this is a use-after-return.
else if (addr < var_end)
pos_descr = "partially overflows";
else if (addr_end <= next_var_beg &&
next_var_beg - addr_end >= addr - var_end)
pos_descr = "overflows";
} else {
if (addr_end > var.beg)
pos_descr = "partially underflows";
else if (addr >= prev_var_end && addr - prev_var_end >= var.beg - addr_end)
pos_descr = "underflows";
}
InternalScopedString str(1024);
str.append(" [%zd, %zd)", var.beg, var_end);
// Render variable name.
str.append(" '");
for (uptr i = 0; i < var.name_len; ++i) {
str.append("%c", var.name_pos[i]);
}
str.append("'");
if (pos_descr) {
Decorator d;
// FIXME: we may want to also print the size of the access here,
// but in case of accesses generated by memset it may be confusing.
str.append("%s <== Memory access at offset %zd %s this variable%s\n",
d.Location(), addr, pos_descr, d.EndLocation());
} else {
str.append("\n");
}
Printf("%s", str.data());
}
bool DescribeAddressIfStack(uptr addr, uptr access_size) {
StackAddressDescription descr;
if (!GetStackAddressInformation(addr, access_size, &descr)) return false;
descr.Print();
return true;
}
// Global descriptions
static void DescribeAddressRelativeToGlobal(uptr addr, uptr access_size,
const __asan_global &g) {
InternalScopedString str(4096);
Decorator d;
str.append("%s", d.Location());
if (addr < g.beg) {
str.append("%p is located %zd bytes to the left", (void *)addr,
g.beg - addr);
} else if (addr + access_size > g.beg + g.size) {
if (addr < g.beg + g.size) addr = g.beg + g.size;
str.append("%p is located %zd bytes to the right", (void *)addr,
addr - (g.beg + g.size));
} else {
// Can it happen?
str.append("%p is located %zd bytes inside", (void *)addr, addr - g.beg);
}
str.append(" of global variable '%s' defined in '",
MaybeDemangleGlobalName(g.name));
PrintGlobalLocation(&str, g);
str.append("' (0x%zx) of size %zu\n", g.beg, g.size);
str.append("%s", d.EndLocation());
PrintGlobalNameIfASCII(&str, g);
Printf("%s", str.data());
}
bool GetGlobalAddressInformation(uptr addr, uptr access_size,
GlobalAddressDescription *descr) {
descr->addr = addr;
int globals_num = GetGlobalsForAddress(addr, descr->globals, descr->reg_sites,
ARRAY_SIZE(descr->globals));
descr->size = globals_num;
descr->access_size = access_size;
return globals_num != 0;
}
bool DescribeAddressIfGlobal(uptr addr, uptr access_size,
const char *bug_type) {
GlobalAddressDescription descr;
if (!GetGlobalAddressInformation(addr, access_size, &descr)) return false;
descr.Print(bug_type);
return true;
}
void ShadowAddressDescription::Print() const {
Printf("Address %p is located in the %s area.\n", addr, ShadowNames[kind]);
}
void GlobalAddressDescription::Print(const char *bug_type) const {
for (int i = 0; i < size; i++) {
DescribeAddressRelativeToGlobal(addr, access_size, globals[i]);
if (0 == internal_strcmp(bug_type, "initialization-order-fiasco") &&
reg_sites[i]) {
Printf(" registered at:\n");
StackDepotGet(reg_sites[i]).Print();
}
}
}
void StackAddressDescription::Print() const {
Decorator d;
char tname[128];
Printf("%s", d.Location());
Printf("Address %p is located in stack of thread T%d%s", addr, tid,
ThreadNameWithParenthesis(tid, tname, sizeof(tname)));
if (!frame_descr) {
Printf("%s\n", d.EndLocation());
return;
}
Printf(" at offset %zu in frame%s\n", offset, d.EndLocation());
// Now we print the frame where the alloca has happened.
// We print this frame as a stack trace with one element.
// The symbolizer may print more than one frame if inlining was involved.
// The frame numbers may be different than those in the stack trace printed
// previously. That's unfortunate, but I have no better solution,
// especially given that the alloca may be from entirely different place
// (e.g. use-after-scope, or different thread's stack).
Printf("%s", d.EndLocation());
StackTrace alloca_stack(&frame_pc, 1);
alloca_stack.Print();
InternalMmapVector<StackVarDescr> vars(16);
if (!ParseFrameDescription(frame_descr, &vars)) {
Printf(
"AddressSanitizer can't parse the stack frame "
"descriptor: |%s|\n",
frame_descr);
// 'addr' is a stack address, so return true even if we can't parse frame
return;
}
uptr n_objects = vars.size();
// Report the number of stack objects.
Printf(" This frame has %zu object(s):\n", n_objects);
// Report all objects in this frame.
for (uptr i = 0; i < n_objects; i++) {
uptr prev_var_end = i ? vars[i - 1].beg + vars[i - 1].size : 0;
uptr next_var_beg = i + 1 < n_objects ? vars[i + 1].beg : ~(0UL);
PrintAccessAndVarIntersection(vars[i], offset, access_size, prev_var_end,
next_var_beg);
}
Printf(
"HINT: this may be a false positive if your program uses "
"some custom stack unwind mechanism or swapcontext\n");
if (SANITIZER_WINDOWS)
Printf(" (longjmp, SEH and C++ exceptions *are* supported)\n");
else
Printf(" (longjmp and C++ exceptions *are* supported)\n");
DescribeThread(GetThreadContextByTidLocked(tid));
}
void HeapAddressDescription::Print() const {
PrintHeapChunkAccess(addr, chunk_access);
asanThreadRegistry().CheckLocked();
AsanThreadContext *alloc_thread = GetThreadContextByTidLocked(alloc_tid);
StackTrace alloc_stack = GetStackTraceFromId(alloc_stack_id);
char tname[128];
Decorator d;
AsanThreadContext *free_thread = nullptr;
if (free_tid != kInvalidTid) {
free_thread = GetThreadContextByTidLocked(free_tid);
Printf("%sfreed by thread T%d%s here:%s\n", d.Allocation(),
free_thread->tid,
ThreadNameWithParenthesis(free_thread, tname, sizeof(tname)),
d.EndAllocation());
StackTrace free_stack = GetStackTraceFromId(free_stack_id);
free_stack.Print();
Printf("%spreviously allocated by thread T%d%s here:%s\n", d.Allocation(),
alloc_thread->tid,
ThreadNameWithParenthesis(alloc_thread, tname, sizeof(tname)),
d.EndAllocation());
} else {
Printf("%sallocated by thread T%d%s here:%s\n", d.Allocation(),
alloc_thread->tid,
ThreadNameWithParenthesis(alloc_thread, tname, sizeof(tname)),
d.EndAllocation());
}
alloc_stack.Print();
DescribeThread(GetCurrentThread());
if (free_thread) DescribeThread(free_thread);
DescribeThread(alloc_thread);
}
AddressDescription::AddressDescription(uptr addr, uptr access_size,
bool shouldLockThreadRegistry) {
if (GetShadowAddressInformation(addr, &data.shadow)) {
data.kind = kAddressKindShadow;
return;
}
if (GetHeapAddressInformation(addr, access_size, &data.heap)) {
data.kind = kAddressKindHeap;
return;
}
bool isStackMemory = false;
if (shouldLockThreadRegistry) {
ThreadRegistryLock l(&asanThreadRegistry());
isStackMemory = GetStackAddressInformation(addr, access_size, &data.stack);
} else {
isStackMemory = GetStackAddressInformation(addr, access_size, &data.stack);
}
if (isStackMemory) {
data.kind = kAddressKindStack;
return;
}
if (GetGlobalAddressInformation(addr, access_size, &data.global)) {
data.kind = kAddressKindGlobal;
return;
}
data.kind = kAddressKindWild;
addr = 0;
}
void PrintAddressDescription(uptr addr, uptr access_size,
const char *bug_type) {
ShadowAddressDescription shadow_descr;
if (GetShadowAddressInformation(addr, &shadow_descr)) {
shadow_descr.Print();
return;
}
GlobalAddressDescription global_descr;
if (GetGlobalAddressInformation(addr, access_size, &global_descr)) {
global_descr.Print(bug_type);
return;
}
StackAddressDescription stack_descr;
if (GetStackAddressInformation(addr, access_size, &stack_descr)) {
stack_descr.Print();
return;
}
HeapAddressDescription heap_descr;
if (GetHeapAddressInformation(addr, access_size, &heap_descr)) {
heap_descr.Print();
return;
}
// We exhausted our possibilities. Bail out.
Printf(
"AddressSanitizer can not describe address in more detail "
"(wild memory access suspected).\n");
}
} // namespace __asan
| [
"me@filcab.net"
] | me@filcab.net |
c44c817e32561ef9576f7c8da74d49301c549020 | ae5521cba3d8c7b8042c145784d55a5f7b3601a5 | /61.cpp | 5644cd49815567d633e9b10933c5fb2d84da4560 | [] | no_license | KonstaMF/500-CPP | 79a59b995933788d994ded9dd44ce2a1d87d6e1e | a7d1bd0a61e0bb9db0c793adce4fb6a204054ba9 | refs/heads/master | 2023-06-23T00:37:40.095306 | 2021-07-18T07:45:07 | 2021-07-18T07:45:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,114 | cpp | // C++ program to find length of
// the longest bitonic subarray
#include <bits/stdc++.h>
using namespace std;
int bitonic(int arr[], int n)
{
// Length of increasing subarray
// ending at all indexes
int inc[n];
// Length of decreasing subarray
// starting at all indexes
int dec[n];
int i, max;
// length of increasing sequence
// ending at first index is 1
inc[0] = 1;
// length of increasing sequence
// starting at first index is 1
dec[n-1] = 1;
// Step 1) Construct increasing sequence array
for (i = 1; i < n; i++)
inc[i] = (arr[i] >= arr[i-1])? inc[i-1] + 1: 1;
// Step 2) Construct decreasing sequence array
for (i = n-2; i >= 0; i--)
dec[i] = (arr[i] >= arr[i+1])? dec[i+1] + 1: 1;
// Step 3) Find the length of
// maximum length bitonic sequence
max = inc[0] + dec[0] - 1;
for (i = 1; i < n; i++)
if (inc[i] + dec[i] - 1 > max)
max = inc[i] + dec[i] - 1;
return max;
}
/* Driver code */
int main()
{
int arr[] = {12, 4, 78, 90, 45, 23};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "nLength of max length Bitnoic Subarray is " << bitonic(arr, n);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
b8d74d74bee63336bb8b113a1764e027405295dd | 51faca0ffd1c452a427e551cd8c528a4ac80fc75 | /CSP/5/gg.cpp | 4730da27a857a65fc764d8c87be3acaad1e80e05 | [] | no_license | xLLLxLLLx/xLLLx | 37f4127a34374b27f14fe856d854c9a13a9b2e28 | 7ec2ddf39d903c0cdfd52268edd44b2ccbe7e73b | refs/heads/master | 2020-04-18T16:19:24.099657 | 2019-11-03T05:11:41 | 2019-11-03T05:11:41 | 167,631,326 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,655 | cpp | #include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
typedef long double ldb;
typedef long long ll;
const int maxn = 55;
int n, m;
char s[maxn][30];
ldb ans;
ldb F[(1 << 20) + 5];//F[j]猜到j状态的概率有多少
ll Choice[(1 << 20) + 5];
//__builtin_popcount()用这个函数来统计位数
int main(){
//freopen("programmer.in", "r", stdin);
scanf("%d", &n);
for(int i = 1; i <= n; i++)
scanf("%s", s[i]);
if(n == 1){
printf("0\n");
return 0;
}
//for(int i = 1; i <= n; i++)
// printf("%s\n", s[i]);
m = strlen(s[1]);
//cerr << m << endl;
F[0] = 1;
for(int i = 1; i <= n; i++)
for(int j = i+1; j <= n; j++){
int stat = 0;
for(int k = 0; k <= m-1; k++)
if(s[i][k] == s[j][k]) stat |= (1 << k);
Choice[stat] |= (1LL << i) | (1LL << j);
//int stat = 0;
//if(s[])
}
for(int j = (1 << m) - 1; j >= 0; j--){
for(int k = 0; k <= m-1; k++){
if((j >> k) & 1){
Choice[j^(1 << k)] |= Choice[j];
}
}
//cerr << "#: " << j << endl;
//cerr << Choice[j] << endl;
printf("f[%d] = %lld\n", j, Choice[j] / 2);
}
// /*
for(register int j = 0; j <= (1 << m) - 1; j++){
int len = __builtin_popcount(j);
len = m - len;
for(register int k = 0; k < m; k++){
if(!((j >> k) & 1)){
int stat = j ^ (1 << k);
// if(__builtin_popcount(Choice[stat]) == 0) continue;
F[stat] += F[j] * 1.0/(ldb)len;
}
}
//cerr << j << endl;
//cerr << F[j] << endl;
}
// */
/*
for(int j = 1; j <= (1 << m) - 1; j++){
int len = __builtin_popcount(j);
len = m - len + 1;
for(int k = 0; k <= m-1; k++){
if((j >> k) & 1){
int stat = j ^ (1 << k);
if(__builtin_popcount(Choice[stat]) == 0) continue;
F[j] += 1.0 / (ldb)len * F[stat];
}
}
//cerr << j << endl;
//cerr << F[j] << endl;
}*/
for(int i = 0; i <= (1 << m) - 1; i++){
int len = __builtin_popcount(Choice[i] & ((1 << 30) - 1));
len += __builtin_popcount(Choice[i] >> 30);
//cif(len == 0)
//cerr << len << endl;
//cerr << i << ": " << endl;
//cerr << len << endl;
ans += F[i] * (ldb)len / (ldb)n;//这步基于期望的可加性
printf("%d\n", len);
//cerr << ans << endl;
}
printf("%.15Lf\n", ans);
} | [
"2656020973@qq.com"
] | 2656020973@qq.com |
6d6222be11dc7aa98ea10ba5c751920d9e35a401 | 440bc87298fef759de173cfa734f13cd71f03c12 | /Source/ProjectJ/Client/MyCharacter/PC/Widget/MainWidget.cpp | d77061b2e50c977674cfd42e2cb5d149d5bfee52 | [] | no_license | ProjectGladiator/ProjectGladiator | 9bb954b01d4e21e5111b518db36fdcf4b3a42617 | 0708250d3e994ffef95527e49b6b5632b9435421 | refs/heads/master | 2021-06-09T03:33:57.499603 | 2019-11-08T11:33:24 | 2019-11-08T11:33:24 | 144,824,947 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,074 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "MainWidget.h"
//클라 헤더
#include "Components/TextBlock.h"
#include "Kismet/GameplayStatics.h"
#include "Client/Menu/MenuWidget.h"
#include "Client/MyCharacter/PC/Widget/Inventory/Widget/InventoryWidget.h"
#include "Client/MyCharacter/PC/Widget/Party/Widget/PartyWidget.h"
#include "Client/MyCharacter/PC/Widget/Party/Widget/PartySlotWiget.h"
#include "Client/MyCharacter/PC/Widget/Party/Widget/PartyAcceptRejectWidget.h"
#include "Client/MyCharacter/PC/Widget/Party/Widget/PartyLeaderGameStartWidget.h"
#include "Client/Menu/MenuWidget.h"
#include "Client/MainMap/MainMapGameMode.h"
#include "Client/MainMap/MainMapPlayerController.h"
#include "Client/MyCharacter/PC/MyCharacter.h"
#include "Client/MyCharacter/PC/Widget/MyCharacterUI.h"
#include "Public/Animation/WidgetAnimation.h"
#include "Client/MyCharacter/PC/Widget/Chatting/ChattingWidget.h"
#include "TimerManager.h"
//서버 헤더
#include "NetWork/JobInfo.h"
void UMainWidget::NativeConstruct()
{
Super::NativeConstruct();
InChannelText = Cast<UTextBlock>(GetWidgetFromName(TEXT("InChannelText")));
InGameStageStartText = Cast<UTextBlock>(GetWidgetFromName(TEXT("InGameStageStartText")));
if (InGameStageStartText)
{
InGameStageStartText->SetVisibility(ESlateVisibility::Hidden);
}
InDunGeonMessageWidget = Cast<UInDunGeonMessageWidget>(GetWidgetFromName(TEXT("InDunGeonMessageWidget")));
if (InDunGeonMessageWidget)
{
InDunGeonMessageWidget->SetVisibility(ESlateVisibility::Hidden);
}
MenuWidget = Cast<UMenuWidget>(GetWidgetFromName(TEXT("MenuWidget")));
if (MenuWidget)
{
MenuWidget->SetVisibility(ESlateVisibility::Hidden);
MenuWidget->OnLogOut.BindDynamic(this, &UMainWidget::LogOut);
MenuWidget->OnCharacterSelect.BindDynamic(this, &UMainWidget::CharacterSelect);
}
InventoryWidget = Cast<UInventoryWidget>(GetWidgetFromName(TEXT("InventoryWidget")));
if (InventoryWidget)
{
InventoryWidget->SetVisibility(ESlateVisibility::Hidden);
}
PartyWidget = Cast<UPartyWidget>(GetWidgetFromName(TEXT("PartyWidget")));
if (PartyWidget)
{
PartyWidget->SetVisibility(ESlateVisibility::Hidden);
}
PartyAcceptRejectWidget = Cast<UPartyAcceptRejectWidget>(GetWidgetFromName(TEXT("PartyAcceptReject")));
if (PartyAcceptRejectWidget)
{
PartyAcceptRejectWidget->SetVisibility(ESlateVisibility::Hidden);
}
PartyLeaderGameStartWidget = Cast<UPartyLeaderGameStartWidget>(GetWidgetFromName(TEXT("PartyLeaderWidget")));
if (PartyLeaderGameStartWidget)
{
PartyLeaderGameStartWidget->SetVisibility(ESlateVisibility::Hidden);
}
ChattingWidget = Cast<UChattingWidget>(GetWidgetFromName(TEXT("ChattingWidget")));
MainMapGameMode = Cast<AMainMapGameMode>(UGameplayStatics::GetGameMode(GetWorld()));
MainMapPlayerController = Cast<AMainMapPlayerController>(UGameplayStatics::GetPlayerController(GetWorld(), 0));
UProperty* prop = GetClass()->PropertyLink;
while (prop != nullptr)
{
if (prop->GetClass() == UObjectProperty::StaticClass())
{
UObjectProperty* objectProp = Cast<UObjectProperty>(prop);
if (objectProp->PropertyClass == UWidgetAnimation::StaticClass())
{
UObject* object = objectProp->GetObjectPropertyValue_InContainer(this);
UWidgetAnimation* widgetAnim = Cast<UWidgetAnimation>(object);
if (widgetAnim != nullptr)
{
InChannelTextInVisibleAnimation = widgetAnim;
}
}
}
prop = prop->PropertyLinkNext;
}
if (InChannelTextInVisibleAnimation)
{
InChannelTextInVisibleAnimation->OnAnimationFinished.AddDynamic(this, &UMainWidget::InChannelTextHidden);
}
}
UMenuWidget * UMainWidget::GetMenuWidget()
{
return MenuWidget;
}
void UMainWidget::MenuWidgetToggle()
{
if (MenuWidget)
{
if (MenuWidget->GetVisibility() == ESlateVisibility::Hidden)
{
MenuWidget->SetVisibility(ESlateVisibility::Visible);
}
else
{
MenuWidget->SetVisibility(ESlateVisibility::Hidden);
MenuWidget->ChannelChangeWidgetHidden();
}
}
}
void UMainWidget::LogOut()
{
ReadyCharacterSelectLogOut("MainMapUnLoadCompleteToTitle");
}
void UMainWidget::CharacterSelect()
{
ReadyCharacterSelectLogOut("MainMapUnLoadCompleteToCharacterSelect");
}
void UMainWidget::ReadyCharacterSelectLogOut(const FName & _BindFunctionName)
{
SetVisibility(ESlateVisibility::Hidden);
if (MainMapPlayerController)
{
auto MyPlayCharacter = Cast<AMyCharacter>(MainMapPlayerController->GetPawn());
if (MyPlayCharacter)
{
MyPlayCharacter->AllUIDestroy();
MyPlayCharacter->Destroy();
}
}
MainMapGameMode->LoadingWidgetViewScreen();
MainMapGameMode->LoginUserAllDestory();
FLatentActionInfo MainMapUnLoadInfo;
MainMapUnLoadInfo.CallbackTarget = this; // 콜백 타겟 지정
MainMapUnLoadInfo.ExecutionFunction = _BindFunctionName; //작업 완료 할시 호출할 함수 이름
MainMapUnLoadInfo.UUID = 123; //고유 식별자를 지정
MainMapUnLoadInfo.Linkage = 0;
UGameplayStatics::UnloadStreamLevel(this, TEXT("MainStageStartArea"), MainMapUnLoadInfo);
}
void UMainWidget::MainMapUnLoadCompleteToTitle()
{
MainMapGameMode->LoadingWidgetHiddenScreen();
auto CreateSelectCharacter = MainMapGameMode->GetCreateSelectCharacter();
if (CreateSelectCharacter)
{
if (MainMapPlayerController)
{
MainMapPlayerController->Possess(CreateSelectCharacter);
MainMapPlayerController->ToCharacterSelect();
}
}
MainMapGameMode->LoginWidgetToggle();
}
void UMainWidget::MainMapUnLoadCompleteToCharacterSelect()
{
MainMapGameMode->LoadingWidgetHiddenScreen();
auto CreateSelectCharacter = MainMapGameMode->GetCreateSelectCharacter();
if (CreateSelectCharacter)
{
if (MainMapPlayerController)
{
MainMapPlayerController->Possess(CreateSelectCharacter);
MainMapPlayerController->ToCharacterSelect();
}
}
MainMapGameMode->CharacterSelectWidgetToggle();
}
void UMainWidget::SetInChannelText(const FText & _ChannelInMessage)
{
if (InChannelText)
{
InChannelText->SetVisibility(ESlateVisibility::Visible);
InChannelText->SetText(_ChannelInMessage);
PlayAnimation(InChannelTextInVisibleAnimation);
}
}
void UMainWidget::InChannelTextHidden()
{
if (InChannelText)
{
InChannelText->SetVisibility(ESlateVisibility::Hidden);
}
}
void UMainWidget::SetInDunGeonMessageWidgetState(const EMessageState& _NewState, const FText & _NewMessage)
{
if (InDunGeonMessageWidget)
{
InDunGeonMessageWidget->SetMessageState(_NewState, _NewMessage);
}
}
void UMainWidget::InDunGeonMessageWidgetVisible()
{
if (InDunGeonMessageWidget)
{
InDunGeonMessageWidget->SetVisibility(ESlateVisibility::Visible);
}
}
bool UMainWidget::IsDunGeonMessageWidgetVisible()
{
if (InDunGeonMessageWidget)
{
if (InDunGeonMessageWidget->GetVisibility() == ESlateVisibility::Visible)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
void UMainWidget::SetGameStageStartCountInit(int32 _GameStageStartCount)
{
if (InGameStageStartText)
{
GameStageStartCount = _GameStageStartCount;
InGameStageStartText->SetText(FText::FromString(FString::Printf(TEXT("게임 시작 까지 %d초"), GameStageStartCount)));
InGameStageStartText->SetVisibility(ESlateVisibility::Visible);
GetWorld()->GetTimerManager().SetTimer(GameStageStartTimer, this, &UMainWidget::StartGameStageCount, 1.0f, true, 0);
}
}
void UMainWidget::StartGameStageCount()
{
if (InGameStageStartText)
{
InGameStageStartText->SetText(FText::FromString(FString::Printf(TEXT("게임 시작 까지 %d초"), --GameStageStartCount)));
if (GameStageStartCount == 0)
{
GetWorld()->GetTimerManager().ClearTimer(GameStageStartTimer);
InGameStageStartText->SetVisibility(ESlateVisibility::Hidden);
if (MainMapPlayerController)
{
auto MyCharacter = Cast<AMyCharacter>(MainMapPlayerController->GetPawn());
if (MyCharacter)
{
bool IsPartyLeader = MyCharacter->GetPartyLeader();
if (IsPartyLeader)
{
MainMapPlayerController->C2S_ReqGameStageStart();
}
}
}
}
}
}
void UMainWidget::ChattingStart()
{
if (ChattingWidget)
{
ChattingWidget->ChattingStart();
}
}
void UMainWidget::InventoryCreate(int32 _NewInventoryMaxCount)
{
InventoryMaxCount = _NewInventoryMaxCount;
if (InventoryWidget)
{
InventoryWidget->CreateInventorySlots(InventoryMaxCount);
}
}
void UMainWidget::InventoryWidgetToggle()
{
if (InventoryWidget)
{
if (InventoryWidget->GetVisibility() == ESlateVisibility::Hidden)
{
InventoryWidget->SetVisibility(ESlateVisibility::Visible);
}
else
{
InventoryWidget->SetVisibility(ESlateVisibility::Hidden);
}
}
}
void UMainWidget::MoneyUpdate(int32 _GetMoney)
{
if (InventoryWidget)
{
InventoryWidget->MoneyUpdate(_GetMoney);
}
}
void UMainWidget::PartyWidgetVisible()
{
if (PartyWidget)
{
PartyWidget->SetVisibility(ESlateVisibility::Visible);
}
}
void UMainWidget::PartyWidgetHidden()
{
if (PartyWidget)
{
PartyWidget->SetVisibility(ESlateVisibility::Hidden);
}
}
void UMainWidget::PartyAcceptRejectWidgetVisible()
{
if (PartyAcceptRejectWidget)
{
PartyAcceptRejectWidget->SetVisibility(ESlateVisibility::Visible);
}
}
void UMainWidget::PartyAcceptRejectWidgetHidden()
{
if (PartyAcceptRejectWidget)
{
PartyAcceptRejectWidget->SetVisibility(ESlateVisibility::Hidden);
}
}
void UMainWidget::PartyLeaderGameStartWidgetVisible()
{
if (PartyLeaderGameStartWidget)
{
PartyLeaderGameStartWidget->SetVisibility(ESlateVisibility::Visible);
}
}
void UMainWidget::PartyLeaderGameStartWidgetHidden()
{
if (PartyLeaderGameStartWidget)
{
PartyLeaderGameStartWidget->SetVisibility(ESlateVisibility::Hidden);
}
}
UPartyWidget * UMainWidget::GetPartyWidget()
{
return PartyWidget;
}
UPartyAcceptRejectWidget * UMainWidget::GetPartyAcceptRejectWidget()
{
return PartyAcceptRejectWidget;
}
void UMainWidget::PartyJoin(AMyCharacter* _PartyInCharacter, char * _CharacterCode, int32 _JobCode, char * _NickName, float _HP, float _MP, bool _Leader)
{
if (_PartyInCharacter)
{
_PartyInCharacter->SetPartyLeader(_Leader);
if (PartyWidget)
{
UPartySlotWiget* PartySlotWidget = PartyWidget->PartySlotCreate(); //파티 슬롯을 만든다.
if (PartySlotWidget) //만든 파티슬롯의 정보를 업데이트 한다.
{
FPartySlot PartySlot;
memset(&PartySlot, 0, sizeof(FPartySlot));
PartySlot.PartyUser = _PartyInCharacter;
memcpy(PartySlot.CharacterCode, _CharacterCode, strlen(_CharacterCode));
PartySlot.JobCode = _JobCode;
memcpy(PartySlot.NickName, _NickName, strlen(_NickName));
PartySlot.HP = _HP;
PartySlot.Leader = _Leader;
int32 Index = PartySlots.Num();
PartySlots.Add(PartySlot);
if (_JobCode == CHARACTER_JOB::Gunner)
{
PartySlot.MP = _MP;
}
else
{
PartySlot.MP = 0;
}
PartySlotWidget->PartySlotInit(PartySlot, Index);
}
else
{
GLog->Log(FString::Printf(TEXT("파티 슬롯 위젯이 만들어지지 않음")));
}
}
}
}
void UMainWidget::PartyKick(char * _CharacterCode)
{
}
void UMainWidget::PartyLeave()
{
if (PartyWidget)
{
PartyWidget->PartyLeave();
PartySlots.Empty();
}
}
void UMainWidget::PartyLeave(char * _CharacterCode)
{
if (PartyWidget)
{
for (int i = 0; i < PartySlots.Num(); i++)
{
if (strcmp(PartySlots[i].CharacterCode, _CharacterCode) == 0)
{
PartySlots.RemoveAt(i);
}
}
PartyWidget->PartyLeave(_CharacterCode);
}
}
void UMainWidget::PartyLeaderUpdate()
{
if (PartyWidget)
{
PartyWidget->PartyLeaderUpdate();
}
}
bool UMainWidget::IsPartyJoin()
{
if (PartySlots.Num() <= 4)
{
return true; //파티 참여 가능
}
else
{
return false; //파티 인원 초과
}
}
int32 UMainWidget::GetPartySize()
{
return PartySlots.Num();
}
FPartySlot UMainWidget::GetPartySlot(int32 _Index)
{
return PartySlots[_Index];
}
void UMainWidget::MapLoadComplete()
{
MainMapGameMode->SelectCharacterDestroy();
GLog->Log(FString::Printf(TEXT("맵 로드 완료")));
MainMapGameMode->LoadingWidgetHiddenScreen();
MainMapPlayerController->C2S_ReqUserList();
}
| [
"tyhg56@naver.com"
] | tyhg56@naver.com |
ffb41cb3212693c1d8cea304b1605c69e14f1728 | b3465a4bebc12c8f4eabad301c343c5c9694afdf | /014-Proxy/property/Project/Sample.h | 859a966b975e82eb420fd57187f721a34c783566 | [] | no_license | dincerunal/design_patterns | fc7be618986b110078deb010fd74d55ca981662f | 243933001dcd12aaa65dbfeb600252eddcac72c2 | refs/heads/main | 2023-05-13T20:20:29.953153 | 2021-06-02T14:00:14 | 2021-06-02T14:00:14 | 372,414,976 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 102 | h | #pragma once
#include "Property.h"
class Sample {
public:
Property<int> x;
Property<double> y;
};
| [
"noreply@github.com"
] | noreply@github.com |
9d1cd61681d6a302996833bf6298729af400a49d | beb534d18b17649a27a7a11ddd3d651ee1645f38 | /server/src/error.cc | c3d9d857cd781689e86290b28bd441053b113257 | [] | no_license | jordankp/map_reduce | d5ad6e6b1e9a1f73d74207091efaa23307fe4075 | a4bfab32025c3fd5f19fccea2139694bde1eaba7 | refs/heads/master | 2022-11-21T07:13:16.839768 | 2020-07-18T18:31:48 | 2020-07-18T18:36:12 | 279,003,678 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,790 | cc | #include <iostream>
#include "error.h"
namespace map_reduce
{
void logger(ErrorCode err)
{
switch (err)
{
case ErrorCode::OK:
std::cerr << "[INFO] Task finished.\n";
break;
case ErrorCode::SOCKET_SERVER_CREATE_FAIL:
std::cerr << "[ERROR] Failed to create server socket.\n";
break;
case ErrorCode::SOCKET_CLIENT_CREATE_FAIL:
std::cerr << "[ERROR] Failed to create client socket.\n";
break;
case ErrorCode::SOCKET_BIND_FAIL:
std::cerr << "[ERROR] Bind operation on server socket failed.\n";
break;
case ErrorCode::SOCKET_LISTEN_FAIL:
std::cerr << "[ERROR] Listen operation on server socket failed.\n";
break;
case ErrorCode::SOCKET_ACCEPT_FAIL:
std::cerr << "[ERROR] Accept operation on server socket failed.\n";
break;
case ErrorCode::SOCKET_READ_SERVER_FAIL:
std::cerr << "[ERROR] Failed to read from client.\n";
break;
case ErrorCode::SOCKET_READ_CLIENT_FAIL:
std::cerr << "[ERROR] Failed to read from server.\n";
break;
case ErrorCode::SOCKET_WRITE_SERVER_FAIL:
std::cerr << "[ERROR] Failed to write to client.\n";
break;
case ErrorCode::SOCKET_WRITE_CLIENT_FAIL:
std::cerr << "[ERROR] Failed to write to server.\n";
break;
case ErrorCode::SOCKET_CONNECT_FAIL:
std::cerr << "[ERROR] Connect operation on client socket failed.\n";
break;
case ErrorCode::DLOPEN_FAIL:
std::cerr << "[ERROR] Failed to open client shared library.\n";
break;
case ErrorCode::DLSYM_FAIL:
std::cerr << "[ERROR] Failed to find a function in client shared library.\n";
break;
case ErrorCode::TASK_INTERRUPTED:
std::cerr << "[WARNING] Client task was interrupted.\n";
break;
}
}
}
| [
"jordan.p@abv.bg"
] | jordan.p@abv.bg |
ebe057ef74de5d8ca6a7409cb23c92be5481f538 | f3f9d546f0ee9c532f9a8bed11f1770b6c1778a6 | /algorithm/knapsack.cpp | 14363c4bfcade25f6fcb09f2e0beef6fbea63f2c | [] | no_license | rohit3463/data-structures | 20de7286fdc00387c57b231b7b8255589379b9c6 | ea2b0250821dcf9b713a57a4e57a2600d2d0ebd6 | refs/heads/master | 2020-03-19T23:51:03.172036 | 2019-10-23T04:52:34 | 2019-10-23T04:52:34 | 137,022,495 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 554 | cpp | #include<iostream>
#include<algorithm>
using namespace std;
int knapsack(int n,int W,int w[],int val[])
{
int k[n+1][W+1];
for(int i=0;i<=n;i++)
{
for(int j = 0;j<=W;j++)
{
if(i==0 || j==0)
{
k[i][j] = 0;
}
else if(w[i-1] <= j)
{
k[i][j] = max(val[i-1] + k[i-1][j- w[i-1]],k[i-1][j]);
}
else
{
k[i][j] = k[i-1][j];
}
}
}
return k[n][W];
}
int main()
{
int w[3] = {10,20,30};
int val[3] = {60,100,120};
int W = 50;
int n = sizeof(w)/sizeof(w[0]);
cout<<knapsack(n,W,w,val)<<endl;
return 0;
} | [
"rohit.sethi9139666@gmail.com"
] | rohit.sethi9139666@gmail.com |
7de22a31af8deac825857d74ef82556006d1d7ba | a5812f02e758c1fd4fc9ecc1b6462788cf6c7f71 | /Easy21.h | f57a79f9225ba8cddabc85304de13a5b17833b81 | [] | no_license | dp90/Easy21 | f2e63c0cc36600689daf55d1e3bc0a296622c410 | 24898eca925cb3fe6ad624647504aeaa7e4fdbba | refs/heads/master | 2021-03-15T23:46:15.000330 | 2020-03-12T20:51:30 | 2020-03-12T20:51:30 | 246,887,665 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 836 | h | #ifndef EASY21_H
#define EASY21_H
#include <tuple>
using namespace std;
class Easy21 {
private:
int N[21][10][2] = {0};
double Vmax[21][10] = {0.0};
double weights[36] = {0.0};
float features[36] = {0.0};
public:
double Q[21][10][2] = {0.0}; // 21 player states, 10 dealer states, 2 actions: hit & stick
Easy21();
int draw();
int step(array<int, 2>* ptS, int* ptA);
int policy(array<int, 2>* ptS);
int policy_LA(array<int, 2>* ptS);
void MC_episode();
void SARSA_episode(float labda);
void assign_features(array<int, 2>* ptS, int *ptA);
double approx_value();
void SARSA_LA_episode(float labda);
void compute_Q_LA();
void calc_Vmax(bool save);
double MSE(Easy21 extGame);
};
#endif | [
"noreply@github.com"
] | noreply@github.com |
30a4982e777ff377f1aae4c2b9045506c0be52d9 | 2f84ee6ea488f25bd75dc15133819a72c870394f | /client/entity.h | b240e1be9e1a9b2559220afa7636645751fc96e6 | [] | no_license | andras-szabo/online-multiplayer-proof-of-concept | 3235447350c08bfbe26e41bbbee246f906d5e210 | 49f7efb66244d5172e1e43ce5ceee27e35edfd4a | refs/heads/master | 2020-06-02T03:28:32.867370 | 2014-06-04T13:53:56 | 2014-06-04T13:53:56 | 20,485,302 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,952 | h | #ifndef __clever_client_2__entity__
#define __clever_client_2__entity__
#include <SFML/Graphics.hpp>
#include "ResourcePath.hpp"
#include "inputstate.h"
enum class EntState : sf::Uint16 { idle, walking, jumping, falling, hittingOnGround, hittingInAir, blocking, beingHit };
struct cAnim {
sf::IntRect mTexRect;
sf::Vector2f mCentre;
sf::Uint8 mPhaseCount { 0 };
};
struct cEntityStatus {
cInputState mCurrentInputState;
sf::Int32 mLastUpdated { 0 };
sf::Uint16 mOwner { 0 };
sf::Uint16 mUid { 0 };
sf::Vector2f mPos { 300, 300 };
sf::Vector2f mVel { 0, 0 };
EntState mState;
sf::Int32 mStatePtr { 0 };
bool mInAir { true };
bool mIsPunching { false };
bool mIsBlocking { false };
bool mHitAlready { false }; // did we hit anyone with this particular punch?
// if so, we must not hit again - i.e. one hit should
// register as one hit, not multiple hits
bool mHitNeedsRelease { false }; // New hit event can only register if this is false.
};
class cEntity {
public:
cEntity(sf::Color);
cEntity(const cEntityStatus&);
void render(sf::RenderWindow& w);
cEntityStatus& updateWithDelta(sf::Int32);
cEntityStatus& updateAt(sf::Int32);
cEntityStatus& updateWithoutDelta(sf::Int32);
void setInputStateAt(const cInputState&, sf::Int32);
void setStatus(const cEntityStatus&);
void hit(bool left, bool top, sf::Int32 time);
private:
void setUpAnimations();
inline bool canIblock() const;
inline bool canIpunch() const;
public:
cEntityStatus mStatus;
sf::Uint16 mOwner;
sf::Uint16 mUid;
const sf::Int32 mPunchStartup { 80 };
const sf::Int32 mPunchActive { 280 };
const sf::Int32 mPunchRecovery { 400 };
const sf::Int32 mHitStun { 400 };
const sf::Int16 gAnimFPS { 100 }; // it's more like: milliseconds-per-frame
private:
sf::Texture mTexture;
sf::Sprite mSprite;
std::map<EntState, cAnim> mAnim;
sf::CircleShape mShape;
sf::Color mColor;
float mAcceleration { 800.0 };
float mJumpAcc { -500.0 };
float mAirAcc { 400 };
float gGravity { 500 };
float gFriction { 20 };
sf::Vector2f gScreenSize { 640, 480 };
bool mFacingRight { true };
bool mPrevFacingRight { true };
};
#endif /* defined(__clever_client_2__entity__) */
| [
"andras.szabo.fin@gmail.com"
] | andras.szabo.fin@gmail.com |
8c8f4dca6a2e2eca7531d1a93420d87b1cf3ed9c | 8cad5efc658618e57a78b670dbf3b1f7ce0f9541 | /A1016/源.cpp | c292ce40d96003a8760fc81908f60629c1ee715a | [] | no_license | 593269082/PAT | 9fd05c032b99d5091e1becb5c4ec934c660d727c | 2a15c9a7295e85261b4ff621b8b9d4ed9394ccd5 | refs/heads/master | 2021-01-26T10:56:15.084268 | 2020-03-21T11:26:40 | 2020-03-21T11:26:40 | 243,413,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,510 | cpp | #include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<map>
using namespace std;
class Trasaction {
public:
string Name;
int Month;
int Day;
int Hour;
int Minute;
bool On_Off_Line;
Trasaction(){
On_Off_Line = 0;
}
};
class Person {
public:
string Name;
vector<pair<Trasaction, Trasaction> > Trasactions;
};
bool cmp(Trasaction A,Trasaction B) {
if (A.Name == B.Name) {
if (A.Day == B.Day) {
if (A.Hour == B.Hour) {
return A.Minute < B.Minute;
}
else {
return A.Hour < B.Hour;
}
}
else {
return A.Day < B.Day;
}
}
return A.Name < B.Name;
}
map<int, int> H_To_Price;
vector<Trasaction> Total_Trasactions;
bool isOnline(string Buffer) {
if (Buffer == "on-line") {
return 1;
}
else {
return 0;
}
}
map<string, Person*> Persons;
int main() {
for (int i = 0; i <= 23; i++) {
cin >> H_To_Price[i];
}
int N;
string TheName;
int theM;
int theD;
int theH;
int theMM;
bool ifOnLine;
string Buffer;
cin >> N;
Trasaction bufferT;
for (int i = 0; i < N; i++) {
cin >> TheName;
if (Persons.find(TheName)== Persons.end()) {
Persons[TheName] = new Person;
Persons[TheName]->Name = TheName;
}
scanf_s("%d:%d:%d:%d", &theM, &theD, &theH, &theMM);
cin >> Buffer;
bufferT.Day = theD;
bufferT.Month = theM;
bufferT.Hour = theH;
bufferT.Name = TheName;
bufferT.Minute = theMM;
bufferT.On_Off_Line = isOnline(Buffer);
Total_Trasactions.push_back(bufferT);
}
sort(Total_Trasactions.begin(), Total_Trasactions.end(), cmp);
Trasaction CurrentTrasact;
CurrentTrasact = Total_Trasactions[0];
int i = 0;
pair<Trasaction, Trasaction> Buf;
for (;;i++) {
if (Total_Trasactions[i].On_Off_Line) {
CurrentTrasact = Total_Trasactions[i];
i++;
break;
}
}
for (; i < Total_Trasactions.size(); i++) {
if (Total_Trasactions[i].Name == CurrentTrasact.Name) {
if (Total_Trasactions[i].On_Off_Line == 1) {
CurrentTrasact = Total_Trasactions[i];
}
else {
Buf.first = CurrentTrasact;
Buf.second= Total_Trasactions[i];
Persons[CurrentTrasact.Name]->Trasactions.push_back(Buf);
for (;i<Total_Trasactions.size(); i++) {
if (Total_Trasactions[i].On_Off_Line) {
CurrentTrasact = Total_Trasactions[i];
break;
}
}
}
}
else {
if (Total_Trasactions[i].On_Off_Line == 1) {
CurrentTrasact = Total_Trasactions[i];
}
}
}
map<string, Person*>::iterator its = Persons.begin();
map<string, Person*>::iterator ite= Persons.end();
int Time = 0;
float Price = 0.0;
float SumPrice = 0.0;
int sd, ed, sh, eh, sm, em;
int tsd, ted, tsh, teh, tsm, tem;
while (its != ite) {
if ((*its).second->Trasactions.size() == 0) {
its++;
continue;
}
cout << (*its).first << " ";
printf("%02d", theM);
cout<< endl;
SumPrice = 0;
for (int i = 0; i < (*its).second->Trasactions.size(); i++) {
printf("%02d:%02d:%02d ", (*its).second->Trasactions[i].first.Day, (*its).second->Trasactions[i].first.Hour, (*its).second->Trasactions[i].first.Minute);
printf("%02d:%02d:%02d ", (*its).second->Trasactions[i].second.Day, (*its).second->Trasactions[i].second.Hour, (*its).second->Trasactions[i].second.Minute);
sd = (*its).second->Trasactions[i].first.Day;
sh = (*its).second->Trasactions[i].first.Hour;
sm = (*its).second->Trasactions[i].first.Minute;
ed = (*its).second->Trasactions[i].second.Day;
eh = (*its).second->Trasactions[i].second.Hour;
em = (*its).second->Trasactions[i].second.Minute;
Time = 0;
Price = 0;
for (int d = sd; d <= ed; d++) {
tsh = 0;
teh = 23;
if (d == ed) {
teh = eh;
}
if(d==sd){
tsh = sh;
}
for (int h = tsh; h <= teh; h++) {
tsm = 0;
tem = 59;
if (h == eh&& d == ed) {
tem = em;
}
if (h == sh&&d==sd) {
tsm = sm;
}
Time += tem - tsm + 1;
if (h == eh && d == ed) {
Price += (tem - tsm) * H_To_Price[h];
}
else {
Price += (tem - tsm+1) * H_To_Price[h];
}
}
}
cout << Time -1<< " ";
printf("$%.2f", Price/100);
SumPrice += Price;
cout << endl;
}
if(SumPrice!=0)
printf("Total amount: $%.2f", SumPrice/100);
cout << endl;
its++;
}
return 0;
}
/*
10 10 10 10 10 10 20 20 20 15 15 15 15 15 15 15 20 30 20 15 15 10 10 10
8
CYLL 01:01:06:01 on-line
CYLL 01:28:16:05 off-line
CYJJ 01:01:07:00 off-line
CYLL 01:01:08:03 off-line
//CYJJ 01:01:05:59 on-line
aaa 01:01:01:03 on-line
CYLL 01:28:15:41 on-line
aaa 01:05:02:24 on-line
*/ | [
"593269082@qq.com"
] | 593269082@qq.com |
464d1665cd800cea0c5a942089c3172b84dd57c6 | d222c01da7f3b3edd015fbdd216c602ad99d4805 | /Project/Procrustes.h | 8e1d956618097ce6f64956fb441bc1253fe0c0bf | [
"Unlicense"
] | permissive | bulatGH/Mesh-image-alignment | 5701677cb7730a56730b5f8888aa3446ac0fc6a4 | 975064ca19cd143b68709c6c31b5ec3a896896c5 | refs/heads/master | 2021-05-12T16:08:22.887538 | 2018-01-10T22:18:47 | 2018-01-10T22:18:47 | 117,004,007 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,408 | h | #ifndef PROCRUSTES_H
#define PROCRUSTES_H
#include "AllTypes.h"
#include "BasicClasses.h"
#include "Object_3D.h"
class Procrustes;
//this class is not literaly procrustes method, but rather different ways of aligning 3D meshes with 3D points.
class Procrustes
{
public:
static double ProcrustesMainVertices_NoScale(shared_ptr<Mesh> tmesh, std::vector<Point3D_F>& tnewPoints);
// only some mesh points are of interest (tselectedVerts).
static double ProcrustesMainVertices_NoScale(shared_ptr<Mesh> tmesh, std::vector<Point3D_F>& tnewPoints, std::vector<bool>& tselectedVerts);
// aligning with transformation parameters returned
static void ProcrustesMainVertices_GetParameters(shared_ptr<Mesh> tmesh, std::vector<Point3D_F>& trefPoints, std::vector<std::vector<double>>& trotation, std::vector<double> & ttrans);
static std::vector<Point3D_F> RotateAxes(std::vector<std::vector<double>>& trotation);
private:
static Point3D_F FindMeanPoint(std::vector<Point3D_F>& tnewPoints);
static Point3D_F FindMeanPoint(std::vector<Point3D_F>& tnewPoints, std::vector<bool>& tselectedVerts, int tnumSelected);
static Point3D_F FindMeanPointMesh(std::vector<shared_ptr<Vertex>>& tnewPoints, std::vector<bool>& tselectedVerts, int tnumSelected);
static double** RotationInternalVertices(shared_ptr<Mesh> tmesh_Norm, std::vector<Point3D_F>& tnewPoints_Norm, std::vector<bool>& tselectedVerts, int tnumSelected);
static double** RotationInternalVerticesInverse(shared_ptr<Mesh> tmesh_Norm, std::vector<Point3D_F>& tnewPoints_Norm);
static Point3D_F RotateOneVector(double** tmart, Point3D_F told);
static Point3D_F RotateOneVector(std::vector<std::vector<double>> tmart, Point3D_F told);
static double** RotationVertices(shared_ptr<Mesh> tmesh_Norm, std::vector<Point3D_F>& tnewPoints_Norm);
static double** RotationVerticesInverse(shared_ptr<Mesh> tmesh_Norm, std::vector<Point3D_F>& tnewPoints_Norm);
static double** RotationVertices(shared_ptr<Mesh> tmesh_Norm, std::vector<Point3D_F>& tnewPoints_Norm, std::vector<bool>& tselectedVerts, int tnumSelected);
static bool CheckStopping(float tscale, double tdet, double tdist);
static double CheckStopping(double tdet, double tdist);
static Point3D_F FindMeanPoint(std::vector<std::vector<Point3D_F>>& tlineMain);
};
#endif | [
"noreply@github.com"
] | noreply@github.com |
2570f1f785fa66bfcf509fd4eef62ded12814060 | 998a061a466cad79ae70cc69e64dac2d188151ba | /Sort/1520.Maximum-Number-of-Non-Overlapping-Substrings/1520.Maximum-Number-of-Non-Overlapping-Substrings.cpp | b0c65760cb4239b47261ef9ef2de5e66bc913364 | [] | no_license | daihui-lu/LeetCode | d65d3428c5ce29b3c727c30c0a5ddc565841fb8f | 4fb2fcb38233d5017bc2c08bd94c26dcc3f2e4c1 | refs/heads/master | 2022-11-23T03:49:40.441660 | 2020-07-21T07:05:43 | 2020-07-21T07:05:43 | 281,460,051 | 0 | 1 | null | 2020-07-21T17:20:07 | 2020-07-21T17:20:06 | null | UTF-8 | C++ | false | false | 1,569 | cpp | class Solution {
static bool cmp(vector<int>&a, vector<int>&b)
{
return a[1]<b[1];
}
public:
vector<string> maxNumOfSubstrings(string s)
{
vector<int>start(26,-1);
vector<int>end(26,-1);
for (int i=0; i<s.size(); i++)
if (start[s[i]-'a']==-1) start[s[i]-'a'] = i;
for (int i=s.size()-1; i>=0; i--)
if (end[s[i]-'a']==-1) end[s[i]-'a'] = i;
vector<vector<int>>intervals;
for (int i=0; i<26; i++)
{
if (start[i]==-1) continue;
int left = start[i], right = end[i];
bool valid = true;
for (int k=left; k<=right; k++)
{
if (start[s[k]-'a']==-1) continue;
if (start[s[k]-'a'] < left)
{
valid = false;
break;
}
right = max(right, end[s[k]-'a']);
}
if (valid) intervals.push_back({left, right});
}
sort(intervals.begin(), intervals.end(), cmp);
vector<string>ret;
for (int i=0; i<intervals.size(); )
{
ret.push_back(s.substr(intervals[i][0], intervals[i][1]-intervals[i][0]+1));
int right = intervals[i][1];
int j = i+1;
while (j<intervals.size() && intervals[j][0]<right)
j++;
i = j;
}
if (ret.size()==0) return {s};
else return ret;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
eb7935a4c992f08db11566d4448635f90cf20487 | d3baacca0b2cc9d2276debc0b4e25c374174e04b | /lab7/lab3.cpp | 58069766be0e9653cf72b242b7946b67399d0ea9 | [] | no_license | Taisoul/C_plus_plus | 58a0042f3e6cacc35cbd21aba47b4d63661a36b6 | 063fd40a11594b09e8e69d23c0f578fe8b7960da | refs/heads/main | 2023-09-04T20:28:25.024136 | 2021-10-19T04:40:05 | 2021-10-19T04:40:05 | 413,714,800 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 690 | cpp | #include<iostream>
using namespace std;
int main(){
int killo = 0,price = 0,count = 0;
cout << "Enter killometer : ";
cin >> killo;
while(count != killo){
count++;
if(count == 1){
price += 40;
}
else if(count >= 2 && count <= 10){
price += 5;
}
else if(count >=11 && count <= 15){
price += 4;
}
else if(count >=16 && count <= 20){
price += 3;
}
else if(count >= 21){
price += 2;
}
}
cout << "\n" << "Total : " << price;
} | [
"markkoko01@gmail.com"
] | markkoko01@gmail.com |
59de2cdbab735142e4b01f7890dca827c010a678 | 7be9bd83c20183466a9e47e66e0d25a0d5f7505f | /arm9/include/_type/type.program.args.h | 10255fe5729d17501cdd8ed582e7c05304b65983 | [
"MIT"
] | permissive | Lrs121/winds | b635398b2906697f83daf07fa62b5750370fb9eb | 35f1b5fd458c527a6c372f94077e784f6fd960b2 | refs/heads/master | 2023-08-08T21:24:16.620369 | 2019-04-24T08:41:53 | 2019-04-24T08:41:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 638 | h | #ifndef _WIN_T_PROGRAMARGS_
#define _WIN_T_PROGRAMARGS_
#include <_type/type.h>
class _programArgs : public _vector<string>
{
public:
//! Ctor
_programArgs( _literal argumentString );
_programArgs(){}
//! Copy and Move Ctors
_programArgs( _programArgs&& ) = default;
_programArgs( const _programArgs& ) = default;
//! Assignment operators
_programArgs& operator=( _programArgs&& ) = default;
_programArgs& operator=( const _programArgs& ) = default;
//! Splits a command in (executeable path;arguments)
static _pair<string,string> splitCommand( const string& cmd );
};
#endif | [
"DuffsDevice@users.noreply.github.com"
] | DuffsDevice@users.noreply.github.com |
4e2caca7c6e85748ff2ed7557f480a478fc47541 | 9c7cfd0d8268bd0d4f5d0d39508bcf29cc02a13c | /proj.android/jni/hellocpp/main.cpp | 34d45d5752365f45feadd839cf27176b84b774cb | [
"MIT"
] | permissive | Dotosoft/game01-cpp-simple2d | 2166f647f44f33912c7cbca7ee7bd90b897acd10 | b5ae178e8bae10e2790dbdea08dd01101d6fc7a9 | refs/heads/master | 2020-06-26T20:26:00.669849 | 2016-09-22T16:47:39 | 2016-09-22T16:47:39 | 66,375,337 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 435 | cpp | #include "cocos2d.h"
#include "platform/android/jni/JniHelper.h"
#include <jni.h>
#include <android/log.h>
#include "breakout/AppDelegate.h"
#define LOG_TAG "main"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
using namespace cocos2d;
using namespace breakout;
void cocos_android_app_init (JNIEnv* env) {
LOGD("cocos_android_app_init");
AppDelegate *pAppDelegate = new AppDelegate();
}
| [
"dotosoft@gmail.com"
] | dotosoft@gmail.com |
7fe882333052a888fe7027b24c71b424699b8333 | d6ce6553d430bf2c2d4bc5061abf0023eadae851 | /src/qt/addressbookpage.cpp | 594150b9e7977d6e34d9db8d78e2db5b7a3aa297 | [
"MIT"
] | permissive | VictorLux/ZiCEofficial | 591804070931105d047e87706128dab93602a19b | d451d5455e2c6e6ee66a41ed5594f31a2ab6ea8a | refs/heads/master | 2020-05-16T18:29:21.065293 | 2019-04-25T15:04:40 | 2019-04-25T15:04:40 | 183,226,781 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,853 | cpp | // Copyright (c) 2011-2017 The Bitcash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcash-config.h>
#endif
#include <qt/addressbookpage.h>
#include <qt/forms/ui_addressbookpage.h>
#include <qt/addresstablemodel.h>
#include <qt/bitcashgui.h>
#include <qt/csvmodelwriter.h>
#include <qt/editaddressdialog.h>
#include <qt/guiutil.h>
#include <qt/platformstyle.h>
#include <QIcon>
#include <QMenu>
#include <QMessageBox>
#include <QSortFilterProxyModel>
class AddressBookSortFilterProxyModel final : public QSortFilterProxyModel
{
const QString m_type;
public:
AddressBookSortFilterProxyModel(const QString& type, QObject* parent)
: QSortFilterProxyModel(parent)
, m_type(type)
{
setDynamicSortFilter(true);
setFilterCaseSensitivity(Qt::CaseInsensitive);
setSortCaseSensitivity(Qt::CaseInsensitive);
}
protected:
bool filterAcceptsRow(int row, const QModelIndex& parent) const
{
auto model = sourceModel();
auto label = model->index(row, AddressTableModel::Label, parent);
if (model->data(label, AddressTableModel::TypeRole).toString() != m_type) {
return false;
}
auto address = model->index(row, AddressTableModel::Address, parent);
if (filterRegExp().indexIn(model->data(address).toString()) < 0 &&
filterRegExp().indexIn(model->data(label).toString()) < 0) {
return false;
}
return true;
}
};
AddressBookPage::AddressBookPage(const PlatformStyle *platformStyle, Mode _mode, Tabs _tab, QWidget *parent) :
QDialog(parent),
ui(new Ui::AddressBookPage),
model(0),
mode(_mode),
tab(_tab)
{
ui->setupUi(this);
if (!platformStyle->getImagesOnButtons()) {
ui->newAddress->setIcon(QIcon());
ui->copyAddress->setIcon(QIcon());
ui->deleteAddress->setIcon(QIcon());
ui->exportButton->setIcon(QIcon());
} else {
ui->newAddress->setIcon(platformStyle->SingleColorIcon(":/icons/add"));
ui->copyAddress->setIcon(platformStyle->SingleColorIcon(":/icons/editcopy"));
ui->deleteAddress->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
ui->exportButton->setIcon(platformStyle->SingleColorIcon(":/icons/export"));
}
switch(mode)
{
case ForSelection:
switch(tab)
{
case SendingTab: setWindowTitle(tr("Choose the address to send coins to")); break;
case ReceivingTab: setWindowTitle(tr("Choose the address to receive coins with")); break;
}
connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept()));
ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableView->setFocus();
ui->closeButton->setText(tr("C&hoose"));
ui->exportButton->hide();
break;
case ForEditing:
switch(tab)
{
case SendingTab: setWindowTitle(tr("Sending addresses")); break;
case ReceivingTab: setWindowTitle(tr("Receiving addresses")); break;
}
break;
}
switch(tab)
{
case SendingTab:
ui->labelExplanation->setText(tr("These are your Bitcash addresses for sending payments. Always check the amount and the receiving address before sending coins."));
ui->deleteAddress->setVisible(true);
ui->newAddress->setVisible(true);
break;
case ReceivingTab:
ui->labelExplanation->setText(tr("These are your Bitcash addresses for receiving payments. It is recommended to use a new receiving address for each transaction."));
ui->deleteAddress->setVisible(false);
ui->newAddress->setVisible(false);
break;
}
// Context menu actions
QAction *copyAddressAction = new QAction(tr("&Copy Address"), this);
QAction *copyLabelAction = new QAction(tr("Copy &Label"), this);
QAction *editAction = new QAction(tr("&Edit"), this);
deleteAction = new QAction(ui->deleteAddress->text(), this);
// Build context menu
contextMenu = new QMenu(this);
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(editAction);
if(tab == SendingTab)
contextMenu->addAction(deleteAction);
contextMenu->addSeparator();
// Connect signals for context menu actions
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction()));
connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction()));
connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked()));
connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept()));
}
AddressBookPage::~AddressBookPage()
{
delete ui;
}
void AddressBookPage::setModel(AddressTableModel *_model)
{
this->model = _model;
if(!_model)
return;
auto type = tab == ReceivingTab ? AddressTableModel::Receive : AddressTableModel::Send;
proxyModel = new AddressBookSortFilterProxyModel(type, this);
proxyModel->setSourceModel(_model);
connect(ui->searchLineEdit, SIGNAL(textChanged(QString)), proxyModel, SLOT(setFilterWildcard(QString)));
ui->tableView->setModel(proxyModel);
ui->tableView->sortByColumn(0, Qt::AscendingOrder);
// Set column widths
#if QT_VERSION < 0x050000
ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch);
ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents);
#else
ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch);
ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents);
#endif
connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(selectionChanged()));
// Select row for newly created address
connect(_model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int)));
selectionChanged();
}
void AddressBookPage::on_copyAddress_clicked()
{
GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address);
}
void AddressBookPage::onCopyLabelAction()
{
GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label);
}
void AddressBookPage::onEditAction()
{
if(!model)
return;
if(!ui->tableView->selectionModel())
return;
QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
if(indexes.isEmpty())
return;
EditAddressDialog dlg(
tab == SendingTab ?
EditAddressDialog::EditSendingAddress :
EditAddressDialog::EditReceivingAddress, this);
dlg.setModel(model);
QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0));
dlg.loadRow(origIndex.row());
dlg.exec();
}
void AddressBookPage::on_newAddress_clicked()
{
if(!model)
return;
if (tab == ReceivingTab) {
return;
}
EditAddressDialog dlg(EditAddressDialog::NewSendingAddress, this);
dlg.setModel(model);
if(dlg.exec())
{
newAddressToSelect = dlg.getAddress();
}
}
void AddressBookPage::on_deleteAddress_clicked()
{
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
QModelIndexList indexes = table->selectionModel()->selectedRows();
if(!indexes.isEmpty())
{
table->model()->removeRow(indexes.at(0).row());
}
}
void AddressBookPage::selectionChanged()
{
// Set button states based on selected tab and selection
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
if(table->selectionModel()->hasSelection())
{
switch(tab)
{
case SendingTab:
// In sending tab, allow deletion of selection
ui->deleteAddress->setEnabled(true);
ui->deleteAddress->setVisible(true);
deleteAction->setEnabled(true);
break;
case ReceivingTab:
// Deleting receiving addresses, however, is not allowed
ui->deleteAddress->setEnabled(false);
ui->deleteAddress->setVisible(false);
deleteAction->setEnabled(false);
break;
}
ui->copyAddress->setEnabled(true);
}
else
{
ui->deleteAddress->setEnabled(false);
ui->copyAddress->setEnabled(false);
}
}
void AddressBookPage::done(int retval)
{
QTableView *table = ui->tableView;
if(!table->selectionModel() || !table->model())
return;
// Figure out which address was selected, and return it
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
for (const QModelIndex& index : indexes) {
QVariant address = table->model()->data(index);
returnValue = address.toString();
}
if(returnValue.isEmpty())
{
// If no address entry selected, return rejected
retval = Rejected;
}
QDialog::done(retval);
}
void AddressBookPage::on_exportButton_clicked()
{
// CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(this,
tr("Export Address List"), QString(),
tr("Comma separated file (*.csv)"), nullptr);
if (filename.isNull())
return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(proxyModel);
writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole);
writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole);
if(!writer.write()) {
QMessageBox::critical(this, tr("Exporting Failed"),
tr("There was an error trying to save the address list to %1. Please try again.").arg(filename));
}
}
void AddressBookPage::contextualMenu(const QPoint &point)
{
QModelIndex index = ui->tableView->indexAt(point);
if(index.isValid())
{
contextMenu->exec(QCursor::pos());
}
}
void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int /*end*/)
{
QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent));
if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect))
{
// Select row of newly created address, once
ui->tableView->setFocus();
ui->tableView->selectRow(idx.row());
newAddressToSelect.clear();
}
}
| [
"willythecat@protonmail.com"
] | willythecat@protonmail.com |
763d98c348d555c00b765f1274c79c55d0a23e24 | 6ef1e5dc614016caa3dd6c73cc4f7540322434ea | /admin/mainwindow.h | 3e79f1ea010e3ac9465245081fb26f7958e3e739 | [] | no_license | Delta3system/delta3-admin | b196fff54a59b38e64026b709b423298e79d6879 | b27c1e750f6ab4a0de24c5d0b6756ced06042a5b | refs/heads/master | 2021-01-19T06:40:30.771530 | 2012-07-24T13:47:07 | 2012-07-24T13:47:07 | 5,897,820 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 853 | h | #pragma once
#include <QMainWindow>
#include <QListWidgetItem>
#include <QTextCodec>
#include <QPoint>
#include <QMenu>
#include "network.h"
#include "telnetform.h"
#include "graphform.h"
#include "fileform.h"
#include "clientinfodialog.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_actionConnect_activated();
void onRedraw();
void on_listWidget_itemClicked(QListWidgetItem *item);
void on_listWidget_itemDoubleClicked(QListWidgetItem *item);
void on_listWidget_customContextMenuRequested(const QPoint &pos);
void runTelnet();
void runGraph();
void runFile();
void runOptions();
private:
Ui::MainWindow *ui;
Network *network_;
QMenu *modeMenu_;
};
| [
"kovalev@quantion.ru"
] | kovalev@quantion.ru |
71bc8570e59f5bdde0e4b1f5b6db0537d146797f | 2af943fbfff74744b29e4a899a6e62e19dc63256 | /ITKAdvancedCourse/src/Exercises/exercise36/ImageMarkovRandomField.cxx | e33db8ffbee430c3e9ed31c604cea0b94c3390e0 | [] | no_license | lheckemann/namic-sandbox | c308ec3ebb80021020f98cf06ee4c3e62f125ad9 | 0c7307061f58c9d915ae678b7a453876466d8bf8 | refs/heads/master | 2021-08-24T12:40:01.331229 | 2014-02-07T21:59:29 | 2014-02-07T21:59:29 | 113,701,721 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,487 | cxx | /*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: $RCSfile: ScalarImageMarkovRandomField1.cxx,v $
Language: C++
Date: $Date: 2005/12/10 18:23:31 $
Version: $Revision: 1.16 $
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImage.h"
#include "itkVector.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkMRFImageFilter.h"
#include "itkDistanceToCentroidMembershipFunction.h"
#include "itkMinimumDecisionRule.h"
#include "itkImageClassifierBase.h"
int main( int argc, char * argv [] )
{
if( argc < 5 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0];
std::cerr << " inputVectorImage inputLabeledImage";
std::cerr << " outputLabeledImage numberOfIterations";
std::cerr << " smoothingFactor numberOfClasses";
std::cerr << " mean1 mean2 ... meanN " << std::endl;
return EXIT_FAILURE;
}
const char * inputImageFileName = argv[1];
const char * inputLabelImageFileName = argv[2];
const char * outputImageFileName = argv[3];
const unsigned int numberOfIterations = atoi( argv[4] );
const double smoothingFactor = atof( argv[5] );
const unsigned int numberOfClasses = atoi( argv[6] );
const unsigned int numberOfArgumentsBeforeMeans = 7;
const unsigned int NumberOfComponents = 3;
if( static_cast<unsigned int>(argc) <
numberOfClasses * NumberOfComponents + numberOfArgumentsBeforeMeans )
{
std::cerr << "Error: " << std::endl;
std::cerr << numberOfClasses << " classes has been specified ";
std::cerr << "but no enough means have been provided in the command ";
std::cerr << "line arguments " << std::endl;
return EXIT_FAILURE;
}
typedef unsigned char PixelComponentType;
const unsigned int Dimension = 2;
typedef itk::Vector<PixelComponentType,NumberOfComponents> PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( inputImageFileName );
typedef unsigned char LabelPixelType;
typedef itk::Image<LabelPixelType, Dimension > LabelImageType;
typedef itk::ImageFileReader< LabelImageType > LabelReaderType;
LabelReaderType::Pointer labelReader = LabelReaderType::New();
labelReader->SetFileName( inputLabelImageFileName );
typedef itk::MRFImageFilter< ImageType, LabelImageType > MRFFilterType;
MRFFilterType::Pointer mrfFilter = MRFFilterType::New();
mrfFilter->SetInput( reader->GetOutput() );
mrfFilter->SetNumberOfClasses( numberOfClasses );
mrfFilter->SetMaximumNumberOfIterations( numberOfIterations );
mrfFilter->SetSmoothingFactor( smoothingFactor );
mrfFilter->SetErrorTolerance( 1e-7 );
typedef itk::ImageClassifierBase<
ImageType,
LabelImageType > SupervisedClassifierType;
SupervisedClassifierType::Pointer classifier =
SupervisedClassifierType::New();
typedef itk::MinimumDecisionRule DecisionRuleType;
DecisionRuleType::Pointer classifierDecisionRule = DecisionRuleType::New();
classifier->SetDecisionRule( classifierDecisionRule.GetPointer() );
typedef itk::Statistics::DistanceToCentroidMembershipFunction<
PixelType >
MembershipFunctionType;
typedef MembershipFunctionType::Pointer MembershipFunctionPointer;
double meanDistance = 0;
vnl_vector<double> centroid(NumberOfComponents);
for( unsigned int i=0; i < numberOfClasses; i++ )
{
MembershipFunctionPointer membershipFunction = MembershipFunctionType::New();
for( unsigned int j=0; j < NumberOfComponents; j++ )
{
centroid[j] = atof( argv[j+i*NumberOfComponents+numberOfArgumentsBeforeMeans] );
}
membershipFunction->SetCentroid( centroid );
classifier->AddMembershipFunction( membershipFunction );
meanDistance += static_cast< double > (centroid[0]);
}
meanDistance /= numberOfClasses;
mrfFilter->SetNeighborhoodRadius( 1 );
std::vector< double > weights;
weights.push_back(1.5);
weights.push_back(2.0);
weights.push_back(1.5);
weights.push_back(2.0);
weights.push_back(0.0); // This is the central pixel
weights.push_back(2.0);
weights.push_back(1.5);
weights.push_back(2.0);
weights.push_back(1.5);
double totalWeight = 0;
for(std::vector< double >::const_iterator wcIt = weights.begin();
wcIt != weights.end(); ++wcIt )
{
totalWeight += *wcIt;
}
for(std::vector< double >::iterator wIt = weights.begin();
wIt != weights.end(); wIt++ )
{
*wIt = static_cast< double > ( (*wIt) * meanDistance / (2 * totalWeight));
}
mrfFilter->SetMRFNeighborhoodWeight( weights );
mrfFilter->SetClassifier( classifier );
typedef MRFFilterType::OutputImageType OutputImageType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( mrfFilter->GetOutput() );
writer->SetFileName( outputImageFileName );
try
{
writer->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Problem encountered while writing ";
std::cerr << " image file : " << argv[2] << std::endl;
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
std::cout << "Number of Iterations : ";
std::cout << mrfFilter->GetNumberOfIterations() << std::endl;
std::cout << std::endl;
std::cout << "Stopping condition: " << std::endl;
switch( mrfFilter->GetStopCondition() )
{
case 1:
std::cout << " (1) Maximum number of iterations " << std::endl;
break;
case 2:
std::cout << " (2) Error tolerance: " << std::endl;
break;
}
return EXIT_SUCCESS;
}
| [
"ibanez@5e132c66-7cf4-0310-b4ca-cd4a7079c2d8"
] | ibanez@5e132c66-7cf4-0310-b4ca-cd4a7079c2d8 |
0a04e823dc96a961d22ca185836a8c61e4a0d690 | f2a1cdb8627e6d933024cc269d7835b782622ef9 | /TestingROS_Gui/src/test_chat_gui/src/main.cpp | a4a81cf7b016533e38f8113e63fe3e6dfaa6d117 | [] | no_license | MarkNo1/ROS | 2037aef4e6600d66ef28fdb30457838c394966f8 | 432f1d19d5c6fd060f8abbcd7813c72b454e910a | refs/heads/master | 2020-03-15T10:54:37.671519 | 2018-05-22T15:12:33 | 2018-05-22T15:12:33 | 132,109,839 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 817 | cpp | /**
* @file /src/main.cpp
*
* @brief Qt based gui.
*
* @date November 2010
**/
/*****************************************************************************
** Includes
*****************************************************************************/
#include <QtGui>
#include <QApplication>
#include <test_chat_gui/main_window.hpp>
/*****************************************************************************
** Main
*****************************************************************************/
int main(int argc, char **argv) {
/*********************
** Qt
**********************/
QApplication app(argc, argv);
test_chat_gui::MainWindow w(argc,argv);
w.show();
app.connect(&app, SIGNAL(lastWindowClosed()), &app, SLOT(quit()));
int result = app.exec();
return result;
}
| [
"marcotreglia0@gmail.com"
] | marcotreglia0@gmail.com |
6ebe8df906a26c1cd93ef57da1e8b0fe78804f1d | 38930ef5b986e3a68fada1ac98a97bd68ee24bf6 | /Applications/GoodCore/Maths/Point3.h | ee5bf67ac4e56d20d1070660e377d59bae20908a | [] | no_license | Mayhem50/Good-Engine | a3786abde7671b7fbf649f5738f79abe345b842b | f2aab74f9ccd1dce7e90c7333af748aea6a0b76a | refs/heads/master | 2018-12-28T19:05:45.992218 | 2013-11-24T12:40:08 | 2013-11-24T12:40:08 | 14,660,388 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,673 | h | #pragma once
#include "Vector3.h"
#include "Math.h"
namespace Good
{
class Point3
{
public:
inline Point3(void) {}
inline Point3(Real px, Real py, Real pz):x(px), y(py), z(pz) {}
inline Point3(Real p[3]): x(p[0]), y(p[1]), z(p[2]) {}
inline Point3& operator=(const Point3& rPoint)
{
x = rPoint.x;
y = rPoint.y;
z = rPoint.z;
return *this;
}
//Deplacement d'un point
inline Point3 operator + (const Vector3& rVector) const
{
return Point3(
x + rVector.x,
y + rVector.y,
z + rVector.z);
}
inline Point3 operator - (const Vector3& rVector) const
{
return Point3(
x - rVector.x,
y - rVector.y,
z - rVector.z);
}
//Deplacement via coeff proportionnel
inline Point3 operator * (const Real coeff) const
{
return Point3(
coeff * x,
coeff * y,
coeff * z);
}
inline Point3 operator / (const Real coeff) const
{
Real newCoeff = 1/coeff;
return this->operator*(newCoeff);
}
//Diff entre 2 points --> un vecteur
inline Vector3 operator - (const Point3& rPoint) const
{
return Vector3(
rPoint.x - x,
rPoint.y - y,
rPoint.z - z);
}
inline Real operator * (const Vector3& rVector) const
{
return (x * rVector.x + y * rVector.y + z * rVector.z);
}
inline bool operator == (const Point3& rPoint) const
{
return (x == rPoint.x && y == rPoint.y && z == rPoint.z);
}
inline bool operator != (const Point3& rPoint) const
{
return (x != rPoint.x || y != rPoint.y || z != rPoint.z);
}
static const Point3 ORIGIN;
Real x, y, z;
};
}
| [
"regnier.ben@gmail.com"
] | regnier.ben@gmail.com |
909d7d69da1e1d4cdd7a6c2852b521b91a39f212 | 7c458b1ffe47ac0ab7e351edba5484039dc2c729 | /ExamplePatchDifference.cpp | e19c917bf9963ddd0b46705838fdfe689349bbe3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | daviddoria/InteractiveBestPatches | 04be8a8d6e01907052b82939bb19646679f478ab | 876c9c3b0e083fde42bda325fe10f351f1b908c7 | refs/heads/master | 2021-01-23T04:00:04.295734 | 2012-05-18T17:25:40 | 2012-05-18T17:25:40 | 2,418,482 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,608 | cpp | /*=========================================================================
*
* Copyright David Doria 2011 daviddoria@gmail.com
*
* 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.txt
*
* 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 "Types.h"
#include "SelfPatchCompare.h"
int main(int argc, char *argv[])
{
if(argc != 3)
{
std::cerr << "Only gave " << argc << " arguments!" << std::endl;
std::cerr << "Required arguments: image mask" << std::endl;
return EXIT_FAILURE;
}
std::string imageFilename = argv[1];
std::string maskFilename = argv[2];
std::cout << "Reading image: " << imageFilename << std::endl;
std::cout << "Reading mask: " << maskFilename << std::endl;
typedef itk::ImageFileReader<FloatVectorImageType> VectorImageReaderType;
VectorImageReaderType::Pointer imageReader = VectorImageReaderType::New();
imageReader->SetFileName(imageFilename.c_str());
imageReader->Update();
typedef itk::ImageFileReader<Mask> MaskReaderType;
MaskReaderType::Pointer maskReader = MaskReaderType::New();
maskReader->SetFileName(maskFilename.c_str());
maskReader->Update();
itk::Size<2> size;
size.Fill(21);
itk::Index<2> sourceCorner;
sourceCorner[0] = 319;
sourceCorner[1] = 292;
itk::ImageRegion<2> sourceRegion(sourceCorner, size);
itk::Index<2> targetCorner;
targetCorner[0] = 193;
targetCorner[1] = 218;
itk::ImageRegion<2> targetRegion(targetCorner, size);
SelfPatchCompare patchCompare(imageReader->GetOutput()->GetNumberOfComponentsPerPixel());
patchCompare.SetTargetRegion(targetRegion);
patchCompare.SetImage(imageReader->GetOutput());
patchCompare.SetMask(maskReader->GetOutput());
float totalAbsoluteDifference = patchCompare.SlowTotalAbsoluteDifference(sourceRegion);
float totalSquaredDifference = patchCompare.SlowTotalSquaredDifference(sourceRegion);
std::cerr << "Total Absolute Difference: " << totalAbsoluteDifference << std::endl;
std::cerr << "Total Squared Difference: " << totalSquaredDifference << std::endl;
return EXIT_SUCCESS;
}
| [
"daviddoria@gmail.com"
] | daviddoria@gmail.com |
37a3acccd1a91e9d3d284cb9a53e3f0c15bf8761 | e7b61bc32df44c178dd1b19769d9df80b85d0d98 | /OpenGL/Project1/Material.cpp | b6445e610fac96721e6320465d2cb214c8d1b2e0 | [] | no_license | haraseiya/LearnOpenGL | 617f1aa9242485529c22327f26bb6216e07861a5 | a7dec67dff5d11daddc55339cd526b64c44ac1f4 | refs/heads/master | 2022-12-02T16:46:16.562063 | 2020-08-18T22:15:24 | 2020-08-18T22:15:24 | 272,852,778 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 12,098 | cpp | #include<stdio.h>
#include<glad.h>
#include<sdl.h>
#include<sdl_image.h>
#include<iostream>
#include "Shader.h"
#include "Math.h"
#include "Input.h"
#include "mouse.h"
#include "FlyCamera.h"
Uint32 lastTime = 0; // 最後のフレーム時刻 intミリ秒単位
float deltaTime = 0.0f; // フレーム間の時刻 秒単位 ( 1.0 sec )
int main(int argc, char** argv)
{
// SDLの初期化
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0)
{
printf("SDL初期化失敗 : %s\n", SDL_GetError());
return -1;
}
// OpenGL アトリビュートのセット
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
// GL version 3.1
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
// 8Bit RGBA チャンネル
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
// ダブルバッファリング
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
// ハードウェアアクセラレーションを強制
SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
// Windowの作成
SDL_Window* SDLWindow = SDL_CreateWindow("SDL & GL Window",
100, 80, 1024, 768, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
if (!SDLWindow)
{
printf("Windowの作成に失敗: %s", SDL_GetError());
return false;
}
// SDL Rendererの作成
SDL_Renderer* renderer = SDL_CreateRenderer(SDLWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (!renderer)
{
printf("SDLRendererの作成に失敗 %s", SDL_GetError());
return false;
}
SDL_GLContext context;
context = SDL_GL_CreateContext(SDLWindow);
// GLADの初期化
const int version = gladLoadGL();
if (version == 0)
{
printf("glad初期化失敗!\n");
}
glEnable(GL_DEPTH_TEST);
// 画像をSDLサーフェスに読み込む
SDL_Surface* surf = IMG_Load("images/nier.jpg");
if (!surf)
{
printf("ファイル読み込みに失敗");
return -1;
}
// 画像の幅・高さを取得
int width = surf->w;
int height = surf->h;
int channels = surf->format->BytesPerPixel;
// 画像フォーマットの判別
int format = GL_RGB;
if (channels == 4)
{
format = GL_RGBA;
}
// SDLサーフェスからGLテクスチャ作成&各種パラメータセット
GLuint textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
// テクスチャラッピング&フィルタリング設定
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// SDLデータをGLのテクスチャデータとしてコピーする
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format,
GL_UNSIGNED_BYTE, surf->pixels);
glGenerateMipmap(GL_TEXTURE_2D);
// SDLサーフェスは用済みなので解放
SDL_FreeSurface(surf);
////////////////////////////////////////////////////////////////////////
// 頂点定義(ライトに照らされる側のキューブ) 頂点+頂点法線
////////////////////////////////////////////////////////////////////////
float cubevertices[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f
};
// 頂点配列 頂点バッファ エレメント配列バッファ
unsigned int CubeVAO, CubeVBO;
glGenVertexArrays(1, &CubeVAO);
glGenBuffers(1, &CubeVBO);
// 頂点配列オブジェクト(VAO)に、VBOを関連付ける
glBindVertexArray(CubeVAO);
{
glBindBuffer(GL_ARRAY_BUFFER, CubeVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubevertices), cubevertices, GL_STATIC_DRAW);
}
// 位置属性 : 0
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// 法線属性 : 1
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
///////////////////////////////////////////////////////////// キューブ頂点定義
////////////////////////////////////////////////////////////////////////
// 頂点定義(光源を表すキューブ)
// 照らされる側の影響を受けたくないので重複しているが別で定義
////////////////////////////////////////////////////////////////////////
float cubeVertices[] = {
//x , y , z Nx, Ny, Nz
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f
};
// 頂点配列 頂点バッファ エレメント配列バッファ
unsigned int lightVAO, lightVBO;
glGenVertexArrays(1, &lightVAO);
glGenBuffers(1, &lightVBO);
// 頂点配列オブジェクト(VAO)に、VBOを関連付ける
glBindVertexArray(lightVAO);
{
glBindBuffer(GL_ARRAY_BUFFER, lightVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), cubeVertices, GL_STATIC_DRAW);
}
// 位置属性 : 0
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// 法線属性 : 1
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
///////////////////////////////////////////////////////////// 光源用頂点定義終わり
// 照らされるキューブ用のシェーダー
Shader cubeshader("PhoneLight.vert", "material.frag");
// 光源用のシェーダー
Shader lightCubeshader("lightCube.vert", "lightCube.frag");
Vector3 cameraPos(0.0f, 1.0f, 5.0f);
FlyCamera flyCamera(cameraPos);
// 光源位置定義
/*Vector3 lightPos(0.0f, 0.5f, 2.0f);*/
Vector2 mouse;
MOUSE_INSTANCE.SetRelativeMouseMode(true);
float anim = 0;
bool renderLoop = true;
while (renderLoop)
{
// キー入力更新
INPUT_INSTANCE.Update(); // レンダーループの初めに1回だけ呼ぶ
MOUSE_INSTANCE.Update(); // レンダーループの初めに1回だけ呼ぶ
deltaTime = (SDL_GetTicks() - lastTime) / 1000.0f;
lastTime = SDL_GetTicks();
// 終了イベントのキャッチ
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_MOUSEWHEEL:
MOUSE_INSTANCE.OnMouseWheelEvent(event);
break;
case SDL_QUIT:
renderLoop = false;
break;
}
}
flyCamera.UpdateCamera(deltaTime);
// Model行列
Matrix4 model;
// レンダリング
// カラーバッファのクリア
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// テクスチャを利用
glBindTexture(GL_TEXTURE_2D, textureID);
// ライト公転
anim += 0.001;
/*float lightX = 2.0f * sin(anim);
float lightY = 0.0f;
float lightZ = 2.0f * cos(anim);*/
float lightX = 0.0f;
float lightY = 1.0f;
float lightZ = 0.0f;
Vector3 lightPos(lightX, lightY, lightZ);
// ライト色
float lightColorR = sin(anim);
float lightColorG = cos(anim);
float lightColorB = sin(anim);
Vector3 lightColor(lightColorR, lightColorG, lightColorB);
// cube
cubeshader.use();
cubeshader.setVec3("light.position", lightPos);
cubeshader.setVec3("viewPos", cameraPos);
cubeshader.setMatrix("model", model.GetAsFloatPtr());
cubeshader.setMatrix("view", flyCamera.GetViewMatrix().GetAsFloatPtr());
cubeshader.setMatrix("projection", flyCamera.GetProjectionMatrix().GetAsFloatPtr());
// ライトセット
Vector3 diffuseColor = lightColor * Vector3(0.5f, 0.5f, 0.5f);
Vector3 ambientColor = diffuseColor * Vector3(0.2f, 0.2f, 0.2f);
cubeshader.setVec3("light.ambient", ambientColor);
cubeshader.setVec3("light.diffuse", diffuseColor);
cubeshader.setVec3("light.specular", 1.0f, 1.0f, 1.0f);
// マテリアルセット
cubeshader.setVec3("material.ambient", 1.0f, 0.5f, 0.31f);
cubeshader.setVec3("material.diffuse", 1.0f, 0.5f, 0.31f);
cubeshader.setVec3("material.specular", 0.5f, 0.5f, 0.5f);
cubeshader.setFloat("material.shininess",2.0f);
glBindVertexArray(CubeVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
Matrix4 lightModel;
lightModel = Matrix4::CreateScale(0.2f) * Matrix4::CreateTranslation(lightPos);
// lightcubeの設定
lightCubeshader.use();
lightCubeshader.setMatrix("model", lightModel.GetAsFloatPtr());
lightCubeshader.setMatrix("view", flyCamera.GetViewMatrix().GetAsFloatPtr());
lightCubeshader.setMatrix("projection", flyCamera.GetProjectionMatrix().GetAsFloatPtr());
// lightcube描画
glBindVertexArray(lightVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
SDL_GL_SwapWindow(SDLWindow);
}
return 0;
} | [
"seiyamidori@gmail.com"
] | seiyamidori@gmail.com |
b05f58be38fce61758e8b9cd47d7a50abf7c5420 | effdc6a43e045824dae19dc9ae275b02a4eeb7a8 | /src/qt/editaddressdialog.h | 8623a8540e037a58d82a66b41aa4faf66088c1f8 | [
"MIT"
] | permissive | CommanderXanon/Xcoin | af0a6589e0e76d662239a8e9a49510bb4c12de56 | 58c8daa1346e1b5f563d457c475c7f2804596551 | refs/heads/master | 2022-11-05T02:28:43.419980 | 2020-06-21T03:05:00 | 2020-06-21T03:05:00 | 272,878,694 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,286 | h | // Copyright (c) 2011-2018 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 XCOIN_QT_EDITADDRESSDIALOG_H
#define XCOIN_QT_EDITADDRESSDIALOG_H
#include <QDialog>
class AddressTableModel;
namespace Ui {
class EditAddressDialog;
}
QT_BEGIN_NAMESPACE
class QDataWidgetMapper;
QT_END_NAMESPACE
/** Dialog for editing an address and associated information.
*/
class EditAddressDialog : public QDialog
{
Q_OBJECT
public:
enum Mode {
NewSendingAddress,
EditReceivingAddress,
EditSendingAddress
};
explicit EditAddressDialog(Mode mode, QWidget *parent = 0);
~EditAddressDialog();
void setModel(AddressTableModel *model);
void loadRow(int row);
QString getAddress() const;
void setAddress(const QString &address);
public Q_SLOTS:
void accept();
private:
bool saveCurrentRow();
/** Return a descriptive string when adding an already-existing address fails. */
QString getDuplicateAddressWarning() const;
Ui::EditAddressDialog *ui;
QDataWidgetMapper *mapper;
Mode mode;
AddressTableModel *model;
QString address;
};
#endif // XCOIN_QT_EDITADDRESSDIALOG_H
| [
"AnonymousCommand@protonmail.com"
] | AnonymousCommand@protonmail.com |
669a763eae413fd383a25c6ef8d71510e66015de | 452e9a09907eb6a884d06e0ace7ef873cd01067e | /problems/problem_18.h | 53d703daaa5b74136895ed8547b76ac38dbd54ac | [] | no_license | hadhadhadhadabettereffect/euler | fd02f2b6366325e70058924742eb86139d6d61f3 | 7a7179e53292de743a38d7f7ab371529fd58f049 | refs/heads/master | 2020-06-25T11:46:14.470947 | 2017-06-30T00:30:45 | 2017-06-30T00:30:45 | 74,532,445 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,192 | h | #ifndef PROBLEM_18
#define PROBLEM_18
#include "problem.h"
/************************
By starting at the top of the triangle below and moving to
adjacent numbers on the row below, the maximum total from top to bottom is 23.
(3)
(7) 4
2(4) 6
8 5(9) 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
NOTE: As there are only 16384 routes, it is possible to solve this problem
by trying every route. However, Problem 67, is the same challenge with a triangle
ontaining one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)
************************/
namespace problem_18 {
// total count of numbers in triangle
// == sum of numbers up to row count (15)
// == 15 * 16 / 2
static const int total_numbers = 120;
int larger ( int &a, int &b )
{
return a > b ? a : b;
}
int solve ()
{
int pyramid[total_numbers] = {
75,
95,64,
17,47,82,
18,35,87,10,
20,4,82,47,65,
19,1,23,75,3,34,
88,2,77,73,7,63,67,
99,65,4,28,6,16,70,92,
41,41,26,56,83,40,80,70,33,
41,48,72,33,47,32,37,16,94,29,
53,71,44,65,25,43,91,52,97,51,14,
70,11,33,28,77,73,17,78,39,68,17,57,
91,71,52,38,17,14,91,43,58,50,27,29,48,
63,66,4,68,89,53,67,30,73,16,69,87,40,31,
4,62,98,27,23,9,70,98,73,93,38,53,60,4,23
};
// manually adding single-path options at the top
// (1,0),(1,1) + (0,0)
pyramid[1] += pyramid[0];
pyramid[2] += pyramid[0];
// (2,0) + (1,0)
pyramid[3] += pyramid[1];
// starting iteration on row 2
int row = 2;
int col = 2;
int largest = 0;
// starting i on 4 since 0-3 set manually
for ( int i = 4; i < total_numbers; ++i )
{
if ( --col ) pyramid[i] += larger( pyramid[i - row], pyramid[i - row - 1] );
else {
col = ++row;
// adding single path along right side
pyramid[i] += pyramid[i - row];
// break on last row
if ( ++i == total_numbers ) break;
// adding single path along left side
pyramid[i] += pyramid[i - row];
}
}
for ( int i = total_numbers - 15; i < total_numbers; ++i )
{
if ( pyramid[i] > largest ) largest = pyramid[i];
}
return largest;
}
Problem p(18, solve);
}
#endif | [
"ericjbirkeland@gmail.com"
] | ericjbirkeland@gmail.com |
6d056cf8127e2982fd1c19cb6e0f6b04d9fcbb48 | ee4d9243c725b2ffc689dcfe0506df2e8e3606bc | /SP3_Base_Team05/Base/Source/MeshBuilder.h | 6f4e61f88d3f6f237ad8ef4a76eb086637ad7f7d | [] | no_license | zhiternn/SP3_Team05 | a5e2280b76b80ae5aa9ab96855df918608953fe1 | 73552ee440e5fe7be487b926758501f2e78bb06f | refs/heads/master | 2021-01-15T15:31:13.876022 | 2016-09-01T09:55:50 | 2016-09-01T09:55:50 | 65,693,677 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,047 | h | #ifndef MESH_BUILDER_H
#define MESH_BUILDER_H
#include "Mesh.h"
#include "Vertex.h"
#include "SpriteAnimation.h"
#include <vector>
/******************************************************************************/
/*!
Class MeshBuilder:
\brief Provides methods to generate mesh of different shapes
*/
/******************************************************************************/
class MeshBuilder
{
public:
static Mesh* GenerateAxes(const std::string &meshName, float lengthX=0.0f, float lengthY=0.0f, float lengthZ=0.0f);
static Mesh* GenerateCrossHair(const std::string &meshName, float colour_r=1.0f, float colour_g=1.0f, float colour_b=0.0f, float length=1.0f);
static Mesh* GenerateQuad(const std::string &meshName, Color color, float length = 1.f, float texRepeat = 1.0f); //hehexd
static Mesh* GenerateCircle(const std::string &meshName, Color color, float length = 1.0f);
static Mesh* GenerateCircleOutline(const std::string &meshName, Color color, float length = 1.f);
static Mesh* GenerateCube(const std::string &meshName, Color color, float length = 1.f);
static Mesh* GenerateRing(const std::string &meshName, Color color, unsigned numSlice, float outerR = 1.f, float innerR = 0.f);
static Mesh* GenerateSphere(const std::string &meshName, Color color, unsigned numStack, unsigned numSlice, float radius = 1.f);
static Mesh* GenerateCone(const std::string &meshName, Color color, unsigned numSlice, float radius, float height);
static Mesh* GenerateOBJ(const std::string &meshName, const std::string &file_path);
static Mesh* GenerateText(const std::string &meshName, unsigned row, unsigned col);
static Mesh* GenerateSkyPlane(const std::string &meshName, Color color, int slices, float PlanetRadius, float AtmosphereRadius, float hTile, float vTile);
static Mesh* GenerateTerrain(const std::string &meshName, const std::string &file_path, std::vector<unsigned char> &heightMap);
static SpriteAnimation* MeshBuilder::GenerateSpriteAnimation(const std::string &meshName, unsigned numRow, unsigned numCol);
};
#endif | [
"zhiternn@outlook.com"
] | zhiternn@outlook.com |
d29785d3d14961637f1f310b9a715c3596818215 | 65c76a2d46c986118c891f071681eed65adea5f9 | /tensorflow/compiler/mlir/lite/utils/perception_ops_utils.cc | ed331cff93c3e9487e4ebe22d0e0916541dca22d | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | permissive | tornado12345/tensorflow | dfe07e3f65f0a36d461a5633f2dd814ebf0c8c31 | afa7d045f009857a1b31e989193c199b95dda0a4 | refs/heads/master | 2022-03-29T17:52:34.030836 | 2022-03-14T00:48:31 | 2022-03-14T00:52:08 | 73,092,236 | 0 | 0 | Apache-2.0 | 2020-12-01T01:01:29 | 2016-11-07T15:27:24 | C++ | UTF-8 | C++ | false | false | 8,827 | cc | /* Copyright 2020 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 "tensorflow/compiler/mlir/lite/utils/perception_ops_utils.h"
#include "mlir/IR/Attributes.h" // from @llvm-project
#include "mlir/IR/Builders.h" // from @llvm-project
#include "mlir/IR/OpDefinition.h" // from @llvm-project
#include "mlir/IR/Types.h" // from @llvm-project
#include "mlir/IR/Value.h" // from @llvm-project
#include "mlir/Support/LogicalResult.h" // from @llvm-project
#include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/lite/c/builtin_op_data.h"
namespace mlir {
namespace TFL {
namespace {
constexpr char kTFImplements[] = "tf._implements";
constexpr char kMaxUnpooling[] = "MaxUnpooling2D";
constexpr char kImageWarping[] = "DenseImageWarp";
inline OpaqueElementsAttr CustomOption(OpBuilder* builder,
const std::string& content) {
ShapedType type = RankedTensorType::get(
{static_cast<int64_t>(content.size())}, builder->getIntegerType(8));
return OpaqueElementsAttr::get(builder->getContext()->getLoadedDialect("tfl"),
type,
StringRef(content.data(), content.size()));
}
inline LogicalResult HasIntegerArrayWithSize(FuncOp* func,
const DictionaryAttr& attrs,
const std::string& attr_name,
int N) {
ArrayAttr array_attr = attrs.get(attr_name).dyn_cast_or_null<ArrayAttr>();
if (array_attr == nullptr || array_attr.size() != N) {
return func->emitWarning()
<< "'" << attr_name << "' attribute for " << kMaxUnpooling
<< " must be set and has size of " << N;
}
for (Attribute integer_attr : array_attr.getValue()) {
IntegerAttr value = integer_attr.dyn_cast<IntegerAttr>();
if (!value) {
return func->emitWarning()
<< "'" << attr_name << "' attribute for " << kMaxUnpooling
<< " does not contain integer values";
}
}
return success();
}
inline LogicalResult GetIntegerArraySafe(
FuncOp* func, const DictionaryAttr& attrs, const std::string& attr_name,
llvm::SmallVectorImpl<int32_t>* results, int N) {
ArrayAttr array_attr = attrs.get(attr_name).dyn_cast_or_null<ArrayAttr>();
if (array_attr == nullptr || array_attr.size() != N) {
return func->emitError()
<< "'" << attr_name << "' attribute for " << kMaxUnpooling
<< " must be set and has size of " << N;
}
results->reserve(N);
for (Attribute integer_attr : array_attr.getValue()) {
IntegerAttr value = integer_attr.dyn_cast<IntegerAttr>();
if (!value) {
return func->emitError()
<< "'" << attr_name << "' attribute for " << kMaxUnpooling
<< " does not contain integer values";
}
results->push_back(value.getInt());
}
return success();
}
} // namespace
LogicalResult ConvertMaxUnpoolingFunc::RewriteFunc() {
func_.eraseBody();
func_.addEntryBlock();
func_->setAttr(kTFImplements,
StringAttr::get(func_.getContext(), kMaxUnpooling));
OpBuilder builder(func_.getBody());
std::string custom_option_buffer;
if (failed(CreateCustomOptions(custom_option_buffer))) {
return failure();
}
auto op = builder.create<CustomOp>(
func_.getLoc(), func_.getType().getResults(), func_.getArguments(),
kMaxUnpooling, CustomOption(&builder, custom_option_buffer));
builder.create<func::ReturnOp>(func_.getLoc(), op.getResults());
return success();
}
LogicalResult ConvertMaxUnpoolingFunc::VerifySignature() {
// Verify high-level function signature.
if (func_.getNumArguments() != 2) {
return func_.emitWarning()
<< "Invalid number of arguments to " << kMaxUnpooling << ": "
<< func_.getNumArguments();
}
if (func_.getType().getNumResults() != 1) {
return func_.emitWarning()
<< "Invalid number of results from " << kMaxUnpooling << ": "
<< func_.getType().getNumResults();
}
auto attrs = attr_.getAttrs();
if (failed(HasIntegerArrayWithSize(&func_, attrs, "pool_size", 2))) {
return failure();
}
if (failed(HasIntegerArrayWithSize(&func_, attrs, "strides", 2))) {
return failure();
}
// Retrieves padding.
auto padding = attrs.get("padding").dyn_cast_or_null<StringAttr>();
if (!padding) {
return func_.emitWarning() << "'padding' attribute for " << kMaxUnpooling
<< " is not set or not a string";
}
if (!padding.getValue().equals("VALID") &&
!padding.getValue().equals("SAME")) {
return func_.emitWarning()
<< "Padding for " << kMaxUnpooling << " must be 'SAME' or 'VALID'";
}
return success();
}
LogicalResult ConvertMaxUnpoolingFunc::CreateCustomOptions(
std::string& custom_option_buffer) {
auto attrs = attr_.getAttrs();
TfLitePoolParams pool_params;
llvm::SmallVector<int32_t, 2> pool_size;
if (failed(GetIntegerArraySafe(&func_, attrs, "pool_size", &pool_size, 2))) {
return failure();
}
pool_params.filter_height = pool_size[0];
pool_params.filter_width = pool_size[1];
// Retrieve strides.
llvm::SmallVector<int32_t, 2> strides;
if (failed(GetIntegerArraySafe(&func_, attrs, "strides", &strides, 2))) {
return failure();
}
pool_params.stride_height = strides[0];
pool_params.stride_width = strides[1];
// Retrieves padding.
auto padding = attrs.get("padding").dyn_cast_or_null<StringAttr>();
if (!padding) {
return func_.emitError() << "'padding' attribute for " << kMaxUnpooling
<< " is not set or not a string";
}
if (padding.getValue().equals("VALID")) {
pool_params.padding = kTfLitePaddingValid;
} else if (padding.getValue().equals("SAME")) {
pool_params.padding = kTfLitePaddingSame;
} else {
return func_.emitError()
<< "Padding for " << kMaxUnpooling << " must be 'SAME' or 'VALID'";
}
pool_params.activation = kTfLiteActNone;
pool_params.computed.padding = TfLitePaddingValues{0, 0, 0, 0};
custom_option_buffer.assign(reinterpret_cast<char*>(&pool_params),
sizeof(TfLitePoolParams));
return success();
}
LogicalResult ConvertDenseImageWarpFunc::RewriteFunc() {
func_.eraseBody();
func_.addEntryBlock();
func_->setAttr(kTFImplements,
StringAttr::get(func_.getContext(), kImageWarping));
OpBuilder builder(func_.getBody());
auto op = builder.create<CustomOp>(
func_.getLoc(), func_.getType().getResults(), func_.getArguments(),
kImageWarping, CustomOption(&builder, /*content=*/""));
builder.create<func::ReturnOp>(func_.getLoc(), op.getResults());
return success();
}
LogicalResult ConvertDenseImageWarpFunc::VerifySignature() {
// Verify high-level function signature.
if (func_.getNumArguments() != 2) {
return func_.emitWarning()
<< "Invalid number of arguments to " << kImageWarping << ": "
<< func_.getNumArguments();
}
if (func_.getType().getNumResults() != 1) {
return func_.emitWarning()
<< "Invalid number of results from " << kImageWarping << ": "
<< func_.getType().getNumResults();
}
// Check types and shapes.
auto image_type =
func_.getType().getInput(0).dyn_cast_or_null<RankedTensorType>();
if (!image_type || !image_type.getElementType().isF32() ||
image_type.getRank() != 4) {
return func_.emitWarning() << "Image should be a 4D float tensor";
}
auto flow_type =
func_.getType().getInput(1).dyn_cast_or_null<RankedTensorType>();
if (!flow_type || !flow_type.getElementType().isF32() ||
flow_type.getRank() != 4) {
return func_.emitWarning() << "Flow should be a 4D float tensor";
}
auto output_type =
func_.getType().getResult(0).dyn_cast_or_null<RankedTensorType>();
if (!output_type || !output_type.getElementType().isF32() ||
output_type.getRank() != 4) {
return func_.emitWarning() << "Output should be a 4D float tensor";
}
return success();
}
} // namespace TFL
} // namespace mlir
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
e94f678307b62480a5b4324b6ed22f0248c188ef | bc90e70ee2139b034c65a5755395ff55faac87d0 | /sprout/algorithm/is_strictly_increasing.hpp | 04a2b2180ea9ffad0adad36690db8252730d9735 | [
"BSL-1.0"
] | permissive | Manu343726/Sprout | 0a8e2d090dbede6f469f6b875d217716d0200bf7 | feac3f52c785deb0e5e6cd70c8b4960095b064be | refs/heads/master | 2021-01-21T07:20:16.742204 | 2015-05-28T04:11:39 | 2015-05-28T04:11:39 | 37,670,169 | 0 | 1 | null | 2015-06-18T16:09:41 | 2015-06-18T16:09:41 | null | UTF-8 | C++ | false | false | 1,144 | hpp | /*=============================================================================
Copyright (c) 2011-2015 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_ALGORITHM_IS_STRICTLY_INCREASING_HPP
#define SPROUT_ALGORITHM_IS_STRICTLY_INCREASING_HPP
#include <iterator>
#include <sprout/config.hpp>
#include <sprout/algorithm/is_sorted.hpp>
#include HDR_FUNCTIONAL_SSCRISK_CEL_OR_SPROUT
namespace sprout {
//
// is_strictly_increasing
//
// recursion depth:
// O(log N)
//
template<typename ForwardIterator>
inline SPROUT_CONSTEXPR bool
is_strictly_increasing(ForwardIterator first, ForwardIterator last) {
return sprout::is_sorted(
first, last,
NS_SSCRISK_CEL_OR_SPROUT::less_equal<typename std::iterator_traits<ForwardIterator>::value_type>()
);
}
} // namespace sprout
#endif // #ifndef SPROUT_ALGORITHM_IS_STRICTLY_INCREASING_HPP
| [
"bolero.murakami@gmail.com"
] | bolero.murakami@gmail.com |
8ef18af13f6f07d9ea0a9e5cda26376f79a9a8d5 | e4f07fa2a63a56cbaa9e72410a743f340665648b | /src_mixed/input.cpp | ba582b14fe9a1096fd4fb8be8fc1ef777c4e7dac | [] | no_license | sepehrs07/Parallel_Path_Swapping | c3fa36b76f70c779fb121d9f0395377d1167a3f3 | ded12d7fda51976230a12256776d4d551805dbcb | refs/heads/master | 2016-09-15T23:30:20.287698 | 2014-05-13T01:32:55 | 2014-05-13T01:32:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,233 | cpp | /* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#include "mpi.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "input.h"
#include "universe.h"
#include "atom.h"
#include "atom_vec.h"
#include "comm.h"
#include "group.h"
#include "domain.h"
#include "output.h"
#include "thermo.h"
#include "force.h"
#include "pair.h"
#include "min.h"
#include "modify.h"
#include "compute.h"
#include "bond.h"
#include "angle.h"
#include "dihedral.h"
#include "improper.h"
#include "kspace.h"
#include "update.h"
#include "neighbor.h"
#include "special.h"
#include "variable.h"
#include "error.h"
#include "memory.h"
#define CommandInclude
#include "style.h"
#undef CommandInclude
using namespace LAMMPS_NS;
#define MAXLINE 2048
#define DELTA 4
/* ---------------------------------------------------------------------- */
Input::Input(LAMMPS *lmp, int argc, char **argv) : Pointers(lmp)
{
MPI_Comm_rank(world,&me);
line = new char[MAXLINE];
copy = new char[MAXLINE];
work = new char[MAXLINE];
narg = maxarg = 0;
arg = NULL;
echo_screen = 0;
echo_log = 1;
label_active = 0;
labelstr = NULL;
jump_skip = 0;
if (me == 0) {
nfile = maxfile = 1;
infiles = (FILE **) memory->smalloc(sizeof(FILE *),"input:infiles");
infiles[0] = infile;
} else infiles = NULL;
variable = new Variable(lmp);
// process command-line args
// check for args "-var" and "-echo"
// caller has already checked that sufficient arguments exist
int iarg = 0;
while (iarg < argc) {
if (strcmp(argv[iarg],"-var") == 0) {
variable->set(argv[iarg+1],argv[iarg+2]);
iarg += 3;
} else if (strcmp(argv[iarg],"-echo") == 0) {
narg = 1;
char **tmp = arg; // trick echo() into using argv instead of arg
arg = &argv[iarg+1];
echo();
arg = tmp;
iarg += 2;
} else iarg++;
}
}
/* ---------------------------------------------------------------------- */
Input::~Input()
{
// don't free command and arg strings
// they just point to other allocated memory
delete variable;
delete [] line;
delete [] copy;
delete [] work;
if (labelstr) delete [] labelstr;
if (arg) memory->sfree(arg);
if (infiles) memory->sfree(infiles);
}
/* ----------------------------------------------------------------------
process all input from infile
infile = stdin or file if command-line arg "-in" was used
------------------------------------------------------------------------- */
void Input::file()
{
int n;
while (1) {
// read one line from input script
// if line ends in continuation char '&', concatenate next line(s)
// n = str length of line
if (me == 0) {
if (fgets(line,MAXLINE,infile) == NULL) n = 0;
else n = strlen(line) + 1;
while (n >= 3 && line[n-3] == '&') {
if (fgets(&line[n-3],MAXLINE-n+3,infile) == NULL) n = 0;
else n = strlen(line) + 1;
}
}
// bcast the line
// if n = 0, end-of-file
// error if label_active is set, since label wasn't encountered
// if original input file, code is done
// else go back to previous input file
MPI_Bcast(&n,1,MPI_INT,0,world);
if (n == 0) {
if (label_active) error->all("Label wasn't found in input script");
if (me == 0) {
if (infile != stdin) fclose(infile);
nfile--;
}
MPI_Bcast(&nfile,1,MPI_INT,0,world);
if (nfile == 0) break;
if (me == 0) infile = infiles[nfile-1];
continue;
}
MPI_Bcast(line,n,MPI_CHAR,0,world);
// if n = MAXLINE, line is too long
if (n == MAXLINE) {
char str[MAXLINE+32];
sprintf(str,"Input line too long: %s",line);
error->all(str);
}
// echo the command unless scanning for label
if (me == 0 && label_active == 0) {
if (echo_screen && screen) fprintf(screen,"%s",line);
if (echo_log && logfile) fprintf(logfile,"%s",line);
}
// parse the line
// if no command, skip to next line in input script
parse();
if (command == NULL) continue;
// if scanning for label, skip command unless it's a label command
if (label_active && strcmp(command,"label") != 0) continue;
// execute the command
if (execute_command()) {
char str[MAXLINE];
sprintf(str,"Unknown command: %s",line);
error->all(str);
}
}
}
/* ----------------------------------------------------------------------
process all input from filename
------------------------------------------------------------------------- */
void Input::file(const char *filename)
{
// error if another nested file still open
// if single open file is not stdin, close it
// open new filename and set infile, infiles[0]
if (me == 0) {
if (nfile > 1)
error->one("Another input script is already being processed");
if (infile != stdin) fclose(infile);
infile = fopen(filename,"r");
if (infile == NULL) {
char str[128];
sprintf(str,"Cannot open input script %s",filename);
error->one(str);
}
infiles[0] = infile;
} else infile = NULL;
file();
}
/* ----------------------------------------------------------------------
parse the command in single and execute it
return command name to caller
------------------------------------------------------------------------- */
char *Input::one(const char *single)
{
strcpy(line,single);
// echo the command unless scanning for label
if (me == 0 && label_active == 0) {
if (echo_screen && screen) fprintf(screen,"%s",line);
if (echo_log && logfile) fprintf(logfile,"%s",line);
}
// parse the line
// if no command, just return NULL
parse();
if (command == NULL) return NULL;
// if scanning for label, skip command unless it's a label command
if (label_active && strcmp(command,"label") != 0) return NULL;
// execute the command and return its name
if (execute_command()) {
char str[MAXLINE];
sprintf(str,"Unknown command: %s",line);
error->all(str);
}
return command;
}
/* ----------------------------------------------------------------------
parse copy of command line
strip comment = all chars from # on
replace all $ via variable substitution
command = first word
narg = # of args
arg[] = individual args
treat text between double quotes as one arg
------------------------------------------------------------------------- */
void Input::parse()
{
// make a copy to work on
strcpy(copy,line);
// strip any # comment by resetting string terminator
// do not strip # inside double quotes
int level = 0;
char *ptr = copy;
while (*ptr) {
if (*ptr == '#' && level == 0) {
*ptr = '\0';
break;
}
if (*ptr == '"') {
if (level == 0) level = 1;
else level = 0;
}
ptr++;
}
// perform $ variable substitution (print changes)
// except if searching for a label since earlier variable may not be defined
if (!label_active) substitute(copy,1);
// command = 1st arg
command = strtok(copy," \t\n\r\f");
if (command == NULL) return;
// point arg[] at each subsequent arg
// treat text between double quotes as one arg
// insert string terminators in copy to delimit args
narg = 0;
while (1) {
if (narg == maxarg) {
maxarg += DELTA;
arg = (char **) memory->srealloc(arg,maxarg*sizeof(char *),"input:arg");
}
arg[narg] = strtok(NULL," \t\n\r\f");
if (arg[narg] && arg[narg][0] == '\"') {
arg[narg] = &arg[narg][1];
if (arg[narg][strlen(arg[narg])-1] == '\"')
arg[narg][strlen(arg[narg])-1] = '\0';
else {
arg[narg][strlen(arg[narg])] = ' ';
ptr = strtok(arg[narg],"\"");
if (ptr == NULL) error->all("Unbalanced quotes in input line");
}
}
if (arg[narg]) narg++;
else break;
}
}
/* ----------------------------------------------------------------------
substitute for $ variables in str
print updated string if flag is set and not searching for label
------------------------------------------------------------------------- */
void Input::substitute(char *str, int flag)
{
// use work[] as scratch space to expand str
// do not replace $ inside double quotes as flagged by level
// var = pts at variable name, ended by NULL
// if $ is followed by '{', trailing '}' becomes NULL
// else $x becomes x followed by NULL
// beyond = pts at text following variable
char *var,*value,*beyond;
int level = 0;
char *ptr = str;
while (*ptr) {
if (*ptr == '$' && level == 0) {
if (*(ptr+1) == '{') {
var = ptr+2;
int i = 0;
while (var[i] != '\0' && var[i] != '}') i++;
if (var[i] == '\0') error->one("Invalid variable name");
var[i] = '\0';
beyond = ptr + strlen(var) + 3;
} else {
var = ptr;
var[0] = var[1];
var[1] = '\0';
beyond = ptr + strlen(var) + 1;
}
value = variable->retrieve(var);
if (value == NULL) error->one("Substitution for illegal variable");
*ptr = '\0';
strcpy(work,str);
if (strlen(work)+strlen(value) >= MAXLINE)
error->one("Input line too long after variable substitution");
strcat(work,value);
if (strlen(work)+strlen(beyond) >= MAXLINE)
error->one("Input line too long after variable substitution");
strcat(work,beyond);
strcpy(str,work);
ptr += strlen(value);
if (flag && me == 0 && label_active == 0) {
if (echo_screen && screen) fprintf(screen,"%s",str);
if (echo_log && logfile) fprintf(logfile,"%s",str);
}
continue;
}
if (*ptr == '"') {
if (level == 0) level = 1;
else level = 0;
}
ptr++;
}
}
/* ----------------------------------------------------------------------
process a single parsed command
return 0 if successful, -1 if did not recognize command
------------------------------------------------------------------------- */
int Input::execute_command()
{
int flag = 1;
if (!strcmp(command,"clear")) clear();
else if (!strcmp(command,"echo")) echo();
else if (!strcmp(command,"if")) ifthenelse();
else if (!strcmp(command,"include")) include();
else if (!strcmp(command,"jump")) jump();
else if (!strcmp(command,"label")) label();
else if (!strcmp(command,"log")) log();
else if (!strcmp(command,"next")) next_command();
else if (!strcmp(command,"print")) print();
else if (!strcmp(command,"variable")) variable_command();
else if (!strcmp(command,"angle_coeff")) angle_coeff();
else if (!strcmp(command,"angle_style")) angle_style();
else if (!strcmp(command,"atom_modify")) atom_modify();
else if (!strcmp(command,"atom_style")) atom_style();
else if (!strcmp(command,"bond_coeff")) bond_coeff();
else if (!strcmp(command,"bond_style")) bond_style();
else if (!strcmp(command,"boundary")) boundary();
else if (!strcmp(command,"communicate")) communicate();
else if (!strcmp(command,"compute")) compute();
else if (!strcmp(command,"compute_modify")) compute_modify();
else if (!strcmp(command,"dielectric")) dielectric();
else if (!strcmp(command,"dihedral_coeff")) dihedral_coeff();
else if (!strcmp(command,"dihedral_style")) dihedral_style();
else if (!strcmp(command,"dimension")) dimension();
else if (!strcmp(command,"dipole")) dipole();
else if (!strcmp(command,"dump")) dump();
else if (!strcmp(command,"dump_modify")) dump_modify();
else if (!strcmp(command,"fix")) fix();
else if (!strcmp(command,"fix_modify")) fix_modify();
else if (!strcmp(command,"group")) group_command();
else if (!strcmp(command,"improper_coeff")) improper_coeff();
else if (!strcmp(command,"improper_style")) improper_style();
else if (!strcmp(command,"kspace_modify")) kspace_modify();
else if (!strcmp(command,"kspace_style")) kspace_style();
else if (!strcmp(command,"lattice")) lattice();
else if (!strcmp(command,"mass")) mass();
else if (!strcmp(command,"min_modify")) min_modify();
else if (!strcmp(command,"min_style")) min_style();
else if (!strcmp(command,"neigh_modify")) neigh_modify();
else if (!strcmp(command,"neighbor")) neighbor_command();
else if (!strcmp(command,"newton")) newton();
else if (!strcmp(command,"pair_coeff")) pair_coeff();
else if (!strcmp(command,"pair_modify")) pair_modify();
else if (!strcmp(command,"pair_style")) pair_style();
else if (!strcmp(command,"pair_write")) pair_write();
else if (!strcmp(command,"processors")) processors();
else if (!strcmp(command,"region")) region();
else if (!strcmp(command,"reset_timestep")) reset_timestep();
else if (!strcmp(command,"restart")) restart();
else if (!strcmp(command,"run_style")) run_style();
else if (!strcmp(command,"shape")) shape();
else if (!strcmp(command,"special_bonds")) special_bonds();
else if (!strcmp(command,"thermo")) thermo();
else if (!strcmp(command,"thermo_modify")) thermo_modify();
else if (!strcmp(command,"thermo_style")) thermo_style();
else if (!strcmp(command,"timestep")) timestep();
else if (!strcmp(command,"uncompute")) uncompute();
else if (!strcmp(command,"undump")) undump();
else if (!strcmp(command,"unfix")) unfix();
else if (!strcmp(command,"units")) units();
else flag = 0;
// return if command was listed above
if (flag) return 0;
// check if command is added via style.h
if (0) return 0; // dummy line to enable else-if macro expansion
#define CommandClass
#define CommandStyle(key,Class) \
else if (strcmp(command,#key) == 0) { \
Class key(lmp); \
key.command(narg,arg); \
return 0; \
}
#include "style.h"
#undef CommandClass
// unrecognized command
return -1;
}
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- */
void Input::clear()
{
if (narg > 0) error->all("Illegal clear command");
lmp->destroy();
lmp->create();
}
/* ---------------------------------------------------------------------- */
void Input::echo()
{
if (narg != 1) error->all("Illegal echo command");
if (strcmp(arg[0],"none") == 0) {
echo_screen = 0;
echo_log = 0;
} else if (strcmp(arg[0],"screen") == 0) {
echo_screen = 1;
echo_log = 0;
} else if (strcmp(arg[0],"log") == 0) {
echo_screen = 0;
echo_log = 1;
} else if (strcmp(arg[0],"both") == 0) {
echo_screen = 1;
echo_log = 1;
} else error->all("Illegal echo command");
}
/* ---------------------------------------------------------------------- */
void Input::ifthenelse()
{
if (narg != 5 && narg != 7) error->all("Illegal if command");
int flag = 0;
if (strcmp(arg[1],"==") == 0) {
if (atof(arg[0]) == atof(arg[2])) flag = 1;
} else if (strcmp(arg[1],"!=") == 0) {
if (atof(arg[0]) != atof(arg[2])) flag = 1;
} else if (strcmp(arg[1],"<") == 0) {
if (atof(arg[0]) < atof(arg[2])) flag = 1;
} else if (strcmp(arg[1],"<=") == 0) {
if (atof(arg[0]) <= atof(arg[2])) flag = 1;
} else if (strcmp(arg[1],">") == 0) {
if (atof(arg[0]) > atof(arg[2])) flag = 1;
} else if (strcmp(arg[1],">=") == 0) {
if (atof(arg[0]) >= atof(arg[2])) flag = 1;
} else error->all("Illegal if command");
if (strcmp(arg[3],"then") != 0) error->all("Illegal if command");
if (narg == 7 && strcmp(arg[5],"else") != 0)
error->all("Illegal if command");
char str[128] = "\0";
if (flag) strcpy(str,arg[4]);
else if (narg == 7) strcpy(str,arg[6]);
strcat(str,"\n");
if (strlen(str) > 1) char *tmp = one(str);
}
/* ---------------------------------------------------------------------- */
void Input::include()
{
if (narg != 1) error->all("Illegal include command");
if (me == 0) {
if (nfile == maxfile) {
maxfile++;
infiles = (FILE **)
memory->srealloc(infiles,maxfile*sizeof(FILE *),"input:infiles");
}
infile = fopen(arg[0],"r");
if (infile == NULL) {
char str[128];
sprintf(str,"Cannot open input script %s",arg[0]);
error->one(str);
}
infiles[nfile++] = infile;
}
}
/* ---------------------------------------------------------------------- */
void Input::jump()
{
if (narg < 1 || narg > 2) error->all("Illegal jump command");
if (jump_skip) {
jump_skip = 0;
return;
}
if (me == 0) {
if (infile != stdin) fclose(infile);
infile = fopen(arg[0],"r");
if (infile == NULL) {
char str[128];
sprintf(str,"Cannot open input script %s",arg[0]);
error->one(str);
}
infiles[nfile-1] = infile;
}
if (narg == 2) {
label_active = 1;
if (labelstr) delete [] labelstr;
int n = strlen(arg[1]) + 1;
labelstr = new char[n];
strcpy(labelstr,arg[1]);
}
}
/* ---------------------------------------------------------------------- */
void Input::label()
{
if (narg != 1) error->all("Illegal label command");
if (label_active && strcmp(labelstr,arg[0]) == 0) label_active = 0;
}
/* ---------------------------------------------------------------------- */
void Input::log()
{
if (narg != 1) error->all("Illegal log command");
if (me == 0) {
if (logfile) fclose(logfile);
if (strcmp(arg[0],"none") == 0) logfile = NULL;
else {
logfile = fopen(arg[0],"w");
if (logfile == NULL) {
char str[128];
sprintf(str,"Cannot open logfile %s",arg[0]);
error->one(str);
}
}
if (universe->nworlds == 1) universe->ulogfile = logfile;
}
}
/* ---------------------------------------------------------------------- */
void Input::next_command()
{
if (variable->next(narg,arg)) jump_skip = 1;
}
/* ---------------------------------------------------------------------- */
void Input::print()
{
if (narg != 1) error->all("Illegal print command");
// substitute for $ variables (no printing)
substitute(arg[0],0);
if (me == 0) {
if (screen) fprintf(screen,"%s\n",arg[0]);
if (logfile) fprintf(logfile,"%s\n",arg[0]);
}
}
/* ---------------------------------------------------------------------- */
void Input::variable_command()
{
variable->set(narg,arg);
}
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
one function for each LAMMPS-specific input script command
------------------------------------------------------------------------- */
void Input::angle_coeff()
{
if (domain->box_exist == 0)
error->all("Angle_coeff command before simulation box is defined");
if (force->angle == NULL)
error->all("Angle_coeff command before angle_style is defined");
if (atom->avec->angles_allow == 0)
error->all("Angle_coeff command when no angles allowed");
force->angle->coeff(0,narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::angle_style()
{
if (narg < 1) error->all("Illegal angle_style command");
if (atom->avec->angles_allow == 0)
error->all("Angle_style command when no angles allowed");
force->create_angle(arg[0]);
if (force->angle) force->angle->settings(narg-1,&arg[1]);
}
/* ---------------------------------------------------------------------- */
void Input::atom_modify()
{
if (domain->box_exist)
error->all("Atom_modify command after simulation box is defined");
atom->modify_params(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::atom_style()
{
if (narg < 1) error->all("Illegal atom_style command");
if (domain->box_exist)
error->all("Atom_style command after simulation box is defined");
atom->create_avec(arg[0],narg-1,&arg[1]);
}
/* ---------------------------------------------------------------------- */
void Input::bond_coeff()
{
if (domain->box_exist == 0)
error->all("Bond_coeff command before simulation box is defined");
if (force->bond == NULL)
error->all("Bond_coeff command before bond_style is defined");
if (atom->avec->bonds_allow == 0)
error->all("Bond_coeff command when no bonds allowed");
force->bond->coeff(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::bond_style()
{
if (narg < 1) error->all("Illegal bond_style command");
if (atom->avec->bonds_allow == 0)
error->all("Bond_style command when no bonds allowed");
force->create_bond(arg[0]);
if (force->bond) force->bond->settings(narg-1,&arg[1]);
}
/* ---------------------------------------------------------------------- */
void Input::boundary()
{
if (domain->box_exist)
error->all("Boundary command after simulation box is defined");
domain->set_boundary(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::communicate()
{
comm->set(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::compute()
{
modify->add_compute(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::compute_modify()
{
modify->modify_compute(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::dielectric()
{
if (narg != 1) error->all("Illegal dielectric command");
force->dielectric = atof(arg[0]);
}
/* ---------------------------------------------------------------------- */
void Input::dihedral_coeff()
{
if (domain->box_exist == 0)
error->all("Dihedral_coeff command before simulation box is defined");
if (force->dihedral == NULL)
error->all("Dihedral_coeff command before dihedral_style is defined");
if (atom->avec->dihedrals_allow == 0)
error->all("Dihedral_coeff command when no dihedrals allowed");
force->dihedral->coeff(0,narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::dihedral_style()
{
if (narg < 1) error->all("Illegal dihedral_style command");
if (atom->avec->dihedrals_allow == 0)
error->all("Dihedral_style command when no dihedrals allowed");
force->create_dihedral(arg[0]);
if (force->dihedral) force->dihedral->settings(narg-1,&arg[1]);
}
/* ---------------------------------------------------------------------- */
void Input::dimension()
{
if (narg != 1) error->all("Illegal dimension command");
if (domain->box_exist)
error->all("Dimension command after simulation box is defined");
domain->dimension = atoi(arg[0]);
if (domain->dimension != 2 && domain->dimension != 3)
error->all("Illegal dimension command");
// must reset default extra_dof of all computes
// since some were created before dimension command is encountered
for (int i = 0; i < modify->ncompute; i++)
modify->compute[i]->reset_extra_dof();
}
/* ---------------------------------------------------------------------- */
void Input::dipole()
{
if (narg != 2) error->all("Illegal dipole command");
if (domain->box_exist == 0)
error->all("Dipole command before simulation box is defined");
atom->set_dipole(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::dump()
{
output->add_dump(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::dump_modify()
{
output->modify_dump(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::fix()
{
modify->add_fix(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::fix_modify()
{
modify->modify_fix(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::group_command()
{
group->assign(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::improper_coeff()
{
if (domain->box_exist == 0)
error->all("Improper_coeff command before simulation box is defined");
if (force->improper == NULL)
error->all("Improper_coeff command before improper_style is defined");
if (atom->avec->impropers_allow == 0)
error->all("Improper_coeff command when no impropers allowed");
force->improper->coeff(0,narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::improper_style()
{
if (narg < 1) error->all("Illegal improper_style command");
if (atom->avec->impropers_allow == 0)
error->all("Improper_style command when no impropers allowed");
force->create_improper(arg[0]);
if (force->improper) force->improper->settings(narg-1,&arg[1]);
}
/* ---------------------------------------------------------------------- */
void Input::kspace_modify()
{
if (force->kspace == NULL) error->all("KSpace style has not yet been set");
force->kspace->modify_params(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::kspace_style()
{
force->create_kspace(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::lattice()
{
domain->set_lattice(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::mass()
{
if (narg != 2) error->all("Illegal mass command");
if (domain->box_exist == 0)
error->all("Mass command before simulation box is defined");
atom->set_mass(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::min_modify()
{
update->minimize->modify_params(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::min_style()
{
if (domain->box_exist == 0)
error->all("Min_style command before simulation box is defined");
update->create_minimize(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::neigh_modify()
{
neighbor->modify_params(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::neighbor_command()
{
neighbor->set(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::newton()
{
int newton_pair,newton_bond;
if (narg == 1) {
if (strcmp(arg[0],"off") == 0) newton_pair = newton_bond = 0;
else if (strcmp(arg[0],"on") == 0) newton_pair = newton_bond = 1;
else error->all("Illegal newton command");
} else if (narg == 2) {
if (strcmp(arg[0],"off") == 0) newton_pair = 0;
else if (strcmp(arg[0],"on") == 0) newton_pair= 1;
else error->all("Illegal newton command");
if (strcmp(arg[1],"off") == 0) newton_bond = 0;
else if (strcmp(arg[1],"on") == 0) newton_bond = 1;
else error->all("Illegal newton command");
} else error->all("Illegal newton command");
force->newton_pair = newton_pair;
if (newton_bond == 0) {
if (domain->box_exist && force->newton_bond == 1)
error->all("Newton bond change after simulation box is defined");
force->newton_bond = 0;
} else {
if (domain->box_exist && force->newton_bond == 0)
error->all("Newton bond change after simulation box is defined");
force->newton_bond = 1;
}
if (newton_pair || newton_bond) force->newton = 1;
else force->newton = 0;
}
/* ---------------------------------------------------------------------- */
void Input::pair_coeff()
{
if (domain->box_exist == 0)
error->all("Pair_coeff command before simulation box is defined");
if (force->pair == NULL)
error->all("Pair_coeff command before pair_style is defined");
force->pair->coeff(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::pair_modify()
{
if (force->pair == NULL)
error->all("Pair_modify command before pair_style is defined");
force->pair->modify_params(narg,arg);
}
/* ----------------------------------------------------------------------
if old pair style exists and new style is same, just change settings
else create new pair class
------------------------------------------------------------------------- */
void Input::pair_style()
{
if (narg < 1) error->all("Illegal pair_style command");
if (force->pair && strcmp(arg[0],force->pair_style) == 0) {
force->pair->settings(narg-1,&arg[1]);
return;
}
force->create_pair(arg[0]);
if (force->pair) force->pair->settings(narg-1,&arg[1]);
}
/* ---------------------------------------------------------------------- */
void Input::pair_write()
{
if (force->pair == NULL)
error->all("Pair_write command before pair_style is defined");
force->pair->write_file(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::processors()
{
if (narg != 3) error->all("Illegal processors command");
if (domain->box_exist)
error->all("Processors command after simulation box is defined");
comm->user_procgrid[0] = atoi(arg[0]);
comm->user_procgrid[1] = atoi(arg[1]);
comm->user_procgrid[2] = atoi(arg[2]);
}
/* ---------------------------------------------------------------------- */
void Input::region()
{
domain->add_region(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::reset_timestep()
{
update->reset_timestep(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::restart()
{
output->create_restart(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::run_style()
{
if (domain->box_exist == 0)
error->all("Run_style command before simulation box is defined");
update->create_integrate(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::shape()
{
if (narg != 4) error->all("Illegal shape command");
if (domain->box_exist == 0)
error->all("Shape command before simulation box is defined");
atom->set_shape(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::special_bonds()
{
// store 1-3,1-4 and dihedral/extra flag values before change
// change in 1-2 coeffs will not change the special list
double lj2 = force->special_lj[2];
double lj3 = force->special_lj[3];
double coul2 = force->special_coul[2];
double coul3 = force->special_coul[3];
int dihedral = force->special_dihedral;
int extra = force->special_extra;
force->set_special(narg,arg);
// if simulation box defined and saved values changed, redo special list
if (domain->box_exist && atom->molecular) {
if (lj2 != force->special_lj[2] || lj3 != force->special_lj[3] ||
coul2 != force->special_coul[2] || coul3 != force->special_coul[3] ||
dihedral != force->special_dihedral || extra != force->special_extra) {
Special special(lmp);
special.build();
}
}
}
/* ---------------------------------------------------------------------- */
void Input::thermo()
{
if (narg != 1) error->all("Illegal thermo command");
output->thermo_every = atoi(arg[0]);
}
/* ---------------------------------------------------------------------- */
void Input::thermo_modify()
{
output->thermo->modify_params(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::thermo_style()
{
output->create_thermo(narg,arg);
}
/* ---------------------------------------------------------------------- */
void Input::timestep()
{
if (narg != 1) error->all("Illegal timestep command");
update->dt = atof(arg[0]);
}
/* ---------------------------------------------------------------------- */
void Input::uncompute()
{
if (narg != 1) error->all("Illegal uncompute command");
modify->delete_compute(arg[0]);
}
/* ---------------------------------------------------------------------- */
void Input::undump()
{
if (narg != 1) error->all("Illegal undump command");
output->delete_dump(arg[0]);
}
/* ---------------------------------------------------------------------- */
void Input::unfix()
{
if (narg != 1) error->all("Illegal unfix command");
modify->delete_fix(arg[0]);
}
/* ---------------------------------------------------------------------- */
void Input::units()
{
if (narg != 1) error->all("Illegal units command");
if (domain->box_exist)
error->all("Units command after simulation box is defined");
update->set_units(arg[0]);
}
| [
"sepehr.saroukhani@gmail.com"
] | sepehr.saroukhani@gmail.com |
5d9090bd7552c8fa2ccfee39ffdc7b4d1988aee9 | 862e93a96880ea46cd1fc1615ca91962f511e4d7 | /BANK.CPP | 2632b162b017c92490c8e0a900fe0deafa6e7807 | [] | no_license | jayantbansal21/HackFormPast | 8f9a0fe5f5cbf0b389accdfbea8a8a61dd8af259 | b261fd5cd2e6841a0008bf523a712f13b86b1318 | refs/heads/main | 2023-03-29T00:29:50.246435 | 2021-04-10T15:09:41 | 2021-04-10T15:09:41 | 356,615,951 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,125 | cpp | #include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
class Acc
{
double accno;
int pass;
char name[15],bcode[10],conno[10];
int amount;
public:
void IN()
{
double accno;
char name[15],bcode[10],conno[10];
int amount;
int pass;
cout<<"Enter name of account holder\n";
gets(name);
strcpy(this->name,name);
cout<<"Enter contact number of the person\n";
gets(conno);
strcpy(this->conno,conno);
cout<<"Enter account number\n";
cin>>accno;
this->accno = accno;
cout<<"Enter Branch code\n";
gets(bcode);
strcpy(this->bcode,bcode);
cout<<"Enter amount you want to credit to your account\n";
cin>>amount;
this->amount=amount;
cout<<"Enter passowrd for your account\n";
cin>>pass;
this->pass=pass;
cout<<"Please note the account number & password\n";
}
void OUT()
{
cout<<"Account number\n";
cout<<accno;
cout<<"Branch code\n";
puts(bcode);
cout<<"Name of account holder\n";
puts(name);
cout<<"Contact number of the person\n";
cout<<conno;
cout<<"Amount in your account\n";
cout<<amount;
}
void Password(double &k,int &j)
{
clrscr();
int choi,pass,amount;
if(this->accno==k&&this->pass==j)
{
cout<<"Entered password is right \n";
cout<<"What you want to do with your account?\n";
cout<<"1. Want to change password?\n";
cout<<"2. Want to withdwran some money?\n";
cout<<"3. Want to in more money in your account?\n";
cout<<"4. Want to see all enteries?\n";
cin>>choi;
switch(choi)
{
case 1: cout<<"Your current password is\n ";
cout<<this->pass<<endl;
cout<<"Enter new password\n";
cin>>pass;
this->pass=pass;
break;
case 2: cout<<"Your current balance is\n";
cout<<this->amount;
cout<<"How much money you want to withdraw \n";
cin>>amount;
if(amount<this->amount&&amount>0)
{
cout<<"\nTransfer complete\n";
cout<<"Remaining amount in your account is\n ";
choi=this->amount-amount;
cout<<choi;
}
else
{
cout<<"not possible";
getch();
exit(0);
}
break;
case 3: cout<<"Your current balance is\n";
cout<<this->amount;
cout<<"\nHow much money you want to put \n";
cin>>amount;
cout<<"tranfer complete\n";
cout<<"New balance is\n";
choi=this->amount+amount;
cout<<choi;
break;
case 4 :this ->OUT();
break;
default : cout<<"You entered wrong choice";
exit(0);
}
}
else
{
exit (0);
}
}
};
void main()
{
clrscr();
Acc s;
int pass;
double accn;
cout<<"\nWelcome to bank \n";
cout<<"To create new account enter following details\n";
s.IN();
clrscr();
cout<<"To access account\n";
cout<<"Enter account number\n";
cin>>accn;
cout<<"Enter password\n";
cin>>pass;
s.Password(accn,pass);
getch();
}
| [
"noreply@github.com"
] | noreply@github.com |
17ae909db6fb91fcf726a15eb153515bccf6c8e6 | cb2f8ae54011f8179433ae80943f60460a617b4a | /graph/edmond_matching.cpp | a65cfa095527eb0b63a8f9907883cf11e964d111 | [] | no_license | yysung1123/NCTU_Kitsune | 15fa41250d1bd75307774c13332c75f2851570f4 | 8e719950253a90794902b9068dfbef1f907d18fb | refs/heads/master | 2020-03-28T15:22:05.778805 | 2018-09-13T05:18:54 | 2018-09-13T05:18:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,404 | cpp | //Problem:http://acm.timus.ru/problem.aspx?space=1&num=1099
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N=250;
int n;
int head;
int tail;
int Start;
int Finish;
int link[N]; //表示哪个点匹配了哪个点
int Father[N]; //这个就是增广路的Father……但是用起来太精髓了
int Base[N]; //该点属于哪朵花
int Q[N];
bool mark[N];
bool map[N][N];
bool InBlossom[N];
bool in_Queue[N];
void CreateGraph(){
int x,y;
scanf("%d",&n);
while (scanf("%d%d",&x,&y)!=EOF)
map[x][y]=map[y][x]=1;
}
void BlossomContract(int x,int y){
fill(mark,mark+n+1,false);
fill(InBlossom,InBlossom+n+1,false);
#define pre Father[link[i]]
int lca,i;
for (i=x;i;i=pre) {i=Base[i]; mark[i]=true; }
for (i=y;i;i=pre) {i=Base[i]; if (mark[i]) {lca=i; break;} } //寻找lca之旅……一定要注意i=Base[i]
for (i=x;Base[i]!=lca;i=pre){
if (Base[pre]!=lca) Father[pre]=link[i]; //对于BFS树中的父边是匹配边的点,Father向后跳
InBlossom[Base[i]]=true;
InBlossom[Base[link[i]]]=true;
}
for (i=y;Base[i]!=lca;i=pre){
if (Base[pre]!=lca) Father[pre]=link[i]; //同理
InBlossom[Base[i]]=true;
InBlossom[Base[link[i]]]=true;
}
#undef pre
if (Base[x]!=lca) Father[x]=y; //注意不能从lca这个奇环的关键点跳回来
if (Base[y]!=lca) Father[y]=x;
for (i=1;i<=n;i++)
if (InBlossom[Base[i]]){
Base[i]=lca;
if (!in_Queue[i]){
Q[++tail]=i;
in_Queue[i]=true; //要注意如果本来连向BFS树中父结点的边是非匹配边的点,可能是没有入队的
}
}
}
void Change(){
int x,y,z;
z=Finish;
while (z){
y=Father[z];
x=link[y];
link[y]=z;
link[z]=y;
z=x;
}
}
void FindAugmentPath(){
fill(Father,Father+n+1,0);
fill(in_Queue,in_Queue+n+1,false);
for (int i=1;i<=n;i++) Base[i]=i;
head=0; tail=1;
Q[1]=Start;
in_Queue[Start]=1;
while (head!=tail){
int x=Q[++head];
for (int y=1;y<=n;y++)
if (map[x][y] && Base[x]!=Base[y] && link[x]!=y) //无意义的边
if ( Start==y || link[y] && Father[link[y]] ) //精髓地用Father表示该点是否
BlossomContract(x,y);
else if (!Father[y]){
Father[y]=x;
if (link[y]){
Q[++tail]=link[y];
in_Queue[link[y]]=true;
}
else{
Finish=y;
Change();
return;
}
}
}
}
void Edmonds(){
memset(link,0,sizeof(link));
for (Start=1;Start<=n;Start++)
if (link[Start]==0)
FindAugmentPath();
}
void output(){
fill(mark,mark+n+1,false);
int cnt=0;
for (int i=1;i<=n;i++)
if (link[i]) cnt++;
printf("%d\n",cnt);
for (int i=1;i<=n;i++)
if (!mark[i] && link[i]){
mark[i]=true;
mark[link[i]]=true;
printf("%d %d\n",i,link[i]);
}
}
int main(){
// freopen("input.txt","r",stdin);
CreateGraph();
Edmonds();
output();
return 0;
}
| [
"sungyuanyao@gmail.com"
] | sungyuanyao@gmail.com |
b841ad92e53bb37a68b605e6b5c7519dd13f5655 | 4e80701d5bce0bb33d5a563598bb8ccce0aad864 | /Beginner/Nível 2/URI 1078.cpp | c9f2751481ee84a786fdb30ba394a9bf50e43024 | [] | no_license | thiagohfo/URIOnlineJudge | 49ce3a3ddc14ada0110b4183164cc16bc5b1e506 | 983beb282050e6e1a8c421acb39dbd6976d1f997 | refs/heads/main | 2022-12-08T06:03:38.677018 | 2022-11-28T14:36:29 | 2022-11-28T14:36:29 | 174,578,594 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 381 | cpp | //
// URI 1078.cpp
// Pratica
//
// Created by Thiago Henrique on 13/10/17.
// Copyright © 2017 Thiago Henrique. All rights reserved.
//
#include <stdio.h>
#include <iostream>
using namespace std;
int main(){
int N;
cin >> N;
for(int i = 0; i < 10; i++){
cout << i + 1 << " x " << N << " = " << (i + 1) * N << endl;
}
return 0;
}
| [
"thiagohfo@gmail.com"
] | thiagohfo@gmail.com |
8751ba8c52da84001a7fdad58e85ddbfcf57fc3a | ca7071c6ae11e706225a6edcb21d49d5fa75668f | /point.cpp | 268683ddffad9780f22f42c8e6794dc313704ae0 | [] | no_license | jdlask12345/greedy_snake | 4251e4cb3c60194f3a8daf9b6f1f1d1377fe0177 | 3963deb0fbbad6ed3ec51c3296239dfb7aeb8349 | refs/heads/master | 2022-12-13T12:55:55.406617 | 2020-09-14T03:51:15 | 2020-09-14T03:55:38 | 295,297,428 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 427 | cpp | #include "point.h"
#include "tool.h"
#include <iostream>
void Point::Print()
{
SetCursorPosition(x, y);
std::cout << "■";
}
void Point::PrintCircular()//输出圆形
{
SetCursorPosition(x, y);
std::cout << "●";
}
void Point::Clear()//清除输出
{
SetCursorPosition(x, y);
std::cout << " ";
}
void Point::ChangePosition(const int &x, const int &y)//改变坐标
{
this->x = x;
this->y = y;
} | [
"794382452@qq.com"
] | 794382452@qq.com |
557aa59affc8f8985fb1d8876088ec50ccb7a020 | a40fbc646a5cdd4b19f843d3ce8968767c4b13bd | /test.cpp | c7fe93b73ff773e08d7b4e45885f26e3522881b2 | [] | no_license | zhaoyou/spoj | b247f853525f3f02ee500418004ce2e80ceb05cd | fee9eddc99547201f7077a437cfbd02f7e6732b2 | refs/heads/master | 2021-01-10T21:10:20.026331 | 2014-06-10T16:32:54 | 2014-06-10T16:32:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 190 | cpp | #include <iostream>
#include <string>
using namespace std;
int main() {
string word;
while(cin >> word) {
if (word == "42") {
return 0;
}
cout << word << endl;
}
}
| [
"zhaoyou.xt@gmail.com"
] | zhaoyou.xt@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.