<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/profiler/convert/op_stats_to_overview_page.h"

#include <algorithm>
#include <utility>

#include "google/protobuf/any.pb.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/profiler/convert/op_metrics_to_record.h"
#include "tensorflow/core/profiler/convert/op_stats_to_input_pipeline_analysis.h"
#include "tensorflow/core/profiler/protobuf/hardware_types.pb.h"
#include "tensorflow/core/profiler/protobuf/input_pipeline.pb.h"
#include "tensorflow/core/profiler/protobuf/op_metrics.pb.h"
#include "tensorflow/core/profiler/protobuf/op_stats.pb.h"
#include "tensorflow/core/profiler/protobuf/overview_page.pb.h"
#include "tensorflow/core/profiler/utils/math_utils.h"
#include "tensorflow/core/profiler/utils/op_metrics_db_utils.h"
#include "tensorflow/core/profiler/utils/time_utils.h"

namespace tensorflow {
namespace profiler {

namespace {

OverviewPageTip MakeOverviewPageTip(const string& text) {
  OverviewPageTip tip;
  tip.set_link(text);
  return tip;
}

string AnchorElement(const string& url, const string& text) {
  return absl::StrCat("", text, "");
}

// Makes a recommendation for looking up a document.
// doc_url is expected to be already be escaped suitably for use in an HTML
// attribute.
OverviewPageTip MakeOverviewPageTipDocLink(const string& doc_url,
                                           const string& text) {
  OverviewPageTip tip;
  tip.set_link(AnchorElement(doc_url, text));
  return tip;
}

void ComputeHostTips(OverviewPageRecommendation* re) {
  *re->add_host_tips() = MakeOverviewPageTip(
      "input_pipeline_analyzer (especially Section 3 for the breakdown of "
      "input operations on the Host)");
  *re->add_host_tips() = MakeOverviewPageTip(
      "trace_viewer (look at the activities on the timeline of each Host "
      "Thread near the bottom of the trace view)");
}

void ComputeDeviceTips(HardwareType hardware_type,
                       OverviewPageRecommendation* re) {
  const string& device_name = HardwareType_Name(hardware_type);
  string timeline_name =
      (hardware_type == tensorflow::profiler::TPU) ? "TPU core" : device_name;
  *re->add_device_tips() = MakeOverviewPageTip(absl::StrCat(
      "op_profile (identify the time-consuming operations executed on the ",
      device_name, ")"));
  *re->add_device_tips() = MakeOverviewPageTip(absl::StrCat(
      "trace_viewer (look at the activities on the timeline of each ",
      timeline_name, " in the trace view)"));
}

void ComputeFaqTips(OverviewPageRecommendation* re) {
  *re->add_faq_tips() = MakeOverviewPageTip("Refer to the Cloud tools FAQ");
}

void ComputeDocumentationTips(OverviewPageRecommendation* re) {
  *re->add_documentation_tips() = MakeOverviewPageTipDocLink(
      "https://www.tensorflow.org/versions/master/api_docs/python/tf/data/"
      "Dataset",
      "TensorFlow Input Pipeline API");
}

}  // namespace

void SetCommonRecommendation(const CommonBottleneck& bottleneck,
                             HardwareType hardware_type,
                             OverviewPageRecommendation* re) {
  re->set_bottleneck(bottleneck.input_classification);
  re->set_statement(bottleneck.input_statement);
  ComputeHostTips(re);
  ComputeDeviceTips(hardware_type, re);
  ComputeDocumentationTips(re);
  ComputeFaqTips(re);
}

OverviewPageRecommendation ComputeGenericRecommendation(
    const GenericBottleneck& bottleneck) {
  OverviewPageRecommendation re;
  GenericRecommendation generic;
  generic.set_kernel_launch_bottleneck(bottleneck.kernel_launch_classification);
  generic.set_kernel_launch_statement(bottleneck.kernel_launch_statement);
  generic.set_all_other_bottleneck(bottleneck.all_other_classification);
  generic.set_all_other_statement(bottleneck.all_other_statement);
  re.mutable_recommendation()->PackFrom(generic);
  return re;
}

OverviewPageAnalysis ComputeAnalysisResult(const OpStats& op_stats) {
  OverviewPageAnalysis analysis;
  OpMetricsDb metrics_db =
      CreateTfMetricsDbFromHloMetricsDb(op_stats.device_op_metrics_db());
  uint64 total_device_time_ps = metrics_db.total_time_ps();
  constexpr int kNumTopOpsShown = 10;
  double device_cumulative_fraction = 0.0;
  for (const OpMetrics* metrics :
       SortedOpMetricsDb(metrics_db, kNumTopOpsShown)) {
    OverviewTfOp* op = analysis.add_top_device_ops();
    op->set_name(metrics->name());
    op->set_category(metrics->category());
    op->set_self_time_fraction(
        SafeDivide(metrics->self_time_ps(), total_device_time_ps));
    device_cumulative_fraction += op->self_time_fraction();
    op->set_cumulative_time_fraction(device_cumulative_fraction);
    op->set_flop_rate(
        SafeDivide(metrics->flops(), PicosToNanos(metrics->time_ps())));
  }
  return analysis;
}

// Converts from HostIndependentJobInfo to OverviewPageHostIndependentJobInfo.
OverviewPageHostIndependentJobInfo ToOverviewPageHostIndependentJobInfo(
    const HostIndependentJobInfoResult& host_independent_job_info) {
  OverviewPageHostIndependentJobInfo result;
  result.set_change_list(host_independent_job_info.change_list());
  result.set_build_time(host_independent_job_info.build_time());
  result.set_build_target(host_independent_job_info.build_target());
  result.set_profile_duration_ms(
      host_independent_job_info.profile_duration_ms());
  return result;
}

// Converts from HostDependentJobInfo to OverviewPageHostDependentJobInfo.
OverviewPageHostDependentJobInfo ToOverviewPageHostDependentJobInfo(
    const HostDependentJobInfoResult& host_dependent_job_info) {
  OverviewPageHostDependentJobInfo result;
  result.set_host_id(host_dependent_job_info.host_id());
  result.set_command_line(host_dependent_job_info.command_line());
  result.set_start_time(host_dependent_job_info.start_time());
  result.set_bns_address(host_dependent_job_info.bns_address());
  result.set_profile_time_ns(host_dependent_job_info.profile_time_ns());
  return result;
}

OverviewPageRunEnvironment ComputeRunEnvironment(
    const RunEnvironment& run_environment) {
  OverviewPageRunEnvironment re;
  re.set_host_count(run_environment.host_count());
  re.set_task_count(run_environment.task_count());
  re.set_device_type(run_environment.device_type());
  re.set_device_core_count(run_environment.device_core_count());
  re.set_per_core_batch_size(run_environment.per_core_batch_size());
  re.set_replica_count(run_environment.replica_count());
  re.set_num_cores_per_replica(run_environment.num_cores_per_replica());
  *re.mutable_host_independent_job_info() =
      ToOverviewPageHostIndependentJobInfo(
          run_environment.host_independent_job_info());
  for (const auto& host_dependent_job_info :
       run_environment.host_dependent_job_info()) {
    *re.add_host_dependent_job_info() =
        ToOverviewPageHostDependentJobInfo(host_dependent_job_info);
  }
  return re;
}

OverviewPage ConvertOpStatsToOverviewPage(const OpStats& op_stats,
                                          HardwareType hardware_type) {
  OverviewPageAnalysis analysis = ComputeAnalysisResult(op_stats);
  InputPipelineAnalysisResult input_analysis =
      ConvertOpStatsToInputPipelineAnalysis(op_stats, hardware_type);
  GenericBottleneck bottleneck = GenericOverallBottleneck(input_analysis);
  OverviewPageRecommendation recommendation =
      ComputeGenericRecommendation(bottleneck);
  SetCommonRecommendation(bottleneck.common, hardware_type, &recommendation);

  OverviewPage overview_page;
  *overview_page.mutable_run_environment() =
      ComputeRunEnvironment(op_stats.run_environment());
  *overview_page.mutable_analysis() = analysis;
  *overview_page.mutable_input_analysis() = input_analysis;
  *overview_page.mutable_recommendation() = recommendation;
  return overview_page;
}

}  // namespace profiler
}  // namespace tensorflow
<commit_msg>Fix output of overview page and input-pipeline analyzer for Cloud TPU.<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/profiler/convert/op_stats_to_overview_page.h"

#include <algorithm>
#include <utility>

#include "google/protobuf/any.pb.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/profiler/convert/op_metrics_to_record.h"
#include "tensorflow/core/profiler/convert/op_stats_to_input_pipeline_analysis.h"
#include "tensorflow/core/profiler/protobuf/hardware_types.pb.h"
#include "tensorflow/core/profiler/protobuf/input_pipeline.pb.h"
#include "tensorflow/core/profiler/protobuf/op_metrics.pb.h"
#include "tensorflow/core/profiler/protobuf/op_stats.pb.h"
#include "tensorflow/core/profiler/protobuf/overview_page.pb.h"
#include "tensorflow/core/profiler/utils/math_utils.h"
#include "tensorflow/core/profiler/utils/op_metrics_db_utils.h"
#include "tensorflow/core/profiler/utils/time_utils.h"

namespace tensorflow {
namespace profiler {

namespace {

OverviewPageTip MakeOverviewPageTip(const string& text) {
  OverviewPageTip tip;
  tip.set_link(text);
  return tip;
}

string AnchorElement(const string& url, const string& text) {
  return absl::StrCat("", text, "");
}

// Makes a recommendation for looking up a document.
// doc_url is expected to be already be escaped suitably for use in an HTML
// attribute.
OverviewPageTip MakeOverviewPageTipDocLink(const string& doc_url,
                                           const string& text) {
  OverviewPageTip tip;
  tip.set_link(AnchorElement(doc_url, text));
  return tip;
}

void ComputeHostTips(OverviewPageRecommendation* re) {
  *re->add_host_tips() = MakeOverviewPageTip(
      "input_pipeline_analyzer (especially Section 3 for the breakdown of "
      "input operations on the Host)");
  *re->add_host_tips() = MakeOverviewPageTip(
      "trace_viewer (look at the activities on the timeline of each Host "
      "Thread near the bottom of the trace view)");
}

void ComputeDeviceTips(HardwareType hardware_type,
                       OverviewPageRecommendation* re) {
  const string& device_name = HardwareType_Name(hardware_type);
  string timeline_name =
      (hardware_type == tensorflow::profiler::TPU) ? "TPU core" : device_name;
  *re->add_device_tips() = MakeOverviewPageTip(absl::StrCat(
      "op_profile (identify the time-consuming operations executed on the ",
      device_name, ")"));
  *re->add_device_tips() = MakeOverviewPageTip(absl::StrCat(
      "trace_viewer (look at the activities on the timeline of each ",
      timeline_name, " in the trace view)"));
}

void ComputeFaqTips(OverviewPageRecommendation* re) {
  *re->add_faq_tips() = MakeOverviewPageTip("Refer to the Cloud tools FAQ");
}

void ComputeDocumentationTips(OverviewPageRecommendation* re) {
  *re->add_documentation_tips() = MakeOverviewPageTipDocLink(
      "https://www.tensorflow.org/guide/"
      "data_performance",
      "Better performance with the tf.data API");
}

}  // namespace

void SetCommonRecommendation(const CommonBottleneck& bottleneck,
                             HardwareType hardware_type,
                             OverviewPageRecommendation* re) {
  re->set_bottleneck(bottleneck.input_classification);
  re->set_statement(bottleneck.input_statement);
  ComputeHostTips(re);
  ComputeDeviceTips(hardware_type, re);
  ComputeDocumentationTips(re);
  ComputeFaqTips(re);
}

OverviewPageRecommendation ComputeGenericRecommendation(
    const GenericBottleneck& bottleneck) {
  OverviewPageRecommendation re;
  GenericRecommendation generic;
  generic.set_kernel_launch_bottleneck(bottleneck.kernel_launch_classification);
  generic.set_kernel_launch_statement(bottleneck.kernel_launch_statement);
  generic.set_all_other_bottleneck(bottleneck.all_other_classification);
  generic.set_all_other_statement(bottleneck.all_other_statement);
  re.mutable_recommendation()->PackFrom(generic);
  return re;
}

OverviewPageAnalysis ComputeAnalysisResult(const OpStats& op_stats) {
  OverviewPageAnalysis analysis;
  OpMetricsDb metrics_db =
      CreateTfMetricsDbFromHloMetricsDb(op_stats.device_op_metrics_db());
  uint64 total_device_time_ps = metrics_db.total_time_ps();
  constexpr int kNumTopOpsShown = 10;
  double device_cumulative_fraction = 0.0;
  for (const OpMetrics* metrics :
       SortedOpMetricsDb(metrics_db, kNumTopOpsShown)) {
    OverviewTfOp* op = analysis.add_top_device_ops();
    op->set_name(metrics->name());
    op->set_category(metrics->category());
    op->set_self_time_fraction(
        SafeDivide(metrics->self_time_ps(), total_device_time_ps));
    device_cumulative_fraction += op->self_time_fraction();
    op->set_cumulative_time_fraction(device_cumulative_fraction);
    op->set_flop_rate(
        SafeDivide(metrics->flops(), PicosToNanos(metrics->time_ps())));
  }
  return analysis;
}

// Converts from HostIndependentJobInfo to OverviewPageHostIndependentJobInfo.
OverviewPageHostIndependentJobInfo ToOverviewPageHostIndependentJobInfo(
    const HostIndependentJobInfoResult& host_independent_job_info) {
  OverviewPageHostIndependentJobInfo result;
  result.set_change_list(host_independent_job_info.change_list());
  result.set_build_time(host_independent_job_info.build_time());
  result.set_build_target(host_independent_job_info.build_target());
  result.set_profile_duration_ms(
      host_independent_job_info.profile_duration_ms());
  return result;
}

// Converts from HostDependentJobInfo to OverviewPageHostDependentJobInfo.
OverviewPageHostDependentJobInfo ToOverviewPageHostDependentJobInfo(
    const HostDependentJobInfoResult& host_dependent_job_info) {
  OverviewPageHostDependentJobInfo result;
  result.set_host_id(host_dependent_job_info.host_id());
  result.set_command_line(host_dependent_job_info.command_line());
  result.set_start_time(host_dependent_job_info.start_time());
  result.set_bns_address(host_dependent_job_info.bns_address());
  result.set_profile_time_ns(host_dependent_job_info.profile_time_ns());
  return result;
}

OverviewPageRunEnvironment ComputeRunEnvironment(
    const RunEnvironment& run_environment) {
  OverviewPageRunEnvironment re;
  re.set_host_count(run_environment.host_count());
  re.set_task_count(run_environment.task_count());
  re.set_device_type(run_environment.device_type());
  re.set_device_core_count(run_environment.device_core_count());
  re.set_per_core_batch_size(run_environment.per_core_batch_size());
  re.set_replica_count(run_environment.replica_count());
  re.set_num_cores_per_replica(run_environment.num_cores_per_replica());
  *re.mutable_host_independent_job_info() =
      ToOverviewPageHostIndependentJobInfo(
          run_environment.host_independent_job_info());
  for (const auto& host_dependent_job_info :
       run_environment.host_dependent_job_info()) {
    *re.add_host_dependent_job_info() =
        ToOverviewPageHostDependentJobInfo(host_dependent_job_info);
  }
  return re;
}

OverviewPage ConvertOpStatsToOverviewPage(const OpStats& op_stats,
                                          HardwareType hardware_type) {
  OverviewPageAnalysis analysis = ComputeAnalysisResult(op_stats);
  InputPipelineAnalysisResult input_analysis =
      ConvertOpStatsToInputPipelineAnalysis(op_stats, hardware_type);
  GenericBottleneck bottleneck = GenericOverallBottleneck(input_analysis);
  OverviewPageRecommendation recommendation =
      ComputeGenericRecommendation(bottleneck);
  SetCommonRecommendation(bottleneck.common, hardware_type, &recommendation);

  OverviewPage overview_page;
  *overview_page.mutable_run_environment() =
      ComputeRunEnvironment(op_stats.run_environment());
  *overview_page.mutable_analysis() = analysis;
  *overview_page.mutable_input_analysis() = input_analysis;
  *overview_page.mutable_recommendation() = recommendation;
  return overview_page;
}

}  // namespace profiler
}  // namespace tensorflow
<|endoftext|>


<commit_before>#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>

#define MAX_BUF 1024

#include <sstream>
#include <iostream>
#include <string>
#include <chrono>
using namespace std;
#include <boost/property_tree/json_parser.hpp>

const static double PI = 3.14159265;
const static int iConstRound = 60;
const static double iConstRoundLimit = sin(iConstRound*PI/180.0);

static int fd = -1;
#include <signal.h>
#include <stdio.h>
void sigcatch(int) {
	if(fd > 0) {
		close(fd);
	}
	exit(0);
}
int main(int ac,char*av[])
{
	system("rm -f /tmp/mpu.6050.unix.domain");
	if (SIG_ERR == signal(SIGINT, sigcatch)) {
		printf("failed to set signal handler.n");
		exit(1);
	}
     fd = socket( AF_LOCAL, SOCK_DGRAM, 0 );

	struct sockaddr_un addr;
	bzero( &addr, sizeof(addr) );
	addr.sun_family = AF_LOCAL;
	strcpy( addr.sun_path, "/tmp/mpu.6050.unix.domain" );

   int use = 1;
   if (::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &use, sizeof(int)) < 0) {
    perror("setsockopt(SO_REUSEADDR) failed");
   }

	struct timeval timeout;
	timeout.tv_sec = 0;
	timeout.tv_usec = 1000;
   	if (::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) {
	    	perror("setsockopt(SO_RCVTIMEO) failed");
   	}

   if(::bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0)
   {

     printf(" cannot bind socket: %d. \n",errno);
     close(fd);

     return 0;

   }

    char buf[MAX_BUF];
    double degree = 90.0;
    if(ac > 1) {
    	degree = ::atof(av[1]);
    }
    degree = std::fabs(degree);
    int iRound = degree/iConstRound;
    double dRemain = degree - (iRound *iConstRound);
    double startDeg = 0.0;
    bool restartBase = true;
    chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
    int msRun = 0;
    // 1000 ms
    while(msRun < 1000) {
    	chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
    	msRun = chrono::duration_cast<chrono::milliseconds>(end - start).count();
    	//printf("msRun=<%d>\n",msRun);

    	socklen_t len = sizeof(addr);
        int ret = ::recvfrom(fd, buf, MAX_BUF, 0, (struct sockaddr *)&addr, &len);
        if(ret>0){
            //printf("Received: %s\n", buf);
            string recvStr(buf,ret);
            //std::cout << recvStr << std::endl;
            std::stringstream ss;
            ss << recvStr;
            try {
            	boost::property_tree::ptree pt;
            	boost::property_tree::read_json(ss, pt);
            	auto current = pt.get<double>("yaw");
            	//std::cout <<  current << std::endl;
            	if(restartBase) {
            		startDeg = current;
            		restartBase = false;
            		continue;
            	}
            	double dRoundRad = 0.0;
            	if(iRound >0) {
            		dRoundRad = iConstRoundLimit;
            	} else {
            		dRoundRad = sin(PI*dRemain/180.0);
            	}
            	double diffDeg = std::fabs(current - startDeg);
            	/// over
            	if(diffDeg > iConstRound) {
            		diffDeg = std::fabs(360 -diffDeg);
            	}
            	double diffRad = (PI*diffDeg/180.0);
            	double diff = dRoundRad - sin(diffRad);
            	std::cout <<  "diff=<" << diff <<">"<< std::endl;
            	if(diff <=0) {
            		std::cout <<  "iRound=<" << iRound <<">"<< std::endl;
            		if(iRound >0) {
            			iRound--;
	            		restartBase = true;
            		}
            		else {
            			break;
            		}
            	}
            } catch(std::exception e) {
            	std::cout << e.what() << std::endl;
            }
        } else if (ret==0){
        	//printf("ret=<%d>\n",ret);
        } else {
        	//printf("ret=<%d>\n",ret);
        }
    }
    close(fd);

    return 0;
}
<commit_msg>Update turn.cpp<commit_after>#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>

#define MAX_BUF 1024

#include <sstream>
#include <iostream>
#include <string>
#include <chrono>
using namespace std;
#include <boost/property_tree/json_parser.hpp>

const static double PI = 3.14159265;
const static int iConstRound = 60;
const static double iConstRoundLimit = sin(iConstRound*PI/180.0);

static int fd = -1;
#include <signal.h>
#include <stdio.h>
void sigcatch(int) {
	if(fd > 0) {
		close(fd);
	}
	exit(0);
}
int main(int ac,char*av[])
{
	system("rm -f /tmp/mpu.6050.unix.domain");
	if (SIG_ERR == signal(SIGINT, sigcatch)) {
		printf("failed to set signal handler.n");
		exit(1);
	}
     fd = socket( AF_LOCAL, SOCK_DGRAM, 0 );

	struct sockaddr_un addr;
	bzero( &addr, sizeof(addr) );
	addr.sun_family = AF_LOCAL;
	strcpy( addr.sun_path, "/tmp/mpu.6050.unix.domain" );

   int use = 1;
   if (::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &use, sizeof(int)) < 0) {
    perror("setsockopt(SO_REUSEADDR) failed");
   }

	struct timeval timeout;
	timeout.tv_sec = 0;
	timeout.tv_usec = 1000;
   	if (::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) {
	    	perror("setsockopt(SO_RCVTIMEO) failed");
   	}

   if(::bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0)
   {

     printf(" cannot bind socket: %d. \n",errno);
     close(fd);

     return 0;

   }

    char buf[MAX_BUF];
    double degree = 90.0;
    if(ac > 1) {
    	degree = ::atof(av[1]);
    }
    degree = std::fabs(degree);
    int iRound = degree/iConstRound;
    double dRemain = degree - (iRound *iConstRound);
    double startDeg = 0.0;
    bool restartBase = true;
    chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
    int msRun = 0;
    // 1000 ms
    while(msRun < 1000) {
    	chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
    	msRun = chrono::duration_cast<chrono::milliseconds>(end - start).count();
    	//printf("msRun=<%d>\n",msRun);

    	socklen_t len = sizeof(addr);
        int ret = ::recvfrom(fd, buf, MAX_BUF, 0, (struct sockaddr *)&addr, &len);
        if(ret>0){
            //printf("Received: %s\n", buf);
            string recvStr(buf,ret);
            //std::cout << recvStr << std::endl;
            std::stringstream ss;
            ss << recvStr;
            try {
            	boost::property_tree::ptree pt;
            	boost::property_tree::read_json(ss, pt);
            	auto current = pt.get<double>("yaw");
            	//std::cout <<  current << std::endl;
            	if(restartBase) {
            		startDeg = current;
            		restartBase = false;
            		continue;
            	}
            	double dRoundRad = 0.0;
            	if(iRound >0) {
            		dRoundRad = iConstRoundLimit;
            	} else {
            		dRoundRad = sin(PI*dRemain/180.0);
            	}
            	double diffDeg = std::fabs(current - startDeg);
            	std::cout <<  "diffDeg=<" << diffDeg <<">"<< std::endl;
            	/// over
            	if(diffDeg > iConstRound) {
            		diffDeg = std::fabs(360 -diffDeg);
            	}
            	std::cout <<  "diffDeg=<" << diffDeg <<">"<< std::endl;
            	double diffRad = (PI*diffDeg/180.0);
            	double diff = dRoundRad - sin(diffRad);
            	std::cout <<  "diff=<" << diff <<">"<< std::endl;
            	if(diff <=0) {
            		std::cout <<  "iRound=<" << iRound <<">"<< std::endl;
            		if(iRound >0) {
            			iRound--;
	            		restartBase = true;
            		}
            		else {
            			break;
            		}
            	}
            } catch(std::exception e) {
            	std::cout << e.what() << std::endl;
            }
        } else if (ret==0){
        	//printf("ret=<%d>\n",ret);
        } else {
        	//printf("ret=<%d>\n",ret);
        }
    }
    close(fd);

    return 0;
}
<|endoftext|>


<commit_before>#include <osvr/ClientKit/Context.h>
#include <osvr/ClientKit/Interface.h>
#include <osvr/ClientKit/InterfaceStateC.h>

#include <windows.h>
#include <iostream>
#include <chrono>

// OSVR Helper Functions
namespace osvrMouseTracker
{
	double osvrQuatGetPitch(const OSVR_Quaternion *p)
	{
		return asin(2.0f * (osvrQuatGetX(p) * osvrQuatGetY(p) - osvrQuatGetW(p) * osvrQuatGetZ(p)));

	}

	double osvrQuatGetYaw(const OSVR_Quaternion *p)
	{
		return atan2(2.0f * osvrQuatGetX(p) * osvrQuatGetZ(p) + 2.0f * osvrQuatGetY(p) * osvrQuatGetW(p), 1.0f - 2.0f * (osvrQuatGetZ(p) * osvrQuatGetZ(p) + osvrQuatGetY(p) * osvrQuatGetY(p)));

	}

	double osvrQuatGetRoll(const OSVR_Quaternion *p)
	{
		return atan2(2.0f * osvrQuatGetX(p) * osvrQuatGetW(p) + 2.0f * osvrQuatGetZ(p) * osvrQuatGetY(p), 1.0f - 2.0f * (osvrQuatGetY(p) * osvrQuatGetY(p) + osvrQuatGetW(p) * osvrQuatGetW(p)));

	}

}

int main()
{
	osvr::clientkit::ClientContext context("com.osvr.MouseTracker");

	// HMD Interface: /me/head
	osvr::clientkit::Interface hmd = context.getInterface("/me/head");

	bool isInitState = false, isActive = false, isKeyDown = false, isKeyAction = false;
	OSVR_PoseState state, prevState;
	std::chrono::high_resolution_clock::time_point stateTime, prevStateTime;

	while (true)
	{
		// Update HMD Tracker State
		context.update();

		// Acquire Current HMD Orientation
		OSVR_TimeValue timestamp;
		OSVR_ReturnCode ret = osvrGetPoseState(hmd.get(), &timestamp, &state);
		stateTime = std::chrono::steady_clock::now();

		if (ret == OSVR_RETURN_SUCCESS)
		{
			// Toggle Mouse Tracking Using Shift Key
			isKeyDown = (GetAsyncKeyState(VK_SHIFT) >= 0);
			if (isKeyDown && !isKeyAction) isKeyAction = true;
			if (!isKeyDown && isKeyAction)
			{
				isActive = !isActive;
				isKeyAction = false;

			}

			if (isInitState && isActive)
			{
				// Calculate X-Axis Rotation From HMD Yaw
				double xAngle = osvrMouseTracker::osvrQuatGetYaw(&state.rotation);
				double xAnglePrev = osvrMouseTracker::osvrQuatGetYaw(&prevState.rotation);

				// Calculate Y-Axis Rotation From HMD Pitch
				double yAngle = osvrMouseTracker::osvrQuatGetPitch(&state.rotation);
				double yAnglePrev = osvrMouseTracker::osvrQuatGetPitch(&prevState.rotation);

				const double SCALING_FACTOR = 1000000.0f;
				const double SENSITIVITY = 20.0f;

				// Calculate X-Axis Rotation Delta
				int xCurAngle = (xAngle * (180 / 3.141592654)) * SCALING_FACTOR;
				int xPrevAngle = (xAnglePrev * (180 / 3.141592654)) * SCALING_FACTOR;
				if (xCurAngle < 0) xCurAngle += (360 * SCALING_FACTOR);
				if (xPrevAngle < 0) xPrevAngle += (360 * SCALING_FACTOR);
				int xDeltaAngle = (xCurAngle - xPrevAngle); // 360 (Turning Left) > 180 > 0 (Turning Right)

				// Calculate Y-Axis Rotation Delta
				int yCurAngle = (yAngle * (180 / 3.141592654)) * SCALING_FACTOR;
				int yPrevAngle = (yAnglePrev * (180 / 3.141592654)) * SCALING_FACTOR;
				int yDeltaAngle = (yCurAngle - yPrevAngle); // -90 (Facing Up) > 0 > 90 (Facing Down)

				auto elaspedTime = std::chrono::duration_cast<std::chrono::milliseconds>(stateTime - prevStateTime).count();

				if (elaspedTime >= 10)
				{
					double xDeltaPos = (static_cast<double>(xDeltaAngle) * elaspedTime / SCALING_FACTOR);
					double yDeltaPos = (static_cast<double>(yDeltaAngle) * elaspedTime / SCALING_FACTOR);
					std::cout << elaspedTime << "ms Elapsed, X: " << xCurAngle / SCALING_FACTOR << ", " << xDeltaPos << ", Y: " << yCurAngle / SCALING_FACTOR << ", " << yDeltaPos << std::endl;
					INPUT input;
					input.type = INPUT_MOUSE;
					input.mi.mouseData = 0;
					input.mi.dx = -xDeltaPos;
					input.mi.dy = yDeltaPos;
					//input.mi.dx = -(static_cast<float>(xDeltaAngle) / SCALING_FACTOR) * SENSITIVITY;// *(65536.0f / GetSystemMetrics(SM_CXSCREEN));
					//input.mi.dy = -(static_cast<float>(yDeltaAngle) / SCALING_FACTOR) * SENSITIVITY;// *(65536.0f / GetSystemMetrics(SM_CYSCREEN));
					input.mi.dwFlags = MOUSEEVENTF_MOVE;// | MOUSEEVENTF_ABSOLUTE;
					SendInput(1, &input, sizeof(input));

					//POINT mousepos;
					//GetCursorPos(&mousepos);
					//SetCursorPos(mousepos.x - static_cast<int>(static_cast<float>(xDeltaAngle) / SCALING_FACTOR) * SENSITIVITY, mousepos.y - static_cast<int>(static_cast<float>(yDeltaAngle) / SCALING_FACTOR) * SENSITIVITY);

					prevState = state;
					prevStateTime = stateTime;

				}

			}
			else
			{
				isInitState = true;
				prevState = state;
				prevStateTime = stateTime;

			}

		}

	}

	return 0;

}
<commit_msg>Switched to calculating mouse delta using HMD's angular velocity report to eliminate euler angle singularities.<commit_after>#include <osvr/ClientKit/Context.h>
#include <osvr/ClientKit/Interface.h>
#include <osvr/ClientKit/InterfaceStateC.h>

#include <windows.h>
#include <iostream>
#include <chrono>

// OSVR Helper Functions
namespace osvrMathHelpers
{
	// Extract Pitch Angle From Quaternion
	double osvrQuatGetPitch(const OSVR_Quaternion *q)
	{
		return asin(2.0f * (osvrQuatGetX(q) * osvrQuatGetY(q) - osvrQuatGetW(q) * osvrQuatGetZ(q)));

	}

	// Extract Yaw Angle From Quaternion
	double osvrQuatGetYaw(const OSVR_Quaternion *q)
	{
		return atan2(2.0f * osvrQuatGetX(q) * osvrQuatGetZ(q) + 2.0f * osvrQuatGetY(q) * osvrQuatGetW(q), 1.0f - 2.0f * (osvrQuatGetZ(q) * osvrQuatGetZ(q) + osvrQuatGetY(q) * osvrQuatGetY(q)));

	}

	// Extract Roll Angle From Quaternion
	double osvrQuatGetRoll(const OSVR_Quaternion *q)
	{
		return atan2(2.0f * osvrQuatGetX(q) * osvrQuatGetW(q) + 2.0f * osvrQuatGetZ(q) * osvrQuatGetY(q), 1.0f - 2.0f * (osvrQuatGetY(q) * osvrQuatGetY(q) + osvrQuatGetW(q) * osvrQuatGetW(q)));

	}

}

int main()
{
	osvr::clientkit::ClientContext context("com.osvr.MouseTracker");

	// HMD Interface: /me/head
	osvr::clientkit::Interface hmd = context.getInterface("/me/head");

	bool isInitState = false, isActive = false, isKeyDown = false, isKeyAction = false;
	OSVR_AngularVelocityState angularVelocityState, prevAngularVelocityState;
	std::chrono::high_resolution_clock::time_point stateTime, prevStateTime = std::chrono::steady_clock::now();

	while (true)
	{
		stateTime = std::chrono::steady_clock::now();
		auto elaspedTime = std::chrono::duration_cast<std::chrono::milliseconds>(stateTime - prevStateTime).count();

		// Update HMD Tracker State Every 10ms
		if (elaspedTime >= 10)
		{
			// Update HMD Tracker State
			context.update();

			// Acquire Current HMD Orientation
			OSVR_TimeValue timestamp;
			OSVR_ReturnCode ret = osvrGetAngularVelocityState(hmd.get(), &timestamp, &angularVelocityState);

			// Toggle Mouse Tracking Using Shift Key
			isKeyDown = (GetAsyncKeyState(VK_SHIFT) >= 0);
			if (isKeyDown && !isKeyAction) isKeyAction = true;
			if (!isKeyDown && isKeyAction)
			{
				isActive = !isActive;
				isKeyAction = false;

			}

			if (ret == OSVR_RETURN_SUCCESS)
			{
				if (isInitState && isActive)
				{
					const double SCALING_FACTOR = 1000000.0f;
					const double SENSITIVITY = 5.0f;

					// Calculate X-Axis Rotation Delta From HMD Pitch
					double xAngle = osvrMathHelpers::osvrQuatGetPitch(&angularVelocityState.incrementalRotation);
					int xDeltaAngle = (xAngle * (180 / 3.141592654)) * SCALING_FACTOR;

					// Calculate Y-Axis Rotation Delta From HMD Yaw
					double yAngle = osvrMathHelpers::osvrQuatGetYaw(&angularVelocityState.incrementalRotation);
					int yDeltaAngle = (yAngle * (180 / 3.141592654)) * SCALING_FACTOR;

					double xDeltaPos = (static_cast<double>(xDeltaAngle) * elaspedTime / SCALING_FACTOR) * SENSITIVITY;
					double yDeltaPos = (static_cast<double>(yDeltaAngle) * elaspedTime / SCALING_FACTOR) * SENSITIVITY;

					INPUT input;
					input.type = INPUT_MOUSE;
					input.mi.mouseData = 0;
					input.mi.dx = xDeltaPos;
					input.mi.dy = yDeltaPos;
					input.mi.dwFlags = MOUSEEVENTF_MOVE;
					SendInput(1, &input, sizeof(input));

					prevAngularVelocityState = angularVelocityState;
					prevStateTime = stateTime;

				}
				else
				{
					isInitState = true;
					prevAngularVelocityState = angularVelocityState;
					prevStateTime = stateTime;

				}

			}

		}

	}

	return 0;

}
<|endoftext|>


<commit_before>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//    * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//    * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "config.h"

#if ENABLE(SVG)
#include "SVGPaintServerSolid.h"

#include "GraphicsContext.h"
#include "RenderPath.h"
#include "SkiaSupport.h"

#include <SkPaintContext.h>
#include "SkiaUtils.h"

namespace WebCore {

// TODO(jhaas): probably there's already an implementation of this somewhere; find it
  inline int FloatAlphaToInt(float alpha) { return std::min(0xFF, std::max(0, static_cast<int>(alpha * 0xFF))); }

bool SVGPaintServerSolid::setup(GraphicsContext*& context, const RenderObject* object, SVGPaintTargetType type, bool isPaintingText) const
{
    const RenderStyle* style = object ? object->style() : NULL;
    const SVGRenderStyle* svgStyle = style ? style->svgStyle() : NULL;

    int red = color().red();
    int green = color().green();
    int blue = color().blue();
    int alpha = color().alpha();

    if ((type & ApplyToFillTargetType) && (!svgStyle || svgStyle->hasFill())) {
        if (svgStyle) {
            alpha = FloatAlphaToInt(svgStyle->fillOpacity());
            context->setFillRule(svgStyle->fillRule());
        }

        if (isPaintingText)
            context->setTextDrawingMode(cTextFill);

        context->setFillColor(SkColorSetARGB(alpha, red, green, blue));
    }

    if ((type & ApplyToStrokeTargetType) && (!svgStyle || svgStyle->hasStroke())) {
        if (svgStyle) {
            alpha = FloatAlphaToInt(svgStyle->strokeOpacity());
            context->setStrokeColor(SkColorSetARGB(alpha, red, green, blue));
        }

        if (isPaintingText)
            context->setTextDrawingMode(cTextStroke);

        applyStrokeStyleToContext(context, style, object);
    }

    return true;
}

} // namespace WebCore

#endif
<commit_msg>Add missing file from my last checkin moving Skia painting objects around. Review URL: http://codereview.chromium.org/8759<commit_after>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//    * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//    * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "config.h"

#if ENABLE(SVG)
#include "SVGPaintServerSolid.h"

#include "GraphicsContext.h"
#include "RenderPath.h"
#include "SkiaSupport.h"

#include "SkiaUtils.h"

namespace WebCore {

// TODO(jhaas): probably there's already an implementation of this somewhere; find it
  inline int FloatAlphaToInt(float alpha) { return std::min(0xFF, std::max(0, static_cast<int>(alpha * 0xFF))); }

bool SVGPaintServerSolid::setup(GraphicsContext*& context, const RenderObject* object, SVGPaintTargetType type, bool isPaintingText) const
{
    const RenderStyle* style = object ? object->style() : NULL;
    const SVGRenderStyle* svgStyle = style ? style->svgStyle() : NULL;

    int red = color().red();
    int green = color().green();
    int blue = color().blue();
    int alpha = color().alpha();

    if ((type & ApplyToFillTargetType) && (!svgStyle || svgStyle->hasFill())) {
        if (svgStyle) {
            alpha = FloatAlphaToInt(svgStyle->fillOpacity());
            context->setFillRule(svgStyle->fillRule());
        }

        if (isPaintingText)
            context->setTextDrawingMode(cTextFill);

        context->setFillColor(SkColorSetARGB(alpha, red, green, blue));
    }

    if ((type & ApplyToStrokeTargetType) && (!svgStyle || svgStyle->hasStroke())) {
        if (svgStyle) {
            alpha = FloatAlphaToInt(svgStyle->strokeOpacity());
            context->setStrokeColor(SkColorSetARGB(alpha, red, green, blue));
        }

        if (isPaintingText)
            context->setTextDrawingMode(cTextStroke);

        applyStrokeStyleToContext(context, style, object);
    }

    return true;
}

} // namespace WebCore

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: uielementwrapperbase.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 14:01:27 $
 *
 *  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_framework.hxx"

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_HELPER_UIELEMENTWRAPPERBASE_HXX_
#include <helper/uielementwrapperbase.hxx>
#endif

#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif

#ifndef __FRAMEWORK_PROPERTIES_H_
#include <properties.h>
#endif

#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

const int UIELEMENT_PROPHANDLE_RESOURCEURL  = 1;
const int UIELEMENT_PROPHANDLE_TYPE         = 2;
const int UIELEMENT_PROPHANDLE_FRAME        = 3;
const int UIELEMENT_PROPCOUNT               = 3;
const rtl::OUString UIELEMENT_PROPNAME_RESOURCEURL( RTL_CONSTASCII_USTRINGPARAM( "ResourceURL" ));
const rtl::OUString UIELEMENT_PROPNAME_TYPE( RTL_CONSTASCII_USTRINGPARAM( "Type" ));
const rtl::OUString UIELEMENT_PROPNAME_FRAME( RTL_CONSTASCII_USTRINGPARAM( "Frame" ));

using namespace rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;

namespace framework
{

//*****************************************************************************************************************
//  XInterface, XTypeProvider
//*****************************************************************************************************************
DEFINE_XINTERFACE_8     (   UIElementWrapperBase                                            ,
                            OWeakObject                                                     ,
                            DIRECT_INTERFACE( ::com::sun::star::lang::XTypeProvider         ),
                            DIRECT_INTERFACE( ::com::sun::star::ui::XUIElement      ),
                            DIRECT_INTERFACE( ::com::sun::star::beans::XMultiPropertySet    ),
                            DIRECT_INTERFACE( ::com::sun::star::beans::XFastPropertySet     ),
                            DIRECT_INTERFACE( ::com::sun::star::beans::XPropertySet         ),
                            DIRECT_INTERFACE( ::com::sun::star::lang::XInitialization       ),
                            DIRECT_INTERFACE( ::com::sun::star::util::XUpdatable            ),
                            DIRECT_INTERFACE( ::com::sun::star::lang::XComponent            )
                        )

DEFINE_XTYPEPROVIDER_8  (   UIElementWrapperBase                        ,
                            ::com::sun::star::lang::XTypeProvider       ,
                            ::com::sun::star::ui::XUIElement    ,
                            ::com::sun::star::beans::XMultiPropertySet  ,
                            ::com::sun::star::beans::XFastPropertySet   ,
                            ::com::sun::star::beans::XPropertySet       ,
                            ::com::sun::star::lang::XInitialization     ,
                            ::com::sun::star::util::XUpdatable          ,
                            ::com::sun::star::lang::XComponent
                        )

UIElementWrapperBase::UIElementWrapperBase( sal_Int16 nType )
    :   ThreadHelpBase              ( &Application::GetSolarMutex()                      )
    ,   ::cppu::OBroadcastHelperVar< ::cppu::OMultiTypeInterfaceContainerHelper, ::cppu::OMultiTypeInterfaceContainerHelper::keyType >( m_aLock.getShareableOslMutex() )
    ,   ::cppu::OPropertySetHelper  ( *(static_cast< ::cppu::OBroadcastHelper* >(this)) )
    ,   ::cppu::OWeakObject         (                                                   )
    ,   m_aListenerContainer        ( m_aLock.getShareableOslMutex()                    )
    ,   m_nType                     ( nType                                             )
    ,   m_bInitialized              ( sal_False                                         )
    ,   m_bDisposed                 ( sal_False                                         )
{
}

UIElementWrapperBase::~UIElementWrapperBase()
{
}

void SAL_CALL UIElementWrapperBase::dispose() throw (::com::sun::star::uno::RuntimeException)
{
    // must be implemented by derived class
    ResetableGuard aLock( m_aLock );
    m_bDisposed = sal_True;
}

void SAL_CALL UIElementWrapperBase::addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException)
{
    m_aListenerContainer.addInterface( ::getCppuType( ( const css::uno::Reference< css::lang::XEventListener >* ) NULL ), xListener );
}

void SAL_CALL UIElementWrapperBase::removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException)
{
    m_aListenerContainer.removeInterface( ::getCppuType( ( const css::uno::Reference< css::lang::XEventListener >* ) NULL ), xListener );
}

void SAL_CALL UIElementWrapperBase::initialize( const Sequence< Any >& aArguments )
throw ( Exception, RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( !m_bInitialized )
    {
        for ( sal_Int32 n = 0; n < aArguments.getLength(); n++ )
        {
            PropertyValue aPropValue;
            if ( aArguments[n] >>= aPropValue )
            {
                if ( aPropValue.Name.equalsAscii( "ResourceURL" ))
                    aPropValue.Value >>= m_aResourceURL;
                else if ( aPropValue.Name.equalsAscii( "Frame" ))
                {
                    Reference< XFrame > xFrame;
                    aPropValue.Value >>= xFrame;
                    m_xWeakFrame = xFrame;
                }
            }
        }

        m_bInitialized = sal_True;
    }
}

// XUpdatable
void SAL_CALL UIElementWrapperBase::update() throw (::com::sun::star::uno::RuntimeException)
{
    // can be implemented by derived class
}

// XPropertySet helper
sal_Bool SAL_CALL UIElementWrapperBase::convertFastPropertyValue( Any&       /*aConvertedValue*/ ,
                                                                  Any&       /*aOldValue*/       ,
                                                                  sal_Int32  /*nHandle*/         ,
                                                                  const Any& /*aValue*/             ) throw( com::sun::star::lang::IllegalArgumentException )
{
    //  Initialize state with FALSE !!!
    //  (Handle can be invalid)
    return sal_False ;
}

void SAL_CALL UIElementWrapperBase::setFastPropertyValue_NoBroadcast(   sal_Int32               /*nHandle*/ ,
                                                                        const com::sun::star::uno::Any&    /*aValue*/  ) throw( com::sun::star::uno::Exception )
{
}

void SAL_CALL UIElementWrapperBase::getFastPropertyValue( com::sun::star::uno::Any& aValue  ,
                                                          sal_Int32      nHandle                ) const
{
    switch( nHandle )
    {
        case UIELEMENT_PROPHANDLE_RESOURCEURL:
            aValue <<= m_aResourceURL;
            break;
        case UIELEMENT_PROPHANDLE_TYPE:
            aValue <<= m_nType;
            break;
        case UIELEMENT_PROPHANDLE_FRAME:
            Reference< XFrame > xFrame( m_xWeakFrame );
            aValue <<= xFrame;
            break;
    }
}

::cppu::IPropertyArrayHelper& SAL_CALL UIElementWrapperBase::getInfoHelper()
{
    // Optimize this method !
    // We initialize a static variable only one time. And we don't must use a mutex at every call!
    // For the first call; pInfoHelper is NULL - for the second call pInfoHelper is different from NULL!
    static ::cppu::OPropertyArrayHelper* pInfoHelper = NULL;

    if( pInfoHelper == NULL )
    {
        // Ready for multithreading
        osl::MutexGuard aGuard( osl::Mutex::getGlobalMutex() ) ;

        // Control this pointer again, another instance can be faster then these!
        if( pInfoHelper == NULL )
        {
            // Define static member to give structure of properties to baseclass "OPropertySetHelper".
            // "impl_getStaticPropertyDescriptor" is a non exported and static funtion, who will define a static propertytable.
            // "sal_True" say: Table is sorted by name.
            static ::cppu::OPropertyArrayHelper aInfoHelper( impl_getStaticPropertyDescriptor(), sal_True );
            pInfoHelper = &aInfoHelper;
        }
    }

    return(*pInfoHelper);
}

com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > SAL_CALL UIElementWrapperBase::getPropertySetInfo() throw (::com::sun::star::uno::RuntimeException)
{
    // Optimize this method !
    // We initialize a static variable only one time. And we don't must use a mutex at every call!
    // For the first call; pInfo is NULL - for the second call pInfo is different from NULL!
    static com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo >* pInfo = NULL;

    if( pInfo == NULL )
    {
        // Ready for multithreading
        osl::MutexGuard aGuard( osl::Mutex::getGlobalMutex() ) ;
        // Control this pointer again, another instance can be faster then these!
        if( pInfo == NULL )
        {
            // Create structure of propertysetinfo for baseclass "OPropertySetHelper".
            // (Use method "getInfoHelper()".)
            static com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
            pInfo = &xInfo;
        }
    }

    return (*pInfo);
}

const com::sun::star::uno::Sequence< com::sun::star::beans::Property > UIElementWrapperBase::impl_getStaticPropertyDescriptor()
{
    // Create a new static property array to initialize sequence!
    // Table of all predefined properties of this class. Its used from OPropertySetHelper-class!
    // Don't forget to change the defines (see begin of this file), if you add, change or delete a property in this list!!!
    // It's necessary for methods of OPropertySetHelper.
    // ATTENTION:
    //      YOU MUST SORT FOLLOW TABLE BY NAME ALPHABETICAL !!!

    static const com::sun::star::beans::Property pProperties[] =
    {
        com::sun::star::beans::Property( UIELEMENT_PROPNAME_FRAME         , UIELEMENT_PROPHANDLE_FRAME          , ::getCppuType((Reference< XFrame >*)NULL), com::sun::star::beans::PropertyAttribute::TRANSIENT | com::sun::star::beans::PropertyAttribute::READONLY ),
        com::sun::star::beans::Property( UIELEMENT_PROPNAME_RESOURCEURL   , UIELEMENT_PROPHANDLE_RESOURCEURL    , ::getCppuType((sal_Int16*)NULL), com::sun::star::beans::PropertyAttribute::TRANSIENT | com::sun::star::beans::PropertyAttribute::READONLY ),
        com::sun::star::beans::Property( UIELEMENT_PROPNAME_TYPE          , UIELEMENT_PROPHANDLE_TYPE           , ::getCppuType((const ::rtl::OUString*)NULL), com::sun::star::beans::PropertyAttribute::TRANSIENT | com::sun::star::beans::PropertyAttribute::READONLY )
    };
    // Use it to initialize sequence!
    static const com::sun::star::uno::Sequence< com::sun::star::beans::Property > lPropertyDescriptor( pProperties, UIELEMENT_PROPCOUNT );
    // Return static "PropertyDescriptor"
    return lPropertyDescriptor;
}

}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.262); FILE MERGED 2008/04/01 15:18:39 thb 1.7.262.3: #i85898# Stripping all external header guards 2008/04/01 10:58:07 thb 1.7.262.2: #i85898# Stripping all external header guards 2008/03/28 15:35:17 rt 1.7.262.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: uielementwrapperbase.cxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________
#include <helper/uielementwrapperbase.hxx>
#include <general.h>
#include <properties.h>
#include <threadhelp/resetableguard.hxx>

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________
#include <vcl/svapp.hxx>

const int UIELEMENT_PROPHANDLE_RESOURCEURL  = 1;
const int UIELEMENT_PROPHANDLE_TYPE         = 2;
const int UIELEMENT_PROPHANDLE_FRAME        = 3;
const int UIELEMENT_PROPCOUNT               = 3;
const rtl::OUString UIELEMENT_PROPNAME_RESOURCEURL( RTL_CONSTASCII_USTRINGPARAM( "ResourceURL" ));
const rtl::OUString UIELEMENT_PROPNAME_TYPE( RTL_CONSTASCII_USTRINGPARAM( "Type" ));
const rtl::OUString UIELEMENT_PROPNAME_FRAME( RTL_CONSTASCII_USTRINGPARAM( "Frame" ));

using namespace rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;

namespace framework
{

//*****************************************************************************************************************
//  XInterface, XTypeProvider
//*****************************************************************************************************************
DEFINE_XINTERFACE_8     (   UIElementWrapperBase                                            ,
                            OWeakObject                                                     ,
                            DIRECT_INTERFACE( ::com::sun::star::lang::XTypeProvider         ),
                            DIRECT_INTERFACE( ::com::sun::star::ui::XUIElement      ),
                            DIRECT_INTERFACE( ::com::sun::star::beans::XMultiPropertySet    ),
                            DIRECT_INTERFACE( ::com::sun::star::beans::XFastPropertySet     ),
                            DIRECT_INTERFACE( ::com::sun::star::beans::XPropertySet         ),
                            DIRECT_INTERFACE( ::com::sun::star::lang::XInitialization       ),
                            DIRECT_INTERFACE( ::com::sun::star::util::XUpdatable            ),
                            DIRECT_INTERFACE( ::com::sun::star::lang::XComponent            )
                        )

DEFINE_XTYPEPROVIDER_8  (   UIElementWrapperBase                        ,
                            ::com::sun::star::lang::XTypeProvider       ,
                            ::com::sun::star::ui::XUIElement    ,
                            ::com::sun::star::beans::XMultiPropertySet  ,
                            ::com::sun::star::beans::XFastPropertySet   ,
                            ::com::sun::star::beans::XPropertySet       ,
                            ::com::sun::star::lang::XInitialization     ,
                            ::com::sun::star::util::XUpdatable          ,
                            ::com::sun::star::lang::XComponent
                        )

UIElementWrapperBase::UIElementWrapperBase( sal_Int16 nType )
    :   ThreadHelpBase              ( &Application::GetSolarMutex()                      )
    ,   ::cppu::OBroadcastHelperVar< ::cppu::OMultiTypeInterfaceContainerHelper, ::cppu::OMultiTypeInterfaceContainerHelper::keyType >( m_aLock.getShareableOslMutex() )
    ,   ::cppu::OPropertySetHelper  ( *(static_cast< ::cppu::OBroadcastHelper* >(this)) )
    ,   ::cppu::OWeakObject         (                                                   )
    ,   m_aListenerContainer        ( m_aLock.getShareableOslMutex()                    )
    ,   m_nType                     ( nType                                             )
    ,   m_bInitialized              ( sal_False                                         )
    ,   m_bDisposed                 ( sal_False                                         )
{
}

UIElementWrapperBase::~UIElementWrapperBase()
{
}

void SAL_CALL UIElementWrapperBase::dispose() throw (::com::sun::star::uno::RuntimeException)
{
    // must be implemented by derived class
    ResetableGuard aLock( m_aLock );
    m_bDisposed = sal_True;
}

void SAL_CALL UIElementWrapperBase::addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException)
{
    m_aListenerContainer.addInterface( ::getCppuType( ( const css::uno::Reference< css::lang::XEventListener >* ) NULL ), xListener );
}

void SAL_CALL UIElementWrapperBase::removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException)
{
    m_aListenerContainer.removeInterface( ::getCppuType( ( const css::uno::Reference< css::lang::XEventListener >* ) NULL ), xListener );
}

void SAL_CALL UIElementWrapperBase::initialize( const Sequence< Any >& aArguments )
throw ( Exception, RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( !m_bInitialized )
    {
        for ( sal_Int32 n = 0; n < aArguments.getLength(); n++ )
        {
            PropertyValue aPropValue;
            if ( aArguments[n] >>= aPropValue )
            {
                if ( aPropValue.Name.equalsAscii( "ResourceURL" ))
                    aPropValue.Value >>= m_aResourceURL;
                else if ( aPropValue.Name.equalsAscii( "Frame" ))
                {
                    Reference< XFrame > xFrame;
                    aPropValue.Value >>= xFrame;
                    m_xWeakFrame = xFrame;
                }
            }
        }

        m_bInitialized = sal_True;
    }
}

// XUpdatable
void SAL_CALL UIElementWrapperBase::update() throw (::com::sun::star::uno::RuntimeException)
{
    // can be implemented by derived class
}

// XPropertySet helper
sal_Bool SAL_CALL UIElementWrapperBase::convertFastPropertyValue( Any&       /*aConvertedValue*/ ,
                                                                  Any&       /*aOldValue*/       ,
                                                                  sal_Int32  /*nHandle*/         ,
                                                                  const Any& /*aValue*/             ) throw( com::sun::star::lang::IllegalArgumentException )
{
    //  Initialize state with FALSE !!!
    //  (Handle can be invalid)
    return sal_False ;
}

void SAL_CALL UIElementWrapperBase::setFastPropertyValue_NoBroadcast(   sal_Int32               /*nHandle*/ ,
                                                                        const com::sun::star::uno::Any&    /*aValue*/  ) throw( com::sun::star::uno::Exception )
{
}

void SAL_CALL UIElementWrapperBase::getFastPropertyValue( com::sun::star::uno::Any& aValue  ,
                                                          sal_Int32      nHandle                ) const
{
    switch( nHandle )
    {
        case UIELEMENT_PROPHANDLE_RESOURCEURL:
            aValue <<= m_aResourceURL;
            break;
        case UIELEMENT_PROPHANDLE_TYPE:
            aValue <<= m_nType;
            break;
        case UIELEMENT_PROPHANDLE_FRAME:
            Reference< XFrame > xFrame( m_xWeakFrame );
            aValue <<= xFrame;
            break;
    }
}

::cppu::IPropertyArrayHelper& SAL_CALL UIElementWrapperBase::getInfoHelper()
{
    // Optimize this method !
    // We initialize a static variable only one time. And we don't must use a mutex at every call!
    // For the first call; pInfoHelper is NULL - for the second call pInfoHelper is different from NULL!
    static ::cppu::OPropertyArrayHelper* pInfoHelper = NULL;

    if( pInfoHelper == NULL )
    {
        // Ready for multithreading
        osl::MutexGuard aGuard( osl::Mutex::getGlobalMutex() ) ;

        // Control this pointer again, another instance can be faster then these!
        if( pInfoHelper == NULL )
        {
            // Define static member to give structure of properties to baseclass "OPropertySetHelper".
            // "impl_getStaticPropertyDescriptor" is a non exported and static funtion, who will define a static propertytable.
            // "sal_True" say: Table is sorted by name.
            static ::cppu::OPropertyArrayHelper aInfoHelper( impl_getStaticPropertyDescriptor(), sal_True );
            pInfoHelper = &aInfoHelper;
        }
    }

    return(*pInfoHelper);
}

com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > SAL_CALL UIElementWrapperBase::getPropertySetInfo() throw (::com::sun::star::uno::RuntimeException)
{
    // Optimize this method !
    // We initialize a static variable only one time. And we don't must use a mutex at every call!
    // For the first call; pInfo is NULL - for the second call pInfo is different from NULL!
    static com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo >* pInfo = NULL;

    if( pInfo == NULL )
    {
        // Ready for multithreading
        osl::MutexGuard aGuard( osl::Mutex::getGlobalMutex() ) ;
        // Control this pointer again, another instance can be faster then these!
        if( pInfo == NULL )
        {
            // Create structure of propertysetinfo for baseclass "OPropertySetHelper".
            // (Use method "getInfoHelper()".)
            static com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
            pInfo = &xInfo;
        }
    }

    return (*pInfo);
}

const com::sun::star::uno::Sequence< com::sun::star::beans::Property > UIElementWrapperBase::impl_getStaticPropertyDescriptor()
{
    // Create a new static property array to initialize sequence!
    // Table of all predefined properties of this class. Its used from OPropertySetHelper-class!
    // Don't forget to change the defines (see begin of this file), if you add, change or delete a property in this list!!!
    // It's necessary for methods of OPropertySetHelper.
    // ATTENTION:
    //      YOU MUST SORT FOLLOW TABLE BY NAME ALPHABETICAL !!!

    static const com::sun::star::beans::Property pProperties[] =
    {
        com::sun::star::beans::Property( UIELEMENT_PROPNAME_FRAME         , UIELEMENT_PROPHANDLE_FRAME          , ::getCppuType((Reference< XFrame >*)NULL), com::sun::star::beans::PropertyAttribute::TRANSIENT | com::sun::star::beans::PropertyAttribute::READONLY ),
        com::sun::star::beans::Property( UIELEMENT_PROPNAME_RESOURCEURL   , UIELEMENT_PROPHANDLE_RESOURCEURL    , ::getCppuType((sal_Int16*)NULL), com::sun::star::beans::PropertyAttribute::TRANSIENT | com::sun::star::beans::PropertyAttribute::READONLY ),
        com::sun::star::beans::Property( UIELEMENT_PROPNAME_TYPE          , UIELEMENT_PROPHANDLE_TYPE           , ::getCppuType((const ::rtl::OUString*)NULL), com::sun::star::beans::PropertyAttribute::TRANSIENT | com::sun::star::beans::PropertyAttribute::READONLY )
    };
    // Use it to initialize sequence!
    static const com::sun::star::uno::Sequence< com::sun::star::beans::Property > lPropertyDescriptor( pProperties, UIELEMENT_PROPCOUNT );
    // Return static "PropertyDescriptor"
    return lPropertyDescriptor;
}

}
<|endoftext|>


<commit_before>// Copyright (c) 2015-2016 The Gulden developers
// Authored by: Malcolm MacLeod (mmacleod@webmail.co.za)
// Distributed under the GULDEN software license, see the accompanying
// file COPYING

#ifdef __APPLE__
    #include <TargetConditionals.h>
#endif
#include "diff_common.h"
#include "diff_delta.h"
#include "diff_old.h"

#ifdef BUILD_IOS
#include "BRMerkleBlock.h"
#endif

#ifdef __JAVA__
package org.bitcoinj.core;
import org.bitcoinj.store.BlockStore;
import java.math.BigInteger;
import org.bitcoinj.store.BlockStoreException;
public class CommonDiff extends DeltaDiff {
public static int nDeltaSwitchoverBlock = DIFF_SWITCHOVER(550000, 250000);
public static int nOldDiffSwitchoverBlock = DIFF_SWITCHOVER(200, 437600);
public static
#endif
unsigned int GetNextWorkRequired(const INDEX_TYPE indexLast, const BLOCK_TYPE block, unsigned int nPowTargetSpacing, unsigned int nPowLimit
#ifdef __JAVA__
,final BlockStore blockStore
#endif
)
{
    #ifndef __JAVA__
    static int nDeltaSwitchoverBlock = DIFF_SWITCHOVER(550000, 250000);
    static int nOldDiffSwitchoverBlock = DIFF_SWITCHOVER(200, 437600);
    #endif

    if (INDEX_HEIGHT(indexLast)+1 >= nOldDiffSwitchoverBlock)
    {
        if (INDEX_HEIGHT(indexLast)+1 >= nDeltaSwitchoverBlock)
        {
            #ifdef __JAVA__
            return GetNextWorkRequired_DELTA(indexLast, block, (int)nPowTargetSpacing, nPowLimit, nDeltaSwitchoverBlock, blockStore);
            #else
            return GetNextWorkRequired_DELTA(indexLast, block, nPowTargetSpacing, nPowLimit, nDeltaSwitchoverBlock);
            #endif
        }
        else
        {
            return 524287999;
        }
    }
    return diff_old(INDEX_HEIGHT(indexLast)+1, nPowLimit);
}

#ifdef __JAVA__
}
#endif
<commit_msg>Revert previous change.<commit_after>// Copyright (c) 2015-2016 The Gulden developers
// Authored by: Malcolm MacLeod (mmacleod@webmail.co.za)
// Distributed under the GULDEN software license, see the accompanying
// file COPYING

#ifdef __APPLE__
    #include <TargetConditionals.h>
#endif
#include "diff_common.h"
#include "diff_delta.h"
#include "diff_old.h"

#ifdef BUILD_IOS
#include "BRMerkleBlock.h"
#endif

#ifdef __JAVA__
package org.bitcoinj.core;
import org.bitcoinj.store.BlockStore;
import java.math.BigInteger;
import org.bitcoinj.store.BlockStoreException;
public class CommonDiff extends DeltaDiff {
public static int nDeltaSwitchoverBlock = DIFF_SWITCHOVER(350000, 250000);
public static int nOldDiffSwitchoverBlock = DIFF_SWITCHOVER(200, 437600);
public static
#endif
unsigned int GetNextWorkRequired(const INDEX_TYPE indexLast, const BLOCK_TYPE block, unsigned int nPowTargetSpacing, unsigned int nPowLimit
#ifdef __JAVA__
,final BlockStore blockStore
#endif
)
{
    #ifndef __JAVA__
    static int nDeltaSwitchoverBlock = DIFF_SWITCHOVER(350000, 250000);
    static int nOldDiffSwitchoverBlock = DIFF_SWITCHOVER(200, 437600);
    #endif

    if (INDEX_HEIGHT(indexLast)+1 >= nOldDiffSwitchoverBlock)
    {
        if (INDEX_HEIGHT(indexLast)+1 >= nDeltaSwitchoverBlock)
        {
            #ifdef __JAVA__
            return GetNextWorkRequired_DELTA(indexLast, block, (int)nPowTargetSpacing, nPowLimit, nDeltaSwitchoverBlock, blockStore);
            #else
            return GetNextWorkRequired_DELTA(indexLast, block, nPowTargetSpacing, nPowLimit, nDeltaSwitchoverBlock);
            #endif
        }
        else
        {
            return 524287999;
        }
    }
    return diff_old(INDEX_HEIGHT(indexLast)+1, nPowLimit);
}

#ifdef __JAVA__
}
#endif
<|endoftext|>


<commit_before>/*
   Copyright 2011 StormMQ Limited

   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 <TestHarness.h>
#include "Thread/Thread.h"
#include "Thread/FastMutex.h"

#include "debug_helper.h"

SUITE(Thread)
{
    class ThreadFixture
    {
    public:
        ThreadFixture() : saved_from_thread(0)
        {
            amqp_threading_initialize();
            amqp_mutex_initialize(&mutex);
            amqp_condition_initialize(&cv);
        }

        ~ThreadFixture()
        {
            amqp_condition_destroy(&cv);
            amqp_mutex_destroy(&mutex);
            amqp_threading_cleanup();
        }

        const char *saved_from_thread;

        amqp_mutex_t mutex;
        amqp_condition_variable_t cv;

        static const char *pattern;
        static void handler(void *argument);
    private:
    };

    const char *ThreadFixture::pattern = "HeLlO wOrLd";
    void ThreadFixture::handler(void *argument)
    {
        ThreadFixture *fixture = (ThreadFixture *) argument;
        amqp_mutex_lock(&fixture->mutex);

        fixture->saved_from_thread = ThreadFixture::pattern;

        amqp_condition_notify(&fixture->cv);

        amqp_mutex_unlock(&fixture->mutex);
    }

    // Not really proof that the threading wrappers do the right thing.
    TEST_FIXTURE(ThreadFixture, exercise_thread_api)
    {
        CHECK_EQUAL((void *) 0, saved_from_thread);

        amqp_mutex_lock(&mutex);
        amqp_thread_t *thread = amqp_thread_start(ThreadFixture::handler, this);
        amqp_condition_wait(&cv, &mutex);
        amqp_mutex_unlock(&mutex);

        amqp_thread_destroy(thread);

        CHECK_EQUAL(pattern, saved_from_thread);
    }

    class FastMutexFixture
    {
    public:
        FastMutexFixture() : count(0), thread_done_count(0), thread_ready_count(0)
        {
            amqp_threading_initialize();
            amqp_fast_mutex_initialize(&fast_mutex);
            amqp_mutex_initialize(&mutex);
            amqp_condition_initialize(&cv);
            amqp_condition_initialize(&cv_gate);
        }

        ~FastMutexFixture()
        {
            amqp_condition_destroy(&cv);
            amqp_condition_destroy(&cv_gate);
            amqp_mutex_destroy(&mutex);
            amqp_fast_mutex_destroy(&fast_mutex);
            amqp_threading_cleanup();
        }

        amqp_fast_mutex_t fast_mutex;
        amqp_mutex_t mutex;
        amqp_condition_variable_t cv;
        amqp_condition_variable_t cv_gate;

        int count;
        int thread_done_count;
        int thread_ready_count;
        static void handler(void *argument);
    private:
    };

    TEST_FIXTURE(FastMutexFixture, validate_fast_lock_lock_value)
    {
        CHECK_EQUAL(0, fast_mutex);
        amqp_fast_mutex_lock(&fast_mutex);
        CHECK_EQUAL(1, fast_mutex);
        amqp_fast_mutex_unlock(&fast_mutex);
        CHECK_EQUAL(0, fast_mutex);
    }

    void FastMutexFixture::handler(void *argument)
    {
        FastMutexFixture *fixture = (FastMutexFixture *) argument;

        amqp_mutex_lock(&fixture->mutex);
        fixture->thread_ready_count++;
        amqp_condition_notify(&fixture->cv);
        amqp_condition_wait(&fixture->cv_gate, &fixture->mutex);
        amqp_mutex_unlock(&fixture->mutex);

        for (int i = 0; i < 10000; i++)
        {
            amqp_fast_mutex_lock(&fixture->fast_mutex);
            fixture->count++;
            amqp_fast_mutex_unlock(&fixture->fast_mutex);
        }

        amqp_mutex_lock(&fixture->mutex);
        fixture->thread_done_count++;
        amqp_condition_notify(&fixture->cv);
        amqp_mutex_unlock(&fixture->mutex);
    }

    TEST_FIXTURE(FastMutexFixture, exercise_thread_api_with_fast_mutex)
    {
        const int N_THREADS = 11;
        amqp_thread_t *threads[N_THREADS];

        for (int i = 0; i < N_THREADS; i++)
        {
            threads[i] = amqp_thread_start(FastMutexFixture::handler, this);
        }

        amqp_mutex_lock(&mutex);
        while (thread_ready_count < N_THREADS)
        {
            amqp_condition_wait(&cv, &mutex);
        }
        amqp_condition_broadcast(&cv_gate);

        while (thread_done_count < N_THREADS)
        {
            amqp_condition_wait(&cv, &mutex);
        }
        amqp_mutex_unlock(&mutex);

        CHECK_EQUAL(N_THREADS * 10000, count);

        for (int i = 0; i < N_THREADS; i++)
        {
            amqp_thread_destroy(threads[i]);
        }
    }
}
<commit_msg>Ensure build works when LIBAMQP_DISABLE_FAST_MUTEX is defined<commit_after>/*
   Copyright 2011 StormMQ Limited

   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 <TestHarness.h>
#include "Thread/Thread.h"
#include "Thread/FastMutex.h"

#include "debug_helper.h"

SUITE(Thread)
{
    class ThreadFixture
    {
    public:
        ThreadFixture() : saved_from_thread(0)
        {
            amqp_threading_initialize();
            amqp_mutex_initialize(&mutex);
            amqp_condition_initialize(&cv);
        }

        ~ThreadFixture()
        {
            amqp_condition_destroy(&cv);
            amqp_mutex_destroy(&mutex);
            amqp_threading_cleanup();
        }

        const char *saved_from_thread;

        amqp_mutex_t mutex;
        amqp_condition_variable_t cv;

        static const char *pattern;
        static void handler(void *argument);
    private:
    };

    const char *ThreadFixture::pattern = "HeLlO wOrLd";
    void ThreadFixture::handler(void *argument)
    {
        ThreadFixture *fixture = (ThreadFixture *) argument;
        amqp_mutex_lock(&fixture->mutex);

        fixture->saved_from_thread = ThreadFixture::pattern;

        amqp_condition_notify(&fixture->cv);

        amqp_mutex_unlock(&fixture->mutex);
    }

    // Not really proof that the threading wrappers do the right thing.
    TEST_FIXTURE(ThreadFixture, exercise_thread_api)
    {
        CHECK_EQUAL((void *) 0, saved_from_thread);

        amqp_mutex_lock(&mutex);
        amqp_thread_t *thread = amqp_thread_start(ThreadFixture::handler, this);
        amqp_condition_wait(&cv, &mutex);
        amqp_mutex_unlock(&mutex);

        amqp_thread_destroy(thread);

        CHECK_EQUAL(pattern, saved_from_thread);
    }

    class FastMutexFixture
    {
    public:
        FastMutexFixture() : count(0), thread_done_count(0), thread_ready_count(0)
        {
            amqp_threading_initialize();
            amqp_fast_mutex_initialize(&fast_mutex);
            amqp_mutex_initialize(&mutex);
            amqp_condition_initialize(&cv);
            amqp_condition_initialize(&cv_gate);
        }

        ~FastMutexFixture()
        {
            amqp_condition_destroy(&cv);
            amqp_condition_destroy(&cv_gate);
            amqp_mutex_destroy(&mutex);
            amqp_fast_mutex_destroy(&fast_mutex);
            amqp_threading_cleanup();
        }

        amqp_fast_mutex_t fast_mutex;
        amqp_mutex_t mutex;
        amqp_condition_variable_t cv;
        amqp_condition_variable_t cv_gate;

        int count;
        int thread_done_count;
        int thread_ready_count;
        static void handler(void *argument);
    private:
    };

#if !defined(LIBAMQP_DISABLE_FAST_MUTEX)
    TEST_FIXTURE(FastMutexFixture, validate_fast_mutex_internal_value)
    {
        CHECK_EQUAL(0, fast_mutex);
        amqp_fast_mutex_lock(&fast_mutex);
        CHECK_EQUAL(1, fast_mutex);
        amqp_fast_mutex_unlock(&fast_mutex);
        CHECK_EQUAL(0, fast_mutex);
    }
#endif

    void FastMutexFixture::handler(void *argument)
    {
        FastMutexFixture *fixture = (FastMutexFixture *) argument;

        amqp_mutex_lock(&fixture->mutex);
        fixture->thread_ready_count++;
        amqp_condition_notify(&fixture->cv);
        amqp_condition_wait(&fixture->cv_gate, &fixture->mutex);
        amqp_mutex_unlock(&fixture->mutex);

        for (int i = 0; i < 10000; i++)
        {
            amqp_fast_mutex_lock(&fixture->fast_mutex);
            fixture->count++;
            amqp_fast_mutex_unlock(&fixture->fast_mutex);
        }

        amqp_mutex_lock(&fixture->mutex);
        fixture->thread_done_count++;
        amqp_condition_notify(&fixture->cv);
        amqp_mutex_unlock(&fixture->mutex);
    }

    TEST_FIXTURE(FastMutexFixture, exercise_thread_api_with_fast_mutex)
    {
        const int N_THREADS = 11;
        amqp_thread_t *threads[N_THREADS];

        for (int i = 0; i < N_THREADS; i++)
        {
            threads[i] = amqp_thread_start(FastMutexFixture::handler, this);
        }

        amqp_mutex_lock(&mutex);
        while (thread_ready_count < N_THREADS)
        {
            amqp_condition_wait(&cv, &mutex);
        }
        amqp_condition_broadcast(&cv_gate);

        while (thread_done_count < N_THREADS)
        {
            amqp_condition_wait(&cv, &mutex);
        }
        amqp_mutex_unlock(&mutex);

        CHECK_EQUAL(N_THREADS * 10000, count);

        for (int i = 0; i < N_THREADS; i++)
        {
            amqp_thread_destroy(threads[i]);
        }
    }
}
<|endoftext|>


<commit_before>
#include <iostream>
#include <ctime>

#include "MUSI8903Config.h"

#include "AudioFileIf.h"
#include "IIRCombFilter.h"
#include "FIRCombFilter.h"
#include "TestBuffering.h"
#include "TestFilter.h"

using std::cout;
using std::endl;

// local function declarations
void    showClInfo ();

/////////////////////////////////////////////////////////////////////////////////
// main function
int main(int argc, char* argv[])
{
    std::string             _sInputFilePath,                 //!< file paths
                            _sOutputFilePath;

    long long               _llBlockLength      = 0;        //!< length of block

    float                   _fDelayLenInSec     = 0.0f;     //!< delay Length in Seconds

    float                   _fGain              = 0.0f;

    clock_t                 time                = 0;

    float                   **ppfAudioData      = 0;

    CAudioFileIf            *phAudioFile        = 0;

    std::ofstream            outFile;

    Filter * _FilterProcess;

    showClInfo ();

    //////////////////////////////////////////////////////////////////////////////
    // Testing

    //    Test for Buffer class
        TestBuffering tTestBuf( 100 );
        std::cout<<"Testing the Buffering Class. The result is shown below: 1 represents success, 0 represents failure. "<<std::endl;
        std::cout<<"Initialization: "<<tTestBuf.isInit()<<std::endl;
        std::cout<<"Writing       : "<<tTestBuf.isReadWrite()<< "\n"<<std::endl;

    //////////////////////////////////////////////////////////////////////////////
    // Test for Filter classes
    ///////////////////////////////////////////////////
    // Filter Test: IIR naive test

        TestFilter testee1(1);
        testee1.zeroInputTest();
        testee1.unitImpulseTest();
        std::cout << "The output of IIR Filter test has been written to a text file at ../bin/debug/ " << std::endl;
    //////////////////////////////////////////////////
    // Filter Test: FIR naive test

        TestFilter testee2(0);
        testee2.zeroInputTest();
        testee2.unitImpulseTest();
        std::cout << "The output of FIR Filter test has been written to a text file at ../bin/debug/ \n" << std::endl;

        std::cout << "Use audioFileTest() in TestFilter class for more evaluation results\n\n";

    //////////////////////////////////////////////////////////////////////////////
    // parse command line arguments
    if (argc<6) {
        std::cerr << "The arguments are not properly provided. Filter cannot be used." << std::endl;
        return -1;
    }
    else {
        _sInputFilePath   = argv[1];
        _sOutputFilePath  = _sInputFilePath + ".txt";

        _llBlockLength     = atoi(argv[2]);
        _fDelayLenInSec   = (float) (atof(argv[3]));
        _fGain            = (float) (atof(argv[4]));

    }

    //////////////////////////////////////////////////////////////////////////////
    // open the input wave file
    CAudioFileIf::FileIoType_t fileType = CAudioFileIf::kFileRead;
    CAudioFileIf::create(phAudioFile);

    phAudioFile -> openFile(_sInputFilePath+".wav", fileType);

    CAudioFileIf::FileSpec_t fileSpec;
    phAudioFile -> getFileSpec(fileSpec);

    //////////////////////////////////////////////////////////////////////////////
    // allocate memory

    time = clock();

    if (atoi(argv[5]) == 0) {
        _FilterProcess = new class FIRCombFilter(_fDelayLenInSec, fileSpec.fSampleRateInHz, _fGain, fileSpec.iNumChannels);
    }
    else if(atoi(argv[5]) == 1) {
        _FilterProcess = new class IIRCombFilter(_fDelayLenInSec, fileSpec.fSampleRateInHz, _fGain, fileSpec.iNumChannels);
    }
    else {
        std::cout << "Filter Type Selection Error. Please select 0 or 1" << std::endl;
        return -1;
    }

    ppfAudioData = new float* [fileSpec.iNumChannels];
    for (int channel = 0; channel < fileSpec.iNumChannels; channel++) {
        ppfAudioData[channel] = new float [_llBlockLength];
    }
    outFile.open(_sOutputFilePath);

    // process the signal
    while (!phAudioFile->isEof()) {
        phAudioFile -> readData(ppfAudioData, _llBlockLength);
        for (int channel=0; channel<fileSpec.iNumChannels; channel++ ) {
            _FilterProcess -> filterProcess(ppfAudioData[channel], _llBlockLength, channel);
        }
        for ( int sample = 0; sample < _llBlockLength; sample++ ) {
            for ( int channel = 0; channel < fileSpec.iNumChannels; channel++ ) {
                outFile << ppfAudioData[channel][sample]<<"\t";
            }
            outFile << "\n";
        }
    }
    outFile.close();

    //////////////////////////////////////////////////////////////////////////////
    // clean-up
    delete _FilterProcess;
    for (int channel = 0; channel < fileSpec.iNumChannels; channel++) {
        delete [] ppfAudioData[channel];
    }
    delete [] ppfAudioData;
    std::cout << "Comb filter processing is done within " << (clock() - time)*1.f / CLOCKS_PER_SEC << " seconds." << std::endl;
    CAudioFileIf::destroy(phAudioFile);

    return 0;
}

void     showClInfo()
    {
        cout << "GTCMT MUSI8903" << endl;
        cout << "(c) 2016 by Liang Tang and Rithesh Kumar" << endl;
        cout  << endl;

        return;
    }

<commit_msg>Consolidated Push(1)<commit_after>
#include <iostream>
#include <ctime>

#include "MUSI8903Config.h"

#include "AudioFileIf.h"
#include "IIRCombFilter.h"
#include "FIRCombFilter.h"
#include "TestBuffering.h"
#include "TestFilter.h"

using std::cout;
using std::endl;

// local function declarations
void    showClInfo ();

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// main function
int main(int argc, char* argv[])
{
    std::string             _sInputFilePath,                 //!< file paths
                            _sOutputFilePath;

    long long               _llBlockLength      = 0;        //!< length of block

    float                   _fDelayLenInSec     = 0.0f;     //!< delay Length in Seconds

    float                   _fGain              = 0.0f;

    clock_t                 time                = 0;

    float                   **ppfAudioData      = 0;

    CAudioFileIf            *phAudioFile        = 0;

    std::ofstream            outFile;

    Filter * _FilterProcess;

    showClInfo ();

    //////////////////////////////////////////////////////////////////////////////
    // Testing

    //    Test for Buffer class
        TestBuffering tTestBuf( 100 );
        std::cout<<"Testing the Buffering Class. The result is shown below: 1 represents success, 0 represents failure. "<<std::endl;
        std::cout<<"Initialization: "<<tTestBuf.isInit()<<std::endl;
        std::cout<<"Writing       : "<<tTestBuf.isReadWrite()<< "\n"<<std::endl;

    //////////////////////////////////////////////////////////////////////////////
    // Test for Filter classes
    ///////////////////////////////////////////////////
    // Filter Test: IIR naive test

        TestFilter testee1(1);
        testee1.zeroInputTest();
        testee1.unitImpulseTest();
        std::cout << "The output of IIR Filter test has been written to a text file at ../bin/debug/ " << std::endl;
    //////////////////////////////////////////////////
    // Filter Test: FIR naive test

        TestFilter testee2(0);
        testee2.zeroInputTest();
        testee2.unitImpulseTest();
        std::cout << "The output of FIR Filter test has been written to a text file at ../bin/debug/ \n" << std::endl;

        std::cout << "Use audioFileTest() in TestFilter class for more evaluation results\n\n";

    //////////////////////////////////////////////////////////////////////////////
    // parse command line arguments
    if (argc<6) {
        std::cerr << "The arguments are not properly provided. Filter cannot be used." << std::endl;
        return -1;
    }
    else {
        _sInputFilePath   = argv[1];
        _sOutputFilePath  = _sInputFilePath + ".txt";

        _llBlockLength     = atoi(argv[2]);
        _fDelayLenInSec   = (float) (atof(argv[3]));
        _fGain            = (float) (atof(argv[4]));

    }

    //////////////////////////////////////////////////////////////////////////////
    // open the input wave file
    CAudioFileIf::FileIoType_t fileType = CAudioFileIf::kFileRead;
    CAudioFileIf::create(phAudioFile);

    phAudioFile -> openFile(_sInputFilePath+".wav", fileType);

    CAudioFileIf::FileSpec_t fileSpec;
    phAudioFile -> getFileSpec(fileSpec);

    //////////////////////////////////////////////////////////////////////////////
    // allocate memory

    time = clock();

    if (atoi(argv[5]) == 0) {
        _FilterProcess = new class FIRCombFilter(_fDelayLenInSec, fileSpec.fSampleRateInHz, _fGain, fileSpec.iNumChannels);
    }
    else if(atoi(argv[5]) == 1) {
        _FilterProcess = new class IIRCombFilter(_fDelayLenInSec, fileSpec.fSampleRateInHz, _fGain, fileSpec.iNumChannels);
    }
    else {
        std::cout << "Filter Type Selection Error. Please select 0 or 1" << std::endl;
        return -1;
    }

    ppfAudioData = new float* [fileSpec.iNumChannels];
    for (int channel = 0; channel < fileSpec.iNumChannels; channel++) {
        ppfAudioData[channel] = new float [_llBlockLength];
    }
    outFile.open(_sOutputFilePath);

    // process the signal
    while (!phAudioFile->isEof()) {
        phAudioFile -> readData(ppfAudioData, _llBlockLength);
        for (int channel=0; channel<fileSpec.iNumChannels; channel++ ) {
            _FilterProcess -> filterProcess(ppfAudioData[channel], _llBlockLength, channel);
        }
        for ( int sample = 0; sample < _llBlockLength; sample++ ) {
            for ( int channel = 0; channel < fileSpec.iNumChannels; channel++ ) {
                outFile << ppfAudioData[channel][sample]<<"\t";
            }
            outFile << "\n";
        }
    }
    outFile.close();

    //////////////////////////////////////////////////////////////////////////////
    // clean-up
    delete _FilterProcess;
    for (int channel = 0; channel < fileSpec.iNumChannels; channel++) {
        delete [] ppfAudioData[channel];
    }
    delete [] ppfAudioData;
    std::cout << "Comb filter processing is done within " << (clock() - time)*1.f / CLOCKS_PER_SEC << " seconds." << std::endl;
    CAudioFileIf::destroy(phAudioFile);

    return 0;
}

void     showClInfo()
    {
        cout << "GTCMT MUSI8903" << endl;
        cout << "(c) 2016 by Liang Tang and Rithesh Kumar" << endl;
        cout  << endl;

        return;
    }

<|endoftext|>