blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7be8f4f0e3645fff521f10afa19b873b104eadc8 | 37f172115175d2ba7b6dba30a85b3d737273c5a3 | /include/caffe/layers/canny_layer.hpp | 06521806e1631758bac9d7ed94b47a7be260f0fb | [
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla"
] | permissive | daijialun/caffe_mvco | 7c6ff8ab57239f40c6e49701f62b708944dcab68 | 6676efabc4a2819efd4dba18fe3c65a89d30553c | refs/heads/master | 2021-01-21T14:11:28.580875 | 2016-07-30T16:45:21 | 2016-07-30T16:45:21 | 58,255,560 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,789 | hpp | #ifndef CAFFE_CANNY_LAYER_HPP_
#define CAFFE_CANNY_LAYER_HPP_
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "caffe/blob.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
/**
* @brief Preprocess the images in network
*/
template <typename Dtype>
class CannyLayer : public Layer<Dtype> {
public:
explicit CannyLayer (const LayerParameter& param)
: Layer<Dtype>(param) {} ;
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
// LayerSetUp: implements common data layer setup functionality, and
// calls DataLayerSetUp to do special data layer setup for layer types.
virtual inline const char* type() const { return "Canny"; }
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline int ExactNumTopBlobs() const { return 1; }
//virtual inline int MinBottomBlobs() const { return 1; }
//virtual inline int MaxTopBlobs() const { return 1; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) ;
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) ;
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {};
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {};
};
} // namespace caffe
#endif | [
"zynzl120@163.com"
] | zynzl120@163.com |
5b84aa1efe6260113f4816fa33352e9bd8bcf42e | 5390eac0ac54d2c3c1c664ae525881fa988e2cf9 | /lib/basic_pointer_oserializer.cpp | 6be7a49f79e669f5ad7256774ab9dd70bb91c26e | [
"BSL-1.0"
] | permissive | pothosware/pothos-serialization | 2935b8ab1fe51299a6beba2a3e11611928186849 | c59130f916a3e5b833a32ba415063f9cb306a8dd | refs/heads/master | 2021-08-16T15:22:12.642058 | 2015-12-10T03:32:04 | 2015-12-10T03:32:04 | 19,961,886 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 949 | cpp | /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// basic_pointer_oserializer.cpp:
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// 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 for updates, documentation, and revision history.
#define POTHOS_ARCHIVE_SOURCE
#include <Pothos/archive/detail/basic_pointer_oserializer.hpp>
namespace Pothos {
namespace archive {
namespace detail {
POTHOS_ARCHIVE_DECL(POTHOS_PP_EMPTY())
basic_pointer_oserializer::basic_pointer_oserializer(
const Pothos::serialization::extended_type_info & eti
) :
basic_serializer(eti)
{}
POTHOS_ARCHIVE_DECL(POTHOS_PP_EMPTY())
basic_pointer_oserializer::~basic_pointer_oserializer() {}
} // namespace detail
} // namespace archive
} // namespace boost
| [
"josh@joshknows.com"
] | josh@joshknows.com |
93b72b9dd900c23d5df545fccde94caa5ae60a67 | 6b580bb5e7bbf83e0d9845818678fbb85ea14450 | /aws-cpp-sdk-kendra/include/aws/kendra/model/ServiceNowServiceCatalogConfiguration.h | 7e450b1da02f3fee2896614b9385f21f098cf898 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | dimatd/aws-sdk-cpp | 870634473781731822e2636005bc215ad43a0339 | 3d3f3d0f98af842e06d3d74648a0fca383538bb3 | refs/heads/master | 2022-12-21T20:54:25.033076 | 2022-12-13T18:18:00 | 2022-12-13T18:18:00 | 219,980,346 | 0 | 0 | Apache-2.0 | 2019-11-06T11:23:20 | 2019-11-06T11:23:20 | null | UTF-8 | C++ | false | false | 24,268 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/kendra/Kendra_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/kendra/model/DataSourceToIndexFieldMapping.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace kendra
{
namespace Model
{
/**
* <p>Provides the configuration information for crawling service catalog items in
* the ServiceNow site</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/kendra-2019-02-03/ServiceNowServiceCatalogConfiguration">AWS
* API Reference</a></p>
*/
class AWS_KENDRA_API ServiceNowServiceCatalogConfiguration
{
public:
ServiceNowServiceCatalogConfiguration();
ServiceNowServiceCatalogConfiguration(Aws::Utils::Json::JsonView jsonValue);
ServiceNowServiceCatalogConfiguration& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>Indicates whether Amazon Kendra should crawl attachments to the service
* catalog items. </p>
*/
inline bool GetCrawlAttachments() const{ return m_crawlAttachments; }
/**
* <p>Indicates whether Amazon Kendra should crawl attachments to the service
* catalog items. </p>
*/
inline bool CrawlAttachmentsHasBeenSet() const { return m_crawlAttachmentsHasBeenSet; }
/**
* <p>Indicates whether Amazon Kendra should crawl attachments to the service
* catalog items. </p>
*/
inline void SetCrawlAttachments(bool value) { m_crawlAttachmentsHasBeenSet = true; m_crawlAttachments = value; }
/**
* <p>Indicates whether Amazon Kendra should crawl attachments to the service
* catalog items. </p>
*/
inline ServiceNowServiceCatalogConfiguration& WithCrawlAttachments(bool value) { SetCrawlAttachments(value); return *this;}
/**
* <p>A list of regular expression patterns to include certain attachments of
* catalogs in your ServiceNow. Item that match the patterns are included in the
* index. Items that don't match the patterns are excluded from the index. If an
* item matches both an inclusion and exclusion pattern, the exclusion pattern
* takes precedence and the item isn't included in the index.</p> <p>The regex is
* applied to the file name of the attachment.</p>
*/
inline const Aws::Vector<Aws::String>& GetIncludeAttachmentFilePatterns() const{ return m_includeAttachmentFilePatterns; }
/**
* <p>A list of regular expression patterns to include certain attachments of
* catalogs in your ServiceNow. Item that match the patterns are included in the
* index. Items that don't match the patterns are excluded from the index. If an
* item matches both an inclusion and exclusion pattern, the exclusion pattern
* takes precedence and the item isn't included in the index.</p> <p>The regex is
* applied to the file name of the attachment.</p>
*/
inline bool IncludeAttachmentFilePatternsHasBeenSet() const { return m_includeAttachmentFilePatternsHasBeenSet; }
/**
* <p>A list of regular expression patterns to include certain attachments of
* catalogs in your ServiceNow. Item that match the patterns are included in the
* index. Items that don't match the patterns are excluded from the index. If an
* item matches both an inclusion and exclusion pattern, the exclusion pattern
* takes precedence and the item isn't included in the index.</p> <p>The regex is
* applied to the file name of the attachment.</p>
*/
inline void SetIncludeAttachmentFilePatterns(const Aws::Vector<Aws::String>& value) { m_includeAttachmentFilePatternsHasBeenSet = true; m_includeAttachmentFilePatterns = value; }
/**
* <p>A list of regular expression patterns to include certain attachments of
* catalogs in your ServiceNow. Item that match the patterns are included in the
* index. Items that don't match the patterns are excluded from the index. If an
* item matches both an inclusion and exclusion pattern, the exclusion pattern
* takes precedence and the item isn't included in the index.</p> <p>The regex is
* applied to the file name of the attachment.</p>
*/
inline void SetIncludeAttachmentFilePatterns(Aws::Vector<Aws::String>&& value) { m_includeAttachmentFilePatternsHasBeenSet = true; m_includeAttachmentFilePatterns = std::move(value); }
/**
* <p>A list of regular expression patterns to include certain attachments of
* catalogs in your ServiceNow. Item that match the patterns are included in the
* index. Items that don't match the patterns are excluded from the index. If an
* item matches both an inclusion and exclusion pattern, the exclusion pattern
* takes precedence and the item isn't included in the index.</p> <p>The regex is
* applied to the file name of the attachment.</p>
*/
inline ServiceNowServiceCatalogConfiguration& WithIncludeAttachmentFilePatterns(const Aws::Vector<Aws::String>& value) { SetIncludeAttachmentFilePatterns(value); return *this;}
/**
* <p>A list of regular expression patterns to include certain attachments of
* catalogs in your ServiceNow. Item that match the patterns are included in the
* index. Items that don't match the patterns are excluded from the index. If an
* item matches both an inclusion and exclusion pattern, the exclusion pattern
* takes precedence and the item isn't included in the index.</p> <p>The regex is
* applied to the file name of the attachment.</p>
*/
inline ServiceNowServiceCatalogConfiguration& WithIncludeAttachmentFilePatterns(Aws::Vector<Aws::String>&& value) { SetIncludeAttachmentFilePatterns(std::move(value)); return *this;}
/**
* <p>A list of regular expression patterns to include certain attachments of
* catalogs in your ServiceNow. Item that match the patterns are included in the
* index. Items that don't match the patterns are excluded from the index. If an
* item matches both an inclusion and exclusion pattern, the exclusion pattern
* takes precedence and the item isn't included in the index.</p> <p>The regex is
* applied to the file name of the attachment.</p>
*/
inline ServiceNowServiceCatalogConfiguration& AddIncludeAttachmentFilePatterns(const Aws::String& value) { m_includeAttachmentFilePatternsHasBeenSet = true; m_includeAttachmentFilePatterns.push_back(value); return *this; }
/**
* <p>A list of regular expression patterns to include certain attachments of
* catalogs in your ServiceNow. Item that match the patterns are included in the
* index. Items that don't match the patterns are excluded from the index. If an
* item matches both an inclusion and exclusion pattern, the exclusion pattern
* takes precedence and the item isn't included in the index.</p> <p>The regex is
* applied to the file name of the attachment.</p>
*/
inline ServiceNowServiceCatalogConfiguration& AddIncludeAttachmentFilePatterns(Aws::String&& value) { m_includeAttachmentFilePatternsHasBeenSet = true; m_includeAttachmentFilePatterns.push_back(std::move(value)); return *this; }
/**
* <p>A list of regular expression patterns to include certain attachments of
* catalogs in your ServiceNow. Item that match the patterns are included in the
* index. Items that don't match the patterns are excluded from the index. If an
* item matches both an inclusion and exclusion pattern, the exclusion pattern
* takes precedence and the item isn't included in the index.</p> <p>The regex is
* applied to the file name of the attachment.</p>
*/
inline ServiceNowServiceCatalogConfiguration& AddIncludeAttachmentFilePatterns(const char* value) { m_includeAttachmentFilePatternsHasBeenSet = true; m_includeAttachmentFilePatterns.push_back(value); return *this; }
/**
* <p>A list of regular expression patterns to exclude certain attachments of
* catalogs in your ServiceNow. Item that match the patterns are excluded from the
* index. Items that don't match the patterns are included in the index. If an item
* matches both an inclusion and exclusion pattern, the exclusion pattern takes
* precedence and the item isn't included in the index.</p> <p>The regex is applied
* to the file name of the attachment.</p>
*/
inline const Aws::Vector<Aws::String>& GetExcludeAttachmentFilePatterns() const{ return m_excludeAttachmentFilePatterns; }
/**
* <p>A list of regular expression patterns to exclude certain attachments of
* catalogs in your ServiceNow. Item that match the patterns are excluded from the
* index. Items that don't match the patterns are included in the index. If an item
* matches both an inclusion and exclusion pattern, the exclusion pattern takes
* precedence and the item isn't included in the index.</p> <p>The regex is applied
* to the file name of the attachment.</p>
*/
inline bool ExcludeAttachmentFilePatternsHasBeenSet() const { return m_excludeAttachmentFilePatternsHasBeenSet; }
/**
* <p>A list of regular expression patterns to exclude certain attachments of
* catalogs in your ServiceNow. Item that match the patterns are excluded from the
* index. Items that don't match the patterns are included in the index. If an item
* matches both an inclusion and exclusion pattern, the exclusion pattern takes
* precedence and the item isn't included in the index.</p> <p>The regex is applied
* to the file name of the attachment.</p>
*/
inline void SetExcludeAttachmentFilePatterns(const Aws::Vector<Aws::String>& value) { m_excludeAttachmentFilePatternsHasBeenSet = true; m_excludeAttachmentFilePatterns = value; }
/**
* <p>A list of regular expression patterns to exclude certain attachments of
* catalogs in your ServiceNow. Item that match the patterns are excluded from the
* index. Items that don't match the patterns are included in the index. If an item
* matches both an inclusion and exclusion pattern, the exclusion pattern takes
* precedence and the item isn't included in the index.</p> <p>The regex is applied
* to the file name of the attachment.</p>
*/
inline void SetExcludeAttachmentFilePatterns(Aws::Vector<Aws::String>&& value) { m_excludeAttachmentFilePatternsHasBeenSet = true; m_excludeAttachmentFilePatterns = std::move(value); }
/**
* <p>A list of regular expression patterns to exclude certain attachments of
* catalogs in your ServiceNow. Item that match the patterns are excluded from the
* index. Items that don't match the patterns are included in the index. If an item
* matches both an inclusion and exclusion pattern, the exclusion pattern takes
* precedence and the item isn't included in the index.</p> <p>The regex is applied
* to the file name of the attachment.</p>
*/
inline ServiceNowServiceCatalogConfiguration& WithExcludeAttachmentFilePatterns(const Aws::Vector<Aws::String>& value) { SetExcludeAttachmentFilePatterns(value); return *this;}
/**
* <p>A list of regular expression patterns to exclude certain attachments of
* catalogs in your ServiceNow. Item that match the patterns are excluded from the
* index. Items that don't match the patterns are included in the index. If an item
* matches both an inclusion and exclusion pattern, the exclusion pattern takes
* precedence and the item isn't included in the index.</p> <p>The regex is applied
* to the file name of the attachment.</p>
*/
inline ServiceNowServiceCatalogConfiguration& WithExcludeAttachmentFilePatterns(Aws::Vector<Aws::String>&& value) { SetExcludeAttachmentFilePatterns(std::move(value)); return *this;}
/**
* <p>A list of regular expression patterns to exclude certain attachments of
* catalogs in your ServiceNow. Item that match the patterns are excluded from the
* index. Items that don't match the patterns are included in the index. If an item
* matches both an inclusion and exclusion pattern, the exclusion pattern takes
* precedence and the item isn't included in the index.</p> <p>The regex is applied
* to the file name of the attachment.</p>
*/
inline ServiceNowServiceCatalogConfiguration& AddExcludeAttachmentFilePatterns(const Aws::String& value) { m_excludeAttachmentFilePatternsHasBeenSet = true; m_excludeAttachmentFilePatterns.push_back(value); return *this; }
/**
* <p>A list of regular expression patterns to exclude certain attachments of
* catalogs in your ServiceNow. Item that match the patterns are excluded from the
* index. Items that don't match the patterns are included in the index. If an item
* matches both an inclusion and exclusion pattern, the exclusion pattern takes
* precedence and the item isn't included in the index.</p> <p>The regex is applied
* to the file name of the attachment.</p>
*/
inline ServiceNowServiceCatalogConfiguration& AddExcludeAttachmentFilePatterns(Aws::String&& value) { m_excludeAttachmentFilePatternsHasBeenSet = true; m_excludeAttachmentFilePatterns.push_back(std::move(value)); return *this; }
/**
* <p>A list of regular expression patterns to exclude certain attachments of
* catalogs in your ServiceNow. Item that match the patterns are excluded from the
* index. Items that don't match the patterns are included in the index. If an item
* matches both an inclusion and exclusion pattern, the exclusion pattern takes
* precedence and the item isn't included in the index.</p> <p>The regex is applied
* to the file name of the attachment.</p>
*/
inline ServiceNowServiceCatalogConfiguration& AddExcludeAttachmentFilePatterns(const char* value) { m_excludeAttachmentFilePatternsHasBeenSet = true; m_excludeAttachmentFilePatterns.push_back(value); return *this; }
/**
* <p>The name of the ServiceNow field that is mapped to the index document
* contents field in the Amazon Kendra index.</p>
*/
inline const Aws::String& GetDocumentDataFieldName() const{ return m_documentDataFieldName; }
/**
* <p>The name of the ServiceNow field that is mapped to the index document
* contents field in the Amazon Kendra index.</p>
*/
inline bool DocumentDataFieldNameHasBeenSet() const { return m_documentDataFieldNameHasBeenSet; }
/**
* <p>The name of the ServiceNow field that is mapped to the index document
* contents field in the Amazon Kendra index.</p>
*/
inline void SetDocumentDataFieldName(const Aws::String& value) { m_documentDataFieldNameHasBeenSet = true; m_documentDataFieldName = value; }
/**
* <p>The name of the ServiceNow field that is mapped to the index document
* contents field in the Amazon Kendra index.</p>
*/
inline void SetDocumentDataFieldName(Aws::String&& value) { m_documentDataFieldNameHasBeenSet = true; m_documentDataFieldName = std::move(value); }
/**
* <p>The name of the ServiceNow field that is mapped to the index document
* contents field in the Amazon Kendra index.</p>
*/
inline void SetDocumentDataFieldName(const char* value) { m_documentDataFieldNameHasBeenSet = true; m_documentDataFieldName.assign(value); }
/**
* <p>The name of the ServiceNow field that is mapped to the index document
* contents field in the Amazon Kendra index.</p>
*/
inline ServiceNowServiceCatalogConfiguration& WithDocumentDataFieldName(const Aws::String& value) { SetDocumentDataFieldName(value); return *this;}
/**
* <p>The name of the ServiceNow field that is mapped to the index document
* contents field in the Amazon Kendra index.</p>
*/
inline ServiceNowServiceCatalogConfiguration& WithDocumentDataFieldName(Aws::String&& value) { SetDocumentDataFieldName(std::move(value)); return *this;}
/**
* <p>The name of the ServiceNow field that is mapped to the index document
* contents field in the Amazon Kendra index.</p>
*/
inline ServiceNowServiceCatalogConfiguration& WithDocumentDataFieldName(const char* value) { SetDocumentDataFieldName(value); return *this;}
/**
* <p>The name of the ServiceNow field that is mapped to the index document title
* field.</p>
*/
inline const Aws::String& GetDocumentTitleFieldName() const{ return m_documentTitleFieldName; }
/**
* <p>The name of the ServiceNow field that is mapped to the index document title
* field.</p>
*/
inline bool DocumentTitleFieldNameHasBeenSet() const { return m_documentTitleFieldNameHasBeenSet; }
/**
* <p>The name of the ServiceNow field that is mapped to the index document title
* field.</p>
*/
inline void SetDocumentTitleFieldName(const Aws::String& value) { m_documentTitleFieldNameHasBeenSet = true; m_documentTitleFieldName = value; }
/**
* <p>The name of the ServiceNow field that is mapped to the index document title
* field.</p>
*/
inline void SetDocumentTitleFieldName(Aws::String&& value) { m_documentTitleFieldNameHasBeenSet = true; m_documentTitleFieldName = std::move(value); }
/**
* <p>The name of the ServiceNow field that is mapped to the index document title
* field.</p>
*/
inline void SetDocumentTitleFieldName(const char* value) { m_documentTitleFieldNameHasBeenSet = true; m_documentTitleFieldName.assign(value); }
/**
* <p>The name of the ServiceNow field that is mapped to the index document title
* field.</p>
*/
inline ServiceNowServiceCatalogConfiguration& WithDocumentTitleFieldName(const Aws::String& value) { SetDocumentTitleFieldName(value); return *this;}
/**
* <p>The name of the ServiceNow field that is mapped to the index document title
* field.</p>
*/
inline ServiceNowServiceCatalogConfiguration& WithDocumentTitleFieldName(Aws::String&& value) { SetDocumentTitleFieldName(std::move(value)); return *this;}
/**
* <p>The name of the ServiceNow field that is mapped to the index document title
* field.</p>
*/
inline ServiceNowServiceCatalogConfiguration& WithDocumentTitleFieldName(const char* value) { SetDocumentTitleFieldName(value); return *this;}
/**
* <p>Maps attributes or field names of catalogs to Amazon Kendra index field
* names. To create custom fields, use the <code>UpdateIndex</code> API before you
* map to ServiceNow fields. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/field-mapping.html">Mapping
* data source fields</a>. The ServiceNow data source field names must exist in
* your ServiceNow custom metadata.</p>
*/
inline const Aws::Vector<DataSourceToIndexFieldMapping>& GetFieldMappings() const{ return m_fieldMappings; }
/**
* <p>Maps attributes or field names of catalogs to Amazon Kendra index field
* names. To create custom fields, use the <code>UpdateIndex</code> API before you
* map to ServiceNow fields. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/field-mapping.html">Mapping
* data source fields</a>. The ServiceNow data source field names must exist in
* your ServiceNow custom metadata.</p>
*/
inline bool FieldMappingsHasBeenSet() const { return m_fieldMappingsHasBeenSet; }
/**
* <p>Maps attributes or field names of catalogs to Amazon Kendra index field
* names. To create custom fields, use the <code>UpdateIndex</code> API before you
* map to ServiceNow fields. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/field-mapping.html">Mapping
* data source fields</a>. The ServiceNow data source field names must exist in
* your ServiceNow custom metadata.</p>
*/
inline void SetFieldMappings(const Aws::Vector<DataSourceToIndexFieldMapping>& value) { m_fieldMappingsHasBeenSet = true; m_fieldMappings = value; }
/**
* <p>Maps attributes or field names of catalogs to Amazon Kendra index field
* names. To create custom fields, use the <code>UpdateIndex</code> API before you
* map to ServiceNow fields. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/field-mapping.html">Mapping
* data source fields</a>. The ServiceNow data source field names must exist in
* your ServiceNow custom metadata.</p>
*/
inline void SetFieldMappings(Aws::Vector<DataSourceToIndexFieldMapping>&& value) { m_fieldMappingsHasBeenSet = true; m_fieldMappings = std::move(value); }
/**
* <p>Maps attributes or field names of catalogs to Amazon Kendra index field
* names. To create custom fields, use the <code>UpdateIndex</code> API before you
* map to ServiceNow fields. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/field-mapping.html">Mapping
* data source fields</a>. The ServiceNow data source field names must exist in
* your ServiceNow custom metadata.</p>
*/
inline ServiceNowServiceCatalogConfiguration& WithFieldMappings(const Aws::Vector<DataSourceToIndexFieldMapping>& value) { SetFieldMappings(value); return *this;}
/**
* <p>Maps attributes or field names of catalogs to Amazon Kendra index field
* names. To create custom fields, use the <code>UpdateIndex</code> API before you
* map to ServiceNow fields. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/field-mapping.html">Mapping
* data source fields</a>. The ServiceNow data source field names must exist in
* your ServiceNow custom metadata.</p>
*/
inline ServiceNowServiceCatalogConfiguration& WithFieldMappings(Aws::Vector<DataSourceToIndexFieldMapping>&& value) { SetFieldMappings(std::move(value)); return *this;}
/**
* <p>Maps attributes or field names of catalogs to Amazon Kendra index field
* names. To create custom fields, use the <code>UpdateIndex</code> API before you
* map to ServiceNow fields. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/field-mapping.html">Mapping
* data source fields</a>. The ServiceNow data source field names must exist in
* your ServiceNow custom metadata.</p>
*/
inline ServiceNowServiceCatalogConfiguration& AddFieldMappings(const DataSourceToIndexFieldMapping& value) { m_fieldMappingsHasBeenSet = true; m_fieldMappings.push_back(value); return *this; }
/**
* <p>Maps attributes or field names of catalogs to Amazon Kendra index field
* names. To create custom fields, use the <code>UpdateIndex</code> API before you
* map to ServiceNow fields. For more information, see <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/field-mapping.html">Mapping
* data source fields</a>. The ServiceNow data source field names must exist in
* your ServiceNow custom metadata.</p>
*/
inline ServiceNowServiceCatalogConfiguration& AddFieldMappings(DataSourceToIndexFieldMapping&& value) { m_fieldMappingsHasBeenSet = true; m_fieldMappings.push_back(std::move(value)); return *this; }
private:
bool m_crawlAttachments;
bool m_crawlAttachmentsHasBeenSet;
Aws::Vector<Aws::String> m_includeAttachmentFilePatterns;
bool m_includeAttachmentFilePatternsHasBeenSet;
Aws::Vector<Aws::String> m_excludeAttachmentFilePatterns;
bool m_excludeAttachmentFilePatternsHasBeenSet;
Aws::String m_documentDataFieldName;
bool m_documentDataFieldNameHasBeenSet;
Aws::String m_documentTitleFieldName;
bool m_documentTitleFieldNameHasBeenSet;
Aws::Vector<DataSourceToIndexFieldMapping> m_fieldMappings;
bool m_fieldMappingsHasBeenSet;
};
} // namespace Model
} // namespace kendra
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
897ae3eb8d027df067752264ea8dccdcf124558d | f0ddda4f94cdfe6f66832700819b94a8024fb1f5 | /257B/main.cpp | 645c6539b7ed8b553d3231233edd7c33f513c713 | [] | no_license | leontalukdar/Codeforces | 3d3232edf10d07b680519624c81988761bf6e27c | 2c3294b1b71682a50279e1a1bef83f633aa96e92 | refs/heads/master | 2021-01-19T10:42:58.541045 | 2017-03-07T00:45:43 | 2017-03-07T00:45:43 | 82,209,524 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,169 | cpp | #include <iostream>
#include <fstream>
#include <sstream>
#include <math.h>
#include <algorithm>
#include <string>
#include <map>
#include <set>
#include <vector>
#include <stdlib.h>
#include <stdio.h>
#include <queue>
#include <stack>
#include <cstring>
#include <ctype.h>
using namespace std;
typedef long long int ll;
typedef pair<int,int> pii;
#define pb push_back
#define mp make_pair
#define PI acos(-1.0)
//Normal Gcd
/*int gcd ( int a, int b )
{
int c;
while ( a != 0 ) {
c = a; a = b%a; b = c;
}
return b;
}*/
//Recursive Gcd
/*int gcdr ( int a, int b )
{
if ( a==0 ) return b;
return gcdr ( b%a, a );
}*/
//moduler arithmetic
//ll M
/*ll bigmod(ll B,ll P)
{
if(P==0)return 1;
if(P%2==0)
{
ll ret=(bigmod(B,P/2))%M;
return ((ret%M)*(ret%M))%M;
}
else
return ((B%M)*(bigmod(B,P-1)%M))%M;
}*/
//int fx[]={0,0,1,-1};
//int fy[]={1,-1,0,0};
//int fx[]={0,0,1,1,1,-1,-1,-1};
//int fy[]={1,-1,0,1,-1,0,1,-1};
//int fx[]={1,1,-1,-1,2,-2,2,-2};
//int fy[]={2,-2,2,-2,1,1,-1,-1};
int main()
{
int n,m;
cin>>n>>m;
int ans1=max(n,m);
int ans2=min(n,m);
cout<<--ans1<<" "<<ans2<<endl;
return 0;
}
| [
"leontalukdar@gmail.com"
] | leontalukdar@gmail.com |
77b2411266f3ee543251a32d8266dba0b2bfee19 | e73189d7958f71101489953aced28ee044bbb864 | /C++only/ex26.cpp | 9a9c32d1b72f1ca4244d99b6582fffc8493060c3 | [] | no_license | Wulnut/Learning-only | ca781ae0e249c789a38fd6c1712456c9fe1ac6b9 | d2e6b8447798dc8e1c8d7273606da5679a6fff0d | refs/heads/master | 2020-11-29T08:49:20.667802 | 2020-07-28T14:35:13 | 2020-07-28T14:35:13 | 230,073,170 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,032 | cpp | #include <bits/stdc++.h>
using namespace std;
const int N = 101;
int maze[N][N];
bool vis[N][N];
int step[N][N];
int dir[4][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
int n, m;
queue<pair<int , int>> p;
bool in(int x, int y) {
return 0 <= x && x < n && 0 <= y && y < m;
}
bool fly(int x, int y) {
int i = x;
int j = y;
if (in(i, j + 2) && maze[i][j + 2] != -1)
return true;
else{
return false;
}
}
int bfs(int x, int y) {
p.push(make_pair(x, y));
vis[x][y] = true;
while(!p.empty()) {
pair<int, int> now = p.front();
p.pop();
for (int i = 0; i < 4; ++i) {
int tx = now.first + dir[i][0];
int ty = now.second + dir[i][1];
if (in(tx, ty) && !vis[tx][ty]){
if (maze[tx][ty] == -1 && fly(tx, ty)) {
vis[tx][ty + 2] = true;
p.push(make_pair(tx,ty + 1));
step[tx][ty + 2] = step[now.first][now.second] + 1;
}
}
if (in(tx, ty) && !vis[tx][ty] && maze[tx][ty] != -1) {
if (maze[tx][ty] == 0)
return step[tx][ty] = step[now.first][now.second] = 1;
}
if (vis[tx][ty] && maze[tx][ty] != -1 && !vis[tx][ty]) {
if (maze[tx][ty] == 1){
vis[tx][ty] = true;
p.push(make_pair(tx, ty));
step[tx][ty] = step[now.first][now.second] + 1;
}
}
}
}
return -1;
}
int main(){
freopen("note.txt", "r", stdin);
freopen("ans.txt", "w", stdout);
int i, j, ans;
cin >> n >> m;
for (i = 0; i < n; ++i) {
for (j = 0; j < m; ++j)
cin >> maze[i][j];
}
for (i = 0; i < n; ++i) {
for (j = 0; j < m; ++j) {
if (maze[i][j] == 0)
vis[i][j] = true;
ans = bfs(i, j);
break;
}
if (maze[i][j] == 0)
break;
}
cout << ans;
return 0;
} | [
"985951964@qq.com"
] | 985951964@qq.com |
475d6b3b5deb10fe3c3aa3ddbba87abc430deb2f | db666b5c6b5381c55c716f95818a7ecc241d59c7 | /C++/154-findMinimumInRotatedArrayII.cpp | f45825484cdaaa892c51382246281e47fecb1e9d | [] | no_license | SaberDa/LeetCode | ed5ea145ff5baaf28ed104bb08046ff9d5275129 | 7dc681a2124fb9e2190d0ab37bf0965736bb52db | refs/heads/master | 2023-06-25T09:16:14.521110 | 2021-07-26T21:58:33 | 2021-07-26T21:58:33 | 234,479,225 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 699 | cpp | #include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums;
nums = { 2,2,2,0,1 };
int left = 0;
int right = nums.size() - 1;
int ans = nums[left];
while (left <= right) {
int mid = (left + right) / 2;
if (left < mid && mid < right && nums[left] == nums[mid] && nums[mid] == nums[right]) {
left++;
right--;
} else if (nums[left] <= nums[mid]) {
ans = (ans < nums[left]) ? ans : nums[left];
left = mid + 1;
} else {
ans = (ans < nums[right]) ? ans : nums[right];
right = mid - 1;
}
}
cout << ans << endl;
return 0;
} | [
"630991493@qq.com"
] | 630991493@qq.com |
2ddcb312f1d13791163fa6174aa40bd940e0de89 | ad682f72fa87559f98bab9c34afce19605db97d3 | /src/zuckerbraten/crypto.hpp | 58223b33b803a50b64f0ac775f388ad278db9c33 | [
"Zlib",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | cztk/luabraten | 32a608e258e3f13d9e623c1b1ceddd0df5284143 | 101690213e86878a988e2c990560958967cc6cba | refs/heads/master | 2020-03-22T14:42:38.432019 | 2018-12-17T09:52:02 | 2018-12-17T09:52:02 | 140,199,351 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 718 | hpp | /*
These are the crypto function prototypes found in shared/iengine.h
*/
#ifndef CRYPTO_HPP
#define CRYPTO_HPP
#include "cube.h"
//extern void genprivkey(const char *seed, vector<char> &privstr, vector<char> &pubstr, int seedlength);
//extern bool hashstring(const char *str, char *result, int maxlen);
//extern void answerchallenge(const char *privstr, const char *challenge, vector<char> &answerstr);
//extern void *parsepubkey(const char *pubstr);
//extern void freepubkey(void *pubkey);
//extern void *genchallenge(void *pubkey, const void *seed, int seedlen, vector<char> &challengestr);
//extern void freechallenge(void *answer);
//extern bool checkchallenge(const char *answerstr, void *correct);
#endif
| [
"support@ztk.me"
] | support@ztk.me |
1d7001a60e0f0772c7b0982b6ead9c66027f5198 | a7a806b217dc2487b8f2c2af5067a0757dc17cdd | /moveit_core/robot_model/src/robot_model.cpp | 345defd411356f76870bc7417e7d1d8306691ec8 | [
"BSD-3-Clause"
] | permissive | KenmeiFusamae/moveit | ba0d971c456680ae63242b66bc0542b8d23aef2a | c267098aafc1c8a8c795e220f4b7151f3f6525c7 | refs/heads/master | 2021-01-13T05:06:17.134450 | 2017-02-07T20:36:35 | 2017-02-07T20:36:35 | 81,251,820 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 53,026 | cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Ioan A. Sucan
* Copyright (c) 2013, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/robot_model/robot_model.h>
#include <geometric_shapes/shape_operations.h>
#include <boost/math/constants/constants.hpp>
#include <moveit/profiler/profiler.h>
#include <algorithm>
#include <limits>
#include <queue>
#include <cmath>
#include "order_robot_model_items.inc"
/* ------------------------ RobotModel ------------------------ */
moveit::core::RobotModel::RobotModel(const boost::shared_ptr<const urdf::ModelInterface> &urdf_model,
const boost::shared_ptr<const srdf::Model> &srdf_model)
{
root_joint_ = NULL;
urdf_ = urdf_model;
srdf_ = srdf_model;
buildModel(*urdf_model, *srdf_model);
}
moveit::core::RobotModel::~RobotModel()
{
for (JointModelGroupMap::iterator it = joint_model_group_map_.begin(); it != joint_model_group_map_.end(); ++it)
delete it->second;
for (std::size_t i = 0; i < joint_model_vector_.size(); ++i)
delete joint_model_vector_[i];
for (std::size_t i = 0; i < link_model_vector_.size(); ++i)
delete link_model_vector_[i];
}
const moveit::core::JointModel *moveit::core::RobotModel::getRootJoint() const
{
return root_joint_;
}
const moveit::core::LinkModel *moveit::core::RobotModel::getRootLink() const
{
return root_link_;
}
void moveit::core::RobotModel::buildModel(const urdf::ModelInterface &urdf_model, const srdf::Model &srdf_model)
{
moveit::tools::Profiler::ScopedStart prof_start;
moveit::tools::Profiler::ScopedBlock prof_block("RobotModel::buildModel");
root_joint_ = NULL;
root_link_ = NULL;
link_geometry_count_ = 0;
variable_count_ = 0;
model_name_ = urdf_model.getName();
logInform("Loading robot model '%s'...", model_name_.c_str());
if (urdf_model.getRoot())
{
const urdf::Link *root_link_ptr = urdf_model.getRoot().get();
model_frame_ = '/' + root_link_ptr->name;
logDebug("... building kinematic chain");
root_joint_ = buildRecursive(NULL, root_link_ptr, srdf_model);
if (root_joint_)
root_link_ = root_joint_->getChildLinkModel();
logDebug("... building mimic joints");
buildMimic(urdf_model);
logDebug("... computing joint indexing");
buildJointInfo();
if (link_models_with_collision_geometry_vector_.empty())
logWarn("No geometry is associated to any robot links");
// build groups
logDebug("... constructing joint groups");
buildGroups(srdf_model);
logDebug("... constructing joint group states");
buildGroupStates(srdf_model);
// For debugging entire model
if (false)
printModelInfo(std::cout);
}
else
logWarn("No root link found");
}
namespace moveit
{
namespace core
{
namespace
{
typedef std::map<const JointModel *, std::pair<std::set<const LinkModel *, OrderLinksByIndex>,
std::set<const JointModel *, OrderJointsByIndex> > > DescMap;
void computeDescendantsHelper(const JointModel *joint, std::vector<const JointModel *> &parents,
std::set<const JointModel *> &seen, DescMap &descendants)
{
if (!joint)
return;
if (seen.find(joint) != seen.end())
return;
seen.insert(joint);
for (std::size_t i = 0; i < parents.size(); ++i)
descendants[parents[i]].second.insert(joint);
const LinkModel *lm = joint->getChildLinkModel();
if (!lm)
return;
for (std::size_t i = 0; i < parents.size(); ++i)
descendants[parents[i]].first.insert(lm);
descendants[joint].first.insert(lm);
parents.push_back(joint);
const std::vector<const JointModel *> &ch = lm->getChildJointModels();
for (std::size_t i = 0; i < ch.size(); ++i)
computeDescendantsHelper(ch[i], parents, seen, descendants);
const std::vector<const JointModel *> &mim = joint->getMimicRequests();
for (std::size_t i = 0; i < mim.size(); ++i)
computeDescendantsHelper(mim[i], parents, seen, descendants);
parents.pop_back();
}
void computeCommonRootsHelper(const JointModel *joint, std::vector<int> &common_roots, int size)
{
if (!joint)
return;
const LinkModel *lm = joint->getChildLinkModel();
if (!lm)
return;
const std::vector<const JointModel *> &ch = lm->getChildJointModels();
for (std::size_t i = 0; i < ch.size(); ++i)
{
const std::vector<const JointModel *> &a = ch[i]->getDescendantJointModels();
for (std::size_t j = i + 1; j < ch.size(); ++j)
{
const std::vector<const JointModel *> &b = ch[j]->getDescendantJointModels();
for (std::size_t m = 0; m < b.size(); ++m)
common_roots[ch[i]->getJointIndex() * size + b[m]->getJointIndex()] =
common_roots[ch[i]->getJointIndex() + b[m]->getJointIndex() * size] = joint->getJointIndex();
for (std::size_t k = 0; k < a.size(); ++k)
{
common_roots[a[k]->getJointIndex() * size + ch[j]->getJointIndex()] =
common_roots[a[k]->getJointIndex() + ch[j]->getJointIndex() * size] = joint->getJointIndex();
for (std::size_t m = 0; m < b.size(); ++m)
common_roots[a[k]->getJointIndex() * size + b[m]->getJointIndex()] =
common_roots[a[k]->getJointIndex() + b[m]->getJointIndex() * size] = joint->getJointIndex();
}
}
computeCommonRootsHelper(ch[i], common_roots, size);
}
}
}
}
}
void moveit::core::RobotModel::computeCommonRoots()
{
// compute common roots for all pairs of joints;
// there are 3 cases of pairs (X, Y):
// X != Y && X and Y are not descendants of one another
// X == Y
// X != Y && X and Y are descendants of one another
// by default, the common root is always the global root;
common_joint_roots_.resize(joint_model_vector_.size() * joint_model_vector_.size(), 0);
// look at all descendants recursively; for two sibling nodes A, B, both children of X, all the pairs of respective
// descendants of A and B
// have X as the common root.
computeCommonRootsHelper(root_joint_, common_joint_roots_, joint_model_vector_.size());
for (std::size_t i = 0; i < joint_model_vector_.size(); ++i)
{
// the common root of a joint and itself is the same joint:
common_joint_roots_[joint_model_vector_[i]->getJointIndex() * (1 + joint_model_vector_.size())] =
joint_model_vector_[i]->getJointIndex();
// a node N and one of its descendants have as common root the node N itself:
const std::vector<const JointModel *> &d = joint_model_vector_[i]->getDescendantJointModels();
for (std::size_t j = 0; j < d.size(); ++j)
common_joint_roots_[d[j]->getJointIndex() * joint_model_vector_.size() +
joint_model_vector_[i]->getJointIndex()] =
common_joint_roots_[d[j]->getJointIndex() +
joint_model_vector_[i]->getJointIndex() * joint_model_vector_.size()] =
joint_model_vector_[i]->getJointIndex();
}
}
void moveit::core::RobotModel::computeDescendants()
{
// compute the list of descendants for all joints
std::vector<const JointModel *> parents;
std::set<const JointModel *> seen;
DescMap descendants;
computeDescendantsHelper(root_joint_, parents, seen, descendants);
for (DescMap::iterator it = descendants.begin(); it != descendants.end(); ++it)
{
JointModel *jm = const_cast<JointModel *>(it->first);
for (std::set<const JointModel *>::const_iterator jt = it->second.second.begin(); jt != it->second.second.end();
++jt)
jm->addDescendantJointModel(*jt);
for (std::set<const LinkModel *>::const_iterator jt = it->second.first.begin(); jt != it->second.first.end(); ++jt)
jm->addDescendantLinkModel(*jt);
}
}
void moveit::core::RobotModel::buildJointInfo()
{
moveit::tools::Profiler::ScopedStart prof_start;
moveit::tools::Profiler::ScopedBlock prof_block("RobotModel::buildJointInfo");
// construct additional maps for easy access by name
variable_count_ = 0;
active_joint_model_start_index_.reserve(joint_model_vector_.size());
variable_names_.reserve(joint_model_vector_.size());
joints_of_variable_.reserve(joint_model_vector_.size());
for (std::size_t i = 0; i < joint_model_vector_.size(); ++i)
{
joint_model_vector_[i]->setJointIndex(i);
const std::vector<std::string> &name_order = joint_model_vector_[i]->getVariableNames();
// compute index map
if (!name_order.empty())
{
for (std::size_t j = 0; j < name_order.size(); ++j)
{
joint_variables_index_map_[name_order[j]] = variable_count_ + j;
variable_names_.push_back(name_order[j]);
joints_of_variable_.push_back(joint_model_vector_[i]);
}
if (joint_model_vector_[i]->getMimic() == NULL)
{
active_joint_model_start_index_.push_back(variable_count_);
active_joint_model_vector_.push_back(joint_model_vector_[i]);
active_joint_model_vector_const_.push_back(joint_model_vector_[i]);
active_joint_models_bounds_.push_back(&joint_model_vector_[i]->getVariableBounds());
}
if (joint_model_vector_[i]->getType() == JointModel::REVOLUTE &&
static_cast<const RevoluteJointModel *>(joint_model_vector_[i])->isContinuous())
continuous_joint_model_vector_.push_back(joint_model_vector_[i]);
joint_model_vector_[i]->setFirstVariableIndex(variable_count_);
joint_variables_index_map_[joint_model_vector_[i]->getName()] = variable_count_;
// compute variable count
std::size_t vc = joint_model_vector_[i]->getVariableCount();
variable_count_ += vc;
if (vc == 1)
single_dof_joints_.push_back(joint_model_vector_[i]);
else
multi_dof_joints_.push_back(joint_model_vector_[i]);
}
}
for (std::size_t i = 0; i < link_model_vector_.size(); ++i)
{
LinkTransformMap associated_transforms;
computeFixedTransforms(link_model_vector_[i], link_model_vector_[i]->getJointOriginTransform().inverse(),
associated_transforms);
if (associated_transforms.size() > 1)
{
for (LinkTransformMap::iterator it = associated_transforms.begin(); it != associated_transforms.end(); ++it)
if (it->first != link_model_vector_[i])
{
getLinkModel(it->first->getName())->addAssociatedFixedTransform(link_model_vector_[i], it->second.inverse());
link_model_vector_[i]->addAssociatedFixedTransform(it->first, it->second);
}
}
}
computeDescendants();
computeCommonRoots(); // must be called _after_ list of descendants was computed
}
void moveit::core::RobotModel::buildGroupStates(const srdf::Model &srdf_model)
{
// copy the default states to the groups
const std::vector<srdf::Model::GroupState> &ds = srdf_model.getGroupStates();
for (std::size_t i = 0; i < ds.size(); ++i)
{
if (hasJointModelGroup(ds[i].group_))
{
JointModelGroup *jmg = getJointModelGroup(ds[i].group_);
std::map<std::string, double> state;
for (std::map<std::string, std::vector<double> >::const_iterator jt = ds[i].joint_values_.begin();
jt != ds[i].joint_values_.end(); ++jt)
{
if (jmg->hasJointModel(jt->first))
{
const JointModel *jm = jmg->getJointModel(jt->first);
const std::vector<std::string> &vn = jm->getVariableNames();
if (vn.size() == jt->second.size())
for (std::size_t j = 0; j < vn.size(); ++j)
state[vn[j]] = jt->second[j];
else
logError("The model for joint '%s' requires %d variable values, but only %d variable values were supplied "
"in default state '%s' for group '%s'",
jt->first.c_str(), (int)vn.size(), (int)jt->second.size(), ds[i].name_.c_str(),
jmg->getName().c_str());
}
else
logError("Group state '%s' specifies value for joint '%s', but that joint is not part of group '%s'",
ds[i].name_.c_str(), jt->first.c_str(), jmg->getName().c_str());
}
if (!state.empty())
jmg->addDefaultState(ds[i].name_, state);
}
else
logError("Group state '%s' specified for group '%s', but that group does not exist", ds[i].name_.c_str(),
ds[i].group_.c_str());
}
}
void moveit::core::RobotModel::buildMimic(const urdf::ModelInterface &urdf_model)
{
// compute mimic joints
for (std::size_t i = 0; i < joint_model_vector_.size(); ++i)
{
const urdf::Joint *jm = urdf_model.getJoint(joint_model_vector_[i]->getName()).get();
if (jm)
if (jm->mimic)
{
JointModelMap::const_iterator jit = joint_model_map_.find(jm->mimic->joint_name);
if (jit != joint_model_map_.end())
{
if (joint_model_vector_[i]->getVariableCount() == jit->second->getVariableCount())
joint_model_vector_[i]->setMimic(jit->second, jm->mimic->multiplier, jm->mimic->offset);
else
logError("Join '%s' cannot mimic joint '%s' because they have different number of DOF",
joint_model_vector_[i]->getName().c_str(), jm->mimic->joint_name.c_str());
}
else
logError("Joint '%s' cannot mimic unknown joint '%s'", joint_model_vector_[i]->getName().c_str(),
jm->mimic->joint_name.c_str());
}
}
// in case we have a joint that mimics a joint that already mimics another joint, we can simplify things:
bool change = true;
while (change)
{
change = false;
for (std::size_t i = 0; i < joint_model_vector_.size(); ++i)
if (joint_model_vector_[i]->getMimic())
{
if (joint_model_vector_[i]->getMimic()->getMimic())
{
joint_model_vector_[i]->setMimic(
joint_model_vector_[i]->getMimic()->getMimic(),
joint_model_vector_[i]->getMimicFactor() * joint_model_vector_[i]->getMimic()->getMimicFactor(),
joint_model_vector_[i]->getMimicOffset() +
joint_model_vector_[i]->getMimicFactor() * joint_model_vector_[i]->getMimic()->getMimicOffset());
change = true;
}
if (joint_model_vector_[i] == joint_model_vector_[i]->getMimic())
{
logError("Cycle found in joint that mimic each other. Ignoring all mimic joints.");
for (std::size_t i = 0; i < joint_model_vector_.size(); ++i)
joint_model_vector_[i]->setMimic(NULL, 0.0, 0.0);
change = false;
break;
}
}
}
// build mimic requests
for (std::size_t i = 0; i < joint_model_vector_.size(); ++i)
if (joint_model_vector_[i]->getMimic())
{
const_cast<JointModel *>(joint_model_vector_[i]->getMimic())->addMimicRequest(joint_model_vector_[i]);
mimic_joints_.push_back(joint_model_vector_[i]);
}
}
bool moveit::core::RobotModel::hasEndEffector(const std::string &eef) const
{
return end_effectors_map_.find(eef) != end_effectors_map_.end();
}
const moveit::core::JointModelGroup *moveit::core::RobotModel::getEndEffector(const std::string &name) const
{
JointModelGroupMap::const_iterator it = end_effectors_map_.find(name);
if (it == end_effectors_map_.end())
{
it = joint_model_group_map_.find(name);
if (it != joint_model_group_map_.end() && it->second->isEndEffector())
return it->second;
logError("End-effector '%s' not found in model '%s'", name.c_str(), model_name_.c_str());
return NULL;
}
return it->second;
}
moveit::core::JointModelGroup *moveit::core::RobotModel::getEndEffector(const std::string &name)
{
JointModelGroupMap::const_iterator it = end_effectors_map_.find(name);
if (it == end_effectors_map_.end())
{
it = joint_model_group_map_.find(name);
if (it != joint_model_group_map_.end() && it->second->isEndEffector())
return it->second;
logError("End-effector '%s' not found in model '%s'", name.c_str(), model_name_.c_str());
return NULL;
}
return it->second;
}
bool moveit::core::RobotModel::hasJointModelGroup(const std::string &name) const
{
return joint_model_group_map_.find(name) != joint_model_group_map_.end();
}
const moveit::core::JointModelGroup *moveit::core::RobotModel::getJointModelGroup(const std::string &name) const
{
JointModelGroupMap::const_iterator it = joint_model_group_map_.find(name);
if (it == joint_model_group_map_.end())
{
logError("Group '%s' not found in model '%s'", name.c_str(), model_name_.c_str());
return NULL;
}
return it->second;
}
moveit::core::JointModelGroup *moveit::core::RobotModel::getJointModelGroup(const std::string &name)
{
JointModelGroupMap::const_iterator it = joint_model_group_map_.find(name);
if (it == joint_model_group_map_.end())
{
logError("Group '%s' not found in model '%s'", name.c_str(), model_name_.c_str());
return NULL;
}
return it->second;
}
void moveit::core::RobotModel::buildGroups(const srdf::Model &srdf_model)
{
const std::vector<srdf::Model::Group> &group_configs = srdf_model.getGroups();
// the only thing tricky is dealing with subgroups
std::vector<bool> processed(group_configs.size(), false);
bool added = true;
while (added)
{
added = false;
// going to make passes until we can't do anything else
for (std::size_t i = 0; i < group_configs.size(); ++i)
if (!processed[i])
{
// if we haven't processed, check and see if the dependencies are met yet
bool all_subgroups_added = true;
for (std::size_t j = 0; j < group_configs[i].subgroups_.size(); ++j)
if (joint_model_group_map_.find(group_configs[i].subgroups_[j]) == joint_model_group_map_.end())
{
all_subgroups_added = false;
break;
}
if (all_subgroups_added)
{
added = true;
processed[i] = true;
if (!addJointModelGroup(group_configs[i]))
logWarn("Failed to add group '%s'", group_configs[i].name_.c_str());
}
}
}
for (std::size_t i = 0; i < processed.size(); ++i)
if (!processed[i])
logWarn("Could not process group '%s' due to unmet subgroup dependencies", group_configs[i].name_.c_str());
for (JointModelGroupMap::const_iterator it = joint_model_group_map_.begin(); it != joint_model_group_map_.end(); ++it)
joint_model_groups_.push_back(it->second);
std::sort(joint_model_groups_.begin(), joint_model_groups_.end(), OrderGroupsByName());
for (std::size_t i = 0; i < joint_model_groups_.size(); ++i)
{
joint_model_groups_const_.push_back(joint_model_groups_[i]);
joint_model_group_names_.push_back(joint_model_groups_[i]->getName());
}
buildGroupsInfo_Subgroups(srdf_model);
buildGroupsInfo_EndEffectors(srdf_model);
}
void moveit::core::RobotModel::buildGroupsInfo_Subgroups(const srdf::Model &srdf_model)
{
// compute subgroups
for (JointModelGroupMap::const_iterator it = joint_model_group_map_.begin(); it != joint_model_group_map_.end(); ++it)
{
JointModelGroup *jmg = it->second;
std::vector<std::string> subgroup_names;
std::set<const JointModel *> joints(jmg->getJointModels().begin(), jmg->getJointModels().end());
for (JointModelGroupMap::const_iterator jt = joint_model_group_map_.begin(); jt != joint_model_group_map_.end();
++jt)
if (jt->first != it->first)
{
bool ok = true;
JointModelGroup *sub_jmg = jt->second;
const std::vector<const JointModel *> &sub_joints = sub_jmg->getJointModels();
for (std::size_t k = 0; k < sub_joints.size(); ++k)
if (joints.find(sub_joints[k]) == joints.end())
{
ok = false;
break;
}
if (ok)
subgroup_names.push_back(sub_jmg->getName());
}
if (!subgroup_names.empty())
jmg->setSubgroupNames(subgroup_names);
}
}
void moveit::core::RobotModel::buildGroupsInfo_EndEffectors(const srdf::Model &srdf_model)
{
// set the end-effector flags
const std::vector<srdf::Model::EndEffector> &eefs = srdf_model.getEndEffectors();
for (JointModelGroupMap::const_iterator it = joint_model_group_map_.begin(); it != joint_model_group_map_.end(); ++it)
{
// check if this group is a known end effector
for (std::size_t k = 0; k < eefs.size(); ++k)
if (eefs[k].component_group_ == it->first)
{
// if it is, mark it as such
it->second->setEndEffectorName(eefs[k].name_);
end_effectors_map_[eefs[k].name_] = it->second;
end_effectors_.push_back(it->second);
// check to see if there are groups that contain the parent link of this end effector.
// record this information if found;
std::vector<JointModelGroup *> possible_parent_groups;
for (JointModelGroupMap::const_iterator jt = joint_model_group_map_.begin(); jt != joint_model_group_map_.end();
++jt)
if (jt->first != it->first)
{
if (jt->second->hasLinkModel(eefs[k].parent_link_))
{
jt->second->attachEndEffector(eefs[k].name_);
possible_parent_groups.push_back(jt->second);
}
}
JointModelGroup *eef_parent_group = NULL;
// if a parent group is specified in SRDF, try to use it
if (!eefs[k].parent_group_.empty())
{
JointModelGroupMap::const_iterator jt = joint_model_group_map_.find(eefs[k].parent_group_);
if (jt != joint_model_group_map_.end())
{
if (jt->second->hasLinkModel(eefs[k].parent_link_))
{
if (jt->second != it->second)
eef_parent_group = jt->second;
else
logError("Group '%s' for end-effector '%s' cannot be its own parent", eefs[k].parent_group_.c_str(),
eefs[k].name_.c_str());
}
else
logError("Group '%s' was specified as parent group for end-effector '%s' but it does not include the "
"parent link '%s'",
eefs[k].parent_group_.c_str(), eefs[k].name_.c_str(), eefs[k].parent_link_.c_str());
}
else
logError("Group name '%s' not found (specified as parent group for end-effector '%s')",
eefs[k].parent_group_.c_str(), eefs[k].name_.c_str());
}
// if no parent group was specified, use a default one
if (eef_parent_group == NULL)
if (!possible_parent_groups.empty())
{
// if there are multiple options for the group that contains this end-effector,
// we pick the group with fewest joints.
std::size_t best = 0;
for (std::size_t g = 1; g < possible_parent_groups.size(); ++g)
if (possible_parent_groups[g]->getJointModels().size() <
possible_parent_groups[best]->getJointModels().size())
best = g;
eef_parent_group = possible_parent_groups[best];
}
if (eef_parent_group)
{
it->second->setEndEffectorParent(eef_parent_group->getName(), eefs[k].parent_link_);
}
else
{
logWarn("Could not identify parent group for end-effector '%s'", eefs[k].name_.c_str());
it->second->setEndEffectorParent("", eefs[k].parent_link_);
}
break;
}
}
std::sort(end_effectors_.begin(), end_effectors_.end(), OrderGroupsByName());
}
bool moveit::core::RobotModel::addJointModelGroup(const srdf::Model::Group &gc)
{
if (joint_model_group_map_.find(gc.name_) != joint_model_group_map_.end())
{
logWarn("A group named '%s' already exists. Not adding.", gc.name_.c_str());
return false;
}
std::set<const JointModel *> jset;
// add joints from chains
for (std::size_t i = 0; i < gc.chains_.size(); ++i)
{
const LinkModel *base_link = getLinkModel(gc.chains_[i].first);
const LinkModel *tip_link = getLinkModel(gc.chains_[i].second);
if (base_link && tip_link)
{
// go from tip, up the chain, until we hit the root or we find the base_link
const LinkModel *lm = tip_link;
std::vector<const JointModel *> cj;
while (lm)
{
if (lm == base_link)
break;
cj.push_back(lm->getParentJointModel());
lm = lm->getParentJointModel()->getParentLinkModel();
}
// if we did not find the base_link, we could have a chain like e.g.,
// from one end-effector to another end-effector, so the root is in between
if (lm != base_link)
{
// we go up the chain from the base this time, and see where we intersect the other chain
lm = base_link;
std::size_t index = 0;
std::vector<const JointModel *> cj2;
while (lm)
{
for (std::size_t j = 0; j < cj.size(); ++j)
if (cj[j] == lm->getParentJointModel())
{
index = j + 1;
break;
}
if (index > 0)
break;
cj2.push_back(lm->getParentJointModel());
lm = lm->getParentJointModel()->getParentLinkModel();
}
if (index > 0)
{
jset.insert(cj.begin(), cj.begin() + index);
jset.insert(cj2.begin(), cj2.end());
}
}
else
// if we have a simple chain, just add the joints
jset.insert(cj.begin(), cj.end());
}
}
// add joints
for (std::size_t i = 0; i < gc.joints_.size(); ++i)
{
const JointModel *j = getJointModel(gc.joints_[i]);
if (j)
jset.insert(j);
}
// add joints that are parents of included links
for (std::size_t i = 0; i < gc.links_.size(); ++i)
{
const LinkModel *l = getLinkModel(gc.links_[i]);
if (l)
jset.insert(l->getParentJointModel());
}
// add joints from subgroups
for (std::size_t i = 0; i < gc.subgroups_.size(); ++i)
{
const JointModelGroup *sg = getJointModelGroup(gc.subgroups_[i]);
if (sg)
{
// active joints
const std::vector<const JointModel *> &js = sg->getJointModels();
for (std::size_t j = 0; j < js.size(); ++j)
jset.insert(js[j]);
// fixed joints
const std::vector<const JointModel *> &fs = sg->getFixedJointModels();
for (std::size_t j = 0; j < fs.size(); ++j)
jset.insert(fs[j]);
// mimic joints
const std::vector<const JointModel *> &ms = sg->getMimicJointModels();
for (std::size_t j = 0; j < ms.size(); ++j)
jset.insert(ms[j]);
}
}
if (jset.empty())
{
logWarn("Group '%s' must have at least one valid joint", gc.name_.c_str());
return false;
}
std::vector<const JointModel *> joints;
for (std::set<const JointModel *>::iterator it = jset.begin(); it != jset.end(); ++it)
joints.push_back(*it);
JointModelGroup *jmg = new JointModelGroup(gc.name_, gc, joints, this);
joint_model_group_map_[gc.name_] = jmg;
return true;
}
moveit::core::JointModel *moveit::core::RobotModel::buildRecursive(LinkModel *parent, const urdf::Link *urdf_link,
const srdf::Model &srdf_model)
{
// construct the joint
JointModel *joint = urdf_link->parent_joint ?
constructJointModel(urdf_link->parent_joint.get(), urdf_link, srdf_model) :
constructJointModel(NULL, urdf_link, srdf_model);
if (joint == NULL)
return NULL;
// bookkeeping for the joint
joint_model_map_[joint->getName()] = joint;
joint->setJointIndex(joint_model_vector_.size());
joint_model_vector_.push_back(joint);
joint_model_vector_const_.push_back(joint);
joint_model_names_vector_.push_back(joint->getName());
joint->setParentLinkModel(parent);
// construct the link
LinkModel *link = constructLinkModel(urdf_link);
joint->setChildLinkModel(link);
link->setParentLinkModel(parent);
// bookkeeping for the link
link_model_map_[joint->getChildLinkModel()->getName()] = link;
link->setLinkIndex(link_model_vector_.size());
link_model_vector_.push_back(link);
link_model_vector_const_.push_back(link);
link_model_names_vector_.push_back(link->getName());
if (!link->getShapes().empty())
{
link_models_with_collision_geometry_vector_.push_back(link);
link_model_names_with_collision_geometry_vector_.push_back(link->getName());
link->setFirstCollisionBodyTransformIndex(link_geometry_count_);
link_geometry_count_ += link->getShapes().size();
}
link->setParentJointModel(joint);
// recursively build child links (and joints)
for (std::size_t i = 0; i < urdf_link->child_links.size(); ++i)
{
JointModel *jm = buildRecursive(link, urdf_link->child_links[i].get(), srdf_model);
if (jm)
link->addChildJointModel(jm);
}
return joint;
}
namespace
{
// construct bounds for 1DOF joint
static inline moveit::core::VariableBounds jointBoundsFromURDF(const urdf::Joint *urdf_joint)
{
moveit::core::VariableBounds b;
if (urdf_joint->safety)
{
b.position_bounded_ = true;
b.min_position_ = urdf_joint->safety->soft_lower_limit;
b.max_position_ = urdf_joint->safety->soft_upper_limit;
if (urdf_joint->limits)
{
if (urdf_joint->limits->lower > b.min_position_)
b.min_position_ = urdf_joint->limits->lower;
if (urdf_joint->limits->upper < b.max_position_)
b.max_position_ = urdf_joint->limits->upper;
}
}
else
{
if (urdf_joint->limits)
{
b.position_bounded_ = true;
b.min_position_ = urdf_joint->limits->lower;
b.max_position_ = urdf_joint->limits->upper;
}
}
if (urdf_joint->limits)
{
b.max_velocity_ = fabs(urdf_joint->limits->velocity);
b.min_velocity_ = -b.max_velocity_;
b.velocity_bounded_ = b.max_velocity_ > std::numeric_limits<double>::epsilon();
}
return b;
}
}
moveit::core::JointModel *moveit::core::RobotModel::constructJointModel(const urdf::Joint *urdf_joint,
const urdf::Link *child_link,
const srdf::Model &srdf_model)
{
JointModel *result = NULL;
// must be the root link transform
if (urdf_joint)
{
switch (urdf_joint->type)
{
case urdf::Joint::REVOLUTE:
{
RevoluteJointModel *j = new RevoluteJointModel(urdf_joint->name);
j->setVariableBounds(j->getName(), jointBoundsFromURDF(urdf_joint));
j->setContinuous(false);
j->setAxis(Eigen::Vector3d(urdf_joint->axis.x, urdf_joint->axis.y, urdf_joint->axis.z));
result = j;
}
break;
case urdf::Joint::CONTINUOUS:
{
RevoluteJointModel *j = new RevoluteJointModel(urdf_joint->name);
j->setVariableBounds(j->getName(), jointBoundsFromURDF(urdf_joint));
j->setContinuous(true);
j->setAxis(Eigen::Vector3d(urdf_joint->axis.x, urdf_joint->axis.y, urdf_joint->axis.z));
result = j;
}
break;
case urdf::Joint::PRISMATIC:
{
PrismaticJointModel *j = new PrismaticJointModel(urdf_joint->name);
j->setVariableBounds(j->getName(), jointBoundsFromURDF(urdf_joint));
j->setAxis(Eigen::Vector3d(urdf_joint->axis.x, urdf_joint->axis.y, urdf_joint->axis.z));
result = j;
}
break;
case urdf::Joint::FLOATING:
result = new FloatingJointModel(urdf_joint->name);
break;
case urdf::Joint::PLANAR:
result = new PlanarJointModel(urdf_joint->name);
break;
case urdf::Joint::FIXED:
result = new FixedJointModel(urdf_joint->name);
break;
default:
logError("Unknown joint type: %d", (int)urdf_joint->type);
break;
}
}
else
{
const std::vector<srdf::Model::VirtualJoint> &vjoints = srdf_model.getVirtualJoints();
for (std::size_t i = 0; i < vjoints.size(); ++i)
{
if (vjoints[i].child_link_ != child_link->name)
{
logWarn("Skipping virtual joint '%s' because its child frame '%s' does not match the URDF frame '%s'",
vjoints[i].name_.c_str(), vjoints[i].child_link_.c_str(), child_link->name.c_str());
}
else if (vjoints[i].parent_frame_.empty())
{
logWarn("Skipping virtual joint '%s' because its parent frame is empty", vjoints[i].name_.c_str());
}
else
{
if (vjoints[i].type_ == "fixed")
result = new FixedJointModel(vjoints[i].name_);
else if (vjoints[i].type_ == "planar")
result = new PlanarJointModel(vjoints[i].name_);
else if (vjoints[i].type_ == "floating")
result = new FloatingJointModel(vjoints[i].name_);
if (result)
{
// for fixed frames we still use the robot root link
if (vjoints[i].type_ != "fixed")
{
model_frame_ = vjoints[i].parent_frame_;
if (model_frame_[0] != '/')
model_frame_ = '/' + model_frame_;
}
break;
}
}
}
if (!result)
{
logInform("No root/virtual joint specified in SRDF. Assuming fixed joint");
result = new FixedJointModel("ASSUMED_FIXED_ROOT_JOINT");
}
}
if (result)
{
result->setDistanceFactor(result->getStateSpaceDimension());
const std::vector<srdf::Model::PassiveJoint> &pjoints = srdf_model.getPassiveJoints();
for (std::size_t i = 0; i < pjoints.size(); ++i)
{
if (result->getName() == pjoints[i].name_)
{
result->setPassive(true);
break;
}
}
}
return result;
}
namespace
{
static inline Eigen::Affine3d urdfPose2Affine3d(const urdf::Pose &pose)
{
Eigen::Quaterniond q(pose.rotation.w, pose.rotation.x, pose.rotation.y, pose.rotation.z);
Eigen::Affine3d af(Eigen::Translation3d(pose.position.x, pose.position.y, pose.position.z) * q.toRotationMatrix());
return af;
}
}
moveit::core::LinkModel *moveit::core::RobotModel::constructLinkModel(const urdf::Link *urdf_link)
{
LinkModel *result = new LinkModel(urdf_link->name);
const std::vector<boost::shared_ptr<urdf::Collision> > &col_array =
urdf_link->collision_array.empty() ? std::vector<boost::shared_ptr<urdf::Collision> >(1, urdf_link->collision) :
urdf_link->collision_array;
std::vector<shapes::ShapeConstPtr> shapes;
EigenSTL::vector_Affine3d poses;
for (std::size_t i = 0; i < col_array.size(); ++i)
if (col_array[i] && col_array[i]->geometry)
{
shapes::ShapeConstPtr s = constructShape(col_array[i]->geometry.get());
if (s)
{
shapes.push_back(s);
poses.push_back(urdfPose2Affine3d(col_array[i]->origin));
}
}
if (shapes.empty())
{
const std::vector<boost::shared_ptr<urdf::Visual> > &vis_array =
urdf_link->visual_array.empty() ? std::vector<boost::shared_ptr<urdf::Visual> >(1, urdf_link->visual) :
urdf_link->visual_array;
for (std::size_t i = 0; i < vis_array.size(); ++i)
if (vis_array[i] && vis_array[i]->geometry)
{
shapes::ShapeConstPtr s = constructShape(vis_array[i]->geometry.get());
if (s)
{
shapes.push_back(s);
poses.push_back(urdfPose2Affine3d(vis_array[i]->origin));
}
}
}
result->setGeometry(shapes, poses);
// figure out visual mesh (try visual urdf tag first, collision tag otherwise
if (urdf_link->visual && urdf_link->visual->geometry)
{
if (urdf_link->visual->geometry->type == urdf::Geometry::MESH)
{
const urdf::Mesh *mesh = static_cast<const urdf::Mesh *>(urdf_link->visual->geometry.get());
if (!mesh->filename.empty())
result->setVisualMesh(mesh->filename, urdfPose2Affine3d(urdf_link->visual->origin),
Eigen::Vector3d(mesh->scale.x, mesh->scale.y, mesh->scale.z));
}
}
else if (urdf_link->collision && urdf_link->collision->geometry)
{
if (urdf_link->collision->geometry->type == urdf::Geometry::MESH)
{
const urdf::Mesh *mesh = static_cast<const urdf::Mesh *>(urdf_link->collision->geometry.get());
if (!mesh->filename.empty())
result->setVisualMesh(mesh->filename, urdfPose2Affine3d(urdf_link->collision->origin),
Eigen::Vector3d(mesh->scale.x, mesh->scale.y, mesh->scale.z));
}
}
if (urdf_link->parent_joint)
result->setJointOriginTransform(urdfPose2Affine3d(urdf_link->parent_joint->parent_to_joint_origin_transform));
return result;
}
shapes::ShapePtr moveit::core::RobotModel::constructShape(const urdf::Geometry *geom)
{
moveit::tools::Profiler::ScopedBlock prof_block("RobotModel::constructShape");
shapes::Shape *result = NULL;
switch (geom->type)
{
case urdf::Geometry::SPHERE:
result = new shapes::Sphere(static_cast<const urdf::Sphere *>(geom)->radius);
break;
case urdf::Geometry::BOX:
{
urdf::Vector3 dim = static_cast<const urdf::Box *>(geom)->dim;
result = new shapes::Box(dim.x, dim.y, dim.z);
}
break;
case urdf::Geometry::CYLINDER:
result = new shapes::Cylinder(static_cast<const urdf::Cylinder *>(geom)->radius,
static_cast<const urdf::Cylinder *>(geom)->length);
break;
case urdf::Geometry::MESH:
{
const urdf::Mesh *mesh = static_cast<const urdf::Mesh *>(geom);
if (!mesh->filename.empty())
{
Eigen::Vector3d scale(mesh->scale.x, mesh->scale.y, mesh->scale.z);
shapes::Mesh *m = shapes::createMeshFromResource(mesh->filename, scale);
result = m;
}
}
break;
default:
logError("Unknown geometry type: %d", (int)geom->type);
break;
}
return shapes::ShapePtr(result);
}
bool moveit::core::RobotModel::hasJointModel(const std::string &name) const
{
return joint_model_map_.find(name) != joint_model_map_.end();
}
bool moveit::core::RobotModel::hasLinkModel(const std::string &name) const
{
return link_model_map_.find(name) != link_model_map_.end();
}
const moveit::core::JointModel *moveit::core::RobotModel::getJointModel(const std::string &name) const
{
JointModelMap::const_iterator it = joint_model_map_.find(name);
if (it != joint_model_map_.end())
return it->second;
logError("Joint '%s' not found in model '%s'", name.c_str(), model_name_.c_str());
return NULL;
}
const moveit::core::JointModel *moveit::core::RobotModel::getJointModel(int index) const
{
if (index < 0 || index >= static_cast<int>(joint_model_vector_.size()))
{
logError("Joint index '%i' out of bounds of joints in model '%s'", index, model_name_.c_str());
return NULL;
}
assert(joint_model_vector_[index]->getJointIndex() == index);
return joint_model_vector_[index];
}
moveit::core::JointModel *moveit::core::RobotModel::getJointModel(const std::string &name)
{
JointModelMap::const_iterator it = joint_model_map_.find(name);
if (it != joint_model_map_.end())
return it->second;
logError("Joint '%s' not found in model '%s'", name.c_str(), model_name_.c_str());
return NULL;
}
const moveit::core::LinkModel *moveit::core::RobotModel::getLinkModel(const std::string &name) const
{
LinkModelMap::const_iterator it = link_model_map_.find(name);
if (it != link_model_map_.end())
return it->second;
logError("Link '%s' not found in model '%s'", name.c_str(), model_name_.c_str());
return NULL;
}
const moveit::core::LinkModel *moveit::core::RobotModel::getLinkModel(int index) const
{
if (index < 0 || index >= static_cast<int>(link_model_vector_.size()))
{
logError("Link index '%i' out of bounds of links in model '%s'", index, model_name_.c_str());
return NULL;
}
assert(link_model_vector_[index]->getLinkIndex() == index);
return link_model_vector_[index];
}
moveit::core::LinkModel *moveit::core::RobotModel::getLinkModel(const std::string &name)
{
LinkModelMap::const_iterator it = link_model_map_.find(name);
if (it != link_model_map_.end())
return it->second;
logError("Link '%s' not found in model '%s'", name.c_str(), model_name_.c_str());
return NULL;
}
void moveit::core::RobotModel::updateMimicJoints(double *values) const
{
for (std::size_t i = 0; i < mimic_joints_.size(); ++i)
{
int src = mimic_joints_[i]->getMimic()->getFirstVariableIndex();
int dest = mimic_joints_[i]->getFirstVariableIndex();
values[dest] = values[src] * mimic_joints_[i]->getMimicFactor() + mimic_joints_[i]->getMimicOffset();
}
}
void moveit::core::RobotModel::getVariableRandomPositions(random_numbers::RandomNumberGenerator &rng,
double *values) const
{
for (std::size_t i = 0; i < active_joint_model_vector_.size(); ++i)
active_joint_model_vector_[i]->getVariableRandomPositions(rng, values + active_joint_model_start_index_[i]);
updateMimicJoints(values);
}
void moveit::core::RobotModel::getVariableRandomPositions(random_numbers::RandomNumberGenerator &rng,
std::map<std::string, double> &values) const
{
std::vector<double> tmp(variable_count_);
getVariableRandomPositions(rng, &tmp[0]);
values.clear();
for (std::size_t i = 0; i < variable_names_.size(); ++i)
values[variable_names_[i]] = tmp[i];
}
void moveit::core::RobotModel::getVariableDefaultPositions(double *values) const
{
for (std::size_t i = 0; i < active_joint_model_vector_.size(); ++i)
active_joint_model_vector_[i]->getVariableDefaultPositions(values + active_joint_model_start_index_[i]);
updateMimicJoints(values);
}
void moveit::core::RobotModel::getVariableDefaultPositions(std::map<std::string, double> &values) const
{
std::vector<double> tmp(variable_count_);
getVariableDefaultPositions(&tmp[0]);
values.clear();
for (std::size_t i = 0; i < variable_names_.size(); ++i)
values[variable_names_[i]] = tmp[i];
}
void moveit::core::RobotModel::getMissingVariableNames(const std::vector<std::string> &variables,
std::vector<std::string> &missing_variables) const
{
missing_variables.clear();
std::set<std::string> keys(variables.begin(), variables.end());
for (std::size_t i = 0; i < variable_names_.size(); ++i)
if (keys.find(variable_names_[i]) == keys.end())
if (getJointOfVariable(variable_names_[i])->getMimic() == NULL)
missing_variables.push_back(variable_names_[i]);
}
int moveit::core::RobotModel::getVariableIndex(const std::string &variable) const
{
VariableIndexMap::const_iterator it = joint_variables_index_map_.find(variable);
if (it == joint_variables_index_map_.end())
throw Exception("Variable '" + variable + "' is not known to model '" + model_name_ + "'");
return it->second;
}
double moveit::core::RobotModel::getMaximumExtent(const JointBoundsVector &active_joint_bounds) const
{
double max_distance = 0.0;
for (std::size_t j = 0; j < active_joint_model_vector_.size(); ++j)
max_distance += active_joint_model_vector_[j]->getMaximumExtent(*active_joint_bounds[j]) *
active_joint_model_vector_[j]->getDistanceFactor();
return max_distance;
}
bool moveit::core::RobotModel::satisfiesPositionBounds(const double *state,
const JointBoundsVector &active_joint_bounds,
double margin) const
{
assert(active_joint_bounds.size() == active_joint_model_vector_.size());
for (std::size_t i = 0; i < active_joint_model_vector_.size(); ++i)
if (!active_joint_model_vector_[i]->satisfiesPositionBounds(state + active_joint_model_start_index_[i],
*active_joint_bounds[i], margin))
return false;
return true;
}
bool moveit::core::RobotModel::enforcePositionBounds(double *state, const JointBoundsVector &active_joint_bounds) const
{
assert(active_joint_bounds.size() == active_joint_model_vector_.size());
bool change = false;
for (std::size_t i = 0; i < active_joint_model_vector_.size(); ++i)
if (active_joint_model_vector_[i]->enforcePositionBounds(state + active_joint_model_start_index_[i],
*active_joint_bounds[i]))
change = true;
if (change)
updateMimicJoints(state);
return change;
}
double moveit::core::RobotModel::distance(const double *state1, const double *state2) const
{
double d = 0.0;
for (std::size_t i = 0; i < active_joint_model_vector_.size(); ++i)
d += active_joint_model_vector_[i]->getDistanceFactor() *
active_joint_model_vector_[i]->distance(state1 + active_joint_model_start_index_[i],
state2 + active_joint_model_start_index_[i]);
return d;
}
void moveit::core::RobotModel::interpolate(const double *from, const double *to, double t, double *state) const
{
// we interpolate values only for active joint models (non-mimic)
for (std::size_t i = 0; i < active_joint_model_vector_.size(); ++i)
active_joint_model_vector_[i]->interpolate(from + active_joint_model_start_index_[i],
to + active_joint_model_start_index_[i], t,
state + active_joint_model_start_index_[i]);
// now we update mimic as needed
updateMimicJoints(state);
}
void moveit::core::RobotModel::setKinematicsAllocators(const std::map<std::string, SolverAllocatorFn> &allocators)
{
// we first set all the "simple" allocators -- where a group has one IK solver
for (JointModelGroupMap::const_iterator it = joint_model_group_map_.begin(); it != joint_model_group_map_.end(); ++it)
{
std::map<std::string, SolverAllocatorFn>::const_iterator jt = allocators.find(it->second->getName());
if (jt != allocators.end())
{
std::pair<SolverAllocatorFn, SolverAllocatorMapFn> result;
result.first = jt->second;
it->second->setSolverAllocators(result);
}
}
// now we set compound IK solvers; we do this later because we need the index maps computed by the previous calls to
// setSolverAllocators()
for (JointModelGroupMap::const_iterator it = joint_model_group_map_.begin(); it != joint_model_group_map_.end(); ++it)
{
JointModelGroup *jmg = it->second;
std::pair<SolverAllocatorFn, SolverAllocatorMapFn> result;
std::map<std::string, SolverAllocatorFn>::const_iterator jt = allocators.find(jmg->getName());
if (jt == allocators.end())
{
// if an kinematics allocator is NOT available for this group, we try to see if we can use subgroups for IK
std::set<const JointModel *> joints;
joints.insert(jmg->getJointModels().begin(), jmg->getJointModels().end());
std::vector<const JointModelGroup *> subs;
// go through the groups that we know have IK allocators and see if they are included in the group that does not;
// if so, put that group in sub
for (std::map<std::string, SolverAllocatorFn>::const_iterator kt = allocators.begin(); kt != allocators.end();
++kt)
{
const JointModelGroup *sub = getJointModelGroup(kt->first);
if (!sub)
{
subs.clear();
break;
}
std::set<const JointModel *> sub_joints;
sub_joints.insert(sub->getJointModels().begin(), sub->getJointModels().end());
if (std::includes(joints.begin(), joints.end(), sub_joints.begin(), sub_joints.end()))
{
std::set<const JointModel *> resultj;
std::set_difference(joints.begin(), joints.end(), sub_joints.begin(), sub_joints.end(),
std::inserter(resultj, resultj.end()));
subs.push_back(sub);
joints.swap(resultj);
}
}
// if we found subgroups, pass that information to the planning group
if (!subs.empty())
{
std::stringstream ss;
for (std::size_t i = 0; i < subs.size(); ++i)
{
ss << subs[i]->getName() << " ";
result.second[subs[i]] = allocators.find(subs[i]->getName())->second;
}
logDebug("Added sub-group IK allocators for group '%s': [ %s]", jmg->getName().c_str(), ss.str().c_str());
}
jmg->setSolverAllocators(result);
}
}
}
void moveit::core::RobotModel::printModelInfo(std::ostream &out) const
{
out << "Model " << model_name_ << " in frame " << model_frame_ << ", using " << getVariableCount() << " variables"
<< std::endl;
std::ios_base::fmtflags old_flags = out.flags();
out.setf(std::ios::fixed, std::ios::floatfield);
std::streamsize old_prec = out.precision();
out.precision(5);
out << "Joints: " << std::endl;
for (std::size_t i = 0; i < joint_model_vector_.size(); ++i)
{
out << " '" << joint_model_vector_[i]->getName() << "' (" << joint_model_vector_[i]->getTypeName() << ")"
<< std::endl;
out << " * Joint Index: " << joint_model_vector_[i]->getJointIndex() << std::endl;
const std::vector<std::string> &vn = joint_model_vector_[i]->getVariableNames();
out << " * " << vn.size() << (vn.size() > 1 ? " variables:" : (vn.empty() ? " variables" : " variable:"))
<< std::endl;
int idx = joint_model_vector_[i]->getFirstVariableIndex();
for (std::vector<std::string>::const_iterator it = vn.begin(); it != vn.end(); ++it)
{
out << " * '" << *it << "', index " << idx++ << " in full state";
if (joint_model_vector_[i]->getMimic())
out << ", mimic '" << joint_model_vector_[i]->getMimic()->getName() << "'";
if (joint_model_vector_[i]->isPassive())
out << ", passive";
out << std::endl;
out << " " << joint_model_vector_[i]->getVariableBounds(*it) << std::endl;
}
}
out << std::endl;
out.precision(old_prec);
out.flags(old_flags);
out << "Links: " << std::endl;
for (std::size_t i = 0; i < link_model_vector_.size(); ++i)
{
out << " '" << link_model_vector_[i]->getName() << "' with " << link_model_vector_[i]->getShapes().size()
<< " geoms" << std::endl;
if (link_model_vector_[i]->parentJointIsFixed())
out << " * "
<< "parent joint is fixed" << std::endl;
if (link_model_vector_[i]->jointOriginTransformIsIdentity())
out << " * "
<< "joint origin transform is identity" << std::endl;
}
out << "Available groups: " << std::endl;
for (std::size_t i = 0; i < joint_model_groups_.size(); ++i)
joint_model_groups_[i]->printGroupInfo(out);
}
void moveit::core::RobotModel::computeFixedTransforms(const LinkModel *link, const Eigen::Affine3d &transform,
LinkTransformMap &associated_transforms)
{
associated_transforms[link] = transform * link->getJointOriginTransform();
for (std::size_t i = 0; i < link->getChildJointModels().size(); ++i)
if (link->getChildJointModels()[i]->getType() == JointModel::FIXED)
computeFixedTransforms(link->getChildJointModels()[i]->getChildLinkModel(),
transform * link->getJointOriginTransform(), associated_transforms);
}
| [
"zgmfx2oaf91@gmail.com"
] | zgmfx2oaf91@gmail.com |
f6233ae5c9d152c0928552fb096483c660c86283 | a0cec8074a9156eb855cdb5039193775d5108241 | /codeforces/2016-03-12-33.cpp | 24df6ab8717f0156b46cc50c4f5e2d582a99b119 | [] | no_license | Caprimulgusindicus/icpc2016 | 37eacc28973a95ca02636f3d12b4bced1722c5f3 | 87989e6c74e2402c3bc3891e128e58be12a0a0e0 | refs/heads/master | 2021-09-15T09:20:34.043369 | 2018-05-29T18:52:58 | 2018-05-29T18:52:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 384 | cpp | #include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
while(~scanf("%d%d%d%d",&sx,&sy,&ex,&ey),sx,sy,ex,ey)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
if(x1>x2)
swap(x1,x2);
if(y1>y2)
swap(y1,y2);
}
}
return 0;
}
| [
"fsszns@163.com"
] | fsszns@163.com |
d8c40730175e6d676190995500d483966ae9ad5a | 3d819577fb854bce4f09eb7ec4a0bd67e5fca4ac | /Unit1.cpp | 430f1f14531b2121fd6bda46a7054579f1fc0a55 | [] | no_license | wirlsawyer/SYGetFileVersion | f9fb8b54d8fb50eebf4106d20e48cef04d2f7aa7 | 719729e2a98a6ab9b368a2ef1622a55c54e4893b | refs/heads/master | 2021-01-17T17:43:34.333630 | 2016-10-11T06:57:59 | 2016-10-11T06:57:59 | 70,565,139 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,200 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
#include <string>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
std::wstring m_appPath = ExtractFilePath(Application->ExeName).c_str();
GetVersionWithFile( (m_appPath+L"SYGetFileVersionDemo.exe").c_str() );
}
//---------------------------------------------------------------------------
void __fastcall TForm1::GetVersionWithFile(const wchar_t *pFile)
{
DWORD verHandle = NULL;
UINT size = 0;
LPBYTE lpBuffer = NULL;
DWORD verSize = GetFileVersionInfoSize( pFile, &verHandle);
if (verSize != NULL)
{
LPSTR verData = new char[verSize];
if (GetFileVersionInfo( pFile, verHandle, verSize, verData))
{
if (VerQueryValue(verData,L"\\",(VOID FAR* FAR*)&lpBuffer,&size))
{
if (size)
{
VS_FIXEDFILEINFO *verInfo = (VS_FIXEDFILEINFO *)lpBuffer;
if (verInfo->dwSignature == 0xfeef04bd)
{
int major = HIWORD(verInfo->dwFileVersionMS);
int minor = LOWORD(verInfo->dwFileVersionMS);
int release = HIWORD(verInfo->dwFileVersionLS);
int build = LOWORD(verInfo->dwFileVersionLS);
wchar_t wszBuf[512];
memset(wszBuf, 0, sizeof(wszBuf));
wsprintf(wszBuf, L"major=%d minor=%d release=%d build=%d", major, minor, release, build);
OutputDebugString(wszBuf);
}
}
}
}
delete[] verData;
}
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{
if (OpenDialog1->Execute())
{
GetVersionWithFile(OpenDialog1->FileName.w_str() );
}
}
//---------------------------------------------------------------------------
| [
"wirlsawyer@gmail.com"
] | wirlsawyer@gmail.com |
b08a739ae9fd129c4147d485a77453c894dc3ac0 | 2f9a2b449107ee7e3bf2558a9480ba8c108f0a90 | /geometric_shapes/src/shape_extents.cpp | 098c57db48c01762f02922fc81344c2500d4dfba | [] | no_license | SiddharthGhodasara/Neo | 83d59206fd5c35dc661c0491dcdc2b7b0b0bfc67 | 9cd238ba5264fd62a99afce9fcbb6a278f562bf0 | refs/heads/master | 2022-11-30T00:12:32.923657 | 2020-08-06T07:44:25 | 2020-08-06T07:44:25 | 285,498,772 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,704 | cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <geometric_shapes/shape_extents.h>
#include <geometric_shapes/solid_primitive_dims.h>
#include <limits>
void geometric_shapes::getShapeExtents(const shape_msgs::SolidPrimitive& shape_msg, double& x_extent, double& y_extent,
double& z_extent)
{
x_extent = y_extent = z_extent = 0.0;
if (shape_msg.type == shape_msgs::SolidPrimitive::SPHERE)
{
if (shape_msg.dimensions.size() >=
geometric_shapes::SolidPrimitiveDimCount<shape_msgs::SolidPrimitive::SPHERE>::value)
x_extent = y_extent = z_extent = shape_msg.dimensions[shape_msgs::SolidPrimitive::SPHERE_RADIUS] * 2.0;
}
else if (shape_msg.type == shape_msgs::SolidPrimitive::BOX)
{
if (shape_msg.dimensions.size() >= geometric_shapes::SolidPrimitiveDimCount<shape_msgs::SolidPrimitive::BOX>::value)
{
x_extent = shape_msg.dimensions[shape_msgs::SolidPrimitive::BOX_X];
y_extent = shape_msg.dimensions[shape_msgs::SolidPrimitive::BOX_Y];
z_extent = shape_msg.dimensions[shape_msgs::SolidPrimitive::BOX_Z];
}
}
else if (shape_msg.type == shape_msgs::SolidPrimitive::CYLINDER)
{
if (shape_msg.dimensions.size() >=
geometric_shapes::SolidPrimitiveDimCount<shape_msgs::SolidPrimitive::CYLINDER>::value)
{
x_extent = y_extent = shape_msg.dimensions[shape_msgs::SolidPrimitive::CYLINDER_RADIUS] * 2.0;
z_extent = shape_msg.dimensions[shape_msgs::SolidPrimitive::CYLINDER_HEIGHT];
}
}
else if (shape_msg.type == shape_msgs::SolidPrimitive::CONE)
{
if (shape_msg.dimensions.size() >=
geometric_shapes::SolidPrimitiveDimCount<shape_msgs::SolidPrimitive::CONE>::value)
{
x_extent = y_extent = shape_msg.dimensions[shape_msgs::SolidPrimitive::CONE_RADIUS] * 2.0;
z_extent = shape_msg.dimensions[shape_msgs::SolidPrimitive::CONE_HEIGHT];
}
}
}
void geometric_shapes::getShapeExtents(const shape_msgs::Mesh& shape_msg, double& x_extent, double& y_extent,
double& z_extent)
{
x_extent = y_extent = z_extent = 0.0;
if (!shape_msg.vertices.empty())
{
double xmin = std::numeric_limits<double>::max(), ymin = std::numeric_limits<double>::max(),
zmin = std::numeric_limits<double>::max();
double xmax = -std::numeric_limits<double>::max(), ymax = -std::numeric_limits<double>::max(),
zmax = -std::numeric_limits<double>::max();
for (const geometry_msgs::Point& vertex : shape_msg.vertices)
{
if (vertex.x > xmax)
xmax = vertex.x;
if (vertex.x < xmin)
xmin = vertex.x;
if (vertex.y > ymax)
ymax = vertex.y;
if (vertex.y < ymin)
ymin = vertex.y;
if (vertex.z > zmax)
zmax = vertex.z;
if (vertex.z < zmin)
zmin = vertex.z;
}
x_extent = xmax - xmin;
y_extent = ymax - ymin;
z_extent = zmax - zmin;
}
}
| [
"sid.ghodasara@gmail.com"
] | sid.ghodasara@gmail.com |
e4dc2a1bf8b6b04294e5c0ace4c87280824ca45c | 6a04fb9005027d8eefab81abc008eaddf3d84fc1 | /UFORun/Classes/LevelHelper/LevelHelperLoader.h | 380a35c687d72f392f2a1d91d35e877e108bd90e | [
"BSD-3-Clause",
"BSD-2-Clause",
"Zlib"
] | permissive | stammen/Nextpeer-UFORUN | 9b684a13d9e74362f577674bd4954c496fcf3011 | 29e8f9ce4ce92635ed22f8a051c917cfe6e0313d | refs/heads/master | 2021-01-16T18:04:58.871918 | 2015-09-21T13:24:44 | 2015-09-21T13:24:44 | 50,257,303 | 0 | 0 | null | 2016-01-23T20:37:32 | 2016-01-23T20:37:32 | null | UTF-8 | C++ | false | false | 16,740 | h | // This file is part of LevelHelper
// http://www.levelhelper.org
//
// Created by Bogdan Vladu
// Copyright 2011 Bogdan Vladu. All rights reserved.
//
////////////////////////////////////////////////////////////////////////////////
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// This notice may not be removed or altered from any source distribution.
// By "software" the author refers to this code file and not the application
// that was used to generate this file.
// You do not have permission to use this code or any part of it if you don't
// own a license to LevelHelper application.
////////////////////////////////////////////////////////////////////////////////
//
// Version history
// ...............
// v0.1 First version for LevelHelper 1.4.9x
////////////////////////////////////////////////////////////////////////////////
#ifndef __LEVEL_HELPER_LOADER__
#define __LEVEL_HELPER_LOADER__
#include "lhConfig.h"
#include "cocos2d.h"
#include "cocoa/CCNS.h"
#include "Box2D/Box2D.h"
#include "Utilities/LHDictionary.h"
#include "Utilities/LHArray.h"
#include "Utilities/LHObject.h"
#include "Nodes/LHCustomSpriteMgr.h"
#include "Nodes/LHContactNode.h"
#include "Nodes/LHAnimationNode.h"
#include "Nodes/LHParallaxNode.h"
#include "Nodes/LHContactInfo.h"
#include "Nodes/LHNode.h"
#include "Nodes/LHLayer.h"
#include "Nodes/LHBatch.h"
#include "Nodes/LHSprite.h"
#include "Nodes/LHBezier.h"
#include "Nodes/LHJoint.h"
#include "Nodes/LHPathNode.h"
#include "CustomClasses/LHCustomClasses.h"
#include "Nodes/LHCuttingEngineMgr.h"
using namespace cocos2d;
enum LevelHelper_TAG
{
DEFAULT_TAG = 0,
GAME_LEVEL_START_BLOCK = 1,
GAME_LEVEL_START_FLAG = 2,
GAME_LEVEL_END_FLAG = 3,
GAME_LEVEL_POWERUP_BOX = 4,
NUMBER_OF_TAGS = 5
};
std::string stringFromInt(const int& i);
typedef void (CCObject::*SEL_CallFuncFloat)(float);
#define callfuncFloat_selector(_SELECTOR) (SEL_CallFuncFloat)(&_SELECTOR)
class LH_b2DestructionListener;
class LevelHelperLoader : public CCObject {
private:
LHArray* lhNodes; //array of NSDictionary //includes LHSprite, LHBezier, LHBatch, LHLayer
LHArray* lhJoints; //array of NSDictionary
LHArray* lhParallax;//array of NSDictionary
LHDictionary* wb;//world boundaries info;
LHLayer* mainLHLayer;
#if COCOS2D_VERSION >= 0x00020000
CCDictionary jointsInLevel;
CCDictionary parallaxesInLevel;
CCDictionary physicBoundariesInLevel;
#else
CCMutableDictionary<std::string> jointsInLevel; //key name - value LHJoint*
CCMutableDictionary<std::string> parallaxesInLevel; //key name - value LHParallaxNode*
CCMutableDictionary<std::string> physicBoundariesInLevel;
#endif
CCPoint safeFrame;
CCRect gameWorldRect;
CCPoint gravity;
CCLayer* cocosLayer; //weak ptr
b2World* box2dWorld; //weak ptr
LHContactNode* contactNode;
LH_b2DestructionListener* destructionListener;
CCObject* loadingProgressId;
SEL_CallFuncFloat loadingProgressSel;
bool m_isPaused;
public:
//------------------------------------------------------------------------------
LevelHelperLoader(const char* levelFile);
virtual ~LevelHelperLoader();
//------------------------------------------------------------------------------
//will call this selector during loading the level (addObjectsToWorld or addSpritesToLayer)
//the registered method needs to have this signature " void HelloWorld::loadingProgress(float percentage) "
//registration should be done like this loader->registerLoadingProgressObserver(this, callfuncFloat_selector(HelloWorld::loadingProgress));
//percentage will return a value from 0.0f to 1.0f
void registerLoadingProgressObserver(CCObject* loadingProgressObj, SEL_CallFuncFloat sel);
//LOADING
void addObjectsToWorld(b2World* world, CCLayer* cocosLayer);
LHLayer* layerWithUniqueName(const std::string& name);
LHBatch* batchWithUniqueName(const std::string& name);
LHSprite* spriteWithUniqueName(const std::string& name);
LHBezier* bezierWithUniqueName(const std::string& name);
LHJoint* jointWithUniqueName(const std::string& name);
LHParallaxNode* parallaxNodeWithUniqueName(const std::string& uniqueName);
CCArray* allLayers();
CCArray* allBatches();
CCArray* allSprites();
CCArray* allBeziers();
CCArray* allJoints();
CCArray* allParallaxes();
CCArray* layersWithTag(enum LevelHelper_TAG tag);
CCArray* batchesWithTag(enum LevelHelper_TAG tag);
CCArray* spritesWithTag(enum LevelHelper_TAG tag);
CCArray* beziersWithTag(enum LevelHelper_TAG tag);
CCArray* jointsWithTag(enum LevelHelper_TAG tag);
/*
to remove any of the LHLayer, LHBatch, LHSprite, LHBezier, LHJoint objects call
object->removeSelf();
if you retain it somewhere the object will not be release - so make sure you dont retain
any of the objects
*/
//in cases where you cannot control when the box2d world is deleted
//you may want to call this method prior releasing the LevelHelperLoader instance so that you
//dont get an crash when cocos2d removes the sprites and box2d world object is no longer alive
void removeAllPhysics();
// void addSpritesToLayer(CCLayer* cocosLayer); //NO PHYSICS
//------------------------------------------------------------------------------
LH_DEPRECATED_ATTRIBUTE static void dontStretchArtOnIpad(void);
static void dontStretchArt(void);
//UTILITIES
//The offset value is not transformed and is device dependend
//You must apply this offset based on device. To test for the device you eighter use one of the
//ios specific method to get the device or test for the winSize using CCDirector
//for iPhone5 if you want to make the level to be positioned starting from the left-centered corner rather then in the center
//the offset should be ccp(-88, 0)
//for iPad if you want to make the level to be positioned starting from the left-centered corner rather then in the center
//the offset should be ccp(-32,0);
//left-top corner should be ccp(-32,-64);
//THIS METHOD SHOULD BE USED TOGETHER WITH dontStretchArt
static void loadLevelsWithOffset(CCPoint offset);
//------------------------------------------------------------------------------
//PAUSING THE GAME
//this will pause all path movement and all parallaxes
//use [[CCDirector sharedDirector] pause]; for everything else
static bool isPaused(void);
static void setPaused(bool value); //pass true to pause, false to unpause
//this will pause only the current loader instance and not all the instances like the static methods above
bool getIsPaused(void);
void setIsPaused(bool value);
//------------------------------------------------------------------------------
//COLLISION HANDLING
//see API Documentation on the website to see how to use this
void useLevelHelperCollisionHandling(void);
void registerBeginOrEndCollisionCallbackBetweenTagA(enum LevelHelper_TAG tagA,
enum LevelHelper_TAG tagB,
CCObject* obj,
SEL_CallFuncO selector);
void cancelBeginOrEndCollisionCallbackBetweenTagA(enum LevelHelper_TAG tagA,
enum LevelHelper_TAG tagB);
void registerPreCollisionCallbackBetweenTagA(enum LevelHelper_TAG tagA,
enum LevelHelper_TAG tagB,
CCObject* obj,
SEL_CallFuncO selector);
void cancelPreCollisionCallbackBetweenTagA(enum LevelHelper_TAG tagA,
enum LevelHelper_TAG tagB);
void registerPostCollisionCallbackBetweenTagA(enum LevelHelper_TAG tagA,
enum LevelHelper_TAG tagB,
CCObject* obj,
SEL_CallFuncO selector);
void cancelPostCollisionCallbackBetweenTagA(enum LevelHelper_TAG tagA,
enum LevelHelper_TAG tagB);
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//CREATION
//SPRITE CREATION
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//name is from one of a sprite already in the level
//parent will be Main Layer
//if you use custom sprite classes - this will create a sprite of that custom registered class
//method will create custom sprite if one is register for the tag of this sprite
LHSprite* createSpriteWithUniqueName(const std::string& name);
//use this method if you want the sprite to be child of a specific node and not the main LH node
//pass nil if you dont want a parent
//method will create custom sprite if one is register for the tag of this sprite
LHSprite* createSpriteWithUniqueName(const std::string& name, CCNode* parent);
//name is from one of a sprite already in the level
//parent will be the batch node that is handling the image file of this sprite
//method will create custom sprite if one is register for the tag of this sprite
LHSprite* createBatchSpriteWithUniqueName(const std::string& name);
LHSprite* createSpriteWithName(const std::string& name,
const std::string& shSheetName,
const std::string& shFile);
//use this method if you want the sprite to be child of a specific node and not the main LH node
//pass nil if you dont want a parent
LHSprite* createSpriteWithName(const std::string& name,
const std::string& shSheetName,
const std::string& shFile,
CCNode* parent);
//use this in order to create sprites of custom types
LHSprite* createSpriteWithName(const std::string& name,
const std::string& shSheetName,
const std::string& shFile,
LevelHelper_TAG tag);
//use this method if you want the sprite to be child of a specific node and not the main LH node
//pass nil if you dont want a parent
LHSprite* createSpriteWithName(const std::string& name,
const std::string& shSheetName,
const std::string& shFile,
LevelHelper_TAG tag,
CCNode* parent);
LHSprite* createBatchSpriteWithName(const std::string& name,
const std::string& shSheetName,
const std::string& shFile);
//use this in order to create sprites of custom types
LHSprite* createBatchSpriteWithName(const std::string& name,
const std::string& shSheetName,
const std::string& shFile,
LevelHelper_TAG tag);
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// //------------------------------------------------------------------------------
// //PARALLAX
void removeParallaxNode(LHParallaxNode* node, bool removeSprites = false);
void removeAllParallaxes(bool removeSprites = false); //does not remove the sprites
// //------------------------------------------------------------------------------
// //------------------------------------------------------------------------------
//GRAVITY
bool isGravityZero(void);
void createGravity(b2World* world);
//------------------------------------------------------------------------------
// //PHYSIC BOUNDARIES
void createPhysicBoundaries(b2World* _world);
//this method should be used when using dontStretchArtOnIpad
//see api documentatin for more info
void createPhysicBoundariesNoStretching(b2World * _world);
CCRect physicBoundariesRect(void);
bool hasPhysicBoundaries(void);
b2Body* leftPhysicBoundary(void);
LHNode* leftPhysicBoundaryNode(void);
b2Body* rightPhysicBoundary(void);
LHNode* rightPhysicBoundaryNode(void);
b2Body* topPhysicBoundary(void);
LHNode* topPhysicBoundaryNode(void);
b2Body* bottomPhysicBoundary(void);
LHNode* bottomPhysicBoundaryNode(void);
void removePhysicBoundaries(void);
// //------------------------------------------------------------------------------
// //LEVEL INFO
CCSize gameScreenSize(void); //the device size set in loaded level
CCRect gameWorldSize(void); //the size of the game world
// //------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//PHYSICS
static void setMeterRatio(float ratio); //default is 32.0f
static float meterRatio(void); //same as pointsToMeterRatio - provided for simplicity as static method
static float pixelsToMeterRatio(void);
static float pointsToMeterRatio(void);
static b2Vec2 pixelToMeters(CCPoint point); //Cocos2d point to Box2d point
static b2Vec2 pointsToMeters(CCPoint point); //Cocos2d point to Box2d point
static CCPoint metersToPoints(b2Vec2 vec); //Box2d point to Cocos2d point
static CCPoint metersToPixels(b2Vec2 vec); //Box2d point to Cocos2d pixels
private:
void initObjects(void);
friend class LHJoint;
friend class LHSprite;
friend class LHBezier;
friend class LHLayer;
friend class LHCuttingEngineMgr;
void createAllNodes();
void createAllJoints();
LHParallaxNode* parallaxNodeFromDictionary(LHDictionary* parallaxDict, CCLayer*layer);
void createParallaxes();
void startAllPaths();
b2World* getPhysicsWorld();
void removeMainLayer();
void removeJoint(LHJoint* jt);
void callLoadingProgressObserverWithValue(float val);
void loadLevelHelperSceneFile(const char* levelFile,
const char* subfolder,
const char* imgFolder);
void loadLevelHelperSceneFromDictionary(const LHDictionary& levelDictionary,
const std::string& imgFolder);
void processLevelFileFromDictionary(LHDictionary* dictionary);
LHDictionary* dictionaryInfoForSpriteNodeNamed(const std::string& name, LHDictionary* dict);
static void setTouchDispatcherForBezierWithTag(LHBezier* object, int tag);
static void setTouchDispatcherForSpriteWithTag(LHSprite* object, int tag);
static void removeTouchDispatcherFromSprite(LHSprite* object);
static void removeTouchDispatcherFromBezier(LHBezier* object);
b2Body* physicBoundarieForKey(const std::string& key);
void setFixtureDefPropertiesFromDictionary(LHDictionary* spritePhysic, b2FixtureDef* shapeDef);
void createPhysicBoundariesHelper(b2World* _world,
const CCPoint& wbConv,
const CCPoint& pos_offset);
};
#endif
| [
"itamarmula@gmail.com"
] | itamarmula@gmail.com |
4b377c765228447b72d39af7d45e10b9fbe58528 | 92ebfffa3725b04b45acbe51f1f15be6f37a95be | /assignment4/2793A Simple Problem/A Simple Problem.cpp | a8cc9ffacb45919cf8e1df472153a50fc7abfe47 | [] | no_license | lyr19950720/data-structure | e12e0210da928c3f668fa76740a9b474ef180363 | c0e1d570301469e024dadfb8df5a39369ae839ca | refs/heads/master | 2020-04-02T03:50:55.299048 | 2019-01-01T15:21:52 | 2019-01-01T15:21:52 | 153,987,722 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,729 | cpp | /*#include<stdio.h>
#include<iostream>
using namespace std;
int T,N;
bool isPrime(int b) //确定一个数是素数
{
for(int j=2;j<=b/2;j++)
{
if(b%j==0)
return false;
}
return true;
}
int find(int N)
{
int r =1;
if(N==1)
return 1;
else if(isPrime(N))
return N;
else
{
for(int i=2;i<=N;)
{
if(N%i==0&&isPrime(i))//判断i是不是N的素因子
{
N/=i;
r *= i;
i++;
}
else
i++;
}
return r;//返回所有素因子的乘积
}
}
int main()
{
cin>>T; //T代表测试数据
while(T--)
{
cin>>N;
cout<<N/find(N)+1<<endl;
}
return 0;
}*/
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int t;
cin >> t;
while(t--)
{
int N;
cin >> N;
int a = 2;
int primes = 1;
int n = N;
int isfirst = true;
while(a*a <= n)
{
if(n%(a*a)==0)
{
n/=(a*a);
if(isfirst)
{
primes*=a;
isfirst = false;
}
}
else if(n%a==0)
{
n/=a;
if(isfirst)
{
primes*=a;
}
isfirst = true;
a++;
}
else
{
a++;
isfirst = true;
}
//cout << a << " " << n <<endl;
}
if(primes%n!=0)
primes*=n;
cout << N/primes + 1 <<endl;
}
} | [
"172736775@qq.com"
] | 172736775@qq.com |
b2b64851365e174f7a7ee0988dae0426e7553548 | 5447e2e8acee0343ec22eab9448f8a343e0b4370 | /itp1/reversing_numbers.cpp | 4242283bb7adf4fb4eb163225dbae145e96e1456 | [] | no_license | fakiyer/aoj | a98dee5389cc4566fa5dc3d7fe74441cbe4cdc93 | 7a383c78c5c90da49ea3e993019f55cc189ccd0d | refs/heads/master | 2021-02-10T10:06:24.086007 | 2020-03-27T12:59:37 | 2020-03-27T12:59:41 | 244,372,375 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 265 | cpp | #include<iostream>
using namespace std;
int main(){
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++){
cin >> a[i];
}
for (int i = n - 1; i >= 0; i--) {
if (i != n - 1) cout << " ";
cout << a[i];
}
cout << endl;
return 0;
}
| [
"fakiyer@gmail.com"
] | fakiyer@gmail.com |
1ae2ea3f47a8636c01411f2f51fd55685463e1d3 | 3da0e221e2e99bd1981d94c914e4efd00cd35765 | /Algorithm/3.Tham lam/Mua_luong_thuc/Mua_luong_thuc.cpp | be403b03f339e1f189fd2283bf9a87cf0c3716c0 | [] | no_license | DuyLongg/DataStructure_Algorithms_PTIT | 2d77708ce10a141657886d5e3003fdab8713ef21 | 26979498d270491f7956df9cc35e09d06cc4b3aa | refs/heads/master | 2022-11-08T01:02:29.586684 | 2020-06-27T11:45:02 | 2020-06-27T11:45:02 | 275,291,236 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 253 | cpp | #include <bits/stdc++.h>
using namespace std;
int main (){
int T; cin >> T;
while (T--){
double N,S,M; cin >> N >> S >> M;
if ((M*7) <= (N*6)) cout << ceil(S*M/N) /*+ floor (ceil((S*M/N))/7)*/ << endl;
else cout << -1 << endl;
}
return 0;
}
| [
"comprehensive1092000@gmail.com"
] | comprehensive1092000@gmail.com |
b1fb4cdecd0ec1fa3c533b5821f461908e1522df | ede70c75e39b840e5e85209ae91afb3632c4494e | /filllib/infill.h | adb462c415b4cee6e7d67f92ab2b9d5d01b64eb8 | [] | no_license | ShenRen/PainterPad2Gcode | 52cd025e39870dd6fbafd15ef03e3686cb4c5d1d | c6c59de4abd2f7083e87feac1712b85228deca07 | refs/heads/master | 2021-01-22T19:09:32.070577 | 2016-06-29T07:38:21 | 2016-06-29T07:38:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,444 | h | /** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */
#ifndef INFILL_H
#define INFILL_H
#include "polygon.h"
namespace cura {
void generateConcentricInfill(Polygons outline, Polygons& result, int inset_value);
void generateConcentricInfillDense(Polygons outline, Polygons& result, Polygons* in_between, int extrusionWidth, bool avoidOverlappingPerimeters);
void generateGridInfill(const Polygons& in_outline, int outlineOffset, Polygons& result, int extrusionWidth, int lineSpacing, int infillOverlap, double rotation);
void generateTriangleInfill(const Polygons& in_outline, int outlineOffset, Polygons& result, int extrusionWidth, int lineSpacing, int infillOverlap, double rotation);
void generateLineInfill(const Polygons& in_outline, int outlineOffset, Polygons& result, int extrusionWidth, int lineSpacing, int infillOverlap, double rotation);
void generateZigZagInfill(const Polygons& in_outline, Polygons& result, int extrusionWidth, int lineSpacing, int infillOverlap, double rotation, bool connect_zigzags, bool use_endPieces);
void generateZigZagInfill_endPieces(const Polygons& in_outline, Polygons& result, int extrusionWidth, int lineSpacing, int infillOverlap, double rotation, bool connect_zigzags);
void generateZigZagInfill_noEndPieces(const Polygons& in_outline, Polygons& result, int extrusionWidth, int lineSpacing, int infillOverlap, double rotation);
}//namespace cura
#endif//INFILL_H
| [
"805318580@qq.com"
] | 805318580@qq.com |
0580b487405482d27ff195961e21b429acb0c3ab | 006ff11fd8cfd5406c6f4318f1bafa1542095f2a | /GeneratorInterface/Hydjet2Interface/src/Hydjet2Hadronizer.cc | 84c8823e4e9daf229c790cc802a52de13bcabbf1 | [] | permissive | amkalsi/cmssw | 8ac5f481c7d7263741b5015381473811c59ac3b1 | ad0f69098dfbe449ca0570fbcf6fcebd6acc1154 | refs/heads/CMSSW_7_4_X | 2021-01-19T16:18:22.857382 | 2016-08-09T16:40:50 | 2016-08-09T16:40:50 | 262,608,661 | 0 | 0 | Apache-2.0 | 2020-05-09T16:10:07 | 2020-05-09T16:10:07 | null | UTF-8 | C++ | false | false | 49,307 | cc | /*
Hydjet2
Interface to the HYDJET++ generator, produces HepMC events
Author: Andrey Belyaev (Andrey.Belyaev@cern.ch)
Hydjet2Hadronizer is the modified InitialStateHydjet
HYDJET++
version 2.2:
InitialStateHydjet is the modified InitialStateBjorken
The high-pt part related with PYTHIA-PYQUEN is included
InitialStateBjorken (FASTMC) was used.
InitialStateBjorken
version 2.0:
Ludmila Malinina malinina@lav01.sinp.msu.ru, SINP MSU/Moscow and JINR/Dubna
Ionut Arsene i.c.arsene@fys.uio.no, Oslo University
June 2007
version 1.0:
Nikolai Amelin, Ludmila Malinina, Timur Pocheptsov (C) JINR/Dubna
amelin@sunhe.jinr.ru, malinina@sunhe.jinr.ru, pocheptsov@sunhe.jinr.ru
November. 2, 2005
*/
//expanding localy equilibated fireball with volume hadron radiation
//thermal part: Blast wave model, Bjorken-like parametrization
//high-pt: PYTHIA + jet quenching model PYQUEN
#include <TLorentzVector.h>
#include <TVector3.h>
#include <TMath.h>
#include "GeneratorInterface/Core/interface/FortranInstance.h"
#include "GeneratorInterface/Hydjet2Interface/interface/Hydjet2Hadronizer.h"
#include "GeneratorInterface/Hydjet2Interface/interface/RandArrayFunction.h"
#include "GeneratorInterface/Hydjet2Interface/interface/HadronDecayer.h"
#include "GeneratorInterface/Hydjet2Interface/interface/GrandCanonical.h"
#include "GeneratorInterface/Hydjet2Interface/interface/StrangePotential.h"
#include "GeneratorInterface/Hydjet2Interface/interface/EquationSolver.h"
#include "GeneratorInterface/Hydjet2Interface/interface/Particle.h"
#include "GeneratorInterface/Hydjet2Interface/interface/ParticlePDG.h"
#include "GeneratorInterface/Hydjet2Interface/interface/UKUtility.h"
#include <iostream>
#include <fstream>
#include <cmath>
#include "boost/lexical_cast.hpp"
#include "FWCore/Concurrency/interface/SharedResourceNames.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/Run.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Utilities/interface/EDMException.h"
#include "GeneratorInterface/Pythia6Interface/interface/Pythia6Declarations.h"
#include "GeneratorInterface/Pythia6Interface/interface/Pythia6Service.h"
#include "HepMC/PythiaWrapper6_4.h"
#include "HepMC/GenEvent.h"
#include "HepMC/HeavyIon.h"
#include "HepMC/SimpleVector.h"
#include "SimDataFormats/GeneratorProducts/interface/HepMCProduct.h"
#include "SimDataFormats/GeneratorProducts/interface/GenEventInfoProduct.h"
#include "SimDataFormats/GeneratorProducts/interface/GenRunInfoProduct.h"
#include "SimDataFormats/HiGenData/interface/GenHIEvent.h"
#include "GeneratorInterface/Hydjet2Interface/interface/HYJET_COMMONS.h"
extern "C" void hyevnt_();
extern "C" void myini_();
extern HYIPARCommon HYIPAR;
extern HYFPARCommon HYFPAR;
extern HYJPARCommon HYJPAR;
extern HYPARTCommon HYPART;
using namespace edm;
using namespace std;
using namespace gen;
TString RunInputHYDJETstr;
// definition of the static member fLastIndex
int Particle::fLastIndex;
bool ev=0;
namespace {
int convertStatus(int st){
if(st<= 0) return 0;
if(st<=10) return 1;
if(st<=20) return 2;
if(st<=30) return 3;
else return st;
}
}
const std::vector<std::string> Hydjet2Hadronizer::theSharedResources = { edm::SharedResourceNames::kPythia6, gen::FortranInstance::kFortranInstance };
//____________________________________________________________________________________________
Hydjet2Hadronizer::Hydjet2Hadronizer(const edm::ParameterSet& pset):
BaseHadronizer(pset),
fSqrtS(pset.getParameter<double>("fSqrtS")), // C.m.s. energy per nucleon pair
fAw(pset.getParameter<double>("fAw")), // Atomic weigth of nuclei, fAw
fIfb(pset.getParameter<int>("fIfb")), // Flag of type of centrality generation, fBfix (=0 is fixed by fBfix, >0 distributed [fBfmin, fBmax])
fBmin(pset.getParameter<double>("fBmin")), // Minimum impact parameter in units of nuclear radius, fBmin
fBmax(pset.getParameter<double>("fBmax")), // Maximum impact parameter in units of nuclear radius, fBmax
fBfix(pset.getParameter<double>("fBfix")), // Fixed impact parameter in units of nuclear radius, fBfix
fT(pset.getParameter<double>("fT")), // Temperature at chemical freeze-out, fT [GeV]
fMuB(pset.getParameter<double>("fMuB")), // Chemical baryon potential per unit charge, fMuB [GeV]
fMuS(pset.getParameter<double>("fMuS")), // Chemical strangeness potential per unit charge, fMuS [GeV]
fMuC(pset.getParameter<double>("fMuC")), // Chemical charm potential per unit charge, fMuC [GeV] (used if charm production is turned on)
fMuI3(pset.getParameter<double>("fMuI3")), // Chemical isospin potential per unit charge, fMuI3 [GeV]
fThFO(pset.getParameter<double>("fThFO")), // Temperature at thermal freeze-out, fThFO [GeV]
fMu_th_pip(pset.getParameter<double>("fMu_th_pip")),// Chemical potential of pi+ at thermal freeze-out, fMu_th_pip [GeV]
fTau(pset.getParameter<double>("fTau")), // Proper time proper at thermal freeze-out for central collisions, fTau [fm/c]
fSigmaTau(pset.getParameter<double>("fSigmaTau")), // Duration of emission at thermal freeze-out for central collisions, fSigmaTau [fm/c]
fR(pset.getParameter<double>("fR")), // Maximal transverse radius at thermal freeze-out for central collisions, fR [fm]
fYlmax(pset.getParameter<double>("fYlmax")), // Maximal longitudinal flow rapidity at thermal freeze-out, fYlmax
fUmax(pset.getParameter<double>("fUmax")), // Maximal transverse flow rapidity at thermal freeze-out for central collisions, fUmax
fDelta(pset.getParameter<double>("fDelta")), // Momentum azimuthal anizotropy parameter at thermal freeze-out, fDelta
fEpsilon(pset.getParameter<double>("fEpsilon")), // Spatial azimuthal anisotropy parameter at thermal freeze-out, fEpsilon
fIfDeltaEpsilon(pset.getParameter<double>("fIfDeltaEpsilon")), // Flag to specify fDelta and fEpsilon values, fIfDeltaEpsilon (=0 user's ones, >=1 calculated)
fDecay(pset.getParameter<int>("fDecay")), // Flag to switch on/off hadron decays, fDecay (=0 decays off, >=1 decays on)
fWeakDecay(pset.getParameter<double>("fWeakDecay")),// Low decay width threshold fWeakDecay[GeV]: width<fWeakDecay decay off, width>=fDecayWidth decay on; can be used to switch off weak decays
fEtaType(pset.getParameter<double>("fEtaType")), // Flag to choose longitudinal flow rapidity distribution, fEtaType (=0 uniform, >0 Gaussian with the dispersion Ylmax)
fTMuType(pset.getParameter<double>("fTMuType")), // Flag to use calculated T_ch, mu_B and mu_S as a function of fSqrtS, fTMuType (=0 user's ones, >0 calculated)
fCorrS(pset.getParameter<double>("fCorrS")), // Strangeness supression factor gamma_s with fCorrS value (0<fCorrS <=1, if fCorrS <= 0 then it is calculated)
fCharmProd(pset.getParameter<int>("fCharmProd")), // Flag to include thermal charm production, fCharmProd (=0 no charm production, >=1 charm production)
fCorrC(pset.getParameter<double>("fCorrC")), // Charmness enhancement factor gamma_c with fCorrC value (fCorrC >0, if fCorrC<0 then it is calculated)
fNhsel(pset.getParameter<int>("fNhsel")), //Flag to include jet (J)/jet quenching (JQ) and hydro (H) state production, fNhsel (0 H on & J off, 1 H/J on & JQ off, 2 H/J/HQ on, 3 J on & H/JQ off, 4 H off & J/JQ on)
fPyhist(pset.getParameter<int>("fPyhist")), // Flag to suppress the output of particle history from PYTHIA, fPyhist (=1 only final state particles; =0 full particle history from PYTHIA)
fIshad(pset.getParameter<int>("fIshad")), // Flag to switch on/off nuclear shadowing, fIshad (0 shadowing off, 1 shadowing on)
fPtmin(pset.getParameter<double>("fPtmin")), // Minimal pt of parton-parton scattering in PYTHIA event, fPtmin [GeV/c]
fT0(pset.getParameter<double>("fT0")), // Initial QGP temperature for central Pb+Pb collisions in mid-rapidity, fT0 [GeV]
fTau0(pset.getParameter<double>("fTau0")), // Proper QGP formation time in fm/c, fTau0 (0.01<fTau0<10)
fNf(pset.getParameter<int>("fNf")), // Number of active quark flavours in QGP, fNf (0, 1, 2 or 3)
fIenglu(pset.getParameter<int>("fIenglu")), // Flag to fix type of partonic energy loss, fIenglu (0 radiative and collisional loss, 1 radiative loss only, 2 collisional loss only)
fIanglu(pset.getParameter<int>("fIanglu")), // Flag to fix type of angular distribution of in-medium emitted gluons, fIanglu (0 small-angular, 1 wide-angular, 2 collinear).
embedding_(pset.getParameter<bool>("embeddingMode")),
rotate_(pset.getParameter<bool>("rotateEventPlane")),
evt(0),
nsub_(0),
nhard_(0),
nsoft_(0),
phi0_(0.),
sinphi0_(0.),
cosphi0_(1.),
pythia6Service_(new Pythia6Service(pset))
{
// constructor
// PYLIST Verbosity Level
// Valid PYLIST arguments are: 1, 2, 3, 5, 7, 11, 12, 13
pythiaPylistVerbosity_ = pset.getUntrackedParameter<int>("pythiaPylistVerbosity",0);
LogDebug("PYLISTverbosity") << "Pythia PYLIST verbosity level = " << pythiaPylistVerbosity_;
//Max number of events printed on verbosity level
maxEventsToPrint_ = pset.getUntrackedParameter<int>("maxEventsToPrint",0);
LogDebug("Events2Print") << "Number of events to be printed = " << maxEventsToPrint_;
if(embedding_) src_ = pset.getParameter<edm::InputTag>("backgroundLabel");
}
//__________________________________________________________________________________________
Hydjet2Hadronizer::~Hydjet2Hadronizer(){
// destructor
call_pystat(1);
delete pythia6Service_;
}
//_____________________________________________________________________
void Hydjet2Hadronizer::doSetRandomEngine(CLHEP::HepRandomEngine* v)
{
pythia6Service_->setRandomEngine(v);
hjRandomEngine = v;
}
//______________________________________________________________________________________________________
bool Hydjet2Hadronizer::readSettings( int ) {
Pythia6Service::InstanceWrapper guard(pythia6Service_);
pythia6Service_->setGeneralParams();
SERVICE.iseed_fromC=hjRandomEngine->CLHEP::HepRandomEngine::getSeed();
LogInfo("Hydjet2Hadronizer|GenSeed") << "Seed for random number generation: "<<hjRandomEngine->CLHEP::HepRandomEngine::getSeed();
fNPartTypes = 0; //counter of hadron species
return kTRUE;
}
//______________________________________________________________________________________________________
bool Hydjet2Hadronizer::initializeForInternalPartons(){
Pythia6Service::InstanceWrapper guard(pythia6Service_);
// the input impact parameter (bxx_) is in [fm]; transform in [fm/RA] for hydjet usage
const float ra = nuclear_radius();
LogInfo("Hydjet2Hadronizer|RAScaling")<<"Nuclear radius(RA) = "<<ra;
fBmin /= ra;
fBmax /= ra;
fBfix /= ra;
//check and redefine input parameters
if(fTMuType>0 && fSqrtS > 2.24) {
if(fSqrtS < 2.24){
LogError("Hydjet2Hadronizer|sqrtS") << "SqrtS<2.24 not allowed with fTMuType>0";
return 0;
}
//sqrt(s) = 2.24 ==> T_kin = 0.8 GeV
//see J. Cleymans, H. Oeschler, K. Redlich,S. Wheaton, Phys Rev. C73 034905 (2006)
fMuB = 1.308/(1. + fSqrtS*0.273);
fT = 0.166 - 0.139*fMuB*fMuB - 0.053*fMuB*fMuB*fMuB*fMuB;
fMuI3 = 0.;
fMuS = 0.;
//create strange potential object and set strangeness density 0
NAStrangePotential* psp = new NAStrangePotential(0., fDatabase);
psp->SetBaryonPotential(fMuB);
psp->SetTemperature(fT);
//compute strangeness potential
if(fMuB > 0.01) fMuS = psp->CalculateStrangePotential();
LogInfo("Hydjet2Hadronizer|Strange") << "fMuS = " << fMuS;
//if user choose fYlmax larger then allowed by kinematics at the specified beam energy sqrt(s)
if(fYlmax > TMath::Log(fSqrtS/0.94)){
LogError("Hydjet2Hadronizer|Ylmax") << "fYlmax more then TMath::Log(fSqrtS vs 0.94)!!! ";
return 0;
}
if(fCorrS <= 0.) {
//see F. Becattini, J. Mannien, M. Gazdzicki, Phys Rev. C73 044905 (2006)
fCorrS = 1. - 0.386* TMath::Exp(-1.23*fT/fMuB);
LogInfo("Hydjet2Hadronizer|Strange") << "The phenomenological f-la F. Becattini et al. PRC73 044905 (2006) for CorrS was used."<<endl
<<"Strangeness suppression parameter = "<<fCorrS;
}
LogInfo("Hydjet2Hadronizer|Strange") << "The phenomenological f-la J. Cleymans et al. PRC73 034905 (2006) for Tch mu_B was used." << endl
<<"The simulation will be done with the calculated parameters:" << endl
<<"Baryon chemical potential = "<<fMuB<< " [GeV]" << endl
<<"Strangeness chemical potential = "<<fMuS<< " [GeV]" << endl
<<"Isospin chemical potential = "<<fMuI3<< " [GeV]" << endl
<<"Strangeness suppression parameter = "<<fCorrS << endl
<<"Eta_max = "<<fYlmax;
}
LogInfo("Hydjet2Hadronizer|Param") << "Used eta_max = "<<fYlmax<< endl
<<"maximal allowed eta_max TMath::Log(fSqrtS/0.94)= "<<TMath::Log(fSqrtS/0.94);
//initialisation of high-pt part
HYJPAR.nhsel = fNhsel;
HYJPAR.ptmin = fPtmin;
HYJPAR.ishad = fIshad;
HYJPAR.iPyhist = fPyhist;
HYIPAR.bminh = fBmin;
HYIPAR.bmaxh = fBmax;
HYIPAR.AW = fAw;
HYPYIN.ifb = fIfb;
HYPYIN.bfix = fBfix;
HYPYIN.ene = fSqrtS;
PYQPAR.T0 = fT0;
PYQPAR.tau0 = fTau0;
PYQPAR.nf = fNf;
PYQPAR.ienglu = fIenglu;
PYQPAR.ianglu = fIanglu;
myini_();
// calculation of multiplicities of different particle species
// according to the grand canonical approach
GrandCanonical gc(15, fT, fMuB, fMuS, fMuI3, fMuC);
GrandCanonical gc_ch(15, fT, fMuB, fMuS, fMuI3, fMuC);
GrandCanonical gc_pi_th(15, fThFO, 0., 0., fMu_th_pip, fMuC);
GrandCanonical gc_th_0(15, fThFO, 0., 0., 0., 0.);
// std::ofstream outMult("densities.txt");
// outMult<<"encoding particle density chemical potential "<<std::endl;
double Nocth=0; //open charm
double NJPsith=0; //JPsi
//effective volume for central
double dYl= 2 * fYlmax; //uniform distr. [-Ylmax; Ylmax]
if (fEtaType >0) dYl = TMath::Sqrt(2 * TMath::Pi()) * fYlmax ; //Gaussian distr.
fVolEff = 2 * TMath::Pi() * fTau * dYl * (fR * fR)/TMath::Power((fUmax),2) *
((fUmax)*TMath::SinH((fUmax))-TMath::CosH((fUmax))+ 1);
LogInfo("Hydjet2Hadronizer|Param") << "central Effective volume = " << fVolEff << " [fm^3]";
double particleDensity_pi_ch=0;
double particleDensity_pi_th=0;
// double particleDensity_th_0=0;
if(fThFO != fT && fThFO > 0){
GrandCanonical gc_ch(15, fT, fMuB, fMuS, fMuI3, fMuC);
GrandCanonical gc_pi_th(15, fThFO, 0., 0., fMu_th_pip, fMuC);
GrandCanonical gc_th_0(15, fThFO, 0., 0., 0., 0.);
particleDensity_pi_ch = gc_ch.ParticleNumberDensity(fDatabase->GetPDGParticle(211));
particleDensity_pi_th = gc_pi_th.ParticleNumberDensity(fDatabase->GetPDGParticle(211));
}
for(int particleIndex = 0; particleIndex < fDatabase->GetNParticles(); particleIndex++) {
ParticlePDG *currParticle = fDatabase->GetPDGParticleByIndex(particleIndex);
int encoding = currParticle->GetPDG();
//strangeness supression
double gammaS = 1;
int S = int(currParticle->GetStrangeness());
if(encoding == 333)S = 2;
if(fCorrS < 1. && S != 0)gammaS = TMath::Power(fCorrS,-TMath::Abs(S));
//average densities
double particleDensity = gc.ParticleNumberDensity(currParticle)/gammaS;
//compute chemical potential for single f.o. mu==mu_ch
double mu = fMuB * int(currParticle->GetBaryonNumber()) +
fMuS * int(currParticle->GetStrangeness()) +
fMuI3 * int(currParticle->GetElectricCharge()) +
fMuC * int(currParticle->GetCharmness());
//thermal f.o.
if(fThFO != fT && fThFO > 0){
double particleDensity_ch = gc_ch.ParticleNumberDensity(currParticle);
double particleDensity_th_0 = gc_th_0.ParticleNumberDensity(currParticle);
double numb_dens_bolt = particleDensity_pi_th*particleDensity_ch/particleDensity_pi_ch;
mu = fThFO*TMath::Log(numb_dens_bolt/particleDensity_th_0);
if(abs(encoding)==211 || encoding==111)mu= fMu_th_pip;
particleDensity = numb_dens_bolt;
}
// set particle densities to zero for some particle codes
// pythia quark codes
if(abs(encoding)<=9) {
particleDensity=0;
}
// leptons
if(abs(encoding)>10 && abs(encoding)<19) {
particleDensity=0;
}
// exchange bosons
if(abs(encoding)>20 && abs(encoding)<30) {
particleDensity=0;
}
// pythia special codes (e.g. strings, clusters ...)
if(abs(encoding)>80 && abs(encoding)<100) {
particleDensity=0;
}
// pythia di-quark codes
// Note: in PYTHIA all diquark codes have the tens digits equal to zero
if(abs(encoding)>1000 && abs(encoding)<6000) {
int tens = ((abs(encoding)-(abs(encoding)%10))/10)%10;
if(tens==0) { // its a diquark;
particleDensity=0;
}
}
// K0S and K0L
if(abs(encoding)==130 || abs(encoding)==310) {
particleDensity=0;
}
// charmed particles
if(encoding==443)NJPsith=particleDensity*fVolEff/dYl;
// We generate thermo-statistically only J/psi(443), D_+(411), D_-(-411), D_0(421),
//Dbar_0(-421), D1_+(413), D1_-(-413), D1_0(423), D1bar_0(-423)
//Dcs(431) Lambdac(4122)
if(currParticle->GetCharmQNumber()!=0 || currParticle->GetCharmAQNumber()!=0) {
//ml if(abs(encoding)!=443 &&
//ml abs(encoding)!=411 && abs(encoding)!=421 &&
//ml abs(encoding)!=413 && abs(encoding)!=423 && abs(encoding)!=4122 && abs(encoding)!=431) {
//ml particleDensity=0; }
if(abs(encoding)==441 ||
abs(encoding)==10441 || abs(encoding)==10443 ||
abs(encoding)==20443 || abs(encoding)==445 || abs(encoding)==4232 || abs(encoding)==4322 ||
abs(encoding)==4132 || abs(encoding)==4312 || abs(encoding)==4324 || abs(encoding)==4314 ||
abs(encoding)==4332 || abs(encoding)==4334
) {
particleDensity=0; }
else
{
if(abs(encoding)!=443){ //only open charm
Nocth=Nocth+particleDensity*fVolEff/dYl;
LogInfo("Hydjet2Hadronizer|Charam") << encoding<<" Nochth "<<Nocth;
// particleDensity=particleDensity*fCorrC;
// if(abs(encoding)==443)particleDensity=particleDensity*fCorrC;
}
}
}
// bottom mesons
if((abs(encoding)>500 && abs(encoding)<600) ||
(abs(encoding)>10500 && abs(encoding)<10600) ||
(abs(encoding)>20500 && abs(encoding)<20600) ||
(abs(encoding)>100500 && abs(encoding)<100600)) {
particleDensity=0;
}
// bottom baryons
if(abs(encoding)>5000 && abs(encoding)<6000) {
particleDensity=0;
}
////////////////////////////////////////////////////////////////////////////////////////
if(particleDensity > 0.) {
fPartEnc[fNPartTypes] = encoding;
fPartMult[2 * fNPartTypes] = particleDensity;
fPartMu[2 * fNPartTypes] = mu;
++fNPartTypes;
if(fNPartTypes > 1000)
LogError("Hydjet2Hadronizer") << "fNPartTypes is too large" << fNPartTypes;
//outMult<<encoding<<" "<<particleDensity*fVolEff/dYl <<" "<<mu<<std::endl;
}
}
//put open charm number and cc number in Params
fNocth = Nocth;
fNccth = NJPsith;
return kTRUE;
}
//__________________________________________________________________________________________
bool Hydjet2Hadronizer::generatePartonsAndHadronize(){
Pythia6Service::InstanceWrapper guard(pythia6Service_);
// Initialize the static "last index variable"
Particle::InitIndexing();
//----- high-pt part------------------------------
TLorentzVector partJMom, partJPos, zeroVec;
// generate single event
if(embedding_){
fIfb = 0;
const edm::Event& e = getEDMEvent();
Handle<HepMCProduct> input;
e.getByLabel(src_,input);
const HepMC::GenEvent * inev = input->GetEvent();
const HepMC::HeavyIon* hi = inev->heavy_ion();
if(hi){
fBfix = hi->impact_parameter();
phi0_ = hi->event_plane_angle();
sinphi0_ = sin(phi0_);
cosphi0_ = cos(phi0_);
}else{
LogWarning("EventEmbedding")<<"Background event does not have heavy ion record!";
}
}else if(rotate_) rotateEvtPlane();
nsoft_ = 0;
nhard_ = 0;
/*
edm::LogInfo("HYDJET2mode") << "##### HYDJET2 fNhsel = " << fNhsel;
edm::LogInfo("HYDJET2fpart") << "##### HYDJET2 fpart = " << hyflow.fpart;??
edm::LogInfo("HYDJET2tf") << "##### HYDJET2 hadron freez-out temp, Tf = " << hyflow.Tf;??
edm::LogInfo("HYDJET2tf") << "##### HYDJET2 hadron freez-out temp, Tf = " << hyflow.Tf;??
edm::LogInfo("HYDJET2inTemp") << "##### HYDJET2: QGP init temperature, fT0 ="<<fT0;
edm::LogInfo("HYDJET2inTau") << "##### HYDJET2: QGP formation time, fTau0 ="<<fTau0;
*/
// generate a HYDJET event
int ntry = 0;
while(nsoft_ == 0 && nhard_ == 0){
if(ntry > 100){
LogError("Hydjet2EmptyEvent") << "##### HYDJET2: No Particles generated, Number of tries ="<<ntry;
// Throw an exception. Use the EventCorruption exception since it maps onto SkipEvent
// which is what we want to do here.
std::ostringstream sstr;
sstr << "Hydjet2HadronizerProducer: No particles generated after " << ntry << " tries.\n";
edm::Exception except(edm::errors::EventCorruption, sstr.str());
throw except;
} else {
//generate non-equilibrated part event
hyevnt_();
////////-------------HARD & SOFT particle list ----------begin------- //////////////// --->to separete func.
if(fNhsel != 0){
//get number of particles in jets
int numbJetPart = HYPART.njp;
for(int i = 0; i <numbJetPart; ++i) {
int pythiaStatus = int(HYPART.ppart[i][0]); // PYTHIA status code
int pdg = int(HYPART.ppart[i][1]); // PYTHIA species code
double px = HYPART.ppart[i][2]; // px
double py = HYPART.ppart[i][3]; // py
double pz = HYPART.ppart[i][4]; // pz
double e = HYPART.ppart[i][5]; // E
double vx = HYPART.ppart[i][6]; // x
double vy = HYPART.ppart[i][7]; // y
double vz = HYPART.ppart[i][8]; // z
double vt = HYPART.ppart[i][9]; // t
// particle line number in pythia are 1 based while we use a 0 based numbering
int mother_index = int(HYPART.ppart[i][10])-1; //line number of parent particle
int daughter_index1 = int(HYPART.ppart[i][11])-1; //line number of first daughter
int daughter_index2 = int(HYPART.ppart[i][12])-1; //line number of last daughter
// For status codes 3, 13, 14 the first and last daughter indexes have a different meaning
// used for color flow in PYTHIA. So these indexes will be reset to zero.
if(TMath::Abs(daughter_index1)>numbJetPart || TMath::Abs(daughter_index2)>numbJetPart ||
TMath::Abs(daughter_index1)>TMath::Abs(daughter_index2)) {
daughter_index1 = -1;
daughter_index2 = -1;
}
ParticlePDG *partDef = fDatabase->GetPDGParticle(pdg);
int type=1; //from jet
if(partDef) {
int motherPdg = int(HYPART.ppart[mother_index][1]);
if(motherPdg==0) motherPdg = -1;
partJMom.SetXYZT(px, py, pz, e);
partJPos.SetXYZT(vx, vy, vz, vt);
Particle particle(partDef, partJPos, partJMom, 0, 0, type, motherPdg, zeroVec, zeroVec);
int index = particle.SetIndex();
if(index!=i) {
LogWarning("Hydjet2Hadronizer") << " Allocated HYDJET++ index is not synchronized with the PYTHIA index!" << endl
<< " Collision history information is destroyed! It happens when a PYTHIA code is not" << endl
<< " implemented in HYDJET++ particle list particles.data! Check it out!";
}
particle.SetPythiaStatusCode(pythiaStatus);
particle.SetMother(mother_index);
particle.SetFirstDaughterIndex(daughter_index1);
particle.SetLastDaughterIndex(daughter_index2);
if(pythiaStatus!=1) particle.SetDecayed();
allocator.AddParticle(particle, source);
}
else {
LogWarning("Hydjet2Hadronizer") << " PYTHIA particle of specie " << pdg << " is not in HYDJET++ particle list" << endl
<<" Please define it in particles.data, otherwise the history information will be de-synchronized and lost!";
}
}
} //nhsel !=0 not only hydro!
//----------HYDRO part--------------------------------------
// get impact parameter
double impactParameter = HYFPAR.bgen;
// Sergey psiforv3
double psiforv3 = 0.; //AS-ML Nov2012 epsilon3 //
double e3 = (0.2/5.5)*TMath::Power(impactParameter,1./3.);
psiforv3 = TMath::TwoPi() * (-0.5 + CLHEP::RandFlat::shoot(hjRandomEngine)) / 3.;
SERVICEEV.psiv3 = -psiforv3;
if(fNhsel < 3){
const double weightMax = 2*TMath::CosH(fUmax);
const int nBins = 100;
double probList[nBins];
RandArrayFunction arrayFunctDistE(nBins);
RandArrayFunction arrayFunctDistR(nBins);
TLorentzVector partPos, partMom, n1, p0;
TVector3 vec3;
const TLorentzVector zeroVec;
//set maximal hadron energy
const double eMax = 5.;
//-------------------------------------
// get impact parameter
double Delta =fDelta;
double Epsilon =fEpsilon;
if(fIfDeltaEpsilon>0){
double Epsilon0 = 0.5*impactParameter; //e0=b/2Ra
double coeff = (HYIPAR.RA/fR)/12.;//phenomenological coefficient
Epsilon = Epsilon0 * coeff;
double C=5.6;
double A = C*Epsilon*(1-Epsilon*Epsilon);
if(TMath::Abs(Epsilon)<0.0001 || TMath::Abs(A)<0.0001 )Delta=0.0;
if(TMath::Abs(Epsilon)>0.0001 && TMath::Abs(A)>0.0001)Delta = 0.5*(TMath::Sqrt(1+4*A*(Epsilon+A))-1)/A;
}
//effective volume for central
double dYl= 2 * fYlmax; //uniform distr. [-Ylmax; Ylmax]
if (fEtaType >0) dYl = TMath::Sqrt(2 * TMath::Pi()) * fYlmax ; //Gaussian distr.
double VolEffcent = 2 * TMath::Pi() * fTau * dYl * (fR * fR)/TMath::Power((fUmax),2) * ((fUmax)*TMath::SinH((fUmax))-TMath::CosH((fUmax))+ 1);
//effective volume for non-central Simpson2
double VolEffnoncent = fTau * dYl * SimpsonIntegrator2(0., 2.*TMath::Pi(), Epsilon, Delta);
fVolEff = VolEffcent * HYFPAR.npart/HYFPAR.npart0;
double coeff_RB = TMath::Sqrt(VolEffcent * HYFPAR.npart/HYFPAR.npart0/VolEffnoncent);
double coeff_R1 = HYFPAR.npart/HYFPAR.npart0;
coeff_R1 = TMath::Power(coeff_R1, 0.333333);
double Veff=fVolEff;
//------------------------------------
//cycle on particles types
double Nbcol = HYFPAR.nbcol;
double NccNN = SERVICE.charm;
double Ncc = Nbcol * NccNN/dYl;
double Nocth = fNocth;
double NJPsith = fNccth;
double gammaC=1.0;
if(fCorrC<=0){
gammaC=CharmEnhancementFactor(Ncc, Nocth, NJPsith, 0.001);
}else{
gammaC=fCorrC;
}
LogInfo("Hydjet2Hadronizer|Param") <<" gammaC = " <<gammaC;
for(int i = 0; i < fNPartTypes; ++i) {
double Mparam = fPartMult[2 * i] * Veff;
const int encoding = fPartEnc[i];
//ml if(abs(encoding)==443)Mparam = Mparam * gammaC * gammaC;
//ml if(abs(encoding)==411 || abs(encoding)==421 ||abs(encoding)==413 || abs(encoding)==423
//ml || abs(encoding)==4122 || abs(encoding)==431)
ParticlePDG *partDef0 = fDatabase->GetPDGParticle(encoding);
if(partDef0->GetCharmQNumber()!=0 || partDef0->GetCharmAQNumber()!=0)Mparam = Mparam * gammaC;
if(abs(encoding)==443)Mparam = Mparam * gammaC;
LogInfo("Hydjet2Hadronizer|Param") <<encoding<<" "<<Mparam/dYl;
int multiplicity = CLHEP::RandPoisson::shoot(hjRandomEngine, Mparam);
LogInfo("Hydjet2Hadronizer|Param") <<"specie: " << encoding << "; average mult: = " << Mparam << "; multiplicity = " << multiplicity;
if (multiplicity > 0) {
ParticlePDG *partDef = fDatabase->GetPDGParticle(encoding);
if(!partDef) {
LogError("Hydjet2Hadronizer") << "No particle with encoding "<< encoding;
continue;
}
if(fCharmProd<=0 && (partDef->GetCharmQNumber()!=0 || partDef->GetCharmAQNumber()!=0)){
LogInfo("Hydjet2Hadronizer|Param") <<"statistical charmed particle not allowed ! "<<encoding;
continue;
}
if(partDef->GetCharmQNumber()!=0 || partDef->GetCharmAQNumber()!=0)
LogInfo("Hydjet2Hadronizer|Param") <<" charm pdg generated "<< encoding;
//compute chemical potential for single f.o. mu==mu_ch
//compute chemical potential for thermal f.o.
double mu = fPartMu[2 * i];
//choose Bose-Einstein or Fermi-Dirac statistics
const double d = !(int(2*partDef->GetSpin()) & 1) ? -1 : 1;
const double mass = partDef->GetMass();
//prepare histogram to sample hadron energy:
double h = (eMax - mass) / nBins;
double x = mass + 0.5 * h;
int i;
for(i = 0; i < nBins; ++i) {
if(x>=mu && fThFO>0)probList[i] = x * TMath::Sqrt(x * x - mass * mass) / (TMath::Exp((x - mu) / (fThFO)) + d);
if(x>=mu && fThFO<=0)probList[i] = x * TMath::Sqrt(x * x - mass * mass) / (TMath::Exp((x - mu) / (fT)) + d);
if(x<mu)probList[i] = 0.;
x += h;
}
arrayFunctDistE.PrepareTable(probList);
//prepare histogram to sample hadron transverse radius:
h = (fR) / nBins;
x = 0.5 * h;
double param = (fUmax) / (fR);
for (i = 0; i < nBins; ++i) {
probList[i] = x * TMath::CosH(param*x);
x += h;
}
arrayFunctDistR.PrepareTable(probList);
//loop over hadrons, assign hadron coordinates and momenta
double weight = 0., yy = 0., px0 = 0., py0 = 0., pz0 = 0.;
double e = 0., x0 = 0., y0 = 0., z0 = 0., t0 = 0., etaF = 0.;
double r, RB, phiF;
RB = fR * coeff_RB * coeff_R1 * TMath::Sqrt((1+e3)/(1-e3));
for(int j = 0; j < multiplicity; ++j) {
do {
fEtaType <=0 ? etaF = fYlmax * (2. * CLHEP::RandFlat::shoot(hjRandomEngine) - 1.) : etaF = (fYlmax) * (CLHEP::RandGauss::shoot(hjRandomEngine));
n1.SetXYZT(0.,0.,TMath::SinH(etaF),TMath::CosH(etaF));
if(TMath::Abs(etaF)>5.)continue;
//old
//double RBold = fR * TMath::Sqrt(1-fEpsilon);
//RB = fR * coeff_RB * coeff_R1;
//double impactParameter =HYFPAR.bgen;
//double e0 = 0.5*impactParameter;
//double RBold1 = fR * TMath::Sqrt(1-e0);
double rho = TMath::Sqrt(CLHEP::RandFlat::shoot(hjRandomEngine));
double phi = TMath::TwoPi() * CLHEP::RandFlat::shoot(hjRandomEngine);
double Rx = TMath::Sqrt(1-Epsilon)*RB;
double Ry = TMath::Sqrt(1+Epsilon)*RB;
x0 = Rx * rho * TMath::Cos(phi);
y0 = Ry * rho * TMath::Sin(phi);
r = TMath::Sqrt(x0*x0+y0*y0);
phiF = TMath::Abs(TMath::ATan(y0/x0));
if(x0<0&&y0>0)phiF = TMath::Pi()-phiF;
if(x0<0&&y0<0)phiF = TMath::Pi()+phiF;
if(x0>0&&y0<0)phiF = 2.*TMath::Pi()-phiF;
//new Nov2012 AS-ML
if(r>RB*(1+e3*TMath::Cos(3*(phiF+psiforv3)))/(1+e3))continue;
//proper time with emission duration
double tau = coeff_R1 * fTau + sqrt(2.) * fSigmaTau * coeff_R1 * (CLHEP::RandGauss::shoot(hjRandomEngine));
z0 = tau * TMath::SinH(etaF);
t0 = tau * TMath::CosH(etaF);
double rhou = fUmax * r / RB;
double rhou3 = 0.063*TMath::Sqrt((0.5*impactParameter)/0.67);
double rhou4 = 0.023*((0.5*impactParameter)/0.67);
double rrcoeff = 1./TMath::Sqrt(1. + Delta*TMath::Cos(2*phiF));
//AS-ML Nov.2012
rhou3=0.;
//rhou4=0.;
rhou = rhou * (1 + rrcoeff*rhou3*TMath::Cos(3*(phiF+psiforv3)) + rrcoeff*rhou4*TMath::Cos(4*phiF) );
//ML new suggestion of AS mar2012
double delta1 = 0.;
Delta = Delta * (1.0 + delta1 * TMath::Cos(phiF) - delta1 * TMath::Cos(3*phiF));
double uxf = TMath::SinH(rhou)*TMath::Sqrt(1+Delta)*TMath::Cos(phiF);
double uyf = TMath::SinH(rhou)*TMath::Sqrt(1-Delta)*TMath::Sin(phiF);
double utf = TMath::CosH(etaF) * TMath::CosH(rhou) *
TMath::Sqrt(1+Delta*TMath::Cos(2*phiF)*TMath::TanH(rhou)*TMath::TanH(rhou));
double uzf = TMath::SinH(etaF) * TMath::CosH(rhou) *
TMath::Sqrt(1+Delta*TMath::Cos(2*phiF)*TMath::TanH(rhou)*TMath::TanH(rhou));
vec3.SetXYZ(uxf / utf, uyf / utf, uzf / utf);
n1.Boost(-vec3);
yy = weightMax * CLHEP::RandFlat::shoot(hjRandomEngine);
double php0 = TMath::TwoPi() * CLHEP::RandFlat::shoot(hjRandomEngine);
double ctp0 = 2. * CLHEP::RandFlat::shoot(hjRandomEngine) - 1.;
double stp0 = TMath::Sqrt(1. - ctp0 * ctp0);
e = mass + (eMax - mass) * arrayFunctDistE();
double pp0 = TMath::Sqrt(e * e - mass * mass);
px0 = pp0 * stp0 * TMath::Sin(php0);
py0 = pp0 * stp0 * TMath::Cos(php0);
pz0 = pp0 * ctp0;
p0.SetXYZT(px0, py0, pz0, e);
//weight for rdr
weight = (n1 * p0) /e; // weight for rdr gammar: weight = (n1 * p0) / n1[3] / e;
} while(yy >= weight);
if(abs(z0)>1000 || abs(x0)>1000) LogInfo("Hydjet2Hadronizer|Param") <<" etaF = "<<etaF<<std::endl;
partMom.SetXYZT(px0, py0, pz0, e);
partPos.SetXYZT(x0, y0, z0, t0);
partMom.Boost(vec3);
int type =0; //hydro
Particle particle(partDef, partPos, partMom, 0., 0, type, -1, zeroVec, zeroVec);
particle.SetIndex();
allocator.AddParticle(particle, source);
} //nhsel==4 , no hydro part
}
}
}
////////-------------HARD & SOFT particle list ----------end------- ///////////////////////////
Npart = (int)HYFPAR.npart;
Bgen = HYFPAR.bgen;
Njet = (int)HYJPAR.njet;
Nbcol = (int)HYFPAR.nbcol;
if(source.empty()) {
LogError("Hydjet2Hadronizer") << "Source is not initialized!!";
//return ;
}
//Run the decays
if(RunDecays()) Evolve(source, allocator, GetWeakDecayLimit());
LPIT_t it;
LPIT_t e;
//Fill the decayed arrays
Ntot = 0; Nhyd=0; Npyt=0;
for(it = source.begin(), e = source.end(); it != e; ++it) {
TVector3 pos(it->Pos().Vect());
TVector3 mom(it->Mom().Vect());
float m1 = it->TableMass();
pdg[Ntot] = it->Encoding();
Mpdg[Ntot] = it->GetLastMotherPdg();
Px[Ntot] = mom[0];
Py[Ntot] = mom[1];
Pz[Ntot] = mom[2];
E[Ntot] = TMath::Sqrt(mom.Mag2() + m1*m1);
X[Ntot] = pos[0];
Y[Ntot] = pos[1];
Z[Ntot] = pos[2];
T[Ntot] = it->T();
type[Ntot] = it->GetType();
pythiaStatus[Ntot] = it->GetPythiaStatusCode();
Index[Ntot] = it->GetIndex();
MotherIndex[Ntot] = it->GetMother();
NDaughters[Ntot] = it->GetNDaughters();
FirstDaughterIndex[Ntot] = -1; LastDaughterIndex[Ntot] = -1;
//index of first daughter
FirstDaughterIndex[Ntot] = it->GetFirstDaughterIndex();
//index of last daughter
LastDaughterIndex[Ntot] = it->GetLastDaughterIndex();
if(type[Ntot]==1) { // jets
if(pythiaStatus[Ntot]==1 && NDaughters[Ntot]==0) // code for final state particle in pythia
final[Ntot]=1;
else
final[Ntot]=0;
}
if(type[Ntot]==0) { // hydro
if(NDaughters[Ntot]==0)
final[Ntot]=1;
else
final[Ntot]=0;
}
if(type[Ntot]==0)Nhyd++;
if(type[Ntot]==1)Npyt++;
Ntot++;
if(Ntot > kMax)
LogError("Hydjet2Hadronizer") << "Ntot is too large" << Ntot;
}
nsoft_ = Nhyd;
nsub_ = Njet;
nhard_ = Npyt;
//100 trys
++ntry;
}
}
if(ev==0) {
Sigin=HYJPAR.sigin;
Sigjet=HYJPAR.sigjet;
}
ev=1;
if(fNhsel < 3) nsub_++;
// event information
HepMC::GenEvent *evt = new HepMC::GenEvent();
if(nhard_>0 || nsoft_>0) get_particles(evt);
evt->set_signal_process_id(pypars.msti[0]); // type of the process
evt->set_event_scale(pypars.pari[16]); // Q^2
add_heavy_ion_rec(evt);
event().reset(evt);
allocator.FreeList(source);
return kTRUE;
}
//________________________________________________________________
bool Hydjet2Hadronizer::declareStableParticles(const std::vector<int>& _pdg )
{
std::vector<int> pdg = _pdg;
for ( size_t i=0; i < pdg.size(); i++ ) {
int pyCode = pycomp_( pdg[i] );
std::ostringstream pyCard ;
pyCard << "MDCY(" << pyCode << ",1)=0";
std::cout << pyCard.str() << std::endl;
call_pygive( pyCard.str() );
}
return true;
}
//________________________________________________________________
bool Hydjet2Hadronizer::hadronize()
{
return false;
}
bool Hydjet2Hadronizer::decay()
{
return true;
}
bool Hydjet2Hadronizer::residualDecay()
{
return true;
}
void Hydjet2Hadronizer::finalizeEvent()
{
}
void Hydjet2Hadronizer::statistics()
{
}
const char* Hydjet2Hadronizer::classname() const
{
return "gen::Hydjet2Hadronizer";
}
//----------------------------------------------------------------------------------------------
//______________________________________________________________________________________________
//f2=f(phi,r)
double Hydjet2Hadronizer::f2(double x, double y, double Delta) {
LogDebug("f2") <<"in f2: "<<"delta"<<Delta;
double RsB = fR; //test: podstavit' *coefff_RB
double rhou = fUmax * y / RsB;
double ff = y*TMath::CosH(rhou)*
TMath::Sqrt(1+Delta*TMath::Cos(2*x)*TMath::TanH(rhou)*TMath::TanH(rhou));
//n_mu u^mu f-la 20
return ff;
}
//____________________________________________________________________________________________
double Hydjet2Hadronizer::SimpsonIntegrator(double a, double b, double phi, double Delta) {
LogDebug("SimpsonIntegrator") <<"in SimpsonIntegrator"<<"delta - "<<Delta;
int nsubIntervals=100;
double h = (b - a)/nsubIntervals;
double s = f2(phi,a + 0.5*h,Delta);
double t = 0.5*(f2(phi,a,Delta) + f2(phi,b,Delta));
double x = a;
double y = a + 0.5*h;
for(int i = 1; i < nsubIntervals; i++) {
x += h;
y += h;
s += f2(phi,y,Delta);
t += f2(phi,x,Delta);
}
t += 2.0*s;
return t*h/3.0;
}
//______________________________________________________________________________________________
double Hydjet2Hadronizer::SimpsonIntegrator2(double a, double b, double Epsilon, double Delta) {
LogInfo("SimpsonIntegrator2") <<"in SimpsonIntegrator2: epsilon - "<<Epsilon<<" delta - "<<Delta;
int nsubIntervals=10000;
double h = (b - a)/nsubIntervals; //-1-pi, phi
double s=0;
// double h2 = (fR)/nsubIntervals; //0-R maximal RB ?
double x = 0; //phi
for(int j = 1; j < nsubIntervals; j++) {
x += h; // phi
double e = Epsilon;
double RsB = fR; //test: podstavit' *coefff_RB
double RB = RsB *(TMath::Sqrt(1-e*e)/TMath::Sqrt(1+e*TMath::Cos(2*x))); //f-la7 RB
double sr = SimpsonIntegrator(0,RB,x,Delta);
s += sr;
}
return s*h;
}
//___________________________________________________________________________________________________
double Hydjet2Hadronizer::MidpointIntegrator2(double a, double b, double Delta, double Epsilon) {
int nsubIntervals=2000;
int nsubIntervals2=1;
double h = (b - a)/nsubIntervals; //0-pi , phi
double h2 = (fR)/nsubIntervals; //0-R maximal RB ?
double x = a + 0.5*h;
double y = 0;
double t = f2(x,y,Delta);
double e = Epsilon;
for(int j = 1; j < nsubIntervals; j++) {
x += h; // integr phi
double RsB = fR; //test: podstavit' *coefff_RB
double RB = RsB *(TMath::Sqrt(1-e*e)/TMath::Sqrt(1+e*TMath::Cos(2*x))); //f-la7 RB
nsubIntervals2 = int(RB / h2)+1;
// integr R
y=0;
for(int i = 1; i < nsubIntervals2; i++)
t += f2(x,(y += h2),Delta);
}
return t*h*h2;
}
//__________________________________________________________________________________________________________
double Hydjet2Hadronizer::CharmEnhancementFactor(double Ncc, double Ndth, double NJPsith, double Epsilon) {
double gammaC=100.;
double x1 = gammaC*Ndth;
double var1 = Ncc-0.5*gammaC*Ndth*TMath::BesselI1(x1)/TMath::BesselI0(x1)-gammaC*gammaC*NJPsith;
LogInfo("Charam") << "gammaC 20"<<" var "<<var1<<endl;
gammaC=1.;
double x0 = gammaC*Ndth;
double var0 = Ncc-0.5*gammaC*Ndth*TMath::BesselI1(x0)/TMath::BesselI0(x0)-gammaC*gammaC*NJPsith;
LogInfo("Charam") << "gammaC 1"<<" var "<<var0;
for(int i=1; i<1000; i++){
if(var1 * var0<0){
gammaC=gammaC+0.01*i;
double x = gammaC*Ndth;
var0 = Ncc-0.5*gammaC*Ndth*TMath::BesselI1(x)/TMath::BesselI0(x)-gammaC*gammaC*NJPsith;
}
else
{
LogInfo("Charam") << "gammaC "<<gammaC<<" var0 "<<var0;
return gammaC;
}
}
LogInfo("Charam") << "gammaC not found ? "<<gammaC<<" var0 "<<var0;
return -100;
}
//----------------------------------------------------------------------------------------------
//_____________________________________________________________________
//________________________________________________________________
void Hydjet2Hadronizer::rotateEvtPlane()
{
const double pi = 3.14159265358979;
phi0_ = 2.*pi*gen::pyr_(0) - pi;
sinphi0_ = sin(phi0_);
cosphi0_ = cos(phi0_);
}
//_____________________________________________________________________
bool Hydjet2Hadronizer::get_particles(HepMC::GenEvent *evt )
{
// Hard particles. The first nhard_ lines from hyjets array.
// Pythia/Pyquen sub-events (sub-collisions) for a given event
// Return T/F if success/failure
// Create particles from lujet entries, assign them into vertices and
// put the vertices in the GenEvent, for each SubEvent
// The SubEvent information is kept by storing indeces of main vertices
// of subevents as a vector in GenHIEvent.
LogDebug("SubEvent")<< "Number of sub events "<<nsub_;
LogDebug("Hydjet2")<<"Number of hard events "<<Njet;
LogDebug("Hydjet2")<<"Number of hard particles "<<nhard_;
LogDebug("Hydjet2")<<"Number of soft particles "<<nsoft_;
vector<HepMC::GenVertex*> sub_vertices(nsub_);
int ihy = 0;
for(int isub=0;isub<nsub_;isub++){
LogDebug("SubEvent") <<"Sub Event ID : "<<isub;
int sub_up = (isub+1)*50000; // Upper limit in mother index, determining the range of Sub-Event
vector<HepMC::GenParticle*> particles;
vector<int> mother_ids;
vector<HepMC::GenVertex*> prods;
sub_vertices[isub] = new HepMC::GenVertex(HepMC::FourVector(0,0,0,0),isub);
evt->add_vertex(sub_vertices[isub]);
if(!evt->signal_process_vertex()) evt->set_signal_process_vertex(sub_vertices[isub]);
while(ihy<nhard_+nsoft_ && (MotherIndex[ihy] < sub_up || ihy > nhard_ )){
particles.push_back(build_hyjet2(ihy,ihy+1));
prods.push_back(build_hyjet2_vertex(ihy,isub));
mother_ids.push_back(MotherIndex[ihy]);
LogDebug("DecayChain")<<"Mother index : "<<MotherIndex[ihy];
ihy++;
}
//Produce Vertices and add them to the GenEvent. Remember that GenParticles are adopted by
//GenVertex and GenVertex is adopted by GenEvent.
LogDebug("Hydjet2")<<"Number of particles in vector "<<particles.size();
for (unsigned int i = 0; i<particles.size(); i++) {
HepMC::GenParticle* part = particles[i];
//The Fortran code is modified to preserve mother id info, by seperating the beginning
//mother indices of successive subevents by 5000
int mid = mother_ids[i]-isub*50000-1;
LogDebug("DecayChain")<<"Particle "<<i;
LogDebug("DecayChain")<<"Mother's ID "<<mid;
LogDebug("DecayChain")<<"Particle's PDG ID "<<part->pdg_id();
if(mid <= 0){
sub_vertices[isub]->add_particle_out(part);
continue;
}
if(mid > 0){
HepMC::GenParticle* mother = particles[mid];
LogDebug("DecayChain")<<"Mother's PDG ID "<<mother->pdg_id();
HepMC::GenVertex* prod_vertex = mother->end_vertex();
if(!prod_vertex){
prod_vertex = prods[i];
prod_vertex->add_particle_in(mother);
evt->add_vertex(prod_vertex);
prods[i]=0; // mark to protect deletion
}
prod_vertex->add_particle_out(part);
}
}
// cleanup vertices not assigned to evt
for (unsigned int i = 0; i<prods.size(); i++) {
if(prods[i]) delete prods[i];
}
}
return kTRUE;
}
//___________________________________________________________________
HepMC::GenParticle* Hydjet2Hadronizer::build_hyjet2(int index, int barcode)
{
// Build particle object corresponding to index in hyjets (soft+hard)
double px0 = Px[index];
double py0 = Py[index];
double px = px0*cosphi0_-py0*sinphi0_;
double py = py0*cosphi0_+px0*sinphi0_;
HepMC::GenParticle* p = new HepMC::GenParticle(
HepMC::FourVector(
px, // px
py, // py
Pz[index], // pz
E[index]), // E
pdg[index], // id
convertStatus(final[index]) // status
);
p->suggest_barcode(barcode);
return p;
}
//___________________________________________________________________
HepMC::GenVertex* Hydjet2Hadronizer::build_hyjet2_vertex(int i,int id)
{
// build verteces for the hyjets stored events
double x0=X[i];
double y0=Y[i];
double x = x0*cosphi0_-y0*sinphi0_;
double y = y0*cosphi0_+x0*sinphi0_;
double z=Z[i];
double t=T[i];
HepMC::GenVertex* vertex = new HepMC::GenVertex(HepMC::FourVector(x,y,z,t),id);
return vertex;
}
//_____________________________________________________________________
void Hydjet2Hadronizer::add_heavy_ion_rec(HepMC::GenEvent *evt)
{
// heavy ion record in the final CMSSW Event
double npart = Npart;
int nproj = static_cast<int>(npart / 2);
int ntarg = static_cast<int>(npart - nproj);
HepMC::HeavyIon* hi = new HepMC::HeavyIon(
nsub_, // Ncoll_hard/N of SubEvents
nproj, // Npart_proj
ntarg, // Npart_targ
Nbcol, // Ncoll
0, // spectator_neutrons
0, // spectator_protons
0, // N_Nwounded_collisions
0, // Nwounded_N_collisions
0, // Nwounded_Nwounded_collisions
Bgen * nuclear_radius(), // impact_parameter in [fm]
phi0_, // event_plane_angle
0, // eccentricity
Sigin // sigma_inel_NN
);
evt->set_heavy_ion(*hi);
delete hi;
}
| [
"wouf@ilst.ru"
] | wouf@ilst.ru |
fb285027634797300f13287c63c179ce60723a14 | d131fffb28b2dced43f157392a953a9d30ab5f44 | /mt_case_switch/App/Lib.hpp | 0698180a255474ee984180c9ac21ced32f51ff8e | [] | no_license | Karl-SIO/hae_karl_gp2 | be59bd4f5db6afa88777b7751def0a5c7d90f2bd | e14d1fa70e1e1f862e1616f024be523639ae6b91 | refs/heads/master | 2022-04-15T01:57:19.148986 | 2020-03-06T10:37:15 | 2020-03-06T10:37:15 | 211,267,070 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,078 | hpp | #pragma once
#include <string>
#include <vector>
#include <SFML/Graphics.hpp>
#include <Box2D/Box2D.h>
using namespace sf;
struct MemFile {
char * data;
int size;
void dispose() {
free(data);
size = 0;
}
};
class Lib {
public:
static bool loadFile(const std::string & path, MemFile & out);
static float catmull(float p0, float p1, float p2, float p3, float t) {
float q = 2.0f * p1;
float t2 = t * t;
q += (-p0 + p2) * t;
q += (2.0f*p0 - 5.0f*p1 + 4.0f * p2 - p3) * t2;
q += (-p0 + 3.0f * p1 - 3 * p2 + p3) * t2 * t;
return 0.5f * q;
};
static Vector2f get(int idx, const std::vector<Vector2f> & points) {
if (idx < 0)idx = 0;
if (idx >= (int)points.size()) idx = (int)points.size() - 1;
return points[idx];
};
static sf::Vector2f c2(float i, const std::vector<sf::Vector2f> & points) {
auto p0 = get((int)(i - 1), points);
auto p1 = get((int)(i), points);
auto p2 = get((int)(i + 1), points);
auto p3 = get((int)(i + 2), points);
auto t = i - (int)i;
auto resX = catmull(p0.x, p1.x, p2.x, p3.x, t);
auto resY = catmull(p0.y, p1.y, p2.y, p3.y, t);
return Vector2f( resX,resY);
};
static Vector2f plot2(float t, const std::vector<Vector2f> & points) {
return c2(t * (points.size() - 1), points);
}
//// hue: 0-360°; sat: 0.f-1.f; val: 0.f-1.f
static sf::Color hsv(int hue, float sat, float val);
float lerp(float a, float b, float r) {
return a + (b - a) * r;
}
static inline float rd() {
return 1.0f * rand() / RAND_MAX;
}
static void m_gaussian_kernel(float * dest, int size, float radius);
static double v2Len(const Vector2f&v0);
static double v2Dist(const Vector2f&v0, const Vector2f&v1);
static void v2Norm(Vector2f & v0);
double v2iLen(const Vector2i & v0);
static double v2iDist(const Vector2i&v0, const Vector2i&v1);
static double PI;
static bool willCollide(Vector2f pos, Vector2f speed, Shape * other, b2Vec2 & inter, b2Vec2 & normal);
static double dot(b2Vec2 v0, b2Vec2 v1);
static double dice(double mn, double mx) {
return mn + rd() * (mx - mn);
}
}; | [
"karl.merrienne@hotmail.fr"
] | karl.merrienne@hotmail.fr |
be87033ecd7b95b508f9015db0b04e03dacffe83 | 88885e8e59855530c09ac930ae57914cbe4fe0f8 | /Source/xs_publicinclude/ClimbLaneCollection.h | 7ac36186b5b462937c1f537a3b0fe6a0516e6bfb | [] | no_license | klainqin/LandXmlSDK | 8767c46c36b2257d388e50a25e64956c7c6ed020 | ca52863d66d172b00835f66cef636790e668a52f | refs/heads/master | 2021-01-10T08:30:45.007060 | 2015-11-25T10:20:13 | 2015-11-25T10:20:13 | 46,108,934 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 601 | h | #if !defined(__CLIMBLANECOLLECTION_H)
#define __CLIMBLANECOLLECTION_H
#pragma warning(push)
#pragma warning(disable : 4786)
#include "lxtypes.h"
#include "ClimbLane.h"
namespace LX
{
// Iterator : ClimbLaneCollection
class ClimbLaneCollectionIterator : public Iterator<ClimbLane*>
{
};
class ClimbLaneCollectionConstIterator : public ConstIterator<ClimbLane>
{
};
// Collection : ClimbLaneCollection
class ClimbLaneCollection : public ObjList<ClimbLane, ClimbLaneCollectionIterator, ClimbLaneCollectionConstIterator>
{
};
}; // namespace : LX
#pragma warning(pop)
#endif
| [
"qink@shac02q6273g8wn.ads.autodesk.com"
] | qink@shac02q6273g8wn.ads.autodesk.com |
39d7868387fa1fa2c82e577e5fe2ae9cca7ad17c | 4549a2187dfb652e9ae86c8f2b08d000e4ec2c6f | /GDI/OGUtils.h | e64ae3c32c46d7bedea2def8714b5d299767bfec | [] | no_license | OscarShen/OGraphics | d7bcdcb813fbc5beb36b990696b7c1059a59e784 | 885dbbf6f92e85f5bf834b5ecd1c92546972649e | refs/heads/master | 2021-06-16T13:13:29.137809 | 2016-12-01T14:23:33 | 2016-12-01T14:23:33 | 68,186,998 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,781 | h | #pragma once
#ifndef OGUtils_h_
#define OGUtils_h_
#include <vector>
//点
struct OGPoint {
double x;
double y;
OGPoint() {}
OGPoint(double x, double y) :x(x), y(y) {}
};
//矩形
typedef struct OGRectangle {
OGPoint p1, p2;
OGRectangle() {}
OGRectangle(OGPoint p1, OGPoint p2) :p1(p1), p2(p2) {}
}OGRect;
//圆
struct OGCircle {
OGPoint p;
double r;
OGCircle(OGPoint p, double r) :p(p), r(r) {}
};
//多边形
typedef struct OGPolygon {
std::vector<OGPoint*> points;
OGPolygon(std::vector<OGPoint*>& points) :points(points){}
bool isValid();
}OGPoly;
//线段
typedef struct LineSegment {
OGPoint pbegin;
OGPoint pend;
LineSegment(OGPoint pbegin, OGPoint pend) :pbegin(pbegin), pend(pend) {}
}OGLineSeg;
//矢量叉乘
double crossProduct(double x0, double y0, double x1, double y1);
//矢量点乘
double dotProduct(double x0, double y0, double x1, double y1);
//判断点是否在矩阵内
bool isPointInRect(const OGRect& rect, const OGPoint& p);
//计算平面两点的距离
double pointDistance(const OGPoint& p1, const OGPoint& p2);
//判断点是否在线段上
bool isPointOnLineSegment(const OGLineSeg& ls, const OGPoint& p);
//获得线段对应的矩阵
void getLineSegmentRect(const OGLineSeg& ls, OGRect& rect);
//浮点精度1e-8的条件下判断为零
bool isZeroFloatValue(double num);
//判断两个矩形是否相交
bool isRectIntersect(const OGRect& rect1, const OGRect& rect2);
//判断线段是否相交
bool isLineSegmentIntersect(const OGLineSeg& ls1, const OGLineSeg& ls2);
//判断线段生成的矩形
bool isRectOfLineIntersect(const OGLineSeg& ls1, const OGLineSeg& ls2);
bool isPointInPolygon(const OGPoly& OGPoly, const OGPoint& p);
void getPolygonMinMax(OGPoly poly, int& ymin, int& ymax);
#endif // !OGUtils_h_
| [
"oscarshen09@foxmail.com"
] | oscarshen09@foxmail.com |
61eaebf51eba1a0ff5b01bc67eba32eb69960b8f | a81fa322f45e4d146cbed134fc36aa2183a00c28 | /src/extended/matrices/IMatrix2x2.hpp | 3b33e48f2e200fc85fbc72c209b053a329ecdd69 | [
"MIT"
] | permissive | ivan0sokin/IOMath | 7a7820202cd09531e7ef613a59b54316a490febf | 1101090023b57bd2db34e5a3e07a620b9311ac0b | refs/heads/master | 2023-01-28T06:24:57.763920 | 2020-12-05T22:37:53 | 2020-12-05T22:37:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,329 | hpp | /*
MIT License
Copyright (c) 2020 x4kkk3r
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 _IO_MATH_IMATRIX_2X2_HPP
#define _IO_MATH_IMATRIX_2X2_HPP
#include "../../types/matrices/TMatrix2x2.hpp"
namespace IOMath
{
using IMatrix2x2 = Types::TMatrix<2, 2, int>;
using IMatrix2 = Types::TMatrix<2, 2, int>;
}
#endif | [
"x4kkk3r@github.com"
] | x4kkk3r@github.com |
1227a57fd348102f9b3cd4972393e992a7e9c9d6 | 55ec7ab4487814aa15fc31927731cf40d6a6ff4c | /OpenCTD_Particle_Boron/OpenCTD_SDCard/OpenCTD_SDCard/src/OpenCTD_SDCard.ino | d82de5310ae1426f800d96227613e213489e5d06 | [
"MIT"
] | permissive | SUPScientist/OpenCTD | f3733bb6c2b04ef6374fe9b5696a2fa6bfb89789 | 0595126c56dbd7e131d17491b5679a944ab44660 | refs/heads/master | 2020-05-16T14:54:16.332308 | 2019-05-29T20:08:08 | 2019-05-29T20:08:08 | 183,113,096 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,144 | ino | /*
* Simple data logger.
*/
#include <SPI.h>
#include "SdFat.h"
// SD chip select pin. Be sure to disable any other SPI devices such as Enet.
const uint8_t chipSelect = SS;
// Interval between data records in milliseconds.
// The interval must be greater than the maximum SD write latency plus the
// time to acquire and write data to the SD to avoid overrun errors.
// Run the bench example to check the quality of your SD card.
const uint32_t SAMPLE_INTERVAL_MS = 1000;
// Log file base name. Must be six characters or less.
#define FILE_BASE_NAME "Data"
//------------------------------------------------------------------------------
// File system object.
SdFat sd;
// Log file.
SdFile file;
// Time in micros for next data record.
uint32_t logTime;
//==============================================================================
// User functions. Edit writeHeader() and logData() for your requirements.
const uint8_t ANALOG_COUNT = 4;
//------------------------------------------------------------------------------
// Write data header.
void writeHeader() {
file.print(F("micros"));
for (uint8_t i = 0; i < ANALOG_COUNT; i++) {
file.print(F(",adc"));
file.print(i, DEC);
}
file.println();
}
//------------------------------------------------------------------------------
// Log a data record.
void logData() {
uint16_t data[ANALOG_COUNT];
// Read all channels to avoid SD write latency between readings.
for (uint8_t i = 0; i < ANALOG_COUNT; i++) {
data[i] = analogRead(i);
}
// Write data to file. Start with log time in micros.
file.print(logTime);
// Write ADC data to CSV record.
for (uint8_t i = 0; i < ANALOG_COUNT; i++) {
file.write(',');
file.print(data[i]);
}
file.println();
}
//==============================================================================
// Error messages stored in flash.
#define error(msg) sd.errorHalt(F(msg))
//------------------------------------------------------------------------------
SYSTEM_MODE(MANUAL);
void setup() {
Cellular.off();
const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;
char fileName[13] = FILE_BASE_NAME "00.csv";
Serial.begin(9600);
// Wait for USB Serial
while (!Serial) {
SysCall::yield();
}
delay(1000);
Serial.println(F("Type any character to start"));
while (!Serial.available()) {
SysCall::yield();
}
// Initialize at the highest speed supported by the board that is
// not over 50 MHz. Try a lower speed if SPI errors occur.
if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) {
sd.initErrorHalt();
}
// Find an unused file name.
if (BASE_NAME_SIZE > 6) {
error("FILE_BASE_NAME too long");
}
while (sd.exists(fileName)) {
if (fileName[BASE_NAME_SIZE + 1] != '9') {
fileName[BASE_NAME_SIZE + 1]++;
} else if (fileName[BASE_NAME_SIZE] != '9') {
fileName[BASE_NAME_SIZE + 1] = '0';
fileName[BASE_NAME_SIZE]++;
} else {
error("Can't create file name");
}
}
if (!file.open(fileName, O_WRONLY | O_CREAT | O_EXCL)) {
error("file.open");
}
// Read any Serial data.
do {
delay(10);
} while (Serial.available() && Serial.read() >= 0);
Serial.print(F("Logging to: "));
Serial.println(fileName);
Serial.println(F("Type any character to stop"));
// Write data header.
writeHeader();
// Start on a multiple of the sample interval.
logTime = micros()/(1000UL*SAMPLE_INTERVAL_MS) + 1;
logTime *= 1000UL*SAMPLE_INTERVAL_MS;
}
//------------------------------------------------------------------------------
void loop() {
// Time for next record.
logTime += 1000UL*SAMPLE_INTERVAL_MS;
// Wait for log time.
int32_t diff;
do {
diff = micros() - logTime;
} while (diff < 0);
// Check for data rate too high.
if (diff > 10) {
error("Missed data record");
}
logData();
// Force data to SD and update the directory entry to avoid data loss.
if (!file.sync() || file.getWriteError()) {
error("write error");
}
if (Serial.available()) {
// Close file and stop.
file.close();
Serial.println(F("Done"));
SysCall::halt();
}
} | [
"pjbresnahan@gmail.com"
] | pjbresnahan@gmail.com |
3d29008bde01c2d603f668067e77423f417aa60f | 4053aca73db104b7b40325ed4b29e6e4e7a2accf | /src/net/server/server.h | d62e294c6c00b358792050aec7c7d5ba9beb22c9 | [] | no_license | ajunlonglive/httpd-1 | bfebfbef960c6ffa6f13fdf36a910a6320cf4477 | d7f3566ae1b3cc325e36bb5119c13b8a8d84b47d | refs/heads/master | 2023-03-15T12:16:55.995466 | 2020-04-15T10:42:41 | 2020-04-15T10:42:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 950 | h | #pragma once
#include "net/service/service.h"
#include "net/socket/listener.h"
#include "net/socket/socket.h"
#include "net/util/noncopyable.h"
#include <functional>
#include <memory>
#include <string>
class ServerOption {
public:
int max_connection_number = 65536;
int process_number = 16;
int thread_number = 16;
int timeout = 10;
string scheduler = "epoll";
};
class Server {
public:
Server(shared_ptr<Service> _service, string &_ip, uint16_t _port,
ServerOption &_option)
: service(_service), ip(_ip), port(_port), option(_option) {
}
virtual void run() = 0;
protected:
shared_ptr<Service> service;
string ip;
uint16_t port;
ServerOption option;
shared_ptr<Listener> listener;
};
shared_ptr<Server> get_server(shared_ptr<Service> service,
const string &server_name, string ip,
uint16_t port, ServerOption &option); | [
"i@dujiaju.me"
] | i@dujiaju.me |
c68051f1d11b593e3fd1e5b74ccf8776cbb87deb | 594eb1f1cad2c7a01ae74ba1653047134ad6d310 | /xanadu/packet_constants.hpp | 835091fa63f61db63497cc35c299a3db87b0a820 | [] | no_license | icelemon1314/xanadu | 9003e9e65fd4475914ebf04bdff0f4023edfd1cb | a5f4a7260efdca5bb346fae15c523afd3ad8e70d | refs/heads/master | 2021-01-21T20:46:25.015648 | 2017-05-02T03:22:58 | 2017-05-02T03:22:58 | 92,274,961 | 1 | 0 | null | 2017-05-24T09:31:27 | 2017-05-24T09:31:27 | null | UTF-8 | C++ | false | false | 223 | hpp | //
#pragma once
constexpr std::size_t kPacketMaxBufferLength = 65535;
constexpr std::size_t kIvBufferSize = 16;
constexpr std::size_t kInitialPacketBufferSize = 600;
constexpr std::size_t kIncreasePacketBufferSize = 100;
| [
"zszabo@t-online.de"
] | zszabo@t-online.de |
b749982b4be07ae88df6a08e3cd66e90a281e294 | 833c5759f5d56721d295ff267b648045248de3f7 | /all13/all13/main.cpp | 35e8ca9c98ac20a1a1aff0407ede0d4663fad604 | [] | no_license | BinyuHuang-nju/leetcode-implement | 6732331a80d3570521bc9f345e63dc2856cfeb06 | 60dfbf4e7fa833040d49a2907842d26808101f53 | refs/heads/master | 2022-12-23T01:43:08.374777 | 2020-09-27T14:03:39 | 2020-09-27T14:03:39 | 277,704,869 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,281 | cpp | #include <iostream>
using namespace std;
#include <vector>
#include <algorithm>
#include <string>
class Solution {
public:
int romanToInt(string s) {
int result = 0;
int len = s.length();
for (int i = 0; i < len; i++) {
switch (s[i]) {
case 'I':if (i + 1 < len && s[i + 1] == 'V') { result += 4; i++; }
else if (i + 1 < len && s[i + 1] == 'X') { result += 9; i++; }
else result++;
break;
case 'V':result += 5; break;
case 'X':if (i + 1 < len && s[i + 1] == 'L') { result += 40; i++; }
else if (i + 1 < len && s[i + 1] == 'C') { result += 90; i++; }
else result += 10;
break;
case 'L':result += 50; break;
case 'C':if (i + 1 < len && s[i + 1] == 'D') { result += 400; i++; }
else if (i + 1 < len && s[i + 1] == 'M') { result += 900; i++; }
else result += 100;
break;
case 'D':result += 500; break;
case 'M':result += 1000; break;
default:break;
}
}
return result;
}
};
int main() {
Solution sol;
sol.romanToInt("MCMXCIV");
return 0;
} | [
"huangbinyu000@outlook.com"
] | huangbinyu000@outlook.com |
31cad9a76223ead1f94ff27fb9f65f6e12c78703 | 05717410ee2fb21a577fd94a124d03c5296633a8 | /Puzzle.cpp | 998c48486e6619fe2a0466d1d22b73305bd7d7f9 | [] | no_license | spidersss/algorithm-practice | e1875079ce21e2b200d95944817bf39025a097f3 | 2b98b1e2f41adf8be7cba9c177d672e4375aa009 | refs/heads/master | 2021-01-01T19:35:46.958860 | 2017-10-16T13:27:19 | 2017-10-16T13:27:19 | 98,617,251 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,013 | cpp | #include<stdio.h>
#include<string.h>
#define maxn 5
int main(){
char s[5][5];
char c;
int pos[2];
for(int i = 0; i < 5; i++)
for(int j = 0; j < 5; j++){
if((c=getchar()) != '\n'){
s[i][j] = c;
if(c == ' ') {
pos[0]=i;
pos[1]=j;
}
}
else break;
}
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++)
printf("%c ", s[i][j]);
printf("\n");
}
c = getchar();
while((c=getchar()) != '0'){
switch(c){
case 'A': s[pos[0]][pos[1]]=s[pos[0]-1][pos[1]]; s[pos[0]-1][pos[1]] = ' '; pos[0]-=1;break;
case 'B': s[pos[0]][pos[1]]=s[pos[0]+1][pos[1]]; s[pos[0]+1][pos[1]] = ' '; pos[0]+=1;break;
case 'L': s[pos[0]][pos[1]]=s[pos[0]][pos[1]-1]; s[pos[0]][pos[1]-1] = ' '; pos[1]-=1;break;
case 'R': s[pos[0]][pos[1]]=s[pos[0]][pos[1]+1]; s[pos[0]][pos[1]+1] = ' '; pos[1]+=1;break;
default: printf("This puzzle has no final configuration."); break;
}
}
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++)
printf("%c ", s[i][j]);
printf("\n");
}
return 0;
}
| [
"604815982@qq.com"
] | 604815982@qq.com |
335708c3d2eb165c9f2fb5519464211c701e0bee | 412f40fd13e75d7d90cc1bb38e309fb9a9b5c975 | /TwoProblems.cpp | 61b771013dccf56ae895e186a62e12ff1ac3e363 | [] | no_license | ritesh-pandey/codeforces | 7ac0a5779ba5278808ab4a34e45d006bff34591d | 6212daffd2f4907302cdca00c8ddd681c3f2018d | refs/heads/master | 2020-06-02T05:25:39.750099 | 2013-09-01T08:32:17 | 2013-09-01T08:32:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 442 | cpp | #include <iostream>
using namespace std;
int main(){
int x,t,a,b,da,db;
cin>>x>>t>>a>>b>>da>>db;
if(x == 0 || x == a || x == b){
cout<<"YES\n";
return 0;
}
for(int i=0; i<t; i++){
for(int j=0; j<t; j++){
if(a-(i*da) == x){
cout<<"YES\n";
return 0;
}
if(b-(i*db) == x){
cout<<"YES\n";
return 0;
}
if(a-(i*da)+b-(j*db) == x){
cout<<"YES\n";
return 0;
}
}
}
cout<<"NO\n";
return 0;
}
| [
"ritesh@ritesh-laptop.(none)"
] | ritesh@ritesh-laptop.(none) |
4cb3bab596f7f71e633f69347b97d2acca835c8e | d0c7c11f15bf307c77cf49ba59c75010f2c6fbbb | /Chapter3/task3_6.cpp | cd53d2aa5caa4e03d79e670ba54bba1bd6f2a952 | [] | no_license | Dimengine/Lippman_2014 | a90ac68d5e6cfa7f16aaaa80b8e4603f736bf8dc | db671984584d67a0500d4eef478cdbf1293b234b | refs/heads/master | 2020-12-27T21:06:50.421309 | 2020-08-11T14:40:54 | 2020-08-11T14:40:54 | 238,055,731 | 1 | 1 | null | 2020-04-27T20:41:30 | 2020-02-03T20:30:21 | C++ | UTF-8 | C++ | false | false | 176 | cpp | #include <iostream>
#include <string>
#include <cctype>
int main()
{
std::string str;
std::cin >> str;
for(auto &c : str)
c = 'X';
std::cout << str;
} | [
"dmytronovak98@gmail.com"
] | dmytronovak98@gmail.com |
e12f4e997005e68a7f917b0e8c7c469e419851c2 | f8dd7e2b80f459682d481135352c853034133d8f | /src/map/gzip.h | e4e7f900c7c121024b54d160c623cf34b1aac93b | [
"WTFPL"
] | permissive | LiquidityC/justdontdie | 265b25b5e50c49c0ab5a24fac1d9936847bf843b | 3d970ce09e26115e002b391524584eab0583af37 | refs/heads/master | 2021-01-24T00:08:52.885829 | 2018-03-30T14:53:48 | 2018-03-30T14:54:29 | 23,753,740 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,055 | h | #ifndef MAP_GZIP_H_
#define MAP_GZIP_H_
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <sstream>
#include <string>
#include <algorithm>
/**
* This class isn't used at the moment
*/
class Gzip {
public:
static std::string compress(const std::string& data)
{
namespace bio = boost::iostreams;
std::stringstream compressed;
std::stringstream origin(data);
bio::filtering_streambuf<bio::input> out;
out.push(bio::gzip_compressor(bio::gzip_params(bio::gzip::best_compression)));
out.push(origin);
bio::copy(out, compressed);
return compressed.str();
}
static std::string decompress(const std::string& data)
{
namespace bio = boost::iostreams;
std::stringstream compressed(data);
std::stringstream decompressed;
bio::filtering_streambuf<bio::input> out;
out.push(bio::gzip_decompressor());
out.push(compressed);
bio::copy(out, decompressed);
return decompressed.str();
}
};
#endif // MAP_GZIP_H_
| [
"linus.probert@gmail.com"
] | linus.probert@gmail.com |
7cf7dd8b525f2b0432bd80785e70c4caedd0511b | b42fd2a016e5abd4e49a792557aaa711facdf9fb | /src/GameEngine/Game.h | 6c3434a16b80768509751a2f5774217dd376d716 | [] | no_license | Megabyte355/DungeonsAndDragonsEclipse | 997e88c855246670062cc03e98d60765f6b1940a | 715f54ebefb6f998262698518c89c0030451fb9b | refs/heads/master | 2016-09-05T21:04:11.708015 | 2013-12-02T02:14:22 | 2013-12-02T02:14:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 678 | h | /*
* Game.h
*
* Created on: Oct 31, 2013
* Author: Gary
*/
#ifndef GAME_H_
#define GAME_H_
#include "GameConfig.h"
#include "Util.h"
#include "ScreenManager.h"
#include "TextureRenderer.h"
#include "TextRenderer.h"
#include <iostream>
#include <string>
#include <SDL.h>
// Forward declaration
class ScreenManager;
class Game
{
public:
std::shared_ptr<ScreenManager> screenManager;
SDL_Renderer * renderer;
SDL_Window * window;
TextureRenderer * textures;
TextRenderer * texts;
Game(void);
~Game(void);
void initialize();
void update(float);
void draw();
void handleEvents(SDL_Event &event);
};
#endif /* GAME_H_ */
| [
"gary.chang.355@gmail.com"
] | gary.chang.355@gmail.com |
15ada9d4e70a8933ef863cf91667a1ec02637d46 | 9b8f20b3d029ab64121928e1de4fceece6e83525 | /Projects/Qt4Calculator/QtCalculator/ui_helpdialog.h | 1b980e89682cf1cdbed5010e53f0be1ab7ce5da6 | [] | no_license | xueweiguo/Qt-QML | b9602251ac9ac76a9e0ce03965bef15da2dd7f6b | 5bf503009e7ee3ba65d2a8def0e8f58033735469 | refs/heads/master | 2022-12-29T10:48:05.997525 | 2020-10-18T14:19:56 | 2020-10-18T14:19:56 | 304,888,398 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,959 | h | /********************************************************************************
** Form generated from reading UI file 'helpdialog.ui'
**
** Created by: Qt User Interface Compiler version 5.15.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_HELPDIALOG_H
#define UI_HELPDIALOG_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QDialog>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QVBoxLayout>
QT_BEGIN_NAMESPACE
class Ui_HelpDialog
{
public:
QVBoxLayout *verticalLayout_3;
QHBoxLayout *horizontalLayout_2;
QSpacerItem *horizontalSpacer;
QVBoxLayout *verticalLayout;
QLabel *label_2;
QLabel *label;
QSpacerItem *horizontalSpacer_2;
QDialogButtonBox *buttonBox;
void setupUi(QDialog *HelpDialog)
{
if (HelpDialog->objectName().isEmpty())
HelpDialog->setObjectName(QString::fromUtf8("HelpDialog"));
HelpDialog->resize(541, 288);
verticalLayout_3 = new QVBoxLayout(HelpDialog);
verticalLayout_3->setObjectName(QString::fromUtf8("verticalLayout_3"));
horizontalLayout_2 = new QHBoxLayout();
horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2"));
horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_2->addItem(horizontalSpacer);
verticalLayout = new QVBoxLayout();
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
label_2 = new QLabel(HelpDialog);
label_2->setObjectName(QString::fromUtf8("label_2"));
QFont font;
font.setFamily(QString::fromUtf8("MS Sans Serif"));
font.setPointSize(32);
font.setItalic(true);
font.setUnderline(true);
label_2->setFont(font);
label_2->setStyleSheet(QString::fromUtf8("color: rgb(0, 85, 255);"));
label_2->setFrameShape(QFrame::NoFrame);
label_2->setFrameShadow(QFrame::Sunken);
verticalLayout->addWidget(label_2);
label = new QLabel(HelpDialog);
label->setObjectName(QString::fromUtf8("label"));
QFont font1;
font1.setPointSize(16);
label->setFont(font1);
label->setLayoutDirection(Qt::RightToLeft);
label->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
verticalLayout->addWidget(label);
horizontalLayout_2->addLayout(verticalLayout);
horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_2->addItem(horizontalSpacer_2);
buttonBox = new QDialogButtonBox(HelpDialog);
buttonBox->setObjectName(QString::fromUtf8("buttonBox"));
buttonBox->setOrientation(Qt::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::Ok);
horizontalLayout_2->addWidget(buttonBox);
verticalLayout_3->addLayout(horizontalLayout_2);
retranslateUi(HelpDialog);
QObject::connect(buttonBox, SIGNAL(accepted()), HelpDialog, SLOT(accept()));
QObject::connect(buttonBox, SIGNAL(rejected()), HelpDialog, SLOT(reject()));
QMetaObject::connectSlotsByName(HelpDialog);
} // setupUi
void retranslateUi(QDialog *HelpDialog)
{
HelpDialog->setWindowTitle(QCoreApplication::translate("HelpDialog", "QtCalculator Help", nullptr));
label_2->setText(QCoreApplication::translate("HelpDialog", " QtCalculator ", nullptr));
label->setText(QCoreApplication::translate("HelpDialog", "ver1.00, 2011/10/8", nullptr));
} // retranslateUi
};
namespace Ui {
class HelpDialog: public Ui_HelpDialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_HELPDIALOG_H
| [
"weiguo_xue@hotmail.com"
] | weiguo_xue@hotmail.com |
299b0afcf6cc6ae4860229dd17274c7ceb200532 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/xgboost/xgboost-old-new/xgboost-old-new-joern/dmlc_xgboost_old_new_new_function_640.cpp | f73cf29a286f4d8d49d5a7fc04b47d3d8ccfac6d | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 960 | cpp | inline booster::IBooster *GetUpdateBooster( void ){
if( tparam.reupdate_booster != -1 ){
const int bid = tparam.reupdate_booster;
utils::Assert( bid >= 0 && bid < (int)boosters.size(), "interact:booster_index exceed existing bound" );
this->ConfigBooster( boosters[bid] );
return boosters[ bid ];
}
if( mparam.do_reboost == 0 || boosters.size() == 0 ){
mparam.num_boosters += 1;
boosters.push_back( booster::CreateBooster<FMatrixS>( mparam.booster_type ) );
booster_info.push_back( 0 );
this->ConfigBooster( boosters.back() );
boosters.back()->InitModel();
}else{
this->ConfigBooster( boosters.back() );
}
return boosters.back();
} | [
"993273596@qq.com"
] | 993273596@qq.com |
8d6d143b6e0fe78b07b9435a84a0e140cf386fc7 | f17bb6a6e3644a820ec69282a9d2970710c4ca42 | /SakaiDX12/SakaiDX12/Source/Input/Input.cpp | 59aca2d81cc4c1b8ae8a778eb6a99f9142669196 | [] | no_license | sakayuu/Sakai_lib | 3fc6b796ee314eadb97d9ae808e28f82cdb83181 | 10cb31d3e36dd384a16cb74998e2fd5469236269 | refs/heads/main | 2023-09-03T15:12:52.253600 | 2021-10-14T16:37:40 | 2021-10-14T16:37:40 | 301,790,664 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,381 | cpp | #include "Input.h"
#include <cassert>
#pragma comment(lib, "dinput8.lib")
bool Input::Initialize(HINSTANCE hInstance, HWND hwnd)
{
HRESULT result = S_FALSE;
hWnd = hwnd;
// DirectInputオブジェクトの生成
result = DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&dinput, nullptr);
assert(SUCCEEDED(result));
// キーボードデバイスの生成
result = dinput->CreateDevice(GUID_SysKeyboard, &devKeyboard, NULL);
assert(SUCCEEDED(result));
// マウスデバイスの生成
result = dinput->CreateDevice(GUID_SysMouse, &devMouse, NULL);
assert(SUCCEEDED(result));
// 入力データ形式のセット
result = devKeyboard->SetDataFormat(&c_dfDIKeyboard); // 標準形式
assert(SUCCEEDED(result));
// 排他制御レベルのセット
result = devKeyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE | DISCL_NOWINKEY);
assert(SUCCEEDED(result));
// 入力データ形式のセット
result = devMouse->SetDataFormat(&c_dfDIMouse2); // 標準形式
assert(SUCCEEDED(result));
// 排他制御レベルのセット
result = devMouse->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE | DISCL_NOWINKEY);
assert(SUCCEEDED(result));
return true;
}
void Input::Update()
{
HRESULT result;
#pragma region キーボード
{
result = devKeyboard->Acquire(); // キーボード動作開始
// 前回のキー入力を保存
memcpy(keyPre, key, sizeof(key));
// キーの入力
result = devKeyboard->GetDeviceState(sizeof(key), key);
}
#pragma endregion
#pragma region マウス
{
result = devMouse->Acquire(); // マウス動作開始
// 前回の入力を保存
mouseStatePre = mouseState;
// マウスの入力
result = devMouse->GetDeviceState(sizeof(mouseState), &mouseState);
}
#pragma endregion
}
bool Input::PushKey(BYTE keyNumber)
{
// 異常な引数を検出
assert(0 <= keyNumber && keyNumber <= 256);
// 0でなければ押している
if (key[keyNumber]) {
return true;
}
// 押していない
return false;
}
bool Input::TriggerKey(BYTE keyNumber)
{
// 異常な引数を検出
assert(0 <= keyNumber && keyNumber <= 256);
// 前回が0で、今回が0でなければトリガー
if (!keyPre[keyNumber] && key[keyNumber]) {
return true;
}
// トリガーでない
return false;
}
bool Input::PushMouseLeft()
{
// 0でなければ押している
if (mouseState.rgbButtons[0]) {
return true;
}
// 押していない
return false;
}
bool Input::PushMouseMiddle()
{
// 0でなければ押している
if (mouseState.rgbButtons[2]) {
return true;
}
// 押していない
return false;
}
bool Input::TriggerMouseLeft()
{
// 前回が0で、今回が0でなければトリガー
if (!mouseStatePre.rgbButtons[0] && mouseState.rgbButtons[0]) {
return true;
}
// トリガーでない
return false;
}
bool Input::TriggerMouseMiddle()
{
// 前回が0で、今回が0でなければトリガー
if (!mouseStatePre.rgbButtons[2] && mouseState.rgbButtons[2]) {
return true;
}
// トリガーでない
return false;
}
Input::MouseMove Input::GetMouseMove()
{
MouseMove tmp;
tmp.lX = mouseState.lX;
tmp.lY = mouseState.lY;
tmp.lZ = mouseState.lZ;
return tmp;
}
POINT Input::GetMousePoint()
{
GetCursorPos(&mousePoint);
ScreenToClient(hWnd, &mousePoint);
return mousePoint;
}
| [
"sakai1203yuu@gmail.com"
] | sakai1203yuu@gmail.com |
2d3491dc83a3f07f1f264118dd8c788756bbfb0b | 58b91b399a07dada20c4c8f57fd6150b85a9cc28 | /content/public/common/content_features.h | 893e30759d5de1b3cb8894c4c3e25e57ea3f357c | [
"BSD-3-Clause"
] | permissive | domramirez/chromium | a2167f6e605dabf49640f04b12e28c8a2f62d20c | a8e1de5b19353797ee41b343d1e4cc021d61d735 | refs/heads/master | 2023-01-13T02:48:01.372551 | 2017-10-25T19:35:10 | 2017-10-25T19:35:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,052 | h | // Copyright 2015 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.
// This file defines all the public base::FeatureList features for the content
// module.
#ifndef CONTENT_PUBLIC_COMMON_CONTENT_FEATURES_H_
#define CONTENT_PUBLIC_COMMON_CONTENT_FEATURES_H_
#include "base/feature_list.h"
#include "build/build_config.h"
#include "content/common/content_export.h"
namespace features {
// All features in alphabetical order. The features should be documented
// alongside the definition of their values in the .cc file.
CONTENT_EXPORT extern const base::Feature kAllowActivationDelegationAttr;
CONTENT_EXPORT extern const base::Feature
kAllowContentInitiatedDataUrlNavigations;
CONTENT_EXPORT extern const base::Feature kAsmJsToWebAssembly;
CONTENT_EXPORT extern const base::Feature kAsyncWheelEvents;
CONTENT_EXPORT extern const base::Feature kBlockCredentialedSubresources;
CONTENT_EXPORT extern const base::Feature kDataSaverHoldback;
CONTENT_EXPORT extern const base::Feature kBrotliEncoding;
CONTENT_EXPORT extern const base::Feature kBrowserSideNavigation;
CONTENT_EXPORT extern const base::Feature kBuggyRSAParser;
CONTENT_EXPORT extern const base::Feature kCanvas2DImageChromium;
CONTENT_EXPORT extern const base::Feature kCheckerImaging;
CONTENT_EXPORT extern const base::Feature kCompositeOpaqueFixedPosition;
CONTENT_EXPORT extern const base::Feature kCompositeOpaqueScrollers;
CONTENT_EXPORT extern const base::Feature kCompositorImageAnimation;
CONTENT_EXPORT extern const base::Feature kCompositorTouchAction;
CONTENT_EXPORT extern const base::Feature kExpensiveBackgroundTimerThrottling;
CONTENT_EXPORT extern const base::Feature kFeaturePolicy;
CONTENT_EXPORT extern const base::Feature kFetchKeepaliveTimeoutSetting;
CONTENT_EXPORT extern const base::Feature kFontCacheScaling;
CONTENT_EXPORT extern const base::Feature
kFramebustingNeedsSameOriginOrUserGesture;
CONTENT_EXPORT extern const base::Feature kGamepadExtensions;
CONTENT_EXPORT extern const base::Feature kGuestViewCrossProcessFrames;
CONTENT_EXPORT extern const base::Feature kHeapCompaction;
CONTENT_EXPORT extern const base::Feature kImageCaptureAPI;
CONTENT_EXPORT extern const base::Feature
kKeepAliveRendererForKeepaliveRequests;
CONTENT_EXPORT extern const base::Feature kLazyInitializeMediaControls;
CONTENT_EXPORT extern const base::Feature kLazyParseCSS;
CONTENT_EXPORT extern const base::Feature kLoadingWithMojo;
CONTENT_EXPORT extern const base::Feature kMemoryCoordinator;
CONTENT_EXPORT extern const base::Feature kNetworkService;
CONTENT_EXPORT extern const base::Feature kNotificationContentImage;
CONTENT_EXPORT extern const base::Feature kMainThreadBusyScrollIntervention;
CONTENT_EXPORT extern const base::Feature kMojoBlobs;
CONTENT_EXPORT extern const base::Feature kMojoInputMessages;
CONTENT_EXPORT extern const base::Feature kMojoVideoEncodeAccelerator;
CONTENT_EXPORT extern const base::Feature kModuleScripts;
CONTENT_EXPORT extern const base::Feature kModuleScriptsDynamicImport;
CONTENT_EXPORT extern const base::Feature kModuleScriptsImportMetaUrl;
CONTENT_EXPORT extern const base::Feature kOffMainThreadFetch;
CONTENT_EXPORT extern const base::Feature kOriginManifest;
CONTENT_EXPORT extern const base::Feature kOriginTrials;
CONTENT_EXPORT extern const base::Feature kOutOfBlinkCORS;
CONTENT_EXPORT extern const base::Feature kParallelDownloading;
CONTENT_EXPORT extern const base::Feature kPassiveDocumentEventListeners;
CONTENT_EXPORT extern const base::Feature kPassiveEventListenersDueToFling;
CONTENT_EXPORT extern const base::Feature kPepper3DImageChromium;
CONTENT_EXPORT extern const base::Feature kPurgeAndSuspend;
CONTENT_EXPORT extern const base::Feature kRafAlignedMouseInputEvents;
CONTENT_EXPORT extern const base::Feature kRenderingPipelineThrottling;
CONTENT_EXPORT extern const base::Feature kReportRendererPeakMemoryStats;
CONTENT_EXPORT extern const base::Feature kResourceLoadScheduler;
CONTENT_EXPORT extern const base::Feature kScrollAnchoring;
CONTENT_EXPORT
extern const base::Feature kSendBeaconThrowForBlobWithNonSimpleType;
CONTENT_EXPORT extern const base::Feature kServiceWorkerPaymentApps;
CONTENT_EXPORT extern const base::Feature kServiceWorkerScriptStreaming;
CONTENT_EXPORT extern const base::Feature kSignInProcessIsolation;
CONTENT_EXPORT extern const base::Feature kSitePerProcess;
CONTENT_EXPORT extern const base::Feature kSlimmingPaintInvalidation;
CONTENT_EXPORT extern const base::Feature kTimerThrottlingForHiddenFrames;
CONTENT_EXPORT extern const base::Feature kTopDocumentIsolation;
CONTENT_EXPORT extern const base::Feature kTouchpadAndWheelScrollLatching;
CONTENT_EXPORT extern const base::Feature
kTurnOff2DAndOpacityCompositorAnimations;
CONTENT_EXPORT extern const base::Feature kUseFeaturePolicyForPermissions;
CONTENT_EXPORT extern const base::Feature kUseMojoAudioOutputStreamFactory;
CONTENT_EXPORT extern const base::Feature kUserActivationV2;
CONTENT_EXPORT extern const base::Feature kV8ContextSnapshot;
CONTENT_EXPORT extern const base::Feature kV8VmFuture;
CONTENT_EXPORT extern const base::Feature kVibrateRequiresUserGesture;
CONTENT_EXPORT extern const base::Feature kVrShell;
CONTENT_EXPORT extern const base::Feature kWebAssembly;
CONTENT_EXPORT extern const base::Feature kWebAssemblyStreaming;
CONTENT_EXPORT extern const base::Feature kWebAssemblyTrapHandler;
CONTENT_EXPORT extern const base::Feature kWebAuth;
CONTENT_EXPORT extern const base::Feature kWebGLImageChromium;
CONTENT_EXPORT extern const base::Feature kWebPayments;
CONTENT_EXPORT extern const base::Feature kWebRtcEcdsaDefault;
CONTENT_EXPORT extern const base::Feature kWebRtcHWH264Encoding;
CONTENT_EXPORT extern const base::Feature kWebRtcHWVP8Encoding;
CONTENT_EXPORT extern const base::Feature kWebRtcScreenshareSwEncoding;
CONTENT_EXPORT extern const base::Feature kWebRtcUseEchoCanceller3;
CONTENT_EXPORT extern const base::Feature kWebRtcUseGpuMemoryBufferVideoFrames;
CONTENT_EXPORT extern const base::Feature kWebUsb;
CONTENT_EXPORT extern const base::Feature kWebVRExperimentalRendering;
CONTENT_EXPORT extern const base::Feature kWorkStealingInScriptRunner;
#if defined(OS_ANDROID)
CONTENT_EXPORT extern const base::Feature kAndroidAutofillAccessibility;
CONTENT_EXPORT extern const base::Feature kHideIncorrectlySizedFullscreenFrames;
CONTENT_EXPORT extern const base::Feature kImeThread;
CONTENT_EXPORT extern const base::Feature kWebNfc;
CONTENT_EXPORT extern const base::Feature kWebVrVsyncAlign;
#endif // defined(OS_ANDROID)
#if defined(OS_MACOSX)
CONTENT_EXPORT extern const base::Feature kDeviceMonitorMac;
CONTENT_EXPORT extern const base::Feature kMacV2Sandbox;
#endif // defined(OS_MACOSX)
CONTENT_EXPORT bool IsMojoBlobsEnabled();
// DON'T ADD RANDOM STUFF HERE. Put it in the main section above in
// alphabetical order, or in one of the ifdefs (also in order in each section).
} // namespace features
#endif // CONTENT_PUBLIC_COMMON_CONTENT_FEATURES_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
e7027ce8f8669e167c4ed297b5d2aecf5349000e | ea3ac0bff775342663899b2219805f5766173d9e | /tests/apc/extra-libs-project/components/sender/hello_sender_exec.h | 7413f2f1ccddba44a8e3d6bff97b91632c70501e | [
"MIT"
] | permissive | RemedyIT/ciaox11 | 42552fad243aa0a89b184a2ccfa37887d44ad124 | c2b79003141311938a93343755a541f86164f97a | refs/heads/master | 2023-08-04T01:06:36.062238 | 2023-08-03T07:16:16 | 2023-08-03T07:16:16 | 208,991,925 | 9 | 3 | MIT | 2023-09-04T17:42:23 | 2019-09-17T07:50:28 | C++ | UTF-8 | C++ | false | false | 4,108 | h | // -*- C++ -*-
/**
* @file hello_sender_exec.h
* @author Marijke Hengstmengel
*
* @copyright Copyright (c) Remedy IT Expertise BV
*/
#ifndef __RIDL_HELLO_SENDER_EXEC_H_JEJEJEFD_INCLUDED__
#define __RIDL_HELLO_SENDER_EXEC_H_JEJEJEFD_INCLUDED__
//@@{__RIDL_REGEN_MARKER__} - HEADER_END : hello_sender_impl.h[Header]
#pragma once
#include "hello_senderEC.h"
#include /**/ "my_export_sender_exec_export.h"
//@@{__RIDL_REGEN_MARKER__} - BEGIN : hello_sender_impl.h[user_includes]
//@@{__RIDL_REGEN_MARKER__} - END : hello_sender_impl.h[user_includes]
//@@{__RIDL_REGEN_MARKER__} - BEGIN : hello_sender_impl.h[user_global_decl]
// Your declarations here
//@@{__RIDL_REGEN_MARKER__} - END : hello_sender_impl.h[user_global_decl]
/// Namespace for implementation of Hello::Sender component
namespace Hello_Sender_Impl
{
/// Forward declarations
class Sender_exec_i;
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl[user_namespace_decl]
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl[user_namespace_decl]
/// Component Executor Implementation Class : Sender_exec_i
class Sender_exec_i final
: public virtual IDL::traits<::Hello::CCM_Sender>::base_type
{
public:
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i[ctor]
/// Constructor
Sender_exec_i ();
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i[ctor]
/// Destructor
~Sender_exec_i () override;
/** @name Component port operations. */
//@{
//@}
/** @name Session component operations */
//@{
/// Setter for container context for this component
/// @param[in] ctx Component context
void set_session_context (IDL::traits<Components::SessionContext>::ref_type ctx) override;
/// Component state change method to configuration_complete state
void configuration_complete () override;
/// Component state change method to activated state
void ccm_activate () override;
/// Component state change method to passivated state
void ccm_passivate () override;
/// Component state change method to removed state
void ccm_remove () override;
//@}
/** @name User defined public operations. */
//@{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i[user_public_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i[user_public_ops]
//@}
private:
/// Context for component instance.
IDL::traits<::Hello::CCM_Sender_Context>::ref_type context_;
/** @name Component facets. */
//@{
//@}
/** @name User defined members. */
//@{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i[user_members]
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i[user_members]
//@}
/** @name User defined private operations. */
//@{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl::Sender_exec_i[user_private_ops]
int test_url ();
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl::Sender_exec_i[user_private_ops]
//@}
private:
/** @name Illegal to be called. Deleted explicitly to let the compiler detect any violation */
//@{
Sender_exec_i(const Sender_exec_i&) = delete;
Sender_exec_i(Sender_exec_i&&) = delete;
Sender_exec_i& operator=(const Sender_exec_i&) = delete;
Sender_exec_i& operator=(Sender_exec_i&&) = delete;
//@}
};
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl[user_namespace_end_decl]
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl[user_namespace_end_decl]
} // namespace Hello_Sender_Impl
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Hello_Sender_Impl[factory]
extern "C" MY_EXPORT_SENDER_EXEC_Export void
create_Hello_Sender_Impl (
IDL::traits<Components::EnterpriseComponent>::ref_type& component);
//@@{__RIDL_REGEN_MARKER__} - END : Hello_Sender_Impl[factory]
//@@{__RIDL_REGEN_MARKER__} - BEGIN : hello_sender_impl.h[Footer]
#endif /* __RIDL_HELLO_SENDER_EXEC_H_JEJEJEFD_INCLUDED__ */
// Your footer (code) here
// -*- END -*-
| [
"jwillemsen@remedy.nl"
] | jwillemsen@remedy.nl |
853c608e0239f705c173843a353d61412827a37b | d7ea39708af66d2bfb80ffe61c56e0b40d96e85f | /3DActionGame/3DActionGame/Src/Scene/ControlScene.cpp | 88c8f6274fa5e5a08c7c545d0b31559db3236d1d | [] | no_license | renonakamoto/3DActionGame | 26ded58d060eb5ed950742b31f658cd2a87ad4b1 | 97db1a4ad2f4b2ca062ed79e2c9cb0a892feabe0 | refs/heads/main | 2023-06-24T05:41:32.653238 | 2021-07-29T04:42:28 | 2021-07-29T04:42:28 | 346,624,157 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,046 | cpp | #include "ControlScene.h"
#include "../Engine/Engine.h"
#include "../ObjectManager/ObjectManager.h"
#include "../Objects/2DObject/BackGround.h"
ControlScene::ControlScene(SceneChanger* sceneChanger_) : Scene(sceneChanger_)
{
m_ThreadHandle = CreateThread(
nullptr, // セキュリティ属性
0, // スタックサイズ
this->LoadResources, // スレッド関数
nullptr, // スレッド関数に渡す引数
0, // 作成オプション
&m_dwThreadID); // スレッドID
m_CurrentState = SceneState::Load;
}
ControlScene::~ControlScene()
{
ObjectManager::GetInstance()->AllRelease();
TEX_MANAGER->AllRelease();
}
void ControlScene::Load()
{
if (WaitForSingleObject(m_ThreadHandle, 0) == WAIT_OBJECT_0)
{
ObjectManager::GetInstance()->Register(new Background("control_bg"));
ObjectManager::GetInstance()->Init();
// 入力モード変更
INPUT_MANAGER->SetInputMode(InputMode::MODE_UI);
m_CurrentState = SceneState::Main;
}
}
DWORD WINAPI ControlScene::LoadResources(LPVOID lpParam_)
{
TEX_MANAGER->Load("Res/Textures/control_bg.png", "control_bg");
return 0;
}
void ControlScene::Main()
{
if (INPUT_MANAGER->GetMouseDown(MouseButton::Left))
{
m_SceneChanger->ChangeScene(SceneID::Tilte);
return;
}
ObjectManager::GetInstance()->Update();
}
void ControlScene::Update()
{
switch (m_CurrentState)
{
case SceneState::Load:
Load();
break;
case SceneState::Main:
Main();
break;
default:
break;
}
}
void ControlScene::Draw()
{
GRAPHICS->StartRendering(KindRT::RT_ON_SCREEN);
switch (m_CurrentState)
{
case SceneState::Load:
break;
case SceneState::Main:
ObjectManager::GetInstance()->Draw();
break;
default:
break;
}
GRAPHICS->FinishRendering();
} | [
"obrsk23@yahoo.co.jp"
] | obrsk23@yahoo.co.jp |
3c16c14ca7c8ccfa7640c2b3307c08ea442d807a | 7b7554fc484b2c4aaab1a97c6b4b760ed942a00e | /iSAMApp/iSAM/isamlib/Slam.cpp | 1b132bdc23079bee7dc0786cdbcd165dbf0f79cb | [] | no_license | sven-glory/GTSAM-NDT | 90bd50bb6404579dc8b5c7f2011be4b64501d572 | 8c5183de63ba54f3cafb67d193b8dffc3afb4b23 | refs/heads/master | 2023-02-25T18:03:14.497787 | 2021-01-31T05:09:56 | 2021-01-31T05:09:56 | 334,640,405 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,957 | cpp | /**
* @file Slam.cpp
* @brief SLAM implementation using iSAM
* @author Michael Kaess
* @author Hordur Johannsson
* @version $Id: Slam.cpp 7610 2012-10-25 10:21:12Z hordurj $
*
* Copyright (C) 2009-2013 Massachusetts Institute of Technology.
* Michael Kaess, Hordur Johannsson, David Rosen,
* Nicholas Carlevaris-Bianco and John. J. Leonard
*
* This file is part of iSAM.
*
* iSAM is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at
* your option) any later version.
*
* iSAM is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with iSAM. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <iomanip>
#include <vector>
#include <map>
#include <list>
#include "isam/util.h"
#include "isam/SparseSystem.h"
#include "isam/OptimizationInterface.h"
#include "isam/covariance.h"
#include "isam/Slam.h"
using namespace std;
using namespace Eigen;
namespace isam
{
// for numbering of factors and nodes
int Node::_next_id = 0;
int Factor::_next_id = 0;
struct DeleteOnReturn
{
SparseVector** _ptr;
explicit DeleteOnReturn(SparseVector** ptr) : _ptr(ptr) {}
~DeleteOnReturn() { delete[] _ptr; }
};
// for getting correct starting positions in matrix for each node,
// only needed after removing nodes
void Slam::update_starts()
{
int start = 0;
const list<Node*>& nodes = get_nodes();
for (list<Node*>::const_iterator it = nodes.begin(); it != nodes.end(); it++)
{
Node* node = *it;
node->_start = start;
start += node->dim();
}
}
Slam::Slam()
: Graph(),
_step(0), _prop(Properties()),
_covariances(this),
_require_batch(true), _cost_func(NULL),
_dim_nodes(0), _dim_measure(0),
_num_new_measurements(0), _num_new_rows(0),
_opt(*this)
{
}
Slam::~Slam()
{
}
void Slam::save(const string fname) const
{
ofstream out(fname.c_str(), ios::out | ios::binary);
require(out, "Slam.save: Cannot open output file.");
write(out);
out.close();
}
void Slam::add_node(Node* node)
{
Graph::add_node(node);
_dim_nodes += node->dim();
}
void Slam::add_factor(Factor* factor)
{
// adds itself to factor lists of adjacent nodes; also initialized linked nodes if necessary
factor->initialize_internal();
// needed to change cost function
factor->set_cost_function(&_cost_func);
Graph::add_factor(factor);
_num_new_measurements++;
_num_new_rows += factor->dim();
_dim_measure += factor->dim();
}
void Slam::remove_node(Node* node)
{
// make a copy, as the original will indirectly be modified below in remove_factor()
list<Factor*> factors = node->factors();
for (list<Factor*>::iterator factor = factors.begin(); factor != factors.end(); factor++)
{
remove_factor(*factor);
}
_dim_nodes -= node->dim();
Graph::remove_node(node);
_require_batch = true;
}
void Slam::remove_factor(Factor* factor)
{
vector<Node*> nodes = factor->nodes();
for (vector<Node*>::iterator node = nodes.begin(); node != nodes.end(); node++)
{
(*node)->remove_factor(factor);
}
_dim_measure -= factor->dim();
Graph::remove_factor(factor);
_require_batch = true;
}
void Slam::incremental_update()
{
// incremental update not possible after removing nodes or factors
// (might change in the future)
if (_require_batch)
{
batch_optimization_step();
}
else if (_num_new_measurements > 0)
{
SparseSystem jac_new = jacobian_partial(_num_new_measurements);
_opt.augment_sparse_linear_system(jac_new, _prop);
_num_new_measurements = 0;
_num_new_rows = 0;
}
}
void Slam::batch_optimization_step()
{
_require_batch = false;
// update linearization point x0 with current estimate x
_num_new_measurements = 0;
_num_new_rows = 0;
_opt.relinearize(_prop);
}
UpdateStats Slam::update()
{
UpdateStats stats;
stats.batch = false;
stats.solve = false;
if (_step%_prop.mod_update == 0)
{
if (_step%_prop.mod_batch == 0)
{
// batch solve periodically to avoid fill-in
if (!_prop.quiet)
{
cout << endl;
cout << "step " << _step;
}
batch_optimization_step();
stats.batch = true;
}
else
{
// for efficiency, incrementally update most of the time.
if (!_prop.quiet)
{
cout << ".";
fflush(stdout);
}
incremental_update();
if (_step%_prop.mod_solve == 0)
{
stats.solve = true;
_opt.update_estimate(_prop);
}
}
}
_step++;
stats.step = _step;
return stats;
}
int Slam::batch_optimization()
{
int num_iterations = 0;
int variables_deleted;
int measurements_deleted;
erase_marked(variables_deleted, measurements_deleted);
_dim_nodes -= variables_deleted;
_dim_measure -= measurements_deleted;
_opt.batch_optimize(_prop, &num_iterations);
return num_iterations;
}
void Slam::set_cost_function(cost_func_t func)
{
_cost_func = func;
}
void Slam::apply_exmap(const Eigen::VectorXd& x)
{
int pos = 0;
for (list<Node*>::iterator node = _nodes.begin(); node != _nodes.end(); node++)
{
int dim = (*node)->dim();
const VectorXd& xi = x.segment(pos, dim);
(*node)->apply_exmap(xi);
pos += dim;
}
}
void Slam::self_exmap(const Eigen::VectorXd& x)
{
int pos = 0;
for (list<Node*>::iterator node = _nodes.begin(); node != _nodes.end(); node++)
{
int dim = (*node)->dim();
VectorXd xi = x.segment(pos, dim);
(*node)->self_exmap(xi);
pos += dim;
}
}
void Slam::linpoint_to_estimate()
{
for (list<Node*>::iterator node = _nodes.begin(); node != _nodes.end(); node++)
{
(*node)->linpoint_to_estimate();
}
}
void Slam::estimate_to_linpoint()
{
for (list<Node*>::iterator node = _nodes.begin(); node != _nodes.end(); node++)
{
(*node)->estimate_to_linpoint();
}
}
void Slam::swap_estimates()
{
for (list<Node*>::iterator node = _nodes.begin(); node != _nodes.end(); node++)
{
(*node)->swap_estimates();
}
}
VectorXd Slam::weighted_errors(Selector s)
{
VectorXd werrors(_dim_measure);
const list<Factor*>& factors = get_factors();
int start = 0;
for (list<Factor*>::const_iterator it = factors.begin(); it != factors.end(); it++)
{
int dim = (*it)->dim();
werrors.segment(start, dim) = (*it)->error(s);
start += dim;
}
return werrors;
}
double Slam::chi2(Selector s)
{
return weighted_errors(s).squaredNorm();
}
double Slam::local_chi2(int last_n)
{
// avoiding two passes by allocating maximum size vector
VectorXd werrors(_dim_measure);
const list<Factor*>& factors = get_factors();
int start = _dim_measure;
int n = 0;
for (list<Factor*>::const_reverse_iterator it = factors.rbegin();
it != factors.rend() && n<last_n;
it++, n++)
{
int dim = (*it)->dim();
start -= dim;
werrors.segment(start, dim) = (*it)->error(ESTIMATE);
}
// only use actually calculated part of werrors
return werrors.tail(_dim_measure - start).squaredNorm();
}
double Slam::normalized_chi2()
{
return chi2() / (double)(_dim_measure - _dim_nodes);
}
const SparseSystem& Slam::get_R() const
{
return _R;
}
const double epsilon = 0.0001;
SparseSystem Slam::jacobian_numerical_columnwise()
{
// label starting points of rows, and initialize sparse row vectors with
// correct number of entries
int num_rows = _dim_measure;
DeleteOnReturn rows_ptr(new SparseVector*[num_rows]);
SparseVector** rows = rows_ptr._ptr; //[num_rows];
int pos = 0;
vector<int> factor_offset(get_factors().size());
for (list<Factor*>::const_iterator it = get_factors().begin(); it != get_factors().end(); it++)
{
(*it)->_start = pos;
int dimtotal = 0;
for (vector<Node*>::const_iterator it2 = (*it)->nodes().begin(); it2 != (*it)->nodes().end(); it2++)
{
dimtotal += (*it2)->dim();
}
for (int i = 0; i<(*it)->dim(); i++, pos++)
{
// do not delete, will be pulled into SparseSystem below
rows[pos] = new SparseVector(dimtotal);
}
}
// larger than needed, but avoids some book keeping and avoids many (smaller) allocations
VectorXd y_plus(num_rows);
VectorXd y_minus(num_rows);
int col = 0;
for (list<Node*>::const_iterator it = get_nodes().begin(); it != get_nodes().end(); it++)
{
Node* node = *it;
int dim_node = node->dim();
VectorXd delta(dim_node);
delta.setZero();
VectorXd original = node->vector0();
for (int c = 0; c<dim_node; c++, col++)
{
// calculate column for +epsilon
delta(c) = epsilon;
node->self_exmap(delta);
int row = 0;
for (list<Factor*>::const_iterator it_factor = node->factors().begin();
it_factor != node->factors().end();
it_factor++)
{
Factor* factor = *it_factor;
int dim_factor = factor->dim();
y_plus.segment(row, dim_factor) = factor->evaluate();
row += dim_factor;
}
node->update0(original);
// calculate column for -epsilon
delta(c) = -epsilon;
node->self_exmap(delta);
row = 0;
for (list<Factor*>::const_iterator it_factor = node->factors().begin();
it_factor != node->factors().end();
it_factor++)
{
Factor* factor = *it_factor;
int dim_factor = factor->dim();
y_minus.segment(row, dim_factor) = factor->evaluate();
row += dim_factor;
}
node->update0(original);
delta(c) = 0.; // reusing delta
// calculate derivative
VectorXd diff = (y_plus.head(row) - y_minus.head(row)) / (epsilon + epsilon);
// write entries into sparse Jacobian
row = 0;
int i = 0;
for (list<Factor*>::const_iterator it_factor = (*it)->factors().begin();
it_factor != (*it)->factors().end();
it_factor++, i++)
{
for (int r = 0; r<(*it_factor)->dim(); r++, row++)
{
if (diff(row) != 0.)
{ // omit 0 entries
int offset = (*it_factor)->_start;
rows[offset + r]->append(col, diff(row)); // faster than SparseVector.set
}
}
}
}
}
VectorXd rhs = weighted_errors(LINPOINT);
return SparseSystem(num_rows, _dim_nodes, rows, rhs);
}
SparseSystem Slam::jacobian()
{
if (_prop.force_numerical_jacobian)
{
// column-wise is more efficient, especially if some nodes are
// connected to many factors
return jacobian_numerical_columnwise();
}
else
{
// have to do row-wise if we want to use any available symbolic
// derivatives
return jacobian_partial(-1);
}
}
const Covariances& Slam::covariances()
{
return _covariances;
}
SparseSystem Slam::jacobian_partial(int last_n)
{
update_starts();
// actual assembly of Jacobian
int num_rows = _dim_measure;
if (last_n > 0)
{
num_rows = _num_new_rows;
}
DeleteOnReturn rows_ptr(new SparseVector*[num_rows]);
SparseVector** rows = rows_ptr._ptr; //[num_rows];
VectorXd rhs(num_rows);
int row = 0;
const list<Factor*>& factors = get_factors();
list<Factor*>::const_iterator it = factors.begin();
if (last_n != -1)
{
// skip all entries except for last_n
for (int n = num_factors(); n>last_n; n--, it++);
}
for (; it != factors.end(); it++)
{
Factor* factor = *it;
Jacobian jac = factor->jacobian_internal(_prop.force_numerical_jacobian);
VectorXd jac_rhs = jac.rhs();
for (int r = 0; r<jac_rhs.rows(); r++)
{
rhs(row + r) = jac_rhs(r);
// do not delete, will be pulled into SparseSystem below
rows[row + r] = new SparseVector(jac.dimtotal());
}
for (Terms::const_iterator it = jac.terms().begin(); it != jac.terms().end(); it++)
{
int offset = it->node()->_start;
int nr = it->term().rows();
for (int r = 0; r<nr; r++)
{ // 0-entries not omitted
rows[row + r]->set(offset, it->term().row(r));
}
}
row += factor->dim();
}
return SparseSystem(num_rows, _dim_nodes, rows, rhs);
}
void Slam::print_stats()
{
double nnz = _R.nnz();
double max_per_col = _R.max_nz();
double dim = _dim_nodes;
double per_col = nnz / dim;
double fill_in = nnz / (dim*dim);
cout << "iSAM statistics:" << endl;
cout << " Normalized chi-square value: " << normalized_chi2() << endl;
cout << " Weighted sum of squared errors: " << chi2() << endl;
cout << " Number of nodes: " << num_nodes() << endl;
cout << " Number of factors: " << num_factors() << endl;
cout << " Number of variables: " << _dim_nodes << endl;
cout << " Number of measurements: " << _dim_measure << endl;
cout << " Number of non-zero entries: " << nnz << endl;
cout << " max per column: " << max_per_col << endl;
cout << " avg per column: " << per_col << endl;
cout << " fill in: " << fill_in << "%" << endl;
}
}
| [
"sven_glory@163.com"
] | sven_glory@163.com |
13c5c5e66b6977013d07b63d9ebc7ee280d53fdf | 8da25442fdd20f0dd40fb24f5def9fd70ce74b51 | /DuiDesigner/stdafx.cpp | f1ed12b71f815a191a41b278864665fea1171ce6 | [
"BSD-2-Clause"
] | permissive | bigsinger/duilib | 9916b2c85a7dea4fe617d158352592083668b339 | b558802375349339471bdba86101e8337d78f599 | refs/heads/master | 2023-02-21T08:34:06.698848 | 2023-02-10T07:01:33 | 2023-02-10T07:01:33 | 83,393,978 | 0 | 2 | null | null | null | null | GB18030 | C++ | false | false | 3,269 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// UIDesigner.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
CMainFrame* g_pMainFrame = NULL;
CToolBoxWnd* g_pToolBoxWnd = NULL;
CPropertiesWnd* g_pPropertiesWnd = NULL;
CFileView* g_pFileView = NULL;
CClassView* g_pClassView = NULL;
CResourceViewBar* g_pResourceView = NULL;
CHookAPI g_pHookAPI;
int gGetUIClass(LPCTSTR pstrClass)
{
int nClass = classPointer;
SIZE_T cchLen = _tcslen(pstrClass);
switch( cchLen ) {
case 6:
if( _tcscmp(pstrClass, _T("FormUI")) == 0 ) nClass=classWindow;
else if( _tcscmp(pstrClass, _T("EditUI")) == 0 ) nClass=classEdit;
else if( _tcscmp(pstrClass, _T("ListUI")) == 0 ) nClass=classList;
else if( _tcscmp(pstrClass, _T("TextUI")) == 0 ) nClass=classText;
break;
case 7:
if( _tcscmp(pstrClass, _T("ComboUI")) == 0 ) nClass=classCombo;
else if( _tcscmp(pstrClass, _T("LabelUI")) == 0 ) nClass=classLabel;
case 8:
if( _tcscmp(pstrClass, _T("ButtonUI")) == 0 ) nClass=classButton;
else if( _tcscmp(pstrClass, _T("OptionUI")) == 0 ) nClass=classOption;
else if( _tcscmp(pstrClass, _T("SliderUI")) == 0 ) nClass=classSlider;
break;
case 9:
if( _tcscmp(pstrClass, _T("ControlUI")) == 0 ) nClass=classControl;
else if( _tcscmp(pstrClass, _T("ActiveXUI")) == 0 ) nClass=classActiveX;
break;
case 10:
if( _tcscmp(pstrClass, _T("ProgressUI")) == 0 ) nClass=classProgress;
if( _tcscmp(pstrClass, _T("CheckBoxUI")) == 0 ) nClass=classCheckBox;
case 11:
if( _tcscmp(pstrClass, _T("ContainerUI")) == 0 ) nClass=classContainer;
else if( _tcscmp(pstrClass, _T("TabLayoutUI")) == 0 ) nClass=classTabLayout;
break;
case 12:
if( _tcscmp(pstrClass, _T("ListHeaderUI")) == 0 ) nClass=classListHeader;
else if( _tcscmp(pstrClass, _T("TileLayoutUI")) == 0 ) nClass=classTileLayout;
else if (_tcscmp(pstrClass, _T("VScrollBarUI")) == 0 ) nClass=classScrollBar;
else if (_tcscmp(pstrClass, _T("HScrollBarUI")) == 0 ) nClass=classScrollBar;
else if( _tcscmp(pstrClass, _T("WebBrowserUI")) == 0 ) nClass=classWebBrowser;
break;
case 13:
if( _tcscmp(pstrClass, _T("ChildLayoutUI")) == 0 ) nClass=classChildLayout;
break;
case 16:
if( _tcscmp(pstrClass, _T("VerticalLayoutUI")) == 0 ) nClass=classVerticalLayout;
else if( _tcscmp(pstrClass, _T("ListHeaderItemUI")) == 0 ) nClass=classListHeaderItem;
break;
case 17:
if( _tcscmp(pstrClass, _T("ListTextElementUI")) == 0 ) nClass=classListTextElement;
break;
case 18:
if( _tcscmp(pstrClass, _T("HorizontalLayoutUI")) == 0 ) nClass=classHorizontalLayout;
else if( _tcscmp(pstrClass, _T("ListLabelElementUI")) == 0 ) nClass=classListLabelElement;
break;
case 22:
if( _tcscmp(pstrClass, _T("ListContainerElementUI")) == 0 ) nClass=classListContainerElement;
break;
}
return nClass;
}
int gGetUIClass(CControlUI* pControl)
{
if(pControl==NULL)
return classPointer;
return gGetUIClass(pControl->GetClass());
} | [
"pushebp@163.com"
] | pushebp@163.com |
b01100e31beac7472ef9aefb34dd52f65206f839 | 65f16cfe6932a9c30c5fabb6a33d8621a2d09e5d | /volume009/CF 992 A - Nastya and an Array.cpp | 15ec5e284e5c9fb84b796339f531c8f8414af2c3 | [] | no_license | Daviswww/Submissions-by-UVa-etc | b059d5920964b8f361042fbceeaabc8b27e0ea61 | b16a43e54a0563d42b2721ebdaf570cdd24c4840 | refs/heads/master | 2022-11-09T13:53:37.852564 | 2022-10-30T08:28:35 | 2022-10-30T08:28:35 | 143,992,796 | 1 | 0 | null | null | null | null | BIG5 | C++ | false | false | 532 | cpp | #include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int N, A[100000];
// 輸入
cin >> N;
for(int i = 0; i < N; ++i)
{
cin >> A[i];
}
// 排序
sort(A, A + N);
// 第一個直接判斷,順便記錄起來
int ans = (A[0] == 0 ? 0 : 1), pre = A[0];
for(int i = 1; i < N; ++i)
{
// 跟前一個不一樣而且不是0就加一種
if(A[i] != pre && A[i] != 0)
{
++ans;
}
// 記錄前一個的數字
pre = A[i];
}
// 輸出
cout << ans << endl;
return 0;
}
| [
"ho861206@gmail.com"
] | ho861206@gmail.com |
a956588288e88772c19ef1eebcdcde7774650030 | 344d9301bf58e5917845fdd13bd05e5fcda0ede2 | /rosalind/algos/minHeap.cpp | 80afd4fe71ccf82e8a49283303e1dd4a345fd903 | [] | no_license | davidhin/Misc-Works | ace9d0ea1fce612a6b656a54522aab94ac72820a | e86900878eea5fb00df52b294201710acdaaf101 | refs/heads/master | 2021-09-15T03:10:50.521049 | 2018-03-06T02:29:42 | 2018-03-06T02:29:42 | 111,035,948 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,465 | cpp | #pragma once
#include <iostream>
#include <vector>
// Pair where first is node and second is distance
typedef std::vector<std::pair<int, int>> nodeDist;
void swap(nodeDist* a, int a1, int a2)
{
std::pair<int, int> temp = (*a).at(a1);
(*a).at(a1) = (*a).at(a2);
(*a).at(a2) = temp;
}
class MinHeap
{
private:
nodeDist* heap;
public:
MinHeap();
void minHeapify();
void push_back(std::pair<int, int>);
void pop_front();
void display();
bool empty();
std::pair<int, int> front();
~MinHeap() { delete heap; }
};
MinHeap::MinHeap()
{
heap = new nodeDist;
}
void MinHeap::minHeapify()
{
nodeDist* a = heap;
int n = heap->size();
for (int i = 2; i <= n; i++)
{
while ((*a).at(i - 1).second < (*a).at(i / 2 - 1).second)
{
int current = i;
int next = i / 2;
while ((*a).at(current - 1).second <= (*a).at(next - 1).second)
{
swap(a, current - 1, next - 1);
current /= 2;
next /= 2;
if (next == 0) break;
}
}
}
}
void MinHeap::push_back(std::pair<int, int> num)
{
nodeDist* a = heap;
a->push_back(num);
int i = a->size();
if (i > 1)
while ((*a).at(i - 1).second < (*a).at(i / 2 - 1).second)
{
int current = i;
int next = i / 2;
while ((*a).at(current - 1).second <= (*a).at(next - 1).second)
{
swap(a, current - 1, next - 1);
current /= 2;
next /= 2;
if (next == 0) break;
}
}
}
void MinHeap::pop_front()
{
nodeDist* a = heap;
swap(a, 0, a->size()-1);
a->pop_back();
int n = a->size();
int i = 1;
while (true)
{
if (2*i < n && (*a).at(2*i).second <= (*a).at(2*i - 1).second && (*a).at(i-1).second >= (*a).at(2*i).second)
{
swap(a, i - 1, 2*i);
i = i*2 + 1;
}
else if (2*i - 1 < n && (*a).at(i-1).second >= (*a).at(2*i - 1).second )
{
swap(a, i - 1, 2*i - 1);
i *= 2;
}
else break;
}
}
std::pair<int, int> MinHeap::front()
{
return heap->at(0);
}
void MinHeap::display()
{
printHeap(*heap, heap->size());
}
bool MinHeap::empty()
{
if (heap->size() == 0) return 1;
return 0;
}
//void swapA(int* a, int a1, int a2)
//{
// int temp = a[a1];
// a[a1] = a[a2];
// a[a2] = temp;
//}
//
//void minHeap(int* a, int n)
//{
// for (int i = 2; i <= n; i++)
// {
// while (a[i - 1] < a[i / 2 - 1])
// {
// int current = i;
// int next = i / 2;
// while (a[current - 1] <= a[next - 1])
// {
// swapA(a, current - 1, next - 1);
// current /= 2;
// next /= 2;
// if (next == 0) break;
// }
// }
// }
//}
| [
"hello@davidhin.com"
] | hello@davidhin.com |
50c1cbb29581dd53fd62bea07b8ebc92c8e10dff | 296ae881fb69cea7e8c1e88ce6517114555ffc51 | /Excersise 1 - KMeans Clustering/src/CustomTypes/Point.h | eb74cd4d05cc584ec04a8f19c9e10e5ce365879b | [] | no_license | RobertKraaijeveld/DataMiningExcersises | 69cd54086ce672f7c233c91b5fa7cdbbe25fccdb | dfbd3e5bee2a4003f5d643eaa312c9c65f3565b1 | refs/heads/master | 2021-01-19T00:29:56.867291 | 2017-04-08T10:38:58 | 2017-04-08T10:38:58 | 82,147,287 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 437 | h | #ifndef POINT_H
#define POINT_H
#include "GenericVector.h"
#include <map>
struct Centroid {
int id;
bool hasChanged = true;
GenericVector vector;
Centroid(int id, GenericVector vector);
Centroid(){ id = -1; vector = GenericVector(); };
};
class Point {
public:
Point(int cId, GenericVector vector);
int centroidId;
GenericVector vector;
double distanceToCentroid;
};
#endif
| [
"0890289@hr.nl"
] | 0890289@hr.nl |
80398d5a2b83d5eb9c1fe45f71fa1d65cc28502a | 3a5cb24560fb1e7bb89166aed99a83749e128c38 | /TTCS_GV3_BĐ3/BAI_1/source_code_1.cpp | be1bd92f9076cf6b4ea11310c56b2661b07c946b | [] | no_license | nnson58th2/NguyenNhuSon_58131375 | 7bdc20acf2e20cd29a8649750a2ce246977974c3 | 71a039c0e9404bf393a045f9b89ec4f08f8030c5 | refs/heads/master | 2020-04-13T14:55:11.979702 | 2019-01-22T01:56:29 | 2019-01-22T01:56:29 | 163,276,165 | 0 | 0 | null | null | null | null | WINDOWS-1258 | C++ | false | false | 6,332 | cpp | #include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
// Khai báo c?u trúc danh b?
typedef struct {
string name;
string phone;
string email;
string address;
string sex;
} CONTACT;
void addContact(); // Hàm thêm danh b?
void showFileContact(); // Hàm hi?n th? danh b?
void editByName(); // Hàm ch?nh s?a danh b? theo tên
void deleteByPhone(); // Hàm xóa danh b? theo s? di?n tho?i
void searchByName(); // Hàm t́m ki?m danh b? theo tên
bool returnToMenu(); // Hàm quay tr? l?i menu
void showMenu(); // Hàm hi?n th? menu
void menuOption(); // Hàm menu tùy ch?n
// Thêm danh b? vào danh sách
void addContact(){
fstream fo;
fstream ai;
string s;
fo.open("du_lieu/danh_ba.txt", ios::out | ios::app);
ai.open("du_lieu/them_danh_ba.txt", ios::in);
fflush(stdin);
getline(ai, s);
do {
fo << s << endl;
fflush(stdin);
getline(ai, s);
} while (s.compare("") != 0);
fo << endl;
cout << "Them thanh cong!" << endl;
fo.close();
ai.close();
}
// Hi?n th? danh sách danh b?
void showFileContact(){
fstream fContact;
string s;
CONTACT co;
fContact.open("du_lieu/danh_ba.txt", ios::in);
getline(fContact, s);
cout << "Danh sach danh ba:" << endl;
do {
co.name = s;
getline(fContact, co.sex);
getline(fContact, co.phone);
getline(fContact, co.email);
getline(fContact, co.address);
cout << co.name << "\t" << co.sex << "\t" << co.phone << "\t" << co.email << "\t" << co.address << endl;
getline(fContact, s);
} while (s.compare("") != 0);
fContact.close();
}
// Ch?nh s?a danh b? b?i tên
void editByName(){
CONTACT co;
string x, s;
fstream fi;
fstream eo;
fstream ci;
fi.open("du_lieu/danh_ba.txt", ios::in);
eo.open("du_lieu/danh_ba_chinh_su.txt", ios::out);
ci.open("du_lieu/du_lieu_chinh_sua.txt", ios::in);
cout << "Nhap ten lien lac muon chinh sua: ";
getline(cin, x);
fflush(stdin);
getline(fi, s);
do {
co.name = s;
if (x.compare(co.name) == 0) {
for (int i = 1; i <= 4; i++)
getline(fi, s);
fflush(stdin);
getline(ci, s);
eo << s << endl;
fflush(stdin);
getline(ci, s);
eo << s << endl;
fflush(stdin);
getline(ci, s);
eo << s << endl;
fflush(stdin);
getline(ci, s);
eo << s << endl;
fflush(stdin);
getline(ci, s);
eo << s << endl;
fflush(stdin);
} else {
eo << s << endl;
fflush(stdin);
getline(fi, s);
eo << s << endl;
fflush(stdin);
getline(fi, s);
eo << s << endl;
fflush(stdin);
getline(fi, s);
eo << s << endl;
fflush(stdin);
getline(fi, s);
eo << s << endl;
fflush(stdin);
}
getline(fi, s);
} while (s.compare("") != 0);
cout << "Chinh sua thanh cong!" << endl;
fi.close();
eo.close();
ci.close();
}
// Xóa danh b? b?i s? di?n tho?i
void deleteByPhone(){
CONTACT co;
string x;
string s;
fstream fi;
fstream go;
fi.open("du_lieu/danh_ba.txt", ios::in);
go.open("du_lieu/danh_ba_xoa.txt", ios::out);
cout << "Nhap ten lien lac muon xoa: ";
getline(cin, x);
fflush(stdin);
getline(fi, s);
do {
co.name = s;
if (x.compare(co.name) == 0)
for (int i = 1; i <= 5; i++)
getline(fi, s);
else {
go << s << endl;
fflush(stdin);
getline(fi, s);
go << s << endl;
fflush(stdin);
getline(fi, s);
go << s << endl;
fflush(stdin);
getline(fi, s);
go << s << endl;
fflush(stdin);
getline(fi, s);
go << s << endl;
fflush(stdin);
}
getline(fi, s);
} while (s.compare("") != 0);
cout << "Xoa thanh cong!" << endl;
fi.close();
go.close();
}
// T́m ki?m danh b? b?i tên
void searchByName(){
CONTACT co;
string x;
string s;
fstream fi;
fi.open("du_lie/danh_ba.txt", ios::in);
cout << "Nhap ten muon tim kiem: ";
getline(cin, x);
fflush(stdin);
getline(fi, s);
do {
co.name = s;
getline(fi, co.sex);
getline(fi, co.phone);
getline(fi, co.email);
getline(fi, co.address);
if (x.compare(co.name) == 0)
cout << co.name << "\t" << co.sex << "\t" << co.phone << "\t" << co.email << "\t" << co.address << endl;
getline(fi, s);
} while (s.compare("") != 0);
fi.close();
}
bool returnToMenu() {
char rtnMenu;
cout << "-----------------------------" << endl;
cout << "Enter z to return to the menu:> ";
cin >> rtnMenu;
if(rtnMenu == 'z' || rtnMenu == 'Z') {
return true;
} return false;
}
void showMenu() {
cout << "1. Add contact" << endl;
cout << "2. Show contact" << endl;
cout << "3. Edit contact" << endl;
cout << "4. Delete contact" << endl;
cout << "5. Find contact" << endl;
cout << "6. Exit contact" << endl;
cout << "Enter your choice:> ";
}
void menuOption() {
int x;
do {
showMenu();
cin >> x;
if (x < 1 || x > 6)
cout << "Chon sai | Chon lai!" << endl;
cout << "--------------------" << endl;
} while(x < 1 || x > 6);
switch(x) {
case 1:
system("cls");
addContact();
if(returnToMenu()) {
system("cls");
menuOption();
} else {
cout << "Exited!" << endl;
}
break;
case 2:
system("cls");
showFileContact();
if(returnToMenu()) {
system("cls");
menuOption();
} else {
cout << "Exited!" << endl;
}
break;
case 3:
system("cls");
cout << "------ Edit ------" << endl;
editByName();
if(returnToMenu()) {
system("cls");
menuOption();
} else {
cout << "Exited!" << endl;
}
break;
case 4:
system("cls");
cout << "------ Delete ------" << endl;
deleteByPhone();
if(returnToMenu()) {
system("cls");
menuOption();
} else {
cout << "Exited!" << endl;
}
break;
case 5:
system("cls");
cout << "------ Search ------" << endl;
searchByName();
if(returnToMenu()) {
system("cls");
menuOption();
} else {
cout << "Exited!" << endl;
}
break;
case 6:
cout << "Exited!" << endl;
break;
default:
system("cls");
showMenu();
cout << "Wrong option!" << endl;
menuOption();
}
}
int main() {
menuOption();
}
| [
"nhuson2306@gmail.com"
] | nhuson2306@gmail.com |
f66270909da44261e229ccd632ef224bf98353fd | 62e19ae450e4e97e45549706804d218a77fba60b | /test/pressure/client.cpp | c6b2a6233396d1104b1db446d8b16ac05c4cf15e | [] | no_license | czb0737/Mini-server | ace64d2525f60e21664100be3e776afa36e3867b | a01cdd57d3f99f9814a24e8c51ee44b2a6ff2944 | refs/heads/master | 2021-01-19T12:54:45.028796 | 2017-10-08T23:39:46 | 2017-10-08T23:39:46 | 100,816,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,896 | cpp | #ifndef SERVER_CPP_INCLUDED
#define SERVER_CPP_INCLUDED
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "../../json.hpp"
#include <string>
#include <fstream>
#include "split.cpp"
#include <vector>
#include "../../access_layer/connect.cpp"
/*
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
*/
using Json = nlohmann::json;
using namespace std;
#define server_ip "127.0.0.1"
#define port 8192
#endif // SERVER_CPP_INCLUDE
int main(int argc, char *argv[])
{
int cfd = 0;
int recbytes =0;
int sin_size = 0;
char *buffer;
struct sockaddr_in s_add, c_add;
cout << "Hello, welcome to client!" << endl;
// Open file
fstream file(argv[1]);
// string user_name, friend_name;
// string password;
// string message;
string token;
int t = 0, op = 0;
// Only register or login
// cout << "Pleast enter type, operating and user_name: " << endl;
// file >> t >> op >> user_name;
string ss;
int count = 0;
while(getline(file, ss, '\n'))
{
cout << "Count: " << count++ << endl;
// if (count++ > 1050) break;
cout << "Test: " << ss << endl;
vector<string> v = split(ss, ' ');
t = stoi(v[0]);
op = stoi(v[1]);
Json json = Json();
json["type"] = t;
json["operating"] = op;
json["userName"] = v[2];
if (t == 1)
{
json["password"] = v[3];
}
else
{
json["token"] = token;
}
if (t == 2 && op > 1)
{
json["userName2"] = v[3];
}
if (t == 3 && op == 2)
{
json["userName2"] = v[3];
json["message"] = v[4];
}
cfd = connect_to_server(port);
string s = json.dump();
cout << s << endl;
int size = s.size();
buffer = new char[size + 1];
s.copy(buffer, size, 0);
buffer[size] = '\0';
if(-1 == write(cfd, buffer, size))
{
cout << "Fail to send it !" << endl;
}
delete[] buffer;
buffer = new char[1024];
if(-1 == (recbytes = read(cfd,buffer,1024)))
{
printf("read data fail !\r\n");
return -1;
}
printf("read ok\r\nREC:\r\n");
buffer[recbytes]='\0';
printf("%s\r\n",buffer);
if (t == 1 && op == 2)
{
auto j = Json::parse(buffer);
token = j["token"];
}
usleep(5000);
}
close(cfd);
return 0;
}
| [
"czb0737@gmail.com"
] | czb0737@gmail.com |
c231d41e452104133fb982d2180497355ba8c56d | f4f0170679edfb9d79aa2cbe8c86ebbbfa9fd06c | /bbs/msgbase1.h | d578afcda4179011f0aad90d4054c3ed98f64dba | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Cloudxtreme/wwiv | d534bc298b0437697e82a9edfb81aa4dab4a44ea | eef320c28f0057521584cf59176a8f7d88e57109 | refs/heads/master | 2021-09-20T03:35:55.551365 | 2018-08-02T16:05:12 | 2018-08-02T16:05:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,471 | h | /**************************************************************************/
/* */
/* WWIV Version 5.x */
/* Copyright (C)1998-2017, WWIV Software Services */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, */
/* software distributed under the License is distributed on an */
/* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, */
/* either express or implied. See the License for the specific */
/* language governing permissions and limitations under the License. */
/**************************************************************************/
#ifndef __INCLUDED_BBS_MSGBASE1_H__
#define __INCLUDED_BBS_MSGBASE1_H__
#include <string>
#include "sdk/config.h"
#include "sdk/subxtr.h"
#include "sdk/vardec.h"
#include "sdk/fido/fido_address.h"
class MessageEditorData;
class PostReplyToData {
public:
// Original text this next post will reply to
std::string text;
// Original name of the sender we are replying to
std::string name;
// Original title this next post will reply to
std::string title;
};
class PostData {
public:
explicit PostData(const PostReplyToData& i) : reply_to(i) {}
PostData() : PostData(PostReplyToData()) {}
PostReplyToData reply_to;
};
void send_net_post(postrec* p, const wwiv::sdk::subboard_t& sub);
void post(const PostData& data);
void add_ftn_msgid(const wwiv::sdk::Config& config, wwiv::sdk::fido::FidoAddress addr, const std::string& msgid,
MessageEditorData* data);
std::string grab_user_name(messagerec* m, const std::string& file_name, int network_number);
void qscan(uint16_t start_subnum, bool& next_sub);
void nscan(uint16_t start_subnum = 0);
void ScanMessageTitles();
void remove_post();
#endif // __INCLUDED_BBS_MSGBASE1_H__ | [
"rushfan@wwivbbs.org"
] | rushfan@wwivbbs.org |
a785118ded25812a6f9eb7234978bd45aa3419b7 | 6347f7e29429e88289a6f36caab9f10a6514a704 | /src/widget/QJD/qjdradiobutton.h | de5d04e880d66d76bcb39295932ae44ceca420d7 | [] | no_license | xtfllbl/Flow2 | 1954f56bf6a180f688c1fcfe834740ee68128c9d | b0f48c604d480aaa8f8bd07791000ece9b0d88da | refs/heads/master | 2021-01-02T22:45:46.438159 | 2012-07-16T06:39:15 | 2012-07-16T06:39:15 | 2,739,626 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 585 | h | #ifndef QJDRADIOBUTTON_H
#define QJDRADIOBUTTON_H
#include <QRadioButton>
/// 与其他控件不一样, 麻烦就麻烦在多个来整合一个
class QJDRadioButton : public QRadioButton
{
Q_OBJECT
public:
explicit QJDRadioButton(QWidget *parent = 0);
int propertyInt;
void setPropertyList(QStringList);
signals:
void sigRadioChanged(int, QStringList);
public slots:
private:
QString PROPERTY;
QString DESC;
QString DATATYPE;
QString DISPLAYTYPE;
QString OPTION;
private slots:
void emitStateChanged(bool);
};
#endif // QJDRADIOBUTTON_H
| [
"xtfllbl@hotmail.com"
] | xtfllbl@hotmail.com |
8722f63b68297a49365e1ac5fc3dbf93e0051359 | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Plugins/Online/OnlineSubsystemUtils/Source/OnlineSubsystemUtils/Private/TestBeaconHost.cpp | 6e8d61717f1b2f1ac1209c0f59ba86f99efc51e0 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 1,008 | cpp | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "TestBeaconHost.h"
#include "TestBeaconClient.h"
ATestBeaconHost::ATestBeaconHost(const FObjectInitializer& ObjectInitializer) :
Super(ObjectInitializer)
{
ClientBeaconActorClass = ATestBeaconClient::StaticClass();
BeaconTypeName = ClientBeaconActorClass->GetName();
}
bool ATestBeaconHost::Init()
{
#if !UE_BUILD_SHIPPING
UE_LOG(LogBeacon, Verbose, TEXT("Init"));
#endif
return true;
}
void ATestBeaconHost::OnClientConnected(AOnlineBeaconClient* NewClientActor, UNetConnection* ClientConnection)
{
#if !UE_BUILD_SHIPPING
Super::OnClientConnected(NewClientActor, ClientConnection);
ATestBeaconClient* BeaconClient = Cast<ATestBeaconClient>(NewClientActor);
if (BeaconClient != NULL)
{
BeaconClient->ClientPing();
}
#endif
}
AOnlineBeaconClient* ATestBeaconHost::SpawnBeaconActor(UNetConnection* ClientConnection)
{
#if !UE_BUILD_SHIPPING
return Super::SpawnBeaconActor(ClientConnection);
#else
return NULL;
#endif
}
| [
"tungnt.rec@gmail.com"
] | tungnt.rec@gmail.com |
20de737a0cb61fe4f24f5167a372df9229b083bb | e5e0d729f082999a9bec142611365b00f7bfc684 | /tensorflow/core/common_runtime/lower_function_call_op.h | 6a418a928223c79bb9e3df9969b28ef83626754a | [
"Apache-2.0"
] | permissive | NVIDIA/tensorflow | ed6294098c7354dfc9f09631fc5ae22dbc278138 | 7cbba04a2ee16d21309eefad5be6585183a2d5a9 | refs/heads/r1.15.5+nv23.03 | 2023-08-16T22:25:18.037979 | 2023-08-03T22:09:23 | 2023-08-03T22:09:23 | 263,748,045 | 763 | 117 | Apache-2.0 | 2023-07-03T15:45:19 | 2020-05-13T21:34:32 | C++ | UTF-8 | C++ | false | false | 1,481 | h | /* Copyright 2019 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.
==============================================================================*/
#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_FUNCTION_CALL_OP_H_
#define TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_FUNCTION_CALL_OP_H_
#include "tensorflow/core/common_runtime/optimization_registry.h"
#include "tensorflow/core/lib/core/status.h"
namespace tensorflow {
// Replaces function call node `n` with its function body. Uses
// InlineFunctionBody from `common_runtime/function.{h,cc}`. If function
// inlining is not possible or safe (see ValidateInlining), leaves the graph in
// unmodified state and returns Status::OK();
Status RewriteFunctionCallNode(Node* n, Graph* g,
const FunctionLibraryDefinition& flib_def,
bool keep_caller_fetchable);
} // namespace tensorflow
#endif // TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_FUNCTION_CALL_OP_H_
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
b7b4c429cd6cac13bb4c37051b07c22c4d8485fa | 93c65db089da913177dbcc91b0684e7ef4d6f0ac | /openexr-c/abigen/std_vector.cpp | 8f2942ec1c2f8f3e3a9f4ff9dedf0efa3dfec221 | [
"BSD-3-Clause"
] | permissive | bgyss/openexr-bind | 2e20075fa7b4d237c694d6afc3ddca6fa54e432c | ee4fd6010beedb0247737a39ee61ffb87c586448 | refs/heads/main | 2023-07-10T11:08:05.099940 | 2021-09-02T08:33:45 | 2021-09-02T08:33:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 109 | cpp | #include <string>
#include <vector>
#include "std_vector.hpp"
void abi_gen_std_vector(std::ostream& os) {
}
| [
"anderslanglands@gmail.com"
] | anderslanglands@gmail.com |
a0c89c20cf2cbdbcd3035806932771e055434df2 | c80df697c0b66cd58a039c928574926bd6161a36 | /runtime/vm/reverse_pc_lookup_cache.cc | 77d4716b192660c3fe4550776262c2c090f65d40 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-unknown"
] | permissive | dart-lang/sdk | d4e50700dfc54b33c0a7a09fab1aa9623ebc84e5 | b25873f11c68772408f6a4aea5f5c961f31ac9f7 | refs/heads/master | 2023-08-31T11:13:09.400940 | 2023-08-31T09:10:57 | 2023-08-31T09:10:57 | 35,726,310 | 10,701 | 2,079 | BSD-3-Clause | 2023-09-14T10:34:15 | 2015-05-16T14:14:58 | Dart | UTF-8 | C++ | false | false | 4,149 | cc | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/reverse_pc_lookup_cache.h"
#include "vm/isolate.h"
#include "vm/object.h"
#include "vm/object_store.h"
#include "vm/stub_code.h"
namespace dart {
CodePtr ReversePc::FindCodeInGroup(IsolateGroup* group,
uword pc,
bool is_return_address) {
#if defined(DART_PRECOMPILED_RUNTIME)
// This can run in the middle of GC and must not allocate handles.
NoSafepointScope no_safepoint;
if (is_return_address) {
pc--;
}
// This expected number of tables is low (one per loading unit), so we go
// through them linearly. If this changes, would could sort the table list
// during deserialization and binary search for the table.
GrowableObjectArrayPtr tables = group->object_store()->instructions_tables();
intptr_t tables_length = Smi::Value(tables->untag()->length());
for (intptr_t i = 0; i < tables_length; i++) {
InstructionsTablePtr table = static_cast<InstructionsTablePtr>(
tables->untag()->data()->untag()->element(i));
CodePtr code = InstructionsTable::FindCode(table, pc);
if (code != Code::null()) {
return code;
}
}
#endif // defined(DART_PRECOMPILED_RUNTIME)
return Code::null();
}
const UntaggedCompressedStackMaps::Payload* ReversePc::FindStackMapInGroup(
IsolateGroup* group,
uword pc,
bool is_return_address,
uword* code_start,
const UntaggedCompressedStackMaps::Payload** global_table) {
#if defined(DART_PRECOMPILED_RUNTIME)
// This can run in the middle of GC and must not allocate handles.
NoSafepointScope no_safepoint;
if (is_return_address) {
pc--;
}
// This expected number of tables is low (one per loading unit), so we go
// through them linearly. If this changes, would could sort the table list
// during deserialization and binary search for the table.
GrowableObjectArrayPtr tables = group->object_store()->instructions_tables();
intptr_t tables_length = Smi::Value(tables->untag()->length());
for (intptr_t i = 0; i < tables_length; i++) {
InstructionsTablePtr table = static_cast<InstructionsTablePtr>(
tables->untag()->data()->untag()->element(i));
auto map = InstructionsTable::FindStackMap(table, pc, code_start);
if (map != nullptr) {
// Take global table from the first table.
table = static_cast<InstructionsTablePtr>(
tables->untag()->data()->untag()->element(0));
*global_table = InstructionsTable::GetCanonicalStackMap(table);
return map;
}
}
#endif // defined(DART_PRECOMPILED_RUNTIME)
*code_start = 0;
return nullptr;
}
const UntaggedCompressedStackMaps::Payload* ReversePc::FindStackMap(
IsolateGroup* group,
uword pc,
bool is_return_address,
uword* code_start,
const UntaggedCompressedStackMaps::Payload** global_table) {
ASSERT(FLAG_precompiled_mode);
NoSafepointScope no_safepoint;
auto map = FindStackMapInGroup(group, pc, is_return_address, code_start,
global_table);
if (map == nullptr) {
map = FindStackMapInGroup(Dart::vm_isolate_group(), pc, is_return_address,
code_start, global_table);
}
return map;
}
CodePtr ReversePc::FindCode(IsolateGroup* group,
uword pc,
bool is_return_address) {
ASSERT(FLAG_precompiled_mode);
NoSafepointScope no_safepoint;
auto code_descriptor = FindCodeInGroup(group, pc, is_return_address);
if (code_descriptor == Code::null()) {
code_descriptor =
FindCodeInGroup(Dart::vm_isolate_group(), pc, is_return_address);
}
return code_descriptor;
}
CodePtr ReversePc::Lookup(IsolateGroup* group,
uword pc,
bool is_return_address) {
ASSERT(FLAG_precompiled_mode);
NoSafepointScope no_safepoint;
return FindCode(group, pc, is_return_address);
}
} // namespace dart
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
c9dab130ad31099050301842e3fcffe5c6ef9d25 | 47b0856c829201ec1039eec9994561f5cb003dc5 | /data_structure/rb_tree/work.bak/rb_tree.h | 436ce79ea18db2f93709af1889b96b8919ca07d0 | [] | no_license | clear-river/c.algs | cf450f61804d7231216a7ff1ddd6852df2273e42 | 873fa00c38f0c95265f418b529b334e49945ba00 | refs/heads/master | 2021-05-30T01:33:57.989330 | 2015-11-21T13:55:38 | 2015-11-21T13:55:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,896 | h | #include <stdio.h>
#include <stdlib.h>
#include <stdexcept>
#include "./bt_node.h"
class rb_tree {
public:
bt_node *root;
private:
bt_node *nil;
public:
rb_tree (const rb_tree *t = NULL){
nil = new bt_node();
if (t == NULL){
root = nil; return;
}
_copy(nil, root, t->root, t->nil);
}
~rb_tree (){
if (root != nil){
_destroy (root);
}
delete nil;
}
void mid_order (){
_mid_order (root);
}
void pre_order (){
_pre_order (root);
}
bt_node* minimum (bt_node* n){
if (n == nil) {return NULL;}
while (n->l != nil){
n = n->l;
}
return n;
}
bt_node* successor (bt_node* n){
if (n == nil) {return NULL;}
if (n->r != nil) {return minimum (n->r);}
bt_node* prt = n->p;
while (prt != nil && n == prt->r){
n = prt;
prt = n->p;
}
return (prt == nil)?NULL:prt;
}
void insert (const bt_node &n){
bt_node *temp = new bt_node (n.v, bt_node::red);
bt_node *prt = nil, *crt = root;
while (crt != nil){
prt = crt;
crt = (temp->v < crt->v)?crt->l:crt->r;
}
if (prt == nil){
root = temp;
}else{
if (temp->v < prt->v){
prt->l = temp;
}else{
prt->r = temp;
}
}
temp->p = prt;
temp->l = temp->r = nil;
insert_fixup(temp);
}
bt_node* find (int v){
bt_node* result = root;
while (result != nil && result->v != v){
result = (v < result->v)? result->l:result->r;
}
return (result == nil)?NULL:result;
}
void remove (bt_node* n){
if (n == nil || n == NULL) {return;}
bt_node *n2d = n, *ch = nil;
if (n->l != nil && n->r != nil){
n2d = successor (n);
}
ch = (n2d->l != nil)? n2d->l:n2d->r;
if (n2d->p == nil){
root = ch;
}else{
if (n2d== n2d->p->l){
n2d->p->l = ch;
}else{
n2d->p->r = ch;
}
}
ch->p = n2d->p;
if (n != n2d){
n->v = n2d->v;
}
if (n2d->c == bt_node::black){
remove_fixup (ch);
}
delete n2d;
}
private:
void _copy (bt_node* prt, bt_node* &crt, const bt_node* t_r, const bt_node* t_n){
if (t_r == t_n){
crt = nil; return;
}
crt = new bt_node (*t_r);
crt->p = prt;
_copy (crt, crt->l, t_r->l, t_n);
_copy (crt, crt->r, t_r->r, t_n);
}
void _destroy (bt_node* crt){
if (crt == nil) {return;}
_destroy (crt->l);
_destroy (crt->r);
delete crt;
}
void _mid_order (const bt_node *n){
if (n == nil) {return;}
_mid_order(n->l);
printf ("%d[%s],", n->v, (n->c == bt_node::red?"red":"black"));
_mid_order (n->r);
}
void _pre_order (const bt_node* n){
if (n == nil) {return;}
printf ("%d[%s],", n->v, (n->c == bt_node::red)? "red" :"black");
_pre_order (n->l);
_pre_order (n->r);
}
void remove_fixup (bt_node* node){
bt_node * bro;
while (node != root && node->c == bt_node::black){
if (node == node->p->l){
bro = node->p->r;
if (bro->c == bt_node::red){
bro->c = bt_node::black;
node->p->c = bt_node::red;
left_rotate (node->p);
bro = node->p->r;
}
if (bro->l->c == bt_node::black && bro->r->c == bt_node::black){
bro->c = bt_node::red;
node = node->p;
continue;
}
if (bro->r->c == bt_node::black){
bro->c = bt_node::red;
bro->l->c = bt_node::black;
right_rotate (bro);
bro = node->p->r;
}
bro->c = node->p->c;
node->p->c = bro->r->c = bt_node::black;
left_rotate (node->p);
node = root;
}else{ // node == node->p->r
bro = node->p->l;
if (bro->c == bt_node::red){
bro->c = bt_node::black;
node->p->c = bt_node::red;
right_rotate (node->p);
bro = node->p->l;
}
if (bro->l->c == bt_node::black && bro->r->c == bt_node::black){
bro->c = bt_node::red;
node = node->p;
continue;
}
if (bro->l->c == bt_node::black){
bro->c = bt_node::red;
bro->r->c = bt_node::black;
left_rotate (bro);
bro = node->p->l;
}
bro->c = node->p->c;
node->p->c = bro->l->c = bt_node::black;
right_rotate (node->p);
node = root;
}// end if
}//while
node->c = bt_node::black;
}
void left_rotate (bt_node* node){
bt_node* rch = node->r;
node->r = rch->l;
if (rch->l != nil){
rch->l->p = node;
}
rch->p = node->p;
if (node->p == nil){
root = rch;
}else{
if (node == node->p->l){
node->p->l = rch;
}else{
node->p->r = rch;
}
}
node->p = rch;
rch->l = node;
}
void right_rotate (bt_node* node){
bt_node* lch = node->l;
node->l = lch->r;
if (lch->r != nil){
lch->r->p = node;
}
lch->p = node->p;
if (node->p == nil){
root = lch;
}else{
if (node == node->p->l){
node->p->l = lch;
}else{
node->p->r = lch;
}
}
lch->r = node;
node->p = lch;
}
void insert_fixup (bt_node* n){
while (n->p->c == bt_node::red){
bt_node* uncle;
if (n->p == n->p->p->l){
uncle = n->p->p->r;
if (uncle->c == bt_node::red){
n->p->c = uncle->c = bt_node::black;
n->p->p->c = bt_node::red;
n = n->p->p; continue;
}
if (n == n->p->r){
n = n->p;
left_rotate(n);
}
n->p->c = bt_node::black;
n->p->p->c = bt_node::red;
right_rotate (n->p->p);
}else{ //n->p == n->p->p->r
uncle = n->p->p->l;
if (uncle->c == bt_node::red){
n->p->c = uncle->c = bt_node::black;
n->p->p->c = bt_node::red;
n = n->p->p; continue;
}
if (n == n->p->l){
n = n->p;
right_rotate(n);
}
n->p->c = bt_node::black;
n->p->p->c = bt_node::red;
left_rotate (n->p->p);
}//endif
}//while
root->c = bt_node::black;
}
};
| [
"chen_yang@mysql.(none)"
] | chen_yang@mysql.(none) |
643e4aeb95dfc8d36765ff4e4a7f286d9cdfcd6e | c3678df923a2ff295a9696242da152cfaff466d3 | /aifm/inc/zipf.hpp | 7efb9a2279893a7da97f8575cc5a33bcacb67b66 | [
"MIT"
] | permissive | vivian-jq/AIFM | f34c2e987fb84bdff0e09980f1c69d8c648e4197 | 369ed1063ce42aa629dd9cfff67007ce985cba55 | refs/heads/master | 2023-01-29T14:26:48.642889 | 2020-12-13T01:49:10 | 2020-12-13T01:49:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,837 | hpp | #pragma once
#include <limits>
#include <random>
#include <vector>
namespace far_memory {
/**
* Example usage:
*
* std::random_device rd;
* std::mt19937 gen(rd());
* zipf_table_distribution<> zipf(300);
*
* for (int i = 0; i < 100; i++)
* printf("draw %d %d\n", i, zipf(gen));
*/
template <class IntType = unsigned long, class RealType = double>
class zipf_table_distribution {
public:
typedef IntType result_type;
static_assert(std::numeric_limits<IntType>::is_integer, "");
static_assert(!std::numeric_limits<RealType>::is_integer, "");
/// zipf_table_distribution(N, s)
/// Zipf distribution for `N` items, in the range `[1,N]` inclusive.
/// The distribution follows the power-law 1/n^s with exponent `s`.
/// This uses a table-lookup, and thus provides values more
/// quickly than zipf_distribution. However, the table can take
/// up a considerable amount of RAM, and initializing this table
/// can consume significant time.
zipf_table_distribution(const IntType n, const RealType q = 1.0);
void reset();
IntType operator()(std::mt19937 &rng);
/// Returns the parameter the distribution was constructed with.
RealType s() const;
/// Returns the minimum value potentially generated by the distribution.
result_type min() const;
/// Returns the maximum value potentially generated by the distribution.
result_type max() const;
private:
std::vector<RealType> pdf_; ///< Prob. distribution
IntType n_; ///< Number of elements
RealType q_; ///< Exponent
std::discrete_distribution<IntType> dist_; ///< Draw generator
/** Initialize the probability mass function */
IntType init(const IntType n, const RealType q);
};
} // namespace far_memory
#include "internal/zipf.ipp"
| [
"zainryan95@gmail.com"
] | zainryan95@gmail.com |
a5da61d95739fd3a3ebe7a886b9ebb6345bac54b | ac5ddd5df0107a079a26d99199476288991ca521 | /Project 36-/36 Deferred Rendering/SkyboxToneMapEffect.cpp | 549c9c7a0ee989b6c5cdc01e24bdadbc2e9b8e8f | [
"MIT"
] | permissive | huangten/DirectX11-With-Windows-SDK | 252e02470cc956ea67dc78b13f26c769d6ebc095 | 148b6306a078618f82b02ae25969dbad2831e456 | refs/heads/master | 2022-05-10T23:21:17.778766 | 2022-04-14T13:04:42 | 2022-04-14T13:04:42 | 182,062,358 | 0 | 0 | MIT | 2020-02-27T13:04:19 | 2019-04-18T09:53:25 | C++ | UTF-8 | C++ | false | false | 5,880 | cpp | #include "Effects.h"
#include "XUtil.h"
#include "RenderStates.h"
#include "EffectHelper.h"
#include "DXTrace.h"
#include "Vertex.h"
#include "TextureManager.h"
using namespace DirectX;
//
// SkyboxToneMapEffect::Impl 需要先于SkyboxToneMapEffect的定义
//
class SkyboxToneMapEffect::Impl
{
public:
// 必须显式指定
Impl() {
XMStoreFloat4x4(&m_View, XMMatrixIdentity());
XMStoreFloat4x4(&m_Proj, XMMatrixIdentity());
}
~Impl() = default;
public:
template<class T>
using ComPtr = Microsoft::WRL::ComPtr<T>;
std::unique_ptr<EffectHelper> m_pEffectHelper;
std::shared_ptr<IEffectPass> m_pCurrEffectPass;
ComPtr<ID3D11InputLayout> m_pVertexPosNormalTexLayout;
XMFLOAT4X4 m_View, m_Proj;
UINT m_MsaaLevels = 1;
};
//
// SkyboxToneMapEffect
//
namespace
{
// SkyEffect单例
static SkyboxToneMapEffect * g_pInstance = nullptr;
}
SkyboxToneMapEffect::SkyboxToneMapEffect()
{
if (g_pInstance)
throw std::exception("BasicEffect is a singleton!");
g_pInstance = this;
pImpl = std::make_unique<SkyboxToneMapEffect::Impl>();
}
SkyboxToneMapEffect::~SkyboxToneMapEffect()
{
}
SkyboxToneMapEffect::SkyboxToneMapEffect(SkyboxToneMapEffect && moveFrom) noexcept
{
pImpl.swap(moveFrom.pImpl);
}
SkyboxToneMapEffect & SkyboxToneMapEffect::operator=(SkyboxToneMapEffect && moveFrom) noexcept
{
pImpl.swap(moveFrom.pImpl);
return *this;
}
SkyboxToneMapEffect & SkyboxToneMapEffect::Get()
{
if (!g_pInstance)
throw std::exception("BasicEffect needs an instance!");
return *g_pInstance;
}
bool SkyboxToneMapEffect::InitAll(ID3D11Device * device)
{
if (!device)
return false;
if (!RenderStates::IsInit())
throw std::exception("RenderStates need to be initialized first!");
pImpl->m_pEffectHelper = std::make_unique<EffectHelper>();
Microsoft::WRL::ComPtr<ID3DBlob> blob;
D3D_SHADER_MACRO defines[] = {
{"MSAA_SAMPLES", "1"},
{nullptr, nullptr}
};
// ******************
// 创建顶点着色器
//
HR(pImpl->m_pEffectHelper->CreateShaderFromFile("SkyboxVS", L"Shaders\\SkyboxToneMap.hlsl",
device, "SkyboxVS", "vs_5_0", defines, blob.GetAddressOf()));
// 创建顶点布局
HR(device->CreateInputLayout(VertexPosNormalTex::GetInputLayout(), ARRAYSIZE(VertexPosNormalTex::GetInputLayout()),
blob->GetBufferPointer(), blob->GetBufferSize(), pImpl->m_pVertexPosNormalTexLayout.ReleaseAndGetAddressOf()));
int msaaSamples = 1;
while (msaaSamples <= 8)
{
// ******************
// 创建像素着色器
//
std::string msaaSamplesStr = std::to_string(msaaSamples);
defines[0].Definition = msaaSamplesStr.c_str();
std::string shaderName = "Skybox_" + msaaSamplesStr + "xMSAA_PS";
HR(pImpl->m_pEffectHelper->CreateShaderFromFile(shaderName, L"Shaders\\SkyboxToneMap.hlsl",
device, "SkyboxPS", "ps_5_0", defines));
// ******************
// 创建通道
//
std::string passName = "Skybox_" + msaaSamplesStr + "xMSAA";
EffectPassDesc passDesc;
passDesc.nameVS = "SkyboxVS";
passDesc.namePS = shaderName.c_str();
HR(pImpl->m_pEffectHelper->AddEffectPass(passName, device, &passDesc));
{
auto pPass = pImpl->m_pEffectHelper->GetEffectPass(passName);
pPass->SetRasterizerState(RenderStates::RSNoCull.Get());
}
msaaSamples <<= 1;
}
pImpl->m_pEffectHelper->SetSamplerStateByName("g_SamplerDiffuse", RenderStates::SSAnistropicWrap16x.Get());
// 设置调试对象名
#if (defined(DEBUG) || defined(_DEBUG)) && (GRAPHICS_DEBUGGER_OBJECT_NAME)
pImpl->m_pVertexPosNormalTexLayout->SetPrivateData(WKPDID_D3DDebugObjectName, LEN_AND_STR("SkyEffect.VertexPosNormalTexLayout"));
#endif
pImpl->m_pEffectHelper->SetDebugObjectName("SkyboxEffect");
return true;
}
void SkyboxToneMapEffect::SetRenderDefault(ID3D11DeviceContext * deviceContext)
{
deviceContext->IASetInputLayout(pImpl->m_pVertexPosNormalTexLayout.Get());
std::string passName = "Skybox_" + std::to_string(pImpl->m_MsaaLevels) + "xMSAA";
pImpl->m_pCurrEffectPass = pImpl->m_pEffectHelper->GetEffectPass(passName);
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}
void XM_CALLCONV SkyboxToneMapEffect::SetWorldMatrix(DirectX::FXMMATRIX W)
{
UNREFERENCED_PARAMETER(W);
}
void XM_CALLCONV SkyboxToneMapEffect::SetViewMatrix(DirectX::FXMMATRIX V)
{
XMStoreFloat4x4(&pImpl->m_View, V);
}
void XM_CALLCONV SkyboxToneMapEffect::SetProjMatrix(DirectX::FXMMATRIX P)
{
XMStoreFloat4x4(&pImpl->m_Proj, P);
}
void SkyboxToneMapEffect::SetMaterial(const Material& material)
{
TextureManager& tm = TextureManager::Get();
const std::string& str = material.GetTexture("$Skybox");
pImpl->m_pEffectHelper->SetShaderResourceByName("g_SkyboxTexture", tm.GetTexture(str));
}
MeshDataInput SkyboxToneMapEffect::GetInputData(const MeshData& meshData)
{
MeshDataInput input;
input.pVertexBuffers = {
meshData.m_pVertices.Get(),
meshData.m_pNormals.Get(),
meshData.m_pTexcoordArrays.empty() ? nullptr : meshData.m_pTexcoordArrays[0].Get()
};
input.strides = { 12, 12, 8 };
input.offsets = { 0, 0, 0 };
input.pIndexBuffer = meshData.m_pIndices.Get();
input.indexCount = meshData.m_IndexCount;
return input;
}
void SkyboxToneMapEffect::SetDepthTexture(ID3D11ShaderResourceView* depthTexture)
{
pImpl->m_pEffectHelper->SetShaderResourceByName("g_DepthTexture", depthTexture);
}
void SkyboxToneMapEffect::SetLitTexture(ID3D11ShaderResourceView* litTexture)
{
pImpl->m_pEffectHelper->SetShaderResourceByName("g_LitTexture", litTexture);
}
void SkyboxToneMapEffect::SetMsaaSamples(UINT msaaSamples)
{
pImpl->m_MsaaLevels = msaaSamples;
}
void SkyboxToneMapEffect::Apply(ID3D11DeviceContext * deviceContext)
{
XMMATRIX VP = XMLoadFloat4x4(&pImpl->m_View) * XMLoadFloat4x4(&pImpl->m_Proj);
VP = XMMatrixTranspose(VP);
pImpl->m_pEffectHelper->GetConstantBufferVariable("g_ViewProj")->SetFloatMatrix(4, 4, (const FLOAT*)&VP);
pImpl->m_pCurrEffectPass->Apply(deviceContext);
}
| [
"757919340@qq.com"
] | 757919340@qq.com |
ad205efe603e98e8a9e47657fe36c1ed60add2ea | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /content/browser/isolated_origin_util.cc | 48dd0d18ccf098909620e33400d018a72e29fa3e | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 5,342 | cc | // Copyright (c) 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "content/browser/isolated_origin_util.h"
#include "base/logging.h"
#include "base/strings/string_util.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "url/gurl.h"
const char* kAllSubdomainsWildcard = "[*.]";
namespace content {
IsolatedOriginPattern::IsolatedOriginPattern(base::StringPiece pattern)
: isolate_all_subdomains_(false), is_valid_(false) {
Parse(pattern);
}
IsolatedOriginPattern::IsolatedOriginPattern(const url::Origin& origin)
: IsolatedOriginPattern(origin.GetURL().spec()) {}
IsolatedOriginPattern::~IsolatedOriginPattern() = default;
IsolatedOriginPattern::IsolatedOriginPattern(
const IsolatedOriginPattern& other) = default;
IsolatedOriginPattern& IsolatedOriginPattern::operator=(
const IsolatedOriginPattern& other) = default;
IsolatedOriginPattern::IsolatedOriginPattern(IsolatedOriginPattern&& other) =
default;
IsolatedOriginPattern& IsolatedOriginPattern::operator=(
IsolatedOriginPattern&& other) = default;
bool IsolatedOriginPattern::Parse(const base::StringPiece& unparsed_pattern) {
pattern_ = unparsed_pattern.as_string();
origin_ = url::Origin();
isolate_all_subdomains_ = false;
is_valid_ = false;
size_t host_begin = unparsed_pattern.find(url::kStandardSchemeSeparator);
if (host_begin == base::StringPiece::npos || host_begin == 0)
return false;
// Skip over the scheme separator.
host_begin += strlen(url::kStandardSchemeSeparator);
if (host_begin >= unparsed_pattern.size())
return false;
base::StringPiece scheme_part = unparsed_pattern.substr(0, host_begin);
base::StringPiece host_part = unparsed_pattern.substr(host_begin);
// Empty schemes or hosts are invalid for isolation purposes.
if (host_part.size() == 0)
return false;
if (host_part.starts_with(kAllSubdomainsWildcard)) {
isolate_all_subdomains_ = true;
host_part.remove_prefix(strlen(kAllSubdomainsWildcard));
}
GURL conformant_url(base::JoinString({scheme_part, host_part}, ""));
origin_ = url::Origin::Create(conformant_url);
// Ports are ignored when matching isolated origins (see also
// https://crbug.com/914511).
const std::string& scheme = origin_.scheme();
int default_port = url::DefaultPortForScheme(scheme.data(), scheme.length());
if (origin_.port() != default_port) {
LOG(ERROR) << "Ignoring port number in isolated origin: " << origin_;
origin_ = url::Origin::Create(GURL(
origin_.scheme() + url::kStandardSchemeSeparator + origin_.host()));
}
// Can't isolate subdomains of an IP address, must be a valid isolated origin
// after processing.
if ((conformant_url.HostIsIPAddress() && isolate_all_subdomains_) ||
!IsolatedOriginUtil::IsValidIsolatedOrigin(origin_)) {
origin_ = url::Origin();
isolate_all_subdomains_ = false;
return false;
}
DCHECK(!is_valid_ || !origin_.opaque());
is_valid_ = true;
return true;
}
// static
bool IsolatedOriginUtil::DoesOriginMatchIsolatedOrigin(
const url::Origin& origin,
const url::Origin& isolated_origin) {
// Don't match subdomains if the isolated origin is an IP address.
if (isolated_origin.GetURL().HostIsIPAddress())
return origin == isolated_origin;
// Compare scheme and hostname, but don't compare ports - see
// https://crbug.com/914511.
if (origin.scheme() != isolated_origin.scheme())
return false;
// Subdomains of an isolated origin are considered to be in the same isolated
// origin.
return origin.DomainIs(isolated_origin.host());
}
// static
bool IsolatedOriginUtil::IsValidIsolatedOrigin(const url::Origin& origin) {
if (origin.opaque())
return false;
// Isolated origins should have HTTP or HTTPS schemes. Hosts in other
// schemes may not be compatible with subdomain matching.
GURL origin_gurl = origin.GetURL();
if (!origin_gurl.SchemeIsHTTPOrHTTPS())
return false;
// IP addresses are allowed.
if (origin_gurl.HostIsIPAddress())
return true;
// Disallow hosts such as http://co.uk/, which don't have a valid
// registry-controlled domain. This prevents subdomain matching from
// grouping unrelated sites on a registry into the same origin.
const bool has_registry_domain =
net::registry_controlled_domains::HostHasRegistryControlledDomain(
origin.host(),
net::registry_controlled_domains::INCLUDE_UNKNOWN_REGISTRIES,
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
if (!has_registry_domain)
return false;
// For now, disallow hosts with a trailing dot.
// TODO(alexmos): Enabling this would require carefully thinking about
// whether hosts without a trailing dot should match it.
if (origin.host().back() == '.')
return false;
return true;
}
// static
bool IsolatedOriginUtil::IsStrictSubdomain(const url::Origin& sub_origin,
const url::Origin& base_origin) {
return sub_origin.scheme() == base_origin.scheme() &&
sub_origin.port() == base_origin.port() && sub_origin != base_origin &&
sub_origin.DomainIs(base_origin.host());
}
} // namespace content
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
4959a1fc83dec7db0b22f3bedb55abacd17fe9de | 2cf962b86c499f0c836e29c6f83cdbe5798b28f3 | /Source/Kabuki.Toolkit/Kabuki.Toolkit/_GUI/UI.h | b9eedb7843d5f0d498f5b6c2f2a135d7db7b4fc2 | [
"Apache-2.0"
] | permissive | skyformat99/Kabuki.Toolkit | 89344ab31448c4e9e1e4c2f0338f3fce19e2e707 | 0a8fd6fed59a97f009a834944b372bf33c4a52c0 | refs/heads/master | 2021-01-22T17:09:02.189894 | 2016-05-13T18:47:36 | 2016-05-13T18:47:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 94,206 | h | /****************************************************************************
GLUI User Interface Toolkit
---------------------------
glui.h - Main (and only) external header for
GLUI User Interface Toolkit
--------------------------------------------------
Copyright (c) 1998 Paul Rademacher
WWW: http://sourceforge.net/projects/glui/
Forums: http://sourceforge.net/forum/?group_id=92496
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*****************************************************************************/
#ifndef GLUI_GLUI_H
#define GLUI_GLUI_H
// Having stdlib here first fixes some 'exit () redefined' errors on MSVC.NET
// that come from old GLUT headers.
#include <cstdlib>
#if defined (GLUI_FREEGLUT)
// FreeGLUT does not yet work perfectly with GLUI
// - use at your own risk.
#include <GL/freeglut.h>
#elif defined (GLUI_OPENGLUT)
// OpenGLUT does not yet work properly with GLUI
// - use at your own risk.
#include <GL/openglut.h>
#else
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#endif
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
/* GLUI API shared library export/import declarations. */
#if defined (_WIN32)
# ifdef GLUI_BUILDING_LIB
# ifdef GLUIDLL
# define GLUIAPI __declspec (dllexport)
# else
# define GLUIAPI
# endif
# else
# ifdef GLUIDLL
# define GLUIAPI __declspec (dllimport)
# else
# define GLUIAPI
# endif
# endif
#else
#define GLUIAPI
#endif
#define GLUI_VERSION 2.36f /********** Current version **********/
#if defined (_WIN32)
# if !defined (GLUI_NO_LIB_PRAGMA) && !defined (GLUI_BUILDING_LIB)
// Link automatically with GLUI library
# if defined GLUIDLL // define this when using glui dynamic library
# pragma comment (lib, "glui32dll.lib")
# else
# pragma comment (lib, "glui32.lib")
# endif
# endif
#endif
/********** List of GLUT callbacks ********/
enum GLUI_Glut_CB_Types
{
GLUI_GLUT_RESHAPE,
GLUI_GLUT_KEYBOARD,
GLUI_GLUT_DISPLAY,
GLUI_GLUT_MOUSE,
GLUI_GLUT_MOTION,
GLUI_GLUT_SPECIAL,
GLUI_GLUT_PASSIVE_MOTION,
GLUI_GLUT_ENTRY,
GLUI_GLUT_VISIBILITY
};
/********* Constants for window placement **********/
#define GLUI_XOFF 6
#define GLUI_YOFF 6
#define GLUI_ITEMSPACING 3
#define GLUI_CHECKBOX_SIZE 13
#define GLUI_RADIOBUTTON_SIZE 13
#define GLUI_BUTTON_SIZE 20
#define GLUI_STATICTEXT_SIZE 13
#define GLUI_SEPARATOR_HEIGHT 8
#define GLUI_DEFAULT_CONTROL_WIDTH 100
#define GLUI_DEFAULT_CONTROL_HEIGHT 13
#define GLUI_EDITTEXT_BOXINNERMARGINX 3
#define GLUI_EDITTEXT_HEIGHT 20
#define GLUI_EDITTEXT_WIDTH 130
#define GLUI_EDITTEXT_MIN_INT_WIDTH 35
#define GLUI_EDITTEXT_MIN_TEXT_WIDTH 50
#define GLUI_PANEL_NAME_DROP 8
#define GLUI_PANEL_EMBOSS_TOP 4
/* #define GLUI_ROTATION_WIDTH 60 */
/* #define GLUI_ROTATION_HEIGHT 78 */
#define GLUI_ROTATION_WIDTH 50
#define GLUI_ROTATION_HEIGHT (GLUI_ROTATION_WIDTH+18)
#define GLUI_MOUSE_INTERACTION_WIDTH 50
#define GLUI_MOUSE_INTERACTION_HEIGHT (GLUI_MOUSE_INTERACTION_WIDTH)+18
/** Different panel control types **/
#define GLUI_PANEL_NONE 0
#define GLUI_PANEL_EMBOSSED 1
#define GLUI_PANEL_RAISED 2
/** Max # of els in control's float_array **/
#define GLUI_DEF_MAX_ARRAY 30
/********* The control's 'active' behavior *********/
#define GLUI_CONTROL_ACTIVE_MOUSEDOWN 1
#define GLUI_CONTROL_ACTIVE_PERMANENT 2
/********* Control alignment types **********/
#define GLUI_ALIGN_CENTER 1
#define GLUI_ALIGN_RIGHT 2
#define GLUI_ALIGN_LEFT 3
/********** Limit types - how to limit spinner values *********/
#define GLUI_LIMIT_NONE 0
#define GLUI_LIMIT_CLAMP 1
#define GLUI_LIMIT_WRAP 2
/********** Translation control types ********************/
#define GLUI_TRANSLATION_XY 0
#define GLUI_TRANSLATION_Z 1
#define GLUI_TRANSLATION_X 2
#define GLUI_TRANSLATION_Y 3
#define GLUI_TRANSLATION_LOCK_NONE 0
#define GLUI_TRANSLATION_LOCK_X 1
#define GLUI_TRANSLATION_LOCK_Y 2
/********** How was a control activated? *****************/
#define GLUI_ACTIVATE_MOUSE 1
#define GLUI_ACTIVATE_TAB 2
/********** What type of live variable does a control have? **********/
#define GLUI_LIVE_NONE 0
#define GLUI_LIVE_INT 1
#define GLUI_LIVE_FLOAT 2
#define GLUI_LIVE_TEXT 3
#define GLUI_LIVE_STRING 6
#define GLUI_LIVE_DOUBLE 4
#define GLUI_LIVE_FLOAT_ARRAY 5
/************* Textbox and List Defaults - JVK ******************/
#define GLUI_TEXTBOX_HEIGHT 130
#define GLUI_TEXTBOX_WIDTH 130
#define GLUI_LIST_HEIGHT 130
#define GLUI_LIST_WIDTH 130
#define GLUI_DOUBLE_CLICK 1
#define GLUI_SINGLE_CLICK 0
#define GLUI_TAB_WIDTH 50 /* In pixels */
#define GLUI_TEXTBOX_BOXINNERMARGINX 3
#define GLUI_TEXTBOX_MIN_TEXT_WIDTH 50
#define GLUI_LIST_BOXINNERMARGINX 3
#define GLUI_LIST_MIN_TEXT_WIDTH 50
/*********************** TreePanel Defaults - JVK *****************************/
#define GLUI_TREEPANEL_DEFAULTS 0 // bar, standard bar color
#define GLUI_TREEPANEL_ALTERNATE_COLOR 1 // Alternate between 8 different bar colors
#define GLUI_TREEPANEL_ENABLE_BAR 2 // enable the bar
#define GLUI_TREEPANEL_DISABLE_BAR 4 // disable the bar
#define GLUI_TREEPANEL_DISABLE_DEEPEST_BAR 8 // disable only the deepest bar
#define GLUI_TREEPANEL_CONNECT_CHILDREN_ONLY 16 // disable only the bar of the last child of each root
#define GLUI_TREEPANEL_DISPLAY_HIERARCHY 32 // display some sort of hierachy in the tree node title
#define GLUI_TREEPANEL_HIERARCHY_NUMERICDOT 64 // display hierarchy in 1.3.2 (etc...) format
#define GLUI_TREEPANEL_HIERARCHY_LEVEL_ONLY 128 // display hierarchy as only the level depth
/******************* GLUI Scrollbar Defaults - JVK ***************************/
#define GLUI_SCROLL_ARROW_WIDTH 16
#define GLUI_SCROLL_ARROW_HEIGHT 16
#define GLUI_SCROLL_BOX_MIN_HEIGHT 5
#define GLUI_SCROLL_BOX_STD_HEIGHT 16
#define GLUI_SCROLL_STATE_NONE 0
#define GLUI_SCROLL_STATE_UP 1
#define GLUI_SCROLL_STATE_DOWN 2
#define GLUI_SCROLL_STATE_BOTH 3
#define GLUI_SCROLL_STATE_SCROLL 4
#define GLUI_SCROLL_DEFAULT_GROWTH_EXP 1.05f
#define GLUI_SCROLL_VERTICAL 0
#define GLUI_SCROLL_HORIZONTAL 1
/** Size of the character width hash table for faster lookups.
Make sure to keep this a power of two to avoid the slow divide.
This is also a speed/memory tradeoff; 128 is enough for low ASCII.
*/
#define CHAR_WIDTH_HASH_SIZE 128
/********** Translation codes **********/
enum TranslationCodes
{
GLUI_TRANSLATION_MOUSE_NONE = 0,
GLUI_TRANSLATION_MOUSE_UP,
GLUI_TRANSLATION_MOUSE_DOWN,
GLUI_TRANSLATION_MOUSE_LEFT,
GLUI_TRANSLATION_MOUSE_RIGHT,
GLUI_TRANSLATION_MOUSE_UP_LEFT,
GLUI_TRANSLATION_MOUSE_UP_RIGHT,
GLUI_TRANSLATION_MOUSE_DOWN_LEFT,
GLUI_TRANSLATION_MOUSE_DOWN_RIGHT
};
/************ A string type for us to use **********/
typedef std::string GLUI_String;
GLUIAPI GLUI_String& glui_format_str (GLUI_String &str, const char* fmt, ...);
/********* Pre-declare classes as needed *********/
class GLUI;
class GLUI_Control;
class GLUI_Listbox;
class GLUI_StaticText;
class GLUI_EditText;
class GLUI_Panel;
class GLUI_Spinner;
class GLUI_RadioButton;
class GLUI_RadioGroup;
class GLUI_Glut_Window;
class GLUI_TreePanel;
class GLUI_Scrollbar;
class GLUI_List;
class Arcball;
/*** Flags for GLUI class constructor ***/
#define GLUI_SUBWINDOW ((long) (1<<1))
#define GLUI_SUBWINDOW_TOP ((long) (1<<2))
#define GLUI_SUBWINDOW_BOTTOM ((long) (1<<3))
#define GLUI_SUBWINDOW_LEFT ((long) (1<<4))
#define GLUI_SUBWINDOW_RIGHT ((long) (1<<5))
/*** Codes for different type of edittext boxes and spinners ***/
#define GLUI_EDITTEXT_TEXT 1
#define GLUI_EDITTEXT_INT 2
#define GLUI_EDITTEXT_FLOAT 3
#define GLUI_SPINNER_INT GLUI_EDITTEXT_INT
#define GLUI_SPINNER_FLOAT GLUI_EDITTEXT_FLOAT
#define GLUI_SCROLL_INT GLUI_EDITTEXT_INT
#define GLUI_SCROLL_FLOAT GLUI_EDITTEXT_FLOAT
// This is only for deprecated interface
#define GLUI_EDITTEXT_STRING 4
/*** Definition of callbacks ***/
typedef void (*GLUI_Update_CB) (int id);
typedef void (*GLUI_Control_CB) (GLUI_Control *);
typedef void (*Int1_CB) (int);
typedef void (*Int2_CB) (int, int);
typedef void (*Int3_CB) (int, int, int);
typedef void (*Int4_CB) (int, int, int, int);
/************************************************************/
/**
Callback Adapter Class
Allows us to support different types of callbacks;
like a GLUI_Update_CB function pointer--which takes an int;
and a GLUI_Control_CB function pointer--which takes a GUI_Control object.
*/
class GLUIAPI GLUI_CB
{
public:
GLUI_CB () : idCB (0),objCB (0) {}
GLUI_CB (GLUI_Update_CB cb) : idCB (cb),objCB (0) {}
GLUI_CB (GLUI_Control_CB cb) : idCB (0),objCB (cb) {}
// (Compiler generated copy constructor)
/** This control just activated. Fire our callback.*/
void operator () (GLUI_Control *ctrl) const;
bool operator! () const { return !idCB && !objCB; }
operator bool () const { return ! (! (*this)); }
private:
GLUI_Update_CB idCB;
GLUI_Control_CB objCB;
};
/************************************************************/
/* */
/* Base class, for hierarchical relationships */
/* */
/************************************************************/
class GLUI_Control;
/**
GLUI_Node is a node in a sort of tree of GLUI controls.
Each GLUI_Node has a list of siblings (in a circular list)
and a linked list of children.
Everything onscreen is a GLUI_Node--windows, buttons, etc.
The nodes are traversed for event processing, sizing, redraws, etc.
*/
class GLUIAPI GLUI_Node
{
friend class GLUI_Tree; /* JVK */
friend class GLUI_Rollout;
friend class GLUI_Main;
public:
GLUI_Node ();
virtual ~GLUI_Node () {}
GLUI_Node *first_sibling ();
GLUI_Node *last_sibling ();
GLUI_Node *prev ();
GLUI_Node *next ();
GLUI_Node *first_child () { return child_head; }
GLUI_Node *last_child () { return child_tail; }
GLUI_Node *parent () { return parent_node; }
/** Link in a new child control */
virtual int add_control (GLUI_Control *control);
void link_this_to_parent_last (GLUI_Node *parent);
void link_this_to_parent_first (GLUI_Node *parent);
void link_this_to_sibling_next (GLUI_Node *sibling);
void link_this_to_sibling_prev (GLUI_Node *sibling);
void unlink ();
void dump (FILE *out, const char *name);
protected:
static void add_child_to_control (GLUI_Node *parent,GLUI_Control *child);
GLUI_Node *parent_node;
GLUI_Node *child_head;
GLUI_Node *child_tail;
GLUI_Node *next_sibling;
GLUI_Node *prev_sibling;
};
/************************************************************/
/* */
/* Standard Bitmap stuff */
/* */
/************************************************************/
enum GLUI_StdBitmaps_Codes
{
GLUI_STDBITMAP_CHECKBOX_OFF = 0,
GLUI_STDBITMAP_CHECKBOX_ON,
GLUI_STDBITMAP_RADIOBUTTON_OFF,
GLUI_STDBITMAP_RADIOBUTTON_ON,
GLUI_STDBITMAP_UP_ARROW,
GLUI_STDBITMAP_DOWN_ARROW,
GLUI_STDBITMAP_LEFT_ARROW,
GLUI_STDBITMAP_RIGHT_ARROW,
GLUI_STDBITMAP_SPINNER_UP_OFF,
GLUI_STDBITMAP_SPINNER_UP_ON,
GLUI_STDBITMAP_SPINNER_DOWN_OFF,
GLUI_STDBITMAP_SPINNER_DOWN_ON,
GLUI_STDBITMAP_CHECKBOX_OFF_DIS, /*** Disactivated control bitmaps ***/
GLUI_STDBITMAP_CHECKBOX_ON_DIS,
GLUI_STDBITMAP_RADIOBUTTON_OFF_DIS,
GLUI_STDBITMAP_RADIOBUTTON_ON_DIS,
GLUI_STDBITMAP_SPINNER_UP_DIS,
GLUI_STDBITMAP_SPINNER_DOWN_DIS,
GLUI_STDBITMAP_LISTBOX_UP,
GLUI_STDBITMAP_LISTBOX_DOWN,
GLUI_STDBITMAP_LISTBOX_UP_DIS,
GLUI_STDBITMAP_NUM_ITEMS
};
/************************************************************/
/* */
/* Class GLUI_Bitmap */
/* */
/************************************************************/
/**
GLUI_Bitmap is a simple 2D texture map. It's used
to represent small textures like checkboxes, arrows, etc.
via the GLUI_StdBitmaps class.
*/
class GLUIAPI GLUI_Bitmap
{
friend class GLUI_StdBitmaps;
public:
GLUI_Bitmap ();
~GLUI_Bitmap ();
/** Create bitmap from greyscale byte image */
void init_grey (unsigned char *array);
/** Create bitmap from color int image */
void init (int *array);
private:
/** RGB pixel data */
unsigned char *pixels;
int w, h;
};
/************************************************************/
/* */
/* Class GLUI_StdBitmap */
/* */
/************************************************************/
/**
Keeps an array of GLUI_Bitmap objects to represent all the
images used in the UI: checkboxes, arrows, etc.
*/
class GLUIAPI GLUI_StdBitmaps
{
public:
GLUI_StdBitmaps ();
~GLUI_StdBitmaps ();
/** Return the width (in pixels) of the n'th standard bitmap. */
int width (int n) const;
/** Return the height (in pixels) of the n'th standard bitmap. */
int height (int n) const;
/** Draw the n'th standard bitmap (one of the enums
listed in GLUI_StdBitmaps_Codes) at pixel corner (x,y).
*/
void draw (int n, int x, int y) const;
private:
GLUI_Bitmap bitmaps[GLUI_STDBITMAP_NUM_ITEMS];
};
/************************************************************/
/* */
/* Master GLUI Class */
/* */
/************************************************************/
/**
The master manages our interaction with GLUT.
There's only one GLUI_Master_Object.
*/
class GLUIAPI GLUI_Master_Object
{
friend void glui_idle_func ();
public:
GLUI_Master_Object ();
~GLUI_Master_Object ();
GLUI_Node gluis;
GLUI_Control *active_control, *curr_left_button_glut_menu;
GLUI *active_control_glui;
int glui_id_counter;
GLUI_Glut_Window *find_glut_window (int window_id);
void set_glutIdleFunc (void (*f) (void));
/**************
void (*glut_keyboard_CB) (unsigned char, int, int);
void (*glut_reshape_CB) (int, int);
void (*glut_special_CB) (int, int, int);
void (*glut_mouse_CB) (int,int,int,int);
void (*glut_passive_motion_CB) (int,int);
void (*glut_visibility_CB) (int);
void (*glut_motion_CB) (int,int);
void (*glut_display_CB) (void);
void (*glut_entry_CB) (int);
**********/
void set_left_button_glut_menu_control (GLUI_Control *control);
/********** GLUT callthroughs **********/
/* These are the glut callbacks that we do not handle */
void set_glutReshapeFunc (void (*f) (int width, int height));
void set_glutKeyboardFunc (void (*f) (unsigned char key, int x, int y));
void set_glutSpecialFunc (void (*f) (int key, int x, int y));
void set_glutMouseFunc (void (*f) (int, int, int, int));
void set_glutDisplayFunc (void (*f) (void)) {glutDisplayFunc (f);}
void set_glutTimerFunc (unsigned int millis, void (*f) (int value), int value)
{ ::glutTimerFunc (millis,f,value);}
void set_glutOverlayDisplayFunc (void (*f) (void)){glutOverlayDisplayFunc (f);}
void set_glutSpaceballMotionFunc (Int3_CB f) {glutSpaceballMotionFunc (f);}
void set_glutSpaceballRotateFunc (Int3_CB f) {glutSpaceballRotateFunc (f);}
void set_glutSpaceballButtonFunc (Int2_CB f) {glutSpaceballButtonFunc (f);}
void set_glutTabletMotionFunc (Int2_CB f) {glutTabletMotionFunc (f);}
void set_glutTabletButtonFunc (Int4_CB f) {glutTabletButtonFunc (f);}
/* void set_glutWindowStatusFunc (Int1_CB f) {glutWindowStatusFunc (f);} */
void set_glutMenuStatusFunc (Int3_CB f) {glutMenuStatusFunc (f);}
void set_glutMenuStateFunc (Int1_CB f) {glutMenuStateFunc (f);}
void set_glutButtonBoxFunc (Int2_CB f) {glutButtonBoxFunc (f);}
void set_glutDialsFunc (Int2_CB f) {glutDialsFunc (f);}
GLUI *create_glui (const char *name, long flags=0, int x=-1, int y=-1);
GLUI *create_glui_subwindow (int parent_window, long flags=0);
GLUI *find_glui_by_window_id (int window_id);
void get_viewport_area (int *x, int *y, int *w, int *h);
void auto_set_viewport ();
void close_all ();
void sync_live_all ();
void reshape ();
float get_version () { return GLUI_VERSION; }
void glui_setIdleFuncIfNecessary (void);
private:
GLUI_Node glut_windows;
void (*glut_idle_CB) (void);
void add_cb_to_glut_window (int window,int cb_type,void *cb);
};
/**
This is the only GLUI_Master_Object in existence.
*/
extern GLUIAPI GLUI_Master_Object GLUI_Master;
/************************************************************/
/* */
/* Class for managing a GLUT window */
/* */
/************************************************************/
/**
A top-level window. The GLUI_Master GLUT callback can route events
to the callbacks in this class, for arbitrary use by external users.
(see GLUI_Master_Object::set_glutKeyboardFunc).
This entire approach seems to be superceded by the "subwindow" flavor
of GLUI.
*/
class GLUIAPI GLUI_Glut_Window : GLUI_Node
{
public:
GLUI_Glut_Window ();
int glut_window_id;
/*********** Pointers to GLUT callthrough functions *****/
void (*glut_keyboard_CB) (unsigned char, int, int);
void (*glut_special_CB) (int, int, int);
void (*glut_reshape_CB) (int, int);
void (*glut_passive_motion_CB) (int,int);
void (*glut_mouse_CB) (int,int,int,int);
void (*glut_visibility_CB) (int);
void (*glut_motion_CB) (int,int);
void (*glut_display_CB) (void);
void (*glut_entry_CB) (int);
};
/************************************************************/
/* */
/* Main Window GLUI class (not user-level) */
/* */
/************************************************************/
/**
A GLUI_Main handles GLUT events for one window, routing them to the
appropriate controls. The central user-visible "GLUI" class
inherits from this class; users should not allocate GLUT_Main objects.
There's a separate GLUI_Main object for:
- Each top-level window with GUI stuff in it.
- Each "subwindow" of another top-level window.
All the GLUI_Main objects are listed in GLUI_Master.gluis.
A better name for this class might be "GLUI_Environment";
this class provides the window-level context for every control.
*/
class GLUIAPI GLUI_Main : GLUI_Node
{
/********** Friend classes *************/
friend class GLUI_Control;
friend class GLUI_Rotation;
friend class GLUI_Translation;
friend class GLUI;
friend class GLUI_Master_Object;
/*********** Friend functions **********/
friend void glui_mouse_func (int button, int state, int x, int y);
friend void glui_keyboard_func (unsigned char key, int x, int y);
friend void glui_special_func (int key, int x, int y);
friend void glui_passive_motion_func (int x, int y);
friend void glui_reshape_func (int w, int h);
friend void glui_visibility_func (int state);
friend void glui_motion_func (int x, int y);
friend void glui_entry_func (int state);
friend void glui_display_func (void);
friend void glui_idle_func (void);
friend void glui_parent_window_reshape_func (int w, int h);
friend void glui_parent_window_keyboard_func (unsigned char, int, int);
friend void glui_parent_window_special_func (int, int, int);
friend void glui_parent_window_mouse_func (int, int, int, int);
protected:
/*** Variables ***/
int main_gfx_window_id;
int mouse_button_down;
int glut_window_id;
int top_level_glut_window_id;
GLUI_Control *active_control;
GLUI_Control *mouse_over_control;
GLUI_Panel *main_panel;
enum buffer_mode_t {
buffer_front=1, ///< Draw updated controls directly to screen.
buffer_back=2 ///< Double buffering: postpone updates until next redraw.
};
buffer_mode_t buffer_mode; ///< Current drawing mode
int curr_cursor;
int w, h;
long flags;
bool closing;
int parent_window;
int glui_id;
/********** Misc functions *************/
GLUI_Control *find_control (int x, int y);
GLUI_Control *find_next_control (GLUI_Control *control);
GLUI_Control *find_next_control_rec (GLUI_Control *control);
GLUI_Control *find_next_control_ (GLUI_Control *control);
GLUI_Control *find_prev_control (GLUI_Control *control);
void create_standalone_window (const char *name, int x=-1, int y=-1);
void create_subwindow (int parent,int window_alignment);
void setup_default_glut_callbacks (void);
void mouse (int button, int state, int x, int y);
void keyboard (unsigned char key, int x, int y);
void special (int key, int x, int y);
void passive_motion (int x, int y);
void reshape (int w, int h);
void visibility (int state);
void motion (int x, int y);
void entry (int state);
void display (void);
void idle (void);
int needs_idle (void);
void (*glut_mouse_CB) (int, int, int, int);
void (*glut_keyboard_CB) (unsigned char, int, int);
void (*glut_special_CB) (int, int, int);
void (*glut_reshape_CB) (int, int);
/*********** Controls ************/
virtual int add_control (GLUI_Node *parent, GLUI_Control *control);
/********** Constructors and Destructors ***********/
GLUI_Main (void);
public:
GLUI_StdBitmaps std_bitmaps;
GLUI_String window_name;
unsigned char bkgd_color[3];
float bkgd_color_f[3];
void *font;
int curr_modifiers;
void adjust_glut_xy (int &x, int &y) { y = h-y; }
void activate_control (GLUI_Control *control, int how);
void align_controls (GLUI_Control *control);
void deactivate_current_control (void);
/** Draw a 3D-look pushed-out box around this rectangle */
void draw_raised_box (int x, int y, int w, int h);
/** Draw a 3D-look pushed-in box around this rectangle */
void draw_lowered_box (int x, int y, int w, int h);
/** Return true if this control should redraw itself immediately (front buffer);
Or queue up a redraw and return false if it shouldn't (back buffer).
*/
bool should_redraw_now (GLUI_Control *ctl);
/** Switch to the appropriate draw buffer now. Returns the old draw buffer.
This routine should probably only be called from inside the GLUI_DrawingSentinal,
in glui_internal_control.h
*/
int set_current_draw_buffer ();
/** Go back to using this draw buffer. Undoes set_current_draw_buffer. */
void restore_draw_buffer (int buffer_state);
/** Pack, resize the window, and redraw all the controls. */
void refresh ();
/** Redraw the main graphics window */
void post_update_main_gfx ();
/** Recompute the sizes and positions of all controls */
void pack_controls ();
void close_internal ();
void check_subwindow_position ();
void set_ortho_projection ();
void set_viewport ();
int get_glut_window_id (void) { return glut_window_id; } /* JVK */
};
/************************************************************/
/* */
/* GLUI_Control: base class for all controls */
/* */
/************************************************************/
/**
All the GUI objects inherit from GLUI_Control: buttons,
checkboxes, labels, edit boxes, scrollbars, etc.
Most of the work of this class is in routing events,
like keystrokes, mouseclicks, redraws, and sizing events.
Yes, this is a huge and hideous class. It needs to be
split up into simpler subobjects. None of the data members
should be directly accessed by users (they should be protected,
not public); only subclasses.
*/
class GLUIAPI GLUI_Control : GLUI_Node
{
public:
/** Onscreen coordinates */
int w, h; /* dimensions of control */
int x_abs, y_abs;
int x_off, y_off_top, y_off_bot; /* INNER margins, by which child
controls are indented */
int contain_x, contain_y;
int contain_w, contain_h;
/* if this is a container control (e.g.,
radiogroup or panel) this indicated dimensions
of inner area in which controls reside */
/** "activation" for tabbing between controls. */
int active_type; ///< "GLUI_CONTROL_ACTIVE_..."
bool active; ///< If true, we've got the focus
bool can_activate; ///< If false, remove from tab order.
bool spacebar_mouse_click; ///< Spacebar simulates click.
/** Callbacks */
long user_id; ///< Integer to pass to callback function.
GLUI_CB callback; ///< User callback function, or NULL.
/** Variable value storage */
float float_val; /**< Our float value */
int int_val; /**< Our integer value */
float float_array_val[GLUI_DEF_MAX_ARRAY];
int float_array_size;
GLUI_String text; /**< The text inside this control */
/** "Live variable" updating */
void *ptr_val; /**< A pointer to the user's live variable value */
int live_type;
bool live_inited;
/* These variables store the last value that live variable was known to have. */
int last_live_int;
float last_live_float;
GLUI_String last_live_text;
float last_live_float_array[GLUI_DEF_MAX_ARRAY];
/** Properties of our control */
GLUI *glui; /**< Our containing event handler (NEVER NULL during event processing!) */
bool is_container; /**< Is this a container class (e.g., panel) */
int alignment;
bool enabled; /**< Is this control grayed out? */
GLUI_String name; /**< The name of this control */
void *font; /**< Our glutbitmap font */
bool collapsible, is_open;
GLUI_Node collapsed_node;
bool hidden; /* Collapsed controls (and children) are hidden */
int char_widths[CHAR_WIDTH_HASH_SIZE][2]; /* Character width hash table */
public:
/*** Get/Set values ***/
virtual void set_name (const char *string);
virtual void set_int_val (int new_int) { int_val = new_int; output_live (true); }
virtual void set_float_val (float new_float) { float_val = new_float; output_live (true); }
virtual void set_ptr_val (void *new_ptr) { ptr_val = new_ptr; output_live (true); }
virtual void set_float_array_val (float *array_ptr);
virtual float get_float_val (void) { return float_val; }
virtual int get_int_val (void) { return int_val; }
virtual void get_float_array_val (float *array_ptr);
virtual int get_id (void) const { return user_id; }
virtual void set_id (int id) { user_id=id; }
virtual int mouse_down_handler (int local_x, int local_y) { return false; }
virtual int mouse_up_handler (int local_x, int local_y, bool inside) { return false; }
virtual int mouse_held_down_handler (int local_x, int local_y, bool inside) { return false; }
virtual int key_handler (unsigned char key, int modifiers) { return false; }
virtual int special_handler (int key,int modifiers) { return false; }
virtual void update_size (void) { }
virtual void idle (void) { }
virtual int mouse_over (int state, int x, int y) { return false; }
virtual void enable (void);
virtual void disable (void);
virtual void activate (int how) { active = true; }
virtual void deactivate (void) { active = false; }
/** Hide (shrink into a rollout) and unhide (expose from a rollout) */
void hide_internal (int recurse);
void unhide_internal (int recurse);
/** Return true if it currently makes sense to draw this class. */
int can_draw (void) { return (glui != NULL && hidden == false); }
/** Redraw this control.
In single-buffering mode (drawing to GL_FRONT), this is just
a call to translate_and_draw_front (after a can_draw () check).
In double-buffering mode (drawing to GL_BACK), this queues up
a redraw and returns false, since you shouldn't draw yet.
*/
void redraw (void);
/** Redraw everybody in our window. */
void redraw_window (void);
virtual void align (void);
void pack (int x, int y); /* Recalculate positions and offsets */
void pack_old (int x, int y);
void draw_recursive (int x, int y);
int set_to_glut_window (void);
void restore_window (int orig);
void translate_and_draw_front (void);
void translate_to_origin (void)
{glTranslatef ((float)x_abs+.5, (float)y_abs+.5,0.0);}
virtual void draw (int x, int y)=0;
void set_font (void *new_font);
void *get_font (void);
int string_width (const char *text);
int string_width (const GLUI_String &str)
{ return string_width (str.c_str ()); }
int char_width (char c);
void draw_name (int x, int y);
void draw_box_inwards_outline (int x_min, int x_max,
int y_min, int y_max);
void draw_box (int x_min, int x_max, int y_min, int y_max,
float r, float g, float b);
void draw_bkgd_box (int x_min, int x_max, int y_min, int y_max);
void draw_emboss_box (int x_min, int x_max,int y_min,int y_max);
void draw_string (const char *text);
void draw_string (const GLUI_String &s)
{ draw_string (s.c_str ()); }
void draw_char (char c);
void draw_active_box (int x_min, int x_max, int y_min, int y_max);
void set_to_bkgd_color (void);
void set_w (int new_w);
void set_h (int new_w);
void set_alignment (int new_align);
void sync_live (int recurse, int draw); /* Reads live variable */
void init_live (void);
void output_live (int update_main_gfx); /** Writes live variable **/
virtual void set_text (const char *t) {}
void execute_callback (void);
void get_this_column_dims (int *col_x, int *col_y,
int *col_w, int *col_h,
int *col_x_off, int *col_y_off);
virtual bool needs_idle (void) const;
virtual bool wants_tabs () const { return false; }
GLUI_Control (void)
{
x_off = GLUI_XOFF;
y_off_top = GLUI_YOFF;
y_off_bot = GLUI_YOFF;
x_abs = GLUI_XOFF;
y_abs = GLUI_YOFF;
active = false;
enabled = true;
int_val = 0;
last_live_int = 0;
float_array_size = 0;
glui_format_str (name, "Control: %p", this);
float_val = 0.0;
last_live_float = 0.0;
ptr_val = NULL;
glui = NULL;
w = GLUI_DEFAULT_CONTROL_WIDTH;
h = GLUI_DEFAULT_CONTROL_HEIGHT;
font = NULL;
active_type = GLUI_CONTROL_ACTIVE_MOUSEDOWN;
alignment = GLUI_ALIGN_LEFT;
is_container = false;
can_activate = true; /* By default, you can activate a control */
spacebar_mouse_click = true; /* Does spacebar simulate a mouse click? */
live_type = GLUI_LIVE_NONE;
text = "";
last_live_text == "";
live_inited = false;
collapsible = false;
is_open = true;
hidden = false;
memset (char_widths, -1, sizeof (char_widths)); /* JVK */
int i;
for (i=0; i<GLUI_DEF_MAX_ARRAY; i++)
float_array_val[i] = last_live_float_array[i] = 0.0;
}
virtual ~GLUI_Control ();
};
/************************************************************/
/* */
/* Button class (container) */
/* */
/************************************************************/
/**
An onscreen, clickable button--an outlined label that
can be clicked. When clicked, a button
calls its GLUI_CB callback with its ID.
*/
class GLUIAPI GLUI_Button : GLUI_Control
{
public:
bool currently_inside;
int mouse_down_handler (int local_x, int local_y);
int mouse_up_handler (int local_x, int local_y, bool inside);
int mouse_held_down_handler (int local_x, int local_y, bool inside);
int key_handler (unsigned char key,int modifiers);
void draw (int x, int y);
void draw_pressed (void);
void draw_text (int sunken);
void update_size (void);
/**
Create a new button.
@param parent The panel our object is inside; or the main GLUI object.
@param name The text inside the button.
@param id Optional ID number, to pass to the optional callback function.
@param callback Optional callback function, taking either the int ID or control.
*/
GLUI_Button (GLUI_Node *parent, const char *name,
int id=-1, GLUI_CB cb=GLUI_CB ());
GLUI_Button (void) { common_init (); };
protected:
void common_init (void) {
glui_format_str (name, "Button: %p", this);
h = GLUI_BUTTON_SIZE;
w = 100;
alignment = GLUI_ALIGN_CENTER;
can_activate = true;
}
};
/************************************************************/
/* */
/* Checkbox class (container) */
/* */
/************************************************************/
/**
A checkbox, which can be checked on or off. Can be linked
to an int value, which gets 1 for on and 0 for off.
*/
class GLUIAPI GLUI_Checkbox : GLUI_Control
{
public:
int orig_value;
bool currently_inside;
int text_x_offset;
int mouse_down_handler (int local_x, int local_y);
int mouse_up_handler (int local_x, int local_y, bool inside);
int mouse_held_down_handler (int local_x, int local_y, bool inside);
int key_handler (unsigned char key,int modifiers);
void update_size (void);
void draw (int x, int y);
void draw_active_area (void);
void draw_empty_box (void);
void set_int_val (int new_val);
/**
Create a new checkbox object.
@param parent The panel our object is inside; or the main GLUI object.
@param name Label next to our checkbox.
@param value_ptr Optional integer value to attach to this checkbox. When the
checkbox is checked or unchecked, *value_ptr will also be changed. ("Live Vars").
@param id Optional ID number, to pass to the optional callback function.
@param callback Optional callback function, taking either the int ID or control.
*/
GLUI_Checkbox (GLUI_Node *parent, const char *name, int *value_ptr=NULL,
int id=-1, GLUI_CB callback=GLUI_CB ());
GLUI_Checkbox (void) { common_init (); }
protected:
void common_init (void) {
glui_format_str (name, "Checkbox: %p", this);
w = 100;
h = GLUI_CHECKBOX_SIZE;
orig_value = -1;
text_x_offset = 18;
can_activate = true;
live_type = GLUI_LIVE_INT; /* This control has an 'int' live auto */
}
};
/************************************************************/
/* */
/* Column class */
/* */
/************************************************************/
/**
A GLUI_Column object separates all previous controls
from subsequent controls with a vertical bar.
*/
class GLUIAPI GLUI_Column : GLUI_Control
{
public:
void draw (int x, int y);
/**
Create a new column, which separates the previous controls
from subsequent controls.
@param parent The panel our object is inside; or the main GLUI object.
@param draw_bar If true, draw a visible bar between new and old controls.
*/
GLUI_Column (GLUI_Node *parent, int draw_bar = true);
GLUI_Column (void) { common_init (); }
protected:
void common_init () {
w = 0;
h = 0;
int_val = 0;
can_activate = false;
}
};
/************************************************************/
/* */
/* Panel class (container) */
/* */
/************************************************************/
/**
A GLUI_Panel contains a group of related controls.
*/
class GLUIAPI GLUI_Panel : GLUI_Control
{
public:
/**
Create a new panel. A panel groups together a set of related controls.
@param parent The outer panel our panel is inside; or the main GLUI object.
@param name The string name at the top of our panel.
@param type Optional style to display the panel with--GLUI_PANEL_EMBOSSED by default.
GLUI_PANEL_RAISED causes the panel to appear higher than the surroundings.
GLUI_PANEL_NONE causes the panel's outline to be invisible.
*/
GLUI_Panel (GLUI_Node *parent, const char *name,
int type=GLUI_PANEL_EMBOSSED);
GLUI_Panel () { common_init (); }
void draw (int x, int y);
void set_name (const char *text);
void set_type (int new_type);
void update_size (void);
protected:
void common_init (void) {
w = 300;
h = GLUI_DEFAULT_CONTROL_HEIGHT + 7;
int_val = GLUI_PANEL_EMBOSSED;
alignment = GLUI_ALIGN_CENTER;
is_container = true;
can_activate = false;
name="";
};
};
/************************************************************/
/* */
/* File Browser class (container) */
/* JVK */
/************************************************************/
/**
A list of files the user can select from.
*/
class GLUIAPI GLUI_FileBrowser : GLUI_Panel
{
public:
/**
Create a new list of files the user can select from.
@param parent The panel our object is inside; or the main GLUI object.
@param name Prompt to give to the user at the top of the file browser.
@param frame_type Optional style to display the panel with--GLUI_PANEL_EMBOSSED by default.
GLUI_PANEL_RAISED causes the panel to appear higher than the surroundings.
GLUI_PANEL_NONE causes the panel's outline to be invisible.
@param id Optional ID number, to pass to the optional callback function.
@param callback Optional callback function, taking either the int ID or control.
*/
GLUI_FileBrowser (GLUI_Node *parent,
const char *name,
int frame_type = GLUI_PANEL_EMBOSSED,
int user_id = -1,
GLUI_CB callback = GLUI_CB ());
GLUI_List *list;
GLUI_String current_dir;
void fbreaddir (const char *);
static void dir_list_callback (GLUI_Control*);
void set_w (int w);
void set_h (int h);
const char* get_file () { return file.c_str (); }
void set_allow_change_dir (int c) { allow_change_dir = c; }
protected:
void common_init ()
{
w = GLUI_DEFAULT_CONTROL_WIDTH;
h = GLUI_DEFAULT_CONTROL_HEIGHT;
int_val = GLUI_PANEL_EMBOSSED;
alignment = GLUI_ALIGN_CENTER;
is_container = true;
can_activate = false;
allow_change_dir = true;
last_item = -1;
user_id = -1;
name = "";
current_dir = ".";
file = "";
};
private:
int last_item;
GLUI_String file;
int allow_change_dir;
};
/************************************************************/
/* */
/* Rollout class (container) */
/* */
/************************************************************/
/**
A rollout contains a set of controls,
like a panel, but can be collapsed to just the name.
*/
class GLUIAPI GLUI_Rollout : GLUI_Panel
{
public:
/**
Create a new rollout. A rollout contains a set of controls,
like a panel, but can be collapsed to just the name.
@param parent The panel our object is inside; or the main GLUI object.
@param name String to show at the top of the rollout.
@param open Optional boolean. If true (the default), the rollout's controls are displayed.
If false, the rollout is closed to display only the name.
@param type Optional style to display the panel with--GLUI_PANEL_EMBOSSED by default.
GLUI_PANEL_RAISED causes the panel to appear higher than the surroundings.
GLUI_PANEL_NONE causes the panel's outline to be invisible.
*/
GLUI_Rollout (GLUI_Node *parent, const char *name, int open=true,
int type=GLUI_PANEL_EMBOSSED);
GLUI_Rollout (void) { common_init (); }
bool currently_inside, initially_inside;
GLUI_Button button;
void draw (int x, int y);
void draw_pressed (void);
int mouse_down_handler (int local_x, int local_y);
int mouse_up_handler (int local_x, int local_y, bool inside);
int mouse_held_down_handler (int local_x, int local_y, bool inside);
void open (void);
void close (void);
void update_size (void);
protected:
void common_init () {
currently_inside = false;
initially_inside = false;
can_activate = true;
is_container = true;
h = GLUI_DEFAULT_CONTROL_HEIGHT + 7;
w = GLUI_DEFAULT_CONTROL_WIDTH;
y_off_top = 21;
collapsible = true;
name = "";
}
};
/************************************************************/
/* */
/* Tree Panel class (container) */
/* JVK */
/************************************************************/
/**
One collapsible entry in a GLUI_TreePanel.
*/
class GLUIAPI GLUI_Tree : GLUI_Panel
{
public:
GLUI_Tree (GLUI_Node *parent, const char *name,
int open=false, int inset=0);
private:
int level; // how deep is this node
float red; //Color coding of column line
float green;
float blue;
float lred; //Color coding of level name
float lgreen;
float lblue;
int id;
GLUI_Column *column;
int is_current; // Whether this tree is the
// current root in a treePanel
int child_number;
int format;
public:
bool currently_inside, initially_inside;
GLUI_Button button;
GLUI_String level_name; // level name, eg: 1.1.2, III, or 3
GLUI_TreePanel *panel;
void draw (int x, int y);
void draw_pressed (void);
int mouse_down_handler (int local_x, int local_y);
int mouse_up_handler (int local_x, int local_y, bool inside);
int mouse_held_down_handler (int local_x, int local_y, bool inside);
void set_column (GLUI_Column *c) { column = c; }
void open (void);
void close (void);
/* void set_name (const char *text) { panel.set_name (text); }; */
void update_size (void);
void set_id (int i) { id = i; }
void set_level (int l) { level = l; }
void set_format (int f) { format = f; }
void set_current (int c) { is_current = c; }
int get_id () { return id; }
int get_level () { return level; }
int get_child_number () { return child_number; }
void enable_bar () { if (column) { column->int_val = 1; set_color (red, green, blue); } }
void disable_bar () { if (column) { column->int_val = 0; } }
void set_child_number (int c) { child_number = c; }
void set_level_color (float r, float g, float b) {
lred = r;
lgreen = g;
lblue = b;
}
void set_color (float r, float g, float b) {
red = r;
green = g;
blue = b;
}
protected:
void common_init ()
{
currently_inside = false;
initially_inside = false;
can_activate = true;
is_container = true;
h = GLUI_DEFAULT_CONTROL_HEIGHT + 7;
w = GLUI_DEFAULT_CONTROL_WIDTH;
y_off_top = 21;
collapsible = true;
red = .5;
green = .5;
blue = .5;
lred = 0;
lgreen = 0;
lblue = 0;
column = NULL;
is_current = 0;
child_number = 0;
format = 0;
panel = NULL;
name = "";
level_name = "";
level = 0;
};
};
/************************************************************/
/* */
/* TreePanel class (container) JVK */
/* */
/************************************************************/
/**
Manages, maintains, and formats a tree of GLUI_Tree objects.
These are shown in a heirarchical, collapsible display.
FIXME: There's an infinite loop in the traversal code (OSL 2006/06)
*/
class GLUIAPI GLUI_TreePanel : GLUI_Panel
{
public:
GLUI_TreePanel (GLUI_Node *parent, const char *name,
bool open=false, int inset=0);
int max_levels;
int next_id;
int format;
float red;
float green;
float blue;
float lred;
float lgreen;
float lblue;
int root_children;
/* These variables allow the tree panel to traverse the tree
using only two function calls. (Well, four, if you count
going in reverse */
GLUI_Tree *curr_branch; /* Current Branch */
GLUI_Panel *curr_root; /* Current Root */
public:
void set_color (float r, float g, float b);
void set_level_color (float r, float g, float b);
void set_format (int f) { format = f; }
/* Adds branch to curr_root */
GLUI_Tree * ab (const char *name, GLUI_Tree *root = NULL);
/* Goes up one level, resets curr_root and curr_branch to parents*/
void fb (GLUI_Tree *branch= NULL);
/* Deletes the curr_branch, goes up one level using fb */
void db (GLUI_Tree *branch = NULL);
/* Finds the very last branch of curr_root, resets vars */
void descendBranch (GLUI_Panel *root = NULL);
/* Resets curr_root and curr branch to TreePanel and lastChild */
void resetToRoot (GLUI_Panel *new_root = NULL);
void next (void);
void refresh (void);
void expand_all (void);
void collapse_all (void);
void update_all (void);
void initNode (GLUI_Tree *temp);
void formatNode (GLUI_Tree *temp);
protected:
int uniqueID (void) { next_id++; return next_id - 1; }
void common_init ()
{
GLUI_Panel ();
next_id = 0;
curr_root = this;
curr_branch = NULL;
red = .5;
green = .5;
blue = .5;
root_children = 0;
}
};
/************************************************************/
/* */
/* User-Level GLUI class */
/* */
/************************************************************/
class GLUI_Rotation;
class GLUI_Translation;
/**
The main user-visible interface object to GLUI.
*/
class GLUIAPI GLUI : GLUI_Main
{
public:
/** DEPRECATED interface for creating new GLUI objects */
int add_control (GLUI_Control *control) { return main_panel->add_control (control); }
void add_column (int draw_bar = true);
void add_column_to_panel (GLUI_Panel *panel, int draw_bar = true);
void add_separator (void);
void add_separator_to_panel (GLUI_Panel *panel);
GLUI_RadioGroup
*add_radiogroup (int *live_var=NULL,
int user_id=-1,GLUI_CB callback=GLUI_CB ());
GLUI_RadioGroup
*add_radiogroup_to_panel (GLUI_Panel *panel,
int *live_var=NULL,
int user_id=-1, GLUI_CB callback=GLUI_CB ());
GLUI_RadioButton
*add_radiobutton_to_group (GLUI_RadioGroup *group,
const char *name);
GLUI_Listbox *add_listbox (const char *name, int *live_var=NULL,
int id=-1, GLUI_CB callback=GLUI_CB () );
GLUI_Listbox *add_listbox_to_panel (GLUI_Panel *panel,
const char *name, int *live_var=NULL,
int id=-1, GLUI_CB callback=GLUI_CB ());
GLUI_Rotation *add_rotation (const char *name, float *live_var=NULL,
int id=-1, GLUI_CB callback=GLUI_CB () );
GLUI_Rotation *add_rotation_to_panel (GLUI_Panel *panel,
const char *name, float *live_var=NULL,
int id=-1, GLUI_CB callback=GLUI_CB ());
GLUI_Translation *add_translation (const char *name,
int trans_type, float *live_var=NULL,
int id=-1, GLUI_CB callback=GLUI_CB () );
GLUI_Translation *add_translation_to_panel (
GLUI_Panel *panel, const char *name,
int trans_type, float *live_var=NULL,
int id=-1, GLUI_CB callback=GLUI_CB ());
GLUI_Checkbox *add_checkbox (const char *name,
int *live_var=NULL,
int id=-1, GLUI_CB callback=GLUI_CB ());
GLUI_Checkbox *add_checkbox_to_panel (GLUI_Panel *panel, const char *name,
int *live_var=NULL, int id=-1,
GLUI_CB callback=GLUI_CB ());
GLUI_Button *add_button (const char *name, int id=-1,
GLUI_CB callback=GLUI_CB ());
GLUI_Button *add_button_to_panel (GLUI_Panel *panel, const char *name,
int id=-1, GLUI_CB callback=GLUI_CB ());
GLUI_StaticText *add_statictext (const char *name);
GLUI_StaticText *add_statictext_to_panel (GLUI_Panel *panel, const char *name);
GLUI_EditText *add_edittext (const char *name,
int data_type=GLUI_EDITTEXT_TEXT,
void*live_var=NULL,
int id=-1, GLUI_CB callback=GLUI_CB () );
GLUI_EditText *add_edittext_to_panel (GLUI_Panel *panel,
const char *name,
int data_type=GLUI_EDITTEXT_TEXT,
void *live_var=NULL, int id=-1,
GLUI_CB callback=GLUI_CB ());
GLUI_EditText *add_edittext (const char *name, GLUI_String& live_var,
int id=-1, GLUI_CB callback=GLUI_CB () );
GLUI_EditText *add_edittext_to_panel (GLUI_Panel *panel, const char *name,
GLUI_String& live_var, int id=-1,
GLUI_CB callback=GLUI_CB ());
GLUI_Spinner *add_spinner (const char *name,
int data_type=GLUI_SPINNER_INT,
void *live_var=NULL,
int id=-1, GLUI_CB callback=GLUI_CB ());
GLUI_Spinner *add_spinner_to_panel (GLUI_Panel *panel,
const char *name,
int data_type=GLUI_SPINNER_INT,
void *live_var=NULL,
int id=-1,
GLUI_CB callback=GLUI_CB ());
GLUI_Panel *add_panel (const char *name, int type=GLUI_PANEL_EMBOSSED);
GLUI_Panel *add_panel_to_panel (GLUI_Panel *panel, const char *name,
int type=GLUI_PANEL_EMBOSSED);
GLUI_Rollout *add_rollout (const char *name, int open=true,
int type=GLUI_PANEL_EMBOSSED);
GLUI_Rollout *add_rollout_to_panel (GLUI_Panel *panel, const char *name,
int open=true,
int type=GLUI_PANEL_EMBOSSED);
/** Set the window where our widgets should be displayed. */
void set_main_gfx_window (int window_id);
int get_glut_window_id (void) { return glut_window_id; }
void enable (void) { main_panel->enable (); }
void disable (void);
void sync_live (void);
void close (void);
void show (void);
void hide (void);
/***** GLUT callback setup functions *****/
/*
void set_glutDisplayFunc (void (*f) (void));
void set_glutReshapeFunc (void (*f) (int width, int height));
void set_glutKeyboardFunc (void (*f) (unsigned char key, int x, int y));
void set_glutSpecialFunc (void (*f) (int key, int x, int y));
void set_glutMouseFunc (void (*f) (int button, int state, int x, int y));
void set_glutMotionFunc (void (*f) (int x, int y));
void set_glutPassiveMotionFunc (void (*f) (int x, int y));
void set_glutEntryFunc (void (*f) (int state));
void set_glutVisibilityFunc (void (*f) (int state));
void set_glutInit (int *argcp, const char **argv);
void set_glutInitWindowSize (int width, int height);
void set_glutInitWindowPosition (int x, int y);
void set_glutInitDisplayMode (unsigned int mode);
int set_glutCreateWindow (const char *name);
*/
/***** Constructors and desctructors *****/
int init (const char *name, long flags, int x, int y, int parent_window);
protected:
virtual int add_control (GLUI_Node *parent, GLUI_Control *control) {
return GLUI_Main::add_control (parent, control);
}
};
/************************************************************/
/* */
/* EditText class */
/* */
/************************************************************/
class GLUIAPI GLUI_EditText : GLUI_Control
{
public:
int has_limits;
int data_type;
GLUI_String orig_text;
int insertion_pt;
int title_x_offset;
int text_x_offset;
int substring_start; /*substring that gets displayed in box*/
int substring_end;
int sel_start, sel_end; /* current selection */
int num_periods;
int last_insertion_pt;
float float_low, float_high;
int int_low, int_high;
GLUI_Spinner *spinner;
int debug;
int draw_text_only;
int mouse_down_handler (int local_x, int local_y);
int mouse_up_handler (int local_x, int local_y, bool inside);
int mouse_held_down_handler (int local_x, int local_y, bool inside);
int key_handler (unsigned char key,int modifiers);
int special_handler (int key, int modifiers);
void activate (int how);
void deactivate (void);
void draw (int x, int y);
int mouse_over (int state, int x, int y);
int find_word_break (int start, int direction);
int substring_width (int start, int end);
void clear_substring (int start, int end);
int find_insertion_pt (int x, int y);
int update_substring_bounds (void);
void update_and_draw_text (void);
void draw_text (int x, int y);
void draw_insertion_pt (void);
void set_numeric_text (void);
void update_x_offsets (void);
void update_size (void);
void set_float_limits (float low,float high,int limit_type=GLUI_LIMIT_CLAMP);
void set_int_limits (int low, int high, int limit_type=GLUI_LIMIT_CLAMP);
void set_float_val (float new_val);
void set_int_val (int new_val);
void set_text (const char *text);
void set_text (const GLUI_String &s) { set_text (s.c_str ()); }
const char *get_text () { return text.c_str (); }
void dump (FILE *out, const char *text);
// Constructor, no live variable
GLUI_EditText (GLUI_Node *parent, const char *name,
int text_type=GLUI_EDITTEXT_TEXT,
int id=-1, GLUI_CB callback=GLUI_CB ());
// Constructor, int live variable
GLUI_EditText (GLUI_Node *parent, const char *name,
int *live_var,
int id=-1, GLUI_CB callback=GLUI_CB ());
// Constructor, float live variable
GLUI_EditText (GLUI_Node *parent, const char *name,
float *live_var,
int id=-1, GLUI_CB callback=GLUI_CB ());
// Constructor, char* live variable
GLUI_EditText (GLUI_Node *parent, const char *name,
char *live_var,
int id=-1, GLUI_CB callback=GLUI_CB ());
// Constructor, std::string live variable
GLUI_EditText (GLUI_Node *parent, const char *name,
std::string &live_var,
int id=-1, GLUI_CB callback=GLUI_CB ());
// Deprecated constructor, only called internally
GLUI_EditText (GLUI_Node *parent, const char *name,
int text_type, void *live_var,
int id, GLUI_CB callback);
// Deprecated constructor, only called internally
GLUI_EditText (void) { common_init (); }
protected:
void common_init (void) {
h = GLUI_EDITTEXT_HEIGHT;
w = GLUI_EDITTEXT_WIDTH;
title_x_offset = 0;
text_x_offset = 55;
insertion_pt = -1;
last_insertion_pt = -1;
name = "";
substring_start = 0;
data_type = GLUI_EDITTEXT_TEXT;
substring_end = 2;
num_periods = 0;
has_limits = GLUI_LIMIT_NONE;
sel_start = 0;
sel_end = 0;
active_type = GLUI_CONTROL_ACTIVE_PERMANENT;
can_activate = true;
spacebar_mouse_click = false;
spinner = NULL;
debug = false;
draw_text_only = false;
}
void common_construct (GLUI_Node *parent, const char *name,
int data_type, int live_type, void *live_var,
int id, GLUI_CB callback);
};
/************************************************************/
/* */
/* CommandLine class */
/* */
/************************************************************/
class GLUIAPI GLUI_CommandLine : GLUI_EditText
{
public:
typedef GLUI_EditText Super;
enum { HIST_SIZE = 100 };
#ifdef _MSC_VER
// Explicit template instantiation needed for dll
template class GLUIAPI std::allocator<GLUI_String>;
template class GLUIAPI std::vector<GLUI_String, std::allocator<GLUI_String> >;
#endif
std::vector<GLUI_String> hist_list;
int curr_hist;
int oldest_hist;
int newest_hist;
bool commit_flag;
public:
int key_handler (unsigned char key,int modifiers);
int special_handler ( int key,int modifiers);
void deactivate (void);
virtual const char *get_history (int command_number) const
{ return hist_list[command_number - oldest_hist].c_str (); }
virtual GLUI_String& get_history_str (int command_number)
{ return hist_list[command_number - oldest_hist]; }
virtual const GLUI_String& get_history_str (int command_number) const
{ return hist_list[command_number - oldest_hist]; }
virtual void recall_history (int history_number);
virtual void scroll_history (int direction);
virtual void add_to_history (const char *text);
virtual void reset_history (void);
void dump (FILE *out, const char *text);
GLUI_CommandLine (GLUI_Node *parent, const char *name, void *live_var=NULL,
int id=-1, GLUI_CB callback=GLUI_CB ());
GLUI_CommandLine (void) { common_init (); }
protected:
void common_init () {
hist_list.resize (HIST_SIZE);
curr_hist = 0;
oldest_hist = 0;
newest_hist = 0;
commit_flag = false;
}
};
/************************************************************/
/* */
/* RadioGroup class (container) */
/* */
/************************************************************/
class GLUIAPI GLUI_RadioGroup : GLUI_Control
{
public:
int num_buttons;
void draw (int x, int y);
void set_name (const char *text);
void set_int_val (int int_val);
void set_selected (int int_val);
void draw_group (int translate);
GLUI_RadioGroup (GLUI_Node *parent, int *live_var=NULL,
int user_id=-1,GLUI_CB callback=GLUI_CB ());
GLUI_RadioGroup (void) { common_init (); }
protected:
void common_init (void) {
x_off = 0;
y_off_top = 0;
y_off_bot = 0;
is_container = true;
w = 300;
h = 300;
num_buttons = 0;
name = "";
can_activate = false;
live_type = GLUI_LIVE_INT;
}
};
/************************************************************/
/* */
/* RadioButton class (container) */
/* */
/************************************************************/
class GLUIAPI GLUI_RadioButton : GLUI_Control
{
public:
int orig_value;
bool currently_inside;
int text_x_offset;
int mouse_down_handler (int local_x, int local_y);
int mouse_up_handler (int local_x, int local_y, bool inside);
int mouse_held_down_handler (int local_x, int local_y, bool inside);
void draw (int x, int y);
void update_size (void);
void draw_active_area (void);
void draw_checked (void);
void draw_unchecked (void);
void draw_O (void);
GLUI_RadioButton (GLUI_RadioGroup *group, const char *name);
GLUI_RadioGroup *group;
protected:
void common_init ()
{
glui_format_str (name, "RadioButton: %p", (void *) this);
h = GLUI_RADIOBUTTON_SIZE;
group = NULL;
orig_value = -1;
text_x_offset = 18;
can_activate = true;
}
};
/************************************************************/
/* */
/* Separator class (container) */
/* */
/************************************************************/
class GLUIAPI GLUI_Separator : GLUI_Control
{
public:
void draw (int x, int y);
GLUI_Separator (GLUI_Node *parent);
GLUI_Separator (void) { common_init (); }
protected:
void common_init () {
w = 100;
h = GLUI_SEPARATOR_HEIGHT;
can_activate = false;
}
};
#define GLUI_SPINNER_ARROW_WIDTH 12
#define GLUI_SPINNER_ARROW_HEIGHT 8
#define GLUI_SPINNER_ARROW_Y 2
#define GLUI_SPINNER_STATE_NONE 0
#define GLUI_SPINNER_STATE_UP 1
#define GLUI_SPINNER_STATE_DOWN 2
#define GLUI_SPINNER_STATE_BOTH 3
#define GLUI_SPINNER_DEFAULT_GROWTH_EXP 1.05f
/************************************************************/
/* */
/* Spinner class (container) */
/* */
/************************************************************/
class GLUIAPI GLUI_Spinner : GLUI_Control
{
public:
// Constructor, no live auto
GLUI_Spinner (GLUI_Node* parent, const char *name,
int data_type=GLUI_SPINNER_INT, int id=-1, GLUI_CB callback=GLUI_CB ());
// Constructor, int live auto
GLUI_Spinner (GLUI_Node* parent, const char *name,
int *live_var, int id=-1, GLUI_CB callback=GLUI_CB ());
// Constructor, float live auto
GLUI_Spinner (GLUI_Node* parent, const char *name,
float *live_var, int id=-1, GLUI_CB callback=GLUI_CB ());
// Deprecated constructor
GLUI_Spinner (GLUI_Node* parent, const char *name,
int data_type,
void *live_var,
int id=-1, GLUI_CB callback=GLUI_CB ());
// Deprecated constructor
GLUI_Spinner (void) { common_init (); }
bool currently_inside;
int state;
float growth, growth_exp;
int last_x, last_y;
int data_type;
int callback_count;
int last_int_val;
float last_float_val;
int first_callback;
float user_speed;
GLUI_EditText *edittext;
int mouse_down_handler (int local_x, int local_y);
int mouse_up_handler (int local_x, int local_y, bool inside);
int mouse_held_down_handler (int local_x, int local_y, bool inside);
int key_handler (unsigned char key,int modifiers);
int special_handler (int key,int modifiers);
void draw (int x, int y);
void draw_pressed (void);
void draw_unpressed (void);
void draw_text (int sunken);
void update_size (void);
void set_float_limits (float low,float high,int limit_type=GLUI_LIMIT_CLAMP);
void set_int_limits (int low, int high,int limit_type=GLUI_LIMIT_CLAMP);
int find_arrow (int local_x, int local_y);
void do_drag (int x, int y);
void do_callbacks (void);
void do_click (void);
void idle (void);
bool needs_idle (void) const;
const char *get_text (void);
void set_float_val (float new_val);
void set_int_val (int new_val);
float get_float_val (void);
int get_int_val (void);
void increase_growth (void);
void reset_growth (void);
void set_speed (float speed) { user_speed = speed; }
protected:
void common_init () {
glui_format_str (name, "Spinner: %p", this);
h = GLUI_EDITTEXT_HEIGHT;
w = GLUI_EDITTEXT_WIDTH;
x_off = 0;
y_off_top = 0;
y_off_bot = 0;
can_activate = true;
state = GLUI_SPINNER_STATE_NONE;
edittext = NULL;
growth_exp = GLUI_SPINNER_DEFAULT_GROWTH_EXP;
callback_count = 0;
first_callback = true;
user_speed = 1.0;
}
void common_construct (GLUI_Node* parent, const char *name,
int data_type, void *live_var,
int id, GLUI_CB callback);
};
/************************************************************/
/* */
/* StaticText class */
/* */
/************************************************************/
class GLUIAPI GLUI_StaticText : GLUI_Control
{
public:
void set_text (const char *text);
void draw (int x, int y);
void draw_text (void);
void update_size (void);
void erase_text (void);
GLUI_StaticText (GLUI_Node *parent, const char *name);
GLUI_StaticText (void) { common_init (); }
protected:
void common_init () {
h = GLUI_STATICTEXT_SIZE;
name = "";
can_activate = false;
}
};
/************************************************************/
/* */
/* TextBox class - JVK */
/* */
/************************************************************/
class GLUIAPI GLUI_TextBox : GLUI_Control
{
public:
/* GLUI Textbox - JVK */
GLUI_TextBox (GLUI_Node *parent, GLUI_String &live_var,
bool scroll = false, int id=-1, GLUI_CB callback=GLUI_CB ());
GLUI_TextBox (GLUI_Node *parent,
bool scroll = false, int id=-1,
GLUI_CB callback=GLUI_CB ());
GLUI_String orig_text;
int insertion_pt;
int substring_start; /*substring that gets displayed in box*/
int substring_end;
int sel_start, sel_end; /* current selection */
int last_insertion_pt;
int debug;
int draw_text_only;
int tab_width;
int start_line;
int num_lines;
int curr_line;
int visible_lines;
int insert_x; /* Similar to "insertion_pt", these variables keep */
int insert_y; /* track of where the ptr is, but in pixels */
int keygoal_x; /* where up down keys would like to put insertion pt*/
GLUI_Scrollbar *scrollbar;
int mouse_down_handler (int local_x, int local_y);
int mouse_up_handler (int local_x, int local_y, bool inside);
int mouse_held_down_handler (int local_x, int local_y, bool inside);
int key_handler (unsigned char key,int modifiers);
int special_handler (int key,int modifiers);
void activate (int how);
void deactivate (void);
void enable (void);
void disable (void);
void draw (int x, int y);
int mouse_over (int state, int x, int y);
int get_box_width ();
int find_word_break (int start, int direction);
int substring_width (int start, int end, int initial_width=0);
void clear_substring (int start, int end);
int find_insertion_pt (int x, int y);
int update_substring_bounds (void);
void update_and_draw_text (void);
void draw_text (int x, int y);
void draw_insertion_pt (void);
void update_x_offsets (void);
void update_size (void);
void set_text (const char *text);
const char *get_text (void) { return text.c_str (); }
void dump (FILE *out, char *text);
void set_tab_w (int w) { tab_width = w; }
void set_start_line (int l) { start_line = l; }
static void scrollbar_callback (GLUI_Control*);
bool wants_tabs (void) const { return true; }
protected:
void common_init ()
{
h = GLUI_TEXTBOX_HEIGHT;
w = GLUI_TEXTBOX_WIDTH;
tab_width = GLUI_TAB_WIDTH;
num_lines = 0;
visible_lines = 0;
start_line = 0;
curr_line = 0;
insert_y = -1;
insert_x = -1;
insertion_pt = -1;
last_insertion_pt = -1;
name[0] = '\0';
substring_start = 0;
substring_end = 2;
sel_start = 0;
sel_end = 0;
active_type = GLUI_CONTROL_ACTIVE_PERMANENT;
can_activate = true;
spacebar_mouse_click = false;
scrollbar = NULL;
debug = false;
draw_text_only = false;
}
void common_construct (
GLUI_Node *parent, GLUI_String *live_var,
bool scroll, int id, GLUI_CB callback);
};
/************************************************************/
/* */
/* List class - JVK */
/* */
/************************************************************/
class GLUIAPI GLUI_List_Item : GLUI_Node
{
public:
GLUI_String text;
int id;
};
/************************************************************/
/* */
/* List class - JVK */
/* */
/************************************************************/
class GLUIAPI GLUI_List : GLUI_Control
{
public:
/* GLUI List - JVK */
GLUI_List (GLUI_Node *parent, bool scroll = false,
int id=-1, GLUI_CB callback=GLUI_CB ());
/*, GLUI_Control *object = NULL
,GLUI_InterObject_CB obj_cb = NULL);*/
GLUI_List (GLUI_Node *parent,
GLUI_String& live_var, bool scroll = false,
int id=-1,
GLUI_CB callback=GLUI_CB ()
/*,GLUI_Control *object = NULL */
/*,GLUI_InterObject_CB obj_cb = NULL*/);
GLUI_String orig_text;
int debug;
int draw_text_only;
int start_line;
int num_lines;
int curr_line;
int visible_lines;
GLUI_Scrollbar *scrollbar;
GLUI_List_Item items_list;
GLUI_Control *associated_object;
GLUI_CB obj_cb;
int cb_click_type;
int last_line;
int last_click_time;
int mouse_down_handler (int local_x, int local_y);
int mouse_up_handler (int local_x, int local_y, bool inside);
int mouse_held_down_handler (int local_x, int local_y, bool inside);
int key_handler (unsigned char key,int modifiers);
int special_handler (int key,int modifiers);
void activate (int how);
void deactivate (void);
void draw (int x, int y);
int mouse_over (int state, int x, int y);
int get_box_width ();
int find_word_break (int start, int direction);
int substring_width (const char *t, int start, int end);
int find_line (int x, int y);
void update_and_draw_text (void);
void draw_text (const char *t, int selected, int x, int y);
void update_size (void);
int add_item (int id, const char *text);
int delete_item (const char *text);
int delete_item (int id);
int delete_all ();
GLUI_List_Item *get_item_ptr (const char *text);
GLUI_List_Item *get_item_ptr (int id);
void dump (FILE *out, const char *text);
void set_start_line (int l) { start_line = l; }
static void scrollbar_callback (GLUI_Control*);
int get_current_item () { return curr_line; }
void set_click_type (int d) {
cb_click_type = d; }
void set_object_callback (GLUI_CB cb=GLUI_CB (), GLUI_Control*obj=NULL)
{ obj_cb=cb; associated_object=obj; }
protected:
void common_init ()
{
h = GLUI_LIST_HEIGHT;
w = GLUI_LIST_WIDTH;
num_lines = 0;
visible_lines = 0;
start_line = 0;
curr_line = 0;
name[0] = '\0';
active_type = GLUI_CONTROL_ACTIVE_PERMANENT;
can_activate = true;
spacebar_mouse_click = false;
scrollbar = NULL;
debug = false;
draw_text_only = false;
cb_click_type = GLUI_SINGLE_CLICK;
last_line = -1;
last_click_time = 0;
associated_object = NULL;
};
void common_construct (
GLUI_Node *parent,
GLUI_String* live_var, bool scroll,
int id,
GLUI_CB callback
/*,GLUI_Control *object*/
/*,GLUI_InterObject_CB obj_cb*/);
};
/************************************************************/
/* */
/* Scrollbar class - JVK */
/* */
/************************************************************/
class GLUIAPI GLUI_Scrollbar : GLUI_Control
{
public:
// Constructor, no live auto
GLUI_Scrollbar (GLUI_Node *parent,
const char *name,
int horz_vert=GLUI_SCROLL_HORIZONTAL,
int data_type=GLUI_SCROLL_INT,
int id=-1, GLUI_CB callback=GLUI_CB ()
/*,GLUI_Control *object = NULL*/
/*,GLUI_InterObject_CB obj_cb = NULL*/
);
// Constructor, int live auto
GLUI_Scrollbar (GLUI_Node *parent, const char *name, int horz_vert,
int *live_var,
int id=-1, GLUI_CB callback=GLUI_CB ()
/*,GLUI_Control *object = NULL*/
/*,GLUI_InterObject_CB obj_cb = NULL*/
);
// Constructor, float live auto
GLUI_Scrollbar (GLUI_Node *parent, const char *name, int horz_vert,
float *live_var,
int id=-1, GLUI_CB callback=GLUI_CB ()
/*,GLUI_Control *object = NULL*/
/*,GLUI_InterObject_CB obj_cb = NULL*/
);
bool currently_inside;
int state;
float growth, growth_exp;
int last_x, last_y;
int data_type;
int callback_count;
int last_int_val; ///< Used to prevent repeated callbacks.
float last_float_val;
int first_callback;
float user_speed;
float float_min, float_max;
int int_min, int_max;
int horizontal;
double last_update_time; ///< GLUI_Time () we last advanced scrollbar.
double velocity_limit; ///< Maximum distance to advance per second.
int box_length;
int box_start_position;
int box_end_position;
int track_length;
/* Rather than directly access an Editbox or Textbox for
changing variables, a pointer to some object is defined
along with a static callback in the form func (void *, int) -
the int is the new value, the void * must be cast to that
particular object type before use.
*/
void * associated_object; /* Lets the Spinner manage it's own callbacks */
GLUI_CB object_cb; /* function pointer to object call_back */
int mouse_down_handler (int local_x, int local_y);
int mouse_up_handler (int local_x, int local_y, bool inside);
int mouse_held_down_handler (int local_x, int local_y, bool inside);
int key_handler (unsigned char key,int modifiers);
int special_handler (int key,int modifiers);
void draw (int x, int y);
void draw_pressed (void);
void draw_unpressed (void);
void draw_text (int sunken);
void update_size (void);
void set_int_limits (int low, int high,int limit_type=GLUI_LIMIT_CLAMP);
void set_float_limits (float low,float high,int limit_type=GLUI_LIMIT_CLAMP);
int find_arrow (int local_x, int local_y);
void do_drag (int x, int y);
void do_callbacks (void);
void draw_scroll (void);
void do_click (void);
void idle (void);
bool needs_idle (void) const;
void set_int_val (int new_val);
void set_float_val (float new_val);
void increase_growth (void);
void reset_growth (void);
void set_speed (float speed) { user_speed = speed; };
void update_scroll_parameters ();
void set_object_callback (GLUI_CB cb=GLUI_CB (), GLUI_Control*obj=NULL)
{ object_cb=cb; associated_object=obj; }
protected:
void common_init (void);
void common_construct (
GLUI_Node *parent,
const char *name,
int horz_vert,
int data_type, void* live_var,
int id, GLUI_CB callback
/*,GLUI_Control *object
,GLUI_InterObject_CB obj_cb*/
);
virtual void draw_scroll_arrow (int arrowtype, int x, int y);
virtual void draw_scroll_box (int x, int y, int w, int h);
};
/************************************************************/
/* */
/* Listbox class */
/* */
/************************************************************/
class GLUIAPI GLUI_Listbox_Item : GLUI_Node
{
public:
GLUI_String text;
int id;
};
class GLUIAPI GLUI_Listbox : GLUI_Control
{
public:
GLUI_String curr_text;
GLUI_Listbox_Item items_list;
int depressed;
int orig_value;
bool currently_inside;
int text_x_offset, title_x_offset;
int glut_menu_id;
int mouse_down_handler (int local_x, int local_y);
int mouse_up_handler (int local_x, int local_y, bool inside);
int mouse_held_down_handler (int local_x, int local_y, bool inside);
int key_handler (unsigned char key,int modifiers);
int special_handler (int key,int modifiers);
void update_size (void);
void draw (int x, int y);
int mouse_over (int state, int x, int y);
void set_int_val (int new_val);
void dump (FILE *output);
int add_item (int id, const char *text);
int delete_item (const char *text);
int delete_item (int id);
int sort_items (void);
int do_selection (int item);
GLUI_Listbox_Item *get_item_ptr (const char *text);
GLUI_Listbox_Item *get_item_ptr (int id);
GLUI_Listbox (GLUI_Node *parent,
const char *name, int *live_var=NULL,
int id=-1, GLUI_CB callback=GLUI_CB ());
GLUI_Listbox (void) { common_init (); }
protected:
/** Change w and return true if we need to be widened to fit the current item. */
bool recalculate_item_width (void);
void common_init () {
glui_format_str (name, "Listbox: %p", this);
w = GLUI_EDITTEXT_WIDTH;
h = GLUI_EDITTEXT_HEIGHT;
orig_value = -1;
title_x_offset = 0;
text_x_offset = 55;
can_activate = true;
curr_text = "";
live_type = GLUI_LIVE_INT; /* This has an integer live auto */
depressed = false;
glut_menu_id = -1;
}
~GLUI_Listbox ();
};
/************************************************************/
/* */
/* Mouse_Interaction class */
/* */
/************************************************************/
/**
This is the superclass of translation and rotation widgets.
*/
class GLUIAPI GLUI_Mouse_Interaction : GLUI_Control
{
public:
/*int get_main_area_size (void) { return MIN (h-18, */
int draw_active_area_only;
int mouse_down_handler (int local_x, int local_y);
int mouse_up_handler (int local_x, int local_y, bool inside);
int mouse_held_down_handler (int local_x, int local_y, bool inside);
int special_handler (int key, int modifiers);
void update_size (void);
void draw (int x, int y);
void draw_active_area (void);
/*** The following methods (starting with "iaction_") need to
be overloaded ***/
virtual int iaction_mouse_down_handler (int local_x, int local_y) = 0;
virtual int iaction_mouse_up_handler (int local_x, int local_y, bool inside)=0;
virtual int iaction_mouse_held_down_handler (int local_x, int local_y, bool inside)=0;
virtual int iaction_special_handler (int key, int modifiers)=0;
virtual void iaction_draw_active_area_persp (void)=0;
virtual void iaction_draw_active_area_ortho (void)=0;
virtual void iaction_dump (FILE *output)=0;
virtual void iaction_init (void) = 0;
GLUI_Mouse_Interaction (void) {
glui_format_str (name, "Mouse_Interaction: %p", this);
w = GLUI_MOUSE_INTERACTION_WIDTH;
h = GLUI_MOUSE_INTERACTION_HEIGHT;
can_activate = true;
live_type = GLUI_LIVE_NONE;
alignment = GLUI_ALIGN_CENTER;
draw_active_area_only = false;
}
};
/************************************************************/
/* */
/* Rotation class */
/* */
/************************************************************/
/**
An onscreen rotation controller--allows the user to interact with
a 3D rotation via a spaceball-like interface.
*/
class GLUIAPI GLUI_Rotation : GLUI_Mouse_Interaction
{
public:
Arcball *ball;
GLUquadricObj *quadObj;
bool can_spin, spinning;
float damping;
int iaction_mouse_down_handler (int local_x, int local_y);
int iaction_mouse_up_handler (int local_x, int local_y, bool inside);
int iaction_mouse_held_down_handler (int local_x, int local_y, bool inside);
int iaction_special_handler (int key, int modifiers);
void iaction_init (void) { init_ball (); }
void iaction_draw_active_area_persp (void);
void iaction_draw_active_area_ortho (void);
void iaction_dump (FILE *output);
/* void update_size (void); */
/* void draw (int x, int y); */
/* int mouse_over (int state, int x, int y); */
void setup_texture (void);
void setup_lights (void);
void draw_ball (float radius);
void init_ball (void);
void reset (void);
bool needs_idle (void) const;
void idle (void);
void copy_float_array_to_ball (void);
void copy_ball_to_float_array (void);
void set_spin (float damp_factor);
GLUI_Rotation (GLUI_Node *parent, const char *name, float *live_var=NULL,
int id=-1, GLUI_CB callback=GLUI_CB ());
GLUI_Rotation (void) { common_init (); }
protected:
void common_init ();
};
/************************************************************/
/* */
/* Translation class */
/* */
/************************************************************/
/**
An onscreen translation controller--allows the user to interact with
a 3D translation.
*/
class GLUIAPI GLUI_Translation : GLUI_Mouse_Interaction
{
public:
int trans_type; /* Is this an XY or a Z controller? */
int down_x, down_y;
float scale_factor;
GLUquadricObj *quadObj;
int trans_mouse_code;
float orig_x, orig_y, orig_z;
int locked;
int iaction_mouse_down_handler (int local_x, int local_y);
int iaction_mouse_up_handler (int local_x, int local_y, bool inside);
int iaction_mouse_held_down_handler (int local_x, int local_y, bool inside);
int iaction_special_handler (int key, int modifiers);
void iaction_init (void) { }
void iaction_draw_active_area_persp (void);
void iaction_draw_active_area_ortho (void);
void iaction_dump (FILE *output);
void set_speed (float s) { scale_factor = s; }
void setup_texture (void);
void setup_lights (void);
void draw_2d_arrow (int radius, int filled, int orientation);
void draw_2d_x_arrows (int radius);
void draw_2d_y_arrows (int radius);
void draw_2d_z_arrows (int radius);
void draw_2d_xy_arrows (int radius);
int get_mouse_code (int x, int y);
/* Float array is either a single float (for single-axis controls),
or two floats for X and Y (if an XY controller) */
float get_z (void) { return float_array_val[0]; }
float get_x (void) { return float_array_val[0]; }
float get_y (void) {
if (trans_type == GLUI_TRANSLATION_XY) return float_array_val[1];
else return float_array_val[0];
}
void set_z (float val);
void set_x (float val);
void set_y (float val);
void set_one_val (float val, int index);
GLUI_Translation (GLUI_Node *parent, const char *name,
int trans_type, float *live_var=NULL,
int id=-1, GLUI_CB callback=GLUI_CB () );
GLUI_Translation (void) { common_init (); }
protected:
void common_init () {
locked = GLUI_TRANSLATION_LOCK_NONE;
glui_format_str (name, "Translation: %p", this);
w = GLUI_MOUSE_INTERACTION_WIDTH;
h = GLUI_MOUSE_INTERACTION_HEIGHT;
can_activate = true;
live_type = GLUI_LIVE_FLOAT_ARRAY;
float_array_size = 0;
alignment = GLUI_ALIGN_CENTER;
trans_type = GLUI_TRANSLATION_XY;
scale_factor = 1.0;
quadObj = NULL;
trans_mouse_code = GLUI_TRANSLATION_MOUSE_NONE;
}
};
/********** Misc functions *********************/
int _glutBitmapWidthString (void *font, const char *s);
void _glutBitmapString (void *font, const char *s);
/********** Our own callbacks for glut *********/
/* These are the callbacks that we pass to glut. They take
some action if necessary, then (possibly) call the user-level
glut callbacks.
*/
void glui_display_func (void);
void glui_reshape_func (int w, int h);
void glui_keyboard_func (unsigned char key, int x, int y);
void glui_special_func (int key, int x, int y);
void glui_mouse_func (int button, int state, int x, int y);
void glui_motion_func (int x, int y);
void glui_passive_motion_func (int x, int y);
void glui_entry_func (int state);
void glui_visibility_func (int state);
void glui_idle_func (void);
void glui_parent_window_reshape_func (int w, int h);
void glui_parent_window_keyboard_func (unsigned char key, int x, int y);
void glui_parent_window_mouse_func (int, int, int, int);
void glui_parent_window_special_func (int key, int x, int y);
#endif
| [
"Blue Storm Engineering LLC"
] | Blue Storm Engineering LLC |
22329fbb12419a87680d075f3e5e2f4c40801ca1 | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/BIOSService/UNIX_BIOSService_HPUX.hxx | 8b3c5eeff14bf1d3e1ba39dac5d8b3947825c53b | [
"MIT"
] | permissive | brunolauze/openpegasus-providers | 3244b76d075bc66a77e4ed135893437a66dd769f | f24c56acab2c4c210a8d165bb499cd1b3a12f222 | refs/heads/master | 2020-04-17T04:27:14.970917 | 2015-01-04T22:08:09 | 2015-01-04T22:08:09 | 19,707,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,806 | hxx | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#ifdef PEGASUS_OS_HPUX
#ifndef __UNIX_BIOSSERVICE_PRIVATE_H
#define __UNIX_BIOSSERVICE_PRIVATE_H
#endif
#endif
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
a04afbc5445719bce82a6331def105e2e46d82c2 | 2c4313a314c642a7e7f04200907004b3e334386a | /text_line_detection/.history/main_20171209162859.cpp | eeddf36ff7591814ae9e3728b3bcfcad3eaadc3f | [] | no_license | Oakga/Image-Recognition | 5d17c38934f8e8e9d8d3d7026978bf26e767817a | 7089fc216a364569b2f42c8008af233dd06d5133 | refs/heads/master | 2021-08-28T00:31:28.557039 | 2017-12-10T21:27:32 | 2017-12-10T21:27:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,780 | cpp | #include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
class imagePP;
class BBox;
struct boxNode;
struct boxNode
{
int type; // 1 for img box, 2 for text-line box, 3 for text-word box, etc.
int minRow;
int minCol;
int maxRow;
int maxCol;
boxNode *nextBox;
boxNode()
{
type = 1;
minRow = minCol = maxRow = maxCol = 0;
nextBox = 0;
};
boxNode(int type_, int minRow_, int minCol_, int maxRow_, int maxCol_)
{
type = type_;
minRow = minRow_;
minCol = minCol_;
maxRow = maxRow_;
maxCol = maxCol_;
};
void printbox()
{
printf("\nBOX: %u %u %u %u %u ", type, minRow, minCol, maxRow, maxCol);
};
};
class imagePP
{
public:
int numRows, numCols, minVal, maxVal;
int threshold;
int **imageAry;
int *HPP;
int *HPPbin;
int *VPP;
int *VPPbin;
ifstream imageScan;
ofstream out;
imagePP(string binaryImage, string thresholdValue, string output)
{
threshold = stoi(thresholdValue);
imageScan.open(binaryImage);
out.open(output);
imageScan >> numRows >> numCols >> minVal >> maxVal;
imageAry = new int *[numRows];
for (int i = 0; i < numRows; i++)
{
imageAry[i] = new int[numCols];
}
HPP = new int[numRows]();
HPPbin = new int[numRows]();
VPP = new int[numCols]();
VPPbin = new int[numCols]();
};
~imagePP()
{
imageScan.close();
out.close();
for (int i = 0; i < numRows; i++)
{
delete[] imageAry[i];
}
delete[] imageAry;
delete[] HPP;
delete[] HPPbin;
delete[] VPP;
delete[] VPPbin;
}
void loadImage()
{
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < numCols; j++)
{
imageScan >> imageAry[i][j];
}
}
}
void computePP(boxNode &box)
{ //compuyte VPP and HPP combined
for (int i = box.minRow; i < box.maxRow; i++)
{
for (int j = box.minCol; j < box.maxCol; j++)
{
if (imageAry[i][j] > 0)
{
HPP[i]++;
VPP[j]++;
}
}
}
//printing
printPP(HPP, numRows, "HOR");
printPP(VPP, numCols, "VER");
};
void clearArrays()
{
memset(HPP, 0, sizeof(int) * numRows);
memset(HPPbin, 0, sizeof(int) * numRows);
memset(VPP, 0, sizeof(int) * numCols);
memset(VPP, 0, sizeof(int) * numCols);
};
void printPP(int *arr, int size, string name)
{
cout << "\n" << name << ":";
for (int j = 0; j < size; j++)
{
cout << arr[j] << " ";
}
cout << "\n";
};
void thresholding(const int size)
{
//check which array we want to threshold i.e VPP or HPP
int *arr;
int *arrBin;
string arrName;
if (size == numRows)
{
arr = HPP;
arrBin = HPPbin;
arrName = "HOR";
}
else
{
arr = VPP;
arrBin = VPPbin;
arrName = "VER";
};
//thresholding
for (int i = 0; i < size; i++)
{
if (arr[i] < threshold)
arrBin[i] = 0;
else
arrBin[i] = 1;
}
//printing
printPP(arrBin, size, arrName);
}
int findReadingDir()
{
int HPPboxCt = countBoxes(numRows);
// int VPPboxCt = countBoxes(numCols);
int VPPboxCt = 5;
printf("\nBOXCOUNT H: %u V: %u", HPPboxCt, VPPboxCt);
if (HPPboxCt > VPPboxCt)
return 1; // horinzontal
else
return 0; //vertical
}
int countBoxes(const int size)
{
//check which array we want to count i.e VPPbin or HPPbin
int *arrBin;
string arrName;
if (size == numRows)
{
arrBin = HPPbin;
arrName = "HOR";
}
else
{
arrBin = VPPbin;
arrName = "VER";
};
//counting
int index, boxCount, counterZero, counterOne;
index = boxCount = 0;
do
{
counterZero = counterOne = 0;
while (arrBin[index] <= 0)
{
index++;
counterZero++;
};
//make sure no overflow
if (index < size)
{
while (arrBin[index] > 0)
{
index++;
counterOne++;
}
}
// this ensure that each boxes are regex [ 0 0* 1 1* ]
if (counterZero > 0 && counterOne > 0) boxCount++;
} while (index < size);
return boxCount;
}
};
class BBox
{
friend class imagePP;
public:
// boxNode *imgBox;
// BBox()
// {
// imgBox = NULL;
// }
// ~BBox()
// {
// free(imgBox);
// }
class boxList
{
public:
boxNode *listHead;
boxNode *last;
boxList()
{
boxNode *dummy = new boxNode;
listHead = last = dummy;
}
~boxList()
{
freeList();
}
void insertLast(boxNode *box)
{
boxNode *lastBox = last;
lastBox->nextBox = box;
last = box;
}
void printList()
{
boxNode *spot = listHead->nextBox;
cout << "\n";
cout << "ListHead-->";
while (spot != 0)
{
cout << "(";
spot->printbox();
cout << ") -->";
spot = spot->nextBox;
}
cout << "NULL\n";
delete spot;
}
void freeList()
{
boxNode *spot = listHead;
while (listHead != 0)
{
spot = listHead;
listHead = listHead->nextBox;
free(spot);
}
}
static void printList(boxList *box)
{
boxNode *spot = box->listHead->nextBox;
cout << "\n";
cout << "ListHead-->";
while (spot != 0)
{
cout << "(" << to_string(spot->type) << ")-->";
spot = spot->nextBox;
}
cout << "NULL\n";
delete spot;
}
};
static boxNode findImgBox(int **&imgAry, const int numRows, const int numCols)
{
bool firstTime = true;
boxNode box;
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < numCols; j++)
{
if (imgAry[i][j] > 0)
{
// intialized the imgBox class object if first time
if (firstTime == true)
{
firstTime = false;
box.minRow = box.maxRow = i;
box.minCol = box.maxCol = j;
};
//otherwise update the object
compare(box, i, j);
};
};
};
box.printbox();
return box;
};
//update the bouding box of the image if new max for row and col are found
static void compare(boxNode &box, const int row, const int col)
{
if (row < box.minRow)
box.minRow = row;
if (row > box.maxRow)
box.maxRow = row;
if (col < box.minCol)
box.minCol = col;
if (col > box.maxCol)
box.maxCol = col;
};
/* for example: if reading dirOfPP is horizontal, we need HPP for line boxes
column is consistant, row will be changing for each line
and dirOfPP in this case will be dirOfPP of PP and thus, dirOfPP is 1
in summary:
if PP is VPPbin , dirOfPP is 0 horizontal
if PP is HPPbin, dirOfPP is 1 vertical
*/
boxList findLineBoxes(boxNode &imgBox, const int dirOfPP, int *PP, const int PPSize)
{
int minCol, maxCol = 0;
int minRow, maxRow = 0;
boxList boxHead;
int index = 0;
while (index < PPSize)
{
//skip all 0s
while (PP[index] <= 0)
index++;
//found starting point
if( dirOfPP == 1) minRow = index; //given PP is HPPbin and dirOfPP 1 is horizontal
else minCol = index;
//avoid overflow
if (index < PPSize)
{
//skip all 1s
while (PP[index] > 0)
index++;
// found the last point of the boundary: bounding box is now complete
if( dirOfPP == 1) {
maxRow = index - 1;
// col is consistant
boxNode *newBox = new boxNode(2, minRow, imgBox.minCol, maxRow, imgBox.maxCol);
boxHead.insertLast(newBox);
}
else {
maxCol = index;
//row is consistant
boxNode *newBox = new boxNode(2, imgBox.minRow, minCol, imgBox.maxRow, maxCol);
boxHead.insertLast(newBox);
}
};
}
boxHead.printList();
return boxHead;
};
};
int main(int argc, char *argv[])
{
//intializations
string dirInEng;
int readingDir;
imagePP textImage(argv[1], argv[2], argv[3]);
textImage.loadImage();
//find text image bouding box
boxNode box = BBox::findImgBox(textImage.imageAry, textImage.numRows, textImage.numCols); //image box
// compute HPP and VPP
textImage.computePP(box);
cout << "After threshold";
//thresholding HPP and VPP with user input
textImage.thresholding(textImage.numRows);
textImage.thresholding(textImage.numCols);
//determine reading dirOfPP
readingDir = textImage.findReadingDir();
if (readingDir == 1) dirInEng = "horizontal";
else dirInEng = "vertical";
cout << "\nReading DIR:" << dirInEng << "\n";
//find text-line bouding boxes
if (Readingdir == "horizontal")
{
BBox::boxList lineList = box.findLineBoxes(box, 1, textImage.numRows);
// BBox::boxList lineList = box.findLineBoxesHorizontal(textImage.HPPbin, textImage.numRows);
// lineList.printList();
// BBox::boxList wordList;
// boxNode *lineWalker = lineList.listHead->nextBox;
// while (lineWalker != 0)
// {
// textImage.clearArrays();
// lineWalker->printbox();
// textImage.computePP(lineWalker);
// textImage.thresholdVertical();
// lineWalker = lineWalker->nextBox;
// cout << endl;
// }
// free(lineWalker);
// }
// else
// {
// BBox::boxList lineList = box.findLineBoxesVertical(textImage.VPPbin, textImage.numCols);
// lineList.printList();
// textImage.clearArrays();
// boxNode *lineWalker = lineList.listHead->nextBox;
// while (lineWalker != 0)
// {
// textImage.clearArrays();
// lineWalker->printbox();
// textImage.computePP(lineWalker);
// textImage.thresholdHorizontal();
// lineWalker = lineWalker->nextBox;
// cout << endl;
// }
// free(lineWalker);
// };
// };
}; | [
"oakioakga@gmail.com"
] | oakioakga@gmail.com |
3875c20e92b6a18654c0504e543d8a21850027c6 | 59515d772c78195cd0c5b22bc58e59c48efcedb2 | /776A[A_Serial_Killer].cpp | 4c7151e04f29ca1976e75100402d63d091da98e4 | [] | no_license | minhazmiraz/Codeforces_AC_Submission | 286a7799699b666c9ceddad25ac59a4fe34ac48b | 6ed22a72b7a49bc3880514e3bfac85451e41dd35 | refs/heads/master | 2021-09-29T00:05:49.985949 | 2018-11-21T18:35:00 | 2018-11-21T18:35:00 | 80,108,257 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 722 | cpp | #include<bits/stdc++.h>
using namespace std;
#define debug(x,y) cout<<x<<y
#define pb push_back
#define mp make_pair
#define long long ll
#define unsigned long long ull
int main() {
string first1,first2;
cin>>first1>>first2;
cout<<first1<<" "<<first2<<"\n";
int n;
cin>>n;
for(int i=1;i<=n;i++){
string str1,str2;
cin>>str1>>str2;
//cout<<str1<<" "<<str2<<" "<<first1<<" "<<first2<<"\n";
if(str1==first1){
cout<<str2<<" "<<first2<<"\n";
first1.clear();
first1=str2;
}else if(str1==first2){
cout<<first1<<" "<<str2<<"\n";
first2.clear();
first2=str2;
}
}
return 0;
}
| [
"minhazmiraz49@gmail.com"
] | minhazmiraz49@gmail.com |
d14a5f00c63bf33a642de26b197c50900a5ed0b7 | c0e01dd6570ab2fe2deaa34d82b6418d40195b85 | /src/IO/binaryIO_test.cpp | 2bd28c897b4501f8df4b033f9cc654a51c4eda72 | [] | no_license | eraserxp/CalculateGreenFunction | d2b6b7552bc9c0f42998855a6625f60dfec6bb14 | d7f71b5bf9adf22449792e45c4677f4c4d4b65d2 | refs/heads/master | 2020-05-01T02:07:37.811708 | 2014-12-13T00:08:21 | 2014-12-13T00:08:21 | 21,175,679 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,030 | cpp | /*
* binaryIO_test.cpp
*
* Created on: Jan 2, 2014
* Author: pxiang
*/
#include "gtest/gtest.h"
#include "binaryIO.h"
TEST(BinaryIO, TwoByTwoMatirx) {
CDMatrix cm(2,2);
cm(0,0) = dcomplex(1.0, 0.5);
cm(0,1) = dcomplex(1.3, 0.3);
cm(1,0) = dcomplex(1.89, 0.35);
cm(1,1) = dcomplex(1.07899, 0.1135);
saveMatrixBin("cm.bin",cm);
CDMatrix cm2;
loadMatrixBin("cm.bin",cm2);
EXPECT_EQ(cm.rows(), cm2.rows());
EXPECT_EQ(cm.cols(), cm2.cols());
for (int i=0; i<cm.rows(); ++i) {
for (int j=0; j<cm.cols(); ++j) {
dcomplex c1 = cm(i,j);
dcomplex c2 = cm2(i,j);
EXPECT_DOUBLE_EQ(c1.real(), c2.real());
EXPECT_DOUBLE_EQ(c1.imag(), c2.imag());
}
}
}
TEST(BinaryIO, TwoByOneMatirx) {
CDMatrix cm(2,1);
cm(0,0) = dcomplex(1.0, 0.5);
cm(1,0) = dcomplex(1.89, 0.35);
saveMatrixBin("cm.bin",cm);
CDMatrix cm2;
loadMatrixBin("cm.bin",cm2);
EXPECT_EQ(cm.rows(), cm2.rows());
EXPECT_EQ(cm.cols(), cm2.cols());
for (int i=0; i<cm.rows(); ++i) {
for (int j=0; j<cm.cols(); ++j) {
dcomplex c1 = cm(i,j);
dcomplex c2 = cm2(i,j);
EXPECT_DOUBLE_EQ(c1.real(), c2.real());
EXPECT_DOUBLE_EQ(c1.imag(), c2.imag());
}
}
}
TEST(BinaryIO, OneByTwoMatirx) {
CDMatrix cm(1,2);
cm(0,0) = dcomplex(1.0, 0.5);
cm(0,1) = dcomplex(1.3, 0.3);
saveMatrixBin("cm.bin",cm);
CDMatrix cm2;
loadMatrixBin("cm.bin",cm2);
EXPECT_EQ(cm.rows(), cm2.rows());
EXPECT_EQ(cm.cols(), cm2.cols());
for (int i=0; i<cm.rows(); ++i) {
for (int j=0; j<cm.cols(); ++j) {
dcomplex c1 = cm(i,j);
dcomplex c2 = cm2(i,j);
EXPECT_DOUBLE_EQ(c1.real(), c2.real());
EXPECT_DOUBLE_EQ(c1.imag(), c2.imag());
}
}
}
TEST(BinaryIO, OneByOneMatirx) {
CDMatrix cm(1,1);
cm(0,0) = dcomplex(1.0, 0.5);
saveMatrixBin("cm.bin",cm);
CDMatrix cm2;
loadMatrixBin("cm.bin",cm2);
EXPECT_EQ(cm.rows(), cm2.rows());
EXPECT_EQ(cm.cols(), cm2.cols());
for (int i=0; i<cm.rows(); ++i) {
for (int j=0; j<cm.cols(); ++j) {
dcomplex c1 = cm(i,j);
dcomplex c2 = cm2(i,j);
EXPECT_DOUBLE_EQ(c1.real(), c2.real());
EXPECT_DOUBLE_EQ(c1.imag(), c2.imag());
}
}
}
TEST(BinaryIO, ThousandByThousandMatirx) {
CDMatrix cm(1000,1000);
RandomNumberGenerator random;
for (int i=0; i<cm.rows(); ++i) {
for (int j=0; j<cm.cols(); ++j) {
cm(i,j) = random.randomComplex();
}
}
saveMatrixBin("cm.bin",cm);
CDMatrix cm2;
loadMatrixBin("cm.bin",cm2);
EXPECT_EQ(cm.rows(), cm2.rows());
EXPECT_EQ(cm.cols(), cm2.cols());
for (int i=0; i<cm.rows(); ++i) {
for (int j=0; j<cm.cols(); ++j) {
dcomplex c1 = cm(i,j);
dcomplex c2 = cm2(i,j);
EXPECT_DOUBLE_EQ(c1.real(), c2.real());
EXPECT_DOUBLE_EQ(c1.imag(), c2.imag());
}
}
}
TEST(TestIOSpeed, Normal) {
CDMatrix cm = CDMatrix::Random(10000,10000);
saveMatrixBin("cm.bin",cm);
CDMatrix cm2;
loadMatrixBin("cm.bin",cm2);
EXPECT_TRUE(true);
}
TEST(TestIOSpeed, Tmpfs) {
CDMatrix cm = CDMatrix::Random(10000,10000);
saveMatrixBin("/dev/shm/cm.bin",cm);
CDMatrix cm2;
loadMatrixBin("/dev/shm/cm.bin",cm2);
EXPECT_TRUE(true);
}
| [
"eraser117xp@gmail.com"
] | eraser117xp@gmail.com |
d0a9e7aa9f82d8478b72245366b2c2ac806467b1 | 1938a256e6c81858a28c89592a431a2479eec325 | /utils/hwstub/lib/hwstub_net.cpp | f561a1004b52b33a2b8e23f59ea830da5ccf783a | [] | no_license | extremeshok/rockbox | d15c815564cac5155b87c73353a2b0e7f6e0f2a0 | d730884fe6e3c6b2561729868cee6f8af423eb00 | refs/heads/master | 2020-12-25T10:59:32.093340 | 2016-06-14T11:25:13 | 2016-06-14T11:25:13 | 61,116,756 | 2 | 0 | null | 2016-06-14T11:18:18 | 2016-06-14T11:18:17 | null | UTF-8 | C++ | false | false | 42,325 | cpp | /***************************************************************************
* __________ __ ___.
* Open \______ \ ____ ____ | | _\_ |__ _______ ___
* Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
* Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
* Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
* \/ \/ \/ \/ \/
* $Id$
*
* Copyright (C) 2016 by Amaury Pouly
*
* 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
****************************************************************************/
#include "hwstub_net.hpp"
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <cstddef>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netdb.h>
namespace hwstub {
namespace net {
/**
* Context
*/
context::context()
:m_state(state::HELLO), m_error(error::SUCCESS)
{
}
context::~context()
{
}
std::shared_ptr<context> context::create_socket(int socket_fd)
{
// NOTE: can't use make_shared() because of the protected ctor */
return std::shared_ptr<socket_context>(new socket_context(socket_fd));
}
std::string context::default_unix_path()
{
return "hwstub";
}
std::string context::default_tcp_domain()
{
return "localhost";
}
std::string context::default_tcp_port()
{
return "6666";
}
namespace
{
/* len is the total length, including a 0 character if any */
int create_unix_low(bool abstract, const char *path, size_t len, bool conn,
std::string *error)
{
struct sockaddr_un address;
if(len > sizeof(address.sun_path))
{
if(error)
*error = "unix path is too long";
return -1;
}
int socket_fd = socket(PF_UNIX, SOCK_STREAM, 0);
if(socket_fd < 0)
{
if(error)
*error = "socket() failed";
return -1;
}
memset(&address, 0, sizeof(struct sockaddr_un));
address.sun_family = AF_UNIX;
/* NOTE memcpy, we don't want to add a extra 0 at the end */
memcpy(address.sun_path, path, len);
/* for abstract name, replace first character by 0 */
if(abstract)
address.sun_path[0] = 0;
/* NOTE sun_path is the last field of the structure */
size_t sz = offsetof(struct sockaddr_un, sun_path) + len;
/* NOTE don't give sizeof(address) because for abstract names it would contain
* extra garbage */
if(conn)
{
if(connect(socket_fd, (struct sockaddr *)&address, sz) != 0)
{
close(socket_fd);
if(error)
*error = "connect() failed";
return -1;
}
else
return socket_fd;
}
else
{
if(bind(socket_fd, (struct sockaddr *)&address, sz) != 0)
{
close(socket_fd);
if(error)
*error = "bind() failed";
return -1;
}
else
return socket_fd;
}
}
int create_tcp_low(const std::string& domain, const std::string& _port, bool server, std::string *error)
{
std::string port = _port.size() != 0 ? _port : context::default_tcp_port();
int socket_fd = -1;
struct addrinfo hints;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = 0; /* any protocol */
struct addrinfo *result;
int err = getaddrinfo(domain.c_str(), port.c_str(), &hints, &result);
if(err != 0)
{
if(error)
*error = std::string("getaddrinfo failed: ") + gai_strerror(err);
return -1;
}
/* getaddrinfo() returns a list of address structures.
* Try each address until we successfully connect(2).
* If socket(2) (or connect(2)/bind(2)) fails, we (close the socket
* and) try the next address. */
for(struct addrinfo *rp = result; rp != nullptr; rp = rp->ai_next)
{
socket_fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if(socket_fd == -1)
continue;
int err = 0;
if(server)
err = bind(socket_fd, rp->ai_addr, rp->ai_addrlen);
else
err = connect(socket_fd, rp->ai_addr, rp->ai_addrlen);
if(err < 0)
{
close(socket_fd);
socket_fd = -1;
}
else
break; /* success */
}
/* no address was tried */
if(socket_fd < 0 && error)
*error = "getaddrinfo() returned no usable result (socket()/connect()/bind() failed)";
return socket_fd;
}
}
std::shared_ptr<context> context::create_tcp(const std::string& domain,
const std::string& port, std::string *error)
{
int fd = create_tcp_low(domain, port, false, error);
if(fd >= 0)
return context::create_socket(fd);
else
return std::shared_ptr<context>();
}
std::shared_ptr<context> context::create_unix(const std::string& path, std::string *error)
{
int fd = create_unix_low(false, path.c_str(), path.size() + 1, true, error);
if(fd >= 0)
return context::create_socket(fd);
else
return std::shared_ptr<context>();
}
std::shared_ptr<context> context::create_unix_abstract(const std::string& path, std::string *error)
{
std::string fake_path = "#" + path; /* the # will be overriden by 0 */
int fd = create_unix_low(true, fake_path.c_str(), fake_path.size(), true, error);
if(fd >= 0)
return context::create_socket(fd);
else
return std::shared_ptr<context>();
}
uint32_t context::from_ctx_dev(ctx_dev_t dev)
{
return (uint32_t)(uintptr_t)dev; /* NOTE safe because it was originally a 32-bit int */
}
hwstub::context::ctx_dev_t context::to_ctx_dev(uint32_t dev)
{
return (ctx_dev_t)(uintptr_t)dev; /* NOTE assume that sizeof(void *)>=sizeof(uint32_t) */
}
error context::fetch_device_list(std::vector<ctx_dev_t>& list, void*& ptr)
{
(void) ptr;
delayed_init();
if(m_state == state::DEAD)
return m_error;
uint32_t args[HWSTUB_NET_ARGS] = {0};
uint8_t *data = nullptr;
size_t data_sz = 0;
debug() << "[net::ctx] --> GET_DEV_LIST\n";
error err = send_cmd(HWSERVER_GET_DEV_LIST, args, nullptr, 0, &data, &data_sz);
debug() << "[net::ctx] <-- GET_DEV_LIST ";
if(err != error::SUCCESS)
{
debug() << "failed: " << error_string(err) << "\n";
return err;
}
/* sanity check on size */
if(data_sz % 4)
{
debug() << "failed: invalid list size\n";
delete[] data;
return error::PROTOCOL_ERROR;
}
debug() << "\n";
list.clear();
/* each entry is a 32-bit ID in network order size */
uint32_t *data_list = (uint32_t *)data;
for(size_t i = 0; i < data_sz / 4; i++)
list.push_back(to_ctx_dev(from_net_order(data_list[i])));
delete[] data;
return error::SUCCESS;
}
void context::destroy_device_list(void *ptr)
{
(void)ptr;
}
error context::create_device(ctx_dev_t dev, std::shared_ptr<hwstub::device>& hwdev)
{
// NOTE: can't use make_shared() because of the protected ctor */
hwdev.reset(new device(shared_from_this(), from_ctx_dev(dev)));
return error::SUCCESS;
}
bool context::match_device(ctx_dev_t dev, std::shared_ptr<hwstub::device> hwdev)
{
device *udev = dynamic_cast<device*>(hwdev.get());
return udev != nullptr && udev->device_id() == from_ctx_dev(dev);
}
uint32_t context::to_net_order(uint32_t u)
{
return htonl(u);
}
uint32_t context::from_net_order(uint32_t u)
{
return ntohl(u);
}
error context::send_cmd(uint32_t cmd, uint32_t args[HWSTUB_NET_ARGS], uint8_t *send_data,
size_t send_size, uint8_t **recv_data, size_t *recv_size)
{
/* make sure with have the lock, this function might be called concurrently
* by the different threads */
std::unique_lock<std::recursive_mutex> lock(m_mutex);
if(m_state == state::DEAD)
return m_error;
/* do a delayed init, unless with are doing a HELLO */
if(m_state == state::HELLO && cmd != HWSERVER_HELLO)
delayed_init();
/* build header */
struct hwstub_net_hdr_t hdr;
hdr.magic = to_net_order(HWSERVER_MAGIC);
hdr.cmd = to_net_order(cmd);
for(size_t i = 0; i < HWSTUB_NET_ARGS; i++)
hdr.args[i] = to_net_order(args[i]);
hdr.length = to_net_order((uint32_t)send_size);
/* send header */
size_t sz = sizeof(hdr);
error err = send((void *)&hdr, sz);
if(err != error::SUCCESS)
{
m_state = state::DEAD;
m_error = err;
return err;
}
if(sz != sizeof(hdr))
{
m_state = state::DEAD;
m_error = error::PROTOCOL_ERROR;
}
/* send data */
if(send_size > 0)
{
sz = send_size;
err = send((void *)send_data, sz);
if(err != error::SUCCESS)
{
m_state = state::DEAD;
m_error = err;
return err;
}
if(sz != send_size)
{
m_state = state::DEAD;
m_error = error::PROTOCOL_ERROR;
}
}
/* receive header */
sz = sizeof(hdr);
err = recv((void *)&hdr, sz);
if(err != error::SUCCESS)
{
m_state = state::DEAD;
m_error = err;
return err;
}
if(sz != sizeof(hdr))
{
m_state = state::DEAD;
m_error = error::PROTOCOL_ERROR;
return m_error;
}
/* correct byte order */
hdr.magic = from_net_order(hdr.magic);
hdr.cmd = from_net_order(hdr.cmd);
hdr.length = from_net_order(hdr.length);
/* copy arguments */
for(size_t i = 0; i < HWSTUB_NET_ARGS; i++)
args[i] = from_net_order(hdr.args[i]);
/* check header */
if(hdr.magic != HWSERVER_MAGIC)
{
m_state = state::DEAD;
m_error = error::PROTOCOL_ERROR;
return m_error;
}
/* check NACK */
if(hdr.cmd == HWSERVER_NACK(cmd))
{
/* translate error */
switch(args[0])
{
case HWERR_FAIL: err = error::ERROR; break;
case HWERR_INVALID_ID: err = error::ERROR; break; /* should not happen */
case HWERR_DISCONNECTED: err = error::DISCONNECTED; break;
}
return err;
}
/* check not ACK */
if(hdr.cmd != HWSERVER_ACK(cmd))
{
m_state = state::DEAD;
m_error = error::PROTOCOL_ERROR;
return m_error;
}
/* receive additional data */
uint8_t *data = nullptr;
if(hdr.length > 0)
{
data = new uint8_t[hdr.length];
sz = hdr.length;
err = recv((void *)data, sz);
if(err != error::SUCCESS)
{
m_state = state::DEAD;
m_error = err;
return err;
}
if(sz != hdr.length)
{
m_state = state::DEAD;
m_error = error::PROTOCOL_ERROR;
return m_error;
}
}
/* copy data if user want it */
if(recv_data)
{
if(*recv_data == nullptr)
{
*recv_data = data;
*recv_size = hdr.length;
}
else if(*recv_size < hdr.length)
{
delete[] data;
return error::OVERFLW;
}
else
{
*recv_size = hdr.length;
memcpy(*recv_data, data, *recv_size);
delete[] data;
}
}
/* throw it away otherwise */
else
{
delete[] data;
}
return error::SUCCESS;
}
void context::delayed_init()
{
/* only do HELLO if we haven't do it yet */
if(m_state != state::HELLO)
return;
debug() << "[net::ctx] --> HELLO " << HWSTUB_VERSION_MAJOR << "."
<< HWSTUB_VERSION_MINOR << "\n";
/* send HELLO with our version and see what the server is up to */
uint32_t args[HWSTUB_NET_ARGS] = {0};
args[0] = HWSTUB_VERSION_MAJOR << 8 | HWSTUB_VERSION_MINOR;
error err = send_cmd(HWSERVER_HELLO, args, nullptr, 0, nullptr, nullptr);
if(err != error::SUCCESS)
{
debug() << "[net::ctx] <-- HELLO failed: " << error_string(err) << "\n";
m_state = state::DEAD;
m_error = err;
return;
}
/* check the server is running the same version */
debug() << "[net::ctx] <-- HELLO " << ((args[0] & 0xff00) >> 8) << "." << (args[0] & 0xff) << "";
if(args[0] != (HWSTUB_VERSION_MAJOR << 8 | HWSTUB_VERSION_MINOR))
{
debug() << " (mismatch)\n";
m_state = state::DEAD;
m_error = error::SERVER_MISMATCH;
}
debug() << " (good)\n";
/* good, we can now send commands */
m_state = state::IDLE;
}
void context::stop_context()
{
/* make sure with have the lock, this function might be call asynchronously */
std::unique_lock<std::recursive_mutex> lock(m_mutex);
/* if dead, don't do anything */
if(m_state == state::DEAD)
return;
/* only send BYE if we are initialized */
if(m_state == state::IDLE)
{
debug() << "[net::ctx] --> BYE\n";
/* send BYE */
uint32_t args[HWSTUB_NET_ARGS] = {0};
error err = send_cmd(HWSERVER_BYE, args, nullptr, 0, nullptr, nullptr);
if(err != error::SUCCESS)
{
debug() << "[net::ctx] <-- BYE failed: " << error_string(err) << "\n";
m_state = state::DEAD;
m_error = err;
return;
}
debug() << "[net::ctx] <-- BYE\n";
}
/* now we are dead */
m_state = state::DEAD;
m_error = error::SERVER_DISCONNECTED;
}
/**
* Socket context
*/
socket_context::socket_context(int socket_fd)
:m_socketfd(socket_fd)
{
set_timeout(std::chrono::milliseconds(1000));
}
socket_context::~socket_context()
{
stop_context();
close(m_socketfd);
}
void socket_context::set_timeout(std::chrono::milliseconds ms)
{
struct timeval tv;
tv.tv_usec = 1000 * (ms.count() % 1000);
tv.tv_sec = ms.count() / 1000;
/* set timeout for the client operations */
setsockopt(m_socketfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
setsockopt(m_socketfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv));
}
error socket_context::send(void *buffer, size_t& sz)
{
debug() << "[net::ctx::sock] send(" << sz << "): ";
int ret = ::send(m_socketfd, buffer, sz, MSG_NOSIGNAL);
if(ret >= 0)
{
debug() << "good(" << ret << ")\n";
sz = (size_t)ret;
return error::SUCCESS;
}
/* convert some errors */
debug() << "fail(" << errno << "," << strerror(errno) << ")\n";
switch(errno)
{
#if EAGAIN != EWOULDBLOCK
case EAGAIN:
#endif
case EWOULDBLOCK: return error::TIMEOUT;
case ECONNRESET: case EPIPE: return error::SERVER_DISCONNECTED;
default: return error::NET_ERROR;
}
}
error socket_context::recv(void *buffer, size_t& sz)
{
debug() << "[net::ctx::sock] recv(" << sz << "): ";
int ret = ::recv(m_socketfd, buffer, sz, MSG_WAITALL);
if(ret > 0)
{
debug() << "good(" << ret << ")\n";
sz = (size_t)ret;
return error::SUCCESS;
}
if(ret == 0)
{
debug() << "disconnected\n";
return error::SERVER_DISCONNECTED;
}
debug() << "fail(" << errno << "," << strerror(errno) << ")\n";
switch(errno)
{
#if EAGAIN != EWOULDBLOCK
case EAGAIN:
#endif
case EWOULDBLOCK: return error::TIMEOUT;
default: return error::NET_ERROR;
}
}
/**
* Device
*/
device::device(std::shared_ptr<hwstub::context> ctx, uint32_t devid)
:hwstub::device(ctx), m_device_id(devid)
{
}
device::~device()
{
}
uint32_t device::device_id()
{
return m_device_id;
}
error device::open_dev(std::shared_ptr<hwstub::handle>& handle)
{
std::shared_ptr<hwstub::context> hctx = get_context();
if(!hctx)
return error::NO_CONTEXT;
context *ctx = dynamic_cast<context*>(hctx.get());
ctx->debug() << "[net::dev] --> DEV_OPEN(" << m_device_id << ")\n";
/* ask the server to open the device, note that the device ID may not exists
* anymore */
uint32_t args[HWSTUB_NET_ARGS] = {0};
args[0] = m_device_id;
error err = ctx->send_cmd(HWSERVER_DEV_OPEN, args, nullptr, 0, nullptr, nullptr);
if(err != error::SUCCESS)
{
ctx->debug() << "[net::ctx::dev] <-- DEV_OPEN failed: " << error_string(err) << "\n";
return err;
}
ctx->debug() << "[net::ctx::dev] <-- DEV_OPEN: handle = " << args[0] << "\n";
// NOTE: can't use make_shared() because of the protected ctor */
handle.reset(new hwstub::net::handle(shared_from_this(), args[0]));
return error::SUCCESS;
}
bool device::has_multiple_open() const
{
return false;
}
/**
* Handle
*/
handle::handle(std::shared_ptr<hwstub::device> dev, uint32_t hid)
:hwstub::handle(dev), m_handle_id(hid)
{
}
handle::~handle()
{
/* try to close the handle, if context is still accessible */
std::shared_ptr<hwstub::context> hctx = get_device()->get_context();
if(hctx)
{
context *ctx = dynamic_cast<context*>(hctx.get());
ctx->debug() << "[net::handle] --> DEV_CLOSE(" << m_handle_id << ")\n";
uint32_t args[HWSTUB_NET_ARGS] = {0};
args[0] = m_handle_id;
error err = ctx->send_cmd(HWSERVER_DEV_CLOSE, args, nullptr, 0, nullptr, nullptr);
if(err != error::SUCCESS)
ctx->debug() << "[net::handle] <-- DEV_CLOSE failed: " << error_string(err) << "\n";
else
ctx->debug() << "[net::handle] <-- DEV_CLOSE\n";
}
}
error handle::read_dev(uint32_t addr, void *buf, size_t& sz, bool atomic)
{
std::shared_ptr<hwstub::context> hctx = get_device()->get_context();
if(!hctx)
return error::NO_CONTEXT;
context *ctx = dynamic_cast<context*>(hctx.get());
ctx->debug() << "[net::handle] --> READ(" << m_handle_id << ",0x" << std::hex
<< addr << "," << sz << "," << atomic << ")\n";
uint32_t args[HWSTUB_NET_ARGS] = {0};
args[0] = m_handle_id;
args[1] = addr;
args[2] = sz;
args[3] = atomic ? HWSERVER_RW_ATOMIC : 0;
error err = ctx->send_cmd(HWSERVER_READ, args, nullptr, 0, (uint8_t **)&buf, &sz);
if(err != error::SUCCESS)
{
ctx->debug() << "[net::handle] <-- READ failed: " << error_string(err) << "\n";
return err;
}
ctx->debug() << "[net::handle] <-- READ\n";
return error::SUCCESS;
}
error handle::write_dev(uint32_t addr, const void *buf, size_t& sz, bool atomic)
{
std::shared_ptr<hwstub::context> hctx = get_device()->get_context();
if(!hctx)
return error::NO_CONTEXT;
context *ctx = dynamic_cast<context*>(hctx.get());
ctx->debug() << "[net::handle] --> WRITE(" << m_handle_id << ",0x" << std::hex
<< addr << "," << sz << "," << atomic << ")\n";
uint32_t args[HWSTUB_NET_ARGS] = {0};
args[0] = m_handle_id;
args[1] = addr;
args[2] = atomic ? HWSERVER_RW_ATOMIC : 0;
error err = ctx->send_cmd(HWSERVER_WRITE, args, (uint8_t *)buf, sz, nullptr, nullptr);
if(err != error::SUCCESS)
{
ctx->debug() << "[net::handle] <-- WRITE failed: " << error_string(err) << "\n";
return err;
}
ctx->debug() << "[net::handle] <-- WRITE\n";
return error::SUCCESS;
}
error handle::get_dev_desc(uint16_t desc, void *buf, size_t& buf_sz)
{
std::shared_ptr<hwstub::context> hctx = get_device()->get_context();
if(!hctx)
return error::NO_CONTEXT;
context *ctx = dynamic_cast<context*>(hctx.get());
ctx->debug() << "[net::handle] --> GET_DESC(" << m_handle_id << ",0x" << std::hex
<< desc << "," << buf_sz << ")\n";
uint32_t args[HWSTUB_NET_ARGS] = {0};
args[0] = m_handle_id;
args[1] = desc;
args[2] = buf_sz;
error err = ctx->send_cmd(HWSERVER_GET_DESC, args, nullptr, 0, (uint8_t **)&buf, &buf_sz);
if(err != error::SUCCESS)
{
ctx->debug() << "[net::handle] <-- GET_DESC failed: " << error_string(err) << "\n";
return err;
}
ctx->debug() << "[net::handle] <-- GET_DESC\n";
return error::SUCCESS;
}
error handle::get_dev_log(void *buf, size_t& buf_sz)
{
std::shared_ptr<hwstub::context> hctx = get_device()->get_context();
if(!hctx)
return error::NO_CONTEXT;
context *ctx = dynamic_cast<context*>(hctx.get());
ctx->debug() << "[net::handle] --> GET_LOG(" << buf_sz << ")\n";
uint32_t args[HWSTUB_NET_ARGS] = {0};
args[0] = m_handle_id;
args[1] = buf_sz;
error err = ctx->send_cmd(HWSERVER_GET_LOG, args, nullptr, 0, (uint8_t **)&buf, &buf_sz);
if(err != error::SUCCESS)
{
ctx->debug() << "[net::handle] <-- GET_LOG failed: " << error_string(err) << "\n";
return err;
}
ctx->debug() << "[net::handle] <-- GET_LOG\n";
return error::SUCCESS;
}
error handle::exec_dev(uint32_t addr, uint16_t flags)
{
(void) addr;
(void) flags;
return error::DUMMY;
}
error handle::status() const
{
return hwstub::handle::status();
}
size_t handle::get_buffer_size()
{
return 2048;
}
/**
* Server
*/
server::server(std::shared_ptr<hwstub::context> ctx)
:m_context(ctx)
{
clear_debug();
}
server::~server()
{
}
void server::stop_server()
{
std::unique_lock<std::recursive_mutex> lock(m_mutex);
/* ask all client threads to stop */
for(auto& cl : m_client)
cl.exit = true;
/* wait for each thread to stop */
for(auto& cl : m_client)
cl.future.wait();
}
std::shared_ptr<server> server::create_unix(std::shared_ptr<hwstub::context> ctx,
const std::string& path, std::string *error)
{
int fd = create_unix_low(false, path.c_str(), path.size() + 1, false, error);
if(fd >= 0)
return socket_server::create_socket(ctx, fd);
else
return std::shared_ptr<server>();
}
std::shared_ptr<server> server::create_unix_abstract(std::shared_ptr<hwstub::context> ctx,
const std::string& path, std::string *error)
{
std::string fake_path = "#" + path; /* the # will be overriden by 0 */
int fd = create_unix_low(true, fake_path.c_str(), fake_path.size(), false, error);
if(fd >= 0)
return socket_server::create_socket(ctx, fd);
else
return std::shared_ptr<server>();
}
std::shared_ptr<server> server::create_socket(std::shared_ptr<hwstub::context> ctx,
int socket_fd)
{
return socket_server::create(ctx, socket_fd);
}
std::shared_ptr<server> server::create_tcp(std::shared_ptr<hwstub::context> ctx,
const std::string& domain, const std::string& port, std::string *error)
{
int fd = create_tcp_low(domain, port, true, error);
if(fd >= 0)
return socket_server::create_socket(ctx, fd);
else
return std::shared_ptr<server>();
}
void server::set_debug(std::ostream& os)
{
m_debug = &os;
}
std::ostream& server::debug()
{
return *m_debug;
}
server::client_state::client_state(srv_client_t cl, std::future<void>&& f)
:client(cl), future(std::move(f)), exit(false), next_dev_id(42),
next_handle_id(19)
{
}
void server::client_thread2(server *s, client_state *cs)
{
s->client_thread(cs);
}
uint32_t server::to_net_order(uint32_t u)
{
return htonl(u);
}
uint32_t server::from_net_order(uint32_t u)
{
return ntohl(u);
}
void server::client_thread(client_state *state)
{
debug() << "[net::srv::client] start: " << state->client << "\n";
while(!state->exit)
{
/* wait for some header */
struct hwstub_net_hdr_t hdr;
size_t sz = sizeof(hdr);
error err;
/* wait for some command, or exit flag */
do
err = recv(state->client, (void *)&hdr, sz);
while(err == error::TIMEOUT && !state->exit);
if(state->exit || err != error::SUCCESS || sz != sizeof(hdr))
break;
/* convert to host order */
hdr.magic = from_net_order(hdr.magic);
hdr.cmd = from_net_order(hdr.cmd);
hdr.length = from_net_order(hdr.length);
/* copy arguments */
for(size_t i = 0; i < HWSTUB_NET_ARGS; i++)
hdr.args[i] = from_net_order(hdr.args[i]);
/* check header */
if(hdr.magic != HWSERVER_MAGIC)
break;
/* receive data
* FIXME check length here */
uint8_t *data = nullptr;
if(hdr.length > 0)
{
data = new uint8_t[hdr.length];
sz = hdr.length;
/* wait for some command, or exit flag */
do
err = recv(state->client, (void *)data, sz);
while(err == error::TIMEOUT && !state->exit);
if(state->exit || err != error::SUCCESS || sz != hdr.length)
{
delete[] data;
break;
}
}
/* hande command */
uint8_t *send_data = nullptr;
size_t send_size = 0;
err = handle_cmd(state, hdr.cmd, hdr.args, data, hdr.length,
send_data, send_size);
/* free data */
delete[] data;
/* construct header */
if(err != error::SUCCESS)
{
hdr.magic = to_net_order(HWSERVER_MAGIC);
hdr.cmd = to_net_order(HWSERVER_NACK(hdr.cmd));
hdr.length = to_net_order(0);
hdr.args[0] = to_net_order(HWERR_FAIL);
for(size_t i = 1; i < HWSTUB_NET_ARGS; i++)
hdr.args[i] = to_net_order(0);
send_size = 0;
}
else
{
hdr.magic = to_net_order(HWSERVER_MAGIC);
hdr.cmd = to_net_order(HWSERVER_ACK(hdr.cmd));
hdr.length = to_net_order(send_size);
for(size_t i = 0; i < HWSTUB_NET_ARGS; i++)
hdr.args[i] = to_net_order(hdr.args[i]);
}
/* send header */
sz = sizeof(hdr);
do
err = send(state->client, (void *)&hdr, sz);
while(err == error::TIMEOUT && !state->exit);
if(state->exit || err != error::SUCCESS || sz != sizeof(hdr))
{
delete[] send_data;
break;
}
/* send data if there is some */
if(send_size > 0)
{
sz = send_size;
do
err = send(state->client, (void *)send_data, sz);
while(err == error::TIMEOUT && !state->exit);
delete[] send_data;
if(state->exit || err != error::SUCCESS || sz != send_size)
break;
}
}
debug() << "[net::srv::client] stop: " << state->client << "\n";
/* clean client state to avoiding keeping references to objets */
state->dev_map.clear();
state->handle_map.clear();
/* kill client */
terminate_client(state->client);
}
void server::client_arrived(srv_client_t client)
{
std::unique_lock<std::recursive_mutex> lock(m_mutex);
debug() << "[net::srv] client arrived: " << client << "\n";
/* the naive way would be to use a std::thread but this class is annoying
* because it is impossible to check if a thread has exited, except by calling
* join() which is blocking. Fortunately, std::packaged_task and std::future
* provide a way around this */
std::packaged_task<void(server*, client_state*)> task(&server::client_thread2);
m_client.emplace_back(client, task.get_future());
std::thread(std::move(task), this, &m_client.back()).detach();
}
void server::client_left(srv_client_t client)
{
std::unique_lock<std::recursive_mutex> lock(m_mutex);
debug() << "[net::srv] client left: " << client << "\n";
/* find thread and set its exit flag, also cleanup threads that finished */
for(auto it = m_client.begin(); it != m_client.end();)
{
/* check if thread has finished */
if(it->future.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready)
{
it = m_client.erase(it);
continue;
}
/* set exit flag if this our thread */
if(it->client == client)
it->exit = true;
++it;
}
}
error server::handle_cmd(client_state *state, uint32_t cmd, uint32_t args[HWSTUB_NET_ARGS],
uint8_t *recv_data, size_t recv_size, uint8_t*& send_data, size_t& send_size)
{
send_data = nullptr;
send_size = 0;
/* NOTE: commands are serialized by the client thread, this function is thus
* thread safe WITH RESPECT TO CLIENT DATA. If you need to use global data here,
* protect it by a mutex or make sure it is safe (hwstub context is thread-safe) */
/* HELLO */
if(cmd == HWSERVER_HELLO)
{
debug() << "[net::srv::cmd] --> HELLO " << ((args[0] & 0xff00) >> 8)
<< "." << (args[0] & 0xff);
if(args[0] != (HWSTUB_VERSION_MAJOR << 8 | HWSTUB_VERSION_MINOR))
{
debug() << " (mismatch)\n";
return error::ERROR;
}
debug() << " (good)\n";
debug() << "[net::srv::cmd] <-- HELLO " << HWSTUB_VERSION_MAJOR << "."
<< HWSTUB_VERSION_MINOR << "\n";
/* send HELLO with our version */
args[0] = HWSTUB_VERSION_MAJOR << 8 | HWSTUB_VERSION_MINOR;
return error::SUCCESS;
}
/* BYE */
else if(cmd == HWSERVER_BYE)
{
debug() << "[net::srv::cmd] --> BYE\n";
/* ask client thread to exit after this */
state->exit = true;
debug() << "[net::srv::cmd] <-- BYE\n";
return error::SUCCESS;
}
/* GET_DEV_LIST */
else if(cmd == HWSERVER_GET_DEV_LIST)
{
debug() << "[net::srv::cmd] --> GET_DEV_LIST\n";
/* fetch list again */
std::vector<std::shared_ptr<hwstub::device>> list;
error err = m_context->get_device_list(list);
if(err != error::SUCCESS)
{
debug() << "[net::srv::cmd] cannot fetch list: " << hwstub::error_string(err) << "\n";
debug() << "[net::srv::cmd] <-- GET_DEV_LIST (error)\n";
return err;
}
/* update list: drop device that left */
std::vector<uint32_t> to_drop;
for(auto it : state->dev_map)
{
bool still_there = false;
/* this has quadratic complexity, optimize this if needed */
for(auto dev : list)
if(it.second == dev)
still_there = true;
if(!still_there)
to_drop.push_back(it.first);
}
for(auto id : to_drop)
state->dev_map.erase(state->dev_map.find(id));
/* add new devices */
std::vector<std::shared_ptr<hwstub::device>> to_add;
for(auto dev : list)
{
bool already_there = false;
for(auto it : state->dev_map)
if(it.second == dev)
already_there = true;
if(!already_there)
to_add.push_back(dev);
}
for(auto dev : to_add)
state->dev_map[state->next_dev_id++] = dev;
/* create response list */
send_size = sizeof(uint32_t) * state->dev_map.size();
send_data = new uint8_t[send_size];
uint32_t *p = (uint32_t *)send_data;
for(auto it : state->dev_map)
*p++ = to_net_order(it.first);
debug() << "[net::srv::cmd] <-- GET_DEV_LIST\n";
return error::SUCCESS;
}
/* DEV_OPEN */
else if(cmd == HWSERVER_DEV_OPEN)
{
uint32_t devid = args[0];
debug() << "[net::srv::cmd] --> DEV_OPEN(" << devid << ")\n";
/* check ID is valid */
auto it = state->dev_map.find(devid);
if(it == state->dev_map.end())
{
debug() << "[net::srv::cmd] unknwon device ID\n";
debug() << "[net::srv::cmd] <-- DEV_OPEN (error)\n";
return error::ERROR;
}
/* good, now try to get a handle */
std::shared_ptr<hwstub::handle> handle;
error err = it->second->open(handle);
if(err != error::SUCCESS)
{
debug() << "[net::srv::cmd] cannot open device: " << hwstub::error_string(err) << "\n";
return err;
}
/* record ID and return it */
args[0] = state->next_handle_id;
state->handle_map[state->next_handle_id++] = handle;
return error::SUCCESS;
}
/* DEV_CLOSE */
else if(cmd == HWSERVER_DEV_CLOSE)
{
uint32_t hid = args[0];
debug() << "[net::srv::cmd] --> DEV_CLOSE(" << hid << ")\n";
/* check ID is valid */
auto it = state->handle_map.find(hid);
if(it == state->handle_map.end())
{
debug() << "[net::srv::cmd] unknwon handle ID\n";
debug() << "[net::srv::cmd] <-- DEV_CLOSE (error)\n";
return error::ERROR;
}
/* release ID and handle */
state->handle_map.erase(it);
debug() << "[net::srv::cmd] <-- DEV_CLOSE\n";
return error::SUCCESS;
}
/* HWSERVER_GET_DESC */
else if(cmd == HWSERVER_GET_DESC)
{
uint32_t hid = args[0];
uint32_t did = args[1];
uint32_t len = args[2];
debug() << "[net::srv::cmd] --> GET_DESC(" << hid << ",0x" << std::hex << did
<< "," << len << ")\n";
/* check ID is valid */
auto it = state->handle_map.find(hid);
if(it == state->handle_map.end())
{
debug() << "[net::srv::cmd] unknown handle ID\n";
debug() << "[net::srv::cmd] <-- GET_DESC (error)\n";
return error::ERROR;
}
/* query desc */
send_size = len;
send_data = new uint8_t[send_size];
error err = it->second->get_desc(did, send_data, send_size);
if(err != error::SUCCESS)
{
delete[] send_data;
debug() << "[net::srv::cmd] cannot get descriptor: " << error_string(err) << "\n";
debug() << "[net::srv::cmd] <-- GET_DESC (error)\n";
return err;
}
debug() << "[net::srv::cmd] <-- GET_DESC\n";
return error::SUCCESS;
}
/* HWSERVER_GET_LOG */
else if(cmd == HWSERVER_GET_LOG)
{
uint32_t hid = args[0];
uint32_t len = args[1];
debug() << "[net::srv::cmd] --> GET_LOG(" << hid << "," << len << ")\n";
/* check ID is valid */
auto it = state->handle_map.find(hid);
if(it == state->handle_map.end())
{
debug() << "[net::srv::cmd] unknown handle ID\n";
debug() << "[net::srv::cmd] <-- GET_DESC (error)\n";
return error::ERROR;
}
/* query log */
send_size = len;
send_data = new uint8_t[send_size];
error err = it->second->get_log(send_data, send_size);
if(err != error::SUCCESS)
{
delete[] send_data;
debug() << "[net::srv::cmd] cannot get log: " << error_string(err) << "\n";
debug() << "[net::srv::cmd] <-- GET_LOG (error)\n";
return err;
}
if(send_size == 0)
delete[] send_data;
debug() << "[net::srv::cmd] <-- GET_LOG\n";
return error::SUCCESS;
}
/* HWSERVER_READ */
else if(cmd == HWSERVER_READ)
{
uint32_t hid = args[0];
uint32_t addr = args[1];
uint32_t len = args[2];
uint32_t flags = args[3];
debug() << "[net::srv::cmd] --> READ(" << hid << ",0x" << std::hex << addr << ","
<< len << ",0x" << std::hex << flags << ")\n";
/* check ID is valid */
auto it = state->handle_map.find(hid);
if(it == state->handle_map.end())
{
debug() << "[net::srv::cmd] unknown handle ID\n";
debug() << "[net::srv::cmd] <-- READ (error)\n";
return error::ERROR;
}
/* read */
send_size = len;
send_data = new uint8_t[send_size];
error err = it->second->read(addr, send_data, send_size, !!(flags & HWSERVER_RW_ATOMIC));
if(err != error::SUCCESS)
{
delete[] send_data;
debug() << "[net::srv::cmd] cannot read: " << error_string(err) << "\n";
debug() << "[net::srv::cmd] <-- READ (error)\n";
return err;
}
debug() << "[net::srv::cmd] <-- READ\n";
return error::SUCCESS;
}
/* HWSERVER_WRITE */
else if(cmd == HWSERVER_WRITE)
{
uint32_t hid = args[0];
uint32_t addr = args[1];
uint32_t flags = args[2];
debug() << "[net::srv::cmd] --> WRITE(" << hid << ",0x" << std::hex << addr << ","
<< recv_size << ",0x" << std::hex << flags << ")\n";
/* check ID is valid */
auto it = state->handle_map.find(hid);
if(it == state->handle_map.end())
{
debug() << "[net::srv::cmd] unknown handle ID\n";
debug() << "[net::srv::cmd] <-- WRITE (error)\n";
return error::ERROR;
}
/* write */
error err = it->second->write(addr, recv_data, recv_size, !!(flags & HWSERVER_RW_ATOMIC));
if(err != error::SUCCESS)
{
delete[] send_data;
debug() << "[net::srv::cmd] cannot write: " << error_string(err) << "\n";
debug() << "[net::srv::cmd] <-- WRITE (error)\n";
return err;
}
debug() << "[net::srv::cmd] <-- WRITE\n";
return error::SUCCESS;
}
else
{
debug() << "[net::srv::cmd] <-> unknown cmd (0x" << std::hex << cmd << ")\n";
return error::ERROR;
}
}
/*
* Socket server
*/
socket_server::socket_server(std::shared_ptr<hwstub::context> contex, int socket_fd)
:server(contex), m_socketfd(socket_fd)
{
m_discovery_exit = false;
set_timeout(std::chrono::milliseconds(1000));
m_discovery_thread = std::thread(&socket_server::discovery_thread1, this);
}
socket_server::~socket_server()
{
/* first stop discovery thread to make sure no more clients are created */
m_discovery_exit = true;
m_discovery_thread.join();
close(m_socketfd);
/* ask server to do a clean stop */
stop_server();
}
std::shared_ptr<server> socket_server::create(std::shared_ptr<hwstub::context> ctx,
int socket_fd)
{
// NOTE: can't use make_shared() because of the protected ctor */
return std::shared_ptr<socket_server>(new socket_server(ctx, socket_fd));
}
void socket_server::set_timeout(std::chrono::milliseconds ms)
{
m_timeout.tv_usec = 1000 * (ms.count() % 1000);
m_timeout.tv_sec = ms.count() / 1000;
}
int socket_server::from_srv_client(srv_client_t cli)
{
return (int)(intptr_t)cli;
}
socket_server::srv_client_t socket_server::to_srv_client(int fd)
{
return (srv_client_t)(intptr_t)fd;
}
void socket_server::discovery_thread1(socket_server *s)
{
s->discovery_thread();
}
void socket_server::terminate_client(srv_client_t client)
{
debug() << "[net::srv::sock] terminate client: " << client << "\n";
/* simply close connection */
close(from_srv_client(client));
}
error socket_server::send(srv_client_t client, void *buffer, size_t& sz)
{
debug() << "[net::ctx::sock] send(" << client << ", " << sz << "): ";
int ret = ::send(from_srv_client(client), buffer, sz, MSG_NOSIGNAL);
if(ret >= 0)
{
debug() << "good(" << ret << ")\n";
sz = (size_t)ret;
return error::SUCCESS;
}
/* convert some errors */
debug() << "fail(" << errno << "," << strerror(errno) << ")\n";
switch(errno)
{
#if EAGAIN != EWOULDBLOCK
case EAGAIN:
#endif
case EWOULDBLOCK: return error::TIMEOUT;
case ECONNRESET: case EPIPE: return error::SERVER_DISCONNECTED;
default: return error::NET_ERROR;
}
}
error socket_server::recv(srv_client_t client, void *buffer, size_t& sz)
{
debug() << "[net::ctx::sock] recv(" << client << ", " << sz << "): ";
int ret = ::recv(from_srv_client(client), buffer, sz, MSG_WAITALL);
if(ret > 0)
{
debug() << "good(" << ret << ")\n";
sz = (size_t)ret;
return error::SUCCESS;
}
if(ret == 0)
{
debug() << "disconnected\n";
return error::SERVER_DISCONNECTED;
}
debug() << "fail(" << errno << "," << strerror(errno) << ")\n";
switch(errno)
{
#if EAGAIN != EWOULDBLOCK
case EAGAIN:
#endif
case EWOULDBLOCK: return error::TIMEOUT;
default: return error::NET_ERROR;
}
}
void socket_server::discovery_thread()
{
debug() << "[net::srv:sock::discovery] start\n";
/* begin listening to incoming connections */
if(listen(m_socketfd, LISTEN_QUEUE_SIZE) < 0)
{
debug() << "[net::srv::sock::discovery] listen() failed: " << errno << "\n";
return;
}
/* handle connections */
while(!m_discovery_exit)
{
/* since accept() is blocking, use select to ensure a timeout */
struct timeval tmo = m_timeout; /* NOTE select() can overwrite timeout */
fd_set set;
FD_ZERO(&set);
FD_SET(m_socketfd, &set);
/* wait for some activity */
int ret = select(m_socketfd + 1, &set, nullptr, nullptr, &tmo);
if(ret < 0 || !FD_ISSET(m_socketfd, &set))
continue;
int clifd = accept(m_socketfd, nullptr, nullptr);
if(clifd >= 0)
{
debug() << "[net::srv::sock::discovery] new client\n";
/* set timeout for the client operations */
setsockopt(clifd, SOL_SOCKET, SO_RCVTIMEO, (char *)&m_timeout, sizeof(m_timeout));
setsockopt(clifd, SOL_SOCKET, SO_SNDTIMEO, (char *)&m_timeout, sizeof(m_timeout));
client_arrived(to_srv_client(clifd));
}
}
debug() << "[net::srv:sock::discovery] stop\n";
}
} // namespace uri
} // namespace net
| [
"amaury.pouly@gmail.com"
] | amaury.pouly@gmail.com |
093b1fdd68f4bb5b3b75b0d5128256e90c5434c9 | 5b89c1228c8e03acaf754328d66caeeb76881da5 | /progPrinPrac/ch4/drill1.cpp | d01b1286dd206a893a736c4d0018461877d9ac5e | [] | no_license | tjwillia28/bjarne_books | 5693eda732b8e983713d51fa18c4c4889a62488f | 0cfc83343ba1e05cd46d9072c2567f8f8e0064d1 | refs/heads/master | 2020-06-24T12:00:22.157865 | 2019-07-26T06:26:54 | 2019-07-26T06:26:54 | 198,957,965 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 411 | cpp | //
// Created by Tyler Williams on 2019-07-24.
//
#include <iostream>
using namespace std;
int main(){
int temp1 = 0;
int temp2 = 0;
cout << "Enter 2 integers\n";
while(cin >> temp1 >> temp2){
cout << "You entered integers: " << temp1 << "\t" << temp2 << "\n" << "Enter 2 more...\n";
}
cout << "You did not enter two integers! program ending... " << "\n";
return 0;
}
| [
"tjwillia28@gmail.com"
] | tjwillia28@gmail.com |
273836961be7c12d5ed0f3692d4e28bc2f335b41 | b289d4a155263136d71ab4f9a6f710fe5324e5d8 | /Server/shared/database/ItemExchangeSet.h | 6f3d916a21efde65d228cbdd49346c9993e7d7c2 | [
"MIT"
] | permissive | iKlotho/KnightOnline | 1f63f588cb532de89a824407da6dc53f3a38c663 | bd3502e1e826a1b9007629fcb3c07c4f6370eba4 | refs/heads/master | 2022-10-16T21:26:10.842056 | 2020-06-13T11:56:04 | 2020-06-13T11:56:04 | 271,982,708 | 0 | 0 | MIT | 2020-06-13T09:57:25 | 2020-06-13T09:57:25 | null | UTF-8 | C++ | false | false | 1,701 | h | #pragma once
class CItemExchangeSet : public OdbcRecordset
{
public:
CItemExchangeSet(OdbcConnection * dbConnection, ItemExchangeArray *pMap)
: OdbcRecordset(dbConnection), m_pMap(pMap) {}
virtual tstring GetTableName() { return _T("ITEM_EXCHANGE"); }
virtual tstring GetColumns()
{
return _T("nIndex, nNpcNum, bRandomFlag, "
"nOriginItemNum1, nOriginItemCount1, nOriginItemNum2, nOriginItemCount2, "
"nOriginItemNum3, nOriginItemCount3, nOriginItemNum4, nOriginItemCount4, "
"nOriginItemNum5, nOriginItemCount5, " //nOriginItemNum6, nOriginItemCount6, "
//"nOriginItemNum7, nOriginItemCount7, nOriginItemNum8, nOriginItemCount8, "
//"nOriginItemNum9, nOriginItemCount9, nOriginItemNum10, nOriginItemCount10, nOriginItemNum11, nOriginItemCount11, "
"nExchangeItemNum1, nExchangeItemCount1, nExchangeItemNum2, nExchangeItemCount2, nExchangeItemNum3, nExchangeItemCount3, "
"nExchangeItemNum4, nExchangeItemCount4, nExchangeItemNum5, nExchangeItemCount5");
}
virtual bool Fetch()
{
_ITEM_EXCHANGE *pData = new _ITEM_EXCHANGE;
int i = 1;
_dbCommand->FetchUInt32(i++, pData->nIndex);
_dbCommand->FetchUInt16(i++, pData->sNpcNum);
_dbCommand->FetchByte(i++, pData->bRandomFlag);
for (int x = 0; x < ITEMS_IN_ORIGIN_GROUP; x++)
{
_dbCommand->FetchUInt32(i++, pData->nOriginItemNum[x]);
_dbCommand->FetchUInt32(i++, pData->sOriginItemCount[x]);
}
for (int j = 0; j < ITEMS_IN_EXCHANGE_GROUP; j++)
{
_dbCommand->FetchUInt32(i++, pData->nExchangeItemNum[j]);
_dbCommand->FetchUInt32(i++, pData->sExchangeItemCount[j]);
}
if (!m_pMap->PutData(pData->nIndex, pData))
delete pData;
return true;
}
ItemExchangeArray * m_pMap;
}; | [
"info@stephenmeier.net"
] | info@stephenmeier.net |
1627150cc0626fdb017ebec1b4b9b92115183d84 | 6f224b734744e38062a100c42d737b433292fb47 | /clang/test/OpenMP/masked_taskloop_simd_aligned_messages.cpp | 8c0ae171fa401bd5fa1697775f36d02f0c647add | [
"NCSA",
"LLVM-exception",
"Apache-2.0"
] | permissive | smeenai/llvm-project | 1af036024dcc175c29c9bd2901358ad9b0e6610e | 764287f1ad69469cc264bb094e8fcdcfdd0fcdfb | refs/heads/main | 2023-09-01T04:26:38.516584 | 2023-08-29T21:11:41 | 2023-08-31T22:16:12 | 216,062,316 | 0 | 0 | Apache-2.0 | 2019-10-18T16:12:03 | 2019-10-18T16:12:03 | null | UTF-8 | C++ | false | false | 9,047 | cpp | // RUN: %clang_cc1 -x c++ -std=c++11 -verify -fopenmp %s -Wuninitialized
// RUN: %clang_cc1 -x c++ -std=c++11 -verify -fopenmp-simd %s -Wuninitialized
struct B {
static int ib[20]; // expected-note 0 {{'B::ib' declared here}}
static constexpr int bfoo() { return 8; }
};
namespace X {
B x; // expected-note {{'x' defined here}}
};
constexpr int bfoo() { return 4; }
int **z;
const int C1 = 1;
const int C2 = 2;
void test_aligned_colons(int *&rp)
{
int *B = 0;
#pragma omp masked taskloop simd aligned(B:bfoo())
for (int i = 0; i < 10; ++i) ;
// expected-error@+1 {{unexpected ':' in nested name specifier; did you mean '::'}}
#pragma omp masked taskloop simd aligned(B::ib:B:bfoo())
for (int i = 0; i < 10; ++i) ;
#pragma omp masked taskloop simd aligned(B:B::bfoo())
for (int i = 0; i < 10; ++i) ;
// expected-error@+1 {{unexpected ':' in nested name specifier; did you mean '::'?}}
#pragma omp masked taskloop simd aligned(z:B:bfoo())
for (int i = 0; i < 10; ++i) ;
#pragma omp masked taskloop simd aligned(B:B::bfoo())
for (int i = 0; i < 10; ++i) ;
// expected-error@+2 {{integral constant expression must have integral or unscoped enumeration type, not 'int **'}}
// expected-error@+1 {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'B'}}
#pragma omp masked taskloop simd aligned(X::x : ::z)
for (int i = 0; i < 10; ++i) ;
// expected-error@+1 {{integral constant expression must have integral or unscoped enumeration type, not 'B'}}
#pragma omp masked taskloop simd aligned(B,rp,::z: X::x)
for (int i = 0; i < 10; ++i) ;
#pragma omp masked taskloop simd aligned(::z)
for (int i = 0; i < 10; ++i) ;
// expected-error@+1 {{expected variable name}}
#pragma omp masked taskloop simd aligned(B::bfoo())
for (int i = 0; i < 10; ++i) ;
// expected-warning@+1 {{aligned clause will be ignored because the requested alignment is not a power of 2}}
#pragma omp masked taskloop simd aligned(B::ib,B:C1+C2)
for (int i = 0; i < 10; ++i) ;
}
// expected-note@+1 {{'num' defined here}}
template<int L, class T, class N> T test_template(T* arr, N num) {
N i;
T sum = (T)0;
T ind2 = - num * L;
// Negative number is passed as L.
// expected-error@+1 {{argument to 'aligned' clause must be a strictly positive integer value}}
#pragma omp masked taskloop simd aligned(arr:L)
for (i = 0; i < num; ++i) {
T cur = arr[(int)ind2];
ind2 += L;
sum += cur;
}
// expected-error@+1 {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'int'}}
#pragma omp masked taskloop simd aligned(num:4)
for (i = 0; i < num; ++i);
return T();
}
template<int LEN> int test_warn() {
int *ind2 = 0;
// expected-error@+1 {{argument to 'aligned' clause must be a strictly positive integer value}}
#pragma omp masked taskloop simd aligned(ind2:LEN)
for (int i = 0; i < 100; i++) {
ind2 += LEN;
}
return 0;
}
struct S1; // expected-note 2 {{declared here}}
extern S1 a; // expected-note {{'a' declared here}}
class S2 {
mutable int a;
public:
S2():a(0) { }
};
const S2 b; // expected-note 1 {{'b' defined here}}
const S2 ba[5];
class S3 {
int a;
public:
S3():a(0) { }
};
const S3 ca[5];
class S4 {
int a;
S4();
public:
S4(int v):a(v) { }
};
class S5 {
int a;
S5():a(0) {}
public:
S5(int v):a(v) { }
};
S3 h; // expected-note 2 {{'h' defined here}}
#pragma omp threadprivate(h)
template<class I, class C> int foomain(I argc, C **argv) {
I e(argc);
I g(argc);
int i; // expected-note {{'i' defined here}}
// expected-note@+1 {{declared here}}
int &j = i;
#pragma omp masked taskloop simd aligned // expected-error {{expected '(' after 'aligned'}}
for (I k = 0; k < argc; ++k) ++k;
#pragma omp masked taskloop simd aligned ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (I k = 0; k < argc; ++k) ++k;
#pragma omp masked taskloop simd aligned () // expected-error {{expected expression}}
for (I k = 0; k < argc; ++k) ++k;
#pragma omp masked taskloop simd aligned (argc // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (I k = 0; k < argc; ++k) ++k;
#pragma omp masked taskloop simd aligned (argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (I k = 0; k < argc; ++k) ++k;
// FIXME: Should argc really be a pointer?
#pragma omp masked taskloop simd aligned (*argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}}
for (I k = 0; k < argc; ++k) ++k;
#pragma omp masked taskloop simd aligned (argc : 5) // expected-warning {{aligned clause will be ignored because the requested alignment is not a power of 2}}
for (I k = 0; k < argc; ++k) ++k;
#pragma omp masked taskloop simd aligned (S1) // expected-error {{'S1' does not refer to a value}}
for (I k = 0; k < argc; ++k) ++k;
#pragma omp masked taskloop simd aligned (argv[1]) // expected-error {{expected variable name}}
for (I k = 0; k < argc; ++k) ++k;
#pragma omp masked taskloop simd aligned(e, g)
for (I k = 0; k < argc; ++k) ++k;
// expected-error@+1 {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'S3'}}
#pragma omp masked taskloop simd aligned(h)
for (I k = 0; k < argc; ++k) ++k;
// expected-error@+1 {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'int'}}
#pragma omp masked taskloop simd aligned(i)
for (I k = 0; k < argc; ++k) ++k;
#pragma omp parallel
{
int *v = 0;
I i;
#pragma omp masked taskloop simd aligned(v:16)
for (I k = 0; k < argc; ++k) { i = k; v += 2; }
}
float *f;
#pragma omp masked taskloop simd aligned(f)
for (I k = 0; k < argc; ++k) ++k;
int v = 0;
// expected-note@+2 {{initializer of 'j' is not a constant expression}}
// expected-error@+1 {{integral constant expression}}
#pragma omp masked taskloop simd aligned(f:j)
for (I k = 0; k < argc; ++k) { ++k; v += j; }
#pragma omp masked taskloop simd aligned(f)
for (I k = 0; k < argc; ++k) ++k;
return 0;
}
// expected-note@+1 2 {{'argc' defined here}}
int main(int argc, char **argv) {
double darr[100];
// expected-note@+1 {{in instantiation of function template specialization 'test_template<-4, double, int>' requested here}}
test_template<-4>(darr, 4);
test_warn<4>(); // ok
// expected-note@+1 {{in instantiation of function template specialization 'test_warn<0>' requested here}}
test_warn<0>();
int i;
int &j = i;
int tid = 0;
#pragma omp masked taskloop simd aligned filter(tid) // expected-error {{expected '(' after 'aligned'}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp masked taskloop simd aligned ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp masked taskloop simd aligned () // expected-error {{expected expression}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp masked taskloop simd aligned (argv // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
// expected-error@+1 {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'int'}}
#pragma omp masked taskloop simd aligned (argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp masked taskloop simd aligned (argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}}
for (int k = 0; k < argc; ++k) ++k;
// expected-error@+1 {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'int'}}
#pragma omp masked taskloop simd aligned (argc)
for (int k = 0; k < argc; ++k) ++k;
#pragma omp masked taskloop simd aligned (S1) // expected-error {{'S1' does not refer to a value}}
for (int k = 0; k < argc; ++k) ++k;
// expected-error@+2 {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'S1'}}
// expected-error@+1 {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'S2'}}
#pragma omp masked taskloop simd aligned(a, b)
for (int k = 0; k < argc; ++k) ++k;
#pragma omp masked taskloop simd aligned (argv[1]) // expected-error {{expected variable name}}
for (int k = 0; k < argc; ++k) ++k;
// expected-error@+1 {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'S3'}}
#pragma omp masked taskloop simd aligned(h)
for (int k = 0; k < argc; ++k) ++k;
int *pargc = &argc;
// expected-note@+1 {{in instantiation of function template specialization 'foomain<int *, char>' requested here}}
foomain<int*,char>(pargc,argv);
return 0;
}
| [
"michael.p.rice@intel.com"
] | michael.p.rice@intel.com |
896e377155423842cd35eb746f2dd24d0c928c4c | 67e8364603f885231b6057abd6859e60562a4008 | /Cpp/358_RearrangeStringKDistanceApart/002.cpp | 802ab9c21055e64c77abb291209ca6752981c1cc | [] | no_license | NeighborUncleWang/Leetcode | 988417721c4a395ac8800cd04e4d5d973b54e9d4 | d5bdbdcd698006c9997ef0e368ffaae6f546ac44 | refs/heads/master | 2021-01-18T22:03:27.400480 | 2019-02-22T04:45:52 | 2019-02-22T04:45:52 | 36,253,135 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,166 | cpp | class Solution {
public:
string rearrangeString(string str, int k) {
if (k == 0) return str;
unordered_map<char, int> map;
for (char ch : str) {
map[ch]++;
}
//pq必须是最大堆,必须让count最大的char最先被插入结果中
//否则"abb",2这个case过不去
priority_queue<pair<int, char>> pq;
for (auto it : map) {
pq.emplace(it.second, it.first);
}
vector<pair<int, char>> temp;
string result;
int length = str.size();
while (!pq.empty()) {
int size = min(length, k);
for (int i = 0; i < size; ++i) {
if (pq.empty()) return "";
result.push_back(pq.top().second);
auto top = pq.top();
pq.pop();
if(--top.first > 0) {
temp.push_back(move(top));
}
--length;
}
//这里结束之后不用把pq清空
for (auto it : temp) {
pq.push(it);
}
temp.clear();
}
return result;
}
}; | [
"lixianshu1992@gmail.com"
] | lixianshu1992@gmail.com |
739996ffc8cdbaebcb76757bcf15a4866867eca7 | 0a808e29270c3d707999a5efcb92eba5976560e9 | /tests/src/mocks/AssignmentProxyTestClass.hpp | b0ef73a22fdd2bbed743d83efee3402f012d12de | [
"BSL-1.0"
] | permissive | daball/props | ff1b97d26128bcb63b071af835aef8a37cfac76b | 6d416984c14bef68bd39e323e029f8879e9cf45f | refs/heads/master | 2020-12-22T05:54:31.826850 | 2020-02-08T07:35:30 | 2020-02-08T07:35:30 | 236,688,141 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 731 | hpp | #pragma once
#include <cstddef>
#include <optional>
#include <daball/props/behaviors/base/AssignmentProxy.hpp>
using daball::props::behaviors::base::AssignmentProxy;
namespace daball::props::tests {
template<typename T>
class AssignmentProxyTestClass:
public AssignmentProxy<T> {
public:
AssignmentProxyTestClass():
AssignmentProxy<T>()
{}
AssignmentProxyTestClass(::std::nullptr_t):
AssignmentProxy<T>(nullptr)
{}
AssignmentProxyTestClass(::std::nullopt_t):
AssignmentProxy<T>(::std::nullopt)
{}
AssignmentProxyTestClass(T &reference):
AssignmentProxy<T>(reference)
{}
};
}
| [
"david@daball.me"
] | david@daball.me |
a15117be2fef3e1ff909bd7a034e8ce2c801b3f2 | 84d577901dbf12c2c1cc7aad94ab566655578c42 | /crne/main.cpp | 7c997f277044d5e9ad679cc7fec14e2df69e880c | [] | no_license | bengorman/Kattis-Problems | 9ea236ed6c17a47f20d4dc8052bfb468d93cdf21 | 71d14d15f3a4f5d78d2944f68a65eddaac00b917 | refs/heads/master | 2020-03-22T05:51:38.283057 | 2018-09-12T01:06:08 | 2018-09-12T01:06:08 | 139,595,031 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 438 | cpp | //
// main.cpp
// crne
//
// Created by Ben Gorman on 8/6/18.
// Copyright © 2018 Ben Gorman. All rights reserved.
//
#include <iostream>
using namespace std;
int main() {
unsigned long long n;
cin >> n;
unsigned long long pieces = 1;
int adder = 1;
for(int i = 0; i < n; i++) {
pieces += adder;
if(i % 2 == 0) {
adder++;
}
}
cout << pieces << endl;
return 0;
}
| [
"bgorman@accusoft.com"
] | bgorman@accusoft.com |
780fecc7b08c8783272a58342b7c0411626fbf75 | e68c1f9134b44ddea144f7efa7523076f3f12d3a | /FinalCode/Wizard_Female_1HS_Orb_Directed.cpp | a0e44592b87e136a71ef1c65a5ce5930ad7daf8e | [] | no_license | iso5930/Direct-3D-Team-Portfolio | 4ac710ede0c9176702595cba5579af42887611cf | 84e64eb4e91c7e5b4aed77212cd08cfee038fcd3 | refs/heads/master | 2021-08-23T08:15:00.128591 | 2017-12-04T06:14:39 | 2017-12-04T06:14:39 | 112,998,717 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 648 | cpp | #include "StdAfx.h"
#include "Wizard_Female_1HS_Orb_Directed.h"
CWizard_Female_1HS_Orb_Directed::CWizard_Female_1HS_Orb_Directed(void)
{
m_eStateType = STATE_TYPE_WIZARD_FEMALE_1HS_ORB_DIRECTED;
}
CWizard_Female_1HS_Orb_Directed::~CWizard_Female_1HS_Orb_Directed(void)
{
}
void CWizard_Female_1HS_Orb_Directed::Initialize()
{
CPlayerState::Initialize();
// SetAnimation
m_pOwner->SetAnimation(11);
// Clear
m_pPathFindCom->Clear();
}
CPlayerState* CWizard_Female_1HS_Orb_Directed::Action()
{
if(m_pAnimController->m_dFrameTime - 0.25 <= m_pAnimController->GetTrackPos())
{
return new CWizard_Female_1HS_Orb_Idle;
}
return NULL;
} | [
"iso5930@naver.com"
] | iso5930@naver.com |
828281213fa4db083e00cd8290c6522e2b683a31 | 8b481519bd46f07055baf33dc290086f37b47fe6 | /leetcode/0206 反转链表 - iterative.cpp | 73f38ab250ab943f581008be04633054173f8b9c | [] | no_license | Hansimov/cs-notes | 1e0717abce9788a25636a3649664de4ba4537f90 | baab60752bafa7964cf63e3051e595c7f28bd415 | refs/heads/master | 2023-04-11T14:06:28.184490 | 2021-03-26T16:28:29 | 2021-03-26T16:28:29 | 167,122,370 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 519 | cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head==NULL) return NULL;
ListNode* pre = NULL;
ListNode* cur = head;
ListNode* tmp;
while (cur) {
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}; | [
"591172499@qq.com"
] | 591172499@qq.com |
8fe70387e7137cfc9e6deaa2d3fe7a8ab6969ab4 | 2ad789090db7a377f746413e397b603c76f547fa | /V-REP_PRO_EDU_V3_6_0_Ubuntu16_04/programming/bluezero/include/spotify-json/test/src/test_string.cpp | 63b55e8d2715bd266bf6051a1d9308a113af1739 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"JSON",
"BSD-3-Clause"
] | permissive | JasonLeeUT/Robotics | 442b8217918a32b3e8df454b9890ab83280ee7f3 | 7e21e5d18b42cfcaafd01b0243f221a051692f11 | refs/heads/master | 2023-01-23T00:14:41.801025 | 2020-11-19T02:23:55 | 2020-11-19T02:23:55 | 314,112,186 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,205 | cpp | /*
* Copyright (c) 2015-2016 Spotify AB
*
* 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 <string>
#include <boost/test/unit_test.hpp>
#include <spotify/json/codec/map.hpp>
#include <spotify/json/codec/boolean.hpp>
#include <spotify/json/decode.hpp>
#include <spotify/json/decode_exception.hpp>
#include <spotify/json/encode.hpp>
BOOST_AUTO_TEST_SUITE(spotify)
BOOST_AUTO_TEST_SUITE(json)
BOOST_AUTO_TEST_SUITE(codec)
namespace {
std::string string_parse(const char *string) {
const auto codec = default_codec<std::string>();
auto ctx = decode_context(string, string + strlen(string));
const auto result = codec.decode(ctx);
BOOST_CHECK_EQUAL(ctx.position, ctx.end);
return result;
}
void string_parse_fail(const char *string) {
auto ctx = decode_context(string, string + strlen(string));
BOOST_CHECK_THROW(default_codec<std::string>().decode(ctx), decode_exception);
}
std::string random_simple_character(size_t i) {
char c;
switch (i % 3) {
case 0: c = '0' + (i % 10); break;
case 1: c = 'a' + (i % ('z' - 'a')); break;
case 2: c = 'A' + (i % ('Z' - 'A')); break;
}
return std::string(&c, 1);
}
std::string random_simple_character_or_escape_sequence(size_t i, bool minimal_escaping) {
switch (i % 37) {
case 27: return "\\u0000";
case 28: return "\\\"";
case 29: return minimal_escaping ? "/" : "\\/";
case 30: return "\\b";
case 31: return "\\f";
case 32: return "\\n";
case 33: return "\\r";
case 34: return "\\t";
case 35: return "\\\\";
case 36: return minimal_escaping ? "\xE2\x82\xAC" : "\\u20AC";
default: return random_simple_character(i);
}
}
std::string random_simple_character_or_unescaped_character(size_t i) {
// Note: since one case below returns 3 bytes and all the other return 1, the
// total number of bytes in one rotation is 39. This number is coprime with
// 16, which is the number of bytes in an SSE block, so this will ensure that
// each byte will end up first in a 16-byte SSE block eventually.
switch (i % 37) {
case 27: return std::string(1, '\0');
case 28: return "\"";
case 29: return "/";
case 30: return "\b";
case 31: return "\f";
case 32: return "\n";
case 33: return "\r";
case 34: return "\t";
case 35: return "\\";
case 36: return "\xE2\x82\xAC";
default: return random_simple_character(i);
}
}
std::string generate_simple_string(size_t size) {
std::string string("\"");
for (size_t i = 0; i < size; i++) {
string.append(random_simple_character(i));
}
string.append("\"");
return string;
}
std::string generate_simple_string_answer(size_t size) {
std::string string;
for (size_t i = 0; i < size; i++) {
string.append(random_simple_character(i));
}
return string;
}
std::string generate_escaped_string(size_t approximate_size, bool minimal_escaping = false) {
std::string string("\"");
for (size_t i = 0; i < approximate_size; i++) {
string.append(random_simple_character_or_escape_sequence(i, minimal_escaping));
}
string.append("\"");
return string;
}
std::string generate_escaped_string_answer(size_t approximate_size) {
std::string string;
for (size_t i = 0; i < approximate_size; i++) {
string.append(random_simple_character_or_unescaped_character(i));
}
return string;
}
std::string generate_utf8_string_answer(size_t size) {
std::string string;
for (size_t i = 0; i < size; i++) {
string.append("\xE2\x98\x83");
}
return string;
}
std::string generate_utf8_string(size_t size) {
std::string string("\"");
for (size_t i = 0; i < size; i++) {
string.append("\xE2\x98\x83");
}
string.append("\"");
return string;
}
} // namespace
/*
* Constructing
*/
BOOST_AUTO_TEST_CASE(json_codec_string_should_construct_with_helper) {
string();
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_construct_with_default_codec) {
default_codec<std::string>();
}
/*
* Decoding Simple Strings
*/
BOOST_AUTO_TEST_CASE(json_codec_string_should_decode_empty) {
BOOST_CHECK_EQUAL(string_parse("\"\""), "");
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_decode_single_letter) {
BOOST_CHECK_EQUAL(string_parse("\"a\""), "a");
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_decode_letters) {
BOOST_CHECK_EQUAL(string_parse("\"abc\""), "abc");
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_decode_long_string) {
const auto string = generate_simple_string(10027);
const auto answer = string.substr(1, string.size() - 2);
BOOST_CHECK_EQUAL(string_parse(string.c_str()), answer);
}
/*
* Decoding Invalid Strings
*/
BOOST_AUTO_TEST_CASE(json_codec_string_should_not_decode_invalid) {
string_parse_fail("");
string_parse_fail("\"");
}
/*
* Decoding Escaped Strings
*/
BOOST_AUTO_TEST_CASE(json_codec_string_should_decode_escaped_characters) {
BOOST_CHECK_EQUAL(string_parse("\"\\\"\""), "\"");
BOOST_CHECK_EQUAL(string_parse("\"\\/\""), "/");
BOOST_CHECK_EQUAL(string_parse("\"\\b\""), "\b");
BOOST_CHECK_EQUAL(string_parse("\"\\f\""), "\f");
BOOST_CHECK_EQUAL(string_parse("\"\\n\""), "\n");
BOOST_CHECK_EQUAL(string_parse("\"\\r\""), "\r");
BOOST_CHECK_EQUAL(string_parse("\"\\t\""), "\t");
BOOST_CHECK_EQUAL(string_parse("\"\\\\\""), "\\");
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_decode_escaped_string_with_unescaped_parts) {
BOOST_CHECK_EQUAL(string_parse("\"prefix\\nmiddle\\nsuffix\""), "prefix\nmiddle\nsuffix");
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_decode_escaped_unicode) {
// Examples from http://en.wikipedia.org/wiki/UTF-8#Examples
BOOST_CHECK_EQUAL(string_parse("\"\\u0024\""), "\x24");
BOOST_CHECK_EQUAL(string_parse("\"\\u00A2\""), "\xC2\xA2");
BOOST_CHECK_EQUAL(string_parse("\"\\u20AC\""), "\xE2\x82\xAC");
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_decode_surrogate_pairs) {
// [TWO HEARTS] Emoji (code point 0x1F495)
const std::string two_hearts = "\xf0\x9f\x92\x95";
BOOST_CHECK_EQUAL(string_parse("\"I \\ud83d\\udc95 Unicode\""),
"I " + two_hearts + " Unicode");
BOOST_CHECK_EQUAL(string_parse("\"I\\n\\ud83d\\udc95\\nUnicode\""),
"I\n" + two_hearts + "\nUnicode");
// Extreme values of each surrogate
BOOST_CHECK_EQUAL(string_parse("\"\\ud800\\udc00\""), "\xf0\x90\x80\x80");
BOOST_CHECK_EQUAL(string_parse("\"\\ud800\\udfff\""), "\xf0\x90\x8f\xbf");
BOOST_CHECK_EQUAL(string_parse("\"\\udbff\\udc00\""), "\xf4\x8f\xb0\x80");
BOOST_CHECK_EQUAL(string_parse("\"\\udbff\\udfff\""), "\xf4\x8f\xbf\xbf");
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_output_code_points_from_broken_surrogate_pairs) {
// [TWO HEARTS] Emoji (code point 0x1F495)
const std::string two_hearts = "\xf0\x9f\x92\x95";
// UTF-8 representations of code points 0xd83d and 0xdc95, which form the
// surrogate pairs for the emoji above.
const std::string high = "\xed\xa0\xbd";
const std::string low = "\xed\xb2\x95";
// Lone high surrogate
BOOST_CHECK_EQUAL(string_parse("\"\\ud83d\""), high);
BOOST_CHECK_EQUAL(string_parse("\"\\n\\ud83d\\n\""), "\n" + high + "\n");
BOOST_CHECK_EQUAL(string_parse("\"\\\\\\ud83d\\\\\""), "\\" + high + "\\");
BOOST_CHECK_EQUAL(string_parse("\"Foo\\ud83dFoo\""), "Foo" + high + "Foo");
BOOST_CHECK_EQUAL(string_parse("\"\\ud83d\\ud83d\\udc95\""), high + two_hearts);
// Lone low surrogate
BOOST_CHECK_EQUAL(string_parse("\"\\udc95\""), low);
BOOST_CHECK_EQUAL(string_parse("\"\\n\\udc95\\n\""), "\n" + low + "\n");
BOOST_CHECK_EQUAL(string_parse("\"\\\\\\udc95\\\\\""), "\\" + low + "\\");
BOOST_CHECK_EQUAL(string_parse("\"Foo\\udc95Foo\""), "Foo" + low + "Foo");
BOOST_CHECK_EQUAL(string_parse("\"\\udc95\\ud83d\\udc95\""), low + two_hearts);
// Flipped order surrogates
BOOST_CHECK_EQUAL(string_parse("\"\\udc95\\ud83d\""), low + high);
// Double high surrogate
BOOST_CHECK_EQUAL(string_parse("\"\\ud83d\\ud83d\""), high + high);
// Double low surrogate
BOOST_CHECK_EQUAL(string_parse("\"\\udc95\\udc95\""), low + low);
// Intermingled valid and invalid sequences
BOOST_CHECK_EQUAL(string_parse("\"\\ud83d\\udc95\\udc95\""), two_hearts + low);
BOOST_CHECK_EQUAL(string_parse("\"\\ud83d\\udc95\\ud83d\""), two_hearts + high);
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_not_decode_incomplete_low_surrogate) {
string_parse_fail("\"\\ud83d\\\"");
string_parse_fail("\"\\ud83d\\u\"");
string_parse_fail("\"\\ud83d\\udc9\"");
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_not_decode_invalid_escaped_characters) {
string_parse_fail("\"\\q\""); // \q is not a valid escape sequence
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_not_decode_invalid_unicode_escape_sequences) {
string_parse_fail("\"\\u0\"");
string_parse_fail("\"\\u01\"");
string_parse_fail("\"\\u012\"");
string_parse_fail("\"\\u_FFF\"");
string_parse_fail("\"\\uF_FF\"");
string_parse_fail("\"\\uFF_F\"");
string_parse_fail("\"\\uFFF_\"");
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_decode_long_escaped_string) {
const auto string = generate_escaped_string(10027);
const auto answer = generate_escaped_string_answer(10027);
BOOST_CHECK_EQUAL(string_parse(string.c_str()), answer);
}
/*
* Encoding Simple Strings
*/
BOOST_AUTO_TEST_CASE(json_codec_string_should_encode_empty) {
BOOST_CHECK_EQUAL(encode(std::string()), "\"\"");
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_encode_single_character) {
BOOST_CHECK_EQUAL(encode(std::string("a")), "\"a\"");
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_encode_long_string) {
const auto string = generate_simple_string_answer(10027);
const auto answer = generate_simple_string(10027);
BOOST_CHECK_EQUAL(encode(string), answer);
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_encode_long_utf8_string) {
const auto string = generate_utf8_string_answer(10027);
const auto answer = generate_utf8_string(10027);
BOOST_CHECK_EQUAL(encode(string), answer);
}
/*
* Encoding Escaped Strings
*/
BOOST_AUTO_TEST_CASE(json_codec_string_should_encode_escaped_character) {
BOOST_CHECK_EQUAL(encode(std::string("\"")), "\"\\\"\"");
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_encode_popular_escaped_characters) {
const auto string = "\b\t\n\f\r";
const auto answer = "\"\\b\\t\\n\\f\\r\"";
BOOST_CHECK_EQUAL(encode(std::string(string)), answer);
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_encode_escaped_control_characters) {
BOOST_CHECK_EQUAL(encode(std::string("\x01\x02")), "\"\\u0001\\u0002\"");
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_encode_null_char) {
// Enough zero bytes to get a full 16-byte SSE block, regardless of what
// memory aligment the string data happens to get.
const std::string input_data(31, '\0');
std::string expected_result = "\"";
for (std::size_t i = 0; i < input_data.size(); i++) {
expected_result += "\\u0000";
}
expected_result += "\"";
BOOST_CHECK_EQUAL(encode(input_data), expected_result);
}
BOOST_AUTO_TEST_CASE(json_codec_string_should_encode_long_string_with_special_chars) {
const auto input_str = generate_escaped_string_answer(10000);
const auto expected_result = generate_escaped_string(10000, true);
BOOST_CHECK(encode(input_str) == expected_result);
}
BOOST_AUTO_TEST_SUITE_END() // codec
BOOST_AUTO_TEST_SUITE_END() // json
BOOST_AUTO_TEST_SUITE_END() // spotify
| [
"18811526516@163.com"
] | 18811526516@163.com |
710645d5a8378347c9b56b1dbc8a41d8fc3aac41 | e99c20155e9b08c7e7598a3f85ccaedbd127f632 | / sjtu-project-pipe/thirdparties/VTK.Net/src/Imaging/vtkImageGradientDotNet.h | f7202034d8fee03ed9c700eb5722a57eb512ff8e | [
"BSD-3-Clause"
] | permissive | unidevop/sjtu-project-pipe | 38f00462d501d9b1134ce736bdfbfe4f9d075e4a | 5a09f098db834d5276a2921d861ef549961decbe | refs/heads/master | 2020-05-16T21:32:47.772410 | 2012-03-19T01:24:14 | 2012-03-19T01:24:14 | 38,281,086 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,343 | h | #pragma once
// managed includes
// native includes
using namespace System;
namespace vtk {
public ref class vtkImageGradient : public vtkThreadedImageAlgorithm
{
public:
// Did not wrap: static vtkImageGradient *New ();
// const char *GetClassName ();
System::String^ GetClassName();
// int IsA (const char *name);
int IsA(System::String^ name);
// vtkImageGradient *NewInstance ();
vtkImageGradient^ NewInstance();
// vtkImageGradient *SafeDownCast (vtkObject* o);
static vtkImageGradient^ SafeDownCast(vtkObject^ o);
void PrintSelf(System::IO::TextWriter^ writer, int indentLevel);
virtual System::String^ ToString() override;
// void SetDimensionality (int );
/// <summary>
/// <para>Determines how the input is interpreted (set of 2d slices ...)</para>
/// </summary>
void SetDimensionality(int arg0);
// int GetDimensionalityMinValue ();
/// <summary>
/// <para>Determines how the input is interpreted (set of 2d slices ...)</para>
/// </summary>
int GetDimensionalityMinValue();
// int GetDimensionalityMaxValue ();
/// <summary>
/// <para>Determines how the input is interpreted (set of 2d slices ...)</para>
/// </summary>
int GetDimensionalityMaxValue();
// int GetDimensionality ();
/// <summary>
/// <para>Determines how the input is interpreted (set of 2d slices ...)</para>
/// </summary>
int GetDimensionality();
// void SetHandleBoundaries (int );
/// <summary>
/// <para>Get/Set whether to handle boundaries. If enabled, boundary pixels are treated as duplicated so that central differencing works for the boundary pixels. If disabled, the output whole extent of the image is reduced by one pixel.</para>
/// </summary>
void SetHandleBoundaries(int arg0);
// int GetHandleBoundaries ();
/// <summary>
/// <para>Get/Set whether to handle boundaries. If enabled, boundary pixels are treated as duplicated so that central differencing works for the boundary pixels. If disabled, the output whole extent of the image is reduced by one pixel.</para>
/// </summary>
int GetHandleBoundaries();
// void HandleBoundariesOn ();
/// <summary>
/// <para>Get/Set whether to handle boundaries. If enabled, boundary pixels are treated as duplicated so that central differencing works for the boundary pixels. If disabled, the output whole extent of the image is reduced by one pixel.</para>
/// </summary>
void HandleBoundariesOn();
// void HandleBoundariesOff ();
/// <summary>
/// <para>Get/Set whether to handle boundaries. If enabled, boundary pixels are treated as duplicated so that central differencing works for the boundary pixels. If disabled, the output whole extent of the image is reduced by one pixel.</para>
/// </summary>
void HandleBoundariesOff();
// Did not wrap: vtkImageGradient ();
// Did not wrap: ~vtkImageGradient ();
// Did not wrap: virtual int RequestInformation (vtkInformation *, vtkInformationVector *, vtkInformationVector *);
// Did not wrap: virtual int RequestUpdateExtent (vtkInformation *, vtkInformationVector *, vtkInformationVector *);
// Did not wrap: void ThreadedRequestData (vtkInformation *, vtkInformationVector *, vtkInformationVector *, vtkImageData *inData, vtkImageData *outData, int outExt[6], int threadId);
// Did not wrap: vtkImageGradient (const vtkImageGradient &);
// Did not wrap: void vtkImageGradient
/// <summary>
/// This constructor is used to convert native pointers into managed wrapper classes.
/// </summary>
vtkImageGradient(System::IntPtr native, bool bConst);
/// <summary>
/// This constructor is called only by derived classes. It asks base classes not allocate a native instance.
/// </summary>
vtkImageGradient(bool donothing);
/// <summary>
/// This constructor creates a wrapper class. It is the one to call. /// </summary>
vtkImageGradient();
/// <summary>
/// This method calls Delete() on the native instance.
/// Use it to release resources in a timely fashion.
/// </summary>
/// <remarks>
/// If this method is not called, then the finalizer will
/// call Delete on this instance.
/// </remarks>
virtual ~vtkImageGradient();
};
} // end vtkImaging
| [
"useminmin@gmail.com"
] | useminmin@gmail.com |
74f658fe1b93e2293926b290e3ea6bc36a8a0337 | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /iotcloud/include/tencentcloud/iotcloud/v20210408/model/UpdateDeviceAvailableStateRequest.h | 8a9912aabe48723931bef4c572bfa8a6a81dd2f8 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 4,528 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_IOTCLOUD_V20210408_MODEL_UPDATEDEVICEAVAILABLESTATEREQUEST_H_
#define TENCENTCLOUD_IOTCLOUD_V20210408_MODEL_UPDATEDEVICEAVAILABLESTATEREQUEST_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Iotcloud
{
namespace V20210408
{
namespace Model
{
/**
* UpdateDeviceAvailableState请求参数结构体
*/
class UpdateDeviceAvailableStateRequest : public AbstractModel
{
public:
UpdateDeviceAvailableStateRequest();
~UpdateDeviceAvailableStateRequest() = default;
std::string ToJsonString() const;
/**
* 获取设备所属产品id
* @return ProductId 设备所属产品id
*
*/
std::string GetProductId() const;
/**
* 设置设备所属产品id
* @param _productId 设备所属产品id
*
*/
void SetProductId(const std::string& _productId);
/**
* 判断参数 ProductId 是否已赋值
* @return ProductId 是否已赋值
*
*/
bool ProductIdHasBeenSet() const;
/**
* 获取设备名称
* @return DeviceName 设备名称
*
*/
std::string GetDeviceName() const;
/**
* 设置设备名称
* @param _deviceName 设备名称
*
*/
void SetDeviceName(const std::string& _deviceName);
/**
* 判断参数 DeviceName 是否已赋值
* @return DeviceName 是否已赋值
*
*/
bool DeviceNameHasBeenSet() const;
/**
* 获取要设置的设备状态,1为启用,0为禁用
* @return EnableState 要设置的设备状态,1为启用,0为禁用
*
*/
uint64_t GetEnableState() const;
/**
* 设置要设置的设备状态,1为启用,0为禁用
* @param _enableState 要设置的设备状态,1为启用,0为禁用
*
*/
void SetEnableState(const uint64_t& _enableState);
/**
* 判断参数 EnableState 是否已赋值
* @return EnableState 是否已赋值
*
*/
bool EnableStateHasBeenSet() const;
private:
/**
* 设备所属产品id
*/
std::string m_productId;
bool m_productIdHasBeenSet;
/**
* 设备名称
*/
std::string m_deviceName;
bool m_deviceNameHasBeenSet;
/**
* 要设置的设备状态,1为启用,0为禁用
*/
uint64_t m_enableState;
bool m_enableStateHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_IOTCLOUD_V20210408_MODEL_UPDATEDEVICEAVAILABLESTATEREQUEST_H_
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
e504ae4d75a3aa6ca531ae864b031d18d5fe5b65 | d5ce9190050be3de21f91a7b4368074f31880905 | /DWMDetour/DWMCapture.h | 95ffca5c1842c4c399178cbc9b90e79733a5f414 | [] | no_license | prolen/TinyUI | 341abfbb1023fb4b2e10dc327be0ad6a87fe22a9 | e0012396608857b9180461087913b560da571e3e | refs/heads/master | 2021-04-03T09:50:05.339547 | 2018-03-07T12:56:40 | 2018-03-07T12:56:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,466 | h | #pragma once
#include "Common/TinyLogging.h"
#include "Common/TinyHook.h"
#include "IO/TinySharedMemory.h"
#include "IO/TinyTask.h"
#include "IDXGIFactoryDWM.h"
#include <d3d10_1.h>
#include <d3d10.h>
#include <d3d11.h>
using namespace TinyUI;
namespace DWM
{
#define DWM_WINDOWCLASS TEXT("DWM WindowClass")
typedef struct tagDWMCaptureDATA
{
UINT CaptureType;
DWORD Format;
SIZE Size;
BOOL bFlip;
BOOL bMultisample;
UINT Pitch;
DWORD MapSize;
HWND HwndCapture;
}DWMCaptureDATA;
class DWMCapture
{
public:
DWMCapture();
~DWMCapture();
BOOL Attach(HMODULE hModule);
BOOL Detach(HMODULE hModule);
public:
BOOL Setup(IDXGISwapChain *swap);
BOOL Render(IDXGISwapChain *swap, UINT flags);
void Release();
public:
BOOL BeginCapture();
BOOL EndCapture();
void OnMessagePump();
BOOL DX101GPUHook(ID3D10Device1 *device);
private:
static LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
private:
HWND m_hWNDD3D;
IO::TinyTask m_task;
HINSTANCE m_hInstance;
public:
DWMCaptureDATA m_captureDATA;
DXGI_FORMAT m_dxgiFormat;
BOOL m_bCapturing;
BOOL m_bTextures;
BOOL m_bDX101;
HANDLE m_hTextureHandle;
HMODULE m_hD3D101;
IDXGISwapChain* m_currentSwap;
TinyComPtr<ID3D10Resource> m_resource;
TinyDetour m_dxPresent;
TinyDetour m_dxResizeBuffers;
};
SELECTANY extern DWMCapture g_dwm;
}
| [
"csy@CSY-PC"
] | csy@CSY-PC |
2169f8bee35f15748e899a4269e155c11833240f | aa2115eefdd230a8d138c54ce57472aebcaa9d43 | /src/bitcoinrpc.cpp | de6a2573c3d180a683f4562b508cd29c92915060 | [
"MIT"
] | permissive | ojetecoin/ojetecoin | 7af5f5cebf89eb097b602f437a2a8b4c7d8fdfa4 | 5776fcab161a9a8326d4c7f18df68ac77853efef | refs/heads/master | 2016-09-03T06:28:13.350669 | 2014-08-19T08:11:41 | 2014-08-19T08:11:41 | 22,548,268 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 48,795 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h"
#include "util.h"
#include "sync.h"
#include "ui_interface.h"
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#include <boost/asio.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/shared_ptr.hpp>
#include <list>
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
static std::string strRPCUserColonPass;
// These are created by StartRPCThreads, destroyed in StopRPCThreads
static asio::io_service* rpc_io_service = NULL;
static ssl::context* rpc_ssl_context = NULL;
static boost::thread_group* rpc_worker_group = NULL;
static inline unsigned short GetDefaultRPCPort()
{
return GetBoolArg("-testnet", false) ? 58591 : 58593;
}
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected,
bool fAllowNull)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
int64 AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > 84000000.0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
int64 nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64 amount)
{
return (double)amount / (double)COIN;
}
std::string HexBits(unsigned int nBits)
{
union {
int32_t nBits;
char cBits[4];
} uBits;
uBits.nBits = htonl((int32_t)nBits);
return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
}
///
/// Note: This interface may still be subject to change.
///
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
if (pcmd->reqWallet && !pwalletMain)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
// Accept the deprecated and ignored 'detach' boolean argument
if (fHelp || params.size() > 1)
throw runtime_error(
"stop\n"
"Stop Ojetecoin server.");
// Shutdown will take long enough that the response should get back
StartShutdown();
return "Ojetecoin server stopping";
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name actor (function) okSafeMode threadSafe reqWallet
// ------------------------ ----------------------- ---------- ---------- ---------
{ "help", &help, true, true, false },
{ "stop", &stop, true, true, false },
{ "getblockcount", &getblockcount, true, false, false },
{ "getbestblockhash", &getbestblockhash, true, false, false },
{ "getconnectioncount", &getconnectioncount, true, false, false },
{ "getpeerinfo", &getpeerinfo, true, false, false },
{ "addnode", &addnode, true, true, false },
{ "getaddednodeinfo", &getaddednodeinfo, true, true, false },
{ "getdifficulty", &getdifficulty, true, false, false },
{ "getnetworkhashps", &getnetworkhashps, true, false, false },
{ "getgenerate", &getgenerate, true, false, false },
{ "setgenerate", &setgenerate, true, false, true },
{ "gethashespersec", &gethashespersec, true, false, false },
{ "getinfo", &getinfo, true, false, false },
{ "getmininginfo", &getmininginfo, true, false, false },
{ "getnewaddress", &getnewaddress, true, false, true },
{ "getaccountaddress", &getaccountaddress, true, false, true },
{ "setaccount", &setaccount, true, false, true },
{ "getaccount", &getaccount, false, false, true },
{ "getaddressesbyaccount", &getaddressesbyaccount, true, false, true },
{ "sendtoaddress", &sendtoaddress, false, false, true },
{ "getreceivedbyaddress", &getreceivedbyaddress, false, false, true },
{ "getreceivedbyaccount", &getreceivedbyaccount, false, false, true },
{ "listreceivedbyaddress", &listreceivedbyaddress, false, false, true },
{ "listreceivedbyaccount", &listreceivedbyaccount, false, false, true },
{ "backupwallet", &backupwallet, true, false, true },
{ "keypoolrefill", &keypoolrefill, true, false, true },
{ "walletpassphrase", &walletpassphrase, true, false, true },
{ "walletpassphrasechange", &walletpassphrasechange, false, false, true },
{ "walletlock", &walletlock, true, false, true },
{ "encryptwallet", &encryptwallet, false, false, true },
{ "validateaddress", &validateaddress, true, false, false },
{ "getbalance", &getbalance, false, false, true },
{ "move", &movecmd, false, false, true },
{ "sendfrom", &sendfrom, false, false, true },
{ "sendmany", &sendmany, false, false, true },
{ "addmultisigaddress", &addmultisigaddress, false, false, true },
{ "createmultisig", &createmultisig, true, true , false },
{ "getrawmempool", &getrawmempool, true, false, false },
{ "getblock", &getblock, false, false, false },
{ "getblockhash", &getblockhash, false, false, false },
{ "gettransaction", &gettransaction, false, false, true },
{ "listtransactions", &listtransactions, false, false, true },
{ "listaddressgroupings", &listaddressgroupings, false, false, true },
{ "signmessage", &signmessage, false, false, true },
{ "verifymessage", &verifymessage, false, false, false },
{ "getwork", &getwork, true, false, true },
{ "getworkex", &getworkex, true, false, true },
{ "listaccounts", &listaccounts, false, false, true },
{ "settxfee", &settxfee, false, false, true },
{ "getblocktemplate", &getblocktemplate, true, false, false },
{ "submitblock", &submitblock, false, false, false },
{ "setmininput", &setmininput, false, false, false },
{ "listsinceblock", &listsinceblock, false, false, true },
{ "dumpprivkey", &dumpprivkey, true, false, true },
{ "importprivkey", &importprivkey, false, false, true },
{ "listunspent", &listunspent, false, false, true },
{ "getrawtransaction", &getrawtransaction, false, false, false },
{ "createrawtransaction", &createrawtransaction, false, false, false },
{ "decoderawtransaction", &decoderawtransaction, false, false, false },
{ "signrawtransaction", &signrawtransaction, false, false, false },
{ "sendrawtransaction", &sendrawtransaction, false, false, false },
{ "getnormalizedtxid", &getnormalizedtxid, true, true, false },
{ "gettxoutsetinfo", &gettxoutsetinfo, true, false, false },
{ "gettxout", &gettxout, true, false, false },
{ "lockunspent", &lockunspent, false, false, true },
{ "listlockunspent", &listlockunspent, false, false, true },
{ "verifychain", &verifychain, true, false, false },
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: ojetecoin-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: ojetecoin-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %"PRIszu"\r\n"
"Content-Type: application/json\r\n"
"Server: ojetecoin-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto,
string& http_method, string& http_uri)
{
string str;
getline(stream, str);
// HTTP request line is space-delimited
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return false;
// HTTP methods permitted: GET, POST
http_method = vWords[0];
if (http_method != "GET" && http_method != "POST")
return false;
// HTTP URI must be an absolute path, relative to current host
http_uri = vWords[1];
if (http_uri.size() == 0 || http_uri[0] != '/')
return false;
// parse proto, if present
string strProto = "";
if (vWords.size() > 2)
strProto = vWords[2];
proto = 0;
const char *ver = strstr(strProto.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return true;
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
loop
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTPMessage(std::basic_istream<char>& stream, map<string,
string>& mapHeadersRet, string& strMessageRet,
int nProto)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read header
int nLen = ReadHTTPHeaders(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return HTTP_OK;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return TimingResistantEqual(strUserPass, strRPCUserColonPass);
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ServiceConnection(AcceptedConnection *conn);
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted && acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
delete conn;
}
else {
ServiceConnection(conn);
conn->close();
delete conn;
}
}
void StartRPCThreads()
{
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if ((mapArgs["-rpcpassword"] == "") ||
(mapArgs["-rpcuser"] == mapArgs["-rpcpassword"]))
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use ojetecoind";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=ojetecoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"Ojetecoin Alert\" admin@foo.com\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
assert(rpc_io_service == NULL);
rpc_io_service = new asio::io_service();
rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23);
const bool fUseSSL = GetBoolArg("-rpcssl");
if (fUseSSL)
{
rpc_ssl_context->set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
boost::system::error_code v6_only_error;
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
bool fListening = false;
std::string strerr;
try
{
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
}
try {
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (!fListening || loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(*rpc_io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
}
if (!fListening) {
uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
rpc_worker_group = new boost::thread_group();
for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
}
void StopRPCThreads()
{
if (rpc_io_service == NULL) return;
rpc_io_service->stop();
if (rpc_worker_group != NULL)
rpc_worker_group->join_all();
delete rpc_worker_group; rpc_worker_group = NULL;
delete rpc_ssl_context; rpc_ssl_context = NULL;
delete rpc_io_service; rpc_io_service = NULL;
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getworkex" && strMethod != "getblocktemplate")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
void ServiceConnection(AcceptedConnection *conn)
{
bool fRun = true;
while (fRun)
{
int nProto = 0;
map<string, string> mapHeaders;
string strRequest, strMethod, strURI;
// Read HTTP request line
if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
break;
// Read HTTP message headers and body
ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto);
if (strURI != "/") {
conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush;
break;
}
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DoS the user really
shouldn't have their RPC port exposed. */
if (mapArgs["-rpcpassword"].size() < 20)
MilliSleep(250);
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
break;
}
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
if (pcmd->reqWallet && !pwalletMain)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
!pcmd->okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
if (pcmd->threadSafe)
result = pcmd->actor(params, false);
else if (!pwalletMain) {
LOCK(cs_main);
result = pcmd->actor(params, false);
} else {
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
throw runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive HTTP reply status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Receive HTTP reply message headers and body
map<string, string> mapHeaders;
string strReply;
ReadHTTPMessage(stream, mapHeaders, strReply, nProto);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
if (fAllowNull && value.type() == null_type)
return;
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
ConvertTo<T>(value2, fAllowNull);
value = value2;
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getnetworkhashps" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "getnetworkhashps" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "setmininput" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
if (strMethod == "sendrawtransaction" && n > 1) ConvertTo<bool>(params[1], true);
if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "verifychain" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "verifychain" && n > 1) ConvertTo<boost::int64_t>(params[1]);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...) {
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
| [
"miji@Mijis-MacBook-Pro.local"
] | miji@Mijis-MacBook-Pro.local |
2339b35798992835f9984fd56c30dc8efae2e960 | 803f1a9a7d3cdf17b063c2e0474083c18acd1ee9 | /406.cpp | 7d21f3acce4c4522a34d5f26f0e988f9a4f46085 | [] | no_license | daneshvar-amrollahi/SGU | 3a3a63fbcd061fe5e7fd6361babb7a292a4cfc97 | 7f561652c2d1a3040d7c4554eca9c835e6abed05 | refs/heads/master | 2021-01-10T12:42:51.292326 | 2018-01-01T19:11:57 | 2018-01-01T19:11:57 | 49,258,537 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,113 | cpp | //Bismillah
#include <bits/stdc++.h>
using namespace std;
#define FOR(i,begin,end) for (int i=begin;i<=end;++i)
#define rep(i,t) for (int i=0;i<t;++i)
#define pb push_back
#define mp make_pair
#define endl '\n'
typedef long long ll;
typedef pair <int,int> pii;
int n,m;
vector <int> seq[20];
int mark[110];
int main()
{
ios_base::sync_with_stdio(false);
cin >> n >> m;
for (int i = 0 ; i < n ; i++)
{
int k;
cin >> k;
for (int j = 0 ; j < k ; j++)
{
int x;
cin >> x;
seq[i].pb(x);
}
}
for (int q = 0 ; q < m ; q++)
{
int l;
cin >> l;
for (int i = 0 ; i < 110 ; i++)
mark[i] = 0;
vector <int> v;
for (int i = 0 ; i < l ; i++)
{
int x;
cin >> x;
if (x < 0)
mark[-x] = 1; //nabayad bashe
if (x > 0)
{
v.pb(x);
mark[x] = 2; //bayad bashe
}
}
vector <int> ans;
for (int i = 0 ; i < n ; i++)
{
bool ok = true;
for (int j = 0 ; j < seq[i].size() ; j++)
{
int cur = seq[i][j];
if (mark[cur] == 1)
ok = false;
}
if (!ok)
continue;
for (int j = 0 ; j < v.size() ; j++)
{
bool has = 0;
for (int p = 0 ; p < seq[i].size() ; p++)
{
if (v[j] == seq[i][p])
has = true;
}
if (!has)
ok = false;
}
if (ok)
ans.pb(i);
}
cout << ans.size() << endl;
for (int i = 0 ; i < ans.size() ; i++)
{
int cur = ans[i];
cout << seq[cur].size() << " ";
for (int j = 0 ; j < seq[cur].size() ; j++)
cout << seq[cur][j] << " ";
cout << endl;
}
}
return 0;
}
| [
"amrollahi.daneshvar@gmail.com"
] | amrollahi.daneshvar@gmail.com |
08a4e5f51bfa24a52aea0ffdfc3c5af63d04cbd4 | 73fbd288ea42f52cf8f19e826b6e3fdb7795d96b | /03-04-2020/CPP 2/0783_ex.5_Joao_Fraga.cpp | c48d884b2219de9115dc72a997833d966e2c34d0 | [] | no_license | MTVirux/C-CPP-Classes | 529493ecab8bc34a49824634b29ea0588f25d47b | 9ac4253f962ecb92536f1b6c1e73342b3dceeac7 | refs/heads/master | 2021-06-28T23:36:12.118889 | 2021-03-24T12:34:37 | 2021-03-24T12:34:37 | 227,125,165 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 751 | cpp | #include <iostream>
using namespace std;
int main(){
int array[20];
int soma_impares = 0;
int soma_pares = 0;
int valor;
cout << "Insira 20 valores: " << endl;
for (int i = 0; i < 20 ; i++){
cin >> array[i]; cin.ignore();
}
for (int i : array){
if(i % 2 == 1)
soma_impares = soma_impares + i;
}
for (int i : array){
if(i % 2 == 0)
soma_pares = soma_pares +i;
}
valor = soma_impares - soma_pares;
if(valor > 0)
cout << "Valor:" << valor << endl;
if(soma_impares - soma_pares < 0)
cout << "Valor abaixo de 0" << endl;
if(soma_impares - soma_pares == 0)
cout << "JACKPOT, vais receber mais um valor" << endl;
} | [
"supersilver-dark@hotmail.com"
] | supersilver-dark@hotmail.com |
c74636ae1f8f7000a2992ebfdffedc8410b6ce02 | fc42f22ffb6d75489c068bbbaa56756d73bcf159 | /OJ/多校/杭电2020/8/D.cpp | 1935742e4aeeceea7a4430b4fe32d22a6c92439d | [] | no_license | ytrsk/ICPC_training_respository | a6031b46927281c1f4d09e55ac75f1c6770b309b | dd6fabc68bcb9f81ccd1cdc9f95d50919698e542 | refs/heads/master | 2022-12-15T06:29:33.189202 | 2020-09-15T11:27:05 | 2020-09-15T11:27:05 | 210,859,312 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,841 | cpp |
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#pragma GCC optimize("Ofast")
#pragma GCC optimize("inline")
#pragma GCC optimize("-fgcse")
#pragma GCC optimize("-fgcse-lm")
#pragma GCC optimize("-fipa-sra")
#pragma GCC optimize("-ftree-pre")
#pragma GCC optimize("-ftree-vrp")
#pragma GCC optimize("-fpeephole2")
#pragma GCC optimize("-ffast-math")
#pragma GCC optimize("-fsched-spec")
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("-falign-jumps")
#pragma GCC optimize("-falign-loops")
#pragma GCC optimize("-falign-labels")
#pragma GCC optimize("-fdevirtualize")
#pragma GCC optimize("-fcaller-saves")
#pragma GCC optimize("-fcrossjumping")
#pragma GCC optimize("-fthread-jumps")
#pragma GCC optimize("-funroll-loops")
#pragma GCC optimize("-fwhole-program")
#pragma GCC optimize("-freorder-blocks")
#pragma GCC optimize("-fschedule-insns")
#pragma GCC optimize("inline-functions")
#pragma GCC optimize("-ftree-tail-merge")
#pragma GCC optimize("-fschedule-insns2")
#pragma GCC optimize("-fstrict-aliasing")
#pragma GCC optimize("-fstrict-overflow")
#pragma GCC optimize("-falign-functions")
#pragma GCC optimize("-fcse-skip-blocks")
#pragma GCC optimize("-fcse-follow-jumps")
#pragma GCC optimize("-fsched-interblock")
#pragma GCC optimize("-fpartial-inlining")
#pragma GCC optimize("no-stack-protector")
#pragma GCC optimize("-freorder-functions")
#pragma GCC optimize("-findirect-inlining")
#pragma GCC optimize("-fhoist-adjacent-loads")
#pragma GCC optimize("-frerun-cse-after-loop")
#pragma GCC optimize("inline-small-functions")
#pragma GCC optimize("-finline-small-functions")
#pragma GCC optimize("-ftree-switch-conversion")
#pragma GCC optimize("-foptimize-sibling-calls")
#pragma GCC optimize("-fexpensive-optimizations")
#pragma GCC optimize("-funsafe-loop-optimizations")
#pragma GCC optimize("inline-functions-called-once")
#pragma GCC optimize("-fdelete-null-pointer-checks")
#include<bits/stdc++.h>
const int maxn = 500005;
const int maxp = maxn*20;
using namespace std;
inline void read(int &a){
char c;bool f=0;
while(!isdigit(c=getchar())) if(c=='-') f=1;
for(a=c-'0';isdigit(c=getchar());a=a*10+c-'0');
if(f) a=-a;
}
#define rd(n) FastIO::read(n)
namespace FastIO {
const int SIZE = 1 << 16;
char buf[SIZE], obuf[SIZE], str[60];
int bi = SIZE, bn = SIZE, opt;
int read(char *s) {
while (bn) {
for (; bi < bn && buf[bi] <= ' '; bi++);
if (bi < bn) break;
bn = fread(buf, 1, SIZE, stdin);
bi = 0;
}
int sn = 0;
while (bn) {
for (; bi < bn && buf[bi] > ' '; bi++) s[sn++] = buf[bi];
if (bi < bn) break;
bn = fread(buf, 1, SIZE, stdin);
bi = 0;
}
s[sn] = 0;
return sn;
}
bool read(int& x) {
int n = read(str), bf;
if (!n) return 0;
int i = 0; if (str[i] == '-') bf = -1, i++; else bf = 1;
for (x = 0; i < n; i++) x = x * 10 + str[i] - '0';
if (bf < 0) x = -x;
return 1;
}
};
namespace LCT{
const int N = 1500005;
int ch[N][2],fa[N],v[N],pos[N],tot,nb[N][2];
bool rev[N];
#define il inline
#define lc ch[x][0]
#define rc ch[x][1]
il bool isr(int x){return ch[fa[x]][0]!=x&&ch[fa[x]][1]!=x;}
il bool isc(int x){return ch[fa[x]][1]==x;}
il void upd(int x){
pos[x]=x;
if(v[pos[x]]>v[pos[lc]]) pos[x]=pos[lc];
if(v[pos[x]]>v[pos[rc]]) pos[x]=pos[rc];
}
il void pushdown(int x){
if(rev[x]){
swap(lc,rc),rev[x]=0;
if(lc) rev[lc]^=1; if(rc) rev[rc]^=1;
}
}
il void pdpath(int x){if(!isr(x)) pdpath(fa[x]);pushdown(x);}
il void rot(int x){
int y=fa[x],z=fa[y],c=isc(x);
if(!isr(y)) ch[z][isc(y)]=x;
(ch[y][c]=ch[x][!c])&&(fa[ch[x][!c]]=y);
fa[ch[x][!c]=y]=x,fa[x]=z;
upd(y),upd(x);
}
il void splay(int x){
pdpath(x);
for(;!isr(x);rot(x))
if(!isr(fa[x])) rot(isc(fa[x])==isc(x)?fa[x]:x);
}
il int access(int x,int y=0){
for(;x;x=fa[y=x]) splay(x),ch[x][1]=y,upd(x);
return y;
}
il void bert(int x){access(x),splay(x),rev[x]^=1;}
il int sert(int x){access(x),splay(x);for(;lc;x=lc);return x;}
il void link(int x,int y){bert(x),fa[x]=y;}
il void cut(int x,int y){bert(x),access(y),splay(y);fa[x]=ch[y][0]=0,upd(y);}
il int split(int x,int y){bert(x),access(y),splay(y); return y;}
il bool judge(int x,int y){bert(x);return sert(y)==x;}
il int insert(int x,int y,int w){
int tmp=0;
if(judge(x,y)){
int p=pos[split(x,y)]; tmp=v[p];
cut(nb[p][0],p),cut(p,nb[p][1]);
}
v[++tot]=w,pos[tot]=tot,nb[tot][0]=x,nb[tot][1]=y;fa[tot]=0;rev[tot]=0;
ch[tot][0]=ch[tot][1]=0;
link(x,tot),link(tot,y);
return tmp;
}
#undef lc
#undef rc
}
int n,m,Q,tp,ans;
int a[maxn],mx[maxn<<2];
void pushup(int o){
mx[o]=max(mx[o<<1],mx[o<<1|1]);
}
void build(int o,int l,int r){
if(l==r){
mx[o]=a[l];return;
}
int m=(l+r)>>1;
build(o<<1,l,m);build(o<<1|1,m+1,r);
pushup(o);
}
int query(int o,int l,int r,int ql,int qr){
if(l==ql&&r==qr) return mx[o];
int m=(l+r)>>1;
if(ql<=m&&qr>m) return max(query(o<<1,l,m,ql,m),query(o<<1|1,m+1,r,m+1,qr));
else if(ql<=m) return query(o<<1,l,m,ql,qr);
else return query(o<<1|1,m+1,r,ql,qr);
}
int main(){
int x,y,t;
rd(t);
while(t--){
rd(n);
rd(m);
rd(Q);
LCT::tot=n;
for(int i=0;i<=n;i++) LCT::pos[i]=0,LCT::v[i]=m+1,LCT::ch[i][0]=LCT::ch[i][1]=0,LCT::rev[i]=LCT::fa[i]=LCT::nb[i][0]=LCT::nb[i][1]=0;
for(int i=1;i<=m;i++){
rd(x);rd(y);
// if(x==y) {rt[i]=rt[i-1];continue;}
a[i]=LCT::insert(x,y,i);
}
build(1,1,m);
int ans=1;
while(Q--){
int x,y;rd(x),rd(y);
int k1=(x^ans)%m+1;
int k2=(y^ans)%m+1;
x=min(k1,k2);y=max(k1,k2);
if(query(1,1,m,x,y)>=x){
ans=1;
}
else ans=0;
if(ans==1) printf("Yes\n");
else printf("No\n");
}
}
return 0;
} | [
"2232160811@qq.com"
] | 2232160811@qq.com |
ab51b3e1cf98989163df3515385109bdb0e3cb07 | 7be1d3b42af0f28563339d537f9a966d7be13c1f | /src/core/config/thirdparty/cppdb/atomic_counter.hpp | 8bef4385a2bff8c15c524471f56b1c40b69be0de | [] | no_license | chakannom/stock-agent | 3144572e6187584a773eb5b93a9632f7a9234023 | 55bd00fccc31c6de2148bccabd08738aca82faaf | refs/heads/master | 2022-12-31T07:12:30.939513 | 2020-10-26T06:36:44 | 2020-10-26T06:36:44 | 280,083,448 | 0 | 0 | null | 2020-10-26T06:36:45 | 2020-07-16T07:21:20 | null | UTF-8 | C++ | false | false | 2,827 | hpp | ///////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2010-2011 Artyom Beilis (Tonkikh) <artyomtnk@yahoo.com>
//
// 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)
//
// or (at your opinion) under:
//
// The MIT License
// (See accompanying file MIT.txt or a copy at
// http://www.opensource.org/licenses/mit-license.php)
//
///////////////////////////////////////////////////////////////////////////////
#ifndef CPPDB_ATOMIC_COUNT_HPP
#define CPPDB_ATOMIC_COUNT_HPP
#include "defs.hpp"
namespace cppdb {
///
/// \brief Atomic counter is a class that allows perform counting in thread safe way.
///
/// It is mainly used for reference counting. Under Windows it uses Interlocked API, under
/// other platforms it used built-in atomic operations or fails back to pthreads locking implementation.
///
/// Notes:
///
/// - This counter is not safe for use in process shared memory, when pthreads fall-back is used
/// - Under POSIX platform pthread_mutex_t is always present in order to make sure that we can implement
/// or remove pthread fall-back at any point not affecting ABI
///
class CPPDB_API atomic_counter {
public:
///
/// Create a counter with initial value v
///
explicit atomic_counter( long v);
~atomic_counter();
///
/// Increment and return the result after increment atomically
///
long operator++()
{
return inc();
}
///
/// Decrement and return the result after decrement atomically
///
long operator--()
{
return dec();
}
///
/// Return current value - atomically
///
operator long() const
{
return get();
}
private:
long inc();
long dec();
long get() const;
atomic_counter(atomic_counter const &);
atomic_counter & operator=(atomic_counter const &);
mutable union {
int i;
unsigned ui;
long l;
unsigned long ul;
long long ll;
unsigned long long ull;
} value_;
// Is actually used for platforms without lock
// it would not be used when atomic operations
// available
void *mutex_;
};
} // cppdb
#endif
| [
"genteelson@gmail.com"
] | genteelson@gmail.com |
12749b78502d8ea13fbf03267a9aef50a8073a46 | 51fd68fc0d7ebadadeb568950920621b58058af3 | /C++/code/378.cpp | 9e01e983092efbc227a63f6b48ebce3ec71806e4 | [] | no_license | leafeonia/leetcode | 7b0eded595ed7bf349472ea26fa1128c28ee3767 | f6c0348d694a11011a0544027a720645a5577bad | refs/heads/master | 2021-12-07T00:32:13.517169 | 2021-10-25T07:46:29 | 2021-10-25T07:46:29 | 194,399,032 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 705 | cpp | class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
typedef pair<int, int> pi;
int m = matrix.size();
int n = matrix[0].size();
auto comp = [&matrix](pi a, pi b) {return matrix[a.first][a.second] > matrix[b.first][b.second];};
priority_queue<pi, vector<pi>, decltype(comp)> pq(comp);
for (int i = 0; i < m; i++) {
pq.push({i, 0});
}
for (int i = 1; i < k; i++) {
auto top = pq.top();
pq.pop();
if (top.second < n - 1) {
pq.push({top.first, top.second + 1});
}
}
return matrix[pq.top().first][pq.top().second];
}
}; | [
"maoym@126.com"
] | maoym@126.com |
3d2c61c9499c46bf8e84c6c929e5142fe8a4b500 | ea401c3e792a50364fe11f7cea0f35f99e8f4bde | /released_plugins/v3d_plugins/bigneuron_AmosSironi_PrzemyslawGlowacki_SQBTree_plugin/libs/ITK_include/itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader.hxx | 903e0aef64a43453ec51eff4430152fea6bc23f8 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | Vaa3D/vaa3d_tools | edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9 | e6974d5223ae70474efaa85e1253f5df1814fae8 | refs/heads/master | 2023-08-03T06:12:01.013752 | 2023-08-02T07:26:01 | 2023-08-02T07:26:01 | 50,527,925 | 107 | 86 | MIT | 2023-05-22T23:43:48 | 2016-01-27T18:19:17 | C++ | UTF-8 | C++ | false | false | 3,712 | hxx | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.
*
*=========================================================================*/
#ifndef __itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader_hxx
#define __itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader_hxx
#include "itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader.h"
#include "itkDefaultConvertPixelTraits.h"
namespace itk
{
template< typename TDomainPartitioner, typename TImageToImageMetric, typename TMeanSquaresMetric >
bool
MeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader< TDomainPartitioner, TImageToImageMetric, TMeanSquaresMetric >
::ProcessPoint( const VirtualIndexType &,
const VirtualPointType & virtualPoint,
const FixedImagePointType &,
const FixedImagePixelType & fixedImageValue,
const FixedImageGradientType &,
const MovingImagePointType & ,
const MovingImagePixelType & movingImageValue,
const MovingImageGradientType & movingImageGradient,
MeasureType & metricValueReturn,
DerivativeType & localDerivativeReturn,
const ThreadIdType threadID) const
{
/** Only the voxelwise contribution given the point pairs. */
FixedImagePixelType diff = fixedImageValue - movingImageValue;
const unsigned int nComponents = NumericTraits<FixedImagePixelType>::GetLength( diff );
metricValueReturn = NumericTraits<MeasureType>::ZeroValue();
for ( unsigned int nc = 0; nc < nComponents; nc++ )
{
MeasureType diffC = DefaultConvertPixelTraits<FixedImagePixelType>::GetNthComponent(nc, diff);
metricValueReturn += diffC*diffC;
}
if( ! this->GetComputeDerivative() )
{
return true;
}
/* Use a pre-allocated jacobian object for efficiency */
typedef typename TImageToImageMetric::JacobianType & JacobianReferenceType;
JacobianReferenceType jacobian = this->m_GetValueAndDerivativePerThreadVariables[threadID].MovingTransformJacobian;
/** For dense transforms, this returns identity */
this->m_Associate->GetMovingTransform()->ComputeJacobianWithRespectToParameters( virtualPoint, jacobian );
for ( unsigned int par = 0; par < this->GetCachedNumberOfLocalParameters(); par++ )
{
localDerivativeReturn[par] = NumericTraits<DerivativeValueType>::Zero;
for ( unsigned int nc = 0; nc < nComponents; nc++ )
{
MeasureType diffValue = DefaultConvertPixelTraits<FixedImagePixelType>::GetNthComponent(nc,diff);
for ( SizeValueType dim = 0; dim < ImageToImageMetricv4Type::MovingImageDimension; dim++ )
{
localDerivativeReturn[par] += 2.0 * diffValue * jacobian(dim, par) *
DefaultConvertPixelTraits<MovingImageGradientType>::GetNthComponent(
ImageToImageMetricv4Type::FixedImageDimension * nc + dim, movingImageGradient );
}
}
}
return true;
}
} // end namespace itk
#endif
| [
"amos.sironi@gmail.com"
] | amos.sironi@gmail.com |
d44bfca7071a079b8fde3d31fc45f0370894ac5b | 3ddd2d01dbcf42282702db685760dafa9979fee3 | /LibM/math.cpp | 68210c7809a2f095d6e904828087e9e66091b8fe | [
"BSD-2-Clause"
] | permissive | kzwkt/serenity | 65f6277faa641a32a8a58635d4737507e9681b3f | 202e922ce85b1b97e0492a02792bb86b9d7906bf | refs/heads/master | 2020-05-18T14:20:10.593865 | 2019-05-01T17:11:08 | 2019-05-01T17:11:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 329 | cpp | #include <LibC/assert.h>
#include <LibM/math.h>
extern "C" {
double cos(double)
{
ASSERT_NOT_REACHED();
}
double sin(double)
{
ASSERT_NOT_REACHED();
}
double pow(double x, double y)
{
(void)x;
(void)y;
ASSERT_NOT_REACHED();
}
double ldexp(double, int exp)
{
(void)exp;
ASSERT_NOT_REACHED();
}
}
| [
"awesomekling@gmail.com"
] | awesomekling@gmail.com |
f585ac475215d144048892130c8395e553ee095d | 02f5f35c4b182f18916e5aab8fa8f8b37fa6023c | /ZeroDenomException.h | 7e831064b983cb7d13e02858dfaae4b315562b6b | [] | no_license | Mozuha/CS255C | 1551f5006abd90a3d79172b737c027e2e5d5c2c6 | be8c69a8cdc2f8261e4c757d84556599e0c6e21a | refs/heads/master | 2020-12-20T02:51:38.450838 | 2020-05-01T14:43:42 | 2020-05-01T14:43:42 | 235,939,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 631 | h | /*
* Apr 21, 2020
* Mizuki Hashimoto
* This is a header file for ZeroDenomException class.
* Contains prototypes for methods and variables of ZeroDenomException class
*/
// prevent multiple inclusions of header file
#ifndef C_PROJECT_ZERODENOMEXCEPTION_H
#define C_PROJECT_ZERODENOMEXCEPTION_H
#include <stdexcept>
using namespace std;
// ZeroDenomException class definition
class ZeroDenomException : public runtime_error { // ZeroDenomException class inherits runtime_error class
public:
ZeroDenomException() : runtime_error("") {} // ZeroDenomException as runtime error
};
#endif //C_PROJECT_ZERODENOMEXCEPTION_H
| [
"mizuki.mikkun.hashimoto@gmail.com"
] | mizuki.mikkun.hashimoto@gmail.com |
7ec148c9fb424611efd1aa65e7643a4a934f7c8a | 785df77400157c058a934069298568e47950e40b | /Common/Foam/include/base/MatrixBlockI.hxx | 423265a1cf1abb5833591bd8bcffed4f31fd2919 | [] | no_license | amir5200fx/Tonb | cb108de09bf59c5c7e139435e0be008a888d99d5 | ed679923dc4b2e69b12ffe621fc5a6c8e3652465 | refs/heads/master | 2023-08-31T08:59:00.366903 | 2023-08-31T07:42:24 | 2023-08-31T07:42:24 | 230,028,961 | 9 | 3 | null | 2023-07-20T16:53:31 | 2019-12-25T02:29:32 | C++ | UTF-8 | C++ | false | false | 3,283 | hxx | #pragma once
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
template<class MatrixType>
tnbLib::ConstMatrixBlock<MatrixType>::ConstMatrixBlock
(
const MatrixType& matrix,
const label m,
const label n,
const label mStart,
const label nStart
)
:
matrix_(matrix),
mRows_(m),
nCols_(n),
rowStart_(mStart),
colStart_(nStart)
{
#ifdef FULLDEBUG
if
(
rowStart_ + mRows_ > matrix.m()
|| colStart_ + nCols_ > matrix.n()
)
{
FatalErrorInFunction
<< "Block addresses outside matrix"
<< abort(FatalError);
}
#endif
}
template<class MatrixType>
tnbLib::MatrixBlock<MatrixType>::MatrixBlock
(
MatrixType& matrix,
const label m,
const label n,
const label mStart,
const label nStart
)
:
matrix_(matrix),
mRows_(m),
nCols_(n),
rowStart_(mStart),
colStart_(nStart)
{
#ifdef FULLDEBUG
if
(
rowStart_ + mRows_ > matrix.m()
|| colStart_ + nCols_ > matrix.n()
)
{
FatalErrorInFunction
<< "Block addresses outside matrix"
<< abort(FatalError);
}
#endif
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class MatrixType>
inline tnbLib::label tnbLib::ConstMatrixBlock<MatrixType>::m() const
{
return mRows_;
}
template<class MatrixType>
inline tnbLib::label tnbLib::ConstMatrixBlock<MatrixType>::n() const
{
return nCols_;
}
template<class MatrixType>
inline tnbLib::label tnbLib::MatrixBlock<MatrixType>::m() const
{
return mRows_;
}
template<class MatrixType>
inline tnbLib::label tnbLib::MatrixBlock<MatrixType>::n() const
{
return nCols_;
}
// * * * * * * * * * * * * * * * Member Operators * * * * * * * * * * * * * //
template<class MatrixType>
inline const typename MatrixType::cmptType&
tnbLib::ConstMatrixBlock<MatrixType>::operator()
(
const label i,
const label j
) const
{
#ifdef FULLDEBUG
if (i < 0 || i >= mRows_)
{
FatalErrorInFunction
<< "Index " << i << " out of range 0 ... " << mRows_ - 1
<< abort(FatalError);
}
if (j < 0 || j >= nCols_)
{
FatalErrorInFunction
<< "Index " << j << " out of range 0 ... " << nCols_ - 1
<< abort(FatalError);
}
#endif
return matrix_(i + rowStart_, j + colStart_);
}
template<class MatrixType>
inline const typename MatrixType::cmptType&
tnbLib::MatrixBlock<MatrixType>::operator()
(
const label i,
const label j
) const
{
#ifdef FULLDEBUG
if (i < 0 || i >= mRows_)
{
FatalErrorInFunction
<< "Index " << i << " out of range 0 ... " << mRows_ - 1
<< abort(FatalError);
}
if (j < 0 || j >= nCols_)
{
FatalErrorInFunction
<< "Index " << j << " out of range 0 ... " << nCols_ - 1
<< abort(FatalError);
}
#endif
return matrix_(i + rowStart_, j + colStart_);
}
template<class MatrixType>
inline typename MatrixType::cmptType&
tnbLib::MatrixBlock<MatrixType>::operator()
(
const label i,
const label j
)
{
#ifdef FULLDEBUG
if (i < 0 || i >= mRows_)
{
FatalErrorInFunction
<< "Index " << i << " out of range 0 ... " << mRows_ - 1
<< abort(FatalError);
}
if (j < 0 || j >= nCols_)
{
FatalErrorInFunction
<< "Index " << j << " out of range 0 ... " << nCols_ - 1
<< abort(FatalError);
}
#endif
return matrix_(i + rowStart_, j + colStart_);
}
// ************************************************************************* // | [
"aasoleimani86@gmail.com"
] | aasoleimani86@gmail.com |
f1195657dae903df0bf61ba8b86467e0e76d9f9d | 0d99bcb8b8717008c1ec9b080c6c86c2b1710eee | /날씨/build/Android/Preview2/app/src/main/include/Uno.Diagnostics.Debug.h | 03ef24c822fc4c037988e3e8fe87d84c7dcb58ac | [] | no_license | shj4849/Fuse | 526d92bc49a0a2d8087beece987b1701dc35cccc | 447f49f96f9dadf203f5f91e8a1d67f19d8ecc04 | refs/heads/master | 2021-05-15T23:08:09.523726 | 2017-12-21T05:28:53 | 2017-12-21T05:28:53 | 106,758,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,594 | h | // This file was generated based on C:/Users/t2/AppData/Local/Fusetools/Packages/UnoCore/1.4.3/Source/Uno/Diagnostics/Debug.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.h>
namespace g{namespace Uno{namespace Diagnostics{struct Debug;}}}
namespace g{
namespace Uno{
namespace Diagnostics{
// public static class Debug :26
// {
uClassType* Debug_typeof();
void Debug__Assert_fn(bool* value, uString* expression, uString* filename, int* line, uArray* operands);
void Debug__EmitLog_fn(uString* message, int* type);
void Debug__Log3_fn(uString* message);
void Debug__Log4_fn(uString* message, int* type);
void Debug__Log5_fn(uString* message, int* type, uString* filename, int* line);
void Debug__SetLogHandler_fn(uDelegate* handler);
struct Debug : uObject
{
static uSStrong<uDelegate*> _assertionHandler_;
static uSStrong<uDelegate*>& _assertionHandler() { return _assertionHandler_; }
static uSStrong<uDelegate*> _logHandler_;
static uSStrong<uDelegate*>& _logHandler() { return _logHandler_; }
static uSStrong<uString*> _indentStr_;
static uSStrong<uString*>& _indentStr() { return _indentStr_; }
static void Assert(bool value, uString* expression, uString* filename, int line, uArray* operands);
static void EmitLog(uString* message, int type);
static void Log3(uString* message);
static void Log4(uString* message, int type);
static void Log5(uString* message, int type, uString* filename, int line);
static void SetLogHandler(uDelegate* handler);
};
// }
}}} // ::g::Uno::Diagnostics
| [
"shj4849@naver.com"
] | shj4849@naver.com |
86ba6e3ba49727944f553951308ca27bf440105a | a2dff12b688bf1d00f2c6a83ee1ffe8853fa4f53 | /Homework 6_2/Movie.cpp | 4f908af48b4413046cf14cb3b3b9e8913e52a3cc | [] | no_license | BuiltInParris/CS172 | d86886c6475dd4b36d840a0341dd73452fc27357 | c41ac57473bf068091e4e014325e43284f5e83a1 | refs/heads/master | 2016-09-03T06:25:37.261724 | 2015-05-12T19:51:10 | 2015-05-12T19:51:10 | 35,509,371 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,998 | cpp |
#include "Movie.h"
#include "Actor.h"
#include "List.h"
using namespace std;
vector<string> blank;
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//Blank Movie constructor, if no parameters, set values to null
Movie::Movie()
{
title_ = "";
director_ = "";
rating_ = Movie_Rating();
year_ = 0;
url_ = "";
}
//Title Movie constructor, if only title, assign title value and leave rest blank
Movie::Movie(const string& title)
{
title_ = title;
director_ = "";
rating_ = Movie_Rating();
year_ = 0;
url_ = "";
}
//Full Movie constructor, assign values passed to the attributes of the object in the class
Movie::Movie(const string& title = "",
const string& director = "",
Movie_Rating rating = Movie_Rating(),
unsigned int year = 0,
const string& path = "")
{
title_ = title;
director_ = director;
rating_ = rating;
year_ = year;
url_ = path;
}
//copy constructor
Movie::Movie(const Movie &old)
{
title_ = old.getName();
director_ = old.getDirector();
rating_ = old.getRating();
year_ = old.getYear();
url_ = old.getURL();
}
Movie::~Movie()
{
actorList_.clear();
}
string Movie::getName() const
{
return title_;
}
string Movie::getDirector() const
{
return director_;
}
Movie_Rating Movie::getRating() const
{
return rating_;
}
unsigned int Movie::getYear() const
{
return year_;
}
string Movie::getURL() const
{
return url_;
}
int Movie::getNumberOfActors() const
{
return numActors_;
}
string Movie::getActorName(int i) const
{
//---------------------------------------------------------------------
// Retrieves point i from the polygon.
//---------------------------------------------------------------------
return actorList_[i]->getName();
}
Actor *Movie::getActor(int i) const
{
return actorList_[i];
}
void Movie::setName(const string& title)
{
title_ = title;
}
void Movie::setDirector(const string& director)
{
director_ = director;
}
void Movie::setRating(Movie_Rating rating)
{
rating_ = rating;
}
void Movie::setYear(unsigned int year)
{
year_ = year;
}
void Movie::setURL(const string& path)
{
url_ = path;
}
void Movie::addActor(Actor *p)
{
//---------------------------------------------------------------------
// Adds a new point to the end of the list.
//---------------------------------------------------------------------
numActors_++;
actorList_.push_back(p);
}
void Movie::output(ostream & out)
{
Movie_Rating rating = this->getRating();
string nmRating;
//this->command() is the same as (*this).command()
//both of these call the object that you call the function on Ex:
// Movie.getRating(PARAMETER) "Movie" is the (*this) or this->
// so, when you're trying to compare two different English_length's, you use the object argument and the one it's being performed on.
//"Movie" is the thing it's being performed on, PARAMETER is the object argument, then you just compare their values
// Convert Movie_Rating to string
if (rating == G)
nmRating = "G";
if (rating == PG)
nmRating = "PG";
if (rating == PG13)
nmRating = "PG13";
if (rating == R)
nmRating = "R";
if (rating == NC17)
nmRating = "NC17";
if (rating == NR)
nmRating = "NR";
// Output the information to the source passed
out << "Movie: " << this->getName() << endl; // this returns a string
out << "Director: " << this->getDirector() << endl; //this returns a string
out << "Year: " << this->getYear() << endl; // this returns an integer
out << "Rating: " << nmRating << endl; // this would return a Movie_Rating which has no cout function so it had to be transformed above
out << "IMDB URL: " << this->getURL() << endl << endl; // this returns a string
out << "Actors: " << endl;
for (int j = 0; j < this->getNumberOfActors(); j++)
{
cout << this->getActorName(j) << endl;
}
}
ostream& operator<< (ostream & out, Movie & myFile)
{
myFile.output(out);
return out;
}
| [
"stevie.parris@gmail.com"
] | stevie.parris@gmail.com |
7c6dfe59a95aefb31914add709c172509ba2bc08 | ecc9168f5cbc90e68aa7f02acee51469d2077cea | /3rdparty/flann/util/.svn/text-base/saving.h.svn-base | f10162b6bd94a83adf22522e4ee7399cb66d601c | [
"JasPer-2.0"
] | permissive | NaterGator/AndroidOpenCV_mods | d98f05ab70191c212816b0fc8e16497d7bb991d6 | f49ed426e997cf615befb70282e892065caa7656 | refs/heads/master | 2021-01-25T07:28:20.427815 | 2010-11-26T06:26:30 | 2010-11-26T06:26:30 | 1,113,889 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,566 | /***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* THE BSD LICENSE
*
* 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 THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR 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.
*************************************************************************/
#ifndef SAVING_H_
#define SAVING_H_
#include "constants.h"
#include "nn_index.h"
namespace cvflann
{
/**
* Structure representing the index header.
*/
struct IndexHeader
{
char signature[16];
int flann_version;
flann_algorithm_t index_type;
int rows;
int cols;
};
/**
* Saves index header to stream
*
* @param stream - Stream to save to
* @param index - The index to save
*/
void save_header(FILE* stream, const NNIndex& index);
/**
*
* @param stream - Stream to load from
* @return Index header
*/
IndexHeader load_header(FILE* stream);
template<typename T>
void save_value(FILE* stream, const T& value, int count = 1)
{
fwrite(&value, sizeof(value),count, stream);
}
template<typename T>
void load_value(FILE* stream, T& value, int count = 1)
{
int read_cnt = fread(&value, sizeof(value),count, stream);
if (read_cnt!=count) {
throw FLANNException("Cannot read from file");
}
}
}
#endif /* SAVING_H_ */
| [
"nweibley@gmail.com"
] | nweibley@gmail.com | |
c20e3633bde5617cd837851e805c31dd13460981 | 8fc7f429d2badfe59d6070e6f6e3d6e896f5d5c9 | /list.h | f0e8dea7cf00ea172ed29c8b979cd00c862edb29 | [] | no_license | TLGKien/QL-Sinh-Vien | 20d12be3e9a3435ec64ca23b352ab6fd037e1426 | 60302671f0a72d89d74177130827ecd33ef35613 | refs/heads/master | 2023-02-10T21:49:19.352579 | 2021-01-06T02:21:54 | 2021-01-06T02:21:54 | 327,173,710 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,189 | h | #pragma once
#include <vector>
#include <fstream>
#include "student.h"
#define CNTT1 "CNTT1"
#define CNTT2 "CNTT2"
#define BDATTT "BDATTT"
#define ANHTTT "ANHTTT"
#define DTH "DTH"
//definition of class "list"
class list
{
private:
vector<student> studentList;
bool checkClassID(char[]);
bool checkStudentID(char[]);
bool verify(student);
void delOrEdit(int);
public:
void outputToFile();
void inputFromFile();
list();
void addStudent();
void editProfile(int);
void deleteStudent(int);
int printList(bool,int&);
void sort(int, int);
void search(int, int);
void statistic();
vector<student>* getList(){return &studentList;};
};
list::list()
{}
// function to update structure data from binary file
void list::inputFromFile()
{
student tmp;
ifstream ifs("data.dat",ios::binary);
while(true)
{
ifs.read((char*)&tmp,sizeof(student));
if(ifs.eof()) break;
studentList.push_back(tmp);
}
ifs.close();
}
// function to output structure data to binary file
void list::outputToFile()
{
ofstream ofs("data.dat",ios::binary);
for (int i = 0; i < (int)studentList.size(); ++i)
ofs.write((char*)&studentList[i],sizeof(student));
ofs.close();
}
| [
"kienmathip1999@gmail.com"
] | kienmathip1999@gmail.com |
837c1dbc39cb189c2afd1d7d49d666c331844311 | 9f0e4c0d85a78db555f69bb30cede63a6d19fa6b | /problems/medium/695-max-area-of-island.cpp | cdbe380ae3e8ae1ac066acbc12b090c677d39e04 | [
"MIT"
] | permissive | azartheen/leetcode | d00e4c4e02214f275d53895ad38c6f80fef5a3cd | 4610507de3a45be074c414016dddbe2867e470a1 | refs/heads/master | 2022-12-10T09:13:39.809615 | 2020-08-26T12:28:00 | 2020-08-26T12:28:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,845 | cpp | /*
Max Area of Island
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
Example 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
Example 2:
[[0,0,0,0,0,0,0,0]]
Given the above grid, return 0.
Note: The length of each dimension in the given grid does not exceed 50.
*/
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int r=(int)grid.size();
int c=(int)grid[0].size();
int ans=0;
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
// perform dfs to find out the max value
if(grid[i][j]) ans=max(ans,dfs(i,j,grid));
}
}
return ans;
}
private:
int ans=0;
int dfs(int i, int j, vector<vector<int>>& grid){
int r=(int)grid.size();
int c=(int)grid[0].size();
// set grid[i][j] to 0 (visited) if it is not out of bound or zero value
if(i>=0&&i<r&&j>=0&&j<c&&grid[i][j]){
grid[i][j]=0;
// add 1 plus the results from 4 directions
return 1+ dfs(i+1,j,grid)+dfs(i-1,j,grid)+dfs(i,j+1,grid)+dfs(i,j-1,grid);
}
return 0;
}
};
static const auto io_sync_off = []() {std::ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);return 0;}(); | [
"wingkwong.code@gmail.com"
] | wingkwong.code@gmail.com |
24ba6082227cd831368de979add6939f26af8836 | 91a8abfc9e71828f6c03d3b1d7fbf760eb47cb81 | /cplusplus/BTreeDB.h | c9cfeaf06a39b64a10feea88914122d109052f5f | [] | no_license | liwenhaosuper/BTreeDatabase | b4e197c37898bb4683af5a202f4a000dfc99e02c | c0e449a6dcd501330353dce6c583047d320a6b65 | refs/heads/master | 2016-09-06T03:58:24.269131 | 2013-11-15T09:19:36 | 2013-11-15T09:19:36 | 14,419,906 | 18 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,994 | h |
#if !defined(__btreedb_h_)
#define __btreedb_h_
#include "DbObj.h"
#include "TreeNode.h"
#include"stdafx.h"
namespace Database
{
class BTreeDB : public Database::RefCount
{
public:
typedef bool (*traverseCallback)(const DbObjPtr&, const DbObjPtr&, int depth);
enum ESeqPos
{
ESP_START = 0, // start iterating through the entire tree
ESP_KEY, // start from the key provided
ESP_CONT // continue from the last position
};
enum ESeqDirection
{
ESD_FORWARD = 0, // iterate forwards through the tree
ESD_BACKWARD // seek backwards through the tree
};
public:
BTreeDB(const std::string& fileName, size_t recSize = -1, size_t keySize = -1, size_t minDegree = 2, compareFn cfn = 0);
~BTreeDB(void);
private:
size_t _recSize; // size of the records to be stored
size_t _keySize; // number of bytes that comprise the key
std::string _fileName; // name of the database file
compareFn _compFunc;
size_t _minDegree;
TreeNodePtr _root;
FILE* _dataFile;
size_t _nodeSize;
private:
struct SFileHeader
{
long rootPos;
size_t recSize;
size_t keySize;
size_t minDegree;
};
private: // internal data manipulation functions (see Cormen, Leiserson, Rivest).
static int _defaultCompare(const DbObjPtr& obj1, const DbObjPtr& obj2);
static int _searchCompare(const DbObjPtr& obj1, const DbObjPtr& obj2);
static bool _searchCallback(const DbObjPtr& obj, const DbObjPtr& ref, int depth);
TreeNodePtr _allocateNode();
void _split(TreeNodePtr& parent, size_t childNum, TreeNodePtr& child);
TreeNodePtr _merge(TreeNodePtr& parent, size_t objNo);
void _insert(const DbObjPtr& key);
void _insertNonFull(TreeNodePtr& node, const DbObjPtr& key);
void _traverse(const TreeNodePtr& node, const DbObjPtr& ref, traverseCallback cbfn, int depth=0);
NodeKeyLocn _search(const TreeNodePtr& node, const DbObjPtr& key, compareFn cfn = 0);
bool _seqNext(NodeKeyLocn& locn, DbObjPtr& rec);
bool _seqPrev(NodeKeyLocn& locn, DbObjPtr& rec);
bool _flush(TreeNodePtr& node, FILE* f);
bool _delete(TreeNodePtr& node, const DbObjPtr& key);
NodeKeyLocn _findPred(TreeNodePtr& node);
NodeKeyLocn _findSucc(TreeNodePtr& node);
public:
void close();
bool open();
bool del(const DbObjPtr& key);
bool put(const DbObjPtr& rec);
bool get(const NodeKeyLocn& locn, DbObjPtr& rec);
bool get(const DbObjPtr& key, DbObjPtr& rec);
void traverse(const DbObjPtr& ref = 0, traverseCallback cbfn = 0);
void findAll(const DbObjPtr& key, DBOBJVECTOR& results);
NodeKeyLocn search(const DbObjPtr& key, compareFn cfn = 0);
bool seq(NodeKeyLocn& locn, DbObjPtr& rec, ESeqDirection sdir = ESD_FORWARD);
bool flush();
size_t getRecSize() const { return _recSize; }
size_t getKeySize() const { return _keySize; }
std::string getFileName() const { return _fileName; }
};
typedef Database::Ptr<BTreeDB> BTreeDBPtr;
};
#endif
| [
"liwenhaosuper@gmail.com"
] | liwenhaosuper@gmail.com |
f6b5fd53601f534a8451d37bc322ba9bfecf73d3 | a551cd04e2f3e7b4a530e35d56acb4231b10ae35 | /solarsystem.hpp | 42efaa2291442e67cf1fa4246f5cbad2c7eb236b | [] | no_license | YuhaiLi78/Solar_System_Simulation | 2eebc632f6041f459339d24c219e71bd906f0272 | c1eefd7b34fa54d6c9ad8528d43806e75eb82612 | refs/heads/master | 2021-06-22T00:02:26.655755 | 2017-07-23T03:07:51 | 2017-07-23T03:07:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 437 | hpp | //
// solarsystem.hpp
// solarsystem
//
#include <GLUT/glut.h>
#include "stars.hpp"
#define STARS_NUM 10
class SolarSystem {
public:
SolarSystem();
~SolarSystem();
void onDisplay();
void onUpdate();
void onKeyboard(unsigned char key, int x, int y);
private:
Star *stars[STARS_NUM];
// define parameters of view
GLdouble viewX, viewY, viewZ;
GLdouble centerX, centerY, centerZ;
GLdouble upX, upY, upZ;
};
| [
"liyuhai6666@gmail.com"
] | liyuhai6666@gmail.com |
46b802139401227e70f22eb8ba9cac27a3945e2f | 518bf342bc4138982af3e2724e75f1d9ca3ba56c | /solutions/1450. Number of Students Doing Homework at a Given Time/1450.cpp | 112e3629e005b1c38353c6bd9929910918a45bc1 | [
"MIT"
] | permissive | walkccc/LeetCode | dae85af7cc689882a84ee5011f0a13a19ad97f18 | a27be41c174565d365cbfe785f0633f634a01b2a | refs/heads/main | 2023-08-28T01:32:43.384999 | 2023-08-20T19:00:45 | 2023-08-20T19:00:45 | 172,231,974 | 692 | 302 | MIT | 2023-08-13T14:48:42 | 2019-02-23T15:46:23 | C++ | UTF-8 | C++ | false | false | 296 | cpp | class Solution {
public:
int busyStudent(vector<int>& startTime, vector<int>& endTime, int queryTime) {
const int n = startTime.size();
int ans = 0;
for (int i = 0; i < n; ++i)
if (startTime[i] <= queryTime && queryTime <= endTime[i])
++ans;
return ans;
}
};
| [
"me@pengyuc.com"
] | me@pengyuc.com |
6942b899312ab8d0f20cb8e946e7dd855e8813cc | e3577d2c658e2e96815e37d0ac4c8a15bf1345df | /snake/Source.cpp | 519c92d89ffbb95cc7b1cfa143e16a276941da8c | [] | no_license | askoropisov/simpl_snake | d2bc96d0047fa7d26f4e5f07eceeb120b9dce9d5 | 961ffea8d1a3c6fddb7bb5b66b3e02d6bea34492 | refs/heads/master | 2023-04-01T10:31:10.211911 | 2021-04-04T10:54:48 | 2021-04-04T10:54:48 | 354,372,423 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 8,580 | cpp |
#include <time.h>
#include <random>
#include <iostream>
#include "glut.h"
#include <ctime>
#include <string>
#include <iomanip>
char ansver = 'y';
int N = 40, M = 40; // size fild
int scale = 12; // distance and scale
int w = scale * N; // widht field
int h = scale * M; // height field
int counter = 0; // counter score
float mass_color[] = {0.1, 0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1 }; //variant colors;
int dir, num = 4; // direction and size.
struct { int x; int y; int z; } s[100]; // size snake
class Barier { // rectangle barier
public:
int left_down_position_x = scale;
int left_down_position_y = scale;
int right_down_position_x = N * scale;
int right_down_position_y = scale;
int right_hight_position_x = N * scale;
int right_hight_position_y = M * scale - 21;
int left_hight_position_x = scale;
int left_hight_position_y = M * scale - 21;
void DrawBarier() { // draw rectangle barier
glBegin(GL_LINE_LOOP);
glColor3f(1, 0, 0);
glVertex3f(left_down_position_x, left_down_position_y, 0);
glVertex3f(right_down_position_x, right_down_position_y, 0);
glVertex3f(right_hight_position_x, right_hight_position_y, 0);
glVertex3f(left_hight_position_x, left_hight_position_y, 0);
glEnd();
}
}barier;
class Target // targets
{
public:
int x, y, z, temp_x, temp_y; // koor-d targets
void New() // create new target
{
temp_x = (barier.left_down_position_x+10 + rand() % barier.right_down_position_x-scale-20) / scale; // x position
temp_y = (barier.left_down_position_y+10+rand() % barier.right_hight_position_y - scale-20) / scale; // y position
z = 0; // z position
for (int k = 0; k < num; k++) {
if ((temp_x==s[k].x && temp_y==s[k].y) // check for spawn target not on snake;
|| (temp_x>= barier.right_down_position_x - 10 - scale // check spawn target in barier
|| temp_x<= barier.left_down_position_x)
|| (temp_y >= barier.right_hight_position_y - 10 - scale
|| temp_y <= barier.left_down_position_y))
m.New();
}
x = temp_x;
y = temp_y;
}
void DrawTarget()
{
srand(time(NULL)); // off psevdorandom
int p = rand() % 10;
float r = mass_color[rand() % 10]; // random red
float g = mass_color[rand() % 10]; // random green
float b = mass_color[rand() % 10]; // random blue
glColor3d(r,g,b); // random color target
glRectf(x * scale, y * scale, (x + 1) * scale, (y+1) * scale);
}
} m;
void Draw() //Debug
{
glColor3f(1, 0, 0); // red color
glBegin(GL_LINES);
for (int i = 0; i < w; i += scale) // draw horizontal line
{
glVertex3f(i, 0, 0); glVertex3f(i, h, 0);
}
for (int j = 0; j < h; j += scale) // draw vertical line
{
glVertex3f(0, j, 0); glVertex3f(w, j, 0);
}
glEnd();
}
void Movement() // all rendering
{
for (int i = num; i > 0; --i) // move snake
{
s[i].x = s[i - 1].x; // Х [i] bloc = i - 1
s[i].y = s[i - 1].y; // ....
}
//direction
if (dir == 0) s[0].y += 1; // to up
if (dir == 1) s[0].x -= 1; // to left
if (dir == 2) s[0].x += 1; // to right
if (dir == 3) s[0].y -= 1; // to down
for (int i = 0; i < 10; i++) // size snake grow up
{
if ((s[0].x == m.x) && (s[0].y == m.y)) // grow up if koor-d head = koor-d target
{
glColor3f(0, 0.5, 0.1);
num++; // size snake ++
counter++;
m.New(); // new target
}
}
// check the borders
if (s[0].x > barier.right_down_position_x/scale-1) { // right border
std::cout << std::endl << std::endl << std::setw(56) << "GAME OVER. YOUR SCORE: " << counter;
//std::cout << "Retry game? (y/n)" << std::endl;
//std::cin >> ansver;
//if (ansver == 'y') goto start;
exit(0);
}
if (s[0].y > barier.left_hight_position_y/scale-1) { // up border
std::cout << std::endl << std::endl << std::setw(56) << "GAME OVER. YOUR SCORE: " << counter;
exit(0);
}
if (s[0].x < barier.left_down_position_x/scale) { // left border
std::cout << std::endl << std::endl << std::setw(56) << "GAME OVER. YOUR SCORE: " << counter;
exit(0);
}
if (s[0].y < barier.left_down_position_y/scale) { // down border
std::cout << std::endl << std::endl << std::setw(56) << "GAME OVER. YOUR SCORE: " << counter;
exit(0);
}
for (int i = 1; i < num; i++) // cutting snake if accidant
if (s[0].x == s[i].x && s[0].y == s[i].y) { // check
num = i; // cutting tail snake
counter = i; // counter = size snake
}
}
void Snake()
{
for (int i = 0; i < num; i++)
{
glRectf(s[i].x * scale, s[i].y * scale, (s[i].x + 1) * scale, (s[i].y +1) * scale);
}
}
void Key(int key, int a, int b) // read keybord
{
switch (key) // switch key
{
case GLUT_KEY_UP:
{
if (dir == 3) dir = 3; // check swap direction
else dir = 0; // move to up
break;
}
case GLUT_KEY_RIGHT:
{
if (dir == 1) dir = 1; // check swap direction
else dir = 2; // move to right
break;
}
case GLUT_KEY_LEFT:
{
if (dir == 2) dir = 2; // check swap direction
else dir = 1; // move to left
break;
}
case GLUT_KEY_DOWN:
{
if (dir == 0) dir = 0; // check swap direction
else dir = 3; // move to down
break;
}
case GLUT_KEY_END: m.New(); break; // spawn new target (for debug)
}
}
//function transfer int in char
void Textout( const char* str, int x, int y, GLfloat red, GLfloat green, GLfloat blue)
{
glColor3f(red, green, blue);
glRasterPos2f(x, y);
int i = 0;
while (str[i] != '\0')
{
glutBitmapCharacter(GLUT_BITMAP_9_BY_15, str[i]);
i++;
glRasterPos2f(x + i * 0.2, y);
}
}
void Display() // general rendering function
{
glClear(GL_COLOR_BUFFER_BIT); // clear window
//character-by-character output of points (посимвольный вывод счета)
Textout("S", barier.left_hight_position_x + 10, barier.left_hight_position_y + 10, 0.8, 0.4, 0);
Textout("C", barier.left_hight_position_x + 20, barier.left_hight_position_y + 10, 0.8, 0.4, 0);
Textout("O", barier.left_hight_position_x + 30, barier.left_hight_position_y + 10, 0.8, 0.4, 0);
Textout("R", barier.left_hight_position_x + 40, barier.left_hight_position_y + 10, 0.8, 0.4, 0);
Textout("E", barier.left_hight_position_x + 50, barier.left_hight_position_y + 10, 0.8, 0.4, 0);
Textout(":", barier.left_hight_position_x + 60, barier.left_hight_position_y + 10, 0.8, 0.4, 0);
int fs = counter / 10; // first symbol score
int ls = counter % 10; // last symbol score
char str[100];
char strl[100];
sprintf_s(str, "%d", fs);
sprintf_s(strl, "%d", ls);
if(counter<10){ // cout last symbol score
Textout(strl, barier.left_hight_position_x + 90, barier.left_hight_position_y + 10, 0.8, 0.4, 0);
}
else { // cout first and last symbol score
Textout(str, barier.left_hight_position_x + 90, barier.left_hight_position_y + 10, 0.8, 0.4, 0);
Textout(strl, barier.left_hight_position_x + 105, barier.left_hight_position_y + 10, 0.8, 0.4, 0);
}
//Draw(); // Debug function (uncomment for debugging)
Snake(); // rendering snake
m.DrawTarget(); // spawn target
barier.DrawBarier(); // rendering barier
glFlush(); // rendering
glutSwapBuffers(); // redraw
}
void timer(int = 0) // Timer
{
Display();
Movement();
glutTimerFunc(100, timer, 0);
}
int main(int argc, char** argv)
{
std::cout <<std::endl<<std::endl<<std::setw(60)<< "Game 'SNAKE' by Artemka =)))0)";
start:
srand(time(0));
for (int i = 0; i < 10; i++) // first draw target
m.New();
s[0].x = 10; // X start position snake
s[0].y = 10; // Y start position snake
s[0].z = 0;
//OpenGL (glut) standart function
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(w, h); //widht and hight window
glutCreateWindow("Snake"); // name window
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 520, 0, 520);
glutDisplayFunc(Display); // "Renderscene"
glutSpecialFunc(Key);
glutTimerFunc(50, timer, 0);
glutMainLoop();
return 0;
//добавить game over при столкновении со стенками
//разобраться с 7границами
} | [
"sckoropisow.ar@yandex.ru"
] | sckoropisow.ar@yandex.ru |
eb8234cce6576365d10feca5560a472c543fe360 | 66330f7a1ff0b8447b4245474ab4de48727fd1c5 | /libs/multiprecision/test/test_mpc_overloads.cpp | 9c737f31e17d153fce6e0c86d58a2694b48c7283 | [
"MIT"
] | permissive | everscalecodes/knapsack-snark | fd3cc6155125ae6ff0fc56aa979f84ba6a8c49c7 | 633515a13906407338a81b9874d964869ddec624 | refs/heads/main | 2023-07-18T06:05:22.319230 | 2021-08-31T16:10:16 | 2021-08-31T16:10:16 | 447,180,824 | 0 | 1 | MIT | 2022-01-12T10:53:21 | 2022-01-12T10:53:20 | null | UTF-8 | C++ | false | false | 1,780 | cpp | // Copyright 2012 John Maddock. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt
#include <type_traits>
#include "test.hpp"
#include <nil/crypto3/multiprecision/mpc.hpp>
#include <boost/math/constants/constants.hpp>
using nil::crypto3::multiprecision::mpc_complex_100;
template<class Complex>
void test_overloads() {
typedef typename Complex::value_type Real;
Complex ya = {5.2, 7.4};
Complex yb = {8.2, 7.3};
Real h = 0.0001;
auto I0 = (ya + yb) * h;
Complex I1 = I0 / 2 + yb * h;
// I1 = I0; // not supposed to work.
Complex z {2, 3};
typename Complex::value_type theta = 0.2;
int n = 2;
using std::sin;
Complex arg = z * sin(theta) - n * theta;
using std::exp;
Real v = 0.2;
Real cotv = 7.8;
Real cscv = 8.2;
Complex den = z + v * cscv * exp(-v * cotv);
nil::crypto3::multiprecision::number<nil::crypto3::multiprecision::backends::mpc_complex_backend<100>> a = 2;
nil::crypto3::multiprecision::number<nil::crypto3::multiprecision::backends::mpc_complex_backend<100>> b = 3;
/*
if (a <= b) {
b = a;
}*/
}
template<class F, class Real>
typename std::result_of_t<F(Real)> some_functional(F f, Real a, Real b) {
if (a <= -boost::math::tools::max_value<Real>()) {
return f(a);
}
return f(b);
}
template<class Complex>
void test_functional() {
typedef typename Complex::value_type Real;
auto f = [](Real x) -> Complex {
Complex z(x, 3);
return z;
};
Real a = 0;
Real b = 1;
Complex result = some_functional(f, a, b);
}
int main() {
test_overloads<mpc_complex_100>();
test_functional<mpc_complex_100>();
}
| [
"curryrasul@gmail.com"
] | curryrasul@gmail.com |
1e9d3c3a537c8a5df6a0f48914e688ce97362380 | 7bea223e054e042f300bb2aeb614fa8950f21033 | /Modbus_Kamread.ino | 0aaf46154b863d9a29fe8e4f445477edcf8fc05b | [] | no_license | daviidw/Modbus_Kamread | 6bb9bc9b0b32f8c52ba8def16ad56449f81f75e6 | c4371df0dcf6a80e07af8d72e98c43393b326714 | refs/heads/master | 2021-01-10T12:50:51.595854 | 2016-04-02T09:14:02 | 2016-04-02T09:14:02 | 55,082,376 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,667 | ino | /*
* Copyright © 2011-2012 Stéphane Raimbault <stephane.raimbault@gmail.com>
* License ISC, see LICENSE for more details.
*/
#include <SimpleModbusSlave.h>
#include <KamRead.h>
#include <ActivityLed.h>
#include <AltSoftSerial.h>
/* Define Pins */
#define LED 13 // onboard led
#define TX_En_Pin 2 // Enable pin for TX transmission
#define Default_Slave_ID 1
//////////////// registers of your slave ///////////////////
enum
{
// just add or remove registers and your good to go...
//0x003C,0x0050,0x004A,0x0056,0x0057,0x0059
MWh_Counter,
KW_Power,
Heat_Flow,
Input_Temp,
Return_Temp,
Delta_In_Out,
Error_Code,
// leave this one
TOTAL_REGS_SIZE
// total number of registers for function 3 and 16 share the same register array
};
unsigned int Total_Errors;
int holdingRegs[TOTAL_REGS_SIZE]; // function 3 and 16 register array
////////////////////////////////////////////////////////////
/* Allocate a mapping of 10 values */
//uint16_t tab_reg[10];
//int tab_reg[10];
//Setup kamstrup interface
// "Heat Energy Counter","Power", "Max power this year", "Input temperature","Return temperature","Delta temperature"
unsigned int Registers[] = {0x003C,0x0050,0x004A,0x0056,0x0057,0x0059};
#define NUMREGS 6
KamRead Kamstrup(1200);
void setup() {
/* The transfer speed is set to 19200 bauds (Eight bits, no parity, One stop bit) */
modbus_configure(19200, Default_Slave_ID, TX_En_Pin, LED, TOTAL_REGS_SIZE, true);
Kamstrup.Setup(holdingRegs, Registers, NUMREGS);
}
void loop() {
Total_Errors = modbus_update(holdingRegs);
Kamstrup.Loop();
//Led_Blink(digitalRead(TX_En_Pin), LED);
}
| [
"david@wikners.se"
] | david@wikners.se |
c76504f6630a8ab27caf86b098621f598444c4e4 | c24181ccfbb66f6c9f8c41923359a7374f39631c | /backup/mutate.cpp | 85160a0e25e4a78bf1883070431043cab1d5263b | [] | no_license | abhi1agarwal/GeneticAlgo | 29d73e046decbc60142177e6325eb7904eb84436 | 3c21f69ba49d8e3dc4208168439e5e7b88b65d08 | refs/heads/master | 2021-03-30T20:25:10.047983 | 2018-03-08T18:56:26 | 2018-03-08T18:56:26 | 124,431,744 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 161 | cpp | void mutateit(vector<dataG>&v, dataG&x)
{
{
int xx=rand()%100000+1;
if (1.0*xx/100000>prom)
return ;
}
int i,j;
for (i=0;i<x.B.size();i++)
{
}
} | [
"abhi.agarwal281295@gmail.com"
] | abhi.agarwal281295@gmail.com |
fde8ceeade5804c4fa975b38dde1853cafabd452 | c2445b8329c7d6e912cc29ca838f41e4c6df6988 | /modules/boost_math/bench/scalar/erfc.cpp | 9492f7a670d5bdd233c128b8c2388bc9f7d4a144 | [
"BSL-1.0"
] | permissive | francescog/nt2 | b88548a8fb26f905e8b237148effe7a41d00fca8 | 1930097285539d3a3a758ec44061ba3a2f7281d9 | refs/heads/master | 2021-01-18T05:54:29.136634 | 2011-06-18T14:59:32 | 2011-06-18T14:59:32 | 1,914,634 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,674 | cpp | //////////////////////////////////////////////////////////////////////////////
/// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand
/// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI
///
/// Distributed under the Boost Software License, Version 1.0
/// See accompanying file LICENSE.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
//////////////////////////////////////////////////////////////////////////////
#define NT2_BENCH_MODULE "nt2 boost_math toolbox - erfc/scalar Mode"
//////////////////////////////////////////////////////////////////////////////
// timing Test behavior of boost_math components in scalar mode
//////////////////////////////////////////////////////////////////////////////
#include <nt2/toolbox/boost_math/include/erfc.hpp>
#include <nt2/sdk/unit/benchmark.hpp>
#include <nt2/sdk/unit/bench_includes.hpp>
#include <cmath>
//////////////////////////////////////////////////////////////////////////////
// scalar runtime benchmark for functor<erfc_> from boost_math
//////////////////////////////////////////////////////////////////////////////
using nt2::boost_math::tag::erfc_;
//////////////////////////////////////////////////////////////////////////////
// range macro
//////////////////////////////////////////////////////////////////////////////
#define RS(T,V1,V2) (T, T(V1) ,T(V2))
namespace n1 {
typedef float T;
typedef nt2::meta::as_integer<T>::type iT;
NT2_TIMING(erfc_,(RS(T,T(-10),T(10))))
}
namespace n2 {
typedef double T;
typedef nt2::meta::as_integer<T>::type iT;
NT2_TIMING(erfc_,(RS(T,T(-10),T(10))))
}
#undef RS
| [
"jtlapreste@gmail.com"
] | jtlapreste@gmail.com |
ed49c599def159867b31c14db3942b86be2715cc | cc71448a6eeb027cc7406d04f36f2a53b422071b | /code_collect/clibs/showdiff.cxx | da3060d7ba5ca2d9a9066a3ccd7a8fc1c7a39886 | [] | no_license | cuibixiong/c_func | e0375d39b018248bfbdc2c15be88d997a0214efa | e06c0394cc5581253cc5400e201c0a17ddea1d77 | refs/heads/master | 2021-07-15T15:47:48.630946 | 2021-04-30T07:56:50 | 2021-04-30T07:56:50 | 10,155,695 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,059 | cxx | #include <iostream>
#include <string>
using namespace std;
string lcs(const string &s1, const string &s2);
void showDiff(const string &s1, const string &s2, const string );
int main(int argc, char **argv) {
string s1, s2;
cin >> s1 >> s2;
string strRes = lcs(s1, s2);
showDiff(s1, s2, strRes);
return 0;
}
string lcs(const string &s1, const string &s2) {
const int rowSize = s1.size() + 1;
const int colSize = s2.size() + 1;
string table[rowSize][colSize];
char rowChar[rowSize];
char colChar[colSize];
int cnt = 0;
rowChar[0] = colChar[0] = '/0';
for (int i = rowSize - 2, cnt = 1; i >= 0; i--, cnt++) {
rowChar[cnt] = s1[i];
}
for (int i = colSize - 2, cnt = 1; i >= 0; i--, cnt++) {
colChar[cnt] = s2[i];
}
char ch1, ch2;
string str1, str2;
for (int i = 1; i < rowSize; i++) {
for (int j = 1; j < colSize; j++) {
ch1 = rowChar[i];
ch2 = colChar[j];
if (ch1 == ch2) {
table[i][j] = ch1 + table[i - 1][j - 1];
} else {
str1 = table[i - 1][j];
str2 = table[i][j - 1];
if (str1.size() == str2.size()) {
table[i][j] = str1 < str2 ? str2 : str1;
} else {
table[i][j] = str1.size() < str2.size() ? str2 : str1;
}
}
}
}
return table[rowSize - 1][colSize - 1];
}
void showDiff(const string &s1, const string &s2, const string sub) {
cout << "LSP: " + sub << endl;
cout << endl;
int tmp = s1.size();
for (int i = 0, j = 0; i < tmp; i++) {
if (s1[i] != sub[j]) {
cout << '-';
} else {
cout << ' ';
j++;
}
}
cout << endl << s1 << endl;
tmp = s2.size();
for (int i = 0, j = 0; i < tmp; i++) {
if (s2[i] != sub[j]) {
cout << '+';
} else {
cout << ' ';
j++;
}
}
cout << endl << s2 << endl;
}
| [
"cuibixiong@gmail.com"
] | cuibixiong@gmail.com |
5048b0c126bc7573d73caefb87e062b1fdc3136c | 38f055a979a0e4acecf5d2a5ad0d0344d1f52db2 | /src/mess/video/hd44780.h | d029ee03d2ab401bf11b49ab45a563e9b6059ed2 | [] | no_license | poliva/mame-rr | 0cc05bed2a80addbb906e97b8f25633496eecab6 | 124dbb66844bc6d8747b19b8483cefa28fb6b7fb | refs/heads/master | 2021-01-22T05:16:42.247183 | 2015-04-24T08:59:22 | 2015-04-24T08:59:22 | 34,506,421 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,654 | h | /***************************************************************************
Hitachi HD44780 LCD controller
***************************************************************************/
#pragma once
#ifndef __HD44780_H__
#define __HD44780_H__
#define MCFG_HD44780_ADD( _tag , _config) \
MCFG_DEVICE_ADD( _tag, HD44780, 0 ) \
MCFG_DEVICE_CONFIG(_config)
//**************************************************************************
// TYPE DEFINITIONS
//**************************************************************************
// ======================> hd44780_interface
struct hd44780_interface
{
UINT8 height; // number of lines
UINT8 width; // chars for line
const UINT8 *custom_layout; // custom display layout (NULL for default)
};
// ======================> hd44780_device
class hd44780_device : public device_t,
public hd44780_interface
{
public:
// construction/destruction
hd44780_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);
// device interface
DECLARE_WRITE8_MEMBER(control_write);
DECLARE_READ8_MEMBER(control_read);
DECLARE_WRITE8_MEMBER(data_write);
DECLARE_READ8_MEMBER(data_read);
int video_update(bitmap_t *bitmap, const rectangle *cliprect);
protected:
// device-level overrides
virtual void device_start();
virtual void device_reset();
virtual void device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr);
virtual void device_config_complete();
virtual bool device_validity_check( emu_options &options, const game_driver &driver ) const;
private:
// internal helper
void set_busy_flag(UINT16 usec);
void update_ac(void);
// internal state
static const device_timer_id BUSY_TIMER = 0;
static const device_timer_id BLINKING_TIMER = 1;
emu_timer *m_blink_timer;
emu_timer *m_busy_timer;
UINT8 m_busy_flag;
UINT8 m_ddram[0x80]; //internal display data RAM
UINT8 m_cgram[0x40]; //internal chargen RAM
INT8 m_ac; //address counter
UINT8 m_ac_mode; //0=DDRAM 1=CGRAM
UINT8 m_data_bus_flag; //0=none 1=write 2=read
INT8 m_cursor_pos; //cursor position
UINT8 m_display_on; //display on/off
UINT8 m_cursor_on; //cursor on/off
UINT8 m_blink_on; //blink on/off
UINT8 m_shift_on; //shift on/off
INT8 m_disp_shift; //display shift
INT8 m_direction; //auto increment/decrement
UINT8 m_data_len; //interface data length 4 or 8 bit
UINT8 m_num_line; //number of lines
UINT8 m_char_size; //char size 5x8 or 5x10
UINT8 m_blink;
};
// device type definition
extern const device_type HD44780;
#endif
| [
"pau@eslack.org"
] | pau@eslack.org |
dfea31530cff4656370ad73ee1d74d6289050f44 | a8cdc86c31dc489b0ee4838c13a43aff6664acd6 | /main.cpp | 708597097bd51b9a0a71c35c068cfa9fa67171d2 | [] | no_license | ErikAguayo/Act11 | 6b2f702dc97e87ca1a641dad1ce5baed4f32df6c | 5ca264ed3e0e4c108bd28113f1ae969771cbc63d | refs/heads/main | 2023-01-01T16:24:31.466475 | 2020-10-27T01:00:22 | 2020-10-27T01:00:22 | 307,546,660 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 513 | cpp | #include <iostream>
#include "dinamico.h"
void modificar(int *a)
{
*a=*a=1;
}
int main()
{
Dinamico dinamico;
dinamico.insertar_final(8);
dinamico.insertar_final(7);
dinamico.insertar_final(6);
dinamico.insertar_final(5);
dinamico.insertar_final(3);
dinamico.insertar_final(4);
dinamico.insertar_final(2);
dinamico.insertar_final(1);
dinamico.insertar_inicio(-20);
dinamico.insertar_inicio(-10);
for (size_t i=0; i< dinamico.size(); i++)
{
cout << dinamico[i] << " ";
}
}
| [
"erik.aguayo2887@alumnos.udg.mx"
] | erik.aguayo2887@alumnos.udg.mx |
2b36b353144c04bca65b01411ecc19c75ccb7662 | 2e324912f1d066a8ae2a89e75792165d6a79060b | /Test/Windows/VirtualKeyBoardMouse_ConfigPort_Test/main.cpp | a5a44155b38d2f6017b3fab1e1615973e35fd88d | [
"MIT"
] | permissive | HEYAHONG/STM32_VirtualKeyBoradMouse | 5f0b7c39d2f8ed41e150715126428e12b8334e34 | b6f6cfd73766db0e98b28c9d98b98de007ae0487 | refs/heads/master | 2022-07-22T11:46:31.587173 | 2020-05-21T04:03:13 | 2020-05-21T04:03:13 | 258,102,476 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,477 | cpp | #include <iostream>
#include "libusb.h"
#include "stdio.h"
/*
本程序主要测试处于配置模式(需安装配置模式驱动,鼠标键盘将失效)下的VirtualKeyBoardMouse的配置接口。
*/
using namespace std;
#define VID 0x483
#define PID 0x572b
#define Config_Interface 0x02
#define OUT_EndPoint 0x04
#define IN_EndPoint 0x85
int main()
{
//初始化libusb库
int r;
r = libusb_init(NULL);
if(r<0)
return r;
//设置libusb debug信息
libusb_set_debug(NULL,0);
//打开设备
libusb_device_handle *hdev=NULL;
if((hdev=libusb_open_device_with_vid_pid(NULL,VID,PID))==NULL)
{
printf("请检查硬件和驱动是否安装正确!\n\r");
libusb_exit(NULL);
return -1;
}
//声明端口
libusb_claim_interface(hdev,Config_Interface);
{//测设读写
unsigned char out[32]="0123456789012345678",in[32]="";
int count=0;
if(libusb_bulk_transfer(hdev,OUT_EndPoint,out,sizeof(out),&count,1000)==0)
printf("\n\r发送数据成功 - %d 字节\n\r",count);
count=0;
if(libusb_bulk_transfer(hdev,IN_EndPoint,in,sizeof(in),&count,4000)==0)
{
printf("\n\r接收数据成功 - %d 字节\n\r",count);
printf((char *)in);
}
}
//关闭USB设备
libusb_close(hdev);
//退出libusb
libusb_exit(NULL);
return 0;
}
| [
"2229388563@qq.com"
] | 2229388563@qq.com |
0ed7529ede8602d4e68fd1b169bc47434f080c51 | 5d06523d5c6da5f877e209d6d6dbfe45f5900f87 | /MFCCClient/MFCCClient/MFCCClientDlg.cpp | 839080ef815e21aef5eb7575ad6a8dc2f185816a | [] | no_license | snandi76/Beautiful_CPP | 9b889eb82ee8db687237a2eefa0f1fbccc826fa2 | 6f3107ade910c7a98106c027468db929f55ee678 | refs/heads/master | 2020-04-16T15:26:28.155375 | 2019-01-20T11:56:04 | 2019-01-20T11:56:04 | 165,702,829 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,086 | cpp |
// MFCCClientDlg.cpp : implementation file
//
#include "stdafx.h"
#include "MFCCClient.h"
#include "MFCCClientDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// Dialog Data
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CMFCCClientDlg dialog
CMFCCClientDlg::CMFCCClientDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(IDD_MFCCCLIENT_DIALOG, pParent)
, m_IP(_T(""))
, m_Port(0)
, m_Msg(_T(""))
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CMFCCClientDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT1, m_IP);
DDX_Text(pDX, IDC_EDIT2, m_Port);
DDX_Text(pDX, IDC_EDIT3, m_Msg);
}
BEGIN_MESSAGE_MAP(CMFCCClientDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON2, &CMFCCClientDlg::OnBnClickedButton2)
ON_BN_CLICKED(IDC_BUTTON1, &CMFCCClientDlg::OnBnClickedButton1)
END_MESSAGE_MAP()
// CMFCCClientDlg message handlers
BOOL CMFCCClientDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
return TRUE; // return TRUE unless you set the focus to a control
}
void CMFCCClientDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CMFCCClientDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CMFCCClientDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CMFCCClientDlg::OnBnClickedButton2()
{//send
// TODO: Add your control notification handler code here
UpdateData(TRUE);
if (m_clientSocket.Send(m_Msg.GetBuffer(m_Msg.GetLength()), m_Msg.GetLength())) {
}
else {
AfxMessageBox(L"Failed to send message");
}
}
void CMFCCClientDlg::OnBnClickedButton1()
{//connect
// TODO: Add your control notification handler code here
UpdateData(TRUE);
m_clientSocket.Create();
if (m_clientSocket.Connect(m_IP, m_Port)) {
AfxMessageBox(L"Connection Successfull");
}
else {
AfxMessageBox(L"Connection Failed");
}
DWORD error = GetLastError();
}
| [
"sunandan.nandi@gmail.com"
] | sunandan.nandi@gmail.com |
bd5412fd25ccef038752146f57cea0ae21b28662 | 03d817a4df718558dca2081a24f87a6ab01e2db6 | /src/chainparamsbase.cpp | a7b377ff1f0e71553310e3887e2d67f3f6e6b01f | [
"MIT"
] | permissive | veroclassic/VeroClassic | f5f9d3752e0a6e8e651a0d5cb516aea0f2562175 | 25853d5d0622eb2cbe6b2f945dc24dd668c1d11e | refs/heads/master | 2021-05-11T23:00:56.869938 | 2018-01-15T07:21:02 | 2018-01-15T07:21:02 | 117,505,598 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,779 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparamsbase.h"
#include "util.h"
#include <assert.h>
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
/**
* Main network
*/
class CBaseMainParams : public CBaseChainParams
{
public:
CBaseMainParams()
{
networkID = CBaseChainParams::MAIN;
nRPCPort = 35154;
}
};
static CBaseMainParams mainParams;
/**
* Testnet (v3)
*/
class CBaseTestNetParams : public CBaseMainParams
{
public:
CBaseTestNetParams()
{
networkID = CBaseChainParams::TESTNET;
nRPCPort = 45154;
strDataDir = "testnet3";
}
};
static CBaseTestNetParams testNetParams;
/*
* Regression test
*/
class CBaseRegTestParams : public CBaseTestNetParams
{
public:
CBaseRegTestParams()
{
networkID = CBaseChainParams::REGTEST;
strDataDir = "regtest";
}
};
static CBaseRegTestParams regTestParams;
/*
* Unit test
*/
class CBaseUnitTestParams : public CBaseMainParams
{
public:
CBaseUnitTestParams()
{
networkID = CBaseChainParams::UNITTEST;
strDataDir = "unittest";
}
};
static CBaseUnitTestParams unitTestParams;
static CBaseChainParams* pCurrentBaseParams = 0;
const CBaseChainParams& BaseParams()
{
assert(pCurrentBaseParams);
return *pCurrentBaseParams;
}
void SelectBaseParams(CBaseChainParams::Network network)
{
switch (network) {
case CBaseChainParams::MAIN:
pCurrentBaseParams = &mainParams;
break;
case CBaseChainParams::TESTNET:
pCurrentBaseParams = &testNetParams;
break;
case CBaseChainParams::REGTEST:
pCurrentBaseParams = ®TestParams;
break;
case CBaseChainParams::UNITTEST:
pCurrentBaseParams = &unitTestParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
CBaseChainParams::Network NetworkIdFromCommandLine()
{
bool fRegTest = GetBoolArg("-regtest", false);
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet && fRegTest)
return CBaseChainParams::MAX_NETWORK_TYPES;
if (fRegTest)
return CBaseChainParams::REGTEST;
if (fTestNet)
return CBaseChainParams::TESTNET;
return CBaseChainParams::MAIN;
}
bool SelectBaseParamsFromCommandLine()
{
CBaseChainParams::Network network = NetworkIdFromCommandLine();
if (network == CBaseChainParams::MAX_NETWORK_TYPES)
return false;
SelectBaseParams(network);
return true;
}
bool AreBaseParamsConfigured()
{
return pCurrentBaseParams != NULL;
}
| [
"35444799+veroclassic@users.noreply.github.com"
] | 35444799+veroclassic@users.noreply.github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.