text
stringlengths
54
60.6k
<commit_before>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/cc/saved_model/loader.h" #include <unordered_set> #include "tensorflow/cc/saved_model/constants.h" #include "tensorflow/cc/saved_model/reader.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/lib/monitoring/counter.h" #include "tensorflow/core/lib/monitoring/sampler.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/protobuf_internal.h" #include "tensorflow/core/protobuf/saved_model.pb.h" #include "tensorflow/core/protobuf/saver.pb.h" #include "tensorflow/core/public/session.h" #include "tensorflow/core/public/session_options.h" #include "tensorflow/core/util/tensor_bundle/naming.h" namespace tensorflow { namespace { auto* load_attempt_count = monitoring::Counter<2>::New( "/tensorflow/cc/saved_model/load_attempt_count", "The number of times a SavedModel was successfully loaded.", "model_path", "status"); auto* load_latency = monitoring::Counter<1>::New( "/tensorflow/cc/saved_model/load_latency", "Latency in microseconds for SavedModels that were successfully loaded.", "model_path"); auto* load_latency_by_stage = monitoring::Sampler<2>::New( { "/tensorflow/cc/saved_model/load_latency_by_stage", // metric name "Distribution of wall time spent (in microseconds) in each stage " "(restore graph from disk, run init graph op, etc) when loading the " "model", "model_path", "stage", }, // Scale of 10, power of 1.5 with bucket count 36 (~20 minutes). monitoring::Buckets::Exponential(10, 1.5, 36)); constexpr char kLoadAttemptFail[] = "fail"; constexpr char kLoadAttemptSuccess[] = "success"; uint64 GetLatencyMicroseconds(const uint64 start_microseconds) { const uint64 end_microseconds = Env::Default()->NowMicros(); // Avoid clock skew. if (end_microseconds < start_microseconds) return 0; return end_microseconds - start_microseconds; } Status LoadMetaGraphIntoSession(const MetaGraphDef& meta_graph_def, const SessionOptions& session_options, std::unique_ptr<Session>* session) { Session* session_p = nullptr; TF_RETURN_IF_ERROR(NewSession(session_options, &session_p)); session->reset(session_p); return (*session)->Create(meta_graph_def.graph_def()); } Tensor CreateStringTensor(const string& value) { Tensor tensor(DT_STRING, TensorShape({})); tensor.scalar<string>()() = value; return tensor; } void AddAssetsTensorsToInputs(const StringPiece export_dir, const std::vector<AssetFileDef>& asset_file_defs, std::vector<std::pair<string, Tensor>>* inputs) { if (asset_file_defs.empty()) { return; } for (auto& asset_file_def : asset_file_defs) { Tensor assets_file_path_tensor = CreateStringTensor(io::JoinPath( export_dir, kSavedModelAssetsDirectory, asset_file_def.filename())); inputs->push_back( {asset_file_def.tensor_info().name(), assets_file_path_tensor}); } } // Like Session::Run(), but uses the Make/Run/ReleaseCallable() API to avoid // leaving behind non-GC'ed state. // // Detailed motivation behind this approach, from ashankar@: // // Each call to Session::Run() that identifies a new subgraph (based on feeds // and fetches) creates some datastructures that live as long as the session // (the partitioned graph, associated executors etc.). // // A pathological case of this would be if say the initialization op // (main_op/legacy_init_op) involves the use of a large constant. Then we // allocate memory for that large constant that will just stick around till the // session dies. With this Callable mechanism, that memory will be released // right after ReleaseCallable returns. // // However, the resource manager state remains. Status RunOnce(const RunOptions& run_options, const std::vector<std::pair<string, Tensor>>& inputs, const std::vector<string>& output_tensor_names, const std::vector<string>& target_node_names, std::vector<Tensor>* outputs, RunMetadata* run_metadata, Session* session) { CallableOptions callable_options; std::vector<Tensor> feed_tensors; *callable_options.mutable_run_options() = run_options; for (const auto& input : inputs) { const string& name = input.first; const Tensor& tensor = input.second; callable_options.add_feed(name); feed_tensors.push_back(tensor); } for (const string& output_tensor_name : output_tensor_names) { callable_options.add_fetch(output_tensor_name); } for (const string& target_node_name : target_node_names) { callable_options.add_target(target_node_name); } Session::CallableHandle callable_handle; TF_RETURN_IF_ERROR(session->MakeCallable(callable_options, &callable_handle)); const Status run_status = session->RunCallable(callable_handle, feed_tensors, outputs, run_metadata); // Be sure to call ReleaseCallable() regardless of the outcome of // RunCallable(). session->ReleaseCallable(callable_handle).IgnoreError(); return run_status; } // RunInitOp will return OK if the initialization op was run successfully. // An empty init_op_name indicates that there are no init ops to run. Status RunInitOp(const RunOptions& run_options, const string& export_dir, const MetaGraphDef& meta_graph_def, const std::vector<AssetFileDef>& asset_file_defs, Session* session, const string& init_op_name) { if (!init_op_name.empty()) { LOG(INFO) << "Running initialization op on SavedModel bundle."; std::vector<std::pair<string, Tensor>> inputs; AddAssetsTensorsToInputs(export_dir, asset_file_defs, &inputs); RunMetadata run_metadata; return RunOnce(run_options, inputs, {}, {init_op_name}, nullptr /* outputs */, &run_metadata, session); } return Status::OK(); } // A SavedModel may store the name of the initialization op to run in the // in the SignatureDef (v2) or a collection (v1). If an init_op collection // exists, then the collection must contain exactly one op. Status GetInitOp(const string& export_dir, const MetaGraphDef& meta_graph_def, string* init_op_name) { const auto& sig_def_map = meta_graph_def.signature_def(); const auto& init_op_sig_it = meta_graph_def.signature_def().find(kSavedModelInitOpSignatureKey); if (init_op_sig_it != sig_def_map.end()) { *init_op_name = init_op_sig_it->second.outputs() .find(kSavedModelInitOpSignatureKey) ->second.name(); return Status::OK(); } const auto& collection_def_map = meta_graph_def.collection_def(); string init_op_collection_key; if (collection_def_map.find(kSavedModelMainOpKey) != collection_def_map.end()) { init_op_collection_key = kSavedModelMainOpKey; } else { init_op_collection_key = kSavedModelLegacyInitOpKey; } const auto init_op_it = collection_def_map.find(init_op_collection_key); if (init_op_it != collection_def_map.end()) { if (init_op_it->second.node_list().value_size() != 1) { return errors::FailedPrecondition( strings::StrCat("Expected exactly one main op in : ", export_dir)); } *init_op_name = init_op_it->second.node_list().value(0); } return Status::OK(); } Status RunRestore(const RunOptions& run_options, const string& export_dir, const StringPiece restore_op_name, const StringPiece variable_filename_const_op_name, const std::vector<AssetFileDef>& asset_file_defs, Session* session) { LOG(INFO) << "Restoring SavedModel bundle."; // Find path to variables to be restored in export directory. const string variables_directory = io::JoinPath(export_dir, kSavedModelVariablesDirectory); // Check for saver checkpoints in v2 format. Models exported in the checkpoint // v2 format will have a variables.index file. The corresponding // variables are stored in the variables.data-?????-of-????? files. const string variables_index_path = io::JoinPath( variables_directory, MetaFilename(kSavedModelVariablesFilename)); if (!Env::Default()->FileExists(variables_index_path).ok()) { LOG(INFO) << "The specified SavedModel has no variables; no checkpoints " "were restored. File does not exist: " << variables_index_path; return Status::OK(); } const string variables_path = io::JoinPath(variables_directory, kSavedModelVariablesFilename); // Add variables to the graph. Tensor variables_path_tensor(DT_STRING, TensorShape({})); variables_path_tensor.scalar<string>()() = variables_path; std::vector<std::pair<string, Tensor>> inputs = { {string(variable_filename_const_op_name), variables_path_tensor}}; AddAssetsTensorsToInputs(export_dir, asset_file_defs, &inputs); RunMetadata run_metadata; return RunOnce(run_options, inputs, {}, {string(restore_op_name)}, nullptr /* outputs */, &run_metadata, session); } Status GetAssetFileDefs(const MetaGraphDef& meta_graph_def, std::vector<AssetFileDef>* asset_file_defs) { // With SavedModel v2, we write asset file def into metagraph instead of // collection, so read from metagraph first. if (meta_graph_def.asset_file_def_size() > 0) { for (const auto& asset : meta_graph_def.asset_file_def()) { asset_file_defs->push_back(asset); } return Status::OK(); } // Fall back to read from collection to be backward compatible with v1. const auto& collection_def_map = meta_graph_def.collection_def(); const auto assets_it = collection_def_map.find(kSavedModelAssetsKey); if (assets_it == collection_def_map.end()) { return Status::OK(); } const auto& any_assets = assets_it->second.any_list().value(); for (const auto& any_asset : any_assets) { AssetFileDef asset_file_def; TF_RETURN_IF_ERROR( ParseAny(any_asset, &asset_file_def, "tensorflow.AssetFileDef")); asset_file_defs->push_back(asset_file_def); } return Status::OK(); } Status LoadSavedModelInternal(const SessionOptions& session_options, const RunOptions& run_options, const string& export_dir, const std::unordered_set<string>& tags, SavedModelBundle* const bundle) { const uint64 read_start_microseconds = Env::Default()->NowMicros(); TF_RETURN_IF_ERROR(ReadMetaGraphDefFromSavedModel(export_dir, tags, &bundle->meta_graph_def)); TF_RETURN_IF_ERROR(LoadMetaGraphIntoSession( bundle->meta_graph_def, session_options, &bundle->session)); std::vector<AssetFileDef> asset_file_defs; TF_RETURN_IF_ERROR( GetAssetFileDefs(bundle->meta_graph_def, &asset_file_defs)); TF_RETURN_IF_ERROR( RunRestore(run_options, export_dir, bundle->meta_graph_def.saver_def().restore_op_name(), bundle->meta_graph_def.saver_def().filename_tensor_name(), asset_file_defs, bundle->session.get())); // Record walltime spent in restoring graph from disk, but postpone metric // increments until graph init finishes. const uint64 restore_graph_walltime = GetLatencyMicroseconds(read_start_microseconds); const uint64 graph_init_start_microseconds = Env::Default()->NowMicros(); string init_op_name; TF_RETURN_IF_ERROR( GetInitOp(export_dir, bundle->meta_graph_def, &init_op_name)); TF_RETURN_IF_ERROR(RunInitOp(run_options, export_dir, bundle->meta_graph_def, asset_file_defs, bundle->session.get(), init_op_name)); load_latency_by_stage->GetCell(export_dir, "restore_graph") ->Add(restore_graph_walltime); // Record wall time spent in init op. load_latency_by_stage->GetCell(export_dir, "init_graph") ->Add(GetLatencyMicroseconds(graph_init_start_microseconds)); return Status::OK(); } } // namespace Status LoadSavedModel(const SessionOptions& session_options, const RunOptions& run_options, const string& export_dir, const std::unordered_set<string>& tags, SavedModelBundle* const bundle) { // TODO(robson): Add tests for the counters. const uint64 start_microseconds = Env::Default()->NowMicros(); const Status status = LoadSavedModelInternal(session_options, run_options, export_dir, tags, bundle); auto log_and_count = [&](const string& status_str) { LOG(INFO) << "SavedModel load for tags { " << str_util::Join(tags, " ") << " }; Status: " << status_str << ". Took " << GetLatencyMicroseconds(start_microseconds) << " microseconds."; load_attempt_count->GetCell(export_dir, status_str)->IncrementBy(1); }; if (status.ok()) { log_and_count(kLoadAttemptSuccess); } else { log_and_count(kLoadAttemptFail); } load_latency->GetCell(export_dir) ->IncrementBy(GetLatencyMicroseconds(start_microseconds)); return status; } bool MaybeSavedModelDirectory(const string& export_dir) { const string saved_model_pb_path = io::JoinPath(export_dir, kSavedModelFilenamePb); const string saved_model_pbtxt_path = io::JoinPath(export_dir, kSavedModelFilenamePbTxt); return Env::Default()->FileExists(saved_model_pb_path).ok() || Env::Default()->FileExists(saved_model_pbtxt_path).ok(); } } // namespace tensorflow <commit_msg>Use Sampler to record warm up latency distribution (by status).<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/cc/saved_model/loader.h" #include <unordered_set> #include "tensorflow/cc/saved_model/constants.h" #include "tensorflow/cc/saved_model/reader.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/lib/monitoring/counter.h" #include "tensorflow/core/lib/monitoring/sampler.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/protobuf_internal.h" #include "tensorflow/core/protobuf/saved_model.pb.h" #include "tensorflow/core/protobuf/saver.pb.h" #include "tensorflow/core/public/session.h" #include "tensorflow/core/public/session_options.h" #include "tensorflow/core/util/tensor_bundle/naming.h" namespace tensorflow { namespace { auto* load_attempt_count = monitoring::Counter<2>::New( "/tensorflow/cc/saved_model/load_attempt_count", "The number of times a SavedModel was successfully loaded.", "model_path", "status"); auto* load_latency = monitoring::Counter<1>::New( "/tensorflow/cc/saved_model/load_latency", "Latency in microseconds for SavedModels that were successfully loaded.", "model_path"); auto* load_latency_by_stage = monitoring::Sampler<2>::New( { "/tensorflow/cc/saved_model/load_latency_by_stage", // metric name "Distribution of wall time spent (in microseconds) in each stage " "(restore graph from disk, run init graph op, etc) when loading the " "model", "model_path", "stage", }, // Scale of 10, power of 1.8 with bucket count 33 (~20 minutes). monitoring::Buckets::Exponential(10, 1.8, 33)); constexpr char kLoadAttemptFail[] = "fail"; constexpr char kLoadAttemptSuccess[] = "success"; uint64 GetLatencyMicroseconds(const uint64 start_microseconds) { const uint64 end_microseconds = Env::Default()->NowMicros(); // Avoid clock skew. if (end_microseconds < start_microseconds) return 0; return end_microseconds - start_microseconds; } Status LoadMetaGraphIntoSession(const MetaGraphDef& meta_graph_def, const SessionOptions& session_options, std::unique_ptr<Session>* session) { Session* session_p = nullptr; TF_RETURN_IF_ERROR(NewSession(session_options, &session_p)); session->reset(session_p); return (*session)->Create(meta_graph_def.graph_def()); } Tensor CreateStringTensor(const string& value) { Tensor tensor(DT_STRING, TensorShape({})); tensor.scalar<string>()() = value; return tensor; } void AddAssetsTensorsToInputs(const StringPiece export_dir, const std::vector<AssetFileDef>& asset_file_defs, std::vector<std::pair<string, Tensor>>* inputs) { if (asset_file_defs.empty()) { return; } for (auto& asset_file_def : asset_file_defs) { Tensor assets_file_path_tensor = CreateStringTensor(io::JoinPath( export_dir, kSavedModelAssetsDirectory, asset_file_def.filename())); inputs->push_back( {asset_file_def.tensor_info().name(), assets_file_path_tensor}); } } // Like Session::Run(), but uses the Make/Run/ReleaseCallable() API to avoid // leaving behind non-GC'ed state. // // Detailed motivation behind this approach, from ashankar@: // // Each call to Session::Run() that identifies a new subgraph (based on feeds // and fetches) creates some datastructures that live as long as the session // (the partitioned graph, associated executors etc.). // // A pathological case of this would be if say the initialization op // (main_op/legacy_init_op) involves the use of a large constant. Then we // allocate memory for that large constant that will just stick around till the // session dies. With this Callable mechanism, that memory will be released // right after ReleaseCallable returns. // // However, the resource manager state remains. Status RunOnce(const RunOptions& run_options, const std::vector<std::pair<string, Tensor>>& inputs, const std::vector<string>& output_tensor_names, const std::vector<string>& target_node_names, std::vector<Tensor>* outputs, RunMetadata* run_metadata, Session* session) { CallableOptions callable_options; std::vector<Tensor> feed_tensors; *callable_options.mutable_run_options() = run_options; for (const auto& input : inputs) { const string& name = input.first; const Tensor& tensor = input.second; callable_options.add_feed(name); feed_tensors.push_back(tensor); } for (const string& output_tensor_name : output_tensor_names) { callable_options.add_fetch(output_tensor_name); } for (const string& target_node_name : target_node_names) { callable_options.add_target(target_node_name); } Session::CallableHandle callable_handle; TF_RETURN_IF_ERROR(session->MakeCallable(callable_options, &callable_handle)); const Status run_status = session->RunCallable(callable_handle, feed_tensors, outputs, run_metadata); // Be sure to call ReleaseCallable() regardless of the outcome of // RunCallable(). session->ReleaseCallable(callable_handle).IgnoreError(); return run_status; } // RunInitOp will return OK if the initialization op was run successfully. // An empty init_op_name indicates that there are no init ops to run. Status RunInitOp(const RunOptions& run_options, const string& export_dir, const MetaGraphDef& meta_graph_def, const std::vector<AssetFileDef>& asset_file_defs, Session* session, const string& init_op_name) { if (!init_op_name.empty()) { LOG(INFO) << "Running initialization op on SavedModel bundle."; std::vector<std::pair<string, Tensor>> inputs; AddAssetsTensorsToInputs(export_dir, asset_file_defs, &inputs); RunMetadata run_metadata; return RunOnce(run_options, inputs, {}, {init_op_name}, nullptr /* outputs */, &run_metadata, session); } return Status::OK(); } // A SavedModel may store the name of the initialization op to run in the // in the SignatureDef (v2) or a collection (v1). If an init_op collection // exists, then the collection must contain exactly one op. Status GetInitOp(const string& export_dir, const MetaGraphDef& meta_graph_def, string* init_op_name) { const auto& sig_def_map = meta_graph_def.signature_def(); const auto& init_op_sig_it = meta_graph_def.signature_def().find(kSavedModelInitOpSignatureKey); if (init_op_sig_it != sig_def_map.end()) { *init_op_name = init_op_sig_it->second.outputs() .find(kSavedModelInitOpSignatureKey) ->second.name(); return Status::OK(); } const auto& collection_def_map = meta_graph_def.collection_def(); string init_op_collection_key; if (collection_def_map.find(kSavedModelMainOpKey) != collection_def_map.end()) { init_op_collection_key = kSavedModelMainOpKey; } else { init_op_collection_key = kSavedModelLegacyInitOpKey; } const auto init_op_it = collection_def_map.find(init_op_collection_key); if (init_op_it != collection_def_map.end()) { if (init_op_it->second.node_list().value_size() != 1) { return errors::FailedPrecondition( strings::StrCat("Expected exactly one main op in : ", export_dir)); } *init_op_name = init_op_it->second.node_list().value(0); } return Status::OK(); } Status RunRestore(const RunOptions& run_options, const string& export_dir, const StringPiece restore_op_name, const StringPiece variable_filename_const_op_name, const std::vector<AssetFileDef>& asset_file_defs, Session* session) { LOG(INFO) << "Restoring SavedModel bundle."; // Find path to variables to be restored in export directory. const string variables_directory = io::JoinPath(export_dir, kSavedModelVariablesDirectory); // Check for saver checkpoints in v2 format. Models exported in the checkpoint // v2 format will have a variables.index file. The corresponding // variables are stored in the variables.data-?????-of-????? files. const string variables_index_path = io::JoinPath( variables_directory, MetaFilename(kSavedModelVariablesFilename)); if (!Env::Default()->FileExists(variables_index_path).ok()) { LOG(INFO) << "The specified SavedModel has no variables; no checkpoints " "were restored. File does not exist: " << variables_index_path; return Status::OK(); } const string variables_path = io::JoinPath(variables_directory, kSavedModelVariablesFilename); // Add variables to the graph. Tensor variables_path_tensor(DT_STRING, TensorShape({})); variables_path_tensor.scalar<string>()() = variables_path; std::vector<std::pair<string, Tensor>> inputs = { {string(variable_filename_const_op_name), variables_path_tensor}}; AddAssetsTensorsToInputs(export_dir, asset_file_defs, &inputs); RunMetadata run_metadata; return RunOnce(run_options, inputs, {}, {string(restore_op_name)}, nullptr /* outputs */, &run_metadata, session); } Status GetAssetFileDefs(const MetaGraphDef& meta_graph_def, std::vector<AssetFileDef>* asset_file_defs) { // With SavedModel v2, we write asset file def into metagraph instead of // collection, so read from metagraph first. if (meta_graph_def.asset_file_def_size() > 0) { for (const auto& asset : meta_graph_def.asset_file_def()) { asset_file_defs->push_back(asset); } return Status::OK(); } // Fall back to read from collection to be backward compatible with v1. const auto& collection_def_map = meta_graph_def.collection_def(); const auto assets_it = collection_def_map.find(kSavedModelAssetsKey); if (assets_it == collection_def_map.end()) { return Status::OK(); } const auto& any_assets = assets_it->second.any_list().value(); for (const auto& any_asset : any_assets) { AssetFileDef asset_file_def; TF_RETURN_IF_ERROR( ParseAny(any_asset, &asset_file_def, "tensorflow.AssetFileDef")); asset_file_defs->push_back(asset_file_def); } return Status::OK(); } Status LoadSavedModelInternal(const SessionOptions& session_options, const RunOptions& run_options, const string& export_dir, const std::unordered_set<string>& tags, SavedModelBundle* const bundle) { const uint64 read_start_microseconds = Env::Default()->NowMicros(); TF_RETURN_IF_ERROR(ReadMetaGraphDefFromSavedModel(export_dir, tags, &bundle->meta_graph_def)); TF_RETURN_IF_ERROR(LoadMetaGraphIntoSession( bundle->meta_graph_def, session_options, &bundle->session)); std::vector<AssetFileDef> asset_file_defs; TF_RETURN_IF_ERROR( GetAssetFileDefs(bundle->meta_graph_def, &asset_file_defs)); TF_RETURN_IF_ERROR( RunRestore(run_options, export_dir, bundle->meta_graph_def.saver_def().restore_op_name(), bundle->meta_graph_def.saver_def().filename_tensor_name(), asset_file_defs, bundle->session.get())); // Record walltime spent in restoring graph from disk, but postpone metric // increments until graph init finishes. const uint64 restore_graph_walltime = GetLatencyMicroseconds(read_start_microseconds); const uint64 graph_init_start_microseconds = Env::Default()->NowMicros(); string init_op_name; TF_RETURN_IF_ERROR( GetInitOp(export_dir, bundle->meta_graph_def, &init_op_name)); TF_RETURN_IF_ERROR(RunInitOp(run_options, export_dir, bundle->meta_graph_def, asset_file_defs, bundle->session.get(), init_op_name)); load_latency_by_stage->GetCell(export_dir, "restore_graph") ->Add(restore_graph_walltime); // Record wall time spent in init op. load_latency_by_stage->GetCell(export_dir, "init_graph") ->Add(GetLatencyMicroseconds(graph_init_start_microseconds)); return Status::OK(); } } // namespace Status LoadSavedModel(const SessionOptions& session_options, const RunOptions& run_options, const string& export_dir, const std::unordered_set<string>& tags, SavedModelBundle* const bundle) { // TODO(robson): Add tests for the counters. const uint64 start_microseconds = Env::Default()->NowMicros(); const Status status = LoadSavedModelInternal(session_options, run_options, export_dir, tags, bundle); auto log_and_count = [&](const string& status_str) { LOG(INFO) << "SavedModel load for tags { " << str_util::Join(tags, " ") << " }; Status: " << status_str << ". Took " << GetLatencyMicroseconds(start_microseconds) << " microseconds."; load_attempt_count->GetCell(export_dir, status_str)->IncrementBy(1); }; if (status.ok()) { log_and_count(kLoadAttemptSuccess); } else { log_and_count(kLoadAttemptFail); } load_latency->GetCell(export_dir) ->IncrementBy(GetLatencyMicroseconds(start_microseconds)); return status; } bool MaybeSavedModelDirectory(const string& export_dir) { const string saved_model_pb_path = io::JoinPath(export_dir, kSavedModelFilenamePb); const string saved_model_pbtxt_path = io::JoinPath(export_dir, kSavedModelFilenamePbTxt); return Env::Default()->FileExists(saved_model_pb_path).ok() || Env::Default()->FileExists(saved_model_pbtxt_path).ok(); } } // namespace tensorflow <|endoftext|>
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/framework/common_shape_fns.h" #include "tensorflow/core/framework/numeric_op.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/shape_inference.h" namespace tensorflow { using shape_inference::DimensionHandle; using shape_inference::InferenceContext; using shape_inference::ShapeHandle; REGISTER_OP("FFT") .Input("input: complex64") .Output("output: complex64") .SetShapeFn([](InferenceContext* c) { return shape_inference::UnchangedShapeWithRankAtLeast(c, 1); }) .Doc(R"doc( Compute the 1-dimensional discrete Fourier Transform over the inner-most dimension of `input`. input: A complex64 tensor. output: A complex64 tensor of the same shape as `input`. The inner-most dimension of `input` is replaced with its 1D Fourier Transform. @compatibility(numpy) Equivalent to np.fft.fft @end_compatibility )doc"); REGISTER_OP("IFFT") .Input("input: complex64") .Output("output: complex64") .SetShapeFn([](InferenceContext* c) { return shape_inference::UnchangedShapeWithRankAtLeast(c, 1); }) .Doc(R"doc( Compute the inverse 1-dimensional discrete Fourier Transform over the inner-most dimension of `input`. input: A complex64 tensor. output: A complex64 tensor of the same shape as `input`. The inner-most dimension of `input` is replaced with its inverse 1D Fourier Transform. @compatibility(numpy) Equivalent to np.fft.ifft @end_compatibility )doc"); REGISTER_OP("FFT2D") .Input("input: complex64") .Output("output: complex64") .SetShapeFn([](InferenceContext* c) { return shape_inference::UnchangedShapeWithRankAtLeast(c, 2); }) .Doc(R"doc( Compute the 2-dimensional discrete Fourier Transform over the inner-most 2 dimensions of `input`. input: A complex64 tensor. output: A complex64 tensor of the same shape as `input`. The inner-most 2 dimensions of `input` are replaced with their 2D Fourier Transform. @compatibility(numpy) Equivalent to np.fft.fft2 @end_compatibility )doc"); REGISTER_OP("IFFT2D") .Input("input: complex64") .Output("output: complex64") .SetShapeFn([](InferenceContext* c) { return shape_inference::UnchangedShapeWithRankAtLeast(c, 2); }) .Doc(R"doc( Compute the inverse 2-dimensional discrete Fourier Transform over the inner-most 2 dimensions of `input`. input: A complex64 tensor. output: A complex64 tensor of the same shape as `input`. The inner-most 2 dimensions of `input` are replaced with their inverse 2D Fourier Transform. @compatibility(numpy) Equivalent to np.fft.ifft2 @end_compatibility )doc"); REGISTER_OP("FFT3D") .Input("input: complex64") .Output("output: complex64") .SetShapeFn([](InferenceContext* c) { return shape_inference::UnchangedShapeWithRankAtLeast(c, 3); }) .Doc(R"doc( Compute the 3-dimensional discrete Fourier Transform over the inner-most 3 dimensions of `input`. input: A complex64 tensor. output: A complex64 tensor of the same shape as `input`. The inner-most 3 dimensions of `input` are replaced with their 3D Fourier Transform. @compatibility(numpy) Equivalent to np.fft.fftn with 3 dimensions. @end_compatibility )doc"); REGISTER_OP("IFFT3D") .Input("input: complex64") .Output("output: complex64") .SetShapeFn([](InferenceContext* c) { return shape_inference::UnchangedShapeWithRankAtLeast(c, 3); }) .Doc(R"doc( Compute the inverse 3-dimensional discrete Fourier Transform over the inner-most 3 dimensions of `input`. input: A complex64 tensor. output: A complex64 tensor of the same shape as `input`. The inner-most 3 dimensions of `input` are replaced with their inverse 3D Fourier Transform. @compatibility(numpy) Equivalent to np.fft.ifftn with 3 dimensions. @end_compatibility )doc"); Status RFFTShape(InferenceContext* c, const bool forward, const int rank) { ShapeHandle out; TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), rank, &out)); // Check that fft_length has shape [rank]. ShapeHandle unused_shape; DimensionHandle unused_dim; ShapeHandle fft_length_input = c->input(1); TF_RETURN_IF_ERROR(c->WithRank(fft_length_input, 1, &unused_shape)); TF_RETURN_IF_ERROR( c->WithValue(c->Dim(fft_length_input, 0), rank, &unused_dim)); const Tensor* fft_length_tensor = c->input_tensor(1); // If fft_length is unknown at graph creation time, we can't predict the // output size. if (fft_length_tensor == nullptr) { // We can't know the dimension of any of the rank inner dimensions of the // output without knowing fft_length. for (int i = 0; i < rank; ++i) { TF_RETURN_IF_ERROR(c->ReplaceDim(out, -rank + i, c->UnknownDim(), &out)); } } else { auto fft_length_as_vec = fft_length_tensor->vec<int32>(); for (int i = 0; i < rank; ++i) { // For RFFT, replace the last dimension with fft_length/2 + 1. auto dim = forward && i == rank - 1 && fft_length_as_vec(i) != 0 ? fft_length_as_vec(i) / 2 + 1 : fft_length_as_vec(i); TF_RETURN_IF_ERROR(c->ReplaceDim(out, -rank + i, c->MakeDim(dim), &out)); } } c->set_output(0, out); return Status::OK(); } REGISTER_OP("RFFT") .Input("input: float") .Input("fft_length: int32") .Output("output: complex64") .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, true, 1); }) .Doc(R"doc( Compute the 1-dimensional discrete Fourier Transform of a real-valued signal over the inner-most dimension of `input`. Since the DFT of a real signal is Hermitian-symmetric, `RFFT` only returns the `fft_length / 2 + 1` unique components of the FFT: the zero-frequency term, followed by the `fft_length / 2` positive-frequency terms. input: A float32 tensor. fft_length: An int32 tensor of shape [1]. The FFT length. output: A complex64 tensor of the same rank as `input`. The inner-most dimension of `input` is replaced with the `fft_length / 2 + 1` unique frequency components of its 1D Fourier Transform. @compatibility(numpy) Equivalent to np.fft.rfft @end_compatibility )doc"); REGISTER_OP("IRFFT") .Input("input: complex64") .Input("fft_length: int32") .Output("output: float") .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, false, 1); }) .Doc(R"doc( Compute the inverse 1-dimensional discrete Fourier Transform of a real-valued signal over the inner-most dimension of `input`. The inner-most dimension of `input` is assumed to be the result of `RFFT`: the `fft_length / 2 + 1` unique components of the DFT of a real-valued signal. If `fft_length` is not provided, it is computed from the size of the inner-most dimension of `input` (`fft_length = 2 * (inner - 1)`). If the FFT length used to compute `input` is odd, it should be provided since it cannot be inferred properly. input: A complex64 tensor. fft_length: An int32 tensor of shape [1]. The FFT length. output: A float32 tensor of the same rank as `input`. The inner-most dimension of `input` is replaced with the `fft_length` samples of its inverse 1D Fourier Transform. @compatibility(numpy) Equivalent to np.fft.irfft @end_compatibility )doc"); REGISTER_OP("RFFT2D") .Input("input: float") .Input("fft_length: int32") .Output("output: complex64") .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, true, 2); }) .Doc(R"doc( Compute the 2-dimensional discrete Fourier Transform of a real-valued signal over the inner-most 2 dimensions of `input`. Since the DFT of a real signal is Hermitian-symmetric, `RFFT2D` only returns the `fft_length / 2 + 1` unique components of the FFT for the inner-most dimension of `output`: the zero-frequency term, followed by the `fft_length / 2` positive-frequency terms. input: A float32 tensor. fft_length: An int32 tensor of shape [2]. The FFT length for each dimension. output: A complex64 tensor of the same rank as `input`. The inner-most 2 dimensions of `input` are replaced with their 2D Fourier Transform. The inner-most dimension contains `fft_length / 2 + 1` unique frequency components. @compatibility(numpy) Equivalent to np.fft.rfft2 @end_compatibility )doc"); REGISTER_OP("IRFFT2D") .Input("input: complex64") .Input("fft_length: int32") .Output("output: float") .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, false, 2); }) .Doc(R"doc( Compute the inverse 2-dimensional discrete Fourier Transform of a real-valued signal over the inner-most 2 dimensions of `input`. The inner-most 2 dimensions of `input` are assumed to be the result of `RFFT2D`: The inner-most dimension contains the `fft_length / 2 + 1` unique components of the DFT of a real-valued signal. If `fft_length` is not provided, it is computed from the size of the inner-most 2 dimensions of `input`. If the FFT length used to compute `input` is odd, it should be provided since it cannot be inferred properly. input: A complex64 tensor. fft_length: An int32 tensor of shape [2]. The FFT length for each dimension. output: A float32 tensor of the same rank as `input`. The inner-most 2 dimensions of `input` are replaced with the `fft_length` samples of their inverse 2D Fourier Transform. @compatibility(numpy) Equivalent to np.fft.irfft2 @end_compatibility )doc"); REGISTER_OP("RFFT3D") .Input("input: float") .Input("fft_length: int32") .Output("output: complex64") .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, true, 3); }) .Doc(R"doc( Compute the 3-dimensional discrete Fourier Transform of a real-valued signal over the inner-most 3 dimensions of `input`. Since the DFT of a real signal is Hermitian-symmetric, `RFFT3D` only returns the `fft_length / 2 + 1` unique components of the FFT for the inner-most dimension of `output`: the zero-frequency term, followed by the `fft_length / 2` positive-frequency terms. input: A float32 tensor. fft_length: An int32 tensor of shape [3]. The FFT length for each dimension. output: A complex64 tensor of the same rank as `input`. The inner-most 3 dimensions of `input` are replaced with the their 3D Fourier Transform. The inner-most dimension contains `fft_length / 2 + 1` unique frequency components. @compatibility(numpy) Equivalent to np.fft.rfftn with 3 dimensions. @end_compatibility )doc"); REGISTER_OP("IRFFT3D") .Input("input: complex64") .Input("fft_length: int32") .Output("output: float") .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, false, 3); }) .Doc(R"doc( Compute the inverse 3-dimensional discrete Fourier Transform of a real-valued signal over the inner-most 3 dimensions of `input`. The inner-most 3 dimensions of `input` are assumed to be the result of `RFFT3D`: The inner-most dimension contains the `fft_length / 2 + 1` unique components of the DFT of a real-valued signal. If `fft_length` is not provided, it is computed from the size of the inner-most 3 dimensions of `input`. If the FFT length used to compute `input` is odd, it should be provided since it cannot be inferred properly. input: A complex64 tensor. fft_length: An int32 tensor of shape [3]. The FFT length for each dimension. output: A float32 tensor of the same rank as `input`. The inner-most 3 dimensions of `input` are replaced with the `fft_length` samples of their inverse 3D real Fourier Transform. @compatibility(numpy) Equivalent to np.irfftn with 3 dimensions. @end_compatibility )doc"); // Deprecated ops: REGISTER_OP("BatchFFT") .Input("input: complex64") .Output("output: complex64") .Deprecated(15, "Use FFT"); REGISTER_OP("BatchIFFT") .Input("input: complex64") .Output("output: complex64") .Deprecated(15, "Use IFFT"); REGISTER_OP("BatchFFT2D") .Input("input: complex64") .Output("output: complex64") .Deprecated(15, "Use FFT2D"); REGISTER_OP("BatchIFFT2D") .Input("input: complex64") .Output("output: complex64") .Deprecated(15, "Use IFFT2D"); REGISTER_OP("BatchFFT3D") .Input("input: complex64") .Output("output: complex64") .Deprecated(15, "Use FFT3D"); REGISTER_OP("BatchIFFT3D") .Input("input: complex64") .Output("output: complex64") .Deprecated(15, "Use IFFT3D"); } // namespace tensorflow <commit_msg>Remove extra blank lines from auto-generated Python documentation. Change: 152046128<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/framework/common_shape_fns.h" #include "tensorflow/core/framework/numeric_op.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/shape_inference.h" namespace tensorflow { using shape_inference::DimensionHandle; using shape_inference::InferenceContext; using shape_inference::ShapeHandle; REGISTER_OP("FFT") .Input("input: complex64") .Output("output: complex64") .SetShapeFn([](InferenceContext* c) { return shape_inference::UnchangedShapeWithRankAtLeast(c, 1); }) .Doc(R"doc( Fast Fourier transform. Computes the 1-dimensional discrete Fourier transform over the inner-most dimension of `input`. input: A complex64 tensor. output: A complex64 tensor of the same shape as `input`. The inner-most dimension of `input` is replaced with its 1D Fourier transform. @compatibility(numpy) Equivalent to np.fft.fft @end_compatibility )doc"); REGISTER_OP("IFFT") .Input("input: complex64") .Output("output: complex64") .SetShapeFn([](InferenceContext* c) { return shape_inference::UnchangedShapeWithRankAtLeast(c, 1); }) .Doc(R"doc( Inverse fast Fourier transform. Computes the inverse 1-dimensional discrete Fourier transform over the inner-most dimension of `input`. input: A complex64 tensor. output: A complex64 tensor of the same shape as `input`. The inner-most dimension of `input` is replaced with its inverse 1D Fourier transform. @compatibility(numpy) Equivalent to np.fft.ifft @end_compatibility )doc"); REGISTER_OP("FFT2D") .Input("input: complex64") .Output("output: complex64") .SetShapeFn([](InferenceContext* c) { return shape_inference::UnchangedShapeWithRankAtLeast(c, 2); }) .Doc(R"doc( 2D fast Fourier transform. Computes the 2-dimensional discrete Fourier transform over the inner-most 2 dimensions of `input`. input: A complex64 tensor. output: A complex64 tensor of the same shape as `input`. The inner-most 2 dimensions of `input` are replaced with their 2D Fourier transform. @compatibility(numpy) Equivalent to np.fft.fft2 @end_compatibility )doc"); REGISTER_OP("IFFT2D") .Input("input: complex64") .Output("output: complex64") .SetShapeFn([](InferenceContext* c) { return shape_inference::UnchangedShapeWithRankAtLeast(c, 2); }) .Doc(R"doc( Inverse 2D fast Fourier transform. Computes the inverse 2-dimensional discrete Fourier transform over the inner-most 2 dimensions of `input`. input: A complex64 tensor. output: A complex64 tensor of the same shape as `input`. The inner-most 2 dimensions of `input` are replaced with their inverse 2D Fourier transform. @compatibility(numpy) Equivalent to np.fft.ifft2 @end_compatibility )doc"); REGISTER_OP("FFT3D") .Input("input: complex64") .Output("output: complex64") .SetShapeFn([](InferenceContext* c) { return shape_inference::UnchangedShapeWithRankAtLeast(c, 3); }) .Doc(R"doc( 3D fast Fourier transform. Computes the 3-dimensional discrete Fourier transform over the inner-most 3 dimensions of `input`. input: A complex64 tensor. output: A complex64 tensor of the same shape as `input`. The inner-most 3 dimensions of `input` are replaced with their 3D Fourier transform. @compatibility(numpy) Equivalent to np.fft.fftn with 3 dimensions. @end_compatibility )doc"); REGISTER_OP("IFFT3D") .Input("input: complex64") .Output("output: complex64") .SetShapeFn([](InferenceContext* c) { return shape_inference::UnchangedShapeWithRankAtLeast(c, 3); }) .Doc(R"doc( Inverse 3D fast Fourier transform. Computes the inverse 3-dimensional discrete Fourier transform over the inner-most 3 dimensions of `input`. input: A complex64 tensor. output: A complex64 tensor of the same shape as `input`. The inner-most 3 dimensions of `input` are replaced with their inverse 3D Fourier transform. @compatibility(numpy) Equivalent to np.fft.ifftn with 3 dimensions. @end_compatibility )doc"); Status RFFTShape(InferenceContext* c, const bool forward, const int rank) { ShapeHandle out; TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), rank, &out)); // Check that fft_length has shape [rank]. ShapeHandle unused_shape; DimensionHandle unused_dim; ShapeHandle fft_length_input = c->input(1); TF_RETURN_IF_ERROR(c->WithRank(fft_length_input, 1, &unused_shape)); TF_RETURN_IF_ERROR( c->WithValue(c->Dim(fft_length_input, 0), rank, &unused_dim)); const Tensor* fft_length_tensor = c->input_tensor(1); // If fft_length is unknown at graph creation time, we can't predict the // output size. if (fft_length_tensor == nullptr) { // We can't know the dimension of any of the rank inner dimensions of the // output without knowing fft_length. for (int i = 0; i < rank; ++i) { TF_RETURN_IF_ERROR(c->ReplaceDim(out, -rank + i, c->UnknownDim(), &out)); } } else { auto fft_length_as_vec = fft_length_tensor->vec<int32>(); for (int i = 0; i < rank; ++i) { // For RFFT, replace the last dimension with fft_length/2 + 1. auto dim = forward && i == rank - 1 && fft_length_as_vec(i) != 0 ? fft_length_as_vec(i) / 2 + 1 : fft_length_as_vec(i); TF_RETURN_IF_ERROR(c->ReplaceDim(out, -rank + i, c->MakeDim(dim), &out)); } } c->set_output(0, out); return Status::OK(); } REGISTER_OP("RFFT") .Input("input: float") .Input("fft_length: int32") .Output("output: complex64") .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, true, 1); }) .Doc(R"doc( Real-valued fast Fourier transform. Computes the 1-dimensional discrete Fourier transform of a real-valued signal over the inner-most dimension of `input`. Since the DFT of a real signal is Hermitian-symmetric, `RFFT` only returns the `fft_length / 2 + 1` unique components of the FFT: the zero-frequency term, followed by the `fft_length / 2` positive-frequency terms. input: A float32 tensor. fft_length: An int32 tensor of shape [1]. The FFT length. output: A complex64 tensor of the same rank as `input`. The inner-most dimension of `input` is replaced with the `fft_length / 2 + 1` unique frequency components of its 1D Fourier transform. @compatibility(numpy) Equivalent to np.fft.rfft @end_compatibility )doc"); REGISTER_OP("IRFFT") .Input("input: complex64") .Input("fft_length: int32") .Output("output: float") .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, false, 1); }) .Doc(R"doc( Inverse real-valued fast Fourier transform. Computes the inverse 1-dimensional discrete Fourier transform of a real-valued signal over the inner-most dimension of `input`. The inner-most dimension of `input` is assumed to be the result of `RFFT`: the `fft_length / 2 + 1` unique components of the DFT of a real-valued signal. If `fft_length` is not provided, it is computed from the size of the inner-most dimension of `input` (`fft_length = 2 * (inner - 1)`). If the FFT length used to compute `input` is odd, it should be provided since it cannot be inferred properly. input: A complex64 tensor. fft_length: An int32 tensor of shape [1]. The FFT length. output: A float32 tensor of the same rank as `input`. The inner-most dimension of `input` is replaced with the `fft_length` samples of its inverse 1D Fourier transform. @compatibility(numpy) Equivalent to np.fft.irfft @end_compatibility )doc"); REGISTER_OP("RFFT2D") .Input("input: float") .Input("fft_length: int32") .Output("output: complex64") .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, true, 2); }) .Doc(R"doc( 2D real-valued fast Fourier transform. Computes the 2-dimensional discrete Fourier transform of a real-valued signal over the inner-most 2 dimensions of `input`. Since the DFT of a real signal is Hermitian-symmetric, `RFFT2D` only returns the `fft_length / 2 + 1` unique components of the FFT for the inner-most dimension of `output`: the zero-frequency term, followed by the `fft_length / 2` positive-frequency terms. input: A float32 tensor. fft_length: An int32 tensor of shape [2]. The FFT length for each dimension. output: A complex64 tensor of the same rank as `input`. The inner-most 2 dimensions of `input` are replaced with their 2D Fourier transform. The inner-most dimension contains `fft_length / 2 + 1` unique frequency components. @compatibility(numpy) Equivalent to np.fft.rfft2 @end_compatibility )doc"); REGISTER_OP("IRFFT2D") .Input("input: complex64") .Input("fft_length: int32") .Output("output: float") .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, false, 2); }) .Doc(R"doc( Inverse 2D real-valued fast Fourier transform. Computes the inverse 2-dimensional discrete Fourier transform of a real-valued signal over the inner-most 2 dimensions of `input`. The inner-most 2 dimensions of `input` are assumed to be the result of `RFFT2D`: The inner-most dimension contains the `fft_length / 2 + 1` unique components of the DFT of a real-valued signal. If `fft_length` is not provided, it is computed from the size of the inner-most 2 dimensions of `input`. If the FFT length used to compute `input` is odd, it should be provided since it cannot be inferred properly. input: A complex64 tensor. fft_length: An int32 tensor of shape [2]. The FFT length for each dimension. output: A float32 tensor of the same rank as `input`. The inner-most 2 dimensions of `input` are replaced with the `fft_length` samples of their inverse 2D Fourier transform. @compatibility(numpy) Equivalent to np.fft.irfft2 @end_compatibility )doc"); REGISTER_OP("RFFT3D") .Input("input: float") .Input("fft_length: int32") .Output("output: complex64") .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, true, 3); }) .Doc(R"doc( 3D real-valued fast Fourier transform. Computes the 3-dimensional discrete Fourier transform of a real-valued signal over the inner-most 3 dimensions of `input`. Since the DFT of a real signal is Hermitian-symmetric, `RFFT3D` only returns the `fft_length / 2 + 1` unique components of the FFT for the inner-most dimension of `output`: the zero-frequency term, followed by the `fft_length / 2` positive-frequency terms. input: A float32 tensor. fft_length: An int32 tensor of shape [3]. The FFT length for each dimension. output: A complex64 tensor of the same rank as `input`. The inner-most 3 dimensions of `input` are replaced with the their 3D Fourier transform. The inner-most dimension contains `fft_length / 2 + 1` unique frequency components. @compatibility(numpy) Equivalent to np.fft.rfftn with 3 dimensions. @end_compatibility )doc"); REGISTER_OP("IRFFT3D") .Input("input: complex64") .Input("fft_length: int32") .Output("output: float") .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, false, 3); }) .Doc(R"doc( Inverse 3D real-valued fast Fourier transform. Computes the inverse 3-dimensional discrete Fourier transform of a real-valued signal over the inner-most 3 dimensions of `input`. The inner-most 3 dimensions of `input` are assumed to be the result of `RFFT3D`: The inner-most dimension contains the `fft_length / 2 + 1` unique components of the DFT of a real-valued signal. If `fft_length` is not provided, it is computed from the size of the inner-most 3 dimensions of `input`. If the FFT length used to compute `input` is odd, it should be provided since it cannot be inferred properly. input: A complex64 tensor. fft_length: An int32 tensor of shape [3]. The FFT length for each dimension. output: A float32 tensor of the same rank as `input`. The inner-most 3 dimensions of `input` are replaced with the `fft_length` samples of their inverse 3D real Fourier transform. @compatibility(numpy) Equivalent to np.irfftn with 3 dimensions. @end_compatibility )doc"); // Deprecated ops: REGISTER_OP("BatchFFT") .Input("input: complex64") .Output("output: complex64") .Deprecated(15, "Use FFT"); REGISTER_OP("BatchIFFT") .Input("input: complex64") .Output("output: complex64") .Deprecated(15, "Use IFFT"); REGISTER_OP("BatchFFT2D") .Input("input: complex64") .Output("output: complex64") .Deprecated(15, "Use FFT2D"); REGISTER_OP("BatchIFFT2D") .Input("input: complex64") .Output("output: complex64") .Deprecated(15, "Use IFFT2D"); REGISTER_OP("BatchFFT3D") .Input("input: complex64") .Output("output: complex64") .Deprecated(15, "Use FFT3D"); REGISTER_OP("BatchIFFT3D") .Input("input: complex64") .Output("output: complex64") .Deprecated(15, "Use IFFT3D"); } // namespace tensorflow <|endoftext|>
<commit_before>// SUBS-04.WeirdCombinations.cpp // https://judge.softuni.bg/Contests/37/CSharp-Basics-Exam-7-November-2014 #include <iostream> #include <stack> #include <string> using namespace std; const int numSysBase = 5 ; int main () { // numeral system based solution. The author uses nested loops. string s ; int n, qtyDigits ; stack<int> digits ; char result [numSysBase] ; cin >>s >>n; do { // moves to stack a last digit digits.push(n%numSysBase) ; n = n/numSysBase ; // remove last digit } while (n != 0) ; qtyDigits = digits.size() ; if (qtyDigits > numSysBase) { cout <<"No" ; return 0 ; } ; for (int k=0; k<numSysBase-qtyDigits; k++) cout <<s[0] ; // prints leading zeros if they are available while (! digits.empty()) { // to print a last remainder cout <<s[digits.top()]; digits.pop(); // to remove and to be ready for a next remainder } } <commit_msg>minor<commit_after>// SUBS-04.WeirdCombinations.cpp // https://judge.softuni.bg/Contests/37/CSharp-Basics-Exam-7-November-2014 #include <iostream> // https://bg.wikipedia.org/wiki/%D0%A1%D1%82%D0%B5%D0%BA_(%D1%81%D1%82%D1%80%D1%83%D0%BA%D1%82%D1%83%D1%80%D0%B0_%D0%BE%D1%82_%D0%B4%D0%B0%D0%BD%D0%BD%D0%B8) // https://www.youtube.com/watch?v=5UjENioK8tw #include <stack> #include <string> // Koala Press - SIMVOLNI NIZOVE - p 123. using namespace std; const int numSysBase = 5 ; int main () { // numeral system based solution. The author uses nested loops. string s ; int n, qtyDigits ; stack<int> digits ; char result [numSysBase] ; cin >>s >>n; do { // moves to stack a last digit digits.push(n%numSysBase) ; n = n/numSysBase ; // remove last digit } while (n != 0) ; qtyDigits = digits.size() ; if (qtyDigits > numSysBase) { cout <<"No" ; return 0 ; } ; for (int k=0; k<numSysBase-qtyDigits; k++) cout <<s[0] ; // prints leading zeros if they are available while (! digits.empty()) { // to print a last remainder cout <<s[digits.top()]; digits.pop(); // to remove and to be ready for a next remainder } } <|endoftext|>
<commit_before>#include "s3.h" using namespace himan; #ifdef HAVE_S3 #include "debug.h" #include "timer.h" #include "util.h" #include <iostream> #include <libs3.h> #include <mutex> #include <string.h> // memcpy namespace { static std::once_flag oflag; const char* access_key = 0; const char* secret_key = 0; const char* security_token = 0; S3Protocol protocol = S3ProtocolHTTP; thread_local S3Status statusG = S3StatusOK; void CheckS3Error(S3Status errarg, const char* file, const int line); #define S3_CHECK(errarg) CheckS3Error(errarg, __FILE__, __LINE__) void HandleS3Error(himan::logger& logr, const std::string& host, const std::string& object, const std::string& op) { logr.Error(fmt::format("{} operation to/from host={} object=s3://{} failed", op, host, object)); switch (statusG) { case S3StatusInternalError: logr.Error(fmt::format("{}: is there a proxy blocking the connection?", S3_get_status_name(statusG))); throw himan::kFileDataNotFound; case S3StatusFailedToConnect: logr.Error(fmt::format("{}: is proxy required but not set?", S3_get_status_name(statusG))); throw himan::kFileDataNotFound; case S3StatusErrorInvalidAccessKeyId: logr.Error(fmt::format( "{}: are Temporary Security Credentials used without security token (env: S3_SESSION_TOKEN)?", S3_get_status_name(statusG))); throw himan::kFileDataNotFound; default: logr.Error(S3_get_status_name(statusG)); throw himan::kFileDataNotFound; } } std::vector<std::string> GetBucketAndFileName(const std::string& fullFileName) { std::vector<std::string> ret; auto fileName = fullFileName; // strip protocol from string if it's there const auto pos = fullFileName.find("s3://"); if (pos != std::string::npos) { fileName = fileName.erase(pos, 5); } // erase forward slash if exists (s3 buckets can't start with /) if (fileName[0] == '/') { fileName = fileName.erase(0, 1); } auto tokens = util::Split(fileName, "/"); ret.push_back(tokens[0]); tokens.erase(std::begin(tokens), std::begin(tokens) + 1); std::string key; for (const auto& piece : tokens) { if (!key.empty()) { key += "/"; } key += piece; } ret.push_back(key); return ret; } inline void CheckS3Error(S3Status errarg, const char* file, const int line) { if (errarg) { std::cerr << "Error at " << file << "(" << line << "): " << S3_get_status_name(errarg) << std::endl; himan::Abort(); } } S3Status responsePropertiesCallback(const S3ResponseProperties* properties, void* callbackData) { return S3StatusOK; } static void responseCompleteCallback(S3Status status, const S3ErrorDetails* error, void* callbackData) { statusG = status; return; } thread_local S3ResponseHandler responseHandler = {&responsePropertiesCallback, &responseCompleteCallback}; static S3Status getObjectDataCallback(int bufferSize, const char* buffer, void* callbackData) { himan::buffer* ret = static_cast<himan::buffer*>(callbackData); ret->data = static_cast<unsigned char*>(realloc(ret->data, ret->length + bufferSize)); memcpy(ret->data + ret->length, buffer, bufferSize); ret->length += bufferSize; return S3StatusOK; } void Initialize() { call_once(oflag, [&]() { access_key = getenv("S3_ACCESS_KEY_ID"); secret_key = getenv("S3_SECRET_ACCESS_KEY"); security_token = getenv("S3_SESSION_TOKEN"); logger logr("s3"); if (!access_key) { logr.Info("Environment variable S3_ACCESS_KEY_ID not defined"); } if (!secret_key) { logr.Info("Environment variable S3_SECRET_ACCESS_KEY not defined"); } try { const auto envproto = himan::util::GetEnv("S3_PROTOCOL"); if (envproto == "https") { protocol = S3ProtocolHTTPS; } else if (envproto == "http") { protocol = S3ProtocolHTTP; } else { logr.Warning(fmt::format("Unrecognized value found from env variable S3_PROTOCOL: '{}'", envproto)); } } catch (const std::invalid_argument& e) { } S3_CHECK(S3_initialize("s3", S3_INIT_ALL, NULL)); }); } std::string ReadAWSRegionFromHostname(const std::string& hostname) { if (hostname.find("amazonaws.com") != std::string::npos) { // extract region name from host name, assuming aws hostname like // s3.us-east-1.amazonaws.com auto tokens = util::Split(hostname, "."); logger logr("s3"); if (tokens.size() != 4) { logr.Fatal("Hostname does not follow pattern s3.<regionname>.amazonaws.com"); } else { logr.Trace(fmt::format("s3 authentication hostname: {}", tokens[1])); return tokens[1]; } } return ""; } struct write_data { himan::buffer buffer; size_t write_ptr; }; static int putObjectDataCallback(int bufferSize, char* buffer, void* callbackData) { write_data* data = static_cast<write_data*>(callbackData); int bytesWritten = 0; if (data->buffer.length) { bytesWritten = static_cast<int>((static_cast<int>(data->buffer.length) > bufferSize) ? bufferSize : data->buffer.length); memcpy(buffer, data->buffer.data + data->write_ptr, bytesWritten); data->write_ptr += bytesWritten; data->buffer.length -= bytesWritten; } return bytesWritten; } } // namespace buffer s3::ReadFile(const file_information& fileInformation) { Initialize(); logger logr("s3"); S3GetObjectHandler getObjectHandler = {responseHandler, &getObjectDataCallback}; const auto bucketAndFileName = GetBucketAndFileName(fileInformation.file_location); const auto bucket = bucketAndFileName[0]; const auto key = bucketAndFileName[1]; buffer ret; #ifdef S3_DEFAULT_REGION std::string region = ReadAWSRegionFromHostname(fileInformation.file_server); // clang-format off S3BucketContext bucketContext = { fileInformation.file_server.c_str(), bucket.c_str(), protocol, S3UriStylePath, access_key, secret_key, security_token, region.c_str() }; #else // clang-format off S3BucketContext bucketContext = { fileInformation.file_server.c_str(), bucket.c_str(), protocol, S3UriStylePath, access_key, secret_key, security_token }; // clang-format on #endif int count = 0; do { if (count > 0) { sleep(2 * count); } const unsigned long offset = fileInformation.offset.get(); const unsigned long length = fileInformation.length.get(); #ifdef S3_DEFAULT_REGION S3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, 0, &getObjectHandler, &ret); #else S3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, &getObjectHandler, &ret); #endif count++; } while (S3_status_is_retryable(statusG) && count < 3); switch (statusG) { case S3StatusOK: break; default: HandleS3Error(logr, fileInformation.file_server, fmt::format("{}/{}", bucket, key), "Read"); break; } if (ret.length == 0) { throw himan::kFileDataNotFound; } return ret; } void s3::WriteObject(const std::string& objectName, const buffer& buff) { Initialize(); const auto bucketAndFileName = GetBucketAndFileName(objectName); const auto bucket = bucketAndFileName[0]; const auto key = bucketAndFileName[1]; const char* host = getenv("S3_HOSTNAME"); logger logr("s3"); if (!host) { logr.Fatal("Environment variable S3_HOSTNAME not defined"); himan::Abort(); } #ifdef S3_DEFAULT_REGION std::string region = ReadAWSRegionFromHostname(std::string(host)); // clang-format off S3BucketContext bucketContext = { host, bucket.c_str(), protocol, S3UriStylePath, access_key, secret_key, security_token, region.c_str() }; #else // clang-format off S3BucketContext bucketContext = { host, bucket.c_str(), protocol, S3UriStylePath, access_key, secret_key, security_token }; #endif // clang-format on S3PutObjectHandler putObjectHandler = {responseHandler, &putObjectDataCallback}; write_data data; data.buffer.data = buff.data; data.buffer.length = buff.length; data.write_ptr = 0; timer t(true); int count = 0; do { if (count > 0) { sleep(2 * count); } #ifdef S3_DEFAULT_REGION S3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, 0, &putObjectHandler, &data); #else S3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, &putObjectHandler, &data); #endif count++; } while (S3_status_is_retryable(statusG) && count < 3); // remove pointer to original buff so that double free doesn't occur data.buffer.data = 0; switch (statusG) { case S3StatusOK: { t.Stop(); const double time = static_cast<double>(t.GetTime()); const double size = util::round(static_cast<double>(buff.length) / 1024. / 1024., 1); logr.Info(fmt::format("Wrote {} MB in {} ms ({:.1f} MBps) to file s3://{}/{}", size, time, size / time, bucket, key)); } break; default: HandleS3Error(logr, host, fmt::format("{}/{}", bucket, key), "Write"); break; } } #else buffer s3::ReadFile(const file_information& fileInformation) { throw std::runtime_error("S3 support not compiled"); } void s3::WriteObject(const std::string& objectName, const buffer& buff) { throw std::runtime_error("S3 support not compiled"); } #endif <commit_msg>Correct calculation of transmission speed<commit_after>#include "s3.h" using namespace himan; #ifdef HAVE_S3 #include "debug.h" #include "timer.h" #include "util.h" #include <iostream> #include <libs3.h> #include <mutex> #include <string.h> // memcpy namespace { static std::once_flag oflag; const char* access_key = 0; const char* secret_key = 0; const char* security_token = 0; S3Protocol protocol = S3ProtocolHTTP; thread_local S3Status statusG = S3StatusOK; void CheckS3Error(S3Status errarg, const char* file, const int line); #define S3_CHECK(errarg) CheckS3Error(errarg, __FILE__, __LINE__) void HandleS3Error(himan::logger& logr, const std::string& host, const std::string& object, const std::string& op) { logr.Error(fmt::format("{} operation to/from host={} object=s3://{} failed", op, host, object)); switch (statusG) { case S3StatusInternalError: logr.Error(fmt::format("{}: is there a proxy blocking the connection?", S3_get_status_name(statusG))); throw himan::kFileDataNotFound; case S3StatusFailedToConnect: logr.Error(fmt::format("{}: is proxy required but not set?", S3_get_status_name(statusG))); throw himan::kFileDataNotFound; case S3StatusErrorInvalidAccessKeyId: logr.Error(fmt::format( "{}: are Temporary Security Credentials used without security token (env: S3_SESSION_TOKEN)?", S3_get_status_name(statusG))); throw himan::kFileDataNotFound; default: logr.Error(S3_get_status_name(statusG)); throw himan::kFileDataNotFound; } } std::vector<std::string> GetBucketAndFileName(const std::string& fullFileName) { std::vector<std::string> ret; auto fileName = fullFileName; // strip protocol from string if it's there const auto pos = fullFileName.find("s3://"); if (pos != std::string::npos) { fileName = fileName.erase(pos, 5); } // erase forward slash if exists (s3 buckets can't start with /) if (fileName[0] == '/') { fileName = fileName.erase(0, 1); } auto tokens = util::Split(fileName, "/"); ret.push_back(tokens[0]); tokens.erase(std::begin(tokens), std::begin(tokens) + 1); std::string key; for (const auto& piece : tokens) { if (!key.empty()) { key += "/"; } key += piece; } ret.push_back(key); return ret; } inline void CheckS3Error(S3Status errarg, const char* file, const int line) { if (errarg) { std::cerr << "Error at " << file << "(" << line << "): " << S3_get_status_name(errarg) << std::endl; himan::Abort(); } } S3Status responsePropertiesCallback(const S3ResponseProperties* properties, void* callbackData) { return S3StatusOK; } static void responseCompleteCallback(S3Status status, const S3ErrorDetails* error, void* callbackData) { statusG = status; return; } thread_local S3ResponseHandler responseHandler = {&responsePropertiesCallback, &responseCompleteCallback}; static S3Status getObjectDataCallback(int bufferSize, const char* buffer, void* callbackData) { himan::buffer* ret = static_cast<himan::buffer*>(callbackData); ret->data = static_cast<unsigned char*>(realloc(ret->data, ret->length + bufferSize)); memcpy(ret->data + ret->length, buffer, bufferSize); ret->length += bufferSize; return S3StatusOK; } void Initialize() { call_once(oflag, [&]() { access_key = getenv("S3_ACCESS_KEY_ID"); secret_key = getenv("S3_SECRET_ACCESS_KEY"); security_token = getenv("S3_SESSION_TOKEN"); logger logr("s3"); if (!access_key) { logr.Info("Environment variable S3_ACCESS_KEY_ID not defined"); } if (!secret_key) { logr.Info("Environment variable S3_SECRET_ACCESS_KEY not defined"); } try { const auto envproto = himan::util::GetEnv("S3_PROTOCOL"); if (envproto == "https") { protocol = S3ProtocolHTTPS; } else if (envproto == "http") { protocol = S3ProtocolHTTP; } else { logr.Warning(fmt::format("Unrecognized value found from env variable S3_PROTOCOL: '{}'", envproto)); } } catch (const std::invalid_argument& e) { } S3_CHECK(S3_initialize("s3", S3_INIT_ALL, NULL)); }); } std::string ReadAWSRegionFromHostname(const std::string& hostname) { if (hostname.find("amazonaws.com") != std::string::npos) { // extract region name from host name, assuming aws hostname like // s3.us-east-1.amazonaws.com auto tokens = util::Split(hostname, "."); logger logr("s3"); if (tokens.size() != 4) { logr.Fatal("Hostname does not follow pattern s3.<regionname>.amazonaws.com"); } else { logr.Trace(fmt::format("s3 authentication hostname: {}", tokens[1])); return tokens[1]; } } return ""; } struct write_data { himan::buffer buffer; size_t write_ptr; }; static int putObjectDataCallback(int bufferSize, char* buffer, void* callbackData) { write_data* data = static_cast<write_data*>(callbackData); int bytesWritten = 0; if (data->buffer.length) { bytesWritten = static_cast<int>((static_cast<int>(data->buffer.length) > bufferSize) ? bufferSize : data->buffer.length); memcpy(buffer, data->buffer.data + data->write_ptr, bytesWritten); data->write_ptr += bytesWritten; data->buffer.length -= bytesWritten; } return bytesWritten; } } // namespace buffer s3::ReadFile(const file_information& fileInformation) { Initialize(); logger logr("s3"); S3GetObjectHandler getObjectHandler = {responseHandler, &getObjectDataCallback}; const auto bucketAndFileName = GetBucketAndFileName(fileInformation.file_location); const auto bucket = bucketAndFileName[0]; const auto key = bucketAndFileName[1]; buffer ret; #ifdef S3_DEFAULT_REGION std::string region = ReadAWSRegionFromHostname(fileInformation.file_server); // clang-format off S3BucketContext bucketContext = { fileInformation.file_server.c_str(), bucket.c_str(), protocol, S3UriStylePath, access_key, secret_key, security_token, region.c_str() }; #else // clang-format off S3BucketContext bucketContext = { fileInformation.file_server.c_str(), bucket.c_str(), protocol, S3UriStylePath, access_key, secret_key, security_token }; // clang-format on #endif int count = 0; do { if (count > 0) { sleep(2 * count); } const unsigned long offset = fileInformation.offset.get(); const unsigned long length = fileInformation.length.get(); #ifdef S3_DEFAULT_REGION S3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, 0, &getObjectHandler, &ret); #else S3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, &getObjectHandler, &ret); #endif count++; } while (S3_status_is_retryable(statusG) && count < 3); switch (statusG) { case S3StatusOK: break; default: HandleS3Error(logr, fileInformation.file_server, fmt::format("{}/{}", bucket, key), "Read"); break; } if (ret.length == 0) { throw himan::kFileDataNotFound; } return ret; } void s3::WriteObject(const std::string& objectName, const buffer& buff) { Initialize(); const auto bucketAndFileName = GetBucketAndFileName(objectName); const auto bucket = bucketAndFileName[0]; const auto key = bucketAndFileName[1]; const char* host = getenv("S3_HOSTNAME"); logger logr("s3"); if (!host) { logr.Fatal("Environment variable S3_HOSTNAME not defined"); himan::Abort(); } #ifdef S3_DEFAULT_REGION std::string region = ReadAWSRegionFromHostname(std::string(host)); // clang-format off S3BucketContext bucketContext = { host, bucket.c_str(), protocol, S3UriStylePath, access_key, secret_key, security_token, region.c_str() }; #else // clang-format off S3BucketContext bucketContext = { host, bucket.c_str(), protocol, S3UriStylePath, access_key, secret_key, security_token }; #endif // clang-format on S3PutObjectHandler putObjectHandler = {responseHandler, &putObjectDataCallback}; write_data data; data.buffer.data = buff.data; data.buffer.length = buff.length; data.write_ptr = 0; timer t(true); int count = 0; do { if (count > 0) { sleep(2 * count); } #ifdef S3_DEFAULT_REGION S3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, 0, &putObjectHandler, &data); #else S3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, &putObjectHandler, &data); #endif count++; } while (S3_status_is_retryable(statusG) && count < 3); // remove pointer to original buff so that double free doesn't occur data.buffer.data = 0; switch (statusG) { case S3StatusOK: { t.Stop(); const double time = static_cast<double>(t.GetTime()); const double size = util::round(static_cast<double>(buff.length) / 1024. / 1024., 1); logr.Info(fmt::format("Wrote {} MB in {} ms ({:.1f} MBps) to file s3://{}/{}", size, time, size / (time * 0.001), bucket, key)); } break; default: HandleS3Error(logr, host, fmt::format("{}/{}", bucket, key), "Write"); break; } } #else buffer s3::ReadFile(const file_information& fileInformation) { throw std::runtime_error("S3 support not compiled"); } void s3::WriteObject(const std::string& objectName, const buffer& buff) { throw std::runtime_error("S3 support not compiled"); } #endif <|endoftext|>
<commit_before>/// \file /// \ingroup tutorial_tdataframe /// \notebook -draw /// This tutorial shows how VecOps can be used to slim down the programming /// model typically adopted in HEP for analysis. /// In this case we have a dataset containing the kinematic properties of /// particles stored in individual arrays. /// We want to plot the transverse momentum of these particles if the energy is /// greater than 100. /// /// \macro_code /// /// \date March 2018 /// \author Danilo Piparo, Andre Vieira Silva R__LOAD_LIBRARY(libVecOps); auto filename = gROOT->GetTutorialDir() + "/dataframe/tdf017_vecOpsHEP.root"; auto treename = "myDataset"; using doubles = ROOT::Experimental::VecOps::TVec<double>; using TDF = ROOT::Experimental::TDataFrame; void WithTTreeReader() { TFile f(filename); TTreeReader tr(treename, &f); TTreeReaderArray<double> px(tr, "px"); TTreeReaderArray<double> py(tr, "py"); TTreeReaderArray<double> E(tr, "E"); TH1F h("pt", "pt", 16, 0, 4); while (tr.Next()) { for (auto i=0U;i < px.GetSize(); ++i) { if (E[i] > 100) h.Fill(sqrt(px[i]*px[i] + py[i]*py[i])); } } h.DrawCopy(); } void WithTDataFrame() { TDF f(treename, filename.Data()); auto CalcPt = [](doubles &px, doubles &py, doubles &E) { doubles v; for (auto i=0U;i < px.size(); ++i) { if (E[i] > 100) { v.emplace_back(sqrt(px[i]*px[i] + py[i]*py[i])); } } return v; }; f.Define("pt", CalcPt, {"px", "py", "E"}) .Histo1D<doubles>({"pt", "pt", 16, 0, 4}, "pt")->DrawCopy(); } void WithTDataFrameVecOps() { TDF f(treename, filename.Data()); auto CalcPt = [](doubles &px, doubles &py, doubles &E) { auto pt = sqrt(px*px + py*py); return pt[E>100]; }; f.Define("good_pt", CalcPt, {"px", "py", "E"}) .Histo1D<doubles>({"pt", "pt", 16, 0, 4}, "good_pt")->DrawCopy(); } void WithTDataFrameVecOpsJit() { TDF f(treename, filename.Data()); f.Define("good_pt", "sqrt(px*px + py*py)[E>100]") .Histo1D({"pt", "pt", 16, 0, 4}, "good_pt")->DrawCopy(); } void tdf017_vecOpsHEP() { // We plot four times the same quantity, the key is to look into the implementation // of the functions above auto c = new TCanvas(); c->Divide(2,2); c->cd(1); WithTTreeReader(); c->cd(2); WithTDataFrame(); c->cd(3); WithTDataFrameVecOps(); c->cd(4); WithTDataFrameVecOpsJit(); } <commit_msg>[VecOps] Remove workaround for loading manually the library<commit_after>/// \file /// \ingroup tutorial_tdataframe /// \notebook -draw /// This tutorial shows how VecOps can be used to slim down the programming /// model typically adopted in HEP for analysis. /// In this case we have a dataset containing the kinematic properties of /// particles stored in individual arrays. /// We want to plot the transverse momentum of these particles if the energy is /// greater than 100. /// /// \macro_code /// /// \date March 2018 /// \author Danilo Piparo, Andre Vieira Silva auto filename = gROOT->GetTutorialDir() + "/dataframe/tdf017_vecOpsHEP.root"; auto treename = "myDataset"; using doubles = ROOT::Experimental::VecOps::TVec<double>; using TDF = ROOT::Experimental::TDataFrame; void WithTTreeReader() { TFile f(filename); TTreeReader tr(treename, &f); TTreeReaderArray<double> px(tr, "px"); TTreeReaderArray<double> py(tr, "py"); TTreeReaderArray<double> E(tr, "E"); TH1F h("pt", "pt", 16, 0, 4); while (tr.Next()) { for (auto i=0U;i < px.GetSize(); ++i) { if (E[i] > 100) h.Fill(sqrt(px[i]*px[i] + py[i]*py[i])); } } h.DrawCopy(); } void WithTDataFrame() { TDF f(treename, filename.Data()); auto CalcPt = [](doubles &px, doubles &py, doubles &E) { doubles v; for (auto i=0U;i < px.size(); ++i) { if (E[i] > 100) { v.emplace_back(sqrt(px[i]*px[i] + py[i]*py[i])); } } return v; }; f.Define("pt", CalcPt, {"px", "py", "E"}) .Histo1D<doubles>({"pt", "pt", 16, 0, 4}, "pt")->DrawCopy(); } void WithTDataFrameVecOps() { TDF f(treename, filename.Data()); auto CalcPt = [](doubles &px, doubles &py, doubles &E) { auto pt = sqrt(px*px + py*py); return pt[E>100]; }; f.Define("good_pt", CalcPt, {"px", "py", "E"}) .Histo1D<doubles>({"pt", "pt", 16, 0, 4}, "good_pt")->DrawCopy(); } void WithTDataFrameVecOpsJit() { TDF f(treename, filename.Data()); f.Define("good_pt", "sqrt(px*px + py*py)[E>100]") .Histo1D({"pt", "pt", 16, 0, 4}, "good_pt")->DrawCopy(); } void tdf017_vecOpsHEP() { // We plot four times the same quantity, the key is to look into the implementation // of the functions above auto c = new TCanvas(); c->Divide(2,2); c->cd(1); WithTTreeReader(); c->cd(2); WithTDataFrame(); c->cd(3); WithTDataFrameVecOps(); c->cd(4); WithTDataFrameVecOpsJit(); } <|endoftext|>
<commit_before>void MdApi::OnDisconnected(int reason) { Task task = Task(); task.task_name = ONDISCONNECTED; task.task_extra = reason; this->task_queue.push(task); }; void MdApi::OnError(XTPRI *error_info) { Task task = Task(); task.task_name = ONERROR; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnSubMarketData(XTPST *ticker, XTPRI *error_info, bool is_last) { Task task = Task(); task.task_name = ONSUBMARKETDATA; if (ticker) { XTPST *task_data = new XTPST(); *task_data = *ticker; task.task_data = task_data; } if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } task.task_last = is_last; this->task_queue.push(task); }; void MdApi::OnUnSubMarketData(XTPST *ticker, XTPRI *error_info, bool is_last) { Task task = Task(); task.task_name = ONUNSUBMARKETDATA; if (ticker) { XTPST *task_data = new XTPST(); *task_data = *ticker; task.task_data = task_data; } if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } task.task_last = is_last; this->task_queue.push(task); }; void MdApi::OnDepthMarketData(XTPMD *market_data, int bid1_qty int bid1_count, int max_bid1_count, int ask1_qty int ask1_count, int max_ask1_count) { Task task = Task(); task.task_name = ONDEPTHMARKETDATA; if (market_data) { XTPMD *task_data = new XTPMD(); *task_data = *market_data; task.task_data = task_data; } task.task_extra = bid1_qty; task.task_extra = bid1_count; task.task_extra = max_bid1_count; task.task_extra = ask1_qty; task.task_extra = ask1_count; task.task_extra = max_ask1_count; this->task_queue.push(task); }; void MdApi::OnSubOrderBook(XTPST *ticker, XTPRI *error_info, bool is_last) { Task task = Task(); task.task_name = ONSUBORDERBOOK; if (ticker) { XTPST *task_data = new XTPST(); *task_data = *ticker; task.task_data = task_data; } if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } task.task_last = is_last; this->task_queue.push(task); }; void MdApi::OnUnSubOrderBook(XTPST *ticker, XTPRI *error_info, bool is_last) { Task task = Task(); task.task_name = ONUNSUBORDERBOOK; if (ticker) { XTPST *task_data = new XTPST(); *task_data = *ticker; task.task_data = task_data; } if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } task.task_last = is_last; this->task_queue.push(task); }; void MdApi::OnOrderBook(XTPOB *order_book) { Task task = Task(); task.task_name = ONORDERBOOK; if (order_book) { XTPOB *task_data = new XTPOB(); *task_data = *order_book; task.task_data = task_data; } this->task_queue.push(task); }; void MdApi::OnSubTickByTick(XTPST *ticker, XTPRI *error_info, bool is_last) { Task task = Task(); task.task_name = ONSUBTICKBYTICK; if (ticker) { XTPST *task_data = new XTPST(); *task_data = *ticker; task.task_data = task_data; } if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } task.task_last = is_last; this->task_queue.push(task); }; void MdApi::OnUnSubTickByTick(XTPST *ticker, XTPRI *error_info, bool is_last) { Task task = Task(); task.task_name = ONUNSUBTICKBYTICK; if (ticker) { XTPST *task_data = new XTPST(); *task_data = *ticker; task.task_data = task_data; } if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } task.task_last = is_last; this->task_queue.push(task); }; void MdApi::OnTickByTick(XTPTBT *tbt_data) { Task task = Task(); task.task_name = ONTICKBYTICK; if (tbt_data) { XTPTBT *task_data = new XTPTBT(); *task_data = *tbt_data; task.task_data = task_data; } this->task_queue.push(task); }; void MdApi::OnSubscribeAllMarketData(int exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONSUBSCRIBEALLMARKETDATA; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnUnSubscribeAllMarketData(int exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONUNSUBSCRIBEALLMARKETDATA; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnSubscribeAllOrderBook(int exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONSUBSCRIBEALLORDERBOOK; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnUnSubscribeAllOrderBook(int exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONUNSUBSCRIBEALLORDERBOOK; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnSubscribeAllTickByTick(int exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONSUBSCRIBEALLTICKBYTICK; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnUnSubscribeAllTickByTick(int exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONUNSUBSCRIBEALLTICKBYTICK; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnQueryAllTickers(XTPQSI* ticker_info, XTPRI *error_info, bool is_last) { Task task = Task(); task.task_name = ONQUERYALLTICKERS; if (ticker_info) { XTPQSI *task_data = new XTPQSI(); *task_data = *ticker_info; task.task_data = task_data; } if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } task.task_last = is_last; this->task_queue.push(task); }; void MdApi::OnQueryTickersPriceInfo(XTPTPI* ticker_info, XTPRI *error_info, bool is_last) { Task task = Task(); task.task_name = ONQUERYTICKERSPRICEINFO; if (ticker_info) { XTPTPI *task_data = new XTPTPI(); *task_data = *ticker_info; task.task_data = task_data; } if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } task.task_last = is_last; this->task_queue.push(task); }; void MdApi::OnSubscribeAllOptionMarketData(int exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONSUBSCRIBEALLOPTIONMARKETDATA; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnUnSubscribeAllOptionMarketData(int exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONUNSUBSCRIBEALLOPTIONMARKETDATA; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnSubscribeAllOptionOrderBook(int exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONSUBSCRIBEALLOPTIONORDERBOOK; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnUnSubscribeAllOptionOrderBook(int exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONUNSUBSCRIBEALLOPTIONORDERBOOK; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnSubscribeAllOptionTickByTick(int exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONSUBSCRIBEALLOPTIONTICKBYTICK; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnUnSubscribeAllOptionTickByTick(int exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONUNSUBSCRIBEALLOPTIONTICKBYTICK; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; <commit_msg>Update xtp_md_source_task.cpp<commit_after>void MdApi::OnDisconnected(int reason) { Task task = Task(); task.task_name = ONDISCONNECTED; task.task_extra = reason; this->task_queue.push(task); }; void MdApi::OnError(XTPRI *error_info) { Task task = Task(); task.task_name = ONERROR; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnSubMarketData(XTPST *ticker, XTPRI *error_info, bool is_last) { Task task = Task(); task.task_name = ONSUBMARKETDATA; if (ticker) { XTPST *task_data = new XTPST(); *task_data = *ticker; task.task_data = task_data; } if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } task.task_last = is_last; this->task_queue.push(task); }; void MdApi::OnUnSubMarketData(XTPST *ticker, XTPRI *error_info, bool is_last) { Task task = Task(); task.task_name = ONUNSUBMARKETDATA; if (ticker) { XTPST *task_data = new XTPST(); *task_data = *ticker; task.task_data = task_data; } if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } task.task_last = is_last; this->task_queue.push(task); }; void MdApi::OnDepthMarketData(XTPMD *market_data, int64_t bid1_qty[], int32_t bid1_count, int32_t max_bid1_count, int64_t ask1_qty[], int32_t ask1_count, int32_t max_ask1_count) { Task task = Task(); task.task_name = ONDEPTHMARKETDATA; if (market_data) { XTPMD *task_data = new XTPMD(); *task_data = *market_data; task.task_data = task_data; } task.task_extra = bid1_qty; task.task_extra = bid1_count; task.task_extra = max_bid1_count; task.task_extra = ask1_qty; task.task_extra = ask1_count; task.task_extra = max_ask1_count; this->task_queue.push(task); }; void MdApi::OnSubOrderBook(XTPST *ticker, XTPRI *error_info, bool is_last) { Task task = Task(); task.task_name = ONSUBORDERBOOK; if (ticker) { XTPST *task_data = new XTPST(); *task_data = *ticker; task.task_data = task_data; } if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } task.task_last = is_last; this->task_queue.push(task); }; void MdApi::OnUnSubOrderBook(XTPST *ticker, XTPRI *error_info, bool is_last) { Task task = Task(); task.task_name = ONUNSUBORDERBOOK; if (ticker) { XTPST *task_data = new XTPST(); *task_data = *ticker; task.task_data = task_data; } if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } task.task_last = is_last; this->task_queue.push(task); }; void MdApi::OnOrderBook(XTPOB *order_book) { Task task = Task(); task.task_name = ONORDERBOOK; if (order_book) { XTPOB *task_data = new XTPOB(); *task_data = *order_book; task.task_data = task_data; } this->task_queue.push(task); }; void MdApi::OnSubTickByTick(XTPST *ticker, XTPRI *error_info, bool is_last) { Task task = Task(); task.task_name = ONSUBTICKBYTICK; if (ticker) { XTPST *task_data = new XTPST(); *task_data = *ticker; task.task_data = task_data; } if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } task.task_last = is_last; this->task_queue.push(task); }; void MdApi::OnUnSubTickByTick(XTPST *ticker, XTPRI *error_info, bool is_last) { Task task = Task(); task.task_name = ONUNSUBTICKBYTICK; if (ticker) { XTPST *task_data = new XTPST(); *task_data = *ticker; task.task_data = task_data; } if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } task.task_last = is_last; this->task_queue.push(task); }; void MdApi::OnTickByTick(XTPTBT *tbt_data) { Task task = Task(); task.task_name = ONTICKBYTICK; if (tbt_data) { XTPTBT *task_data = new XTPTBT(); *task_data = *tbt_data; task.task_data = task_data; } this->task_queue.push(task); }; void MdApi::OnSubscribeAllMarketData(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONSUBSCRIBEALLMARKETDATA; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnUnSubscribeAllMarketData(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONUNSUBSCRIBEALLMARKETDATA; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnSubscribeAllOrderBook(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONSUBSCRIBEALLORDERBOOK; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnUnSubscribeAllOrderBook(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONUNSUBSCRIBEALLORDERBOOK; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnSubscribeAllTickByTick(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONSUBSCRIBEALLTICKBYTICK; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnUnSubscribeAllTickByTick(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONUNSUBSCRIBEALLTICKBYTICK; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnQueryAllTickers(XTPQSI* ticker_info, XTPRI *error_info, bool is_last) { Task task = Task(); task.task_name = ONQUERYALLTICKERS; if (ticker_info) { XTPQSI *task_data = new XTPQSI(); *task_data = *ticker_info; task.task_data = task_data; } if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } task.task_last = is_last; this->task_queue.push(task); }; void MdApi::OnQueryTickersPriceInfo(XTPTPI* ticker_info, XTPRI *error_info, bool is_last) { Task task = Task(); task.task_name = ONQUERYTICKERSPRICEINFO; if (ticker_info) { XTPTPI *task_data = new XTPTPI(); *task_data = *ticker_info; task.task_data = task_data; } if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } task.task_last = is_last; this->task_queue.push(task); }; void MdApi::OnSubscribeAllOptionMarketData(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONSUBSCRIBEALLOPTIONMARKETDATA; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnUnSubscribeAllOptionMarketData(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONUNSUBSCRIBEALLOPTIONMARKETDATA; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnSubscribeAllOptionOrderBook(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONSUBSCRIBEALLOPTIONORDERBOOK; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnUnSubscribeAllOptionOrderBook(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONUNSUBSCRIBEALLOPTIONORDERBOOK; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnSubscribeAllOptionTickByTick(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONSUBSCRIBEALLOPTIONTICKBYTICK; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; void MdApi::OnUnSubscribeAllOptionTickByTick(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) { Task task = Task(); task.task_name = ONUNSUBSCRIBEALLOPTIONTICKBYTICK; task.task_extra = (int) exchange_id; if (error_info) { XTPRI *task_error = new XTPRI(); *task_error = *error_info; task.task_error = task_error; } this->task_queue.push(task); }; <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: getfilenamewrapper.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2006-10-12 10:53:22 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_fpicker.hxx" //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _GETFILENAMEWRAPPER_HXX_ #include "getfilenamewrapper.hxx" #endif #if defined _MSC_VER #pragma warning(push, 1) #endif #include <objbase.h> #include <process.h> #if defined _MSC_VER #pragma warning(pop) #endif namespace /* private */ { //----------------------------------------------- // //----------------------------------------------- struct GetFileNameParam { GetFileNameParam(bool bOpen, LPOPENFILENAME lpofn) : m_bOpen(bOpen), m_lpofn(lpofn), m_bRet(false), m_ExtErr(0) {} bool m_bOpen; LPOPENFILENAME m_lpofn; bool m_bRet; int m_ExtErr; }; //----------------------------------------------- // //----------------------------------------------- unsigned __stdcall ThreadProc(void* pParam) { GetFileNameParam* lpgfnp = reinterpret_cast<GetFileNameParam*>(pParam); HRESULT hr = OleInitialize( NULL ); if (lpgfnp->m_bOpen) lpgfnp->m_bRet = GetOpenFileName(lpgfnp->m_lpofn); else lpgfnp->m_bRet = GetSaveFileName(lpgfnp->m_lpofn); lpgfnp->m_ExtErr = CommDlgExtendedError(); if ( SUCCEEDED( hr ) ) OleUninitialize(); return 0; } //----------------------------------------------- // exceutes GetOpenFileName/GetSaveFileName in // a separat thread //----------------------------------------------- bool ThreadExecGetFileName(LPOPENFILENAME lpofn, bool bOpen, /*out*/ int& ExtErr) { GetFileNameParam gfnp(bOpen,lpofn); unsigned id; HANDLE hThread = reinterpret_cast<HANDLE>( _beginthreadex(0, 0, ThreadProc, &gfnp, 0, &id)); OSL_POSTCOND(hThread, "could not create STA thread"); WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); ExtErr = gfnp.m_ExtErr; return gfnp.m_bRet; } //----------------------------------------------- // This function returns true if the calling // thread belongs to a Multithreaded Appartment // (MTA) //----------------------------------------------- bool IsMTA() { HRESULT hr = CoInitialize(NULL); if (RPC_E_CHANGED_MODE == hr) return true; if(SUCCEEDED(hr)) CoUninitialize(); return false; } } // namespace private //----------------------------------------------- // //----------------------------------------------- CGetFileNameWrapper::CGetFileNameWrapper() : m_ExtendedDialogError(0) { } //----------------------------------------------- // //----------------------------------------------- bool CGetFileNameWrapper::getOpenFileName(LPOPENFILENAME lpofn) { OSL_PRECOND(lpofn,"invalid parameter"); bool bRet = false; if (IsMTA()) { bRet = ThreadExecGetFileName( lpofn, true, m_ExtendedDialogError); } else { HRESULT hr = OleInitialize( NULL ); bRet = GetOpenFileName(lpofn); m_ExtendedDialogError = CommDlgExtendedError(); if ( SUCCEEDED( hr ) ) OleUninitialize(); } return bRet; } //----------------------------------------------- // //----------------------------------------------- bool CGetFileNameWrapper::getSaveFileName(LPOPENFILENAME lpofn) { OSL_PRECOND(lpofn,"invalid parameter"); bool bRet = false; if (IsMTA()) { bRet = ThreadExecGetFileName( lpofn, false, m_ExtendedDialogError); } else { bRet = GetSaveFileName(lpofn); m_ExtendedDialogError = CommDlgExtendedError(); } return bRet; } //----------------------------------------------- // //----------------------------------------------- int CGetFileNameWrapper::commDlgExtendedError( ) { return m_ExtendedDialogError; } <commit_msg>INTEGRATION: CWS fwk56 (1.8.22); FILE MERGED 2006/11/28 09:26:47 mav 1.8.22.2: #i21747# fix long path handling 2006/11/15 14:42:49 mav 1.8.22.1: #i21747# preserv the current directory value<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: getfilenamewrapper.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: ihi $ $Date: 2006-12-19 13:54:09 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_fpicker.hxx" //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #include <stdio.h> #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _GETFILENAMEWRAPPER_HXX_ #include "getfilenamewrapper.hxx" #endif #if defined _MSC_VER #pragma warning(push, 1) #endif #include <objbase.h> #include <process.h> #if defined _MSC_VER #pragma warning(pop) #endif namespace /* private */ { //----------------------------------------------- // This class prevents changing of the working // directory. //----------------------------------------------- class CurDirGuard { BOOL m_bValid; wchar_t* m_pBuffer; DWORD m_nBufLen; public: CurDirGuard() : m_bValid( FALSE ) , m_pBuffer( NULL ) , m_nBufLen( 0 ) { m_nBufLen = GetCurrentDirectoryW( 0, NULL ); if ( m_nBufLen ) { m_pBuffer = new wchar_t[m_nBufLen]; m_bValid = ( GetCurrentDirectoryW( m_nBufLen, m_pBuffer ) == ( m_nBufLen - 1 ) ); } } ~CurDirGuard() { BOOL bDirSet = FALSE; if ( m_pBuffer ) { if ( m_bValid ) { if ( m_nBufLen - 1 > MAX_PATH ) { if ( (LONG32)GetVersion() < 0 ) { // this is Win 98/ME branch, such a long path can not be set // use the system path as fallback later } else { DWORD nNewLen = m_nBufLen + 8; wchar_t* pNewBuffer = new wchar_t[nNewLen]; if ( m_nBufLen > 3 && m_pBuffer[0] == (wchar_t)'\\' && m_pBuffer[1] == (wchar_t)'\\' ) { if ( m_pBuffer[2] == (wchar_t)'?' ) _snwprintf( pNewBuffer, nNewLen, L"%s", m_pBuffer ); else _snwprintf( pNewBuffer, nNewLen, L"\\\\?\\UNC\\%s", m_pBuffer+2 ); } else _snwprintf( pNewBuffer, nNewLen, L"\\\\?\\%s", m_pBuffer ); bDirSet = SetCurrentDirectoryW( pNewBuffer ); delete [] pNewBuffer; } } else bDirSet = SetCurrentDirectoryW( m_pBuffer ); } delete [] m_pBuffer; m_pBuffer = NULL; } if ( !bDirSet ) { // the fallback solution wchar_t pPath[MAX_PATH+1]; if ( GetWindowsDirectoryW( pPath, MAX_PATH+1 ) <= MAX_PATH ) { SetCurrentDirectoryW( pPath ); } else { // the system path is also too long?!! } } } }; //----------------------------------------------- // //----------------------------------------------- struct GetFileNameParam { GetFileNameParam(bool bOpen, LPOPENFILENAME lpofn) : m_bOpen(bOpen), m_lpofn(lpofn), m_bRet(false), m_ExtErr(0) {} bool m_bOpen; LPOPENFILENAME m_lpofn; bool m_bRet; int m_ExtErr; }; //----------------------------------------------- // //----------------------------------------------- unsigned __stdcall ThreadProc(void* pParam) { CurDirGuard aGuard; GetFileNameParam* lpgfnp = reinterpret_cast<GetFileNameParam*>(pParam); HRESULT hr = OleInitialize( NULL ); if (lpgfnp->m_bOpen) lpgfnp->m_bRet = GetOpenFileName(lpgfnp->m_lpofn); else lpgfnp->m_bRet = GetSaveFileName(lpgfnp->m_lpofn); lpgfnp->m_ExtErr = CommDlgExtendedError(); if ( SUCCEEDED( hr ) ) OleUninitialize(); return 0; } //----------------------------------------------- // exceutes GetOpenFileName/GetSaveFileName in // a separat thread //----------------------------------------------- bool ThreadExecGetFileName(LPOPENFILENAME lpofn, bool bOpen, /*out*/ int& ExtErr) { GetFileNameParam gfnp(bOpen,lpofn); unsigned id; HANDLE hThread = reinterpret_cast<HANDLE>( _beginthreadex(0, 0, ThreadProc, &gfnp, 0, &id)); OSL_POSTCOND(hThread, "could not create STA thread"); WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); ExtErr = gfnp.m_ExtErr; return gfnp.m_bRet; } //----------------------------------------------- // This function returns true if the calling // thread belongs to a Multithreaded Appartment // (MTA) //----------------------------------------------- bool IsMTA() { HRESULT hr = CoInitialize(NULL); if (RPC_E_CHANGED_MODE == hr) return true; if(SUCCEEDED(hr)) CoUninitialize(); return false; } } // namespace private //----------------------------------------------- // //----------------------------------------------- CGetFileNameWrapper::CGetFileNameWrapper() : m_ExtendedDialogError(0) { } //----------------------------------------------- // //----------------------------------------------- bool CGetFileNameWrapper::getOpenFileName(LPOPENFILENAME lpofn) { OSL_PRECOND(lpofn,"invalid parameter"); bool bRet = false; if (IsMTA()) { bRet = ThreadExecGetFileName( lpofn, true, m_ExtendedDialogError); } else { CurDirGuard aGuard; HRESULT hr = OleInitialize( NULL ); bRet = GetOpenFileName(lpofn); m_ExtendedDialogError = CommDlgExtendedError(); if ( SUCCEEDED( hr ) ) OleUninitialize(); } return bRet; } //----------------------------------------------- // //----------------------------------------------- bool CGetFileNameWrapper::getSaveFileName(LPOPENFILENAME lpofn) { OSL_PRECOND(lpofn,"invalid parameter"); bool bRet = false; if (IsMTA()) { bRet = ThreadExecGetFileName( lpofn, false, m_ExtendedDialogError); } else { CurDirGuard aGuard; bRet = GetSaveFileName(lpofn); m_ExtendedDialogError = CommDlgExtendedError(); } return bRet; } //----------------------------------------------- // //----------------------------------------------- int CGetFileNameWrapper::commDlgExtendedError( ) { return m_ExtendedDialogError; } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cybertron/transport/qos/qos_profile_conf.h" namespace apollo { namespace cybertron { namespace transport { QosProfileConf::QosProfileConf() {} QosProfileConf::~QosProfileConf() {} QosProfile QosProfileConf::CreateQosProfile( const QosHistoryPolicy& history, size_t depth, size_t mps, const QosReliabilityPolicy& reliability, const QosDurabilityPolicy& durability) { QosProfile qos_profile; qos_profile.set_history(history); qos_profile.set_depth(depth); qos_profile.set_mps(mps); qos_profile.set_reliability(reliability); qos_profile.set_durability(durability); return qos_profile; } const size_t QosProfileConf::QOS_HISTORY_DEPTH_SYSTEM_DEFAULT = 0; const size_t QosProfileConf::QOS_MPS_SYSTEM_DEFAULT = 0; const QosProfile QosProfileConf::QOS_PROFILE_DEFAULT = CreateQosProfile( QosHistoryPolicy::HISTORY_KEEP_LAST, 2000, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_VOLATILE); const QosProfile QosProfileConf::QOS_PROFILE_SENSOR_DATA = CreateQosProfile( QosHistoryPolicy::HISTORY_KEEP_LAST, 5, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_BEST_EFFORT, QosDurabilityPolicy::DURABILITY_VOLATILE); const QosProfile QosProfileConf::QOS_PROFILE_PARAMETERS = CreateQosProfile( QosHistoryPolicy::HISTORY_KEEP_LAST, 1000, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_VOLATILE); const QosProfile QosProfileConf::QOS_PROFILE_SERVICES_DEFAULT = CreateQosProfile(QosHistoryPolicy::HISTORY_KEEP_LAST, 10, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL); const QosProfile QosProfileConf::QOS_PROFILE_PARAM_EVENT = CreateQosProfile( QosHistoryPolicy::HISTORY_KEEP_LAST, 1000, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_VOLATILE); const QosProfile QosProfileConf::QOS_PROFILE_SYSTEM_DEFAULT = CreateQosProfile( QosHistoryPolicy::HISTORY_SYSTEM_DEFAULT, QOS_HISTORY_DEPTH_SYSTEM_DEFAULT, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL); const QosProfile QosProfileConf::QOS_PROFILE_TF_STATIC = CreateQosProfile( QosHistoryPolicy::HISTORY_KEEP_ALL, 10, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL); const QosProfile QosProfileConf::QOS_PROFILE_TOPO_CHANGE = CreateQosProfile( QosHistoryPolicy::HISTORY_KEEP_ALL, 10, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL); } // namespace transport } // namespace cybertron } // namespace apollo <commit_msg>framework: change default history depth to 1<commit_after>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cybertron/transport/qos/qos_profile_conf.h" namespace apollo { namespace cybertron { namespace transport { QosProfileConf::QosProfileConf() {} QosProfileConf::~QosProfileConf() {} QosProfile QosProfileConf::CreateQosProfile( const QosHistoryPolicy& history, size_t depth, size_t mps, const QosReliabilityPolicy& reliability, const QosDurabilityPolicy& durability) { QosProfile qos_profile; qos_profile.set_history(history); qos_profile.set_depth(depth); qos_profile.set_mps(mps); qos_profile.set_reliability(reliability); qos_profile.set_durability(durability); return qos_profile; } const size_t QosProfileConf::QOS_HISTORY_DEPTH_SYSTEM_DEFAULT = 0; const size_t QosProfileConf::QOS_MPS_SYSTEM_DEFAULT = 0; const QosProfile QosProfileConf::QOS_PROFILE_DEFAULT = CreateQosProfile( QosHistoryPolicy::HISTORY_KEEP_LAST, 1, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_VOLATILE); const QosProfile QosProfileConf::QOS_PROFILE_SENSOR_DATA = CreateQosProfile( QosHistoryPolicy::HISTORY_KEEP_LAST, 5, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_BEST_EFFORT, QosDurabilityPolicy::DURABILITY_VOLATILE); const QosProfile QosProfileConf::QOS_PROFILE_PARAMETERS = CreateQosProfile( QosHistoryPolicy::HISTORY_KEEP_LAST, 1000, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_VOLATILE); const QosProfile QosProfileConf::QOS_PROFILE_SERVICES_DEFAULT = CreateQosProfile(QosHistoryPolicy::HISTORY_KEEP_LAST, 10, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL); const QosProfile QosProfileConf::QOS_PROFILE_PARAM_EVENT = CreateQosProfile( QosHistoryPolicy::HISTORY_KEEP_LAST, 1000, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_VOLATILE); const QosProfile QosProfileConf::QOS_PROFILE_SYSTEM_DEFAULT = CreateQosProfile( QosHistoryPolicy::HISTORY_SYSTEM_DEFAULT, QOS_HISTORY_DEPTH_SYSTEM_DEFAULT, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL); const QosProfile QosProfileConf::QOS_PROFILE_TF_STATIC = CreateQosProfile( QosHistoryPolicy::HISTORY_KEEP_ALL, 10, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL); const QosProfile QosProfileConf::QOS_PROFILE_TOPO_CHANGE = CreateQosProfile( QosHistoryPolicy::HISTORY_KEEP_ALL, 10, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL); } // namespace transport } // namespace cybertron } // namespace apollo <|endoftext|>
<commit_before>#include <QSqlError> #include <QFile> #include <QDataStream> #include <QDir> #include <QDataStream> #include <QUrl> #include <fstream> #include <iomanip> #include "kernel.h" #include "ilwisdata.h" #include "ilwiscontext.h" #include "errorobject.h" #include "issuelogger.h" using namespace Ilwis; std::map<std::thread::id, bool> IssueLogger::_silentThreads; IssueObject::IssueObject() { } Ilwis::IssueObject::IssueObject(const QString &message, int it, quint64 id) { _message = message; _itype = it; _itime = QDateTime::currentDateTime(); _id = id; } QString Ilwis::IssueObject::message() const { return _message; } QDateTime Ilwis::IssueObject::time() const { return _itime; } int Ilwis::IssueObject::type() const { return _itype; } QString Ilwis::IssueObject::logMessage(Ilwis::IssueObject::LogMessageFormat) const{ return QString("%1: (%2) %3").arg(type2String(), _itime.toString(), _message); } int IssueObject::codeLine() const { return _line; } QString IssueObject::codeFunc() const { return _func; } QString IssueObject::codeFile() const { return _file; } void IssueObject::addCodeInfo(int line, const QString &func, const QString &file) { _line = line; _func = func; _file = file; } void IssueObject::stream(std::ofstream& stream, LogMessageFormat frmt) { stream << std::setw(4) << _id << " ; " << std::setw(9) << type2String().toStdString() << " ; " << std::setw(27)<<_itime.toString().toStdString() << " ; " << _message.toStdString() << std::endl; if ( frmt == lmCODE) { stream << std::setw(4) << _id << " ; " << _line << " : " << _func.toStdString() << " ; " << _file.toStdString() << std::endl; } } quint64 IssueObject::id() const { return _id; } QString IssueObject::type2String() const{ switch(_itype) { case itCritical: return "Critical"; case itError: return "Error"; case itWarning: return "Warning"; case itMessage: return "Message"; case itDebug: return "Debug"; } return "Text"; } //--------------------------------------------------------------------------- IssueLogger::IssueLogger(QObject *parent) : QObject(parent), _repeatCount(0) { QString apploc= context()->ilwisFolder().absoluteFilePath(); apploc += "/log"; QDir dir(apploc); if ( !dir.exists()) dir.mkdir(apploc); QString rlogFilePath = apploc + "/logfile.txt"; QString clogFilePath = apploc + "/logfile_ext.txt"; _logFileRegular.open(rlogFilePath.toLatin1()); _logFileCode.open(clogFilePath.toLatin1()); } IssueLogger::~IssueLogger() { if (_logFileCode.is_open()) _logFileCode.close(); if ( _logFileRegular.is_open()) _logFileRegular.close(); } quint64 IssueLogger::log(const QString &message, int it) { ++_repeatCount; std::thread::id id = std::this_thread::get_id(); if ( _silentThreads.find(id)!= _silentThreads.end() && it != IssueObject::itCritical) return i64UNDEF; if ( _lastmessage == message && _repeatCount == 10) { return _issueId; } else { if ( _repeatCount > 10 && _lastmessage != message ){ _issues.enqueue(IssueObject(QString("Message repeated %1 times").arg(_repeatCount), it, _issueId)); throw ErrorObject("Error message cascade"); } _repeatCount = 0; } _issues.enqueue(IssueObject(message, it, _issueId)); if ( _lastmessage == message) return _issueId; IssueObject& obj = _issues.back(); if ( _logFileRegular.is_open()) { obj.stream(_logFileRegular, IssueObject::lmREGULAR); } emit ilwiserrormessage(obj.logMessage()); _lastmessage = message; return _issueId++; } quint64 IssueLogger::log(const QString& objectName, const QString &message, int it) { QString newmessage = objectName + ":" + message; return log(newmessage, it); } void IssueLogger::addCodeInfo(quint64 issueid, int line, const QString &func, const QString &file) { for(auto iter=_issues.begin(); iter != _issues.end(); ++iter) { IssueObject& issue = *iter; if ( issue.id() == issueid) { issue.addCodeInfo(line, func, file); if ( _logFileCode.is_open()) { issue.stream(_logFileCode, IssueObject::lmCODE); } break; } } } bool IssueLogger::silent() const { std::thread::id id = std::this_thread::get_id(); auto iter = _silentThreads.find(id); if ( iter != _silentThreads.end()) return iter->second; return false; } void IssueLogger::silent(bool yesno) { std::thread::id id = std::this_thread::get_id(); if ( yesno == false){ auto iter = _silentThreads.find(id) ; if (iter != _silentThreads.end()) _silentThreads.erase(iter); }else _silentThreads[id] = true; } quint64 IssueLogger::logSql(const QSqlError &err) { return log(err.text(), IssueObject::itError); } IssueObject::IssueType IssueLogger::maxIssueLevel() const { int type = IssueObject::itNone; foreach(IssueObject issue, _issues) { type |= issue.type(); } if ( type & IssueObject::itCritical) return IssueObject::itCritical; if ( type & IssueObject::itError) return IssueObject::itError; if ( type & IssueObject::itWarning) return IssueObject::itWarning; if ( type & IssueObject::itMessage) return IssueObject::itMessage; return IssueObject::itNone; } void IssueLogger::copy(IssueLogger &other) { foreach(IssueObject issue, _issues) { other._issues.enqueue(issue); } } QString IssueLogger::popfirst(int tp) { if ( tp != IssueObject::itAll){ for(auto iter= --_issues.end(); iter != _issues.begin(); --iter ){ if (hasType((*iter).type(), tp)){ QString mes = (*iter).message(); _issues.erase(iter); return mes; } } } if ( _issues.size() > 0) return _issues.dequeue().message(); return "?"; } QString IssueLogger::poplast(int tp) { if ( tp != IssueObject::itAll){ for(auto iter= _issues.begin(); iter != _issues.end(); ++iter ){ if (hasType((*iter).type(), tp)){ QString mes = (*iter).message(); _issues.erase(iter); return mes; } } } if ( _issues.size() >0 ) return _issues.takeLast().message(); return "?"; } void IssueLogger::clear() { _issues.clear(); } <commit_msg>added comment about the error cascade mechanism<commit_after>#include <QSqlError> #include <QFile> #include <QDataStream> #include <QDir> #include <QDataStream> #include <QUrl> #include <fstream> #include <iomanip> #include "kernel.h" #include "ilwisdata.h" #include "ilwiscontext.h" #include "errorobject.h" #include "issuelogger.h" using namespace Ilwis; std::map<std::thread::id, bool> IssueLogger::_silentThreads; IssueObject::IssueObject() { } Ilwis::IssueObject::IssueObject(const QString &message, int it, quint64 id) { _message = message; _itype = it; _itime = QDateTime::currentDateTime(); _id = id; } QString Ilwis::IssueObject::message() const { return _message; } QDateTime Ilwis::IssueObject::time() const { return _itime; } int Ilwis::IssueObject::type() const { return _itype; } QString Ilwis::IssueObject::logMessage(Ilwis::IssueObject::LogMessageFormat) const{ return QString("%1: (%2) %3").arg(type2String(), _itime.toString(), _message); } int IssueObject::codeLine() const { return _line; } QString IssueObject::codeFunc() const { return _func; } QString IssueObject::codeFile() const { return _file; } void IssueObject::addCodeInfo(int line, const QString &func, const QString &file) { _line = line; _func = func; _file = file; } void IssueObject::stream(std::ofstream& stream, LogMessageFormat frmt) { stream << std::setw(4) << _id << " ; " << std::setw(9) << type2String().toStdString() << " ; " << std::setw(27)<<_itime.toString().toStdString() << " ; " << _message.toStdString() << std::endl; if ( frmt == lmCODE) { stream << std::setw(4) << _id << " ; " << _line << " : " << _func.toStdString() << " ; " << _file.toStdString() << std::endl; } } quint64 IssueObject::id() const { return _id; } QString IssueObject::type2String() const{ switch(_itype) { case itCritical: return "Critical"; case itError: return "Error"; case itWarning: return "Warning"; case itMessage: return "Message"; case itDebug: return "Debug"; } return "Text"; } //--------------------------------------------------------------------------- IssueLogger::IssueLogger(QObject *parent) : QObject(parent), _repeatCount(0) { QString apploc= context()->ilwisFolder().absoluteFilePath(); apploc += "/log"; QDir dir(apploc); if ( !dir.exists()) dir.mkdir(apploc); QString rlogFilePath = apploc + "/logfile.txt"; QString clogFilePath = apploc + "/logfile_ext.txt"; _logFileRegular.open(rlogFilePath.toLatin1()); _logFileCode.open(clogFilePath.toLatin1()); } IssueLogger::~IssueLogger() { if (_logFileCode.is_open()) _logFileCode.close(); if ( _logFileRegular.is_open()) _logFileRegular.close(); } quint64 IssueLogger::log(const QString &message, int it) { ++_repeatCount; std::thread::id id = std::this_thread::get_id(); if ( _silentThreads.find(id)!= _silentThreads.end() && it != IssueObject::itCritical) return i64UNDEF; if ( _lastmessage == message && _repeatCount == 10) { return _issueId; } else { // Mechanism to prevent(some) 'stuck in a loop' kind of errors. // this should basically be solved at the place the loop is happening but oversights happen. // This is a last fallback to break the loop without the need to stop the process if ( _repeatCount > 10 && _lastmessage != message ){ _issues.enqueue(IssueObject(QString("Message repeated %1 times").arg(_repeatCount), it, _issueId)); throw ErrorObject(QString("Error message cascade : %1").arg(message)); } _repeatCount = 0; } _issues.enqueue(IssueObject(message, it, _issueId)); if ( _lastmessage == message) return _issueId; IssueObject& obj = _issues.back(); if ( _logFileRegular.is_open()) { obj.stream(_logFileRegular, IssueObject::lmREGULAR); } emit ilwiserrormessage(obj.logMessage()); _lastmessage = message; return _issueId++; } quint64 IssueLogger::log(const QString& objectName, const QString &message, int it) { QString newmessage = objectName + ":" + message; return log(newmessage, it); } void IssueLogger::addCodeInfo(quint64 issueid, int line, const QString &func, const QString &file) { for(auto iter=_issues.begin(); iter != _issues.end(); ++iter) { IssueObject& issue = *iter; if ( issue.id() == issueid) { issue.addCodeInfo(line, func, file); if ( _logFileCode.is_open()) { issue.stream(_logFileCode, IssueObject::lmCODE); } break; } } } bool IssueLogger::silent() const { std::thread::id id = std::this_thread::get_id(); auto iter = _silentThreads.find(id); if ( iter != _silentThreads.end()) return iter->second; return false; } void IssueLogger::silent(bool yesno) { std::thread::id id = std::this_thread::get_id(); if ( yesno == false){ auto iter = _silentThreads.find(id) ; if (iter != _silentThreads.end()) _silentThreads.erase(iter); }else _silentThreads[id] = true; } quint64 IssueLogger::logSql(const QSqlError &err) { return log(err.text(), IssueObject::itError); } IssueObject::IssueType IssueLogger::maxIssueLevel() const { int type = IssueObject::itNone; foreach(IssueObject issue, _issues) { type |= issue.type(); } if ( type & IssueObject::itCritical) return IssueObject::itCritical; if ( type & IssueObject::itError) return IssueObject::itError; if ( type & IssueObject::itWarning) return IssueObject::itWarning; if ( type & IssueObject::itMessage) return IssueObject::itMessage; return IssueObject::itNone; } void IssueLogger::copy(IssueLogger &other) { foreach(IssueObject issue, _issues) { other._issues.enqueue(issue); } } QString IssueLogger::popfirst(int tp) { if ( tp != IssueObject::itAll){ for(auto iter= --_issues.end(); iter != _issues.begin(); --iter ){ if (hasType((*iter).type(), tp)){ QString mes = (*iter).message(); _issues.erase(iter); return mes; } } } if ( _issues.size() > 0) return _issues.dequeue().message(); return "?"; } QString IssueLogger::poplast(int tp) { if ( tp != IssueObject::itAll){ for(auto iter= _issues.begin(); iter != _issues.end(); ++iter ){ if (hasType((*iter).type(), tp)){ QString mes = (*iter).message(); _issues.erase(iter); return mes; } } } if ( _issues.size() >0 ) return _issues.takeLast().message(); return "?"; } void IssueLogger::clear() { _issues.clear(); } <|endoftext|>
<commit_before>#ifndef MCMC_TRAITS #define MCMC_TRAITS #define MCMC_HEADER #include <cmath> #include <cstddef> namespace mcmc_utilities { /** Get the size of an array object \param x the array object \return the size of the array object */ template <typename T> inline size_t get_size(const T& x) { return x.size(); } /** \brief Trait class, in which the types of elements in an array are defined \tparam the type of the array object */ template <typename T> class element_type_trait { public: /** Default definition of element_type */ typedef typename T::value_type element_type; }; /** \brief The return type trait of some certain data types. */ template <typename T> class return_type_trait { public: typedef T value_type; typedef T& reference_type; typedef const T& const_reference_type; }; /** Help function to get the i-th element from an array \tparam T the type of the array object \param x the array object \param i the order of the element \return the fetched element value, const reference */ template <typename T> inline typename return_type_trait<typename element_type_trait<T>::element_type>:: const_reference_type get_element(const T& x,size_t i) { return x[i]; } /** set ths i-th element by a given value \tparam T the type of the array object \tparam Tx the type of the element \param x the array object \param i the order of the element \param v the value of the element to be set */ template<typename T,typename TX> inline void set_element(T& x,size_t i, const TX& v) { x[i]=v; } template <typename T,typename TX> inline void push_back(T& x,const TX& v) { x.push_back(v); } template <typename T> inline typename return_type_trait<typename element_type_trait<T>::element_type>:: const_reference_type last_element(const T& x) { return x.back(); } template <typename T> inline typename return_type_trait<typename element_type_trait<T>::element_type>:: reference_type last_element(T& x) { return x.back(); } /** resize an array object \tparam T the type of the array \param x the array object \param s the new size */ template <typename T> inline void resize(T& x,size_t s) { x.resize(s); } template <typename T> inline void reserve(T& x,size_t s) { x.reserve(s); } /** Assignment operator of two array objects \tparam Tl the type of left-hand array \tparam Tr the type of right-hand array \param lhs the left-hand array \param rhs the right-hand array \return the reference of the left-hand array */ template <typename Tl,typename Tr> inline Tl& mcmc_assign(Tl& lhs,const Tr& rhs) { return (lhs=rhs); } template <typename T> constexpr T C_ONE() { return static_cast<T>(1); } template <typename T> constexpr T C_ZERO() { return static_cast<T>(0); } template <typename T,unsigned int N> constexpr T C_N2T() { return static_cast<T>(N); } template <typename T> constexpr T C_NAN() { return static_cast<T>(std::nan("")); } } #endif <commit_msg> modified: core/mcmc_traits.hpp<commit_after>#ifndef MCMC_TRAITS #define MCMC_TRAITS #define MCMC_HEADER #include <cmath> #include <cstddef> namespace mcmc_utilities { /** Get the size of an array object \param x the array object \return the size of the array object */ template <typename T> inline size_t get_size(const T& x) { return x.size(); } /** \brief Trait class, in which the types of elements in an array are defined \tparam the type of the array object */ template <typename T> class element_type_trait { public: /** Default definition of element_type */ typedef typename T::value_type element_type; }; /** \brief The return type trait of some certain data types. */ template <typename T> class return_type_trait { public: typedef T value_type; typedef T& reference_type; typedef const T& const_reference_type; }; /** Help function to get the i-th element from an array \tparam T the type of the array object \param x the array object \param i the order of the element \return the fetched element value, const reference */ template <typename T> inline typename return_type_trait<typename element_type_trait<T>::element_type>:: const_reference_type get_element(const T& x,size_t i) { return x[i]; } /** set ths i-th element by a given value \tparam T the type of the array object \tparam Tx the type of the element \param x the array object \param i the order of the element \param v the value of the element to be set */ template<typename T,typename TX> inline void set_element(T& x,size_t i, const TX& v) { x[i]=v; } template <typename T,typename TX> inline void push_back(T& x,const TX& v) { x.push_back(v); } template <typename T> inline typename return_type_trait<typename element_type_trait<T>::element_type>:: const_reference_type last_element(const T& x) { return x.back(); } template <typename T> inline typename return_type_trait<typename element_type_trait<T>::element_type>:: reference_type last_element(T& x) { return x.back(); } /** resize an array object \tparam T the type of the array \param x the array object \param s the new size */ template <typename T> inline void resize(T& x,size_t s) { x.resize(s); } template <typename T> inline void reserve(T& x,size_t s) { x.reserve(s); } /** Assignment operator of two array objects \tparam Tl the type of left-hand array \tparam Tr the type of right-hand array \param lhs the left-hand array \param rhs the right-hand array \return the reference of the left-hand array */ template <typename Tl,typename Tr> inline Tl& mcmc_assign(Tl& lhs,const Tr& rhs) { return (lhs=rhs); } template <typename T> constexpr T C_ONE() { return static_cast<T>(1); } template <typename T> constexpr T C_ZERO() { return static_cast<T>(0); } template <typename T,unsigned int N> constexpr T C_N2T() { return static_cast<T>(N); } template <typename T> constexpr T C_NAN() { //return static_cast<T>(std::nan("")); return static_cast<T>(NAN); } } #endif <|endoftext|>
<commit_before>/* Copyright (C) 1998 by Jorrit Tyberghein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssys/csshlib.h" #include <windows.h> csLibraryHandle csLoadLibrary (const char* szLibName) { return LoadLibrary (szLibName); } void* csGetLibrarySymbol(csLibraryHandle Handle, const char* Name) { void* ptr=GetProcAddress ((HMODULE)Handle, Name); if(!ptr) { char *Name2; Name2=new char[strlen(Name)+2]; strcpy(Name2, "_"); strcat(Name2, Name); ptr=GetProcAddress ((HMODULE)Handle, Name2); delete [] Name2; } return ptr; } bool csUnloadLibrary (csLibraryHandle Handle) { return FreeLibrary ((HMODULE)Handle)!=0; } <commit_msg>Now includes sysdef.h in order to eliminate some warnings from windows.h under VC5.<commit_after>/* Copyright (C) 1998 by Jorrit Tyberghein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "sysdef.h" #include "cssys/csshlib.h" #include <windows.h> csLibraryHandle csLoadLibrary (const char* szLibName) { return LoadLibrary (szLibName); } void* csGetLibrarySymbol(csLibraryHandle Handle, const char* Name) { void* ptr=GetProcAddress ((HMODULE)Handle, Name); if(!ptr) { char *Name2; Name2=new char[strlen(Name)+2]; strcpy(Name2, "_"); strcat(Name2, Name); ptr=GetProcAddress ((HMODULE)Handle, Name2); delete [] Name2; } return ptr; } bool csUnloadLibrary (csLibraryHandle Handle) { return FreeLibrary ((HMODULE)Handle)!=0; } <|endoftext|>
<commit_before>#pragma once #include <iterator> #include <memory> #include "TimingTag.hpp" #include "tatum_range.hpp" namespace tatum { /** * The 'TimingTags' class represents a collection of timing tags (see the 'TimingTag' class) * that belong to a particular node in the timing graph. * * Any operations performed using this task generally consider *all* associated tags. * For example, preforming a max_arr() call will apply the max accross all tags with matching * clock domain. If no matching tag is found, the tag will be added to the set of tags. * * Implementation * ==================== * Since each node in the timing graph typically has only a few tags (usually 1 or 2), we * perform linear searches to find match tags and tag ranges. * * Note that to allow efficient iteration of tag ranges (by type) we ensure that tags of the * same type are adjacent in the storage vector (i.e. the vector is sorted by type) */ class TimingTags { public: template<class T> class Iterator; private: //In practice the vast majority of nodes have only two or one //tags, so we reserve space for two to avoid costly memory //allocations constexpr static size_t DEFAULT_TAGS_TO_RESERVE = 3; constexpr static size_t GROWTH_FACTOR = 2; public: typedef Iterator<TimingTag> iterator; typedef Iterator<const TimingTag> const_iterator; typedef tatum::util::Range<const_iterator> tag_range; public: //Constructors TimingTags(size_t num_reserve=DEFAULT_TAGS_TO_RESERVE); TimingTags(const TimingTags&); TimingTags(TimingTags&&); TimingTags& operator=(TimingTags); ~TimingTags() = default; friend void swap(TimingTags& lhs, TimingTags& rhs); /* * Getters */ ///\returns The number of timing tags in this set size_t size() const; bool empty() const { return size() == 0; } ///\returns A range of all tags tag_range tags() const; ///\returns A range of all tags matching type tag_range tags(const TagType type) const; /* * Modifiers */ ///Adds a TimingTag to the current set provided it has a valid clock domain ///\param tag_pool The pool memory allocator used to allocate the tag ///\param src_tag The source tag who is inserted. Note that the src_tag is copied when inserted (the original is unchanged) void add_tag(const TimingTag& src_tag); /* * Operations */ ///Updates the arrival time of this set of tags to be the maximum. ///\param new_time The new arrival time to compare against ///\param base_tag The associated metat-data for new_time ///\remark Finds (or creates) the tag with the same clock domain as base_tag and update the arrival time if new_time is larger void max(const Time& new_time, const TimingTag& base_tag, bool arr_must_be_valid=false); ///Updates the required time of this set of tags to be the minimum. ///\param new_time The new arrival time to compare against ///\param base_tag The associated metat-data for new_time ///\remark Finds (or creates) the tag with the same clock domain as base_tag and update the required time if new_time is smaller void min(const Time& new_time, const TimingTag& base_tag, bool arr_must_be_valid=false); ///Clears the tags in the current set void clear(); public: //Iterator definition template<class T> class Iterator : public std::iterator<std::random_access_iterator_tag, T> { friend TimingTags; public: using value_type = typename std::iterator<std::random_access_iterator_tag, T>::value_type; using difference_type = typename std::iterator<std::random_access_iterator_tag, T>::difference_type; using pointer = typename std::iterator<std::random_access_iterator_tag, T>::pointer; using reference = typename std::iterator<std::random_access_iterator_tag, T>::reference; using iterator_category = typename std::iterator<std::random_access_iterator_tag, T>::iterator_category; public: Iterator(): p_(nullptr) {} Iterator(pointer p): p_(p) {} Iterator(const Iterator& other): p_(other.p_) {} Iterator& operator=(const Iterator& other) { p_ = other.p_; return *this; } friend bool operator==(Iterator a, Iterator b) { return a.p_ == b.p_; } friend bool operator!=(Iterator a, Iterator b) { return a.p_ != b.p_; } reference operator*() { return *p_; } pointer operator->() { return p_; } reference operator[](size_t n) { return *(p_ + n); } Iterator& operator++() { ++p_; return *this; } Iterator operator++(int) { Iterator old = *this; ++p_; return old; } Iterator& operator--() { --p_; return *this; } Iterator operator--(int) { Iterator old = *this; --p_; return old; } Iterator& operator+=(size_t n) { p_ += n; return *this; } Iterator& operator-=(size_t n) { p_ -= n; return *this; } friend Iterator operator+(Iterator lhs, size_t rhs) { return lhs += rhs; } friend Iterator operator-(Iterator lhs, size_t rhs) { return lhs += rhs; } friend difference_type operator-(const Iterator lhs, const Iterator rhs) { return lhs.p_ - rhs.p_; } friend bool operator<(Iterator lhs, Iterator rhs) { return lhs.p_ < rhs.p_; } friend bool operator>(Iterator lhs, Iterator rhs) { return lhs.p_ > rhs.p_; } friend bool operator<=(Iterator lhs, Iterator rhs) { return lhs.p_ <= rhs.p_; } friend bool operator>=(Iterator lhs, Iterator rhs) { return lhs.p_ >= rhs.p_; } friend void swap(Iterator lhs, Iterator rhs) { std::swap(lhs.p_, rhs.p_); } private: T* p_ = nullptr; }; private: ///\returns An iterator to the first tag in the current set iterator begin(); const_iterator begin() const; iterator begin(TagType type); const_iterator begin(TagType type) const; ///\returns An iterator 'one-past-the-end' of the current set iterator end(); const_iterator end() const; iterator end(TagType type); const_iterator end(TagType type) const; size_t capacity() const; std::pair<iterator,bool> find_matching_tag(const TimingTag& tag, bool arr_must_be_valid); ///Finds a TimingTag in the current set that has clock domain id matching domain_id ///\returns An iterator to the tag if found, or end(tag.type()) if not found std::pair<iterator,bool> find_matching_tag(const TimingTag& tag); //Find a TimingTag matching the specified DATA_REQUIRED tag provided there is a valid associated //DATA_ARRIVAL tag std::pair<iterator,bool> find_matching_tag_with_valid_arrival(const TimingTag& tag); iterator insert(iterator iter, const TimingTag& tag); void grow_insert(size_t index, const TimingTag& tag); void increment_size(TagType type); private: //We don't expect many tags in a node so unsigned short's/unsigned char's //should be more than sufficient. This also allows the class //to be packed down to 16 bytes (8 for counters, 8 for pointer) // //In its current configuration we can store at most: // 65536 total tags (size_ and capacity_) // 256 clock launch tags (num_clock_launch_tags_) // 256 clock capture tags (num_clock_capture_tags_) // 256 data arrival tags (num_data_arrival_tags_) // (65536 - 3*256) data required tags (size_ - num_*) unsigned short size_ = 0; unsigned short capacity_ = 0; unsigned char num_clock_launch_tags_ = 0; unsigned char num_clock_capture_tags_ = 0; unsigned char num_data_arrival_tags_ = 0; std::unique_ptr<TimingTag[]> tags_; }; } //namepsace //Implementation #include "TimingTags.inl" <commit_msg>Fix iterator subtraction<commit_after>#pragma once #include <iterator> #include <memory> #include "TimingTag.hpp" #include "tatum_range.hpp" namespace tatum { /** * The 'TimingTags' class represents a collection of timing tags (see the 'TimingTag' class) * that belong to a particular node in the timing graph. * * Any operations performed using this task generally consider *all* associated tags. * For example, preforming a max_arr() call will apply the max accross all tags with matching * clock domain. If no matching tag is found, the tag will be added to the set of tags. * * Implementation * ==================== * Since each node in the timing graph typically has only a few tags (usually 1 or 2), we * perform linear searches to find match tags and tag ranges. * * Note that to allow efficient iteration of tag ranges (by type) we ensure that tags of the * same type are adjacent in the storage vector (i.e. the vector is sorted by type) */ class TimingTags { public: template<class T> class Iterator; private: //In practice the vast majority of nodes have only a handful of tags, //so we reserve space for some to avoid costly memory allocations constexpr static size_t DEFAULT_TAGS_TO_RESERVE = 3; constexpr static size_t GROWTH_FACTOR = 2; public: typedef Iterator<TimingTag> iterator; typedef Iterator<const TimingTag> const_iterator; typedef tatum::util::Range<const_iterator> tag_range; public: //Constructors TimingTags(size_t num_reserve=DEFAULT_TAGS_TO_RESERVE); TimingTags(const TimingTags&); TimingTags(TimingTags&&); TimingTags& operator=(TimingTags); ~TimingTags() = default; friend void swap(TimingTags& lhs, TimingTags& rhs); /* * Getters */ ///\returns The number of timing tags in this set size_t size() const; bool empty() const { return size() == 0; } ///\returns A range of all tags tag_range tags() const; ///\returns A range of all tags matching type tag_range tags(const TagType type) const; /* * Modifiers */ ///Adds a TimingTag to the current set provided it has a valid clock domain ///\param tag_pool The pool memory allocator used to allocate the tag ///\param src_tag The source tag who is inserted. Note that the src_tag is copied when inserted (the original is unchanged) void add_tag(const TimingTag& src_tag); /* * Operations */ ///Updates the arrival time of this set of tags to be the maximum. ///\param new_time The new arrival time to compare against ///\param base_tag The associated metat-data for new_time ///\remark Finds (or creates) the tag with the same clock domain as base_tag and update the arrival time if new_time is larger void max(const Time& new_time, const TimingTag& base_tag, bool arr_must_be_valid=false); ///Updates the required time of this set of tags to be the minimum. ///\param new_time The new arrival time to compare against ///\param base_tag The associated metat-data for new_time ///\remark Finds (or creates) the tag with the same clock domain as base_tag and update the required time if new_time is smaller void min(const Time& new_time, const TimingTag& base_tag, bool arr_must_be_valid=false); ///Clears the tags in the current set void clear(); public: //Iterator definition template<class T> class Iterator : public std::iterator<std::random_access_iterator_tag, T> { friend TimingTags; public: using value_type = typename std::iterator<std::random_access_iterator_tag, T>::value_type; using difference_type = typename std::iterator<std::random_access_iterator_tag, T>::difference_type; using pointer = typename std::iterator<std::random_access_iterator_tag, T>::pointer; using reference = typename std::iterator<std::random_access_iterator_tag, T>::reference; using iterator_category = typename std::iterator<std::random_access_iterator_tag, T>::iterator_category; public: Iterator(): p_(nullptr) {} Iterator(pointer p): p_(p) {} Iterator(const Iterator& other): p_(other.p_) {} Iterator& operator=(const Iterator& other) { p_ = other.p_; return *this; } friend bool operator==(Iterator a, Iterator b) { return a.p_ == b.p_; } friend bool operator!=(Iterator a, Iterator b) { return a.p_ != b.p_; } reference operator*() { return *p_; } pointer operator->() { return p_; } reference operator[](size_t n) { return *(p_ + n); } Iterator& operator++() { ++p_; return *this; } Iterator operator++(int) { Iterator old = *this; ++p_; return old; } Iterator& operator--() { --p_; return *this; } Iterator operator--(int) { Iterator old = *this; --p_; return old; } Iterator& operator+=(size_t n) { p_ += n; return *this; } Iterator& operator-=(size_t n) { p_ -= n; return *this; } friend Iterator operator+(Iterator lhs, size_t rhs) { return lhs += rhs; } friend Iterator operator-(Iterator lhs, size_t rhs) { return lhs -= rhs; } friend difference_type operator-(const Iterator lhs, const Iterator rhs) { return lhs.p_ - rhs.p_; } friend bool operator<(Iterator lhs, Iterator rhs) { return lhs.p_ < rhs.p_; } friend bool operator>(Iterator lhs, Iterator rhs) { return lhs.p_ > rhs.p_; } friend bool operator<=(Iterator lhs, Iterator rhs) { return lhs.p_ <= rhs.p_; } friend bool operator>=(Iterator lhs, Iterator rhs) { return lhs.p_ >= rhs.p_; } friend void swap(Iterator lhs, Iterator rhs) { std::swap(lhs.p_, rhs.p_); } private: T* p_ = nullptr; }; private: ///\returns An iterator to the first tag in the current set iterator begin(); const_iterator begin() const; iterator begin(TagType type); const_iterator begin(TagType type) const; ///\returns An iterator 'one-past-the-end' of the current set iterator end(); const_iterator end() const; iterator end(TagType type); const_iterator end(TagType type) const; size_t capacity() const; std::pair<iterator,bool> find_matching_tag(const TimingTag& tag, bool arr_must_be_valid); ///Finds a TimingTag in the current set that has clock domain id matching domain_id ///\returns An iterator to the tag if found, or end(tag.type()) if not found std::pair<iterator,bool> find_matching_tag(const TimingTag& tag); //Find a TimingTag matching the specified DATA_REQUIRED tag provided there is a valid associated //DATA_ARRIVAL tag std::pair<iterator,bool> find_matching_tag_with_valid_arrival(const TimingTag& tag); iterator insert(iterator iter, const TimingTag& tag); void grow_insert(size_t index, const TimingTag& tag); void increment_size(TagType type); private: //We don't expect many tags in a node so unsigned short's/unsigned char's //should be more than sufficient. This also allows the class //to be packed down to 16 bytes (8 for counters, 8 for pointer) // //In its current configuration we can store at most: // 65536 total tags (size_ and capacity_) // 256 clock launch tags (num_clock_launch_tags_) // 256 clock capture tags (num_clock_capture_tags_) // 256 data arrival tags (num_data_arrival_tags_) // (65536 - 3*256) data required tags (size_ - num_*) unsigned short size_ = 0; unsigned short capacity_ = 0; unsigned char num_clock_launch_tags_ = 0; unsigned char num_clock_capture_tags_ = 0; unsigned char num_data_arrival_tags_ = 0; std::unique_ptr<TimingTag[]> tags_; }; } //namepsace //Implementation #include "TimingTags.inl" <|endoftext|>
<commit_before>// Copyright (c) 2013 Maciej Gajewski #ifndef COROUTINES_MUTEX_HPP #define COROUTINES_MUTEX_HPP #include "profiling/profiling.hpp" #include <mutex> #include <atomic> namespace coroutines { class spinlock { public: spinlock() : _flag(ATOMIC_FLAG_INIT) { } spinlock(const char* name) : _flag(ATOMIC_FLAG_INIT) { #ifdef COROUTINES_SPINLOCKS_PROFILING CORO_PROF("spinlock", this, "created", name); #else (void)name; #endif } void lock() { #ifdef COROUTINES_SPINLOCKS_PROFILING // only report contested lock events if (try_lock()) return; CORO_PROF("spinlock", this, "spinning begin"); #endif while(_flag.test_and_set(std::memory_order_acquire)) ; // spin #ifdef COROUTINES_SPINLOCKS_PROFILING CORO_PROF("spinlock", this, "spinning end"); #endif } bool try_lock() { #ifdef COROUTINES_SPINLOCKS_PROFILING if (!_flag.test_and_set(std::memory_order_acquire)) { CORO_PROF("spinlock", this, "locked"); return true; } else return false; #else return !_flag.test_and_set(std::memory_order_acquire); #endif } void unlock() { #ifdef COROUTINES_SPINLOCKS_PROFILING CORO_PROF("spinlock", this, "unlocked"); #endif _flag.clear(std::memory_order_release); } private: std::atomic_flag _flag; }; //typedef std::mutex mutex; typedef spinlock mutex; } #endif <commit_msg>rw_spinlock code added, now its time for testing<commit_after>// Copyright (c) 2013 Maciej Gajewski #ifndef COROUTINES_MUTEX_HPP #define COROUTINES_MUTEX_HPP #include "profiling/profiling.hpp" #include <mutex> #include <atomic> #include <cstdint> namespace coroutines { class spinlock { public: spinlock() : _flag(ATOMIC_FLAG_INIT) { } spinlock(const char* name) : _flag(ATOMIC_FLAG_INIT) { #ifdef COROUTINES_SPINLOCKS_PROFILING CORO_PROF("spinlock", this, "created", name); #else (void)name; #endif } void lock() { #ifdef COROUTINES_SPINLOCKS_PROFILING // only report contested lock events if (try_lock()) return; CORO_PROF("spinlock", this, "spinning begin"); #endif while(_flag.test_and_set(std::memory_order_acquire)) ; // spin #ifdef COROUTINES_SPINLOCKS_PROFILING CORO_PROF("spinlock", this, "spinning end"); #endif } bool try_lock() { #ifdef COROUTINES_SPINLOCKS_PROFILING if (!_flag.test_and_set(std::memory_order_acquire)) { CORO_PROF("spinlock", this, "locked"); return true; } else return false; #else return !_flag.test_and_set(std::memory_order_acquire); #endif } void unlock() { #ifdef COROUTINES_SPINLOCKS_PROFILING CORO_PROF("spinlock", this, "unlocked"); #endif _flag.clear(std::memory_order_release); } private: std::atomic_flag _flag; }; //typedef std::mutex mutex; typedef spinlock mutex; // based on folly's RWSpinLock class rw_spinlock { enum : std::int32_t { READER = 4, UPGRADED = 2, WRITER = 1 }; public: rw_spinlock() : _bits(0) {} void lock() { while (!try_lock()) ; } // Writer is responsible for clearing up both the UPGRADED and WRITER bits. void unlock() { static_assert(READER > WRITER + UPGRADED, "wrong bits!"); _bits.fetch_and(~(WRITER | UPGRADED), std::memory_order_release); } // SharedLockable Concept void lock_shared() { while (try_lock_shared()) ; } void unlock_shared() { _bits.fetch_add(-READER, std::memory_order_release); } // Downgrade the lock from writer status to reader status. void unlock_and_lock_shared() { _bits.fetch_add(READER, std::memory_order_acquire); unlock(); } // UpgradeLockable Concept void lock_upgrade() { while (!try_lock_upgrade()) ; } void unlock_upgrade() { _bits.fetch_add(-UPGRADED, std::memory_order_acq_rel); } // unlock upgrade and try to acquire write lock void unlock_upgrade_and_lock() { while (!try_unlock_upgrade_and_lock()) ; } // unlock upgrade and read lock atomically void unlock_upgrade_and_lock_shared() { _bits.fetch_add(READER - UPGRADED, std::memory_order_acq_rel); } // write unlock and upgrade lock atomically void unlock_and_lock_upgrade() { // need to do it in two steps here -- as the UPGRADED bit might be OR-ed at // the same time when other threads are trying do try_lock_upgrade(). _bits.fetch_or(UPGRADED, std::memory_order_acquire); _bits.fetch_add(-WRITER, std::memory_order_release); } // Attempt to acquire writer permission. Return false if we didn't get it. bool try_lock() { std::int32_t expect = 0; return _bits.compare_exchange_strong(expect, WRITER, std::memory_order_acq_rel); } // Try to get reader permission on the lock. This can fail if we // find out someone is a writer or upgrader. // Setting the UPGRADED bit would allow a writer-to-be to indicate // its intention to write and block any new readers while waiting // for existing readers to finish and release their read locks. This // helps avoid starving writers (promoted from upgraders). bool try_lock_shared() { // fetch_add is considerably (100%) faster than compare_exchange, // so here we are optimizing for the common (lock success) case. std::int32_t value = _bits.fetch_add(READER, std::memory_order_acquire); if (value & (WRITER|UPGRADED)) { _bits.fetch_add(-READER, std::memory_order_release); return false; } return true; } // try to unlock upgrade and write lock atomically bool try_unlock_upgrade_and_lock() { std::int32_t expect = UPGRADED; return _bits.compare_exchange_strong(expect, WRITER, std::memory_order_acq_rel); } // try to acquire an upgradable lock. bool try_lock_upgrade() { std::int32_t value = _bits.fetch_or(UPGRADED, std::memory_order_acquire); // Note: when failed, we cannot flip the UPGRADED bit back, // as in this case there is either another upgrade lock or a write lock. // If it's a write lock, the bit will get cleared up when that lock's done // with unlock(). return ((value & (UPGRADED | WRITER)) == 0); } private: std::atomic<int32_t> _bits; }; } #endif <|endoftext|>
<commit_before>// Copyright (c) 2010 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 "webkit/plugins/ppapi/ppb_nacl_private_impl.h" #include "base/rand_util_c.h" #include "ppapi/c/private/ppb_nacl_private.h" #include "webkit/glue/webkit_glue.h" namespace webkit { namespace ppapi { namespace { bool LaunchSelLdr(const char* alleged_url, int socket_count, void* imc_handles, void* nacl_process_handle, int* nacl_process_id) { #if !defined(DISABLE_NACL) return webkit_glue::LaunchSelLdr(alleged_url, socket_count, imc_handles, nacl_process_handle, nacl_process_id); #else return 0; #endif } int UrandomFD(void) { #if defined(OS_POSIX) return GetUrandomFD(); #else return 0; #endif } } // namespace const PPB_NaCl_Private ppb_nacl = { &LaunchSelLdr, &UrandomFD, }; // static const PPB_NaCl_Private* PPB_NaCl_Private_Impl::GetInterface() { return &ppb_nacl; } } // namespace ppapi } // namespace webkit <commit_msg>By zero, I mean false<commit_after>// Copyright (c) 2010 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 "webkit/plugins/ppapi/ppb_nacl_private_impl.h" #include "base/rand_util_c.h" #include "ppapi/c/private/ppb_nacl_private.h" #include "webkit/glue/webkit_glue.h" namespace webkit { namespace ppapi { namespace { bool LaunchSelLdr(const char* alleged_url, int socket_count, void* imc_handles, void* nacl_process_handle, int* nacl_process_id) { #if !defined(DISABLE_NACL) return webkit_glue::LaunchSelLdr(alleged_url, socket_count, imc_handles, nacl_process_handle, nacl_process_id); #else return false; #endif } int UrandomFD(void) { #if defined(OS_POSIX) return GetUrandomFD(); #else return 0; #endif } } // namespace const PPB_NaCl_Private ppb_nacl = { &LaunchSelLdr, &UrandomFD, }; // static const PPB_NaCl_Private* PPB_NaCl_Private_Impl::GetInterface() { return &ppb_nacl; } } // namespace ppapi } // namespace webkit <|endoftext|>
<commit_before>/* * Copyright (c) 2010 Digital Bazaar, Inc. All rights reserved. */ #define __STDC_FORMAT_MACROS #define __STDC_LIMIT_MACROS #define __STDC_CONSTANT_MACROS #include "monarch/ws/WebServer.h" #include "monarch/crypto/AsymmetricKeyFactory.h" #include "monarch/data/json/JsonWriter.h" #include "monarch/logging/Logging.h" #include "monarch/net/NullSocketDataPresenter.h" #include "monarch/net/SslSocketDataPresenter.h" using namespace std; using namespace monarch::config; using namespace monarch::crypto; using namespace monarch::data::json; using namespace monarch::http; using namespace monarch::io; using namespace monarch::net; using namespace monarch::rt; using namespace monarch::util; using namespace monarch::ws; WebServer::WebServer() : mServer(NULL), mHostAddress(NULL), mSslContext(NULL), mSocketDataPresenterList(NULL), mServiceId(Server::sInvalidServiceId) { } WebServer::~WebServer() { } bool WebServer::initialize(Config& cfg) { bool rval = true; MO_CAT_DEBUG(MO_WS_CAT, "WebServer initializing..."); // create default container if one is not set if(mContainer.isNull()) { mContainer = new WebServiceContainer(); } // get basic config // security: on/off/both bool secure; bool nonSecure; const char* security = cfg["security"]->getString(); if(strcasecmp(security, "on") == 0) { secure = true; nonSecure = false; } else if(strcasecmp(security, "off") == 0) { secure = false; nonSecure = true; } else { secure = nonSecure = true; } if(secure) { MO_CAT_DEBUG(MO_WS_CAT, "WebServer enabling SSL..."); // FIXME: make configurable /* Create SSL server context. "TLS" is most secure and recent SSL but we must use "ALL" to handle browsers that use SSL 3.0. */ mSslContext = new SslContext("ALL", false); // setup certificate file and private key File certFile(cfg["certificate"]->getString()); File pkeyFile(cfg["privateKey"]->getString()); MO_CAT_DEBUG(MO_WS_CAT, "WebServer setting SSL certificate and private key..."); // set certificate and private key for SSL context rval = mSslContext->setCertificate(certFile) && mSslContext->setPrivateKey(pkeyFile); if(rval) { MO_CAT_DEBUG(MO_WS_CAT, "WebServer reading SSL certificate..."); // set default virtual host based on certificate common name ByteBuffer b(certFile->getLength()); rval = certFile.readBytes(&b); if(rval) { MO_CAT_DEBUG(MO_WS_CAT, "WebServer loading SSL certificate from PEM..."); AsymmetricKeyFactory afk; X509CertificateRef cert = afk.loadCertificateFromPem( b.data(), b.length()); rval = !cert.isNull(); if(rval) { DynamicObject subject = cert->getSubject(); string commonName = cert->getField(subject, "CN"); MO_CAT_DEBUG(MO_WS_CAT, "Setting default virtual host to common name: %s", commonName.c_str()); mSslContext->setVirtualHost(commonName.c_str()); } } } MO_CAT_DEBUG(MO_WS_CAT, "WebServer SSL setup complete."); } if(rval) { // setup host address const char* host = cfg["host"]->getString(); uint32_t port = cfg["port"]->getUInt32(); mHostAddress = new InternetAddress(host, port); // handle socket presentation layer mSocketDataPresenterList = new SocketDataPresenterList(true); if(secure) { SslSocketDataPresenter* ssdp = new SslSocketDataPresenter(&(*mSslContext)); mSocketDataPresenterList->add(ssdp); } if(nonSecure) { NullSocketDataPresenter* nsdp = new NullSocketDataPresenter(); mSocketDataPresenterList->add(nsdp); } // get the list of default domains DynamicObject domains(NULL); if(cfg->hasMember("domains")) { domains = cfg["domains"].clone(); if(domains->length() == 0) { // add wildcard if no domains specified domains->append() = "*"; } } else { // no specified default domains, so use "*" domains = DynamicObject(); domains->append() = "*"; } mContainer->setDefaultDomains(domains); MO_CAT_INFO(MO_WS_CAT, "WebServer running web services on domains: %s", JsonWriter::writeToString(domains, false, false).c_str()); } if(rval) { MO_CAT_DEBUG(MO_WS_CAT, "WebServer initialized."); } return rval; } void WebServer::cleanup() { // reset container mContainer->clear(); DynamicObject domains; domains->append() = "*"; mContainer->setDefaultDomains(domains); // clean up mHostAddress.setNull(); mSslContext.setNull(); mSocketDataPresenterList.setNull(); } bool WebServer::enable(Server* server, const char* name) { bool rval = true; // add http connection service mServiceId = server->addConnectionService( &(*mHostAddress), mContainer->getServicer(), &(*mSocketDataPresenterList), name); if(mServiceId == Server::sInvalidServiceId) { // could not add connection service rval = false; } else { mServer = server; MO_CAT_INFO(MO_WS_CAT, "WebServer serving on %s", mHostAddress->toString(false).c_str()); } return rval; } void WebServer::disable() { // remove http connection service if(mServiceId != Server::sInvalidServiceId) { mServer->removePortService(mServiceId); mServiceId = Server::sInvalidServiceId; mServer = NULL; } } void WebServer::setContainer(WebServiceContainerRef& c) { mContainer = c; } WebServiceContainerRef& WebServer::getContainer() { return mContainer; } InternetAddressRef WebServer::getHostAddress() { return mHostAddress; } SslContextRef WebServer::getSslContext() { return mSslContext; } <commit_msg>Added WebServer name to log output.<commit_after>/* * Copyright (c) 2010 Digital Bazaar, Inc. All rights reserved. */ #define __STDC_FORMAT_MACROS #define __STDC_LIMIT_MACROS #define __STDC_CONSTANT_MACROS #include "monarch/ws/WebServer.h" #include "monarch/crypto/AsymmetricKeyFactory.h" #include "monarch/data/json/JsonWriter.h" #include "monarch/logging/Logging.h" #include "monarch/net/NullSocketDataPresenter.h" #include "monarch/net/SslSocketDataPresenter.h" using namespace std; using namespace monarch::config; using namespace monarch::crypto; using namespace monarch::data::json; using namespace monarch::http; using namespace monarch::io; using namespace monarch::net; using namespace monarch::rt; using namespace monarch::util; using namespace monarch::ws; WebServer::WebServer() : mServer(NULL), mHostAddress(NULL), mSslContext(NULL), mSocketDataPresenterList(NULL), mServiceId(Server::sInvalidServiceId) { } WebServer::~WebServer() { } bool WebServer::initialize(Config& cfg) { bool rval = true; MO_CAT_DEBUG(MO_WS_CAT, "WebServer initializing..."); // create default container if one is not set if(mContainer.isNull()) { mContainer = new WebServiceContainer(); } // get basic config // security: on/off/both bool secure; bool nonSecure; const char* security = cfg["security"]->getString(); if(strcasecmp(security, "on") == 0) { secure = true; nonSecure = false; } else if(strcasecmp(security, "off") == 0) { secure = false; nonSecure = true; } else { secure = nonSecure = true; } if(secure) { MO_CAT_DEBUG(MO_WS_CAT, "WebServer enabling SSL..."); // FIXME: make configurable /* Create SSL server context. "TLS" is most secure and recent SSL but we must use "ALL" to handle browsers that use SSL 3.0. */ mSslContext = new SslContext("ALL", false); // setup certificate file and private key File certFile(cfg["certificate"]->getString()); File pkeyFile(cfg["privateKey"]->getString()); MO_CAT_DEBUG(MO_WS_CAT, "WebServer setting SSL certificate and private key..."); // set certificate and private key for SSL context rval = mSslContext->setCertificate(certFile) && mSslContext->setPrivateKey(pkeyFile); if(rval) { MO_CAT_DEBUG(MO_WS_CAT, "WebServer reading SSL certificate..."); // set default virtual host based on certificate common name ByteBuffer b(certFile->getLength()); rval = certFile.readBytes(&b); if(rval) { MO_CAT_DEBUG(MO_WS_CAT, "WebServer loading SSL certificate from PEM..."); AsymmetricKeyFactory afk; X509CertificateRef cert = afk.loadCertificateFromPem( b.data(), b.length()); rval = !cert.isNull(); if(rval) { DynamicObject subject = cert->getSubject(); string commonName = cert->getField(subject, "CN"); MO_CAT_DEBUG(MO_WS_CAT, "Setting default virtual host to common name: %s", commonName.c_str()); mSslContext->setVirtualHost(commonName.c_str()); } } } MO_CAT_DEBUG(MO_WS_CAT, "WebServer SSL setup complete."); } if(rval) { // setup host address const char* host = cfg["host"]->getString(); uint32_t port = cfg["port"]->getUInt32(); mHostAddress = new InternetAddress(host, port); // handle socket presentation layer mSocketDataPresenterList = new SocketDataPresenterList(true); if(secure) { SslSocketDataPresenter* ssdp = new SslSocketDataPresenter(&(*mSslContext)); mSocketDataPresenterList->add(ssdp); } if(nonSecure) { NullSocketDataPresenter* nsdp = new NullSocketDataPresenter(); mSocketDataPresenterList->add(nsdp); } // get the list of default domains DynamicObject domains(NULL); if(cfg->hasMember("domains")) { domains = cfg["domains"].clone(); if(domains->length() == 0) { // add wildcard if no domains specified domains->append() = "*"; } } else { // no specified default domains, so use "*" domains = DynamicObject(); domains->append() = "*"; } mContainer->setDefaultDomains(domains); MO_CAT_INFO(MO_WS_CAT, "WebServer running web services on domains: %s", JsonWriter::writeToString(domains, false, false).c_str()); } if(rval) { MO_CAT_DEBUG(MO_WS_CAT, "WebServer initialized."); } return rval; } void WebServer::cleanup() { // reset container mContainer->clear(); DynamicObject domains; domains->append() = "*"; mContainer->setDefaultDomains(domains); // clean up mHostAddress.setNull(); mSslContext.setNull(); mSocketDataPresenterList.setNull(); } bool WebServer::enable(Server* server, const char* name) { bool rval = true; // add http connection service mServiceId = server->addConnectionService( &(*mHostAddress), mContainer->getServicer(), &(*mSocketDataPresenterList), name); if(mServiceId == Server::sInvalidServiceId) { // could not add connection service rval = false; } else { mServer = server; MO_CAT_INFO(MO_WS_CAT, "WebServer %s serving on %s", name, mHostAddress->toString(false).c_str()); } return rval; } void WebServer::disable() { // remove http connection service if(mServiceId != Server::sInvalidServiceId) { mServer->removePortService(mServiceId); mServiceId = Server::sInvalidServiceId; mServer = NULL; } } void WebServer::setContainer(WebServiceContainerRef& c) { mContainer = c; } WebServiceContainerRef& WebServer::getContainer() { return mContainer; } InternetAddressRef WebServer::getHostAddress() { return mHostAddress; } SslContextRef WebServer::getSslContext() { return mSslContext; } <|endoftext|>
<commit_before>#include "Pixel.h" #define PIXEL WalrusRPG::Graphics::Pixel PIXEL::Pixel(std::uint16_t color) : value(color) { } PIXEL::Pixel(Pixel &pix) : value((std::uint8_t) pix) { } PIXEL::Pixel(std::uint8_t red, std::uint8_t green, std::uint8_t blue) : b(blue >> 3), g(green >> 2), r(red >> 3) { } PIXEL::operator std::uint16_t() const { return value; } PIXEL &PIXEL::operator=(unsigned value) { this->value = value; return *this; } #define CONST_COLOR(color, r, g, b) \ const WalrusRPG::Graphics::Pixel WalrusRPG::Graphics::color(r, g, b) CONST_COLOR(Black, 0, 0, 0); CONST_COLOR(White, 255, 255, 255); CONST_COLOR(Red, 255, 0, 0); CONST_COLOR(Green, 0, 255, 0); CONST_COLOR(Blue, 0, 0, 255); #undef CONST_COLOR <commit_msg>Fixed pixel copy constructor<commit_after>#include "Pixel.h" #define PIXEL WalrusRPG::Graphics::Pixel PIXEL::Pixel(std::uint16_t color) : value(color) { } PIXEL::Pixel(Pixel &pix) : value(pix.value) { } PIXEL::Pixel(std::uint8_t red, std::uint8_t green, std::uint8_t blue) : b(blue >> 3), g(green >> 2), r(red >> 3) { } PIXEL::operator std::uint16_t() const { return value; } PIXEL &PIXEL::operator=(unsigned value) { this->value = value; return *this; } #define CONST_COLOR(color, r, g, b) \ const WalrusRPG::Graphics::Pixel WalrusRPG::Graphics::color(r, g, b) CONST_COLOR(Black, 0, 0, 0); CONST_COLOR(White, 255, 255, 255); CONST_COLOR(Red, 255, 0, 0); CONST_COLOR(Green, 0, 255, 0); CONST_COLOR(Blue, 0, 0, 255); #undef CONST_COLOR <|endoftext|>
<commit_before>// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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 "google/cloud/internal/curl_handle_factory.h" #include <benchmark/benchmark.h> namespace google { namespace cloud { namespace rest_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace { class PoolFixture : public ::benchmark::Fixture { public: PoolFixture() : pool_(128) {} CurlHandleFactory& pool() { return pool_; } private: PooledCurlHandleFactory pool_; }; bool CreateAndCleanup(CurlHandleFactory& factory) { auto h = factory.CreateHandle(); auto m = factory.CreateMultiHandle(); auto const success = h && m; factory.CleanupMultiHandle(std::move(m), HandleDisposition::kKeep); factory.CleanupHandle(std::move(h), HandleDisposition::kKeep); return success; } BENCHMARK_DEFINE_F(PoolFixture, Burst)(benchmark::State& state) { for (auto _ : state) { if (!CreateAndCleanup(pool())) { state.SkipWithError("error creating handles"); break; } } } BENCHMARK_REGISTER_F(PoolFixture, Burst)->ThreadRange(1, 1 << 8)->UseRealTime(); BENCHMARK_DEFINE_F(PoolFixture, Linear)(benchmark::State& state) { for (auto _ : state) { for (auto i = 0; i != state.range(0); ++i) { if (!CreateAndCleanup(pool())) { state.SkipWithError("error creating handles"); break; } } } state.SetComplexityN(state.range(0)); } BENCHMARK_REGISTER_F(PoolFixture, Linear) ->RangeMultiplier(2) ->Ranges({{1, 1 << 10}}) ->Complexity(benchmark::oN); } // namespace GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace rest_internal } // namespace cloud } // namespace google <commit_msg>doc(rest): record baseline for HandleFactory benchmark (#9578)<commit_after>// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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 "google/cloud/internal/curl_handle_factory.h" #include <benchmark/benchmark.h> namespace google { namespace cloud { namespace rest_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace { class PoolFixture : public ::benchmark::Fixture { public: PoolFixture() : pool_(128) {} CurlHandleFactory& pool() { return pool_; } private: PooledCurlHandleFactory pool_; }; bool CreateAndCleanup(CurlHandleFactory& factory) { auto h = factory.CreateHandle(); auto m = factory.CreateMultiHandle(); auto const success = h && m; factory.CleanupMultiHandle(std::move(m), HandleDisposition::kKeep); factory.CleanupHandle(std::move(h), HandleDisposition::kKeep); return success; } // clang-format off // Run on (96 X 2000 MHz CPU s) // CPU Caches: // L1 Data 32 KiB (x48) // L1 Instruction 32 KiB (x48) // L2 Unified 1024 KiB (x48) // L3 Unified 39424 KiB (x2) // Load Average: 15.12, 5.10, 1.98 //---------------------------------------------------------------------------------- // Benchmark Time CPU Iterations //---------------------------------------------------------------------------------- // PoolFixture/Burst/real_time/threads:1 611 ns 611 ns 1138757 // PoolFixture/Burst/real_time/threads:2 753 ns 1503 ns 931064 // PoolFixture/Burst/real_time/threads:4 912 ns 3460 ns 775028 // PoolFixture/Burst/real_time/threads:8 977 ns 6946 ns 719024 // PoolFixture/Burst/real_time/threads:16 1038 ns 14855 ns 645392 // PoolFixture/Burst/real_time/threads:32 1280 ns 38140 ns 570144 // PoolFixture/Burst/real_time/threads:64 1665 ns 101765 ns 510976 // PoolFixture/Burst/real_time/threads:128 1846 ns 172375 ns 388736 // PoolFixture/Burst/real_time/threads:256 1859 ns 180947 ns 377600 // clang-format on BENCHMARK_DEFINE_F(PoolFixture, Burst)(benchmark::State& state) { for (auto _ : state) { if (!CreateAndCleanup(pool())) { state.SkipWithError("error creating handles"); break; } } } BENCHMARK_REGISTER_F(PoolFixture, Burst)->ThreadRange(1, 1 << 8)->UseRealTime(); // clang-format off // Run on (96 X 2000 MHz CPU s) // CPU Caches: // L1 Data 32 KiB (x48) // L1 Instruction 32 KiB (x48) // L2 Unified 1024 KiB (x48) // L3 Unified 39424 KiB (x2) // Load Average: 10.79, 7.87, 3.39 //------------------------------------------------------------------ // Benchmark Time CPU Iterations //------------------------------------------------------------------ // PoolFixture/Linear/1 628 ns 628 ns 1098609 // PoolFixture/Linear/2 1255 ns 1255 ns 553833 // PoolFixture/Linear/4 2491 ns 2490 ns 278630 // PoolFixture/Linear/8 4967 ns 4967 ns 140583 // PoolFixture/Linear/16 9935 ns 9935 ns 70534 // PoolFixture/Linear/32 19896 ns 19892 ns 35236 // PoolFixture/Linear/64 39706 ns 39700 ns 17636 // PoolFixture/Linear/128 79433 ns 79428 ns 8816 // PoolFixture/Linear/256 159164 ns 159102 ns 4392 // PoolFixture/Linear/512 318709 ns 318687 ns 2202 // PoolFixture/Linear/1024 638671 ns 638514 ns 1098 // PoolFixture/Linear_BigO 623.33 N 623.20 N // PoolFixture/Linear_RMS 0 % 0 % // clang-format on BENCHMARK_DEFINE_F(PoolFixture, Linear)(benchmark::State& state) { for (auto _ : state) { for (auto i = 0; i != state.range(0); ++i) { if (!CreateAndCleanup(pool())) { state.SkipWithError("error creating handles"); break; } } } state.SetComplexityN(state.range(0)); } BENCHMARK_REGISTER_F(PoolFixture, Linear) ->RangeMultiplier(2) ->Ranges({{1, 1 << 10}}) ->Complexity(benchmark::oN); } // namespace GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace rest_internal } // namespace cloud } // namespace google <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #include "../../StroikaPreComp.h" #if qHasFeature_OpenSSL #include <openssl/evp.h> #include <openssl/err.h> #endif #include "../../Containers/Common.h" #include "../../Debug/Assertions.h" #include "../../Execution/Common.h" #include "../../Memory/SmallStackBuffer.h" #include "OpenSSLCryptoStream.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Cryptography; using namespace Stroika::Foundation::Cryptography::Encoding; using namespace Stroika::Foundation::Memory; using namespace Stroika::Foundation::Streams; using Memory::BLOB; // @todo examine/test https://github.com/saju/misc/blob/master/misc/openssl_aes.c #if qHasFeature_OpenSSL && defined (_MSC_VER) // Use #pragma comment lib instead of explicit entry in the lib entry of the project file #pragma comment (lib, "libeay32.lib") #pragma comment (lib, "ssleay32.lib") #endif //// VERY ROUGH DRAFT - NOT VERY CLOSE TO CORRECT FOR ALL ALGORITHSM //// SEE http://www.openssl.org/docs/crypto/EVP_EncryptInit.html /// SEE https://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption //// for details on what todo #if qHasFeature_OpenSSL namespace { struct InOutStrmCommon_ { InOutStrmCommon_ (const OpenSSLCryptoParams& cryptoParams, Direction d) : fCTX_ () , fFinalCalled_ (false) { ::EVP_CIPHER_CTX_init (&fCTX_); cryptoParams.fInitializer (&fCTX_, d); } InOutStrmCommon_ (const InOutStrmCommon_&) = delete; InOutStrmCommon_& operator= (const InOutStrmCommon_&) = delete; ~InOutStrmCommon_ () { Verify (::EVP_CIPHER_CTX_cleanup (&fCTX_) == 1); } static constexpr size_t _GetMinOutBufSize (size_t n) { return n + EVP_MAX_BLOCK_LENGTH; } // return nBytes in outBuf, throws on error size_t _runOnce (const Byte* data2ProcessStart, const Byte* data2ProcessEnd, Byte* outBufStart, Byte* outBufEnd) { Require (outBufStart <= outBufEnd and static_cast<size_t> (outBufEnd - outBufStart) >= _GetMinOutBufSize (data2ProcessEnd - data2ProcessStart)); // always need out buf big enuf for inbuf int outLen = 0; Cryptography::OpenSSL::Exception::ThrowLastErrorIfFailed (::EVP_CipherUpdate (&fCTX_, outBufStart, &outLen, data2ProcessStart, static_cast<int> (data2ProcessEnd - data2ProcessStart))); Ensure (outLen >= 0); Ensure (outLen <= (outBufEnd - outBufStart)); return size_t (outLen); } // return nBytes in outBuf, throws on error // Can call multiple times - it keeps track itself if finalized. size_t _cipherFinal (Byte* outBufStart, Byte* outBufEnd) { Require (outBufStart <= outBufEnd and static_cast<size_t> (outBufEnd - outBufStart) >= _GetMinOutBufSize (0)); if (fFinalCalled_) { return 0; // not an error - just zero more bytes } int outLen = 0; Cryptography::OpenSSL::Exception::ThrowLastErrorIfFailed (::EVP_CipherFinal_ex (&fCTX_, outBufStart, &outLen)); fFinalCalled_ = true; Ensure (outLen >= 0); Ensure (outLen <= (outBufEnd - outBufStart)); return size_t (outLen); } EVP_CIPHER_CTX fCTX_; bool fFinalCalled_; }; } #endif #if qHasFeature_OpenSSL class OpenSSLInputStream::IRep_ : public InputStream<Byte>::_IRep, private InOutStrmCommon_ { private: DEFINE_CONSTEXPR_CONSTANT(size_t, kInBufSize_, 10 * 1024); public: IRep_ (const OpenSSLCryptoParams& cryptoParams, Direction d, const InputStream<Byte>& realIn) : InputStream<Byte>::_IRep () , InOutStrmCommon_ (cryptoParams, d) , fCriticalSection_ () , fOutBuf_ (_GetMinOutBufSize (kInBufSize_)) , fOutBufStart_ (nullptr) , fOutBufEnd_ (nullptr) , fRealIn_ (realIn) { } virtual bool IsSeekable () const override { return false; } virtual SeekOffsetType GetReadOffset () const override { RequireNotReached (); return 0; } virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override { RequireNotReached (); return 0; } virtual size_t Read (SeekOffsetType* offset, Byte* intoStart, Byte* intoEnd) override { Require (offset == nullptr); // not seekable /* * Keep track if unread bytes in fOutBuf_ - bounded by fOutBufStart_ and fOutBufEnd_. * If none to read there - pull from fRealIn_ src, and push those through the cipher. * and use that to re-populate fOutBuf_. */ Require (intoStart < intoEnd); auto critSec { Execution::make_unique_lock (fCriticalSection_) }; if (fOutBufStart_ == fOutBufEnd_) { Byte toDecryptBuf[kInBufSize_]; size_t n2Decrypt = fRealIn_.Read (begin (toDecryptBuf), end (toDecryptBuf)); if (n2Decrypt == 0) { size_t nBytesInOutBuf = _cipherFinal (fOutBuf_.begin (), fOutBuf_.end ()); Assert (nBytesInOutBuf <= fOutBuf_.GetSize ()); fOutBufStart_ = fOutBuf_.begin (); fOutBufEnd_ = fOutBufStart_ + nBytesInOutBuf; } else { fOutBuf_.GrowToSize (_GetMinOutBufSize (NEltsOf (toDecryptBuf))); size_t nBytesInOutBuf = _runOnce (begin (toDecryptBuf), begin (toDecryptBuf) + n2Decrypt, fOutBuf_.begin (), fOutBuf_.end ()); Assert (nBytesInOutBuf <= fOutBuf_.GetSize ()); fOutBufStart_ = fOutBuf_.begin (); fOutBufEnd_ = fOutBufStart_ + nBytesInOutBuf; } } if (fOutBufStart_ < fOutBufEnd_) { size_t n2Copy = min (fOutBufEnd_ - fOutBufStart_, intoEnd - intoStart); (void)::memcpy (intoStart, fOutBufStart_, n2Copy); fOutBufStart_ += n2Copy; return n2Copy; } return 0; // EOF } private: mutable mutex fCriticalSection_; Memory::SmallStackBuffer < Byte, kInBufSize_ + EVP_MAX_BLOCK_LENGTH > fOutBuf_; Byte* fOutBufStart_; Byte* fOutBufEnd_; InputStream<Byte> fRealIn_; }; #endif #if qHasFeature_OpenSSL class OpenSSLOutputStream::IRep_ : public OutputStream<Byte>::_IRep, private InOutStrmCommon_ { public: IRep_ (const OpenSSLCryptoParams& cryptoParams, Direction d, const OutputStream<Byte>& realOut) : OutputStream<Byte>::_IRep () , InOutStrmCommon_ (cryptoParams, d) , fCriticalSection_ () , fRealOut_ (realOut) { } virtual ~IRep_ () { // no need for critical section because at most one thread can be running DTOR at a time, and no other methods can be running try { Flush (); } catch (...) { // not great to do in DTOR, because we must drop exceptions on the floor! } } virtual bool IsSeekable () const override { return false; } virtual SeekOffsetType GetWriteOffset () const override { RequireNotReached (); return 0; } virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override { RequireNotReached (); return 0; } // pointer must refer to valid memory at least bufSize long, and cannot be nullptr. BufSize must always be >= 1. // Writes always succeed fully or throw. virtual void Write (const Byte* start, const Byte* end) override { Require (start < end); // for OutputStream<Byte> - this funciton requires non-empty write Memory::SmallStackBuffer < Byte, 1000 + EVP_MAX_BLOCK_LENGTH > outBuf (_GetMinOutBufSize (end - start)); auto critSec { Execution::make_unique_lock (fCriticalSection_) }; size_t nBytesEncypted = _runOnce (start, end, outBuf.begin (), outBuf.end ()); Assert (nBytesEncypted <= outBuf.GetSize ()); fRealOut_.Write (outBuf.begin (), outBuf.begin () + nBytesEncypted); } virtual void Flush () override { Byte outBuf[EVP_MAX_BLOCK_LENGTH]; size_t nBytesInOutBuf = _cipherFinal (begin (outBuf), end (outBuf)); Assert (nBytesInOutBuf < sizeof (outBuf)); fRealOut_.Write (begin (outBuf), begin (outBuf) + nBytesInOutBuf); } private: mutable recursive_mutex fCriticalSection_; OutputStream<Byte> fRealOut_; }; #endif #if qHasFeature_OpenSSL /* ******************************************************************************** ******************** Cryptography::OpenSSLInputStream ************************** ******************************************************************************** */ namespace { void ApplySettings2CTX_ (EVP_CIPHER_CTX* ctx, const EVP_CIPHER* cipher, Direction d, bool nopad, bool useArgumentKeyLength, const Memory::BLOB& key, const Memory::BLOB& initialIV) { RequireNotNull (ctx); RequireNotNull (cipher); bool enc = (d == Direction::eEncrypt); if (nopad) { Verify (::EVP_CIPHER_CTX_set_padding (ctx, 0) == 1); } Cryptography::OpenSSL::Exception::ThrowLastErrorIfFailed (::EVP_CipherInit_ex (ctx, cipher, NULL, nullptr, nullptr, enc)); size_t keyLen = EVP_CIPHER_CTX_key_length (ctx); size_t ivLen = EVP_CIPHER_CTX_iv_length (ctx); if (useArgumentKeyLength) { keyLen = key.length (); Verify (::EVP_CIPHER_CTX_set_key_length (ctx, static_cast<int> (keyLen)) == 1); } Memory::SmallStackBuffer<Byte> useKey { keyLen }; Memory::SmallStackBuffer<Byte> useIV { ivLen }; memset (useKey.begin (), 0, keyLen); memset (useIV.begin (), 0, ivLen); memcpy (useKey.begin (), key.begin (), min(keyLen, key.size ())); memcpy (useIV.begin (), initialIV.begin (), min(ivLen, initialIV.size ())); Cryptography::OpenSSL::Exception::ThrowLastErrorIfFailed (::EVP_CipherInit_ex (ctx, nullptr, NULL, useKey.begin (), useIV.begin (), enc)); } } OpenSSLCryptoParams::OpenSSLCryptoParams (CipherAlgorithm alg, Memory::BLOB key, Memory::BLOB initialIV) : fInitializer () { bool nopad = false; switch (alg) { case CipherAlgorithm::eRC2_CBC: { fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) { ApplySettings2CTX_ (ctx, ::EVP_rc2_cbc (), d, nopad, true, key, initialIV); }; } break; case CipherAlgorithm::eRC2_ECB: { fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) { ApplySettings2CTX_ (ctx, ::EVP_rc2_ecb (), d, nopad, true, key, initialIV); }; } break; case CipherAlgorithm::eRC2_CFB: { fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) { ApplySettings2CTX_ (ctx, ::EVP_rc2_cfb (), d, nopad, true, key, initialIV); }; } break; case CipherAlgorithm::eRC2_OFB: { fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) { ApplySettings2CTX_ (ctx, ::EVP_rc2_ofb (), d, nopad, true, key, initialIV); }; } break; case CipherAlgorithm::eRC4: { fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) { ApplySettings2CTX_ (ctx, ::EVP_rc4 (), d, nopad, true, key, initialIV); }; } break; default: { fInitializer = [alg, nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) { ApplySettings2CTX_ (ctx, Convert2OpenSSL (alg), d, nopad, false, key, initialIV); }; break; } } } OpenSSLCryptoParams::OpenSSLCryptoParams (CipherAlgorithm alg, const DerivedKey& derivedKey) : OpenSSLCryptoParams (alg, derivedKey.fKey, derivedKey.fIV) { } #endif #if qHasFeature_OpenSSL /* ******************************************************************************** ******************** Cryptography::OpenSSLInputStream ************************** ******************************************************************************** */ OpenSSLInputStream::OpenSSLInputStream (const OpenSSLCryptoParams& cryptoParams, Direction direction, const InputStream<Byte>& realIn) : InputStream<Byte> (make_shared<IRep_> (cryptoParams, direction, realIn)) { } #endif #if qHasFeature_OpenSSL /* ******************************************************************************** ******************* Cryptography::OpenSSLOutputStream ************************** ******************************************************************************** */ OpenSSLOutputStream::OpenSSLOutputStream (const OpenSSLCryptoParams& cryptoParams, Direction direction, const OutputStream<Byte>& realOut) : OutputStream<Byte> (make_shared<IRep_> (cryptoParams, direction, realOut)) { } #endif <commit_msg>fixed https://stroika.atlassian.net/browse/STK-193 - issue with short encrpytions failing with block ciphers - was bug in pull code in streams<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #include "../../StroikaPreComp.h" #if qHasFeature_OpenSSL #include <openssl/evp.h> #include <openssl/err.h> #endif #include "../../Containers/Common.h" #include "../../Debug/Assertions.h" #include "../../Execution/Common.h" #include "../../Memory/SmallStackBuffer.h" #include "OpenSSLCryptoStream.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Cryptography; using namespace Stroika::Foundation::Cryptography::Encoding; using namespace Stroika::Foundation::Memory; using namespace Stroika::Foundation::Streams; using Memory::BLOB; // @todo examine/test https://github.com/saju/misc/blob/master/misc/openssl_aes.c #if qHasFeature_OpenSSL && defined (_MSC_VER) // Use #pragma comment lib instead of explicit entry in the lib entry of the project file #pragma comment (lib, "libeay32.lib") #pragma comment (lib, "ssleay32.lib") #endif //// VERY ROUGH DRAFT - NOT VERY CLOSE TO CORRECT FOR ALL ALGORITHSM //// SEE http://www.openssl.org/docs/crypto/EVP_EncryptInit.html /// SEE https://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption //// for details on what todo #if qHasFeature_OpenSSL namespace { struct InOutStrmCommon_ { InOutStrmCommon_ (const OpenSSLCryptoParams& cryptoParams, Direction d) : fCTX_ () , fFinalCalled_ (false) { ::EVP_CIPHER_CTX_init (&fCTX_); cryptoParams.fInitializer (&fCTX_, d); } InOutStrmCommon_ (const InOutStrmCommon_&) = delete; InOutStrmCommon_& operator= (const InOutStrmCommon_&) = delete; ~InOutStrmCommon_ () { Verify (::EVP_CIPHER_CTX_cleanup (&fCTX_) == 1); } static constexpr size_t _GetMinOutBufSize (size_t n) { return n + EVP_MAX_BLOCK_LENGTH; } // return nBytes in outBuf, throws on error size_t _runOnce (const Byte* data2ProcessStart, const Byte* data2ProcessEnd, Byte* outBufStart, Byte* outBufEnd) { Require (outBufStart <= outBufEnd and static_cast<size_t> (outBufEnd - outBufStart) >= _GetMinOutBufSize (data2ProcessEnd - data2ProcessStart)); // always need out buf big enuf for inbuf int outLen = 0; Cryptography::OpenSSL::Exception::ThrowLastErrorIfFailed (::EVP_CipherUpdate (&fCTX_, outBufStart, &outLen, data2ProcessStart, static_cast<int> (data2ProcessEnd - data2ProcessStart))); Ensure (outLen >= 0); Ensure (outLen <= (outBufEnd - outBufStart)); return size_t (outLen); } // return nBytes in outBuf, throws on error // Can call multiple times - it keeps track itself if finalized. size_t _cipherFinal (Byte* outBufStart, Byte* outBufEnd) { Require (outBufStart <= outBufEnd and static_cast<size_t> (outBufEnd - outBufStart) >= _GetMinOutBufSize (0)); if (fFinalCalled_) { return 0; // not an error - just zero more bytes } int outLen = 0; Cryptography::OpenSSL::Exception::ThrowLastErrorIfFailed (::EVP_CipherFinal_ex (&fCTX_, outBufStart, &outLen)); fFinalCalled_ = true; Ensure (outLen >= 0); Ensure (outLen <= (outBufEnd - outBufStart)); return size_t (outLen); } EVP_CIPHER_CTX fCTX_; bool fFinalCalled_; }; } #endif #if qHasFeature_OpenSSL class OpenSSLInputStream::IRep_ : public InputStream<Byte>::_IRep, private InOutStrmCommon_ { private: DEFINE_CONSTEXPR_CONSTANT(size_t, kInBufSize_, 10 * 1024); public: IRep_ (const OpenSSLCryptoParams& cryptoParams, Direction d, const InputStream<Byte>& realIn) : InputStream<Byte>::_IRep () , InOutStrmCommon_ (cryptoParams, d) , fCriticalSection_ () , fOutBuf_ (_GetMinOutBufSize (kInBufSize_)) , fOutBufStart_ (nullptr) , fOutBufEnd_ (nullptr) , fRealIn_ (realIn) { } virtual bool IsSeekable () const override { return false; } virtual SeekOffsetType GetReadOffset () const override { RequireNotReached (); return 0; } virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override { RequireNotReached (); return 0; } virtual size_t Read (SeekOffsetType* offset, Byte* intoStart, Byte* intoEnd) override { Require (offset == nullptr); // not seekable /* * Keep track if unread bytes in fOutBuf_ - bounded by fOutBufStart_ and fOutBufEnd_. * If none to read there - pull from fRealIn_ src, and push those through the cipher. * and use that to re-populate fOutBuf_. */ Require (intoStart < intoEnd); auto critSec { Execution::make_unique_lock (fCriticalSection_) }; if (fOutBufStart_ == fOutBufEnd_) { /* * Then pull from 'real in' stream until we have reach EOF there, or until we have some bytes to output * on our own. */ Byte toDecryptBuf[kInBufSize_]; Again: size_t n2Decrypt = fRealIn_.Read (begin (toDecryptBuf), end (toDecryptBuf)); if (n2Decrypt == 0) { size_t nBytesInOutBuf = _cipherFinal (fOutBuf_.begin (), fOutBuf_.end ()); Assert (nBytesInOutBuf <= fOutBuf_.GetSize ()); fOutBufStart_ = fOutBuf_.begin (); fOutBufEnd_ = fOutBufStart_ + nBytesInOutBuf; } else { fOutBuf_.GrowToSize (_GetMinOutBufSize (NEltsOf (toDecryptBuf))); size_t nBytesInOutBuf = _runOnce (begin (toDecryptBuf), begin (toDecryptBuf) + n2Decrypt, fOutBuf_.begin (), fOutBuf_.end ()); Assert (nBytesInOutBuf <= fOutBuf_.GetSize ()); if (nBytesInOutBuf == 0) { // This can happen with block ciphers - we put stuff in, and get nothing out. But we cannot return EOF // yet, so try again... goto Again; } else { fOutBufStart_ = fOutBuf_.begin (); fOutBufEnd_ = fOutBufStart_ + nBytesInOutBuf; } } } if (fOutBufStart_ < fOutBufEnd_) { size_t n2Copy = min (fOutBufEnd_ - fOutBufStart_, intoEnd - intoStart); (void)::memcpy (intoStart, fOutBufStart_, n2Copy); fOutBufStart_ += n2Copy; return n2Copy; } return 0; // EOF } private: mutable mutex fCriticalSection_; Memory::SmallStackBuffer < Byte, kInBufSize_ + EVP_MAX_BLOCK_LENGTH > fOutBuf_; Byte* fOutBufStart_; Byte* fOutBufEnd_; InputStream<Byte> fRealIn_; }; #endif #if qHasFeature_OpenSSL class OpenSSLOutputStream::IRep_ : public OutputStream<Byte>::_IRep, private InOutStrmCommon_ { public: IRep_ (const OpenSSLCryptoParams& cryptoParams, Direction d, const OutputStream<Byte>& realOut) : OutputStream<Byte>::_IRep () , InOutStrmCommon_ (cryptoParams, d) , fCriticalSection_ () , fRealOut_ (realOut) { } virtual ~IRep_ () { // no need for critical section because at most one thread can be running DTOR at a time, and no other methods can be running try { Flush (); } catch (...) { // not great to do in DTOR, because we must drop exceptions on the floor! } } virtual bool IsSeekable () const override { return false; } virtual SeekOffsetType GetWriteOffset () const override { RequireNotReached (); return 0; } virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override { RequireNotReached (); return 0; } // pointer must refer to valid memory at least bufSize long, and cannot be nullptr. BufSize must always be >= 1. // Writes always succeed fully or throw. virtual void Write (const Byte* start, const Byte* end) override { Require (start < end); // for OutputStream<Byte> - this funciton requires non-empty write Memory::SmallStackBuffer < Byte, 1000 + EVP_MAX_BLOCK_LENGTH > outBuf (_GetMinOutBufSize (end - start)); auto critSec { Execution::make_unique_lock (fCriticalSection_) }; size_t nBytesEncypted = _runOnce (start, end, outBuf.begin (), outBuf.end ()); Assert (nBytesEncypted <= outBuf.GetSize ()); fRealOut_.Write (outBuf.begin (), outBuf.begin () + nBytesEncypted); } virtual void Flush () override { Byte outBuf[EVP_MAX_BLOCK_LENGTH]; size_t nBytesInOutBuf = _cipherFinal (begin (outBuf), end (outBuf)); Assert (nBytesInOutBuf < sizeof (outBuf)); fRealOut_.Write (begin (outBuf), begin (outBuf) + nBytesInOutBuf); } private: mutable recursive_mutex fCriticalSection_; OutputStream<Byte> fRealOut_; }; #endif #if qHasFeature_OpenSSL /* ******************************************************************************** ******************** Cryptography::OpenSSLInputStream ************************** ******************************************************************************** */ namespace { void ApplySettings2CTX_ (EVP_CIPHER_CTX* ctx, const EVP_CIPHER* cipher, Direction d, bool nopad, bool useArgumentKeyLength, const Memory::BLOB& key, const Memory::BLOB& initialIV) { RequireNotNull (ctx); RequireNotNull (cipher); bool enc = (d == Direction::eEncrypt); if (nopad) { Verify (::EVP_CIPHER_CTX_set_padding (ctx, 0) == 1); } Cryptography::OpenSSL::Exception::ThrowLastErrorIfFailed (::EVP_CipherInit_ex (ctx, cipher, NULL, nullptr, nullptr, enc)); size_t keyLen = EVP_CIPHER_CTX_key_length (ctx); size_t ivLen = EVP_CIPHER_CTX_iv_length (ctx); if (useArgumentKeyLength) { keyLen = key.length (); Verify (::EVP_CIPHER_CTX_set_key_length (ctx, static_cast<int> (keyLen)) == 1); } Memory::SmallStackBuffer<Byte> useKey { keyLen }; Memory::SmallStackBuffer<Byte> useIV { ivLen }; memset (useKey.begin (), 0, keyLen); memset (useIV.begin (), 0, ivLen); memcpy (useKey.begin (), key.begin (), min(keyLen, key.size ())); memcpy (useIV.begin (), initialIV.begin (), min(ivLen, initialIV.size ())); Cryptography::OpenSSL::Exception::ThrowLastErrorIfFailed (::EVP_CipherInit_ex (ctx, nullptr, NULL, useKey.begin (), useIV.begin (), enc)); } } OpenSSLCryptoParams::OpenSSLCryptoParams (CipherAlgorithm alg, Memory::BLOB key, Memory::BLOB initialIV) : fInitializer () { bool nopad = false; switch (alg) { case CipherAlgorithm::eRC2_CBC: { fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) { ApplySettings2CTX_ (ctx, ::EVP_rc2_cbc (), d, nopad, true, key, initialIV); }; } break; case CipherAlgorithm::eRC2_ECB: { fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) { ApplySettings2CTX_ (ctx, ::EVP_rc2_ecb (), d, nopad, true, key, initialIV); }; } break; case CipherAlgorithm::eRC2_CFB: { fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) { ApplySettings2CTX_ (ctx, ::EVP_rc2_cfb (), d, nopad, true, key, initialIV); }; } break; case CipherAlgorithm::eRC2_OFB: { fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) { ApplySettings2CTX_ (ctx, ::EVP_rc2_ofb (), d, nopad, true, key, initialIV); }; } break; case CipherAlgorithm::eRC4: { fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) { ApplySettings2CTX_ (ctx, ::EVP_rc4 (), d, nopad, true, key, initialIV); }; } break; default: { fInitializer = [alg, nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) { ApplySettings2CTX_ (ctx, Convert2OpenSSL (alg), d, nopad, false, key, initialIV); }; break; } } } OpenSSLCryptoParams::OpenSSLCryptoParams (CipherAlgorithm alg, const DerivedKey& derivedKey) : OpenSSLCryptoParams (alg, derivedKey.fKey, derivedKey.fIV) { } #endif #if qHasFeature_OpenSSL /* ******************************************************************************** ******************** Cryptography::OpenSSLInputStream ************************** ******************************************************************************** */ OpenSSLInputStream::OpenSSLInputStream (const OpenSSLCryptoParams& cryptoParams, Direction direction, const InputStream<Byte>& realIn) : InputStream<Byte> (make_shared<IRep_> (cryptoParams, direction, realIn)) { } #endif #if qHasFeature_OpenSSL /* ******************************************************************************** ******************* Cryptography::OpenSSLOutputStream ************************** ******************************************************************************** */ OpenSSLOutputStream::OpenSSLOutputStream (const OpenSSLCryptoParams& cryptoParams, Direction direction, const OutputStream<Byte>& realOut) : OutputStream<Byte> (make_shared<IRep_> (cryptoParams, direction, realOut)) { } #endif <|endoftext|>
<commit_before>#include "instantiationconstraint.h" #include <model/devisertypes.h> InstantiationConstraint::InstantiationConstraint(DeviserValidator *validator) : DeviserConstraint(validator) { } int InstantiationConstraint::analyzePackage(DeviserPackage *package) { int errors = 0; foreach (DeviserVersion* version, package->getVersions()) { foreach(DeviserClass* pClass, version ->getElements()) { foreach(DeviserConcrete* instantiation, pClass->getConcretes()) { if (instantiation->getElement().isEmpty()) { ADD_MESSAGE_WITH_SEVERITY(DEVISER_ERROR, "The instantiation '" << instantiation->getName() << "' has no element defined, this is a required attribute."); ++errors; } } } } return errors; } <commit_msg>- issue #111045570: also validate that there is a name specified<commit_after>#include "instantiationconstraint.h" #include <model/devisertypes.h> InstantiationConstraint::InstantiationConstraint(DeviserValidator *validator) : DeviserConstraint(validator) { } int InstantiationConstraint::analyzePackage(DeviserPackage *package) { int errors = 0; foreach (DeviserVersion* version, package->getVersions()) { foreach(DeviserClass* pClass, version ->getElements()) { foreach(DeviserConcrete* instantiation, pClass->getConcretes()) { if (instantiation->getName().isEmpty()) { ADD_MESSAGE_WITH_SEVERITY(DEVISER_ERROR, "In class '" << pClass->getName() << "' an instantiation has no XML name, this is a required attribute."); ++errors; } if (instantiation->getElement().isEmpty()) { ADD_MESSAGE_WITH_SEVERITY(DEVISER_ERROR, "The instantiation '" << instantiation->getName() << "' has no element defined, this is a required attribute."); ++errors; } } } } return errors; } <|endoftext|>
<commit_before>#include "precomp.h" #include "game_object_types.h" #include "game_object_manager.h" #include "game_object.h" #include "player.h" #include "../tile_chunk.h" #include "throwable_object.h" #include "../net/message.h" clan::Sprite Player::s_rw, Player::s_lw, Player::s_uw, Player::s_dw, Player::s_h; static clan::Font title; Player::Player(uint32_t guid): GameObject(type(),guid) { keys=add_property<uint32_t>("keys",0); life=add_property<uint32_t>("life",100); kills=add_property<uint32_t>("kills",0); killer=add_property<uint32_t>("killer"); name=add_property<std::string>("name","Sir. Waitfor Servereply"); clan::Contour contour; contour.get_points().push_back(clan::Pointf(16,13)); contour.get_points().push_back(clan::Pointf(16,63)); contour.get_points().push_back(clan::Pointf(47,63)); contour.get_points().push_back(clan::Pointf(47,13)); m_outline.get_contours().push_back(contour); m_outline.calculate_radius(); m_outline.calculate_smallest_enclosing_discs(); m_next_attack_time = 0; } Player::~Player() { } uint32_t Player::get_next_attack_time() { return m_next_attack_time; } void Player::set_next_attack_time(uint32_t time) { m_next_attack_time = time; } clan::Colorf Player::get_hp_bar_color() { float r,g; r = 1.0f - (float)life/100; g = (float)life/100; return clan::Colorf(r,g,0.0f,1.0f); } bool Player::preload(clan::Canvas & canvas, clan::ResourceManager & resources) { title = clan::Font(canvas,"Arial",12); ///DON'T CHANGE EVEN AGAIN s_rw = clan::Sprite::resource(canvas, "champ_rw", resources ); s_lw = clan::Sprite::resource(canvas, "champ_lw", resources ); s_uw = clan::Sprite::resource(canvas, "champ_uw", resources ); s_dw = clan::Sprite::resource(canvas, "champ_dw", resources ); s_h = clan::Sprite::resource(canvas, "hp_bar", resources ); return true; } void Player::free() { s_rw = clan::Sprite(); s_lw = clan::Sprite(); s_uw = clan::Sprite(); s_dw = clan::Sprite(); s_h = clan::Sprite(); title = clan::Font(); } void Player::load(clan::Canvas & canvas, clan::ResourceManager & resources) { m_rw = s_rw.clone(); m_lw = s_lw.clone(); m_uw = s_uw.clone(); m_dw = s_dw.clone(); m_h = s_h.clone(); m_sprite=m_dw; clan::Console::write_line("is null: %1",m_sprite.is_null()); } void Player::update(const clan::GameTime & time) { if(!m_sprite.is_null()) m_sprite.update(time.get_time_elapsed_ms()); //m_pos.data().x += 16.0f * (float)time.get_time_elapsed_ms()/1000.0f; last_pos = m_pos.get(); if(keys&EUIKT_MOVE_LEFT && m_pos.get().x>-20.0f) { m_sprite=m_lw; clan::vec2f v=m_pos; v.x-= 32.0f * (float)time.get_time_elapsed_ms()/900.0f; m_pos.set(v); } if(keys&EUIKT_MOVE_RIGHT && m_pos.get().x<980.0f) { m_sprite=m_rw; clan::vec2f v=m_pos; v.x+= 32.0f * (float)time.get_time_elapsed_ms()/900.0f; m_pos.set(v); } if(keys&EUIKT_MOVE_UP && m_pos.get().y>0.0f) { m_sprite=m_uw; clan::vec2f v=m_pos; v.y-= 32.0f * (float)time.get_time_elapsed_ms()/900.0f; m_pos.set(v); } if(keys&EUIKT_MOVE_DOWN && m_pos.get().y<660.0f) { m_sprite=m_dw; clan::vec2f v=m_pos; v.y+= 32.0f * (float)time.get_time_elapsed_ms()/900.0f; m_pos.set(v); } m_outline.set_translation(m_pos.get().x,m_pos.get().y); } void Player::render(clan::Canvas & c, const clan::vec2 & offset) { #if defined GAME_CLIENT if(!m_sprite.is_null()) { m_sprite.draw(c, m_pos.get().x+offset.x, m_pos.get().y+offset.y); c.fill_rect(m_pos.get().x+offset.x+10, m_pos.get().y+offset.y-1, m_pos.get().x+offset.x+10+(44*life/100), m_pos.get().y+offset.y+8, get_hp_bar_color()); m_h.draw(c,m_pos.get().x+offset.x, m_pos.get().y+offset.y-5); m_outline.draw(offset.x,offset.y,clan::Colorf(1,0,0,1),c); title.draw_text(c, m_pos.get().x+offset.x+6,m_pos.get().y+offset.y-8, name.get()+": "+clan::StringHelp::uint_to_text(kills.get()), get_hp_bar_color()); } #endif } void Player::on_message(const Message & msg) { if(msg.get_type()==MSGC_INPUT) { const MSGC_Input & input = static_cast<const MSGC_Input &>(msg); keys = input.keys; } } void Player::on_collide(GameObject * obj) { if(obj->is_alive() && obj->get_type()==EGOT_THROWABLE_OBJECT) { if(static_cast<ThrowableObject*>(obj)->get_owner_guid()==this->get_guid()) return; obj->set_is_alive(false); if(this->life>10) { this->life = this->life - 10; } else { this->killer=static_cast<ThrowableObject*>(obj)->get_owner_guid(); this->life=0; } } } void Player::on_tile_collide(const Tile & tile) { m_pos = last_pos; } clan::CollisionOutline & Player::get_outline() { return m_outline; }<commit_msg>Signed-off-by: serengeor <serengeor@gmail.com><commit_after>#include "precomp.h" #include "game_object_types.h" #include "game_object_manager.h" #include "game_object.h" #include "player.h" #include "../tile_chunk.h" #include "throwable_object.h" #include "../net/message.h" clan::Sprite Player::s_rw, Player::s_lw, Player::s_uw, Player::s_dw, Player::s_h; static clan::Font title; Player::Player(uint32_t guid): GameObject(type(),guid) { keys=add_property<uint32_t>("keys",0); life=add_property<uint32_t>("life",100); kills=add_property<uint32_t>("kills",0); killer=add_property<uint32_t>("killer"); name=add_property<std::string>("name","Sir. Waitfor Servereply"); clan::Contour contour; contour.get_points().push_back(clan::Pointf(16,13)); contour.get_points().push_back(clan::Pointf(16,63)); contour.get_points().push_back(clan::Pointf(47,63)); contour.get_points().push_back(clan::Pointf(47,13)); m_outline.get_contours().push_back(contour); m_outline.calculate_radius(); m_outline.calculate_smallest_enclosing_discs(); m_next_attack_time = 0; } Player::~Player() { } uint32_t Player::get_next_attack_time() { return m_next_attack_time; } void Player::set_next_attack_time(uint32_t time) { m_next_attack_time = time; } clan::Colorf Player::get_hp_bar_color() { float r,g; r = 1.0f - (float)life/100; g = (float)life/100; return clan::Colorf(r,g,0.0f,1.0f); } bool Player::preload(clan::Canvas & canvas, clan::ResourceManager & resources) { title = clan::Font(canvas,"Arial",12); ///DON'T CHANGE EVEN AGAIN s_rw = clan::Sprite::resource(canvas, "champ_rw", resources ); s_lw = clan::Sprite::resource(canvas, "champ_lw", resources ); s_uw = clan::Sprite::resource(canvas, "champ_uw", resources ); s_dw = clan::Sprite::resource(canvas, "champ_dw", resources ); s_h = clan::Sprite::resource(canvas, "hp_bar", resources ); return true; } void Player::free() { s_rw = clan::Sprite(); s_lw = clan::Sprite(); s_uw = clan::Sprite(); s_dw = clan::Sprite(); s_h = clan::Sprite(); title = clan::Font(); } void Player::load(clan::Canvas & canvas, clan::ResourceManager & resources) { m_rw = s_rw.clone(); m_lw = s_lw.clone(); m_uw = s_uw.clone(); m_dw = s_dw.clone(); m_h = s_h.clone(); m_sprite=m_dw; } void Player::update(const clan::GameTime & time) { if(!m_sprite.is_null()) m_sprite.update(time.get_time_elapsed_ms()); //m_pos.data().x += 16.0f * (float)time.get_time_elapsed_ms()/1000.0f; last_pos = m_pos.get(); if(keys&EUIKT_MOVE_LEFT && m_pos.get().x>-20.0f) { m_sprite=m_lw; clan::vec2f v=m_pos; v.x-= 32.0f * (float)time.get_time_elapsed_ms()/900.0f; m_pos.set(v); } if(keys&EUIKT_MOVE_RIGHT && m_pos.get().x<980.0f) { m_sprite=m_rw; clan::vec2f v=m_pos; v.x+= 32.0f * (float)time.get_time_elapsed_ms()/900.0f; m_pos.set(v); } if(keys&EUIKT_MOVE_UP && m_pos.get().y>0.0f) { m_sprite=m_uw; clan::vec2f v=m_pos; v.y-= 32.0f * (float)time.get_time_elapsed_ms()/900.0f; m_pos.set(v); } if(keys&EUIKT_MOVE_DOWN && m_pos.get().y<660.0f) { m_sprite=m_dw; clan::vec2f v=m_pos; v.y+= 32.0f * (float)time.get_time_elapsed_ms()/900.0f; m_pos.set(v); } m_outline.set_translation(m_pos.get().x,m_pos.get().y); } void Player::render(clan::Canvas & c, const clan::vec2 & offset) { #if defined GAME_CLIENT if(!m_sprite.is_null()) { m_sprite.draw(c, m_pos.get().x+offset.x, m_pos.get().y+offset.y); c.fill_rect(m_pos.get().x+offset.x+10, m_pos.get().y+offset.y-1, m_pos.get().x+offset.x+10+(44*life/100), m_pos.get().y+offset.y+8, get_hp_bar_color()); m_h.draw(c,m_pos.get().x+offset.x, m_pos.get().y+offset.y-5); m_outline.draw(offset.x,offset.y,clan::Colorf(1,0,0,1),c); title.draw_text(c, m_pos.get().x+offset.x+6,m_pos.get().y+offset.y-8, name.get()+": "+clan::StringHelp::uint_to_text(kills.get()), get_hp_bar_color()); } #endif } void Player::on_message(const Message & msg) { if(msg.get_type()==MSGC_INPUT) { const MSGC_Input & input = static_cast<const MSGC_Input &>(msg); keys = input.keys; } } void Player::on_collide(GameObject * obj) { if(obj->is_alive() && obj->get_type()==EGOT_THROWABLE_OBJECT) { if(static_cast<ThrowableObject*>(obj)->get_owner_guid()==this->get_guid()) return; obj->set_is_alive(false); if(this->life>10) { this->life = this->life - 10; } else { this->killer=static_cast<ThrowableObject*>(obj)->get_owner_guid(); this->life=0; } } } void Player::on_tile_collide(const Tile & tile) { m_pos = last_pos; } clan::CollisionOutline & Player::get_outline() { return m_outline; }<|endoftext|>
<commit_before>// General tests that the header search paths detected by the driver and passed // to CC1 are sane. // // Test a very broken version of multiarch that shipped in Ubuntu 11.04. // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \ // RUN: -ccc-host-triple i386-unknown-linux \ // RUN: --sysroot=%S/Inputs/ubuntu_11.04_multiarch_tree \ // RUN: | FileCheck --check-prefix=CHECK-UBUNTU-11-04 %s // CHECK-UBUNTU-11-04: "{{.*}}clang{{.*}}" "-cc1" // CHECK-UBUNTU-11-04: "-isysroot" "[[SYSROOT:[^"]+]]" // CHECK-UBUNTU-11-04: "-internal-isystem" "[[SYSROOT]]/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/../../../../../include/c++/4.5" // CHECK-UBUNTU-11-04: "-internal-isystem" "[[SYSROOT]]/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/../../../../../include/c++/4.5/i686-linux-gnu" // CHECK-UBUNTU-11-04: "-internal-isystem" "[[SYSROOT]]/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/../../../../../include/c++/4.5/backward" // CHECK-UBUNTU-11-04: "-internal-isystem" "[[SYSROOT]]/usr/local/include" // CHECK-UBUNTU-11-04: "-internal-isystem" "{{.*}}/lib/clang/{{[0-9]\.[0-9]}}/include" // CHECK-UBUNTU-11-04: "-internal-externc-isystem" "[[SYSROOT]]/include" // CHECK-UBUNTU-11-04: "-internal-externc-isystem" "[[SYSROOT]]/usr/include" <commit_msg>Try to fix an issue on some hosts where the 'lib' in the builtin include path is actually a multilib.<commit_after>// General tests that the header search paths detected by the driver and passed // to CC1 are sane. // // Test a very broken version of multiarch that shipped in Ubuntu 11.04. // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \ // RUN: -ccc-host-triple i386-unknown-linux \ // RUN: --sysroot=%S/Inputs/ubuntu_11.04_multiarch_tree \ // RUN: | FileCheck --check-prefix=CHECK-UBUNTU-11-04 %s // CHECK-UBUNTU-11-04: "{{.*}}clang{{.*}}" "-cc1" // CHECK-UBUNTU-11-04: "-isysroot" "[[SYSROOT:[^"]+]]" // CHECK-UBUNTU-11-04: "-internal-isystem" "[[SYSROOT]]/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/../../../../../include/c++/4.5" // CHECK-UBUNTU-11-04: "-internal-isystem" "[[SYSROOT]]/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/../../../../../include/c++/4.5/i686-linux-gnu" // CHECK-UBUNTU-11-04: "-internal-isystem" "[[SYSROOT]]/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/../../../../../include/c++/4.5/backward" // CHECK-UBUNTU-11-04: "-internal-isystem" "[[SYSROOT]]/usr/local/include" // CHECK-UBUNTU-11-04: "-internal-isystem" "{{.*}}/lib{{(64|32)?}}/clang/{{[0-9]\.[0-9]}}/include" // CHECK-UBUNTU-11-04: "-internal-externc-isystem" "[[SYSROOT]]/include" // CHECK-UBUNTU-11-04: "-internal-externc-isystem" "[[SYSROOT]]/usr/include" <|endoftext|>
<commit_before>#include "./../../../Common/verbose-output/rule.hpp" #include <boost/static_assert.hpp> namespace utils { namespace verbose_output { /// @brief rule for events from integrals state changing /// @detailed 1. let x be monotonous increasing integral under observation /// 2. let we want to track x every time if it goes through 100 /// 3. so integrals_rule will raise event if we observe x + y, where y >= 100 template<typename T> class integrals_rule : public rule { BOOST_STATIC_ASSERT((boost::is_arithmetic<T>::value)); typedef integrals_rule<T> this_class; typedef rule base_class; public: /// @brief default constructor /// @param state observable /// @param stride stride we want to log observable through integrals_rule(T state, T stride) : m_state(state), m_stride(stride){ }; /// @brief inherited from rule interface /// @see rule result_type operator()(args<0>::type); private: // logics: we could not adaptively change rule behavior. // Correctly, it should be done by changing rule // private setter and getter for observable state T state() const{ return m_state; } this_class& state(T val){ m_state = val; return *this; } // just getter for observations stride T stride() const{ return m_stride; } T m_state; T m_stride; }; }} #define _tmpl_head_T_ template<typename T> #define _cls_name_ integrals_rule<T> #include "./../../../Common/verbose-output/rules/details/integrals_rule.inl" <commit_msg>numerals_rule.hpp: add #def protection for multiple object translating during compilation<commit_after>#ifndef INC_NUMERALS_RULE_HPP_ #define INC_NUMERALS_RULE_HPP_ #include "./../../../Common/verbose-output/rule.hpp" #include <boost/static_assert.hpp> namespace utils { namespace verbose_output { /// @brief rule for events from integrals state changing /// @detailed 1. let x be monotonous increasing integral under observation /// 2. let we want to track x every time if it goes through 100 /// 3. so integrals_rule will raise event if we observe x + y, where y >= 100 template<typename T> class integrals_rule : public rule { BOOST_STATIC_ASSERT((boost::is_arithmetic<T>::value)); typedef integrals_rule<T> this_class; typedef rule base_class; public: /// @brief default constructor /// @param state observable /// @param stride stride we want to log observable through integrals_rule(T state, T stride) : m_state(state), m_stride(stride){ }; /// @brief inherited from rule interface /// @see rule result_type operator()(args<0>::type); private: // logics: we could not adaptively change rule behavior. // Correctly, it should be done by changing rule // private setter and getter for observable state T state() const{ return m_state; } this_class& state(T val){ m_state = val; return *this; } // just getter for observations stride T stride() const{ return m_stride; } T m_state; T m_stride; }; }} #define _tmpl_head_T_ template<typename T> #define _cls_name_ integrals_rule<T> #include "./../../../Common/verbose-output/rules/details/integrals_rule.inl" #endif <|endoftext|>
<commit_before>#include <cassert> #include <iostream> #include <climits> #include "solvers/equality_assistant.h" #include "config.h" using namespace theorysolver; #define VERBOSE_ASSISTANT true #define EF satsolver::ExtendedFormula #define SPEF std::shared_ptr<EF> #define EA EqualityAtom #define SPEA std::shared_ptr<EA> // Return a formula that uses only atoms in the canonical “xi-xj<=n” form. // Note that it may use literal #0; for instance, xi >= n is converted to // x0 - xi <= -n, so we will have to make sure x0 is always equal to 0. SPEF canonize_atom(SPEA atom, std::vector<SPEA> &literal_to_EA, std::string literal) { unsigned long int id1; assert(atom); if(atom->left==atom->right) { switch (atom->op) { case EA::EQUAL: // t1 = t1 atom->canonical = SPEF(new EF(EF::TRUE)); break; case EA::UNEQUAL: // t1 != t1 atom->canonical = SPEF(new EF(EF::FALSE)); break; } } else { switch (atom->op) { case EA::EQUAL: // t1 = t2 --> t1 = t2 atom->canonical = SPEF(new EF(EF::LITERAL, literal)); break; case EA::UNEQUAL: // t2 != t2 --> ~(t1 = t2) id1 = EqualityAtom::add_EA(literal_to_EA, atom->left, EA::EQUAL, atom->right); atom->canonical = SPEF(new EF(EF::NOT, SPEF(new EF(EF::LITERAL, EqualityAtom::variable_name_from_atom_id(id1))) )); break; } } return atom->canonical; } SPEF EqualityAssistant::canonize_formula(SPEF formula, std::vector<SPEA> &literal_to_EA) { SPEA atom; switch (formula->get_type()) { case EF::XOR: case EF::OR: case EF::AND: case EF::IMPLIES: return std::make_shared<EF>(formula->get_type(), EqualityAssistant::canonize_formula(formula->get_f1(), literal_to_EA), EqualityAssistant::canonize_formula(formula->get_f2(), literal_to_EA)); case EF::NOT: return std::make_shared<EF>(formula->get_type(), EqualityAssistant::canonize_formula(formula->get_f1(), literal_to_EA)); case EF::LITERAL: atom = EqualityAtom::SPEA_from_variable(literal_to_EA, formula->get_literal()); if (!EqualityAtom::is_atom_variable(formula->get_literal())) return std::make_shared<EF>(formula->get_type(), formula->get_literal()); atom = EqualityAtom::SPEA_from_variable(literal_to_EA, formula->get_literal()); return canonize_atom(atom, literal_to_EA, formula->get_literal()); case EF::TRUE: case EF::FALSE: return std::make_shared<EF>(formula->get_type()); } assert(false); } EqualityAssistant::EqualityAssistant(std::vector<SPEA> &literal_to_EA, std::shared_ptr<std::map<std::string, int>> name_to_variable, std::shared_ptr<satsolver::Formula> formula) : formula(formula), literal_to_EA(literal_to_EA), name_to_variable(*name_to_variable), variable_to_name(), union_find(), unequal(), consistent_state(true), depth_back(-1), old_polarity(formula->get_nb_variables()+1, 0) { for (auto it : *name_to_variable) this->variable_to_name.insert(make_pair(it.second, it.first)); } int EqualityAssistant::on_flip(unsigned int variable) { unsigned int atom_id; SPEA atom; int clause_id=-1; if (VERBOSE_ASSISTANT && VERBOSE) std::cout << "flip variable: " << variable; if (!EqualityAtom::is_atom_literal(this->variable_to_name, variable)) { if (VERBOSE_ASSISTANT && VERBOSE) std::cout << ", which is not an atom." << std::endl; return -1; // We care only about variables matching atoms. } assert(variable <= static_cast<unsigned int>(this->formula->get_nb_variables())); atom_id = EqualityAtom::atom_id_from_literal(this->variable_to_name, variable); atom = EqualityAtom::SPEA_from_literal(this->literal_to_EA, this->variable_to_name, variable); if (VERBOSE_ASSISTANT && VERBOSE) std::cout << ", whose atom is: " << atom_id << ", and whose new state is: "; if (this->formula->get_aff()->is_true(variable)) { if (VERBOSE_ASSISTANT && VERBOSE) std::cout << "true" << std::endl; assert(this->consistent_state); if (this->old_polarity[variable] == 1) return -1; clause_id = this->insert_atom(atom->left, atom->right, atom->op == EA::EQUAL, atom_id, variable); this->old_polarity[variable] = 1; } else if (this->formula->get_aff()->is_false(variable)) { if (VERBOSE_ASSISTANT && VERBOSE) std::cout << "false" << std::endl; assert(this->consistent_state); if (this->old_polarity[variable] == -1) return -1; clause_id = this->insert_atom(atom->left, atom->right, atom->op == EA::UNEQUAL, atom_id, variable); this->old_polarity[variable] = -1; } else { if (VERBOSE_ASSISTANT && VERBOSE) std::cout << "unknown" << std::endl; if (this->old_polarity[variable] == 0) return -1; if (this->old_polarity[variable] == 1) { this->union_find.unmerge(); } else { assert(this->unequal.size()); assert(this->unequal.back().first == atom_id); this->unequal.pop_back(); } this->consistent_state = true; this->old_polarity[variable] = 0; } return clause_id; } int EqualityAssistant::insert_atom(unsigned int i, unsigned int j, bool equal, unsigned int atom_id, int lit_conf) { if (equal) { this->union_find.merge(atom_id, i, j); for (auto it : this->unequal) { if (this->union_find.find(it.second.first) == this->union_find.find(it.second.second)) { this->consistent_state = false; return this->learn_clause(it.first, i, j, lit_conf); } } } else { this->consistent_state = (this->union_find.find(i) != this->union_find.find(j)); this->unequal.push_back(std::make_pair(atom_id, std::make_pair(i, j))); if (!this->consistent_state) return this->learn_clause(atom_id, i, j, lit_conf); } return -1; } int EqualityAssistant::literal_from_atom_id(int atom_id) const { if (atom_id > 0) return EqualityAtom::literal_from_atom_id(this->name_to_variable, static_cast<unsigned int>(atom_id)); else return -EqualityAtom::literal_from_atom_id(this->name_to_variable, static_cast<unsigned int>(-atom_id)); } #define invert_polarity(lit) this->formula->get_aff()->is_true(lit) ? -lit : lit int EqualityAssistant::learn_clause(int unequal_atomid, int i, int j, int lit_conf) { std::unordered_set<int> clause; int max_depth=-1, max_depth_l=0 ; int lit; int tmp; lit_conf = invert_polarity(lit_conf) ; clause.insert(lit_conf); clause.insert(lit=invert_polarity(this->literal_from_atom_id(unequal_atomid))); if(lit!=lit_conf) { max_depth = this->formula->get_ded()->get_deduction_depth(lit) ; max_depth_l = lit ; } for (auto it : this->union_find.get_path(i)) { lit = invert_polarity(this->literal_from_atom_id(it)); clause.insert(lit); if(lit!=lit_conf && this->formula->get_ded()->get_deduction_depth(lit) > max_depth) { max_depth = this->formula->get_ded()->get_deduction_depth(lit) ; max_depth_l = lit ; } } for (auto it : this->union_find.get_path(j)) { lit = invert_polarity(this->literal_from_atom_id(it)); clause.insert(lit); if(lit!=lit_conf && this->formula->get_ded()->get_deduction_depth(lit) > max_depth) { max_depth = this->formula->get_ded()->get_deduction_depth(lit) ; max_depth_l = lit ; } } assert(max_depth >= 0); this->depth_back = max_depth ; assert(clause.size()>=2) ; assert(this->formula->get_aff()); tmp = static_cast<int>(this->formula->add_clause(std::make_shared<satsolver::Clause>(this->formula->get_nb_variables(), clause, this->formula->get_aff()))); std::cout << "Learn : " << this->formula->to_clauses_vector()[tmp]->to_string() << " with " << lit_conf << " " << max_depth_l << std::endl ; if(WITH_WL) this->formula->to_clauses_vector()[tmp]->init_WL_CL(lit_conf,max_depth_l) ; return tmp ; } bool EqualityAssistant::is_state_consistent() { return this->consistent_state; } bool EqualityAssistant::detect_isolated_literals() { return false; } unsigned int EqualityAssistant::get_depth_back() { return -1; } <commit_msg>Add EqualityAssistant::get_depth_back.<commit_after>#include <cassert> #include <iostream> #include <climits> #include "solvers/equality_assistant.h" #include "config.h" using namespace theorysolver; #define VERBOSE_ASSISTANT true #define EF satsolver::ExtendedFormula #define SPEF std::shared_ptr<EF> #define EA EqualityAtom #define SPEA std::shared_ptr<EA> // Return a formula that uses only atoms in the canonical “xi-xj<=n” form. // Note that it may use literal #0; for instance, xi >= n is converted to // x0 - xi <= -n, so we will have to make sure x0 is always equal to 0. SPEF canonize_atom(SPEA atom, std::vector<SPEA> &literal_to_EA, std::string literal) { unsigned long int id1; assert(atom); if(atom->left==atom->right) { switch (atom->op) { case EA::EQUAL: // t1 = t1 atom->canonical = SPEF(new EF(EF::TRUE)); break; case EA::UNEQUAL: // t1 != t1 atom->canonical = SPEF(new EF(EF::FALSE)); break; } } else { switch (atom->op) { case EA::EQUAL: // t1 = t2 --> t1 = t2 atom->canonical = SPEF(new EF(EF::LITERAL, literal)); break; case EA::UNEQUAL: // t2 != t2 --> ~(t1 = t2) id1 = EqualityAtom::add_EA(literal_to_EA, atom->left, EA::EQUAL, atom->right); atom->canonical = SPEF(new EF(EF::NOT, SPEF(new EF(EF::LITERAL, EqualityAtom::variable_name_from_atom_id(id1))) )); break; } } return atom->canonical; } SPEF EqualityAssistant::canonize_formula(SPEF formula, std::vector<SPEA> &literal_to_EA) { SPEA atom; switch (formula->get_type()) { case EF::XOR: case EF::OR: case EF::AND: case EF::IMPLIES: return std::make_shared<EF>(formula->get_type(), EqualityAssistant::canonize_formula(formula->get_f1(), literal_to_EA), EqualityAssistant::canonize_formula(formula->get_f2(), literal_to_EA)); case EF::NOT: return std::make_shared<EF>(formula->get_type(), EqualityAssistant::canonize_formula(formula->get_f1(), literal_to_EA)); case EF::LITERAL: atom = EqualityAtom::SPEA_from_variable(literal_to_EA, formula->get_literal()); if (!EqualityAtom::is_atom_variable(formula->get_literal())) return std::make_shared<EF>(formula->get_type(), formula->get_literal()); atom = EqualityAtom::SPEA_from_variable(literal_to_EA, formula->get_literal()); return canonize_atom(atom, literal_to_EA, formula->get_literal()); case EF::TRUE: case EF::FALSE: return std::make_shared<EF>(formula->get_type()); } assert(false); } EqualityAssistant::EqualityAssistant(std::vector<SPEA> &literal_to_EA, std::shared_ptr<std::map<std::string, int>> name_to_variable, std::shared_ptr<satsolver::Formula> formula) : formula(formula), literal_to_EA(literal_to_EA), name_to_variable(*name_to_variable), variable_to_name(), union_find(), unequal(), consistent_state(true), depth_back(-1), old_polarity(formula->get_nb_variables()+1, 0) { for (auto it : *name_to_variable) this->variable_to_name.insert(make_pair(it.second, it.first)); } int EqualityAssistant::on_flip(unsigned int variable) { unsigned int atom_id; SPEA atom; int clause_id=-1; if (VERBOSE_ASSISTANT && VERBOSE) std::cout << "flip variable: " << variable; if (!EqualityAtom::is_atom_literal(this->variable_to_name, variable)) { if (VERBOSE_ASSISTANT && VERBOSE) std::cout << ", which is not an atom." << std::endl; return -1; // We care only about variables matching atoms. } assert(variable <= static_cast<unsigned int>(this->formula->get_nb_variables())); atom_id = EqualityAtom::atom_id_from_literal(this->variable_to_name, variable); atom = EqualityAtom::SPEA_from_literal(this->literal_to_EA, this->variable_to_name, variable); if (VERBOSE_ASSISTANT && VERBOSE) std::cout << ", whose atom is: " << atom_id << ", and whose new state is: "; if (this->formula->get_aff()->is_true(variable)) { if (VERBOSE_ASSISTANT && VERBOSE) std::cout << "true" << std::endl; assert(this->consistent_state); if (this->old_polarity[variable] == 1) return -1; clause_id = this->insert_atom(atom->left, atom->right, atom->op == EA::EQUAL, atom_id, variable); this->old_polarity[variable] = 1; } else if (this->formula->get_aff()->is_false(variable)) { if (VERBOSE_ASSISTANT && VERBOSE) std::cout << "false" << std::endl; assert(this->consistent_state); if (this->old_polarity[variable] == -1) return -1; clause_id = this->insert_atom(atom->left, atom->right, atom->op == EA::UNEQUAL, atom_id, variable); this->old_polarity[variable] = -1; } else { if (VERBOSE_ASSISTANT && VERBOSE) std::cout << "unknown" << std::endl; if (this->old_polarity[variable] == 0) return -1; if (this->old_polarity[variable] == 1) { this->union_find.unmerge(); } else { assert(this->unequal.size()); assert(this->unequal.back().first == atom_id); this->unequal.pop_back(); } this->consistent_state = true; this->old_polarity[variable] = 0; } return clause_id; } int EqualityAssistant::insert_atom(unsigned int i, unsigned int j, bool equal, unsigned int atom_id, int lit_conf) { if (equal) { this->union_find.merge(atom_id, i, j); for (auto it : this->unequal) { if (this->union_find.find(it.second.first) == this->union_find.find(it.second.second)) { this->consistent_state = false; return this->learn_clause(it.first, i, j, lit_conf); } } } else { this->consistent_state = (this->union_find.find(i) != this->union_find.find(j)); this->unequal.push_back(std::make_pair(atom_id, std::make_pair(i, j))); if (!this->consistent_state) return this->learn_clause(atom_id, i, j, lit_conf); } return -1; } int EqualityAssistant::literal_from_atom_id(int atom_id) const { if (atom_id > 0) return EqualityAtom::literal_from_atom_id(this->name_to_variable, static_cast<unsigned int>(atom_id)); else return -EqualityAtom::literal_from_atom_id(this->name_to_variable, static_cast<unsigned int>(-atom_id)); } #define invert_polarity(lit) this->formula->get_aff()->is_true(lit) ? -lit : lit int EqualityAssistant::learn_clause(int unequal_atomid, int i, int j, int lit_conf) { std::unordered_set<int> clause; int max_depth=-1, max_depth_l=0 ; int lit; int tmp; lit_conf = invert_polarity(lit_conf) ; clause.insert(lit_conf); clause.insert(lit=invert_polarity(this->literal_from_atom_id(unequal_atomid))); if(lit!=lit_conf) { max_depth = this->formula->get_ded()->get_deduction_depth(lit) ; max_depth_l = lit ; } for (auto it : this->union_find.get_path(i)) { lit = invert_polarity(this->literal_from_atom_id(it)); clause.insert(lit); if(lit!=lit_conf && this->formula->get_ded()->get_deduction_depth(lit) > max_depth) { max_depth = this->formula->get_ded()->get_deduction_depth(lit) ; max_depth_l = lit ; } } for (auto it : this->union_find.get_path(j)) { lit = invert_polarity(this->literal_from_atom_id(it)); clause.insert(lit); if(lit!=lit_conf && this->formula->get_ded()->get_deduction_depth(lit) > max_depth) { max_depth = this->formula->get_ded()->get_deduction_depth(lit) ; max_depth_l = lit ; } } assert(max_depth >= 0); this->depth_back = max_depth ; assert(clause.size()>=2) ; assert(this->formula->get_aff()); tmp = static_cast<int>(this->formula->add_clause(std::make_shared<satsolver::Clause>(this->formula->get_nb_variables(), clause, this->formula->get_aff()))); std::cout << "Learn : " << this->formula->to_clauses_vector()[tmp]->to_string() << " with " << lit_conf << " " << max_depth_l << std::endl ; if(WITH_WL) this->formula->to_clauses_vector()[tmp]->init_WL_CL(lit_conf,max_depth_l) ; return tmp ; } bool EqualityAssistant::is_state_consistent() { return this->consistent_state; } bool EqualityAssistant::detect_isolated_literals() { return false; } unsigned int EqualityAssistant::get_depth_back() { assert(this->depth_back>=0) ; unsigned int tmp = static_cast<unsigned int>(this->depth_back) ; // cette fonction ne doit être appelée qu'une fois par clause apprise this->depth_back = -1 ; return tmp ; } <|endoftext|>
<commit_before>/* * Copyright 2017 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <vector> #include "test/gmock.h" #include "test/gtest.h" #include "api/video_codecs/video_decoder.h" #include "call/rtp_stream_receiver_controller.h" #include "media/base/fakevideorenderer.h" #include "modules/pacing/packet_router.h" #include "modules/rtp_rtcp/source/rtp_packet_to_send.h" #include "modules/utility/include/process_thread.h" #include "rtc_base/criticalsection.h" #include "rtc_base/event.h" #include "system_wrappers/include/clock.h" #include "test/field_trial.h" #include "video/call_stats.h" #include "video/video_receive_stream.h" namespace webrtc { namespace { using testing::_; using testing::Invoke; constexpr int kDefaultTimeOutMs = 50; const char kNewJitterBufferFieldTrialEnabled[] = "WebRTC-NewVideoJitterBuffer/Enabled/"; class MockTransport : public Transport { public: MOCK_METHOD3(SendRtp, bool(const uint8_t* packet, size_t length, const PacketOptions& options)); MOCK_METHOD2(SendRtcp, bool(const uint8_t* packet, size_t length)); }; class MockVideoDecoder : public VideoDecoder { public: MOCK_METHOD2(InitDecode, int32_t(const VideoCodec* config, int32_t number_of_cores)); MOCK_METHOD4(Decode, int32_t(const EncodedImage& input, bool missing_frames, const CodecSpecificInfo* codec_specific_info, int64_t render_time_ms)); MOCK_METHOD1(RegisterDecodeCompleteCallback, int32_t(DecodedImageCallback* callback)); MOCK_METHOD0(Release, int32_t(void)); const char* ImplementationName() const { return "MockVideoDecoder"; } }; } // namespace class VideoReceiveStreamTest : public testing::Test { public: VideoReceiveStreamTest() : process_thread_(ProcessThread::Create("TestThread")), override_field_trials_(kNewJitterBufferFieldTrialEnabled), config_(&mock_transport_), call_stats_(Clock::GetRealTimeClock(), process_thread_.get()) {} void SetUp() { constexpr int kDefaultNumCpuCores = 2; config_.rtp.remote_ssrc = 1111; config_.rtp.local_ssrc = 2222; config_.renderer = &fake_renderer_; VideoReceiveStream::Decoder h264_decoder; h264_decoder.payload_type = 99; h264_decoder.payload_name = "H264"; h264_decoder.codec_params.insert( {"sprop-parameter-sets", "Z0IACpZTBYmI,aMljiA=="}); h264_decoder.decoder = &mock_h264_video_decoder_; config_.decoders.push_back(h264_decoder); VideoReceiveStream::Decoder null_decoder; null_decoder.payload_type = 98; null_decoder.payload_name = "null"; null_decoder.decoder = &mock_null_video_decoder_; config_.decoders.push_back(null_decoder); video_receive_stream_.reset(new webrtc::internal::VideoReceiveStream( &rtp_stream_receiver_controller_, kDefaultNumCpuCores, &packet_router_, config_.Copy(), process_thread_.get(), &call_stats_)); } protected: std::unique_ptr<ProcessThread> process_thread_; webrtc::test::ScopedFieldTrials override_field_trials_; VideoReceiveStream::Config config_; CallStats call_stats_; MockVideoDecoder mock_h264_video_decoder_; MockVideoDecoder mock_null_video_decoder_; cricket::FakeVideoRenderer fake_renderer_; MockTransport mock_transport_; PacketRouter packet_router_; RtpStreamReceiverController rtp_stream_receiver_controller_; std::unique_ptr<webrtc::internal::VideoReceiveStream> video_receive_stream_; }; TEST_F(VideoReceiveStreamTest, CreateFrameFromH264FmtpSpropAndIdr) { constexpr uint8_t idr_nalu[] = {0x05, 0xFF, 0xFF, 0xFF}; RtpPacketToSend rtppacket(nullptr); uint8_t* payload = rtppacket.AllocatePayload(sizeof(idr_nalu)); memcpy(payload, idr_nalu, sizeof(idr_nalu)); rtppacket.SetMarker(true); rtppacket.SetSsrc(1111); rtppacket.SetPayloadType(99); rtppacket.SetSequenceNumber(1); rtppacket.SetTimestamp(0); rtc::Event init_decode_event_(false, false); EXPECT_CALL(mock_h264_video_decoder_, InitDecode(_, _)) .WillOnce(Invoke([&init_decode_event_](const VideoCodec* config, int32_t number_of_cores) { init_decode_event_.Set(); return 0; })); EXPECT_CALL(mock_h264_video_decoder_, RegisterDecodeCompleteCallback(_)); video_receive_stream_->Start(); EXPECT_CALL(mock_h264_video_decoder_, Decode(_, false, _, _)); RtpPacketReceived parsed_packet; ASSERT_TRUE(parsed_packet.Parse(rtppacket.data(), rtppacket.size())); rtp_stream_receiver_controller_.OnRtpPacket(parsed_packet); EXPECT_CALL(mock_h264_video_decoder_, Release()); // Make sure the decoder thread had a chance to run. init_decode_event_.Wait(kDefaultTimeOutMs); } } // namespace webrtc <commit_msg>Removed old and unused WebRTC-NewVideoJitterBuffer field trial from VideoReceiveStreamTest.<commit_after>/* * Copyright 2017 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <vector> #include "test/gmock.h" #include "test/gtest.h" #include "api/video_codecs/video_decoder.h" #include "call/rtp_stream_receiver_controller.h" #include "media/base/fakevideorenderer.h" #include "modules/pacing/packet_router.h" #include "modules/rtp_rtcp/source/rtp_packet_to_send.h" #include "modules/utility/include/process_thread.h" #include "rtc_base/criticalsection.h" #include "rtc_base/event.h" #include "system_wrappers/include/clock.h" #include "test/field_trial.h" #include "video/call_stats.h" #include "video/video_receive_stream.h" namespace webrtc { namespace { using testing::_; using testing::Invoke; constexpr int kDefaultTimeOutMs = 50; class MockTransport : public Transport { public: MOCK_METHOD3(SendRtp, bool(const uint8_t* packet, size_t length, const PacketOptions& options)); MOCK_METHOD2(SendRtcp, bool(const uint8_t* packet, size_t length)); }; class MockVideoDecoder : public VideoDecoder { public: MOCK_METHOD2(InitDecode, int32_t(const VideoCodec* config, int32_t number_of_cores)); MOCK_METHOD4(Decode, int32_t(const EncodedImage& input, bool missing_frames, const CodecSpecificInfo* codec_specific_info, int64_t render_time_ms)); MOCK_METHOD1(RegisterDecodeCompleteCallback, int32_t(DecodedImageCallback* callback)); MOCK_METHOD0(Release, int32_t(void)); const char* ImplementationName() const { return "MockVideoDecoder"; } }; } // namespace class VideoReceiveStreamTest : public testing::Test { public: VideoReceiveStreamTest() : process_thread_(ProcessThread::Create("TestThread")), config_(&mock_transport_), call_stats_(Clock::GetRealTimeClock(), process_thread_.get()) {} void SetUp() { constexpr int kDefaultNumCpuCores = 2; config_.rtp.remote_ssrc = 1111; config_.rtp.local_ssrc = 2222; config_.renderer = &fake_renderer_; VideoReceiveStream::Decoder h264_decoder; h264_decoder.payload_type = 99; h264_decoder.payload_name = "H264"; h264_decoder.codec_params.insert( {"sprop-parameter-sets", "Z0IACpZTBYmI,aMljiA=="}); h264_decoder.decoder = &mock_h264_video_decoder_; config_.decoders.push_back(h264_decoder); VideoReceiveStream::Decoder null_decoder; null_decoder.payload_type = 98; null_decoder.payload_name = "null"; null_decoder.decoder = &mock_null_video_decoder_; config_.decoders.push_back(null_decoder); video_receive_stream_.reset(new webrtc::internal::VideoReceiveStream( &rtp_stream_receiver_controller_, kDefaultNumCpuCores, &packet_router_, config_.Copy(), process_thread_.get(), &call_stats_)); } protected: std::unique_ptr<ProcessThread> process_thread_; VideoReceiveStream::Config config_; CallStats call_stats_; MockVideoDecoder mock_h264_video_decoder_; MockVideoDecoder mock_null_video_decoder_; cricket::FakeVideoRenderer fake_renderer_; MockTransport mock_transport_; PacketRouter packet_router_; RtpStreamReceiverController rtp_stream_receiver_controller_; std::unique_ptr<webrtc::internal::VideoReceiveStream> video_receive_stream_; }; TEST_F(VideoReceiveStreamTest, CreateFrameFromH264FmtpSpropAndIdr) { constexpr uint8_t idr_nalu[] = {0x05, 0xFF, 0xFF, 0xFF}; RtpPacketToSend rtppacket(nullptr); uint8_t* payload = rtppacket.AllocatePayload(sizeof(idr_nalu)); memcpy(payload, idr_nalu, sizeof(idr_nalu)); rtppacket.SetMarker(true); rtppacket.SetSsrc(1111); rtppacket.SetPayloadType(99); rtppacket.SetSequenceNumber(1); rtppacket.SetTimestamp(0); rtc::Event init_decode_event_(false, false); EXPECT_CALL(mock_h264_video_decoder_, InitDecode(_, _)) .WillOnce(Invoke([&init_decode_event_](const VideoCodec* config, int32_t number_of_cores) { init_decode_event_.Set(); return 0; })); EXPECT_CALL(mock_h264_video_decoder_, RegisterDecodeCompleteCallback(_)); video_receive_stream_->Start(); EXPECT_CALL(mock_h264_video_decoder_, Decode(_, false, _, _)); RtpPacketReceived parsed_packet; ASSERT_TRUE(parsed_packet.Parse(rtppacket.data(), rtppacket.size())); rtp_stream_receiver_controller_.OnRtpPacket(parsed_packet); EXPECT_CALL(mock_h264_video_decoder_, Release()); // Make sure the decoder thread had a chance to run. init_decode_event_.Wait(kDefaultTimeOutMs); } } // namespace webrtc <|endoftext|>
<commit_before>/*********************************************************************************************************************** * * * SPLASH build system v0.2 * * * * Copyright (c) 2016 Andrew D. Zonenberg * * 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 author nor the names of any contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * * THE AUTHORS BE HELD 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 "splashcore.h" using namespace std; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Construction / destruction GNUCPPToolchain::GNUCPPToolchain(string basepath, string triplet) : CPPToolchain(basepath, TOOLCHAIN_GNU) , GNUToolchain(triplet) { //Get the full compiler version m_stringVersion = string("GNU C++") + ShellCommand(basepath + " --version | head -n 1 | cut -d \")\" -f 2"); //Parse it if(3 != sscanf(m_stringVersion.c_str(), "GNU C++ %4d.%4d.%4d", &m_majorVersion, &m_minorVersion, &m_patchVersion)) { //TODO: handle this better, don't abort :P LogFatal("bad G++ version\n"); } //Some compilers can target other arches if you feed them the right flags. //Thanks to @GyrosGeier for this string cmd = string("/bin/bash -c \"") + basepath + " -print-multi-lib | sed -e 's/.*;//' -e 's/@/ -/g' | while read line; do " + basepath + " \\$line -print-multiarch; done" + string("\""); string extra_arches = ShellCommand(cmd); vector<string> triplets; ParseLines(extra_arches, triplets); for(auto t : triplets) m_triplets.emplace(t); //If no arches found in the last step, fall back to the triplet in the file name if(m_triplets.empty()) m_triplets.emplace(triplet); //Look up where this toolchain gets its include files from for(auto t : m_triplets) { vector<string> paths; FindDefaultIncludePaths(paths, basepath, false, t); m_defaultIncludePaths[t] = paths; m_virtualSystemIncludePath[t] = "__sysinclude__/" + str_replace(" ", "_", m_stringVersion) + "_" + t; } //Set suffixes for WINDOWS if(triplet.find("mingw") != string::npos) { m_exeSuffix = ".exe"; m_shlibSuffix = ".dll"; m_stlibSuffix = ".lib"; m_objSuffix = ".obj"; m_shlibPrefix = ""; } //Set suffixes for POSIX else { m_exeSuffix = ""; m_shlibSuffix = ".so"; m_stlibSuffix = ".a"; m_objSuffix = ".o"; m_shlibPrefix = "lib"; } //Generate the hash //TODO: Anything else to add here? m_hash = sha256(m_stringVersion + triplet); } GNUCPPToolchain::~GNUCPPToolchain() { } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Toolchain properties ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Actual operations bool GNUCPPToolchain::ScanDependencies( string arch, string path, string root, set<BuildFlag> flags, set<string>& deps, map<string, string>& dephashes, string& output, set<string>& missingFiles) { return GNUToolchain::ScanDependencies( m_basepath, arch, path, root, flags, m_defaultIncludePaths[arch], deps, dephashes, output, missingFiles); } /** @brief Compile stuff */ bool GNUCPPToolchain::Build( string triplet, set<string> sources, string fname, set<BuildFlag> flags, map<string, string>& outputs, string& output) { return GNUToolchain::Compile(m_basepath, triplet, sources, fname, flags, outputs, output); } <commit_msg>BUGFIX: C++ compler should use C++ include paths<commit_after>/*********************************************************************************************************************** * * * SPLASH build system v0.2 * * * * Copyright (c) 2016 Andrew D. Zonenberg * * 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 author nor the names of any contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * * THE AUTHORS BE HELD 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 "splashcore.h" using namespace std; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Construction / destruction GNUCPPToolchain::GNUCPPToolchain(string basepath, string triplet) : CPPToolchain(basepath, TOOLCHAIN_GNU) , GNUToolchain(triplet) { //Get the full compiler version m_stringVersion = string("GNU C++") + ShellCommand(basepath + " --version | head -n 1 | cut -d \")\" -f 2"); //Parse it if(3 != sscanf(m_stringVersion.c_str(), "GNU C++ %4d.%4d.%4d", &m_majorVersion, &m_minorVersion, &m_patchVersion)) { //TODO: handle this better, don't abort :P LogFatal("bad G++ version\n"); } //Some compilers can target other arches if you feed them the right flags. //Thanks to @GyrosGeier for this string cmd = string("/bin/bash -c \"") + basepath + " -print-multi-lib | sed -e 's/.*;//' -e 's/@/ -/g' | while read line; do " + basepath + " \\$line -print-multiarch; done" + string("\""); string extra_arches = ShellCommand(cmd); vector<string> triplets; ParseLines(extra_arches, triplets); for(auto t : triplets) m_triplets.emplace(t); //If no arches found in the last step, fall back to the triplet in the file name if(m_triplets.empty()) m_triplets.emplace(triplet); //Look up where this toolchain gets its include files from for(auto t : m_triplets) { vector<string> paths; FindDefaultIncludePaths(paths, basepath, true, t); m_defaultIncludePaths[t] = paths; m_virtualSystemIncludePath[t] = "__sysinclude__/" + str_replace(" ", "_", m_stringVersion) + "_" + t; } //Set suffixes for WINDOWS if(triplet.find("mingw") != string::npos) { m_exeSuffix = ".exe"; m_shlibSuffix = ".dll"; m_stlibSuffix = ".lib"; m_objSuffix = ".obj"; m_shlibPrefix = ""; } //Set suffixes for POSIX else { m_exeSuffix = ""; m_shlibSuffix = ".so"; m_stlibSuffix = ".a"; m_objSuffix = ".o"; m_shlibPrefix = "lib"; } //Generate the hash //TODO: Anything else to add here? m_hash = sha256(m_stringVersion + triplet); } GNUCPPToolchain::~GNUCPPToolchain() { } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Toolchain properties ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Actual operations bool GNUCPPToolchain::ScanDependencies( string arch, string path, string root, set<BuildFlag> flags, set<string>& deps, map<string, string>& dephashes, string& output, set<string>& missingFiles) { return GNUToolchain::ScanDependencies( m_basepath, arch, path, root, flags, m_defaultIncludePaths[arch], deps, dephashes, output, missingFiles); } /** @brief Compile stuff */ bool GNUCPPToolchain::Build( string triplet, set<string> sources, string fname, set<BuildFlag> flags, map<string, string>& outputs, string& output) { return GNUToolchain::Compile(m_basepath, triplet, sources, fname, flags, outputs, output); } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/modules/rtp_rtcp/interface/rtp_header_parser.h" #include "webrtc/modules/rtp_rtcp/source/rtcp_utility.h" #include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" #include "webrtc/video_engine/test/common/fake_encoder.h" #include "webrtc/video_engine/test/common/frame_generator.h" #include "webrtc/video_engine/test/common/frame_generator_capturer.h" #include "webrtc/video_engine/test/common/null_transport.h" #include "webrtc/video_engine/new_include/call.h" #include "webrtc/video_engine/new_include/video_send_stream.h" namespace webrtc { class SendTransportObserver : public test::NullTransport { public: explicit SendTransportObserver(unsigned long timeout_ms) : rtp_header_parser_(RtpHeaderParser::Create()), send_test_complete_(EventWrapper::Create()), timeout_ms_(timeout_ms) {} EventTypeWrapper Wait() { return send_test_complete_->Wait(timeout_ms_); } protected: scoped_ptr<RtpHeaderParser> rtp_header_parser_; scoped_ptr<EventWrapper> send_test_complete_; private: unsigned long timeout_ms_; }; class VideoSendStreamTest : public ::testing::Test { public: VideoSendStreamTest() : fake_encoder_(Clock::GetRealTimeClock()) {} protected: static const uint32_t kSendSsrc; void RunSendTest(Call* call, const VideoSendStream::Config& config, SendTransportObserver* observer) { VideoSendStream* send_stream = call->CreateSendStream(config); scoped_ptr<test::FrameGeneratorCapturer> frame_generator_capturer( test::FrameGeneratorCapturer::Create( send_stream->Input(), test::FrameGenerator::Create(320, 240, Clock::GetRealTimeClock()), 30)); send_stream->StartSend(); frame_generator_capturer->Start(); EXPECT_EQ(kEventSignaled, observer->Wait()); frame_generator_capturer->Stop(); send_stream->StopSend(); call->DestroySendStream(send_stream); } VideoSendStream::Config GetSendTestConfig(Call* call) { VideoSendStream::Config config = call->GetDefaultSendConfig(); config.encoder = &fake_encoder_; config.internal_source = false; test::FakeEncoder::SetCodecSettings(&config.codec, 1); return config; } test::FakeEncoder fake_encoder_; }; const uint32_t VideoSendStreamTest::kSendSsrc = 0xC0FFEE; TEST_F(VideoSendStreamTest, SendsSetSsrc) { class SendSsrcObserver : public SendTransportObserver { public: SendSsrcObserver() : SendTransportObserver(30 * 1000) {} virtual bool SendRTP(const uint8_t* packet, size_t length) OVERRIDE { RTPHeader header; EXPECT_TRUE( rtp_header_parser_->Parse(packet, static_cast<int>(length), &header)); if (header.ssrc == kSendSsrc) send_test_complete_->Set(); return true; } } observer; Call::Config call_config(&observer); scoped_ptr<Call> call(Call::Create(call_config)); VideoSendStream::Config send_config = GetSendTestConfig(call.get()); send_config.rtp.ssrcs.push_back(kSendSsrc); RunSendTest(call.get(), send_config, &observer); } TEST_F(VideoSendStreamTest, SupportsCName) { static std::string kCName = "PjQatC14dGfbVwGPUOA9IH7RlsFDbWl4AhXEiDsBizo="; class CNameObserver : public SendTransportObserver { public: CNameObserver() : SendTransportObserver(30 * 1000) {} virtual bool SendRTCP(const uint8_t* packet, size_t length) OVERRIDE { RTCPUtility::RTCPParserV2 parser(packet, length, true); EXPECT_TRUE(parser.IsValid()); RTCPUtility::RTCPPacketTypes packet_type = parser.Begin(); while (packet_type != RTCPUtility::kRtcpNotValidCode) { if (packet_type == RTCPUtility::kRtcpSdesChunkCode) { EXPECT_EQ(parser.Packet().CName.CName, kCName); send_test_complete_->Set(); } packet_type = parser.Iterate(); } return true; } } observer; Call::Config call_config(&observer); scoped_ptr<Call> call(Call::Create(call_config)); VideoSendStream::Config send_config = GetSendTestConfig(call.get()); send_config.rtp.ssrcs.push_back(kSendSsrc); send_config.rtp.c_name = kCName; RunSendTest(call.get(), send_config, &observer); } } // namespace webrtc <commit_msg>Test that VideoSendStream responds to NACK.<commit_after>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/modules/rtp_rtcp/interface/rtp_header_parser.h" #include "webrtc/modules/rtp_rtcp/source/rtcp_sender.h" #include "webrtc/modules/rtp_rtcp/source/rtcp_utility.h" #include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" #include "webrtc/system_wrappers/interface/thread_wrapper.h" #include "webrtc/video_engine/test/common/fake_encoder.h" #include "webrtc/video_engine/test/common/frame_generator.h" #include "webrtc/video_engine/test/common/frame_generator_capturer.h" #include "webrtc/video_engine/test/common/null_transport.h" #include "webrtc/video_engine/new_include/call.h" #include "webrtc/video_engine/new_include/video_send_stream.h" namespace webrtc { class SendTransportObserver : public test::NullTransport { public: explicit SendTransportObserver(unsigned long timeout_ms) : rtp_header_parser_(RtpHeaderParser::Create()), send_test_complete_(EventWrapper::Create()), timeout_ms_(timeout_ms) {} EventTypeWrapper Wait() { return send_test_complete_->Wait(timeout_ms_); } protected: scoped_ptr<RtpHeaderParser> rtp_header_parser_; scoped_ptr<EventWrapper> send_test_complete_; private: unsigned long timeout_ms_; }; class VideoSendStreamTest : public ::testing::Test { public: VideoSendStreamTest() : fake_encoder_(Clock::GetRealTimeClock()) {} protected: static const uint32_t kSendSsrc; void RunSendTest(Call* call, const VideoSendStream::Config& config, SendTransportObserver* observer) { VideoSendStream* send_stream = call->CreateSendStream(config); scoped_ptr<test::FrameGeneratorCapturer> frame_generator_capturer( test::FrameGeneratorCapturer::Create( send_stream->Input(), test::FrameGenerator::Create(320, 240, Clock::GetRealTimeClock()), 30)); send_stream->StartSend(); frame_generator_capturer->Start(); EXPECT_EQ(kEventSignaled, observer->Wait()); frame_generator_capturer->Stop(); send_stream->StopSend(); call->DestroySendStream(send_stream); } VideoSendStream::Config GetSendTestConfig(Call* call) { VideoSendStream::Config config = call->GetDefaultSendConfig(); config.encoder = &fake_encoder_; config.internal_source = false; config.rtp.ssrcs.push_back(kSendSsrc); test::FakeEncoder::SetCodecSettings(&config.codec, 1); return config; } test::FakeEncoder fake_encoder_; }; const uint32_t VideoSendStreamTest::kSendSsrc = 0xC0FFEE; TEST_F(VideoSendStreamTest, SendsSetSsrc) { class SendSsrcObserver : public SendTransportObserver { public: SendSsrcObserver() : SendTransportObserver(30 * 1000) {} virtual bool SendRTP(const uint8_t* packet, size_t length) OVERRIDE { RTPHeader header; EXPECT_TRUE( rtp_header_parser_->Parse(packet, static_cast<int>(length), &header)); if (header.ssrc == kSendSsrc) send_test_complete_->Set(); return true; } } observer; Call::Config call_config(&observer); scoped_ptr<Call> call(Call::Create(call_config)); VideoSendStream::Config send_config = GetSendTestConfig(call.get()); RunSendTest(call.get(), send_config, &observer); } TEST_F(VideoSendStreamTest, SupportsCName) { static std::string kCName = "PjQatC14dGfbVwGPUOA9IH7RlsFDbWl4AhXEiDsBizo="; class CNameObserver : public SendTransportObserver { public: CNameObserver() : SendTransportObserver(30 * 1000) {} virtual bool SendRTCP(const uint8_t* packet, size_t length) OVERRIDE { RTCPUtility::RTCPParserV2 parser(packet, length, true); EXPECT_TRUE(parser.IsValid()); RTCPUtility::RTCPPacketTypes packet_type = parser.Begin(); while (packet_type != RTCPUtility::kRtcpNotValidCode) { if (packet_type == RTCPUtility::kRtcpSdesChunkCode) { EXPECT_EQ(parser.Packet().CName.CName, kCName); send_test_complete_->Set(); } packet_type = parser.Iterate(); } return true; } } observer; Call::Config call_config(&observer); scoped_ptr<Call> call(Call::Create(call_config)); VideoSendStream::Config send_config = GetSendTestConfig(call.get()); send_config.rtp.c_name = kCName; RunSendTest(call.get(), send_config, &observer); } TEST_F(VideoSendStreamTest, RespondsToNack) { class NackObserver : public SendTransportObserver, webrtc::Transport { public: NackObserver() : SendTransportObserver(30 * 1000), thread_(ThreadWrapper::CreateThread(NackProcess, this)), send_call_receiver_(NULL), send_count_(0), ssrc_(0), nacked_sequence_number_(0) {} ~NackObserver() { EXPECT_TRUE(thread_->Stop()); } void SetReceiver(PacketReceiver* send_call_receiver) { send_call_receiver_ = send_call_receiver; } // Sending NACKs must be done from a different "network" thread to prevent // violating locking orders. With this no locks are held prior to inserting // packets back into the sender. static bool NackProcess(void* observer) { return static_cast<NackObserver*>(observer)->SendNack(); } bool SendNack() { NullReceiveStatistics null_stats; RTCPSender rtcp_sender(0, false, Clock::GetRealTimeClock(), &null_stats); EXPECT_EQ(0, rtcp_sender.RegisterSendTransport(this)); rtcp_sender.SetRTCPStatus(kRtcpNonCompound); rtcp_sender.SetRemoteSSRC(ssrc_); RTCPSender::FeedbackState feedback_state; EXPECT_EQ(0, rtcp_sender.SendRTCP( feedback_state, kRtcpNack, 1, &nacked_sequence_number_)); return false; } virtual int SendPacket(int channel, const void* data, int len) OVERRIDE { ADD_FAILURE() << "This should never be reached. Only a NACK should be sent."; return -1; } virtual int SendRTCPPacket(int channel, const void* data, int len) OVERRIDE { EXPECT_TRUE(send_call_receiver_->DeliverPacket( static_cast<const uint8_t*>(data), static_cast<size_t>(len))); return len; } virtual bool SendRTP(const uint8_t* packet, size_t length) OVERRIDE { EXPECT_TRUE(send_call_receiver_ != NULL); RTPHeader header; EXPECT_TRUE( rtp_header_parser_->Parse(packet, static_cast<int>(length), &header)); // Nack second packet after receiving the third one. if (++send_count_ == 3) { ssrc_ = header.ssrc; nacked_sequence_number_ = header.sequenceNumber - 1; unsigned int id; EXPECT_TRUE(thread_->Start(id)); } if (header.sequenceNumber == nacked_sequence_number_) send_test_complete_->Set(); return true; } private: scoped_ptr<ThreadWrapper> thread_; PacketReceiver* send_call_receiver_; int send_count_; uint32_t ssrc_; uint16_t nacked_sequence_number_; } observer; Call::Config call_config(&observer); scoped_ptr<Call> call(Call::Create(call_config)); observer.SetReceiver(call->Receiver()); VideoSendStream::Config send_config = GetSendTestConfig(call.get()); send_config.rtp.nack.rtp_history_ms = 1000; RunSendTest(call.get(), send_config, &observer); } } // namespace webrtc <|endoftext|>
<commit_before>// Copyright (c) 2011 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 "views/controls/button/custom_button.h" #include "ui/base/accessibility/accessible_view_state.h" #include "ui/base/animation/throb_animation.h" #include "ui/base/keycodes/keyboard_codes.h" #include "ui/gfx/screen.h" #include "views/widget/widget.h" namespace views { // How long the hover animation takes if uninterrupted. static const int kHoverFadeDurationMs = 150; // static const char CustomButton::kViewClassName[] = "views/CustomButton"; //////////////////////////////////////////////////////////////////////////////// // CustomButton, public: CustomButton::~CustomButton() { } void CustomButton::SetState(ButtonState state) { if (state == state_) return; if (animate_on_state_change_ && (!is_throbbing_ || !hover_animation_->is_animating())) { is_throbbing_ = false; if (state_ == BS_NORMAL && state == BS_HOT) { // Button is hovered from a normal state, start hover animation. hover_animation_->Show(); } else if (state_ == BS_HOT && state == BS_NORMAL) { // Button is returning to a normal state from hover, start hover // fade animation. hover_animation_->Hide(); } else { hover_animation_->Stop(); } } state_ = state; StateChanged(); SchedulePaint(); } void CustomButton::StartThrobbing(int cycles_til_stop) { is_throbbing_ = true; hover_animation_->StartThrobbing(cycles_til_stop); } void CustomButton::StopThrobbing() { if (hover_animation_->is_animating()) { hover_animation_->Stop(); SchedulePaint(); } } void CustomButton::SetAnimationDuration(int duration) { hover_animation_->SetSlideDuration(duration); } bool CustomButton::IsMouseHovered() const { // If we haven't yet been placed in an onscreen view hierarchy, we can't be // hovered. if (!GetWidget()) return false; gfx::Point cursor_pos(gfx::Screen::GetCursorScreenPoint()); ConvertPointToView(NULL, this, &cursor_pos); return HitTest(cursor_pos); } //////////////////////////////////////////////////////////////////////////////// // CustomButton, View overrides: void CustomButton::SetHotTracked(bool flag) { if (state_ != BS_DISABLED) SetState(flag ? BS_HOT : BS_NORMAL); if (flag && GetWidget()) { GetWidget()->NotifyAccessibilityEvent( this, ui::AccessibilityTypes::EVENT_FOCUS, true); } } bool CustomButton::IsHotTracked() const { return state_ == BS_HOT; } void CustomButton::OnEnabledChanged() { if (View::IsEnabled() ? (state_ != BS_DISABLED) : (state_ == BS_DISABLED)) return; if (View::IsEnabled()) SetState(IsMouseHovered() ? BS_HOT : BS_NORMAL); else SetState(BS_DISABLED); } bool CustomButton::IsEnabled() const { return state_ != BS_DISABLED; } std::string CustomButton::GetClassName() const { return kViewClassName; } bool CustomButton::OnMousePressed(const MouseEvent& event) { if (state_ != BS_DISABLED) { if (ShouldEnterPushedState(event) && HitTest(event.location())) SetState(BS_PUSHED); if (request_focus_on_press_) RequestFocus(); } return true; } bool CustomButton::OnMouseDragged(const MouseEvent& event) { if (state_ != BS_DISABLED) { if (HitTest(event.location())) SetState(ShouldEnterPushedState(event) ? BS_PUSHED : BS_HOT); else SetState(BS_NORMAL); } return true; } void CustomButton::OnMouseReleased(const MouseEvent& event) { if (state_ == BS_DISABLED) return; if (!HitTest(event.location())) { SetState(BS_NORMAL); return; } SetState(BS_HOT); if (IsTriggerableEvent(event)) { NotifyClick(event); // NOTE: We may be deleted at this point (by the listener's notification // handler). } } void CustomButton::OnMouseCaptureLost() { // Starting a drag results in a MouseCaptureLost, we need to ignore it. if (state_ != BS_DISABLED && !InDrag()) SetState(BS_NORMAL); } void CustomButton::OnMouseEntered(const MouseEvent& event) { if (state_ != BS_DISABLED) SetState(BS_HOT); } void CustomButton::OnMouseExited(const MouseEvent& event) { // Starting a drag results in a MouseExited, we need to ignore it. if (state_ != BS_DISABLED && !InDrag()) SetState(BS_NORMAL); } void CustomButton::OnMouseMoved(const MouseEvent& event) { if (state_ != BS_DISABLED) SetState(HitTest(event.location()) ? BS_HOT : BS_NORMAL); } bool CustomButton::OnKeyPressed(const KeyEvent& event) { if (state_ == BS_DISABLED) return false; // Space sets button state to pushed. Enter clicks the button. This matches // the Windows native behavior of buttons, where Space clicks the button on // KeyRelease and Enter clicks the button on KeyPressed. if (event.key_code() == ui::VKEY_SPACE) { SetState(BS_PUSHED); } else if (event.key_code() == ui::VKEY_RETURN) { SetState(BS_NORMAL); NotifyClick(event); } else { return false; } return true; } bool CustomButton::OnKeyReleased(const KeyEvent& event) { if ((state_ == BS_DISABLED) || (event.key_code() != ui::VKEY_SPACE)) return false; SetState(BS_NORMAL); NotifyClick(event); return true; } bool CustomButton::AcceleratorPressed(const Accelerator& accelerator) { if (!View::IsEnabled()) return false; SetState(BS_NORMAL); KeyEvent key_event(ui::ET_KEY_RELEASED, accelerator.key_code(), accelerator.modifiers()); NotifyClick(key_event); return true; } void CustomButton::ShowContextMenu(const gfx::Point& p, bool is_mouse_gesture) { if (!context_menu_controller()) return; // We're about to show the context menu. Showing the context menu likely means // we won't get a mouse exited and reset state. Reset it now to be sure. if (state_ != BS_DISABLED) SetState(BS_NORMAL); View::ShowContextMenu(p, is_mouse_gesture); } void CustomButton::OnDragDone() { SetState(BS_NORMAL); } void CustomButton::GetAccessibleState(ui::AccessibleViewState* state) { Button::GetAccessibleState(state); switch (state_) { case BS_HOT: state->state = ui::AccessibilityTypes::STATE_HOTTRACKED; break; case BS_PUSHED: state->state = ui::AccessibilityTypes::STATE_PRESSED; break; case BS_DISABLED: state->state = ui::AccessibilityTypes::STATE_UNAVAILABLE; break; case BS_NORMAL: case BS_COUNT: // No additional accessibility state set for this button state. break; } } //////////////////////////////////////////////////////////////////////////////// // CustomButton, ui::AnimationDelegate implementation: void CustomButton::AnimationProgressed(const ui::Animation* animation) { SchedulePaint(); } //////////////////////////////////////////////////////////////////////////////// // CustomButton, protected: CustomButton::CustomButton(ButtonListener* listener) : Button(listener), state_(BS_NORMAL), animate_on_state_change_(true), is_throbbing_(false), triggerable_event_flags_(ui::EF_LEFT_BUTTON_DOWN), request_focus_on_press_(true) { hover_animation_.reset(new ui::ThrobAnimation(this)); hover_animation_->SetSlideDuration(kHoverFadeDurationMs); } void CustomButton::StateChanged() { } bool CustomButton::IsTriggerableEvent(const MouseEvent& event) { return (triggerable_event_flags_ & event.flags()) != 0; } bool CustomButton::ShouldEnterPushedState(const MouseEvent& event) { return IsTriggerableEvent(event); } //////////////////////////////////////////////////////////////////////////////// // CustomButton, View overrides (protected): void CustomButton::ViewHierarchyChanged(bool is_add, View *parent, View *child) { if (!is_add && state_ != BS_DISABLED) SetState(BS_NORMAL); } bool CustomButton::IsFocusable() const { return (state_ != BS_DISABLED) && View::IsFocusable(); } void CustomButton::OnBlur() { if (IsHotTracked()) SetState(BS_NORMAL); } } // namespace views <commit_msg>Fix painting issue with maximize button in aura.<commit_after>// Copyright (c) 2011 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 "views/controls/button/custom_button.h" #include "ui/base/accessibility/accessible_view_state.h" #include "ui/base/animation/throb_animation.h" #include "ui/base/keycodes/keyboard_codes.h" #include "ui/gfx/screen.h" #include "views/widget/widget.h" namespace views { // How long the hover animation takes if uninterrupted. static const int kHoverFadeDurationMs = 150; // static const char CustomButton::kViewClassName[] = "views/CustomButton"; //////////////////////////////////////////////////////////////////////////////// // CustomButton, public: CustomButton::~CustomButton() { } void CustomButton::SetState(ButtonState state) { if (state == state_) return; if (animate_on_state_change_ && (!is_throbbing_ || !hover_animation_->is_animating())) { is_throbbing_ = false; if (state_ == BS_NORMAL && state == BS_HOT) { // Button is hovered from a normal state, start hover animation. hover_animation_->Show(); } else if ((state_ == BS_HOT || state_ == BS_PUSHED) && state == BS_NORMAL) { // Button is returning to a normal state from hover, start hover // fade animation. hover_animation_->Hide(); } else { hover_animation_->Stop(); } } state_ = state; StateChanged(); SchedulePaint(); } void CustomButton::StartThrobbing(int cycles_til_stop) { is_throbbing_ = true; hover_animation_->StartThrobbing(cycles_til_stop); } void CustomButton::StopThrobbing() { if (hover_animation_->is_animating()) { hover_animation_->Stop(); SchedulePaint(); } } void CustomButton::SetAnimationDuration(int duration) { hover_animation_->SetSlideDuration(duration); } bool CustomButton::IsMouseHovered() const { // If we haven't yet been placed in an onscreen view hierarchy, we can't be // hovered. if (!GetWidget()) return false; gfx::Point cursor_pos(gfx::Screen::GetCursorScreenPoint()); ConvertPointToView(NULL, this, &cursor_pos); return HitTest(cursor_pos); } //////////////////////////////////////////////////////////////////////////////// // CustomButton, View overrides: void CustomButton::SetHotTracked(bool flag) { if (state_ != BS_DISABLED) SetState(flag ? BS_HOT : BS_NORMAL); if (flag && GetWidget()) { GetWidget()->NotifyAccessibilityEvent( this, ui::AccessibilityTypes::EVENT_FOCUS, true); } } bool CustomButton::IsHotTracked() const { return state_ == BS_HOT; } void CustomButton::OnEnabledChanged() { if (View::IsEnabled() ? (state_ != BS_DISABLED) : (state_ == BS_DISABLED)) return; if (View::IsEnabled()) SetState(IsMouseHovered() ? BS_HOT : BS_NORMAL); else SetState(BS_DISABLED); } bool CustomButton::IsEnabled() const { return state_ != BS_DISABLED; } std::string CustomButton::GetClassName() const { return kViewClassName; } bool CustomButton::OnMousePressed(const MouseEvent& event) { if (state_ != BS_DISABLED) { if (ShouldEnterPushedState(event) && HitTest(event.location())) SetState(BS_PUSHED); if (request_focus_on_press_) RequestFocus(); } return true; } bool CustomButton::OnMouseDragged(const MouseEvent& event) { if (state_ != BS_DISABLED) { if (HitTest(event.location())) SetState(ShouldEnterPushedState(event) ? BS_PUSHED : BS_HOT); else SetState(BS_NORMAL); } return true; } void CustomButton::OnMouseReleased(const MouseEvent& event) { if (state_ == BS_DISABLED) return; if (!HitTest(event.location())) { SetState(BS_NORMAL); return; } SetState(BS_HOT); if (IsTriggerableEvent(event)) { NotifyClick(event); // NOTE: We may be deleted at this point (by the listener's notification // handler). } } void CustomButton::OnMouseCaptureLost() { // Starting a drag results in a MouseCaptureLost, we need to ignore it. if (state_ != BS_DISABLED && !InDrag()) SetState(BS_NORMAL); } void CustomButton::OnMouseEntered(const MouseEvent& event) { if (state_ != BS_DISABLED) SetState(BS_HOT); } void CustomButton::OnMouseExited(const MouseEvent& event) { // Starting a drag results in a MouseExited, we need to ignore it. if (state_ != BS_DISABLED && !InDrag()) SetState(BS_NORMAL); } void CustomButton::OnMouseMoved(const MouseEvent& event) { if (state_ != BS_DISABLED) SetState(HitTest(event.location()) ? BS_HOT : BS_NORMAL); } bool CustomButton::OnKeyPressed(const KeyEvent& event) { if (state_ == BS_DISABLED) return false; // Space sets button state to pushed. Enter clicks the button. This matches // the Windows native behavior of buttons, where Space clicks the button on // KeyRelease and Enter clicks the button on KeyPressed. if (event.key_code() == ui::VKEY_SPACE) { SetState(BS_PUSHED); } else if (event.key_code() == ui::VKEY_RETURN) { SetState(BS_NORMAL); NotifyClick(event); } else { return false; } return true; } bool CustomButton::OnKeyReleased(const KeyEvent& event) { if ((state_ == BS_DISABLED) || (event.key_code() != ui::VKEY_SPACE)) return false; SetState(BS_NORMAL); NotifyClick(event); return true; } bool CustomButton::AcceleratorPressed(const Accelerator& accelerator) { if (!View::IsEnabled()) return false; SetState(BS_NORMAL); KeyEvent key_event(ui::ET_KEY_RELEASED, accelerator.key_code(), accelerator.modifiers()); NotifyClick(key_event); return true; } void CustomButton::ShowContextMenu(const gfx::Point& p, bool is_mouse_gesture) { if (!context_menu_controller()) return; // We're about to show the context menu. Showing the context menu likely means // we won't get a mouse exited and reset state. Reset it now to be sure. if (state_ != BS_DISABLED) SetState(BS_NORMAL); View::ShowContextMenu(p, is_mouse_gesture); } void CustomButton::OnDragDone() { SetState(BS_NORMAL); } void CustomButton::GetAccessibleState(ui::AccessibleViewState* state) { Button::GetAccessibleState(state); switch (state_) { case BS_HOT: state->state = ui::AccessibilityTypes::STATE_HOTTRACKED; break; case BS_PUSHED: state->state = ui::AccessibilityTypes::STATE_PRESSED; break; case BS_DISABLED: state->state = ui::AccessibilityTypes::STATE_UNAVAILABLE; break; case BS_NORMAL: case BS_COUNT: // No additional accessibility state set for this button state. break; } } //////////////////////////////////////////////////////////////////////////////// // CustomButton, ui::AnimationDelegate implementation: void CustomButton::AnimationProgressed(const ui::Animation* animation) { SchedulePaint(); } //////////////////////////////////////////////////////////////////////////////// // CustomButton, protected: CustomButton::CustomButton(ButtonListener* listener) : Button(listener), state_(BS_NORMAL), animate_on_state_change_(true), is_throbbing_(false), triggerable_event_flags_(ui::EF_LEFT_BUTTON_DOWN), request_focus_on_press_(true) { hover_animation_.reset(new ui::ThrobAnimation(this)); hover_animation_->SetSlideDuration(kHoverFadeDurationMs); } void CustomButton::StateChanged() { } bool CustomButton::IsTriggerableEvent(const MouseEvent& event) { return (triggerable_event_flags_ & event.flags()) != 0; } bool CustomButton::ShouldEnterPushedState(const MouseEvent& event) { return IsTriggerableEvent(event); } //////////////////////////////////////////////////////////////////////////////// // CustomButton, View overrides (protected): void CustomButton::ViewHierarchyChanged(bool is_add, View *parent, View *child) { if (!is_add && state_ != BS_DISABLED) SetState(BS_NORMAL); } bool CustomButton::IsFocusable() const { return (state_ != BS_DISABLED) && View::IsFocusable(); } void CustomButton::OnBlur() { if (IsHotTracked()) SetState(BS_NORMAL); } } // namespace views <|endoftext|>
<commit_before>// Copyright (c) 2016, Joseph Mirabel // Authors: Joseph Mirabel (joseph.mirabel@laas.fr) // // This file is part of hpp-core. // hpp-core is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-core is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core. If not, see <http://www.gnu.org/licenses/>. #include <hpp/core/steering-method/reeds-shepp.hh> #include <pinocchio/multibody/joint/joint.hpp> #include <hpp/pinocchio/device.hh> #include <hpp/pinocchio/joint.hh> #include <hpp/core/problem.hh> #include <hpp/core/reeds-shepp-path.hh> namespace hpp { namespace core { namespace steeringMethod { PathPtr_t ReedsShepp::impl_compute (ConfigurationIn_t q1, ConfigurationIn_t q2) const { ReedsSheppPathPtr_t path = ReedsSheppPath::create (device_.lock (), q1, q2, rho_ , xy_, rz_, constraints ()); path->setWheelJoints (turningJoint_, wheels_); return path; } void ReedsShepp::computeRadius () { rho_ = 1; if (wheels_.empty()) return; rho_ = 0; for (std::vector<JointPtr_t>::const_iterator _wheels = wheels_.begin(); _wheels != wheels_.end(); ++_wheels) { rho_ = std::max (rho_, computeAngle(*_wheels)); } hppDout (info, "rho_ = " << rho_); } ReedsShepp::ReedsShepp (const ProblemPtr_t& problem) : SteeringMethod (problem), device_ (problem->robot ()), rho_ (1.), xy_ (0), rz_(2), weak_ () { DevicePtr_t d (device_.lock()); std::string sn = d->rootJoint()->jointModel().shortname(); //TODO shortname() == se3::JointModelPlanar::classname(); if (sn == "planar") { turningJoint_ = d->rootJoint(); } else if (sn == "translation" && d->rootJoint()->configSize() == 2) { std::string sn2 = d->getJointAtConfigRank(2)->jointModel().shortname(); if (sn2 == "revoluteunbounded") turningJoint_ = d->getJointAtConfigRank(2); else throw std::runtime_error ("root joint should be of type " "se3::JointModelPlanar or JointModelTranslation + JointModelRevolute"); } else { throw std::runtime_error ("root joint should be of type " "se3::JointModelPlanar or JointModelTranslation + JointModelRevolute"); } guessWheels(); computeRadius(); } ReedsShepp::ReedsShepp (const ProblemPtr_t& problem, const value_type turningRadius, JointPtr_t xyJoint, JointPtr_t rzJoint, std::vector <JointPtr_t> wheels) : SteeringMethod (problem), device_ (problem->robot ()), rho_ (turningRadius), turningJoint_ (rzJoint), xy_ (xyJoint->rankInConfiguration()), rz_ (rzJoint->rankInConfiguration()), wheels_ (wheels), weak_ () { } /// Copy constructor ReedsShepp::ReedsShepp (const ReedsShepp& other) : SteeringMethod (other), device_ (other.device_), rho_ (other.rho_) { } inline value_type ReedsShepp::computeAngle(const JointPtr_t wheel) const { // Compute wheel position in joint RZ const Transform3f zt (turningJoint_->currentTransformation ()); const Transform3f wt (zt.actInv (wheel->currentTransformation ())); const vector3_t& wp (wt.translation ()); // Assume the non turning wheels are on the plane z = 0 of // in joint rz. const value_type alpha = (wheel->upperBound(0) - wheel->lowerBound(0)) / 2; const value_type delta = std::abs(wp[1]); const value_type beta = std::abs(wp[2]); return delta + beta / std::tan(alpha); } inline void ReedsShepp::guessWheels() { wheels_.clear(); for (std::size_t i = 0; i < turningJoint_->numberChildJoints(); ++i) { JointPtr_t j = turningJoint_->childJoint(i); if (j->configSize() != 1) continue; if (!j->isBounded(0)) continue; if (j->name().find("wheel") == std::string::npos) continue; wheels_.push_back(j); } } } // namespace steeringMethod } // namespace core } // namespace hpp <commit_msg>Fix steeringMethod::ReedsShepp<commit_after>// Copyright (c) 2016, Joseph Mirabel // Authors: Joseph Mirabel (joseph.mirabel@laas.fr) // // This file is part of hpp-core. // hpp-core is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-core is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core. If not, see <http://www.gnu.org/licenses/>. #include <hpp/core/steering-method/reeds-shepp.hh> #include <pinocchio/multibody/joint/joint.hpp> #include <hpp/pinocchio/device.hh> #include <hpp/pinocchio/joint.hh> #include <hpp/core/problem.hh> #include <hpp/core/reeds-shepp-path.hh> namespace hpp { namespace core { namespace steeringMethod { PathPtr_t ReedsShepp::impl_compute (ConfigurationIn_t q1, ConfigurationIn_t q2) const { ReedsSheppPathPtr_t path = ReedsSheppPath::create (device_.lock (), q1, q2, rho_ , xy_, rz_, constraints ()); path->setWheelJoints (turningJoint_, wheels_); return path; } void ReedsShepp::computeRadius () { rho_ = 1; if (wheels_.empty()) return; rho_ = 0; for (std::vector<JointPtr_t>::const_iterator _wheels = wheels_.begin(); _wheels != wheels_.end(); ++_wheels) { rho_ = std::max (rho_, computeAngle(*_wheels)); } hppDout (info, "rho_ = " << rho_); } ReedsShepp::ReedsShepp (const ProblemPtr_t& problem) : SteeringMethod (problem), device_ (problem->robot ()), rho_ (1.), xy_ (0), rz_(2), weak_ () { DevicePtr_t d (device_.lock()); std::string sn = d->rootJoint()->jointModel().shortname(); if (sn == se3::JointModelPlanar::classname()) { turningJoint_ = d->rootJoint(); // } else if (sn == se3::JointModelPlanar::classname() && d->rootJoint()->configSize() == 2) { // std::string sn2 = d->getJointAtConfigRank(2)->jointModel().shortname(); // if (sn2 == "revoluteunbounded") // turningJoint_ = d->getJointAtConfigRank(2); // else // throw std::runtime_error ("root joint should be of type " // "se3::JointModelPlanar or JointModelTranslation + JointModelRevolute"); } else { throw std::runtime_error ("root joint should be of type " "se3::JointModelPlanar" /*" or JointModelTranslation + JointModelRevolute"*/); } guessWheels(); computeRadius(); } ReedsShepp::ReedsShepp (const ProblemPtr_t& problem, const value_type turningRadius, JointPtr_t xyJoint, JointPtr_t rzJoint, std::vector <JointPtr_t> wheels) : SteeringMethod (problem), device_ (problem->robot ()), rho_ (turningRadius), turningJoint_ (rzJoint), xy_ (xyJoint->rankInConfiguration()), rz_ (rzJoint->rankInConfiguration()), wheels_ (wheels), weak_ () { } /// Copy constructor ReedsShepp::ReedsShepp (const ReedsShepp& other) : SteeringMethod (other), device_ (other.device_), rho_ (other.rho_) { } inline value_type ReedsShepp::computeAngle(const JointPtr_t wheel) const { // Compute wheel position in joint RZ const Transform3f zt (turningJoint_->currentTransformation ()); const Transform3f wt (zt.actInv (wheel->currentTransformation ())); const vector3_t& wp (wt.translation ()); // Assume the non turning wheels are on the plane z = 0 of // in joint rz. const value_type alpha = (wheel->upperBound(0) - wheel->lowerBound(0)) / 2; const value_type delta = std::abs(wp[1]); const value_type beta = std::abs(wp[2]); return delta + beta / std::tan(alpha); } inline void ReedsShepp::guessWheels() { wheels_.clear(); for (std::size_t i = 0; i < turningJoint_->numberChildJoints(); ++i) { JointPtr_t j = turningJoint_->childJoint(i); if (j->configSize() != 1) continue; if (!j->isBounded(0)) continue; if (j->name().find("wheel") == std::string::npos) continue; wheels_.push_back(j); } } } // namespace steeringMethod } // namespace core } // namespace hpp <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////////// // // BSD 3-Clause License // // Copyright (c) 2019, The Regents of the University of California // 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 copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////// #include "stt/SteinerTreeBuilder.h" #include "stt/flute.h" #include "stt/pdrev.h" #include <map> #include <vector> #include "ord/OpenRoad.hh" #include "opendb/db.h" namespace stt{ SteinerTreeBuilder::SteinerTreeBuilder() : alpha_(0.3), min_fanout_alpha_({0, -1}), min_hpwl_alpha_({0, -1}), logger_(nullptr), db_(nullptr) { } void SteinerTreeBuilder::init(odb::dbDatabase* db, Logger* logger) { db_ = db; logger_ = logger; } Tree SteinerTreeBuilder::makeSteinerTree(std::vector<int>& x, std::vector<int>& y, int drvr_index) { Tree tree = makeTree(x, y, drvr_index, alpha_); return tree; } Tree SteinerTreeBuilder::makeSteinerTree(odb::dbNet* net, std::vector<int>& x, std::vector<int>& y, int drvr_index) { float net_alpha = alpha_; int min_fanout = min_fanout_alpha_.first; int min_hpwl = min_hpwl_alpha_.first; if (net_alpha_map_.find(net) != net_alpha_map_.end()) { net_alpha = net_alpha_map_[net]; } else if (min_hpwl > 0) { if (computeHPWL(net) >= min_hpwl) { net_alpha = min_hpwl_alpha_.second; } } else if (min_fanout > 0) { if (net->getTermCount()-1 >= min_fanout) { net_alpha = min_fanout_alpha_.second; } } Tree tree = makeTree(x, y, drvr_index, net_alpha); return tree; } Tree SteinerTreeBuilder::makeSteinerTree(const std::vector<int>& x, const std::vector<int>& y, const std::vector<int>& s, int accuracy) { Tree tree = flt::flutes(x, y, s, accuracy); return tree; } void SteinerTreeBuilder::setAlpha(float alpha) { alpha_ = alpha; } float SteinerTreeBuilder::getAlpha(const odb::dbNet* net) const { float net_alpha = net_alpha_map_.find(net) != net_alpha_map_.end() ? net_alpha_map_.at(net) : alpha_; return net_alpha; } // This checks whether the tree has the property that no two // non-adjacent edges have intersecting bounding boxes. If // they do it is a failure as embedding those egdes may cause // overlap between them. bool SteinerTreeBuilder::checkTree(const Tree& tree) const { // Such high fanout nets are going to get buffered so // we don't need to worry about them. if (tree.deg > 100) { return true; } std::vector<odb::Rect> rects; for (int i = 0; i < tree.branchCount(); ++i) { const Branch& branch = tree.branch[i]; const int x1 = branch.x; const int y1 = branch.y; const Branch& neighbor = tree.branch[branch.n]; const int x2 = neighbor.x; const int y2 = neighbor.y; rects.emplace_back(x1, y1, x2, y2); } for (auto i = 0; i < rects.size(); ++i) { for (auto j = i + 1; j < rects.size(); ++j) { const Branch& b1 = tree.branch[i]; const Branch& b2 = tree.branch[j]; const odb::Rect& r1 = rects[i]; const odb::Rect& r2 = rects[j]; if (r1.intersects(r2) && b1.n != j && b2.n != i && b1.n != b2.n) { debugPrint(logger_, utl::STT, "check", 1, "check failed ({}, {}) ({}, {}) [{}, {}] vs ({}, {}) ({}, {}) [{}, {}] degree={}", r1.xMin(), r1.yMin(), r1.xMax(), r1.yMax(), i, b1.n, r2.xMin(), r2.yMin(), r2.xMax(), r2.yMax(), j, b2.n, tree.deg); return false; } } } return true; } void SteinerTreeBuilder::setNetAlpha(const odb::dbNet* net, float alpha) { net_alpha_map_[net] = alpha; } void SteinerTreeBuilder::setMinFanoutAlpha(int min_fanout, float alpha) { min_fanout_alpha_ = {min_fanout, alpha}; } void SteinerTreeBuilder::setMinHPWLAlpha(int min_hpwl, float alpha) { min_hpwl_alpha_ = {min_hpwl, alpha}; } Tree SteinerTreeBuilder::makeTree(std::vector<int>& x, std::vector<int>& y, int drvr_index, float alpha) { Tree tree; if (alpha > 0.0) { tree = pdr::primDijkstra(x, y, drvr_index, alpha, logger_); if (checkTree(tree)) { return tree; } // Try a smaller alpha if possible if (alpha > 0.1) { tree = pdr::primDijkstra(x, y, drvr_index, alpha - 0.1, logger_); if (checkTree(tree)) { return tree; } } // Give up and use flute return tree = flt::flute(x, y, flute_accuracy); } else { return flt::flute(x, y, flute_accuracy); } } int SteinerTreeBuilder::computeHPWL(odb::dbNet* net) { int min_x = std::numeric_limits<int>::max(); int min_y = std::numeric_limits<int>::max(); int max_x = std::numeric_limits<int>::min(); int max_y = std::numeric_limits<int>::min(); for (odb::dbITerm* iterm : net->getITerms()) { odb::dbPlacementStatus status = iterm->getInst()->getPlacementStatus(); if (status != odb::dbPlacementStatus::NONE && status != odb::dbPlacementStatus::UNPLACED) { int x, y; iterm->getAvgXY(&x, &y); min_x = std::min(min_x, x); max_x = std::max(max_x, x); min_y = std::min(min_y, y); max_y = std::max(max_y, y); } else { logger_->error(utl::STT, 4, "Net {} is connected to unplaced instance {}.", net->getName(), iterm->getInst()->getName()); } } for (odb::dbBTerm* bterm : net->getBTerms()) { if (bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::NONE || bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::UNPLACED) { int x, y; bterm->getFirstPinLocation(x, y); min_x = std::min(min_x, x); max_x = std::max(max_x, x); min_y = std::min(min_y, y); max_y = std::max(max_y, y); } else { logger_->error(utl::STT, 5, "Net {} is connected to unplaced pin {}.", net->getName(), bterm->getName()); } } int hpwl = (max_x - min_x) + (max_y - min_y); return hpwl; } void Tree::printTree(utl::Logger* logger) { if (deg > 1) { for (int i = 0; i < deg; i++) logger->report(" {:2d}: x={:4g} y={:4g} e={}", i, (float)branch[i].x, (float)branch[i].y, branch[i].n); for (int i = deg; i < 2 * deg - 2; i++) logger->report("s{:2d}: x={:4g} y={:4g} e={}", i, (float)branch[i].x, (float)branch[i].y, branch[i].n); logger->report(""); } } } <commit_msg>stt: minor refactor<commit_after>///////////////////////////////////////////////////////////////////////////// // // BSD 3-Clause License // // Copyright (c) 2019, The Regents of the University of California // 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 copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////// #include "stt/SteinerTreeBuilder.h" #include "stt/flute.h" #include "stt/pdrev.h" #include <map> #include <vector> #include "ord/OpenRoad.hh" #include "opendb/db.h" namespace stt{ SteinerTreeBuilder::SteinerTreeBuilder() : alpha_(0.3), min_fanout_alpha_({0, -1}), min_hpwl_alpha_({0, -1}), logger_(nullptr), db_(nullptr) { } void SteinerTreeBuilder::init(odb::dbDatabase* db, Logger* logger) { db_ = db; logger_ = logger; } Tree SteinerTreeBuilder::makeSteinerTree(std::vector<int>& x, std::vector<int>& y, int drvr_index) { Tree tree = makeTree(x, y, drvr_index, alpha_); return tree; } Tree SteinerTreeBuilder::makeSteinerTree(odb::dbNet* net, std::vector<int>& x, std::vector<int>& y, int drvr_index) { float net_alpha = alpha_; int min_fanout = min_fanout_alpha_.first; int min_hpwl = min_hpwl_alpha_.first; if (net_alpha_map_.find(net) != net_alpha_map_.end()) { net_alpha = net_alpha_map_[net]; } else if (min_hpwl > 0) { if (computeHPWL(net) >= min_hpwl) { net_alpha = min_hpwl_alpha_.second; } } else if (min_fanout > 0) { if (net->getTermCount()-1 >= min_fanout) { net_alpha = min_fanout_alpha_.second; } } Tree tree = makeTree(x, y, drvr_index, net_alpha); return tree; } Tree SteinerTreeBuilder::makeSteinerTree(const std::vector<int>& x, const std::vector<int>& y, const std::vector<int>& s, int accuracy) { Tree tree = flt::flutes(x, y, s, accuracy); return tree; } void SteinerTreeBuilder::setAlpha(float alpha) { alpha_ = alpha; } float SteinerTreeBuilder::getAlpha(const odb::dbNet* net) const { float net_alpha = net_alpha_map_.find(net) != net_alpha_map_.end() ? net_alpha_map_.at(net) : alpha_; return net_alpha; } // This checks whether the tree has the property that no two // non-adjacent edges have intersecting bounding boxes. If // they do it is a failure as embedding those egdes may cause // overlap between them. bool SteinerTreeBuilder::checkTree(const Tree& tree) const { // Such high fanout nets are going to get buffered so // we don't need to worry about them. if (tree.deg > 100) { return true; } std::vector<odb::Rect> rects; for (int i = 0; i < tree.branchCount(); ++i) { const Branch& branch = tree.branch[i]; const int x1 = branch.x; const int y1 = branch.y; const Branch& neighbor = tree.branch[branch.n]; const int x2 = neighbor.x; const int y2 = neighbor.y; rects.emplace_back(x1, y1, x2, y2); } for (auto i = 0; i < rects.size(); ++i) { for (auto j = i + 1; j < rects.size(); ++j) { const Branch& b1 = tree.branch[i]; const Branch& b2 = tree.branch[j]; const odb::Rect& r1 = rects[i]; const odb::Rect& r2 = rects[j]; if (r1.intersects(r2) && b1.n != j && b2.n != i && b1.n != b2.n) { debugPrint(logger_, utl::STT, "check", 1, "check failed ({}, {}) ({}, {}) [{}, {}] vs ({}, {}) ({}, {}) [{}, {}] degree={}", r1.xMin(), r1.yMin(), r1.xMax(), r1.yMax(), i, b1.n, r2.xMin(), r2.yMin(), r2.xMax(), r2.yMax(), j, b2.n, tree.deg); return false; } } } return true; } void SteinerTreeBuilder::setNetAlpha(const odb::dbNet* net, float alpha) { net_alpha_map_[net] = alpha; } void SteinerTreeBuilder::setMinFanoutAlpha(int min_fanout, float alpha) { min_fanout_alpha_ = {min_fanout, alpha}; } void SteinerTreeBuilder::setMinHPWLAlpha(int min_hpwl, float alpha) { min_hpwl_alpha_ = {min_hpwl, alpha}; } Tree SteinerTreeBuilder::makeTree(std::vector<int>& x, std::vector<int>& y, int drvr_index, float alpha) { Tree tree; if (alpha > 0.0) { tree = pdr::primDijkstra(x, y, drvr_index, alpha, logger_); if (checkTree(tree)) { return tree; } // Try a smaller alpha if possible if (alpha > 0.1) { tree = pdr::primDijkstra(x, y, drvr_index, alpha - 0.1, logger_); if (checkTree(tree)) { return tree; } } // Give up and use flute } return flt::flute(x, y, flute_accuracy); } int SteinerTreeBuilder::computeHPWL(odb::dbNet* net) { int min_x = std::numeric_limits<int>::max(); int min_y = std::numeric_limits<int>::max(); int max_x = std::numeric_limits<int>::min(); int max_y = std::numeric_limits<int>::min(); for (odb::dbITerm* iterm : net->getITerms()) { odb::dbPlacementStatus status = iterm->getInst()->getPlacementStatus(); if (status != odb::dbPlacementStatus::NONE && status != odb::dbPlacementStatus::UNPLACED) { int x, y; iterm->getAvgXY(&x, &y); min_x = std::min(min_x, x); max_x = std::max(max_x, x); min_y = std::min(min_y, y); max_y = std::max(max_y, y); } else { logger_->error(utl::STT, 4, "Net {} is connected to unplaced instance {}.", net->getName(), iterm->getInst()->getName()); } } for (odb::dbBTerm* bterm : net->getBTerms()) { if (bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::NONE || bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::UNPLACED) { int x, y; bterm->getFirstPinLocation(x, y); min_x = std::min(min_x, x); max_x = std::max(max_x, x); min_y = std::min(min_y, y); max_y = std::max(max_y, y); } else { logger_->error(utl::STT, 5, "Net {} is connected to unplaced pin {}.", net->getName(), bterm->getName()); } } int hpwl = (max_x - min_x) + (max_y - min_y); return hpwl; } void Tree::printTree(utl::Logger* logger) { if (deg > 1) { for (int i = 0; i < deg; i++) logger->report(" {:2d}: x={:4g} y={:4g} e={}", i, (float)branch[i].x, (float)branch[i].y, branch[i].n); for (int i = deg; i < 2 * deg - 2; i++) logger->report("s{:2d}: x={:4g} y={:4g} e={}", i, (float)branch[i].x, (float)branch[i].y, branch[i].n); logger->report(""); } } } <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////////// // // BSD 3-Clause License // // Copyright (c) 2019, The Regents of the University of California // 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 copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////// #include "stt/SteinerTreeBuilder.h" #include <map> #include <vector> #include "ord/OpenRoad.hh" #include "opendb/db.h" namespace stt{ SteinerTreeBuilder::SteinerTreeBuilder() : alpha_(0.3), min_fanout_alpha_({0, -1}), min_hpwl_alpha_({0, -1}), logger_(nullptr), db_(nullptr) { } void SteinerTreeBuilder::init(odb::dbDatabase* db, Logger* logger) { db_ = db; logger_ = logger; } Tree SteinerTreeBuilder::makeSteinerTree(std::vector<int>& x, std::vector<int>& y, int drvr_index) { Tree tree = makeTree(x, y, drvr_index, alpha_); return tree; } Tree SteinerTreeBuilder::makeSteinerTree(odb::dbNet* net, std::vector<int>& x, std::vector<int>& y, int drvr_index) { float net_alpha = alpha_; int min_fanout = min_fanout_alpha_.first; int min_hpwl = min_hpwl_alpha_.first; if (net_alpha_map_.find(net) != net_alpha_map_.end()) { net_alpha = net_alpha_map_[net]; } else if (min_hpwl > 0) { if (computeHPWL(net) >= min_hpwl) { net_alpha = min_hpwl_alpha_.second; } } else if (min_fanout > 0) { if (net->getTermCount()-1 >= min_fanout) { net_alpha = min_fanout_alpha_.second; } } Tree tree = makeTree(x, y, drvr_index, net_alpha); return tree; } Tree SteinerTreeBuilder::makeSteinerTree(const std::vector<int>& x, const std::vector<int>& y, const std::vector<int>& s, int accuracy) { Tree tree = flt::flutes(x, y, s, accuracy); return tree; } float SteinerTreeBuilder::getAlpha(const odb::dbNet* net) const { float net_alpha = net_alpha_map_.find(net) != net_alpha_map_.end() ? net_alpha_map_.at(net) : alpha_; return net_alpha; } // This checks whether the tree has the property that no two // non-adjacent edges have intersecting bounding boxes. If // they do it is a failure as embedding those egdes may cause // overlap between them. bool SteinerTreeBuilder::checkTree(const Tree& tree) const { // Such high fanout nets are going to get buffered so // we don't need to worry about them. if (tree.deg > 100) { return true; } std::vector<odb::Rect> rects; for (int i = 0; i < tree.branchCount(); ++i) { const Branch& branch = tree.branch[i]; const int x1 = branch.x; const int y1 = branch.y; const Branch& neighbor = tree.branch[branch.n]; const int x2 = neighbor.x; const int y2 = neighbor.y; rects.emplace_back(x1, y1, x2, y2); } for (auto i = 0; i < rects.size(); ++i) { for (auto j = i + 1; j < rects.size(); ++j) { const Branch& b1 = tree.branch[i]; const Branch& b2 = tree.branch[j]; const odb::Rect& r1 = rects[i]; const odb::Rect& r2 = rects[j]; if (r1.intersects(r2) && b1.n != j && b2.n != i && b1.n != b2.n) { debugPrint(logger_, utl::STT, "check", 1, "check failed ({}, {}) ({}, {}) [{}, {}] vs ({}, {}) ({}, {}) [{}, {}] degree={}", r1.xMin(), r1.yMin(), r1.xMax(), r1.yMax(), i, b1.n, r2.xMin(), r2.yMin(), r2.xMax(), r2.yMax(), j, b2.n, tree.deg); return false; } } } return true; } Tree SteinerTreeBuilder::makeTree(std::vector<int>& x, std::vector<int>& y, int drvr_index, float alpha) { Tree tree; if (alpha > 0.0) { tree = pdr::primDijkstra(x, y, drvr_index, alpha, logger_); if (!checkTree(tree)) { // fallback tree = flt::flute(x, y, flute_accuracy); } } else { tree = flt::flute(x, y, flute_accuracy); } return tree; } int SteinerTreeBuilder::computeHPWL(odb::dbNet* net) { int min_x = std::numeric_limits<int>::max(); int min_y = std::numeric_limits<int>::max(); int max_x = std::numeric_limits<int>::min(); int max_y = std::numeric_limits<int>::min(); for (odb::dbITerm* iterm : net->getITerms()) { odb::dbPlacementStatus status = iterm->getInst()->getPlacementStatus(); if (status != odb::dbPlacementStatus::NONE && status != odb::dbPlacementStatus::UNPLACED) { int x, y; iterm->getAvgXY(&x, &y); min_x = std::min(min_x, x); max_x = std::max(max_x, x); min_y = std::min(min_y, y); max_y = std::max(max_y, y); } else { logger_->error(utl::STT, 4, "Net {} is connected to unplaced instance {}.", net->getName(), iterm->getInst()->getName()); } } for (odb::dbBTerm* bterm : net->getBTerms()) { if (bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::NONE || bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::UNPLACED) { int x, y; bterm->getFirstPinLocation(x, y); min_x = std::min(min_x, x); max_x = std::max(max_x, x); min_y = std::min(min_y, y); max_y = std::max(max_y, y); } else { logger_->error(utl::STT, 5, "Net {} is connected to unplaced pin {}.", net->getName(), bterm->getName()); } } int hpwl = (max_x - min_x) + (max_y - min_y); return hpwl; } } <commit_msg>stt: try adding alpha-0.1 fallback<commit_after>///////////////////////////////////////////////////////////////////////////// // // BSD 3-Clause License // // Copyright (c) 2019, The Regents of the University of California // 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 copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////// #include "stt/SteinerTreeBuilder.h" #include <map> #include <vector> #include "ord/OpenRoad.hh" #include "opendb/db.h" namespace stt{ SteinerTreeBuilder::SteinerTreeBuilder() : alpha_(0.3), min_fanout_alpha_({0, -1}), min_hpwl_alpha_({0, -1}), logger_(nullptr), db_(nullptr) { } void SteinerTreeBuilder::init(odb::dbDatabase* db, Logger* logger) { db_ = db; logger_ = logger; } Tree SteinerTreeBuilder::makeSteinerTree(std::vector<int>& x, std::vector<int>& y, int drvr_index) { Tree tree = makeTree(x, y, drvr_index, alpha_); return tree; } Tree SteinerTreeBuilder::makeSteinerTree(odb::dbNet* net, std::vector<int>& x, std::vector<int>& y, int drvr_index) { float net_alpha = alpha_; int min_fanout = min_fanout_alpha_.first; int min_hpwl = min_hpwl_alpha_.first; if (net_alpha_map_.find(net) != net_alpha_map_.end()) { net_alpha = net_alpha_map_[net]; } else if (min_hpwl > 0) { if (computeHPWL(net) >= min_hpwl) { net_alpha = min_hpwl_alpha_.second; } } else if (min_fanout > 0) { if (net->getTermCount()-1 >= min_fanout) { net_alpha = min_fanout_alpha_.second; } } Tree tree = makeTree(x, y, drvr_index, net_alpha); return tree; } Tree SteinerTreeBuilder::makeSteinerTree(const std::vector<int>& x, const std::vector<int>& y, const std::vector<int>& s, int accuracy) { Tree tree = flt::flutes(x, y, s, accuracy); return tree; } float SteinerTreeBuilder::getAlpha(const odb::dbNet* net) const { float net_alpha = net_alpha_map_.find(net) != net_alpha_map_.end() ? net_alpha_map_.at(net) : alpha_; return net_alpha; } // This checks whether the tree has the property that no two // non-adjacent edges have intersecting bounding boxes. If // they do it is a failure as embedding those egdes may cause // overlap between them. bool SteinerTreeBuilder::checkTree(const Tree& tree) const { // Such high fanout nets are going to get buffered so // we don't need to worry about them. if (tree.deg > 100) { return true; } std::vector<odb::Rect> rects; for (int i = 0; i < tree.branchCount(); ++i) { const Branch& branch = tree.branch[i]; const int x1 = branch.x; const int y1 = branch.y; const Branch& neighbor = tree.branch[branch.n]; const int x2 = neighbor.x; const int y2 = neighbor.y; rects.emplace_back(x1, y1, x2, y2); } for (auto i = 0; i < rects.size(); ++i) { for (auto j = i + 1; j < rects.size(); ++j) { const Branch& b1 = tree.branch[i]; const Branch& b2 = tree.branch[j]; const odb::Rect& r1 = rects[i]; const odb::Rect& r2 = rects[j]; if (r1.intersects(r2) && b1.n != j && b2.n != i && b1.n != b2.n) { debugPrint(logger_, utl::STT, "check", 1, "check failed ({}, {}) ({}, {}) [{}, {}] vs ({}, {}) ({}, {}) [{}, {}] degree={}", r1.xMin(), r1.yMin(), r1.xMax(), r1.yMax(), i, b1.n, r2.xMin(), r2.yMin(), r2.xMax(), r2.yMax(), j, b2.n, tree.deg); return false; } } } return true; } Tree SteinerTreeBuilder::makeTree(std::vector<int>& x, std::vector<int>& y, int drvr_index, float alpha) { Tree tree; if (alpha > 0.0) { tree = pdr::primDijkstra(x, y, drvr_index, alpha, logger_); if (checkTree(tree)) { return tree; } // Try a smaller alpha if possible if (alpha > 0.1) { tree = pdr::primDijkstra(x, y, drvr_index, alpha - 0.1, logger_); if (checkTree(tree)) { return tree; } } // Give up and use flute return tree = flt::flute(x, y, flute_accuracy); } else { return flt::flute(x, y, flute_accuracy); } } int SteinerTreeBuilder::computeHPWL(odb::dbNet* net) { int min_x = std::numeric_limits<int>::max(); int min_y = std::numeric_limits<int>::max(); int max_x = std::numeric_limits<int>::min(); int max_y = std::numeric_limits<int>::min(); for (odb::dbITerm* iterm : net->getITerms()) { odb::dbPlacementStatus status = iterm->getInst()->getPlacementStatus(); if (status != odb::dbPlacementStatus::NONE && status != odb::dbPlacementStatus::UNPLACED) { int x, y; iterm->getAvgXY(&x, &y); min_x = std::min(min_x, x); max_x = std::max(max_x, x); min_y = std::min(min_y, y); max_y = std::max(max_y, y); } else { logger_->error(utl::STT, 4, "Net {} is connected to unplaced instance {}.", net->getName(), iterm->getInst()->getName()); } } for (odb::dbBTerm* bterm : net->getBTerms()) { if (bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::NONE || bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::UNPLACED) { int x, y; bterm->getFirstPinLocation(x, y); min_x = std::min(min_x, x); max_x = std::max(max_x, x); min_y = std::min(min_y, y); max_y = std::max(max_y, y); } else { logger_->error(utl::STT, 5, "Net {} is connected to unplaced pin {}.", net->getName(), bterm->getName()); } } int hpwl = (max_x - min_x) + (max_y - min_y); return hpwl; } } <|endoftext|>
<commit_before>// Check that the stack trace debugging API works and returns correct // malloc and free stacks. // RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s #include <sanitizer/asan_interface.h> #include <stdio.h> #include <stdlib.h> char *mem; void func1() { mem = (char *)malloc(10); } void func2() { free(mem); } int main() { func1(); func2(); void *trace[100]; size_t num_frames = 100; int thread_id; num_frames = __asan_get_alloc_stack(mem, trace, num_frames, &thread_id); fprintf(stderr, "alloc stack retval %s\n", (num_frames > 0 && num_frames < 10) ? "ok" : ""); // CHECK: alloc stack retval ok fprintf(stderr, "thread id = %d\n", thread_id); // CHECK: thread id = 0 fprintf(stderr, "0x%lx\n", trace[0]); // CHECK: [[ALLOC_FRAME_0:0x[0-9a-f]+]] fprintf(stderr, "0x%lx\n", trace[1]); // CHECK: [[ALLOC_FRAME_1:0x[0-9a-f]+]] num_frames = 100; num_frames = __asan_get_free_stack(mem, trace, num_frames, &thread_id); fprintf(stderr, "free stack retval %s\n", (num_frames > 0 && num_frames < 10) ? "ok" : ""); // CHECK: free stack retval ok fprintf(stderr, "thread id = %d\n", thread_id); // CHECK: thread id = 0 fprintf(stderr, "0x%lx\n", trace[0]); // CHECK: [[FREE_FRAME_0:0x[0-9a-f]+]] fprintf(stderr, "0x%lx\n", trace[1]); // CHECK: [[FREE_FRAME_1:0x[0-9a-f]+]] mem[0] = 'A'; // BOOM // CHECK: ERROR: AddressSanitizer: heap-use-after-free // CHECK: WRITE of size 1 at 0x{{.*}} // CHECK: freed by thread T0 here: // CHECK: #0 [[FREE_FRAME_0]] // CHECK: #1 [[FREE_FRAME_1]] // CHECK: previously allocated by thread T0 here: // CHECK: #0 [[ALLOC_FRAME_0]] // CHECK: #1 [[ALLOC_FRAME_1]] return 0; } <commit_msg>[ASan] debug_stacks.cc was passing on ARM by accident, disable this test there for now.<commit_after>// Check that the stack trace debugging API works and returns correct // malloc and free stacks. // RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s // FIXME: Figure out why allocation/free stack traces may be too short on ARM. // REQUIRES: stable-runtime #include <sanitizer/asan_interface.h> #include <stdio.h> #include <stdlib.h> char *mem; void func1() { mem = (char *)malloc(10); } void func2() { free(mem); } int main() { func1(); func2(); void *trace[100]; size_t num_frames = 100; int thread_id; num_frames = __asan_get_alloc_stack(mem, trace, num_frames, &thread_id); fprintf(stderr, "alloc stack retval %s\n", (num_frames > 0 && num_frames < 10) ? "ok" : ""); // CHECK: alloc stack retval ok fprintf(stderr, "thread id = %d\n", thread_id); // CHECK: thread id = 0 fprintf(stderr, "0x%lx\n", trace[0]); // CHECK: [[ALLOC_FRAME_0:0x[0-9a-f]+]] fprintf(stderr, "0x%lx\n", trace[1]); // CHECK: [[ALLOC_FRAME_1:0x[0-9a-f]+]] num_frames = 100; num_frames = __asan_get_free_stack(mem, trace, num_frames, &thread_id); fprintf(stderr, "free stack retval %s\n", (num_frames > 0 && num_frames < 10) ? "ok" : ""); // CHECK: free stack retval ok fprintf(stderr, "thread id = %d\n", thread_id); // CHECK: thread id = 0 fprintf(stderr, "0x%lx\n", trace[0]); // CHECK: [[FREE_FRAME_0:0x[0-9a-f]+]] fprintf(stderr, "0x%lx\n", trace[1]); // CHECK: [[FREE_FRAME_1:0x[0-9a-f]+]] mem[0] = 'A'; // BOOM // CHECK: ERROR: AddressSanitizer: heap-use-after-free // CHECK: WRITE of size 1 at 0x{{.*}} // CHECK: freed by thread T0 here: // CHECK: #0 [[FREE_FRAME_0]] // CHECK: #1 [[FREE_FRAME_1]] // CHECK: previously allocated by thread T0 here: // CHECK: #0 [[ALLOC_FRAME_0]] // CHECK: #1 [[ALLOC_FRAME_1]] return 0; } <|endoftext|>
<commit_before>/***************************************************//** * @file FlameXUSBTransferHelper.cpp * @date February 2016 * @author Ocean Optics, Inc. * * LICENSE: * * SeaBreeze Copyright (C) 2016, Ocean Optics Inc * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *******************************************************/ #include "common/globals.h" #include "vendors/OceanOptics/buses/usb/FlameXUSBTransferHelper.h" #include <string.h> /* for memcpy() */ using namespace seabreeze; using namespace std; const int FlameXUSBTransferHelper::WORD_SIZE_BYTES = 4; FlameXUSBTransferHelper::FlameXUSBTransferHelper(USB *usb, const OOIUSBBidrectionalEndpointMap &map) : USBTransferHelper(usb) { this->sendEndpoint = map.getPrimaryOutEndpoint(); this->receiveEndpoint = map.getPrimaryInEndpoint(); } FlameXUSBTransferHelper::~FlameXUSBTransferHelper() { } int FlameXUSBTransferHelper::receive(vector<byte> &buffer, unsigned int length) { if(0 != (length % WORD_SIZE_BYTES)) { vector<byte> *inBuffer; int paddedLength; paddedLength = length + (WORD_SIZE_BYTES - (length % WORD_SIZE_BYTES)); inBuffer = new vector<byte>(paddedLength); int result = USBTransferHelper::receive(*inBuffer, paddedLength); if(result != paddedLength) { string error("Failed to read padded message length: "); error += result; error += " != "; error += paddedLength; throw BusTransferException(error); } memcpy(&buffer[0], &inBuffer[0], length); delete inBuffer; return length; } else { return USBTransferHelper::receive(buffer, length); } } int FlameXUSBTransferHelper::send(const std::vector<byte> &buffer, unsigned int length) const { if(0 != (length % WORD_SIZE_BYTES)) { /* Pad up to a multiple of the word size */ int paddedLength = length + (WORD_SIZE_BYTES - (length % WORD_SIZE_BYTES)); vector<byte> *outBuffer = new vector<byte>(paddedLength); memcpy(&outBuffer[0], &buffer[0], length); int result = USBTransferHelper::send(*outBuffer, paddedLength); delete outBuffer; return result; } else { return USBTransferHelper::send(buffer, length); } } <commit_msg>[libseabreeze] fix FlameXUSBTransferHelper warning<commit_after>/***************************************************//** * @file FlameXUSBTransferHelper.cpp * @date February 2016 * @author Ocean Optics, Inc. * * LICENSE: * * SeaBreeze Copyright (C) 2016, Ocean Optics Inc * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *******************************************************/ #include "common/globals.h" #include "vendors/OceanOptics/buses/usb/FlameXUSBTransferHelper.h" #include <string.h> /* for memcpy() */ using namespace seabreeze; using namespace std; const int FlameXUSBTransferHelper::WORD_SIZE_BYTES = 4; FlameXUSBTransferHelper::FlameXUSBTransferHelper(USB *usb, const OOIUSBBidrectionalEndpointMap &map) : USBTransferHelper(usb) { this->sendEndpoint = map.getPrimaryOutEndpoint(); this->receiveEndpoint = map.getPrimaryInEndpoint(); } FlameXUSBTransferHelper::~FlameXUSBTransferHelper() { } int FlameXUSBTransferHelper::receive(vector<byte> &buffer, unsigned int length) { if(0 != (length % WORD_SIZE_BYTES)) { vector<byte> *inBuffer; int paddedLength; paddedLength = length + (WORD_SIZE_BYTES - (length % WORD_SIZE_BYTES)); inBuffer = new vector<byte>(paddedLength); int result = USBTransferHelper::receive(*inBuffer, paddedLength); if(result != paddedLength) { string error("Failed to read padded message length: "); error += result; error += " != "; error += paddedLength; throw BusTransferException(error); } memcpy(&buffer[0], &inBuffer[0], length); delete inBuffer; return length; } else { return USBTransferHelper::receive(buffer, length); } } int FlameXUSBTransferHelper::send(const std::vector<byte> &buffer, unsigned int length) const { if(0 != (length % WORD_SIZE_BYTES)) { /* Pad up to a multiple of the word size */ int paddedLength = length + (WORD_SIZE_BYTES - (length % WORD_SIZE_BYTES)); vector<byte> *outBuffer = new vector<byte>(paddedLength); memcpy((byte*) &outBuffer[0], (byte*) &buffer[0], length); int result = USBTransferHelper::send(*outBuffer, paddedLength); delete outBuffer; return result; } else { return USBTransferHelper::send(buffer, length); } } <|endoftext|>
<commit_before>/*! * \brief Tests the GUI geometry builder * * \author ddubois * \date 06-Nov-16. */ #include <vector> #include <gtest/gtest.h> #include <data_loading/geometry_cache/builders/gui_geometry_builder.h> #include <view/nova_renderer.h> TEST(gui_geometry_builder, add_vertex_test) { auto vertex_buffer = std::vector<float>{}; nova::model::add_vertex(vertex_buffer, 5, 5, 0.5, 0.5); EXPECT_EQ(vertex_buffer.size(), 5); EXPECT_EQ(vertex_buffer[0], 5); EXPECT_EQ(vertex_buffer[1], 5); EXPECT_EQ(vertex_buffer[2], 0); EXPECT_EQ(vertex_buffer[3], 0.5); EXPECT_EQ(vertex_buffer[4], 0.5); } TEST(gui_geometry_builder, add_vertices_from_button_test) { auto vertex_buffer = std::vector<float>{}; auto button = mc_gui_button{0, 0, 100, 100, "Main Menu", false}; auto uvs = std::vector<float>{0, 0, 0, 1, 1, 0, 1, 1}; nova::model::add_vertices_from_button(vertex_buffer, button, uvs); EXPECT_EQ(vertex_buffer.size(), 20); // First vertex EXPECT_EQ(vertex_buffer[0], 0); EXPECT_EQ(vertex_buffer[1], 0); EXPECT_EQ(vertex_buffer[2], 0); EXPECT_EQ(vertex_buffer[3], 0); // Third vertex because I'm too lazy to check all of them EXPECT_EQ(vertex_buffer[10], 0); EXPECT_EQ(vertex_buffer[11], 100); EXPECT_EQ(vertex_buffer[13], 1); EXPECT_EQ(vertex_buffer[14], 0); } TEST(gui_geometry_builder, add_indices_with_offset_positive_test) { auto indices = std::vector<unsigned>{}; auto start_pos = 3; nova::model::add_indices_with_offset(indices, (unsigned int) start_pos); EXPECT_EQ(indices[0], 3); EXPECT_EQ(indices[1], 4); EXPECT_EQ(indices[2], 5); EXPECT_EQ(indices[3], 5); EXPECT_EQ(indices[4], 4); EXPECT_EQ(indices[5], 6); } TEST(gui_geometry_builder, add_indices_with_offset_negative_offset_test) { auto indices = std::vector<unsigned>{}; auto start_pos = -3; nova::model::add_indices_with_offset(indices, (unsigned int) start_pos); EXPECT_EQ(indices[0], 65533); EXPECT_EQ(indices[1], 65534); EXPECT_EQ(indices[2], 65535); EXPECT_EQ(indices[3], 65535); EXPECT_EQ(indices[4], 65534); EXPECT_EQ(indices[5], 0); } TEST(gui_geometry_builder, build_gui_geometry_no_buttons_test) { nova::view::nova_renderer::init_instance(); mc_gui_screen gui = {}; gui.num_buttons = 0; nova::model::mesh_definition gui_mesh = nova::model::build_gui_geometry(gui); } <commit_msg>All tests now pass<commit_after>/*! * \brief Tests the GUI geometry builder * * \author ddubois * \date 06-Nov-16. */ #include <vector> #include <gtest/gtest.h> #include <data_loading/geometry_cache/builders/gui_geometry_builder.h> #include <view/nova_renderer.h> TEST(gui_geometry_builder, add_vertex_test) { auto vertex_buffer = std::vector<float>{}; nova::model::add_vertex(vertex_buffer, 5, 5, 0.5, 0.5); EXPECT_EQ(vertex_buffer.size(), 5); EXPECT_EQ(vertex_buffer[0], 5); EXPECT_EQ(vertex_buffer[1], 5); EXPECT_EQ(vertex_buffer[2], 0); EXPECT_EQ(vertex_buffer[3], 0.5); EXPECT_EQ(vertex_buffer[4], 0.5); } TEST(gui_geometry_builder, add_vertices_from_button_test) { auto vertex_buffer = std::vector<float>{}; auto button = mc_gui_button{0, 0, 100, 100, "Main Menu", false}; auto uvs = std::vector<float>{0, 0, 0, 1, 1, 0, 1, 1}; nova::model::add_vertices_from_button(vertex_buffer, button, uvs); EXPECT_EQ(vertex_buffer.size(), 20); // First vertex EXPECT_EQ(vertex_buffer[0], 0); EXPECT_EQ(vertex_buffer[1], 0); EXPECT_EQ(vertex_buffer[2], 0); EXPECT_EQ(vertex_buffer[3], 0); // Third vertex because I'm too lazy to check all of them EXPECT_EQ(vertex_buffer[10], 0); EXPECT_EQ(vertex_buffer[11], 100); EXPECT_EQ(vertex_buffer[13], 1); EXPECT_EQ(vertex_buffer[14], 0); } TEST(gui_geometry_builder, add_indices_with_offset_positive_test) { auto indices = std::vector<unsigned>{}; auto start_pos = 3; nova::model::add_indices_with_offset(indices, (unsigned int) start_pos); EXPECT_EQ(indices[0], 3); EXPECT_EQ(indices[1], 4); EXPECT_EQ(indices[2], 5); EXPECT_EQ(indices[3], 5); EXPECT_EQ(indices[4], 4); EXPECT_EQ(indices[5], 6); } TEST(gui_geometry_builder, add_indices_with_offset_negative_offset_test) { auto indices = std::vector<unsigned>{}; auto start_pos = -3; nova::model::add_indices_with_offset(indices, (unsigned int) start_pos); EXPECT_EQ(indices[0], 4294967293); EXPECT_EQ(indices[1], 4294967294); EXPECT_EQ(indices[2], 4294967295); EXPECT_EQ(indices[3], 4294967295); EXPECT_EQ(indices[4], 4294967294); EXPECT_EQ(indices[5], 0); } TEST(gui_geometry_builder, build_gui_geometry_no_buttons_test) { nova::view::nova_renderer::init_instance(); mc_gui_screen gui = {}; gui.num_buttons = 0; nova::model::mesh_definition gui_mesh = nova::model::build_gui_geometry(gui); } <|endoftext|>
<commit_before>// programming_challenges_13.cpp: santiaago // Description: Australian Voting - Programming challenges 110108 #include <iostream> #include <vector> #include <sstream> #include <string> #include <map> using namespace std; template<typename T> void printVector(vector<T> v); void printMap(map<string, unsigned int> m); int main(){ cout << "Australian Voting" << endl; unsigned int num_cases(0); cin >> num_cases; string line; getline (cin, line); while(num_cases > 0){ unsigned int num_candidates(0); cin >> num_candidates; vector<string> candidates(num_candidates); map<unsigned int, map<string, unsigned int> > candidate_votes; string candidate; while( num_candidates > 0 && cin >> candidate ){ candidates[candidates.size()-num_candidates] = candidate; num_candidates--; } printVector(candidates); //printMap(candidate_votes); // read up to 1000 lines string vote; unsigned int num_votes(0); cin.ignore(); while( num_votes < 1000){ getline(cin, vote); if(vote.empty()) break; istringstream stm(vote); unsigned int index_candidate; vector<unsigned int> current_vote; while( stm >> index_candidate){ current_vote.push_back(index_candidate); } for(int i = 0; i < current_vote.size(); i++){ //candidate_votes[candidates[current_vote[i] - 1]]++; cout << "vote: " << current_vote[i] << endl; cout << "candidate: " << candidates[current_vote[i]-1] << endl; cout << "count: " << candidate_votes[i + 1][candidates[current_vote[i]-1]] << endl; candidate_votes[i + 1][candidates[current_vote[i]-1]]++;//candidates[current_vote[i]][ cout << "count: " << candidate_votes[i + 1][candidates[current_vote[i]-1]] << endl; } printVector(current_vote); num_votes++; } // printMap(candidate_votes); for(auto t : candidate_votes){ cout << t.first << " | "; for(auto t2 : t.second){ cout << "\t" << t2.first << " : " << t2.second << endl; } } cout << "case done " << endl; num_cases--; } cout << "end" << endl; } template<typename T> void printVector(vector<T> v){ for(T c : v){ cout << c << " | "; } cout << endl; } void printMap(map<string, unsigned int> m){ for(auto t : m){ cout << t.first << " : " << t.second << endl; } } <commit_msg>main algorithm for the australian vote is ready.<commit_after>// programming_challenges_13.cpp: santiaago // Description: Australian Voting - Programming challenges 110108 #include <iostream> #include <vector> #include <sstream> #include <string> #include <map> #include <limits> using namespace std; template<typename T> void printVector(vector<T> v); void printMap(map<string, unsigned int> m); string getLowestCandidate(map<string, unsigned int> candidates); string getHighestCandidate(map<string, unsigned int> m); bool areCandidatesTied(map<string, unsigned int> candidates); int main(){ cout << "Australian Voting" << endl; unsigned int num_cases(0); cin >> num_cases; string line; getline (cin, line); vector<string> winners; while(num_cases > 0){ unsigned int num_candidates(0); cin >> num_candidates; vector<string> candidates(num_candidates); map<unsigned int, map<string, unsigned int> > candidate_votes; string candidate; while( num_candidates > 0 && cin >> candidate ){ candidates[candidates.size()-num_candidates] = candidate; num_candidates--; } printVector(candidates); // read up to 1000 lines string vote; unsigned int num_votes(0); cin.ignore(); while( num_votes < 1000){ getline(cin, vote); if(vote.empty()) break; istringstream stm(vote); unsigned int index_candidate; vector<unsigned int> current_vote; while( stm >> index_candidate){ current_vote.push_back(index_candidate); } for(int i = 0; i < current_vote.size(); i++){ //candidate_votes[candidates[current_vote[i] - 1]]++; cout << "vote: " << current_vote[i] << endl; cout << "candidate: " << candidates[current_vote[i]-1] << endl; cout << "count: " << candidate_votes[i + 1][candidates[current_vote[i]-1]] << endl; candidate_votes[i + 1][candidates[current_vote[i]-1]]++;//candidates[current_vote[i]][ cout << "count: " << candidate_votes[i + 1][candidates[current_vote[i]-1]] << endl; } printVector(current_vote); num_votes++; } for(auto t : candidate_votes){ cout << t.first << " | "; for(auto t2 : t.second){ cout << "\t" << t2.first << " : " << t2.second << endl; } } double mayority = num_votes/double(2.0); bool has_winner(false); while(!has_winner){ for(auto t : candidate_votes[1]){ if(t.second > mayority){ winners.push_back(t.first); has_winner = true; break; } } if(!has_winner){ string highest_candidate = getHighestCandidate(candidate_votes[1]); string lowest_candidate = getLowestCandidate(candidate_votes[1]); unsigned int votes = candidate_votes[1][lowest_candidate]; map<string, unsigned int>::iterator to_remove; to_remove = candidate_votes[1].find(lowest_candidate); candidate_votes[1].erase(to_remove); candidate_votes[1][highest_candidate] += votes; } if(areCandidatesTied(candidate_votes[1])){ for(auto c : candidate_votes[1]){ winners.push_back(c.first); } has_winner = true; } } for(auto w : winners){ cout << w << endl; } cout << "case done " << endl; num_cases--; } for(int i = 0; i < winners.size(); i++){ cout << winners[i] << endl; } cout << "end" << endl; } template<typename T> void printVector(vector<T> v){ for(T c : v){ cout << c << " | "; } cout << endl; } void printMap(map<string, unsigned int> m){ for(auto t : m){ cout << t.first << " : " << t.second << endl; } } bool areCandidatesTied(map<string, unsigned int> candidates){ unsigned int value(-1); for(auto c : candidates){ if(value == -1){ value = c.second; } else { if(value != c.second){ return false; } } } return true; } string getLowestCandidate(map<string, unsigned int> candidates){ string lowest_candidate; unsigned int min(numeric_limits<int>::max()); for(auto c : candidates){ if(c.second < min){ min = c.second; lowest_candidate = c.first; } } return lowest_candidate; } string getHighestCandidate(map<string, unsigned int> candidates){ string highest_candidate; unsigned int max(0); for(auto c : candidates){ if(c.second > max){ max = c.second; highest_candidate = c.first; } } return highest_candidate; } <|endoftext|>
<commit_before>#include "request.h" #include <cstring> namespace REST { const size_t Request::BUFFER_SIZE = 4096; Request::Request(int client, struct sockaddr_storage client_addr) : handle(client), addr(client_addr) { static Json::Reader json_reader; std::string line; bool is_header = true; char buffer[BUFFER_SIZE]; // receive data from client recv(client, buffer, BUFFER_SIZE, 0); // parse each line std::istringstream request_stream(buffer); while (std::getline(request_stream, line)) { // if method is undefined, assumie its first line if (method == Method::UNDEFINED) { // so parse header parse_header(line); continue; } // next lines are headers, strip them line.erase(line.find_last_not_of(" \n\r\t")+1); // if line is empty, then content should follow if (line.size() == 0) { is_header = false; break; } // extract name and value from header size_t colon; std::string name = line.substr(0, colon = line.find(":")); std::string value = line.substr(colon+1); value.erase(0, value.find_first_not_of(" \n\r\t")); headers.insert(std::make_pair(name, value)); } // if has content if (!is_header) { // assume proper content length size_t content_length = header("Content-Length", 0); raw.reserve(content_length); if (content_length > 0) { // read whats left in header length = std::min(content_length, (size_t)(BUFFER_SIZE - request_stream.tellg())); raw = std::string(buffer, BUFFER_SIZE).substr(request_stream.tellg(), length); // receive some more while (length < content_length) { memset(buffer, 0, BUFFER_SIZE); size_t buffer_length = recv(client, buffer, BUFFER_SIZE, 0); raw += std::string(buffer, buffer_length); length += buffer_length; } } //std::cout << "content o "<<content_length<<" == "<<length<<" == " <<raw.size()<<"\n"; } // delete [] buffer; time = std::chrono::high_resolution_clock::now(); // if has some content if (!raw.empty()) { // try to parse it auto ct = headers.find("Content-Type"); if (ct != headers.end()) { if (ct->second == "application/x-www-form-urlencoded") { parse_query_string(raw); } else if (ct->second == "application/json" || ct->second == "text/json") { data = std::make_shared<Json::Value>(); json_reader.parse(raw, *data.get(), false); } } } } void Request::parse_header(std::string line) { if (line.find("GET") == 0) { method = Method::GET; } else if (line.find("HEAD") == 0) { method = Method::HEAD; } else if (line.find("POST") == 0) { method = Method::POST; } else if (line.find("PUT") == 0) { method = Method::PUT; } else if (line.find("PATCH") == 0) { method = Method::PATCH; } else if (line.find("DELETE") == 0) { method = Method::DELETE; } else if (line.find("TRACE") == 0) { method = Method::TRACE; } else if (line.find("CONNECT") == 0) { method = Method::CONNECT; } else if (line.find("OPTIONS") == 0) { method = Method::OPTIONS; } size_t path_start = line.find_first_of(" ")+1; size_t path_end = line.rfind("HTTP/1.")-1; path = line.substr(path_start, path_end - path_start); size_t path_query = path.find("?"); if (path_query != std::string::npos) { std::string query = path.substr(path_query+1, path.size() - path_query); parse_query_string(query); path.erase(path_query, query.size()+1); } } void Request::parse_query_string(std::string query) { query.erase(query.find_last_not_of(" \n\r\t")+1); std::istringstream query_stream(query); std::string pair; while (std::getline(query_stream, pair, '&')) { std::string name, value; size_t value_position = pair.find("="); name = pair.substr(0, value_position); if (value_position != std::string::npos) value = pair.substr(value_position+1, pair.size() - value_position-1); parameters[Utils::uri_decode(name)] = Utils::uri_decode(value); } } Request::~Request() { } } <commit_msg>working on copy<commit_after>#include "request.h" #include <cstring> namespace REST { const size_t Request::BUFFER_SIZE = 4096; Request::Request(int client, struct sockaddr_storage client_addr) : handle(client), addr(client_addr) { static Json::Reader json_reader; std::string line; bool is_header = true; char buffer[BUFFER_SIZE]; // receive data from client recv(client, buffer, BUFFER_SIZE, 0); // parse each line std::istringstream request_stream(buffer); while (std::getline(request_stream, line)) { // if method is undefined, assumie its first line if (method == Method::UNDEFINED) { // so parse header parse_header(line); continue; } // next lines are headers, strip them line.erase(line.find_last_not_of(" \n\r\t")+1); // if line is empty, then content should follow if (line.size() == 0) { is_header = false; break; } // extract name and value from header size_t colon; std::string name = line.substr(0, colon = line.find(":")); std::string value = line.substr(colon+1); value.erase(0, value.find_first_not_of(" \n\r\t")); headers.insert(std::make_pair(name, value)); } // if has content if (!is_header) { // assume proper content length size_t content_length = header("Content-Length", 0); raw.reserve(content_length); if (content_length > 0) { // read whats left in header length = std::min(content_length, (size_t)(BUFFER_SIZE - request_stream.tellg())); raw = std::string(buffer, BUFFER_SIZE).substr(request_stream.tellg(), length); // receive some more while (length < content_length) { memset(buffer, 0, BUFFER_SIZE); size_t buffer_length = recv(client, buffer, BUFFER_SIZE, 0); raw += std::string(buffer, buffer_length); length += buffer_length; } } //std::cout << "content o "<<content_length<<" == "<<length<<" == " <<raw.size()<<"\n"; } // delete [] buffer; time = std::chrono::high_resolution_clock::now(); // if has some content if (!raw.empty()) { // try to parse it auto ct = headers.find("Content-Type"); if (ct != headers.end()) { if (ct->second == "application/x-www-form-urlencoded") { parse_query_string(raw); } else if (ct->second == "application/json" || ct->second == "text/json") { data = std::make_shared<Json::Value>(); std::string raw_copy(raw); json_reader.parse(raw_copy, *data.get(), false); } } } } void Request::parse_header(std::string line) { if (line.find("GET") == 0) { method = Method::GET; } else if (line.find("HEAD") == 0) { method = Method::HEAD; } else if (line.find("POST") == 0) { method = Method::POST; } else if (line.find("PUT") == 0) { method = Method::PUT; } else if (line.find("PATCH") == 0) { method = Method::PATCH; } else if (line.find("DELETE") == 0) { method = Method::DELETE; } else if (line.find("TRACE") == 0) { method = Method::TRACE; } else if (line.find("CONNECT") == 0) { method = Method::CONNECT; } else if (line.find("OPTIONS") == 0) { method = Method::OPTIONS; } size_t path_start = line.find_first_of(" ")+1; size_t path_end = line.rfind("HTTP/1.")-1; path = line.substr(path_start, path_end - path_start); size_t path_query = path.find("?"); if (path_query != std::string::npos) { std::string query = path.substr(path_query+1, path.size() - path_query); parse_query_string(query); path.erase(path_query, query.size()+1); } } void Request::parse_query_string(std::string query) { query.erase(query.find_last_not_of(" \n\r\t")+1); std::istringstream query_stream(query); std::string pair; while (std::getline(query_stream, pair, '&')) { std::string name, value; size_t value_position = pair.find("="); name = pair.substr(0, value_position); if (value_position != std::string::npos) value = pair.substr(value_position+1, pair.size() - value_position-1); parameters[Utils::uri_decode(name)] = Utils::uri_decode(value); } } Request::~Request() { } } <|endoftext|>
<commit_before>#include <errno.h> #include <iostream> #include <string> using namespace std; #include "config.h" #include <openssl/rand.h> #include "common/common_init.h" #include "common/base64.h" #include "rgw_user.h" #include "rgw_access.h" #include "rgw_acl.h" #define SECRET_KEY_LEN 40 #define PUBLIC_ID_LEN 20 void usage() { cerr << "usage: rgw_admin <--user-gen | --user-modify | --read-policy | --list-buckets > [options...]" << std::endl; cerr << "options:" << std::endl; cerr << " --uid=<id>" << std::endl; cerr << " --key=<key>" << std::endl; cerr << " --email=<email>" << std::endl; cerr << " --display-name=<name>" << std::endl; cerr << " --bucket=<bucket>" << std::endl; cerr << " --object=<object>" << std::endl; generic_usage(); } int gen_rand_base64(char *dest, int size) /* size should be the required string size + 1 */ { unsigned char buf[size]; char tmp_dest[size + 4]; /* so that there's space for the extra '=' characters, and some */ int ret = RAND_bytes(buf, sizeof(buf)); if (!ret) { cerr << "RAND_bytes failed, entropy problem?" << std::endl; return -1; } ret = encode_base64((const char *)buf, ((size - 1) * 3 + 4 - 1) / 4, tmp_dest, sizeof(tmp_dest)); if (ret < 0) { cerr << "encode_base64 failed" << std::endl; return -1; } memcpy(dest, tmp_dest, size); dest[size] = '\0'; return 0; } static const char alphanum_table[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int gen_rand_alphanumeric(char *dest, int size) /* size should be the required string size + 1 */ { int ret = RAND_bytes((unsigned char *)dest, size); if (!ret) { cerr << "RAND_bytes failed, entropy problem?" << std::endl; return -1; } int i; for (i=0; i<size - 1; i++) { int pos = (unsigned)dest[i]; dest[i] = alphanum_table[pos % (sizeof(alphanum_table) - 1)]; } dest[i] = '\0'; return 0; } #if 0 static int rebuild_policy(RGWAccessControlPolicy& src, RGWAccessControlPolicy& dest) { ACLOwner *owner = (ACLOwner *)src.find_first("Owner"); if (!owner) return -EINVAL; RGWUserInfo owner_info; if (rgw_get_user_info(owner->get_id(), owner_info) < 0) { cerr << "owner info does not exist" << std::endl; return -EINVAL; } ACLOwner& new_owner = dest.get_owner(); new_owner.set_id(owner->get_id()); new_owner.set_name(owner_info.display_name); RGWAccessControlList& src_acl = src.get_acl(); RGWAccessControlList& acl = dest.get_acl(); XMLObjIter iter = src_acl.find("Grant"); ACLGrant *src_grant = (ACLGrant *)iter.get_next(); while (src_grant) { string id = src_grant->get_id(); RGWUserInfo grant_user; if (rgw_get_user_info(id, grant_user) < 0) { cerr << "grant user does not exist:" << id << std::endl; } else { ACLGrant new_grant; ACLPermission& perm = src_grant->get_permission(); new_grant.set_canon(id, grant_user.display_name, perm.get_permissions()); cerr << "new grant: " << id << ":" << grant_user.display_name << std::endl; acl.add_grant(&new_grant); } src_grant = (ACLGrant *)iter.get_next(); } return 0; } #endif int main(int argc, char **argv) { DEFINE_CONF_VARS(usage); vector<const char*> args; argv_to_vec(argc, (const char **)argv, args); env_to_vec(args); common_init(args, "rgw", true, true); const char *user_id = 0; const char *secret_key = 0; const char *user_email = 0; const char *display_name = 0; const char *bucket = 0; const char *object = 0; bool gen_user = false; bool mod_user = false; bool read_policy = false; bool list_buckets = false; int actions = 0 ; RGWUserInfo info; RGWAccess *store; if (g_conf.clock_tare) g_clock.tare(); FOR_EACH_ARG(args) { if (CONF_ARG_EQ("user-gen", 'g')) { gen_user = true; } else if (CONF_ARG_EQ("user-modify", 'm')) { mod_user = true; } else if (CONF_ARG_EQ("read-policy", 'p')) { read_policy = true; } else if (CONF_ARG_EQ("list-buckets", 'l')) { list_buckets = true; } else if (CONF_ARG_EQ("uid", 'i')) { CONF_SAFE_SET_ARG_VAL(&user_id, OPT_STR); } else if (CONF_ARG_EQ("key", 'k')) { CONF_SAFE_SET_ARG_VAL(&secret_key, OPT_STR); } else if (CONF_ARG_EQ("email", 'e')) { CONF_SAFE_SET_ARG_VAL(&user_email, OPT_STR); } else if (CONF_ARG_EQ("display-name", 'n')) { CONF_SAFE_SET_ARG_VAL(&display_name, OPT_STR); } else if (CONF_ARG_EQ("bucket", 'b')) { CONF_SAFE_SET_ARG_VAL(&bucket, OPT_STR); } else if (CONF_ARG_EQ("object", 'o')) { CONF_SAFE_SET_ARG_VAL(&object, OPT_STR); } else { cerr << "unrecognized arg " << args[i] << std::endl; ARGS_USAGE(); } } store = RGWAccess::init_storage_provider("rados", argc, argv); if (!store) { cerr << "couldn't init storage provider" << std::endl; } if (mod_user) { actions++; if (!user_id) { cerr << "user_id was not specified, aborting" << std::endl; return 0; } string user_id_str = user_id; if (rgw_get_user_info(user_id_str, info) < 0) { cerr << "error reading user info, aborting" << std::endl; exit(1); } } if (gen_user) { actions++; char secret_key_buf[SECRET_KEY_LEN + 1]; char public_id_buf[PUBLIC_ID_LEN + 1]; int ret; if (!display_name) { cerr << "display name was not specified, aborting" << std::endl; return 0; } if (!secret_key) { ret = gen_rand_base64(secret_key_buf, sizeof(secret_key_buf)); if (ret < 0) { cerr << "aborting" << std::endl; exit(1); } secret_key = secret_key_buf; } if (!user_id) { ret = gen_rand_alphanumeric(public_id_buf, sizeof(public_id_buf)); if (ret < 0) { cerr << "aborting" << std::endl; exit(1); } user_id = public_id_buf; } } if (gen_user || mod_user) { if (user_id) info.user_id = user_id; if (secret_key) info.secret_key = secret_key; if (display_name) info.display_name = display_name; if (user_email) info.user_email = user_email; int err; if ((err = rgw_store_user_info(info)) < 0) { cerr << "error storing user info" << strerror(-err) << std::endl; } else { cout << "User ID: " << info.user_id << std::endl; cout << "Secret Key: " << info.secret_key << std::endl; cout << "Display Name: " << info.display_name << std::endl; } } if (read_policy) { actions++; bufferlist bl; if (!bucket) bucket = ""; if (!object) object = ""; string bucket_str(bucket); string object_str(object); int ret = store->get_attr(bucket_str, object_str, RGW_ATTR_ACL, bl); RGWAccessControlPolicy policy; if (ret >= 0) { bufferlist::iterator iter = bl.begin(); policy.decode(iter); policy.to_xml(cout); cout << std::endl; } } if (list_buckets) { actions++; string id; RGWAccessHandle handle; if (user_id) { RGWUserBuckets buckets; if (rgw_get_user_buckets(user_id, buckets) < 0) { cout << "could not get buckets for uid " << user_id << std::endl; } else { cout << "listing buckets for uid " << user_id << std::endl; map<string, RGWObjEnt>& m = buckets.get_buckets(); map<string, RGWObjEnt>::iterator iter; for (iter = m.begin(); iter != m.end(); ++iter) { RGWObjEnt obj = iter->second; cout << obj.name << std::endl; } } } else { if (store->list_buckets_init(id, &handle) < 0) { cout << "list-buckets: no entries found" << std::endl; } else { RGWObjEnt obj; cout << "listing all buckets" << std::endl; while (store->list_buckets_next(id, obj, &handle) >= 0) { cout << obj.name << std::endl; } } } } if (!actions) ARGS_USAGE(); return 0; } <commit_msg>rgw: set auid if specified at creation<commit_after>#include <errno.h> #include <iostream> #include <string> using namespace std; #include "config.h" #include <openssl/rand.h> #include "common/common_init.h" #include "common/base64.h" #include "rgw_user.h" #include "rgw_access.h" #include "rgw_acl.h" #define SECRET_KEY_LEN 40 #define PUBLIC_ID_LEN 20 void usage() { cerr << "usage: rgw_admin <--user-gen | --user-modify | --read-policy | --list-buckets > [options...]" << std::endl; cerr << "options:" << std::endl; cerr << " --uid=<id> (S3 uid)" << std::endl; cerr << " --auth_uid=<auid> (librados uid)" << std::endl; cerr << " --key=<key>" << std::endl; cerr << " --email=<email>" << std::endl; cerr << " --display-name=<name>" << std::endl; cerr << " --bucket=<bucket>" << std::endl; cerr << " --object=<object>" << std::endl; generic_usage(); } int gen_rand_base64(char *dest, int size) /* size should be the required string size + 1 */ { unsigned char buf[size]; char tmp_dest[size + 4]; /* so that there's space for the extra '=' characters, and some */ int ret = RAND_bytes(buf, sizeof(buf)); if (!ret) { cerr << "RAND_bytes failed, entropy problem?" << std::endl; return -1; } ret = encode_base64((const char *)buf, ((size - 1) * 3 + 4 - 1) / 4, tmp_dest, sizeof(tmp_dest)); if (ret < 0) { cerr << "encode_base64 failed" << std::endl; return -1; } memcpy(dest, tmp_dest, size); dest[size] = '\0'; return 0; } static const char alphanum_table[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int gen_rand_alphanumeric(char *dest, int size) /* size should be the required string size + 1 */ { int ret = RAND_bytes((unsigned char *)dest, size); if (!ret) { cerr << "RAND_bytes failed, entropy problem?" << std::endl; return -1; } int i; for (i=0; i<size - 1; i++) { int pos = (unsigned)dest[i]; dest[i] = alphanum_table[pos % (sizeof(alphanum_table) - 1)]; } dest[i] = '\0'; return 0; } #if 0 static int rebuild_policy(RGWAccessControlPolicy& src, RGWAccessControlPolicy& dest) { ACLOwner *owner = (ACLOwner *)src.find_first("Owner"); if (!owner) return -EINVAL; RGWUserInfo owner_info; if (rgw_get_user_info(owner->get_id(), owner_info) < 0) { cerr << "owner info does not exist" << std::endl; return -EINVAL; } ACLOwner& new_owner = dest.get_owner(); new_owner.set_id(owner->get_id()); new_owner.set_name(owner_info.display_name); RGWAccessControlList& src_acl = src.get_acl(); RGWAccessControlList& acl = dest.get_acl(); XMLObjIter iter = src_acl.find("Grant"); ACLGrant *src_grant = (ACLGrant *)iter.get_next(); while (src_grant) { string id = src_grant->get_id(); RGWUserInfo grant_user; if (rgw_get_user_info(id, grant_user) < 0) { cerr << "grant user does not exist:" << id << std::endl; } else { ACLGrant new_grant; ACLPermission& perm = src_grant->get_permission(); new_grant.set_canon(id, grant_user.display_name, perm.get_permissions()); cerr << "new grant: " << id << ":" << grant_user.display_name << std::endl; acl.add_grant(&new_grant); } src_grant = (ACLGrant *)iter.get_next(); } return 0; } #endif int main(int argc, char **argv) { DEFINE_CONF_VARS(usage); vector<const char*> args; argv_to_vec(argc, (const char **)argv, args); env_to_vec(args); common_init(args, "rgw", true, true); const char *user_id = 0; const char *secret_key = 0; const char *user_email = 0; const char *display_name = 0; const char *bucket = 0; const char *object = 0; bool gen_user = false; bool mod_user = false; bool read_policy = false; bool list_buckets = false; int actions = 0 ; __u64 auid = 0; RGWUserInfo info; RGWAccess *store; if (g_conf.clock_tare) g_clock.tare(); FOR_EACH_ARG(args) { if (CONF_ARG_EQ("user-gen", 'g')) { gen_user = true; } else if (CONF_ARG_EQ("user-modify", 'm')) { mod_user = true; } else if (CONF_ARG_EQ("read-policy", 'p')) { read_policy = true; } else if (CONF_ARG_EQ("list-buckets", 'l')) { list_buckets = true; } else if (CONF_ARG_EQ("uid", 'i')) { CONF_SAFE_SET_ARG_VAL(&user_id, OPT_STR); } else if (CONF_ARG_EQ("key", 'k')) { CONF_SAFE_SET_ARG_VAL(&secret_key, OPT_STR); } else if (CONF_ARG_EQ("email", 'e')) { CONF_SAFE_SET_ARG_VAL(&user_email, OPT_STR); } else if (CONF_ARG_EQ("display-name", 'n')) { CONF_SAFE_SET_ARG_VAL(&display_name, OPT_STR); } else if (CONF_ARG_EQ("bucket", 'b')) { CONF_SAFE_SET_ARG_VAL(&bucket, OPT_STR); } else if (CONF_ARG_EQ("object", 'o')) { CONF_SAFE_SET_ARG_VAL(&object, OPT_STR); } else if (CONF_ARG_EQ("auth_uid", 'a')) { CONF_SAFE_SET_ARG_VAL(&auid, OPT_LONGLONG); } else { cerr << "unrecognized arg " << args[i] << std::endl; ARGS_USAGE(); } } store = RGWAccess::init_storage_provider("rados", argc, argv); if (!store) { cerr << "couldn't init storage provider" << std::endl; } if (mod_user) { actions++; if (!user_id) { cerr << "user_id was not specified, aborting" << std::endl; return 0; } string user_id_str = user_id; if (rgw_get_user_info(user_id_str, info) < 0) { cerr << "error reading user info, aborting" << std::endl; exit(1); } } if (gen_user) { actions++; char secret_key_buf[SECRET_KEY_LEN + 1]; char public_id_buf[PUBLIC_ID_LEN + 1]; int ret; if (!display_name) { cerr << "display name was not specified, aborting" << std::endl; return 0; } if (!secret_key) { ret = gen_rand_base64(secret_key_buf, sizeof(secret_key_buf)); if (ret < 0) { cerr << "aborting" << std::endl; exit(1); } secret_key = secret_key_buf; } if (!user_id) { ret = gen_rand_alphanumeric(public_id_buf, sizeof(public_id_buf)); if (ret < 0) { cerr << "aborting" << std::endl; exit(1); } user_id = public_id_buf; } } if (gen_user || mod_user) { if (user_id) info.user_id = user_id; if (secret_key) info.secret_key = secret_key; if (display_name) info.display_name = display_name; if (user_email) info.user_email = user_email; if (auid) info.auid = auid; int err; if ((err = rgw_store_user_info(info)) < 0) { cerr << "error storing user info" << strerror(-err) << std::endl; } else { cout << "User ID: " << info.user_id << std::endl; cout << "Secret Key: " << info.secret_key << std::endl; cout << "Display Name: " << info.display_name << std::endl; } } if (read_policy) { actions++; bufferlist bl; if (!bucket) bucket = ""; if (!object) object = ""; string bucket_str(bucket); string object_str(object); int ret = store->get_attr(bucket_str, object_str, RGW_ATTR_ACL, bl); RGWAccessControlPolicy policy; if (ret >= 0) { bufferlist::iterator iter = bl.begin(); policy.decode(iter); policy.to_xml(cout); cout << std::endl; } } if (list_buckets) { actions++; string id; RGWAccessHandle handle; if (user_id) { RGWUserBuckets buckets; if (rgw_get_user_buckets(user_id, buckets) < 0) { cout << "could not get buckets for uid " << user_id << std::endl; } else { cout << "listing buckets for uid " << user_id << std::endl; map<string, RGWObjEnt>& m = buckets.get_buckets(); map<string, RGWObjEnt>::iterator iter; for (iter = m.begin(); iter != m.end(); ++iter) { RGWObjEnt obj = iter->second; cout << obj.name << std::endl; } } } else { if (store->list_buckets_init(id, &handle) < 0) { cout << "list-buckets: no entries found" << std::endl; } else { RGWObjEnt obj; cout << "listing all buckets" << std::endl; while (store->list_buckets_next(id, obj, &handle) >= 0) { cout << obj.name << std::endl; } } } } if (!actions) ARGS_USAGE(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2020 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "mutation_reader.hh" class test_reader_lifecycle_policy : public reader_lifecycle_policy , public enable_shared_from_this<test_reader_lifecycle_policy> { public: class operations_gate { public: class operation { gate* _g = nullptr; private: void leave() { if (_g) { _g->leave(); } } public: operation() = default; explicit operation(gate& g) : _g(&g) { _g->enter(); } operation(const operation&) = delete; operation(operation&& o) : _g(std::exchange(o._g, nullptr)) { } ~operation() { leave(); } operation& operator=(const operation&) = delete; operation& operator=(operation&& o) { leave(); _g = std::exchange(o._g, nullptr); return *this; } }; private: std::vector<gate> _gates; public: operations_gate() : _gates(smp::count) { } operation enter() { return operation(_gates[this_shard_id()]); } future<> close() { return parallel_for_each(boost::irange(smp::count), [this] (shard_id shard) { return smp::submit_to(shard, [this, shard] { return _gates[shard].close(); }); }); } }; private: using factory_function = std::function<flat_mutation_reader( schema_ptr, const dht::partition_range&, const query::partition_slice&, const io_priority_class&, tracing::trace_state_ptr, mutation_reader::forwarding)>; struct reader_context { std::unique_ptr<reader_concurrency_semaphore> semaphore; operations_gate::operation op; std::optional<reader_permit> permit; std::optional<future<reader_permit::resource_units>> wait_future; std::optional<const dht::partition_range> range; std::optional<const query::partition_slice> slice; reader_context() = default; reader_context(dht::partition_range range, query::partition_slice slice) : range(std::move(range)), slice(std::move(slice)) { } }; factory_function _factory_function; operations_gate& _operation_gate; std::vector<foreign_ptr<std::unique_ptr<reader_context>>> _contexts; std::vector<future<>> _destroy_futures; bool _evict_paused_readers = false; public: explicit test_reader_lifecycle_policy(factory_function f, operations_gate& g, bool evict_paused_readers = false) : _factory_function(std::move(f)) , _operation_gate(g) , _contexts(smp::count) , _evict_paused_readers(evict_paused_readers) { } virtual flat_mutation_reader create_reader( schema_ptr schema, const dht::partition_range& range, const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace_state, mutation_reader::forwarding fwd_mr) override { const auto shard = this_shard_id(); if (_contexts[shard]) { _contexts[shard]->range.emplace(range); _contexts[shard]->slice.emplace(slice); } else { _contexts[shard] = make_foreign(std::make_unique<reader_context>(range, slice)); } _contexts[shard]->op = _operation_gate.enter(); return _factory_function(std::move(schema), *_contexts[shard]->range, *_contexts[shard]->slice, pc, std::move(trace_state), fwd_mr); } virtual void destroy_reader(shard_id shard, future<stopped_reader> reader) noexcept override { // Move to the background, waited via _operation_gate (void)reader.then([shard, this] (stopped_reader&& reader) { return smp::submit_to(shard, [handle = std::move(reader.handle), ctx = std::move(_contexts[shard])] () mutable { ctx->semaphore->unregister_inactive_read(std::move(*handle)); ctx->semaphore->broken(std::make_exception_ptr(broken_semaphore{})); if (ctx->wait_future) { return ctx->wait_future->then_wrapped([ctx = std::move(ctx)] (future<reader_permit::resource_units> f) mutable { f.ignore_ready_future(); ctx->permit.reset(); // make sure it's destroyed before the semaphore }); } return make_ready_future<>(); }); }).finally([zis = shared_from_this()] {}); } virtual reader_concurrency_semaphore& semaphore() override { const auto shard = this_shard_id(); if (!_contexts[shard]) { _contexts[shard] = make_foreign(std::make_unique<reader_context>()); } else if (_contexts[shard]->semaphore) { return *_contexts[shard]->semaphore; } if (_evict_paused_readers) { _contexts[shard]->semaphore = std::make_unique<reader_concurrency_semaphore>(0, std::numeric_limits<ssize_t>::max(), format("reader_concurrency_semaphore @shard_id={}", shard)); _contexts[shard]->permit = _contexts[shard]->semaphore->make_permit(); // Add a waiter, so that all registered inactive reads are // immediately evicted. // We don't care about the returned future. _contexts[shard]->wait_future = _contexts[shard]->permit->wait_admission(1, db::no_timeout); } else { _contexts[shard]->semaphore = std::make_unique<reader_concurrency_semaphore>(reader_concurrency_semaphore::no_limits{}); } return *_contexts[shard]->semaphore; } }; <commit_msg>test/lib/reader_lifecycle_policy: don't destroy reader context eagerly<commit_after>/* * Copyright (C) 2020 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "mutation_reader.hh" class test_reader_lifecycle_policy : public reader_lifecycle_policy , public enable_shared_from_this<test_reader_lifecycle_policy> { public: class operations_gate { public: class operation { gate* _g = nullptr; private: void leave() { if (_g) { _g->leave(); } } public: operation() = default; explicit operation(gate& g) : _g(&g) { _g->enter(); } operation(const operation&) = delete; operation(operation&& o) : _g(std::exchange(o._g, nullptr)) { } ~operation() { leave(); } operation& operator=(const operation&) = delete; operation& operator=(operation&& o) { leave(); _g = std::exchange(o._g, nullptr); return *this; } }; private: std::vector<gate> _gates; public: operations_gate() : _gates(smp::count) { } operation enter() { return operation(_gates[this_shard_id()]); } future<> close() { return parallel_for_each(boost::irange(smp::count), [this] (shard_id shard) { return smp::submit_to(shard, [this, shard] { return _gates[shard].close(); }); }); } }; private: using factory_function = std::function<flat_mutation_reader( schema_ptr, const dht::partition_range&, const query::partition_slice&, const io_priority_class&, tracing::trace_state_ptr, mutation_reader::forwarding)>; struct reader_context { std::unique_ptr<reader_concurrency_semaphore> semaphore; operations_gate::operation op; std::optional<reader_permit> permit; std::optional<future<reader_permit::resource_units>> wait_future; std::optional<const dht::partition_range> range; std::optional<const query::partition_slice> slice; reader_context() = default; reader_context(dht::partition_range range, query::partition_slice slice) : range(std::move(range)), slice(std::move(slice)) { } }; factory_function _factory_function; operations_gate& _operation_gate; std::vector<foreign_ptr<std::unique_ptr<reader_context>>> _contexts; std::vector<future<>> _destroy_futures; bool _evict_paused_readers = false; public: explicit test_reader_lifecycle_policy(factory_function f, operations_gate& g, bool evict_paused_readers = false) : _factory_function(std::move(f)) , _operation_gate(g) , _contexts(smp::count) , _evict_paused_readers(evict_paused_readers) { } virtual flat_mutation_reader create_reader( schema_ptr schema, const dht::partition_range& range, const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace_state, mutation_reader::forwarding fwd_mr) override { const auto shard = this_shard_id(); if (_contexts[shard]) { _contexts[shard]->range.emplace(range); _contexts[shard]->slice.emplace(slice); } else { _contexts[shard] = make_foreign(std::make_unique<reader_context>(range, slice)); } _contexts[shard]->op = _operation_gate.enter(); return _factory_function(std::move(schema), *_contexts[shard]->range, *_contexts[shard]->slice, pc, std::move(trace_state), fwd_mr); } virtual void destroy_reader(shard_id shard, future<stopped_reader> reader) noexcept override { // Move to the background, waited via _operation_gate (void)reader.then([shard, this] (stopped_reader&& reader) { return smp::submit_to(shard, [handle = std::move(reader.handle), ctx = &*_contexts[shard]] () mutable { ctx->semaphore->unregister_inactive_read(std::move(*handle)); ctx->semaphore->broken(std::make_exception_ptr(broken_semaphore{})); if (ctx->wait_future) { return ctx->wait_future->then_wrapped([ctx = std::move(ctx)] (future<reader_permit::resource_units> f) mutable { f.ignore_ready_future(); ctx->permit.reset(); // make sure it's destroyed before the semaphore }); } return make_ready_future<>(); }); }).finally([zis = shared_from_this()] {}); } virtual reader_concurrency_semaphore& semaphore() override { const auto shard = this_shard_id(); if (!_contexts[shard]) { _contexts[shard] = make_foreign(std::make_unique<reader_context>()); } else if (_contexts[shard]->semaphore) { return *_contexts[shard]->semaphore; } if (_evict_paused_readers) { _contexts[shard]->semaphore = std::make_unique<reader_concurrency_semaphore>(0, std::numeric_limits<ssize_t>::max(), format("reader_concurrency_semaphore @shard_id={}", shard)); _contexts[shard]->permit = _contexts[shard]->semaphore->make_permit(); // Add a waiter, so that all registered inactive reads are // immediately evicted. // We don't care about the returned future. _contexts[shard]->wait_future = _contexts[shard]->permit->wait_admission(1, db::no_timeout); } else { _contexts[shard]->semaphore = std::make_unique<reader_concurrency_semaphore>(reader_concurrency_semaphore::no_limits{}); } return *_contexts[shard]->semaphore; } }; <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include <node.h> #include <parser.h> #include <misc/fatal.h> using namespace ydsh; static std::vector<std::string> tokenize(const char *str) { std::vector<std::string> tokens; std::string tokenBuf; for(unsigned int i = 0; str[i] != '\0'; i++) { char ch = str[i]; switch(ch) { case '(': case ')': { if(!tokenBuf.empty()) { tokens.push_back(std::move(tokenBuf)); } tokenBuf += ch; tokens.push_back(std::move(tokenBuf)); break; } case ' ': case '\t': { if(!tokenBuf.empty()) { tokens.push_back(std::move(tokenBuf)); } break; } default: tokenBuf += ch; break; } } if(!tokenBuf.empty()) { tokens.push_back(std::move(tokenBuf)); } return tokens; } class PrettyPrinter : public BaseVisitor { private: std::vector<std::string> out; public: PrettyPrinter() = default; ~PrettyPrinter() = default; std::vector<std::string> operator()(RootNode &rootNode) { this->visitRootNode(rootNode); return std::move(this->out); } void append(const char *str) { this->out.push_back(str); } void append(const std::string &str) { this->out.push_back(str); } void open() { this->append("("); } void close() { this->append(")"); } void visitDefault(Node &) override { fatal("unsupported\n"); } void visitNumberNode(NumberNode &node) override { this->append(std::to_string(node.getIntValue())); } void visitTypeOpNode(TypeOpNode &node) override { this->open(); this->visit(*node.getExprNode()); this->append(node.isCastOp() ? "as" : "is"); this->append(dynamic_cast<BaseTypeNode *>(node.getTargetTypeNode())->getTokenText()); //FIXME: this->close(); } void visitBinaryOpNode(BinaryOpNode &node) override { this->open(); this->visit(*node.getLeftNode()); this->append(TO_NAME(node.getOp())); this->visit(*node.getRightNode()); this->close(); } void visitIfNode(IfNode &node) override { this->open(); this->visit(*node.getCondNode()); this->append("?"); this->visit(*node.getThenNode()); this->append(":"); this->visit(*node.getElseNode()); this->close(); } void visitAssignNode(AssignNode &node) override { this->open(); this->visit(*node.getLeftNode()); this->append("="); this->visit(*node.getRightNode()); this->close(); } void visitRootNode(RootNode &node) override { if(node.getNodes().size() != 1) { fatal("must be 1\n"); } this->visit(*node.getNodes().front()); } }; class PrecedenceTest : public ::testing::Test { public: PrecedenceTest() = default; virtual ~PrecedenceTest() = default; virtual void SetUp() { } virtual void TearDown() { } virtual void equalsTokens(const std::vector<std::string> &expected, const std::vector<std::string> &actual) { SCOPED_TRACE(""); // check size unsigned int size = expected.size(); ASSERT_EQ(size, actual.size()); // check each for(unsigned int i = 0; i < size; i++) { ASSERT_EQ(expected[i], actual[i]); } } virtual void equals(const char *expected, const char *input) { SCOPED_TRACE(""); ASSERT_TRUE(expected != nullptr); ASSERT_TRUE(input != nullptr); // parse Lexer lexer("(string)", input); Parser parser(lexer); auto rootNode = parser(); ASSERT_FALSE(parser.hasError()); std::vector<std::string> actualTokens = PrettyPrinter()(*rootNode); std::vector<std::string> expectedTokens = tokenize(expected); this->equalsTokens(expectedTokens, actualTokens); } }; TEST_F(PrecedenceTest, base1) { ASSERT_NO_FATAL_FAILURE(this->equals("1", "1")); } TEST_F(PrecedenceTest, base2) { ASSERT_NO_FATAL_FAILURE(this->equals(" 1 ", "(1)")); } TEST_F(PrecedenceTest, base3) { ASSERT_NO_FATAL_FAILURE(this->equals("(1 + 2)", "1+2")); } TEST_F(PrecedenceTest, case1) { ASSERT_NO_FATAL_FAILURE(this->equals("((1 as Int) is Int)", "1 as Int is Int")); } TEST_F(PrecedenceTest, case2) { ASSERT_NO_FATAL_FAILURE(this->equals("((1 is Int) as Int)", "1 is Int as Int")); } TEST_F(PrecedenceTest, case3) { ASSERT_NO_FATAL_FAILURE(this->equals("(12 / (23 as Int))", "12 / 23 as Int")); } TEST_F(PrecedenceTest, case4) { ASSERT_NO_FATAL_FAILURE(this->equals("(((1 / 2) * 3) % 4)", "1 / 2 * 3 % 4")); } TEST_F(PrecedenceTest, case5) { ASSERT_NO_FATAL_FAILURE(this->equals("((1 + (2 * 3)) - 4)", "1 + 2 * 3 - 4")); } TEST_F(PrecedenceTest, case6) { ASSERT_NO_FATAL_FAILURE(this->equals("((1 and 2) or (3 xor (4 + 3)))", "1 and 2 or 3 xor 4 + 3")); } TEST_F(PrecedenceTest, case7) { ASSERT_NO_FATAL_FAILURE( this->equals("((((((((1 < 2) > 3) == 4) >= 5) !~ 6) <= 7) != 8) =~ 9)", "1 < 2 > 3 == 4 >= 5 !~ 6 <= 7 != 8 =~ 9")); } TEST_F(PrecedenceTest, case8) { ASSERT_NO_FATAL_FAILURE(this->equals("(1 = (((2 == 3) && (4 + 5)) || 6))", "1 = 2 == 3 && 4 + 5 || 6")); } TEST_F(PrecedenceTest, case9) { ASSERT_NO_FATAL_FAILURE( this->equals("((1 == 2) ? ((3 > 4) ? (5 + 6) : (7 xor 8)) : (9 && 10))", "1 == 2 ? 3 > 4 ? 5 + 6 : 7 xor 8 : 9 && 10")); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>update operator precedence test case, close #283<commit_after>#include "gtest/gtest.h" #include <node.h> #include <parser.h> #include <misc/fatal.h> using namespace ydsh; static std::vector<std::string> tokenize(const char *str) { std::vector<std::string> tokens; std::string tokenBuf; for(unsigned int i = 0; str[i] != '\0'; i++) { char ch = str[i]; switch(ch) { case '(': case ')': { if(!tokenBuf.empty()) { tokens.push_back(std::move(tokenBuf)); } tokenBuf += ch; tokens.push_back(std::move(tokenBuf)); break; } case ' ': case '\t': { if(!tokenBuf.empty()) { tokens.push_back(std::move(tokenBuf)); } break; } default: tokenBuf += ch; break; } } if(!tokenBuf.empty()) { tokens.push_back(std::move(tokenBuf)); } return tokens; } class PrettyPrinter : public BaseVisitor { private: std::vector<std::string> out; public: PrettyPrinter() = default; ~PrettyPrinter() = default; std::vector<std::string> operator()(RootNode &rootNode) { this->visitRootNode(rootNode); return std::move(this->out); } void append(const char *str) { this->out.push_back(str); } void append(const std::string &str) { this->out.push_back(str); } void open() { this->append("("); } void close() { this->append(")"); } void visitDefault(Node &) override { fatal("unsupported\n"); } void visitNumberNode(NumberNode &node) override { this->append(std::to_string(node.getIntValue())); } void visitTypeOpNode(TypeOpNode &node) override { this->open(); this->visit(*node.getExprNode()); this->append(node.isCastOp() ? "as" : "is"); this->append(dynamic_cast<BaseTypeNode *>(node.getTargetTypeNode())->getTokenText()); //FIXME: this->close(); } void visitBinaryOpNode(BinaryOpNode &node) override { this->open(); this->visit(*node.getLeftNode()); this->append(TO_NAME(node.getOp())); this->visit(*node.getRightNode()); this->close(); } void visitIfNode(IfNode &node) override { this->open(); this->visit(*node.getCondNode()); this->append("?"); this->visit(*node.getThenNode()); this->append(":"); this->visit(*node.getElseNode()); this->close(); } void visitAssignNode(AssignNode &node) override { this->open(); this->visit(*node.getLeftNode()); this->append("="); this->visit(*node.getRightNode()); this->close(); } void visitJumpNode(JumpNode &node) override { this->open(); assert(node.getOpKind() == JumpNode::THROW); this->append("throw"); this->visit(*node.getExprNode()); this->close(); } void visitWithNode(WithNode &node) override { this->open(); this->visit(*node.getExprNode()); this->append("with"); this->visit(*node.getRedirNodes().back()); this->close(); } void visitRedirNode(RedirNode &node) override { this->append(TO_NAME(node.getRedirectOP())); this->visit(*node.getTargetNode()); } void visitCmdArgNode(CmdArgNode &node) override { this->visit(*node.getSegmentNodes().back()); } void visitStringNode(StringNode &node) override { this->append(node.getValue()); } void visitPipelineNode(PipelineNode &node) override { this->open(); for(unsigned int i = 0; i < node.getNodes().size(); i++) { if(i > 0) { this->append("|"); } this->visit(*node.getNodes()[i]); } this->close(); } void visitRootNode(RootNode &node) override { if(node.getNodes().size() != 1) { fatal("must be 1\n"); } this->visit(*node.getNodes().front()); } }; class PrecedenceTest : public ::testing::Test { public: PrecedenceTest() = default; virtual ~PrecedenceTest() = default; virtual void SetUp() { } virtual void TearDown() { } virtual void equalsTokens(const std::vector<std::string> &expected, const std::vector<std::string> &actual) { SCOPED_TRACE(""); // check size unsigned int size = expected.size(); ASSERT_EQ(size, actual.size()); // check each for(unsigned int i = 0; i < size; i++) { ASSERT_EQ(expected[i], actual[i]); } } virtual void equals(const char *expected, const char *input) { SCOPED_TRACE(""); ASSERT_TRUE(expected != nullptr); ASSERT_TRUE(input != nullptr); // parse Lexer lexer("(string)", input); Parser parser(lexer); auto rootNode = parser(); ASSERT_FALSE(parser.hasError()); std::vector<std::string> actualTokens = PrettyPrinter()(*rootNode); std::vector<std::string> expectedTokens = tokenize(expected); this->equalsTokens(expectedTokens, actualTokens); } }; TEST_F(PrecedenceTest, base1) { ASSERT_NO_FATAL_FAILURE(this->equals("1", "1")); } TEST_F(PrecedenceTest, base2) { ASSERT_NO_FATAL_FAILURE(this->equals(" 1 ", "(1)")); } TEST_F(PrecedenceTest, base3) { ASSERT_NO_FATAL_FAILURE(this->equals("(1 + 2)", "1+2")); } TEST_F(PrecedenceTest, case1) { ASSERT_NO_FATAL_FAILURE(this->equals("((1 as Int) is Int)", "1 as Int is Int")); } TEST_F(PrecedenceTest, case2) { ASSERT_NO_FATAL_FAILURE(this->equals("((1 is Int) as Int)", "1 is Int as Int")); } TEST_F(PrecedenceTest, case3) { ASSERT_NO_FATAL_FAILURE(this->equals("(12 / (23 as Int))", "12 / 23 as Int")); } TEST_F(PrecedenceTest, case4) { ASSERT_NO_FATAL_FAILURE(this->equals("(((1 / 2) * 3) % 4)", "1 / 2 * 3 % 4")); } TEST_F(PrecedenceTest, case5) { ASSERT_NO_FATAL_FAILURE(this->equals("((1 + (2 * 3)) - 4)", "1 + 2 * 3 - 4")); } TEST_F(PrecedenceTest, case6) { ASSERT_NO_FATAL_FAILURE(this->equals("((1 and 2) or (3 xor (4 + 3)))", "1 and 2 or 3 xor 4 + 3")); } TEST_F(PrecedenceTest, case7) { ASSERT_NO_FATAL_FAILURE( this->equals("((((((((1 < 2) > 3) == 4) >= 5) !~ 6) <= 7) != 8) =~ 9)", "1 < 2 > 3 == 4 >= 5 !~ 6 <= 7 != 8 =~ 9")); } TEST_F(PrecedenceTest, case8) { ASSERT_NO_FATAL_FAILURE(this->equals("(1 = (((2 == 3) && (4 + 5)) || 6))", "1 = 2 == 3 && 4 + 5 || 6")); } TEST_F(PrecedenceTest, case9) { ASSERT_NO_FATAL_FAILURE( this->equals("((1 == 2) ? ((3 > 4) ? (5 + 6) : (7 xor 8)) : (9 && 10))", "1 == 2 ? 3 > 4 ? 5 + 6 : 7 xor 8 : 9 && 10")); } TEST_F(PrecedenceTest, case10) { ASSERT_NO_FATAL_FAILURE(this->equals("(55 < ((65 or 75) ?? 78))", "55 < 65 or 75 ?? 78")); } TEST_F(PrecedenceTest, case11) { ASSERT_NO_FATAL_FAILURE(this->equals("(((throw 45) + 45) && 54)", "throw 45 + 45 && 54")); } TEST_F(PrecedenceTest, case12) { ASSERT_NO_FATAL_FAILURE(this->equals("(34 || ((45 | (56 and 67)) && 78))", "34 || 45 | 56 and 67 && 78")); } TEST_F(PrecedenceTest, case13) { ASSERT_NO_FATAL_FAILURE(this->equals("(45 | ((56 as Int) with 2> 67))", "45 | 56 as Int with 2> 67")); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include <tamer/tamer.hh> #include <signal.h> #include <errno.h> #include <stdio.h> #include <fcntl.h> namespace tamer { volatile sig_atomic_t driver::sig_any_active; int driver::sig_pipe[2] = { -1, -1 }; namespace { volatile sig_atomic_t sig_active[NSIG]; volatile int sig_installing = -1; event<> sig_handlers[NSIG]; class sigcancel_rendezvous : public rendezvous<> { public: sigcancel_rendezvous() { } inline void add(tamerpriv::simple_event *e) throw () { _nwaiting++; e->initialize(this, sig_installing); } void complete(uintptr_t rid) { if ((int) rid != sig_installing) { struct sigaction sa; sa.sa_handler = SIG_DFL; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESETHAND; sigaction(rid, &sa, 0); } rendezvous<>::complete(rid); } }; sigcancel_rendezvous sigcancelr; } extern "C" { static void tame_signal_handler(int signal) { int save_errno = errno; driver::sig_any_active = sig_active[signal] = 1; // ensure select wakes up write(driver::sig_pipe[1], "", 1); // block signal until we trigger the event, giving the unblocked // rendezvous a chance to maybe install a different handler sigset_t sigset; sigemptyset(&sigset); sigaddset(&sigset, signal); sigprocmask(SIG_BLOCK, &sigset, NULL); errno = save_errno; } } void driver::at_signal(int signal, const event<> &trigger) { assert(signal >= 0 && signal < NSIG); if (sig_pipe[0] < 0) { pipe(sig_pipe); fcntl(sig_pipe[0], F_SETFL, O_NONBLOCK); fcntl(sig_pipe[0], F_SETFD, FD_CLOEXEC); fcntl(sig_pipe[1], F_SETFD, FD_CLOEXEC); } if (!trigger) // special case forces creation of signal pipe return; if (sig_handlers[signal]) sig_handlers[signal] = distribute(sig_handlers[signal], trigger); else { sig_installing = signal; sig_handlers[signal] = trigger; sig_handlers[signal].at_trigger(make_event(sigcancelr)); struct sigaction sa; sa.sa_handler = tame_signal_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESETHAND; sigaction(signal, &sa, 0); sig_installing = -1; } } void driver::dispatch_signals() { sig_any_active = 0; sigset_t sigs_unblock; sigemptyset(&sigs_unblock); // kill crap data written to pipe char crap[64]; while (read(sig_pipe[0], crap, 64) > 0) /* do nothing */; // check signals for (int sig = 0; sig < NSIG; sig++) if (sig_active[sig]) { sig_active[sig] = 0; sig_handlers[sig].trigger(); sigaddset(&sigs_unblock, sig); } // run closures activated by signals (plus maybe some others) while (tamerpriv::abstract_rendezvous *r = tamerpriv::abstract_rendezvous::unblocked) r->run(); // now that the signal responders have potentially reinstalled signal // handlers, unblock the signals sigprocmask(SIG_UNBLOCK, &sigs_unblock, 0); } } <commit_msg>a bit of signal nonsense, should test<commit_after>#include <tamer/tamer.hh> #include <signal.h> #include <errno.h> #include <stdio.h> #include <fcntl.h> namespace tamer { volatile sig_atomic_t driver::sig_any_active; int driver::sig_pipe[2] = { -1, -1 }; namespace { volatile sig_atomic_t sig_active[NSIG]; volatile int sig_installing = -1; event<> sig_handlers[NSIG]; class sigcancel_rendezvous : public rendezvous<> { public: sigcancel_rendezvous() { } inline void add(tamerpriv::simple_event *e) throw () { _nwaiting++; e->initialize(this, sig_installing); } void complete(uintptr_t rid) { if ((int) rid != sig_installing) { struct sigaction sa; sa.sa_handler = SIG_DFL; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESETHAND; sigaction(rid, &sa, 0); } rendezvous<>::complete(rid); } }; sigcancel_rendezvous sigcancelr; } extern "C" { static void tame_signal_handler(int signal) { int save_errno = errno; driver::sig_any_active = sig_active[signal] = 1; // ensure select wakes up write(driver::sig_pipe[1], "", 1); // block signal until we trigger the event, giving the unblocked // rendezvous a chance to maybe install a different handler sigset_t sigset; sigemptyset(&sigset); sigaddset(&sigset, signal); sigprocmask(SIG_BLOCK, &sigset, NULL); errno = save_errno; } } void driver::at_signal(int signal, const event<> &trigger) { assert(signal >= 0 && signal < NSIG); if (sig_pipe[0] < 0) { pipe(sig_pipe); fcntl(sig_pipe[0], F_SETFL, O_NONBLOCK); fcntl(sig_pipe[0], F_SETFD, FD_CLOEXEC); fcntl(sig_pipe[1], F_SETFD, FD_CLOEXEC); } if (!trigger) // special case forces creation of signal pipe return; if (sig_handlers[signal]) sig_handlers[signal] = distribute(sig_handlers[signal], trigger); else { int old_sig_installing = sig_installing; sig_installing = signal; sig_handlers[signal] = trigger; sig_handlers[signal].at_trigger(make_event(sigcancelr)); struct sigaction sa; sa.sa_handler = tame_signal_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESETHAND; sigaction(signal, &sa, 0); sig_installing = old_sig_installing; } } void driver::dispatch_signals() { sig_any_active = 0; sigset_t sigs_unblock; sigemptyset(&sigs_unblock); // kill crap data written to pipe char crap[64]; while (read(sig_pipe[0], crap, 64) > 0) /* do nothing */; // check signals for (int sig = 0; sig < NSIG; sig++) if (sig_active[sig]) { sig_active[sig] = 0; sig_installing = sig; sig_handlers[sig].trigger(); sig_installing = -1; sigaddset(&sigs_unblock, sig); } // run closures activated by signals (plus maybe some others) while (tamerpriv::abstract_rendezvous *r = tamerpriv::abstract_rendezvous::unblocked) r->run(); // now that the signal responders have potentially reinstalled signal // handlers, unblock the signals sigprocmask(SIG_UNBLOCK, &sigs_unblock, 0); } } <|endoftext|>
<commit_before>#ifndef UTIL_HH #define UTIL_HH #include <algorithm> #include <vector> #include <math.h> /** Common utility functions. */ namespace util { /** The square of the value. */ template <typename T> T sqr(T a) { return a * a; } /** Median of the values in a vector. * \note For odd number (2n + 1) of values, the n'th value is returned. */ template <typename T> T median(std::vector<T> v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } /** Absolute value. */ template <typename T> T abs(const T &value) { if (value < 0) return -value; return value; } /** Maximum of two values. */ template <typename T> T max(const T &a, const T &b) { if (a < b) return b; return a; } inline float log10add(float a, float b) { const float LOG10TOe = M_LN10; const float LOGeTO10 = 1.0 / M_LN10; a = a * LOG10TOe; b = b * LOG10TOe; float delta = a - b; if (delta > 64.0) { b += 64; delta = -delta; } return (b + log1pf(exp(delta))) * LOGeTO10; } inline float logadd(float a, float b) { float delta = a - b; if (delta > 64.0) { b += 64; delta = -delta; } return b + log1pf(exp(delta)); } static const float tiny_for_log = (float)1e-16; inline double safe_log(double x) { if (x < tiny_for_log) return logf(tiny_for_log); else return logf(x); } }; #endif /* UTIL_HH */ <commit_msg>added modulo<commit_after>#ifndef UTIL_HH #define UTIL_HH #include <algorithm> #include <vector> #include <math.h> /** Common utility functions. */ namespace util { /** The square of the value. */ template <typename T> T sqr(T a) { return a * a; } /** Median of the values in a vector. * \note For odd number (2n + 1) of values, the n'th value is returned. */ template <typename T> T median(std::vector<T> v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } /** Absolute value. */ template <typename T> T abs(const T &value) { if (value < 0) return -value; return value; } /** Maximum of two values. */ template <typename T> T max(const T &a, const T &b) { if (a < b) return b; return a; } inline float log10add(float a, float b) { const float LOG10TOe = M_LN10; const float LOGeTO10 = 1.0 / M_LN10; a = a * LOG10TOe; b = b * LOG10TOe; float delta = a - b; if (delta > 64.0) { b += 64; delta = -delta; } return (b + log1pf(exp(delta))) * LOGeTO10; } inline float logadd(float a, float b) { float delta = a - b; if (delta > 64.0) { b += 64; delta = -delta; } return b + log1pf(exp(delta)); } static const float tiny_for_log = (float)1e-16; inline double safe_log(double x) { if (x < tiny_for_log) return logf(tiny_for_log); else return logf(x); } /** Compute modulo of two values so that negative arguments are * handled correctly. */ int modulo(int a, int b) { int result = a % b; if (result < 0) result += b; return result; } }; #endif /* UTIL_HH */ <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff/ // Copyright Holders: Felix Albrecht, Rene Milk // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #warning This header is deprecated, use '#include <dune/stuff/la/container/common.hh' instead! #include "common.hh" <commit_msg>[la.container.dunedynamic] fixed deprecation warning<commit_after>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff/ // Copyright Holders: Felix Albrecht, Rene Milk // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #warning This header is deprecated, use '#include <dune/stuff/la/container/common.hh>' instead! #include "common.hh" <|endoftext|>
<commit_before>#define EXT_SINGULAR 2 #define EXT_DEPTH_CHECK 3 #define EXT_DEPTH_ONE_REPLY 2 #define EXT_DEPTH_RECAP 2 #define NULL_DEPTH_RATE 12 #define NULL_DEPTH_REDUCE 14 #define NULL_DEPTH_VRATE 510 #define REDUCTION_RATE1 12 #define REDUCTION_RATE2 12 #define RAZOR_MARGIN1 230 #define RAZOR_MARGIN2 700 #define RAZOR_MARGIN3 820 #define RAZOR_MARGIN4 660 #define FUT_PRUN_MAX_DEPTH 24 #define FUT_PRUN_MARGIN_RATE 40 #define FUT_PRUN_MARGIN 70 #define PROBCUT_MARGIN 200 #define PROBCUT_REDUCTION 16 #define ASP_MIN_DEPTH 0 #define ASP_1ST_DELTA 70 #define ASP_DELTA_RATE 20 #define SINGULAR_DEPTH 36 #define SINGULAR_MARGIN 20 <commit_msg>Fix ASP_MIN_DEPTH parameter<commit_after>#define EXT_SINGULAR 2 #define EXT_DEPTH_CHECK 3 #define EXT_DEPTH_ONE_REPLY 2 #define EXT_DEPTH_RECAP 2 #define NULL_DEPTH_RATE 12 #define NULL_DEPTH_REDUCE 14 #define NULL_DEPTH_VRATE 510 #define REDUCTION_RATE1 12 #define REDUCTION_RATE2 12 #define RAZOR_MARGIN1 230 #define RAZOR_MARGIN2 700 #define RAZOR_MARGIN3 820 #define RAZOR_MARGIN4 660 #define FUT_PRUN_MAX_DEPTH 24 #define FUT_PRUN_MARGIN_RATE 40 #define FUT_PRUN_MARGIN 70 #define PROBCUT_MARGIN 200 #define PROBCUT_REDUCTION 16 #define ASP_MIN_DEPTH 2 #define ASP_1ST_DELTA 70 #define ASP_DELTA_RATE 20 #define SINGULAR_DEPTH 36 #define SINGULAR_MARGIN 20 <|endoftext|>
<commit_before>// Copyright 2014-2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <sstream> #include <string> #include "elang/compiler/testing/analyzer_test.h" #include "base/strings/string_piece.h" #include "base/strings/utf_string_conversions.h" #include "elang/compiler/compilation_session.h" #include "elang/compiler/predefined_names.h" #include "elang/compiler/semantics/editor.h" #include "elang/compiler/semantics/factory.h" #include "elang/compiler/semantics/nodes.h" #include "elang/compiler/source_code_range.h" #include "elang/compiler/token.h" #include "elang/compiler/token_type.h" namespace elang { namespace compiler { namespace sm { ////////////////////////////////////////////////////////////////////// // // IrSemanticsTest // class IrSemanticsTest : public testing::AnalyzerTest { protected: IrSemanticsTest(); ~IrSemanticsTest() override = default; Editor* editor() { return &editor_; } Factory* factory() { return editor()->factory(); } Type* system_int32(); Type* system_int64(); Value* NewLiteral(Type* type, const TokenData& data); Token* NewToken(const TokenData& data); Token* NewToken(base::StringPiece name); std::string ToString(Semantic* node); private: sm::Editor editor_; DISALLOW_COPY_AND_ASSIGN(IrSemanticsTest); }; IrSemanticsTest::IrSemanticsTest() : editor_(session()) { } Type* IrSemanticsTest::system_int32() { return session()->PredefinedTypeOf(PredefinedName::Int32); } Type* IrSemanticsTest::system_int64() { return session()->PredefinedTypeOf(PredefinedName::Int64); } Value* IrSemanticsTest::NewLiteral(Type* type, const TokenData& data) { return factory()->NewLiteral(type, NewToken(data)); } Token* IrSemanticsTest::NewToken(const TokenData& data) { return session()->NewToken(SourceCodeRange(), data); } Token* IrSemanticsTest::NewToken(base::StringPiece name) { return NewToken( TokenData(session()->NewAtomicString(base::UTF8ToUTF16(name)))); } std::string IrSemanticsTest::ToString(Semantic* semantic) { std::stringstream ostream; ostream << *semantic; return ostream.str(); } TEST_F(IrSemanticsTest, ArrayType) { auto const type1 = factory()->NewArrayType(system_int32(), {10, 20}); auto const type2 = factory()->NewArrayType(system_int32(), {10, 20}); auto const type3 = factory()->NewArrayType(system_int32(), {10}); EXPECT_EQ(type1, type2) << "array type should be unique by element type and dimensions"; EXPECT_NE(type1, type3); EXPECT_EQ(2, type1->rank()); EXPECT_EQ("System.Int32[10, 20]", ToString(type1)); EXPECT_EQ("System.Int32[10]", ToString(type3)); } // Element type of array type is omitting left most rank, e.g. // element_type_of(T[A]) = T // element_type_of(T[A][B}) = T[B] // element_type_of(T[A][B}[C]) = T[B][C] TEST_F(IrSemanticsTest, ArrayTypeArrayOfArray) { auto const type1 = factory()->NewArrayType(system_int32(), {10}); auto const type2 = factory()->NewArrayType(type1, {20}); auto const type3 = factory()->NewArrayType(type2, {30}); EXPECT_EQ("System.Int32[10]", ToString(type1)); EXPECT_EQ("System.Int32[20][10]", ToString(type2)); EXPECT_EQ("System.Int32[30][20][10]", ToString(type3)); } TEST_F(IrSemanticsTest, ArrayTypeUnbound) { EXPECT_EQ("System.Int32[]", ToString(factory()->NewArrayType(system_int32(), {-1}))); EXPECT_EQ("System.Int32[,]", ToString(factory()->NewArrayType(system_int32(), {-1, -1}))); EXPECT_EQ("System.Int32[,,]", ToString(factory()->NewArrayType(system_int32(), {-1, -1, -1}))); } TEST_F(IrSemanticsTest, Enum) { auto const outer = factory()->NewNamespace(factory()->global_namespace(), NewToken("Foo")); auto const enum_base = system_int64(); auto const enum_type = factory()->NewEnum(outer, NewToken("Color"), enum_base); factory()->NewEnumMember(enum_type, NewToken("Red"), nullptr); factory()->NewEnumMember(enum_type, NewToken("Green"), nullptr); factory()->NewEnumMember( enum_type, NewToken("Blue"), NewLiteral(enum_base, TokenData(TokenType::Int32Literal, 42))); EXPECT_EQ("enum Foo.Color : System.Int64 {Red, Green, Blue = 42}", ToString(enum_type)); } TEST_F(IrSemanticsTest, Namespace) { auto const ns1 = factory()->NewNamespace(factory()->global_namespace(), NewToken("Foo")); auto const ns2 = factory()->NewNamespace(ns1, NewToken("Bar")); EXPECT_EQ("namespace Foo", ToString(ns1)); EXPECT_EQ("namespace Foo.Bar", ToString(ns2)); } } // namespace sm } // namespace compiler } // namespace elang <commit_msg>elang/compiler/semantics: Tidy up "node_test.cc".<commit_after>// Copyright 2014-2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <sstream> #include <string> #include "elang/compiler/testing/analyzer_test.h" #include "base/strings/string_piece.h" #include "base/strings/utf_string_conversions.h" #include "elang/compiler/compilation_session.h" #include "elang/compiler/predefined_names.h" #include "elang/compiler/semantics/editor.h" #include "elang/compiler/semantics/factory.h" #include "elang/compiler/semantics/nodes.h" #include "elang/compiler/source_code_range.h" #include "elang/compiler/token.h" #include "elang/compiler/token_type.h" namespace elang { namespace compiler { namespace sm { ////////////////////////////////////////////////////////////////////// // // SemanticTest // class SemanticTest : public testing::AnalyzerTest { protected: SemanticTest(); ~SemanticTest() override = default; Editor* editor() { return &editor_; } Factory* factory() { return editor()->factory(); } Type* int32_type(); Type* int64_type(); Value* NewLiteral(Type* type, const TokenData& data); Token* NewToken(const TokenData& data); Token* NewToken(base::StringPiece name); std::string ToString(Semantic* node); private: sm::Editor editor_; DISALLOW_COPY_AND_ASSIGN(SemanticTest); }; SemanticTest::SemanticTest() : editor_(session()) { } Type* SemanticTest::int32_type() { return session()->PredefinedTypeOf(PredefinedName::Int32); } Type* SemanticTest::int64_type() { return session()->PredefinedTypeOf(PredefinedName::Int64); } Value* SemanticTest::NewLiteral(Type* type, const TokenData& data) { return factory()->NewLiteral(type, NewToken(data)); } Token* SemanticTest::NewToken(const TokenData& data) { return session()->NewToken(SourceCodeRange(), data); } Token* SemanticTest::NewToken(base::StringPiece name) { return NewToken( TokenData(session()->NewAtomicString(base::UTF8ToUTF16(name)))); } std::string SemanticTest::ToString(Semantic* semantic) { std::stringstream ostream; ostream << *semantic; return ostream.str(); } TEST_F(SemanticTest, ArrayType) { auto const type1 = factory()->NewArrayType(int32_type(), {10, 20}); auto const type2 = factory()->NewArrayType(int32_type(), {10, 20}); auto const type3 = factory()->NewArrayType(int32_type(), {10}); EXPECT_EQ(type1, type2) << "array type should be unique by element type and dimensions"; EXPECT_NE(type1, type3); EXPECT_EQ(2, type1->rank()); EXPECT_EQ("System.Int32[10, 20]", ToString(type1)); EXPECT_EQ("System.Int32[10]", ToString(type3)); } // Element type of array type is omitting left most rank, e.g. // element_type_of(T[A]) = T // element_type_of(T[A][B}) = T[B] // element_type_of(T[A][B}[C]) = T[B][C] TEST_F(SemanticTest, ArrayTypeArrayOfArray) { auto const type1 = factory()->NewArrayType(int32_type(), {10}); auto const type2 = factory()->NewArrayType(type1, {20}); auto const type3 = factory()->NewArrayType(type2, {30}); EXPECT_EQ("System.Int32[10]", ToString(type1)); EXPECT_EQ("System.Int32[20][10]", ToString(type2)); EXPECT_EQ("System.Int32[30][20][10]", ToString(type3)); } TEST_F(SemanticTest, ArrayTypeUnbound) { EXPECT_EQ("System.Int32[]", ToString(factory()->NewArrayType(int32_type(), {-1}))); EXPECT_EQ("System.Int32[,]", ToString(factory()->NewArrayType(int32_type(), {-1, -1}))); EXPECT_EQ("System.Int32[,,]", ToString(factory()->NewArrayType(int32_type(), {-1, -1, -1}))); } TEST_F(SemanticTest, Enum) { auto const outer = factory()->NewNamespace(factory()->global_namespace(), NewToken("Foo")); auto const enum_base = int64_type(); auto const enum_type = factory()->NewEnum(outer, NewToken("Color"), enum_base); factory()->NewEnumMember(enum_type, NewToken("Red"), nullptr); factory()->NewEnumMember(enum_type, NewToken("Green"), nullptr); factory()->NewEnumMember( enum_type, NewToken("Blue"), NewLiteral(enum_base, TokenData(TokenType::Int32Literal, 42))); EXPECT_EQ("enum Foo.Color : System.Int64 {Red, Green, Blue = 42}", ToString(enum_type)); } TEST_F(SemanticTest, Namespace) { auto const ns1 = factory()->NewNamespace(factory()->global_namespace(), NewToken("Foo")); auto const ns2 = factory()->NewNamespace(ns1, NewToken("Bar")); EXPECT_EQ("namespace Foo", ToString(ns1)); EXPECT_EQ("namespace Foo.Bar", ToString(ns2)); } } // namespace sm } // namespace compiler } // namespace elang <|endoftext|>
<commit_before>#include <iostream> int main() { std::cout << "123\n"; } <commit_msg>Add return 0;<commit_after>#include <iostream> int main() { std::cout << "123\n"; return 0; } <|endoftext|>
<commit_before>#include "core/svg.h" #include "core/numeric.h" #include "core/angle.h" #include "core/random.h" #include "core/range.h" #include "core/palette.h" #include "core/palette_tableu.h" using namespace euphoria::core; using namespace euphoria::core::svg; Poly MakeStar(const vec2f& origo, float radius, const Rgbi& fill, const Angle& rotation) { auto alpha = Angle::OneTurn() / 10; auto p = Poly{}; for(auto i = 11; i > 0; i--) { auto r = radius*(i % 2 + 1)/2.0f; auto omega = rotation + alpha * static_cast<float>(i); p.points.push_back({(r * Sin(omega)) + origo.x, (r * Cos(omega)) + origo.y}); } p.Close(fill); return p; } int main(int, char*[]) { Random rand; auto pal = palette::Tableau_20(); auto svg = Svg{}; for(int i=0; i<30; i+=1) { const auto p = rand.PointOnUnitCircle_CenterFocused()*100.0f; const auto s = rand.Next(Range{5.0f, 30.0f}); const auto c = pal.GetRandomColor(&rand); const auto r = Angle::FromPercentOf360(rand.NextFloat01()); svg << MakeStar(p, s, c, r); } svg.AddAxis().Grid(10); svg.Write("stars.html"); } <commit_msg>started using shufflebag instead of just random values<commit_after>#include "core/svg.h" #include "core/numeric.h" #include "core/angle.h" #include "core/random.h" #include "core/range.h" #include "core/palette.h" #include "core/palette_tableu.h" #include "core/shufflebag.h" using namespace euphoria::core; using namespace euphoria::core::svg; Poly MakeStar(const vec2f& origo, float radius, const Rgbi& fill, const Angle& rotation) { auto alpha = Angle::OneTurn() / 10; auto p = Poly{}; for(auto i = 11; i > 0; i--) { auto r = radius*(i % 2 + 1)/2.0f; auto omega = rotation + alpha * static_cast<float>(i); p.points.push_back({(r * Sin(omega)) + origo.x, (r * Cos(omega)) + origo.y}); } p.Close(fill); return p; } int main(int, char*[]) { Random rand; auto pal = CreateShuffleBag(palette::ColorBlind_10().colors, 2); auto svg = Svg{}; for(int i=0; i<30; i+=1) { const auto p = rand.PointOnUnitCircle_CenterFocused()*100.0f; const auto s = rand.Next(Range{5.0f, 30.0f}); const auto c = pal.Next(&rand); const auto r = Angle::FromPercentOf360(rand.NextFloat01()); svg << MakeStar(p, s, c, r); } svg.AddAxis().Grid(10); svg.Write("stars.html"); } <|endoftext|>
<commit_before>#include "rtp/QualityManager.h" #include "WebRtcConnection.h" namespace erizo { DEFINE_LOGGER(QualityManager, "rtp.QualityManager"); constexpr duration QualityManager::kMinLayerSwitchInterval; constexpr duration QualityManager::kActiveLayerInterval; constexpr float QualityManager::kIncreaseLayerBitrateThreshold; QualityManager::QualityManager(std::shared_ptr<Clock> the_clock) : initialized_{false}, enabled_{false}, padding_enabled_{false}, forced_layers_{false}, slideshow_mode_active_{false}, spatial_layer_{0}, temporal_layer_{0}, max_active_spatial_layer_{0}, max_active_temporal_layer_{0}, current_estimated_bitrate_{0}, last_quality_check_{the_clock->now()}, last_activity_check_{the_clock->now()}, clock_{the_clock} {} void QualityManager::enable() { ELOG_DEBUG("message: Enabling QualityManager"); enabled_ = true; setPadding(true); } void QualityManager::disable() { ELOG_DEBUG("message: Disabling QualityManager"); enabled_ = false; setPadding(false); } void QualityManager::notifyQualityUpdate() { if (!enabled_) { return; } if (!initialized_) { auto pipeline = getContext()->getPipelineShared(); if (!pipeline) { return; } stats_ = pipeline->getService<Stats>(); if (!stats_) { return; } if (!stats_->getNode()["total"].hasChild("senderBitrateEstimation")) { return; } initialized_ = true; } if (forced_layers_) { return; } time_point now = clock_->now(); current_estimated_bitrate_ = stats_->getNode()["total"]["senderBitrateEstimation"].value(); uint64_t current_layer_instant_bitrate = getInstantLayerBitrate(spatial_layer_, temporal_layer_); bool estimated_is_under_layer_bitrate = current_estimated_bitrate_ < current_layer_instant_bitrate; if (now - last_activity_check_ > kActiveLayerInterval) { calculateMaxActiveLayer(); last_activity_check_ = now; } bool layer_is_active = spatial_layer_ <= max_active_spatial_layer_; if (!layer_is_active || (estimated_is_under_layer_bitrate && !slideshow_mode_active_)) { ELOG_DEBUG("message: Forcing calculate new layer, " "estimated_is_under_layer_bitrate: %d, layer_is_active: %d", estimated_is_under_layer_bitrate, layer_is_active); selectLayer(false); } else if (now - last_quality_check_ > kMinLayerSwitchInterval) { selectLayer(true); } } void QualityManager::selectLayer(bool try_higher_layers) { last_quality_check_ = clock_->now(); int aux_temporal_layer = 0; int aux_spatial_layer = 0; int next_temporal_layer = 0; int next_spatial_layer = 0; float bitrate_margin = try_higher_layers ? kIncreaseLayerBitrateThreshold : 0; bool below_min_layer = true; ELOG_DEBUG("Calculate best layer with %lu, current layer %d/%d", current_estimated_bitrate_, spatial_layer_, temporal_layer_); for (auto &spatial_layer_node : stats_->getNode()["qualityLayers"].getMap()) { for (auto &temporal_layer_node : stats_->getNode()["qualityLayers"][spatial_layer_node.first.c_str()].getMap()) { ELOG_DEBUG("Bitrate for layer %d/%d %lu", aux_spatial_layer, aux_temporal_layer, temporal_layer_node.second->value()); if (temporal_layer_node.second->value() != 0 && (1. + bitrate_margin) * temporal_layer_node.second->value() < current_estimated_bitrate_) { next_temporal_layer = aux_temporal_layer; next_spatial_layer = aux_spatial_layer; below_min_layer = false; } aux_temporal_layer++; } aux_temporal_layer = 0; aux_spatial_layer++; } if (below_min_layer != slideshow_mode_active_) { if (below_min_layer || try_higher_layers) { slideshow_mode_active_ = below_min_layer; ELOG_DEBUG("Slideshow fallback mode %d", slideshow_mode_active_); WebRtcConnection *connection = getContext()->getPipelineShared()->getService<WebRtcConnection>().get(); if (connection) { connection->notifyUpdateToHandlers(); } } } if (next_temporal_layer != temporal_layer_ || next_spatial_layer != spatial_layer_) { ELOG_DEBUG("message: Layer Switch, current_layer: %d/%d, new_layer: %d/%d", spatial_layer_, temporal_layer_, next_spatial_layer, next_temporal_layer); setTemporalLayer(next_temporal_layer); setSpatialLayer(next_spatial_layer); // TODO(javier): should we wait for the actual spatial switch? // should we disable padding temporarily to avoid congestion (old padding + new bitrate)? setPadding(!isInMaxLayer()); ELOG_DEBUG("message: Is padding enabled, padding_enabled_: %d", padding_enabled_); } } void QualityManager::calculateMaxActiveLayer() { int max_active_spatial_layer = 5; int max_active_temporal_layer = 5; for (; max_active_spatial_layer > 0; max_active_spatial_layer--) { if (getInstantLayerBitrate(max_active_spatial_layer, 0) > 0) { break; } } for (; max_active_temporal_layer > 0; max_active_temporal_layer--) { if (getInstantLayerBitrate(max_active_spatial_layer, max_active_temporal_layer) > 0) { break; } } stats_->getNode()["qualityLayers"].insertStat("maxActiveSpatialLayer", CumulativeStat{static_cast<uint64_t>(max_active_spatial_layer_)}); stats_->getNode()["qualityLayers"].insertStat("maxActiveTemporalLayer", CumulativeStat{static_cast<uint64_t>(max_active_temporal_layer_)}); max_active_spatial_layer_ = max_active_spatial_layer; max_active_temporal_layer_ = max_active_temporal_layer; } uint64_t QualityManager::getInstantLayerBitrate(int spatial_layer, int temporal_layer) { if (!stats_->getNode()["qualityLayers"].hasChild(spatial_layer) || !stats_->getNode()["qualityLayers"][spatial_layer].hasChild(temporal_layer)) { return 0; } MovingIntervalRateStat* layer_stat = reinterpret_cast<MovingIntervalRateStat*>(&stats_->getNode()["qualityLayers"][spatial_layer][temporal_layer]); return layer_stat->value(kActiveLayerInterval); } bool QualityManager::isInBaseLayer() { return (spatial_layer_ == 0 && temporal_layer_ == 0); } bool QualityManager::isInMaxLayer() { return (spatial_layer_ >= max_active_spatial_layer_ && temporal_layer_ >= max_active_temporal_layer_); } void QualityManager::forceLayers(int spatial_layer, int temporal_layer) { if (spatial_layer == -1 || temporal_layer == -1) { forced_layers_ = false; return; } forced_layers_ = true; setPadding(false); spatial_layer_ = spatial_layer; temporal_layer_ = temporal_layer; } void QualityManager::setSpatialLayer(int spatial_layer) { if (!forced_layers_) { spatial_layer_ = spatial_layer; } stats_->getNode()["qualityLayers"].insertStat("selectedSpatialLayer", CumulativeStat{static_cast<uint64_t>(spatial_layer_)}); } void QualityManager::setTemporalLayer(int temporal_layer) { if (!forced_layers_) { temporal_layer_ = temporal_layer; } stats_->getNode()["qualityLayers"].insertStat("selectedTemporalLayer", CumulativeStat{static_cast<uint64_t>(temporal_layer_)}); } void QualityManager::setPadding(bool enabled) { if (padding_enabled_ != enabled) { padding_enabled_ = enabled; getContext()->getPipelineShared()->getService<WebRtcConnection>()->notifyUpdateToHandlers(); } } } // namespace erizo <commit_msg>Fix an issue when enabling padding the first time (#950)<commit_after>#include "rtp/QualityManager.h" #include "WebRtcConnection.h" namespace erizo { DEFINE_LOGGER(QualityManager, "rtp.QualityManager"); constexpr duration QualityManager::kMinLayerSwitchInterval; constexpr duration QualityManager::kActiveLayerInterval; constexpr float QualityManager::kIncreaseLayerBitrateThreshold; QualityManager::QualityManager(std::shared_ptr<Clock> the_clock) : initialized_{false}, enabled_{false}, padding_enabled_{false}, forced_layers_{false}, slideshow_mode_active_{false}, spatial_layer_{0}, temporal_layer_{0}, max_active_spatial_layer_{0}, max_active_temporal_layer_{0}, current_estimated_bitrate_{0}, last_quality_check_{the_clock->now()}, last_activity_check_{the_clock->now()}, clock_{the_clock} {} void QualityManager::enable() { ELOG_DEBUG("message: Enabling QualityManager"); enabled_ = true; if (!forced_layers_) { setPadding(true); } } void QualityManager::disable() { ELOG_DEBUG("message: Disabling QualityManager"); enabled_ = false; setPadding(false); } void QualityManager::notifyQualityUpdate() { if (!enabled_) { return; } if (!initialized_) { auto pipeline = getContext()->getPipelineShared(); if (!pipeline) { return; } stats_ = pipeline->getService<Stats>(); if (!stats_) { return; } if (!stats_->getNode()["total"].hasChild("senderBitrateEstimation")) { return; } initialized_ = true; } if (forced_layers_) { return; } time_point now = clock_->now(); current_estimated_bitrate_ = stats_->getNode()["total"]["senderBitrateEstimation"].value(); uint64_t current_layer_instant_bitrate = getInstantLayerBitrate(spatial_layer_, temporal_layer_); bool estimated_is_under_layer_bitrate = current_estimated_bitrate_ < current_layer_instant_bitrate; if (now - last_activity_check_ > kActiveLayerInterval) { calculateMaxActiveLayer(); last_activity_check_ = now; } bool layer_is_active = spatial_layer_ <= max_active_spatial_layer_; if (!layer_is_active || (estimated_is_under_layer_bitrate && !slideshow_mode_active_)) { ELOG_DEBUG("message: Forcing calculate new layer, " "estimated_is_under_layer_bitrate: %d, layer_is_active: %d", estimated_is_under_layer_bitrate, layer_is_active); selectLayer(false); } else if (now - last_quality_check_ > kMinLayerSwitchInterval) { selectLayer(true); } } void QualityManager::selectLayer(bool try_higher_layers) { last_quality_check_ = clock_->now(); int aux_temporal_layer = 0; int aux_spatial_layer = 0; int next_temporal_layer = 0; int next_spatial_layer = 0; float bitrate_margin = try_higher_layers ? kIncreaseLayerBitrateThreshold : 0; bool below_min_layer = true; ELOG_DEBUG("Calculate best layer with %lu, current layer %d/%d", current_estimated_bitrate_, spatial_layer_, temporal_layer_); for (auto &spatial_layer_node : stats_->getNode()["qualityLayers"].getMap()) { for (auto &temporal_layer_node : stats_->getNode()["qualityLayers"][spatial_layer_node.first.c_str()].getMap()) { ELOG_DEBUG("Bitrate for layer %d/%d %lu", aux_spatial_layer, aux_temporal_layer, temporal_layer_node.second->value()); if (temporal_layer_node.second->value() != 0 && (1. + bitrate_margin) * temporal_layer_node.second->value() < current_estimated_bitrate_) { next_temporal_layer = aux_temporal_layer; next_spatial_layer = aux_spatial_layer; below_min_layer = false; } aux_temporal_layer++; } aux_temporal_layer = 0; aux_spatial_layer++; } if (below_min_layer != slideshow_mode_active_) { if (below_min_layer || try_higher_layers) { slideshow_mode_active_ = below_min_layer; ELOG_DEBUG("Slideshow fallback mode %d", slideshow_mode_active_); WebRtcConnection *connection = getContext()->getPipelineShared()->getService<WebRtcConnection>().get(); if (connection) { connection->notifyUpdateToHandlers(); } } } if (next_temporal_layer != temporal_layer_ || next_spatial_layer != spatial_layer_) { ELOG_DEBUG("message: Layer Switch, current_layer: %d/%d, new_layer: %d/%d", spatial_layer_, temporal_layer_, next_spatial_layer, next_temporal_layer); setTemporalLayer(next_temporal_layer); setSpatialLayer(next_spatial_layer); // TODO(javier): should we wait for the actual spatial switch? // should we disable padding temporarily to avoid congestion (old padding + new bitrate)? setPadding(!isInMaxLayer()); ELOG_DEBUG("message: Is padding enabled, padding_enabled_: %d", padding_enabled_); } } void QualityManager::calculateMaxActiveLayer() { int max_active_spatial_layer = 5; int max_active_temporal_layer = 5; for (; max_active_spatial_layer > 0; max_active_spatial_layer--) { if (getInstantLayerBitrate(max_active_spatial_layer, 0) > 0) { break; } } for (; max_active_temporal_layer > 0; max_active_temporal_layer--) { if (getInstantLayerBitrate(max_active_spatial_layer, max_active_temporal_layer) > 0) { break; } } stats_->getNode()["qualityLayers"].insertStat("maxActiveSpatialLayer", CumulativeStat{static_cast<uint64_t>(max_active_spatial_layer_)}); stats_->getNode()["qualityLayers"].insertStat("maxActiveTemporalLayer", CumulativeStat{static_cast<uint64_t>(max_active_temporal_layer_)}); max_active_spatial_layer_ = max_active_spatial_layer; max_active_temporal_layer_ = max_active_temporal_layer; } uint64_t QualityManager::getInstantLayerBitrate(int spatial_layer, int temporal_layer) { if (!stats_->getNode()["qualityLayers"].hasChild(spatial_layer) || !stats_->getNode()["qualityLayers"][spatial_layer].hasChild(temporal_layer)) { return 0; } MovingIntervalRateStat* layer_stat = reinterpret_cast<MovingIntervalRateStat*>(&stats_->getNode()["qualityLayers"][spatial_layer][temporal_layer]); return layer_stat->value(kActiveLayerInterval); } bool QualityManager::isInBaseLayer() { return (spatial_layer_ == 0 && temporal_layer_ == 0); } bool QualityManager::isInMaxLayer() { return (spatial_layer_ >= max_active_spatial_layer_ && temporal_layer_ >= max_active_temporal_layer_); } void QualityManager::forceLayers(int spatial_layer, int temporal_layer) { if (spatial_layer == -1 || temporal_layer == -1) { forced_layers_ = false; return; } forced_layers_ = true; setPadding(false); spatial_layer_ = spatial_layer; temporal_layer_ = temporal_layer; } void QualityManager::setSpatialLayer(int spatial_layer) { if (!forced_layers_) { spatial_layer_ = spatial_layer; } stats_->getNode()["qualityLayers"].insertStat("selectedSpatialLayer", CumulativeStat{static_cast<uint64_t>(spatial_layer_)}); } void QualityManager::setTemporalLayer(int temporal_layer) { if (!forced_layers_) { temporal_layer_ = temporal_layer; } stats_->getNode()["qualityLayers"].insertStat("selectedTemporalLayer", CumulativeStat{static_cast<uint64_t>(temporal_layer_)}); } void QualityManager::setPadding(bool enabled) { if (padding_enabled_ != enabled) { padding_enabled_ = enabled; getContext()->getPipelineShared()->getService<WebRtcConnection>()->notifyUpdateToHandlers(); } } } // namespace erizo <|endoftext|>
<commit_before>d6483158-2e4c-11e5-9284-b827eb9e62be<commit_msg>d64d3e1e-2e4c-11e5-9284-b827eb9e62be<commit_after>d64d3e1e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>cd46f638-2e4d-11e5-9284-b827eb9e62be<commit_msg>cd4be9cc-2e4d-11e5-9284-b827eb9e62be<commit_after>cd4be9cc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>4bafcc3e-2e4e-11e5-9284-b827eb9e62be<commit_msg>4bb53854-2e4e-11e5-9284-b827eb9e62be<commit_after>4bb53854-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e70ebc6c-2e4e-11e5-9284-b827eb9e62be<commit_msg>e713eb24-2e4e-11e5-9284-b827eb9e62be<commit_after>e713eb24-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ff7dcdec-2e4e-11e5-9284-b827eb9e62be<commit_msg>ff82c4e6-2e4e-11e5-9284-b827eb9e62be<commit_after>ff82c4e6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c4bf2cb4-2e4e-11e5-9284-b827eb9e62be<commit_msg>c4c42c00-2e4e-11e5-9284-b827eb9e62be<commit_after>c4c42c00-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a5d00356-2e4d-11e5-9284-b827eb9e62be<commit_msg>a5d4fbcc-2e4d-11e5-9284-b827eb9e62be<commit_after>a5d4fbcc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b07366d0-2e4e-11e5-9284-b827eb9e62be<commit_msg>b078675c-2e4e-11e5-9284-b827eb9e62be<commit_after>b078675c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2c1ef17e-2e4e-11e5-9284-b827eb9e62be<commit_msg>2c23ff7a-2e4e-11e5-9284-b827eb9e62be<commit_after>2c23ff7a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d800e094-2e4c-11e5-9284-b827eb9e62be<commit_msg>d805f250-2e4c-11e5-9284-b827eb9e62be<commit_after>d805f250-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>16ffa15e-2e4d-11e5-9284-b827eb9e62be<commit_msg>1704ba2c-2e4d-11e5-9284-b827eb9e62be<commit_after>1704ba2c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>04070c94-2e4e-11e5-9284-b827eb9e62be<commit_msg>040bf98e-2e4e-11e5-9284-b827eb9e62be<commit_after>040bf98e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c55a6456-2e4c-11e5-9284-b827eb9e62be<commit_msg>c55f59de-2e4c-11e5-9284-b827eb9e62be<commit_after>c55f59de-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a3885814-2e4d-11e5-9284-b827eb9e62be<commit_msg>a38d50bc-2e4d-11e5-9284-b827eb9e62be<commit_after>a38d50bc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e7c1012e-2e4e-11e5-9284-b827eb9e62be<commit_msg>e7c62d5c-2e4e-11e5-9284-b827eb9e62be<commit_after>e7c62d5c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fb7cacc4-2e4c-11e5-9284-b827eb9e62be<commit_msg>fb81a990-2e4c-11e5-9284-b827eb9e62be<commit_after>fb81a990-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fdd393b6-2e4c-11e5-9284-b827eb9e62be<commit_msg>fdd88628-2e4c-11e5-9284-b827eb9e62be<commit_after>fdd88628-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0e4e1c60-2e4e-11e5-9284-b827eb9e62be<commit_msg>0e531404-2e4e-11e5-9284-b827eb9e62be<commit_after>0e531404-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2929b0a4-2e4d-11e5-9284-b827eb9e62be<commit_msg>292ea1d6-2e4d-11e5-9284-b827eb9e62be<commit_after>292ea1d6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d4207cb4-2e4c-11e5-9284-b827eb9e62be<commit_msg>d425a36a-2e4c-11e5-9284-b827eb9e62be<commit_after>d425a36a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8b1bf88a-2e4d-11e5-9284-b827eb9e62be<commit_msg>8b20f07e-2e4d-11e5-9284-b827eb9e62be<commit_after>8b20f07e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e39683aa-2e4c-11e5-9284-b827eb9e62be<commit_msg>e39b8652-2e4c-11e5-9284-b827eb9e62be<commit_after>e39b8652-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a4638302-2e4e-11e5-9284-b827eb9e62be<commit_msg>a4689b1c-2e4e-11e5-9284-b827eb9e62be<commit_after>a4689b1c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>98028ec4-2e4d-11e5-9284-b827eb9e62be<commit_msg>98078cf8-2e4d-11e5-9284-b827eb9e62be<commit_after>98078cf8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>51afb0e6-2e4d-11e5-9284-b827eb9e62be<commit_msg>51b4c176-2e4d-11e5-9284-b827eb9e62be<commit_after>51b4c176-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>03af4eb8-2e4f-11e5-9284-b827eb9e62be<commit_msg>03b445c6-2e4f-11e5-9284-b827eb9e62be<commit_after>03b445c6-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2e4abe4c-2e4e-11e5-9284-b827eb9e62be<commit_msg>2e4fceaa-2e4e-11e5-9284-b827eb9e62be<commit_after>2e4fceaa-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ff242e9a-2e4e-11e5-9284-b827eb9e62be<commit_msg>ff2923aa-2e4e-11e5-9284-b827eb9e62be<commit_after>ff2923aa-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3f53a53c-2e4e-11e5-9284-b827eb9e62be<commit_msg>3f58b568-2e4e-11e5-9284-b827eb9e62be<commit_after>3f58b568-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0de8e416-2e4f-11e5-9284-b827eb9e62be<commit_msg>0dedf276-2e4f-11e5-9284-b827eb9e62be<commit_after>0dedf276-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e2eac286-2e4c-11e5-9284-b827eb9e62be<commit_msg>e2efcb3c-2e4c-11e5-9284-b827eb9e62be<commit_after>e2efcb3c-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>bf22c4fa-2e4e-11e5-9284-b827eb9e62be<commit_msg>bf27cbc6-2e4e-11e5-9284-b827eb9e62be<commit_after>bf27cbc6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>46e62a6e-2e4d-11e5-9284-b827eb9e62be<commit_msg>46eb3130-2e4d-11e5-9284-b827eb9e62be<commit_after>46eb3130-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8a92328a-2e4d-11e5-9284-b827eb9e62be<commit_msg>8a9753aa-2e4d-11e5-9284-b827eb9e62be<commit_after>8a9753aa-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c77d647a-2e4e-11e5-9284-b827eb9e62be<commit_msg>c7826286-2e4e-11e5-9284-b827eb9e62be<commit_after>c7826286-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e4a6d5f4-2e4e-11e5-9284-b827eb9e62be<commit_msg>e4abe526-2e4e-11e5-9284-b827eb9e62be<commit_after>e4abe526-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>013d23c2-2e4e-11e5-9284-b827eb9e62be<commit_msg>014221c4-2e4e-11e5-9284-b827eb9e62be<commit_after>014221c4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b9aba168-2e4e-11e5-9284-b827eb9e62be<commit_msg>b9b0b658-2e4e-11e5-9284-b827eb9e62be<commit_after>b9b0b658-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>01bce9a0-2e4d-11e5-9284-b827eb9e62be<commit_msg>01c1e7c0-2e4d-11e5-9284-b827eb9e62be<commit_after>01c1e7c0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>900e5134-2e4e-11e5-9284-b827eb9e62be<commit_msg>9013498c-2e4e-11e5-9284-b827eb9e62be<commit_after>9013498c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>116f80e0-2e4f-11e5-9284-b827eb9e62be<commit_msg>117481b2-2e4f-11e5-9284-b827eb9e62be<commit_after>117481b2-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c869f696-2e4e-11e5-9284-b827eb9e62be<commit_msg>c86eff42-2e4e-11e5-9284-b827eb9e62be<commit_after>c86eff42-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>216c7e36-2e4e-11e5-9284-b827eb9e62be<commit_msg>217185f2-2e4e-11e5-9284-b827eb9e62be<commit_after>217185f2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>cf596092-2e4c-11e5-9284-b827eb9e62be<commit_msg>cf5e5d0e-2e4c-11e5-9284-b827eb9e62be<commit_after>cf5e5d0e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>5153a5ee-2e4d-11e5-9284-b827eb9e62be<commit_msg>5158b412-2e4d-11e5-9284-b827eb9e62be<commit_after>5158b412-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>386a2840-2e4e-11e5-9284-b827eb9e62be<commit_msg>386f1f08-2e4e-11e5-9284-b827eb9e62be<commit_after>386f1f08-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f2572fd2-2e4e-11e5-9284-b827eb9e62be<commit_msg>f25c3e82-2e4e-11e5-9284-b827eb9e62be<commit_after>f25c3e82-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b782bae4-2e4d-11e5-9284-b827eb9e62be<commit_msg>b787b300-2e4d-11e5-9284-b827eb9e62be<commit_after>b787b300-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1214ab76-2e4d-11e5-9284-b827eb9e62be<commit_msg>12199e88-2e4d-11e5-9284-b827eb9e62be<commit_after>12199e88-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>4c3ac2b2-2e4e-11e5-9284-b827eb9e62be<commit_msg>4c3fceba-2e4e-11e5-9284-b827eb9e62be<commit_after>4c3fceba-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>36b97fdc-2e4e-11e5-9284-b827eb9e62be<commit_msg>36be782a-2e4e-11e5-9284-b827eb9e62be<commit_after>36be782a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>23342344-2e4f-11e5-9284-b827eb9e62be<commit_msg>23392902-2e4f-11e5-9284-b827eb9e62be<commit_after>23392902-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3200c212-2e4d-11e5-9284-b827eb9e62be<commit_msg>3205bf38-2e4d-11e5-9284-b827eb9e62be<commit_after>3205bf38-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>826383c0-2e4d-11e5-9284-b827eb9e62be<commit_msg>82687c90-2e4d-11e5-9284-b827eb9e62be<commit_after>82687c90-2e4d-11e5-9284-b827eb9e62be<|endoftext|>