<commit_before>/*
   Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   SPDX-License-Identifier: Apache-2.0
*/

#include <aws/core/Aws.h>
#include <aws/core/utils/threading/Semaphore.h>
#include <aws/core/auth/AWSCredentialsProviderChain.h>
#include <aws/transcribestreaming/TranscribeStreamingServiceClient.h>
#include <aws/transcribestreaming/model/StartStreamTranscriptionHandler.h>
#include <aws/transcribestreaming/model/StartStreamTranscriptionRequest.h>
#include <aws/core/platform/FileSystem.h>
#include <fstream>
#include <chrono>
#include <thread>
#include <array>

using namespace Aws;
using namespace Aws::TranscribeStreamingService;
using namespace Aws::TranscribeStreamingService::Model;

//TODO(User): Update path to location of local .wav test file, if necessary.
static const Aws::String FILE_NAME{MEDIA_DIR "/transcribe-test-file.wav"};
static const int BUFFER_SIZE = 1024;
static const int END_OF_STREAM_SLEEP_SECONDS = 10;

//snippet-start:[transcribe.cpp.stream_transcription_async.code]
int main() {
    Aws::SDKOptions options;
    options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace;
    Aws::InitAPI(options);
    {
        //TODO(User): Set to the region of your AWS account.
        const Aws::String region = Aws::Region::US_WEST_2;

        Aws::Utils::Threading::Semaphore received(0 /*initialCount*/, 1 /*maxCount*/);

        //Load a profile that has been granted AmazonTranscribeFullAccess AWS managed permission policy.
        Aws::Client::ClientConfiguration config;
#ifdef _WIN32
        // ATTENTION: On Windows with AWS SDK version 1.9, this example only runs if the SDK is built
        // with the curl library.  (9/15/2022)
        // For more information, see the accompanying ReadMe.
        // For more information, see "Building the SDK for Windows with curl".
        // https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/setup-windows.html
        //TODO(User): Update to the location of your .crt file.
        config.caFile = "C:/curl/bin/curl-ca-bundle.crt";
#endif
        config.region = region;

        TranscribeStreamingServiceClient client(config);
        StartStreamTranscriptionHandler handler;
        handler.SetOnErrorCallback(
                [](const Aws::Client::AWSError<TranscribeStreamingServiceErrors> &error) {
                        std::cerr << "ERROR: " + error.GetMessage() << std::endl;
                });
        //SetTranscriptEventCallback called for every 'chunk' of file transcripted.
        // Partial results are returned in real time.
        handler.SetTranscriptEventCallback([&received](const TranscriptEvent &ev) {
                for (auto &&r: ev.GetTranscript().GetResults()) {
                    if (r.GetIsPartial()) {
                        std::cout << "[partial] ";
                    }
                    else {
                        std::cout << "[Final] ";
                    }
                    for (auto &&alt: r.GetAlternatives()) {
                        std::cout << alt.GetTranscript() << std::endl;
                    }
                }
                received.Release();
        });

        StartStreamTranscriptionRequest request;
        request.SetMediaSampleRateHertz(8000);
        request.SetLanguageCode(LanguageCode::en_US);
        request.SetMediaEncoding(
                MediaEncoding::pcm); // wav and aiff files are PCM formats.
        request.SetEventStreamHandler(handler);

        auto OnStreamReady = [](AudioStream &stream) {
                Aws::FStream file(FILE_NAME, std::ios_base::in | std::ios_base::binary);
                if (!file.is_open()) {
                    std::cerr << "Failed to open " << FILE_NAME << '\n';
                }
                std::array<char, BUFFER_SIZE> buf;
                int i = 0;
                while (file) {
                    file.read(&buf[0], buf.size());

                    if (!file)
                        std::cout << "File: only " << file.gcount() << " could be read"
                                  << std::endl;

                    Aws::Vector<unsigned char> bits{buf.begin(), buf.end()};
                    AudioEvent event(std::move(bits));
                    if (!stream) {
                        std::cerr << "Failed to create a stream" << std::endl;
                        break;
                    }
                    //The std::basic_istream::gcount() is used to count the characters in the given string. It returns
                    //the number of characters extracted by the last read() operation.
                    if (file.gcount() > 0) {
                        if (!stream.WriteAudioEvent(event)) {
                            std::cerr << "Failed to write an audio event" << std::endl;
                            break;
                        }
                    }
                    else {
                        break;
                    }
                    std::this_thread::sleep_for(std::chrono::milliseconds(
                            25)); // Slow down because we are streaming from a file.
                }
                if (!stream.WriteAudioEvent(
                        AudioEvent())) {
                    // Per the spec, we have to send an empty event (an event without a payload) at the end.
                    std::cerr << "Failed to send an empty frame" << std::endl;
                }
                else {
                    std::cout << "Successfully sent the empty frame" << std::endl;
                }
                stream.flush();
                // Workaround to prevent an error at the end of the stream for this contrived example.
                std::this_thread::sleep_for(std::chrono::seconds(
                        END_OF_STREAM_SLEEP_SECONDS));
                stream.Close();
        };

        Aws::Utils::Threading::Semaphore signaling(0 /*initialCount*/, 1 /*maxCount*/);
        auto OnResponseCallback = [&signaling](
                const TranscribeStreamingServiceClient * /*unused*/,
                const Model::StartStreamTranscriptionRequest & /*unused*/,
                const Model::StartStreamTranscriptionOutcome & /*unused*/,
                const std::shared_ptr<const Aws::Client::AsyncCallerContext> & /*unused*/) {
                signaling.Release();
        };

        std::cout << "Starting..." << std::endl;
        client.StartStreamTranscriptionAsync(request, OnStreamReady, OnResponseCallback,
                                             nullptr /*context*/);
        signaling.WaitOne(); // Prevent the application from exiting until we're done.
        std::cout << "Done" << std::endl;
    }

    Aws::ShutdownAPI(options);

    return 0;
}
//snippet-end:[transcribe.cpp.stream_transcription_async.code]
<commit_msg>changes tow show sequence for closing stream<commit_after>/*
   Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   SPDX-License-Identifier: Apache-2.0
*/

#include <aws/core/Aws.h>
#include <aws/core/utils/threading/Semaphore.h>
#include <aws/core/auth/AWSCredentialsProviderChain.h>
#include <aws/transcribestreaming/TranscribeStreamingServiceClient.h>
#include <aws/transcribestreaming/model/StartStreamTranscriptionHandler.h>
#include <aws/transcribestreaming/model/StartStreamTranscriptionRequest.h>
#include <aws/core/platform/FileSystem.h>
#include <fstream>
#include <chrono>
#include <thread>
#include <array>

using namespace Aws;
using namespace Aws::TranscribeStreamingService;
using namespace Aws::TranscribeStreamingService::Model;

//TODO(User): Update path to location of local .wav test file, if necessary.
static const Aws::String FILE_NAME{MEDIA_DIR "/transcribe-test-file.wav"};
static const int BUFFER_SIZE = 1024;
static const int END_OF_STREAM_SLEEP_SECONDS = 10;

//snippet-start:[transcribe.cpp.stream_transcription_async.code]
int main() {
    Aws::SDKOptions options;
    options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace;
    Aws::InitAPI(options);
    {
        //TODO(User): Set to the region of your AWS account.
        const Aws::String region = Aws::Region::US_WEST_2;

        Aws::Utils::Threading::Semaphore canCloseStream(0 /*initialCount*/, 1 /*maxCount*/);

        //Load a profile that has been granted AmazonTranscribeFullAccess AWS managed permission policy.
        Aws::Client::ClientConfiguration config;
#ifdef _WIN32
        // ATTENTION: On Windows with AWS SDK version 1.9, this example only runs if the SDK is built
        // with the curl library.  (9/15/2022)
        // For more information, see the accompanying ReadMe.
        // For more information, see "Building the SDK for Windows with curl".
        // https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/setup-windows.html
        //TODO(User): Update to the location of your .crt file.
        config.caFile = "C:/curl/bin/curl-ca-bundle.crt";
#endif
        config.region = region;

        TranscribeStreamingServiceClient client(config);
        StartStreamTranscriptionHandler handler;
        handler.SetOnErrorCallback(
                [](const Aws::Client::AWSError<TranscribeStreamingServiceErrors> &error) {
                        std::cerr << "ERROR: " + error.GetMessage() << std::endl;
                });
        //SetTranscriptEventCallback called for every 'chunk' of file transcripted.
        // Partial results are returned in real time.
        handler.SetTranscriptEventCallback([&canCloseStream](const TranscriptEvent &ev) {
                bool isFinal = false;
                for (auto &&r: ev.GetTranscript().GetResults()) {
                    if (r.GetIsPartial()) {
                        std::cout << "[partial] ";
                    }
                    else {
                        std::cout << "[Final] ";
                        isFinal = true;
                    }
                    for (auto &&alt: r.GetAlternatives()) {
                        std::cout << alt.GetTranscript() << std::endl;
                    }
                }
                if (isFinal) {
                    canCloseStream.Release();
                }
        });

        StartStreamTranscriptionRequest request;
        request.SetMediaSampleRateHertz(8000);
        request.SetLanguageCode(LanguageCode::en_US);
        request.SetMediaEncoding(
                MediaEncoding::pcm); // wav and aiff files are PCM formats.
        request.SetEventStreamHandler(handler);

        auto OnStreamReady = [&canCloseStream](AudioStream &stream) {
                Aws::FStream file(FILE_NAME, std::ios_base::in | std::ios_base::binary);
                if (!file.is_open()) {
                    std::cerr << "Failed to open " << FILE_NAME << '\n';
                }
                std::array<char, BUFFER_SIZE> buf;
                int i = 0;
                while (file) {
                    file.read(&buf[0], buf.size());

                    if (!file)
                        std::cout << "File: only " << file.gcount() << " could be read"
                                  << std::endl;

                    Aws::Vector<unsigned char> bits{buf.begin(), buf.end()};
                    AudioEvent event(std::move(bits));
                    if (!stream) {
                        std::cerr << "Failed to create a stream" << std::endl;
                        break;
                    }
                    //The std::basic_istream::gcount() is used to count the characters in the given string. It returns
                    //the number of characters extracted by the last read() operation.
                    if (file.gcount() > 0) {
                        if (!stream.WriteAudioEvent(event)) {
                            std::cerr << "Failed to write an audio event" << std::endl;
                            break;
                        }
                    }
                    else {
                        break;
                    }
                    std::this_thread::sleep_for(std::chrono::milliseconds(
                            25)); // Slow down because we are streaming from a file.
                }
                if (!stream.WriteAudioEvent(
                        AudioEvent())) {
                    // Per the spec, we have to send an empty event (an event without a payload) at the end.
                    std::cerr << "Failed to send an empty frame" << std::endl;
                }
                else {
                    std::cout << "Successfully sent the empty frame" << std::endl;
                }
                stream.flush();
                // Wait until final transcript is received before closing the stream.
                canCloseStream.WaitOne();
                stream.Close();
         };

        Aws::Utils::Threading::Semaphore signaling(0 /*initialCount*/, 1 /*maxCount*/);
        auto OnResponseCallback = [&signaling, &canCloseStream](
                const TranscribeStreamingServiceClient * /*unused*/,
                const Model::StartStreamTranscriptionRequest & /*unused*/,
                const Model::StartStreamTranscriptionOutcome & outcome,
                const std::shared_ptr<const Aws::Client::AsyncCallerContext> & /*unused*/) {

            if (!outcome.IsSuccess())
            {
                std::cerr << "Transcribe streaming error " << outcome.GetError().GetMessage() << std::endl;
            }

            canCloseStream.Release();  // Just to be safe.
            signaling.Release();
        };

        std::cout << "Starting..." << std::endl;
        client.StartStreamTranscriptionAsync(request, OnStreamReady, OnResponseCallback,
                                             nullptr /*context*/);
        signaling.WaitOne(); // Prevent the application from exiting until we're done.
        std::cout << "Done" << std::endl;
    }

    Aws::ShutdownAPI(options);

    return 0;
}
//snippet-end:[transcribe.cpp.stream_transcription_async.code]
<|endoftext|>


<commit_before>// Copyright (C) 2011 The Libphonenumber Authors
//
// 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.
//
// Author: Tao Huang
//
// Basic test cases for PhoneNumberMatch.

#include "phonenumbers/phonenumber.h"
#include "phonenumbers/phonenumbermatch.h"

#include <gtest/gtest.h>

#include "phonenumbers/phonenumber.pb.h"

namespace i18n {
namespace phonenumbers {

TEST(PhoneNumberMatch, TestGetterMethods) {
  PhoneNumber number;
  const int start_index = 10;
  const string raw_phone_number("1 800 234 45 67");
  PhoneNumberMatch match1(start_index, raw_phone_number, number);

  EXPECT_EQ(start_index, match1.start());
  EXPECT_EQ(start_index + raw_phone_number.length(), match1.end());
  EXPECT_EQ(raw_phone_number.length(), match1.length());
  EXPECT_EQ(raw_phone_number, match1.raw_string());

  EXPECT_EQ("PhoneNumberMatch [10,25) 1 800 234 45 67", match1.ToString());
}

TEST(PhoneNumberMatch, TestEquals) {
  PhoneNumber number;
  PhoneNumberMatch match1(10, "1 800 234 45 67", number);
  PhoneNumberMatch match2(10, "1 800 234 45 67", number);

  match2.set_start(11);
  ASSERT_FALSE(match1.Equals(match2));
  match2.set_start(match1.start());
  EXPECT_TRUE(match1.Equals(match2));

  PhoneNumber number2;
  number2.set_raw_input("123");
  match2.set_number(number2);
  ASSERT_FALSE(match1.Equals(match2));
  match2.set_number(match1.number());
  EXPECT_TRUE(ExactlySameAs(match1.number(), match2.number()));
  EXPECT_TRUE(match1.Equals(match2));

  match2.set_raw_string("123");
  ASSERT_FALSE(match1.Equals(match2));
}

TEST(PhoneNumberMatch, TestAssignmentOverload) {
  PhoneNumber number;
  PhoneNumberMatch match1(10, "1 800 234 45 67", number);
  PhoneNumberMatch match2;
  ASSERT_FALSE(match1.Equals(match2));

  match2.CopyFrom(match1);
  ASSERT_TRUE(match1.Equals(match2));

  PhoneNumberMatch match3;
  PhoneNumberMatch match4;
  match4.CopyFrom(match2);
  match3.CopyFrom(match2);
  ASSERT_TRUE(match3.Equals(match4));
  ASSERT_TRUE(match4.Equals(match2));
}

TEST(PhoneNumberMatch, TestCopyConstructor) {
  PhoneNumber number;
  PhoneNumberMatch match1(10, "1 800 234 45 67", number);
  PhoneNumberMatch match2;
  match2.CopyFrom(match1);
  ASSERT_TRUE(match1.Equals(match2));
}

}  // namespace phonenumbers
}  // namespace i18n
<commit_msg>CPP: Adjust phonenumbermatch_test.cc integer types.<commit_after>// Copyright (C) 2011 The Libphonenumber Authors
//
// 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.
//
// Author: Tao Huang
//
// Basic test cases for PhoneNumberMatch.

#include "phonenumbers/phonenumber.h"
#include "phonenumbers/phonenumbermatch.h"

#include <gtest/gtest.h>

#include "phonenumbers/phonenumber.pb.h"

namespace i18n {
namespace phonenumbers {

TEST(PhoneNumberMatch, TestGetterMethods) {
  PhoneNumber number;
  const int start_index = 10;
  const string raw_phone_number("1 800 234 45 67");
  PhoneNumberMatch match1(start_index, raw_phone_number, number);

  EXPECT_EQ(start_index, match1.start());
  EXPECT_EQ(start_index + static_cast<int>(raw_phone_number.length()),
            match1.end());
  EXPECT_EQ(static_cast<int>(raw_phone_number.length()), match1.length());
  EXPECT_EQ(raw_phone_number, match1.raw_string());

  EXPECT_EQ("PhoneNumberMatch [10,25) 1 800 234 45 67", match1.ToString());
}

TEST(PhoneNumberMatch, TestEquals) {
  PhoneNumber number;
  PhoneNumberMatch match1(10, "1 800 234 45 67", number);
  PhoneNumberMatch match2(10, "1 800 234 45 67", number);

  match2.set_start(11);
  ASSERT_FALSE(match1.Equals(match2));
  match2.set_start(match1.start());
  EXPECT_TRUE(match1.Equals(match2));

  PhoneNumber number2;
  number2.set_raw_input("123");
  match2.set_number(number2);
  ASSERT_FALSE(match1.Equals(match2));
  match2.set_number(match1.number());
  EXPECT_TRUE(ExactlySameAs(match1.number(), match2.number()));
  EXPECT_TRUE(match1.Equals(match2));

  match2.set_raw_string("123");
  ASSERT_FALSE(match1.Equals(match2));
}

TEST(PhoneNumberMatch, TestAssignmentOverload) {
  PhoneNumber number;
  PhoneNumberMatch match1(10, "1 800 234 45 67", number);
  PhoneNumberMatch match2;
  ASSERT_FALSE(match1.Equals(match2));

  match2.CopyFrom(match1);
  ASSERT_TRUE(match1.Equals(match2));

  PhoneNumberMatch match3;
  PhoneNumberMatch match4;
  match4.CopyFrom(match2);
  match3.CopyFrom(match2);
  ASSERT_TRUE(match3.Equals(match4));
  ASSERT_TRUE(match4.Equals(match2));
}

TEST(PhoneNumberMatch, TestCopyConstructor) {
  PhoneNumber number;
  PhoneNumberMatch match1(10, "1 800 234 45 67", number);
  PhoneNumberMatch match2;
  match2.CopyFrom(match1);
  ASSERT_TRUE(match1.Equals(match2));
}

}  // namespace phonenumbers
}  // namespace i18n
<|endoftext|>


<commit_before>
#include "nethandlers.h"
#include "netmessages.h"

#define DECLARE_NET_HANDLER_ARRAY(funcname) \
    { \
        &NetHandlers::Net_NOP_##funcname, \
        &NetHandlers::Net_Disconnect_##funcname, \
        &NetHandlers::Net_File_##funcname, \
        &NetHandlers::Net_Tick_##funcname, \
        &NetHandlers::Net_StringCmd_##funcname, \
        &NetHandlers::Net_SetConVar_##funcname, \
        &NetHandlers::Net_SignonState_##funcname, \
        &NetHandlers::SVC_Print_##funcname, \
        &NetHandlers::SVC_ServerInfo_##funcname, \
        &NetHandlers::SVC_SendTable_##funcname, \
        &NetHandlers::SVC_ClassInfo_##funcname, \
        &NetHandlers::SVC_SetPause_##funcname, \
        &NetHandlers::SVC_CreateStringTable_##funcname, \
        &NetHandlers::SVC_UpdateStringTable_##funcname, \
        &NetHandlers::SVC_VoiceInit_##funcname, \
        &NetHandlers::SVC_VoiceData_##funcname, \
        &NetHandlers::SVC_HLTV_##funcname, \
        &NetHandlers::SVC_Sounds_##funcname, \
        &NetHandlers::SVC_SetView_##funcname, \
        &NetHandlers::SVC_FixAngle_##funcname, \
        &NetHandlers::SVC_CrosshairAngle_##funcname, \
        &NetHandlers::SVC_BSPDecal_##funcname, \
        &NetHandlers::SVC_TerrainMod_##funcname, \
        &NetHandlers::SVC_UserMessage_##funcname, \
        &NetHandlers::SVC_EntityMessage_##funcname, \
        &NetHandlers::SVC_GameEvent_##funcname, \
        &NetHandlers::SVC_PacketEntities_##funcname, \
        &NetHandlers::SVC_TempEntities_##funcname, \
        &NetHandlers::SVC_Prefetch_##funcname, \
        &NetHandlers::SVC_Menu_##funcname, \
        &NetHandlers::SVC_GameEventList_##funcname, \
        &NetHandlers::SVC_GetCvarValue_##funcname \
    }

typedef bool (*NetMsgBitReadFn)(bf_read& bitbuf, SourceGameContext& context, void* data);
typedef bool (*NetMsgBitWriteFn)(bf_write& bitbuf, const SourceGameContext& context, void* data);
typedef bool (*NetMsgJsonReadFn)(JsonRead& bitbuf, SourceGameContext& context, void* data);
typedef bool (*NetMsgJsonWriteFn)(JsonWrite& bitbuf, const SourceGameContext& context, void* data);
typedef void (*NetMsgToStringFn)(std::ostringstream& out, void* data);

bool NetHandlers::NetMsg_BitRead(uint32_t type, bf_read& bitbuf, SourceGameContext& context, void* data)
{
    static const NetMsgBitReadFn netHandlers[] = DECLARE_NET_HANDLER_ARRAY(BitRead);
    return netHandlers[type](bitbuf, context, data);
}

bool NetHandlers::NetMsg_BitWrite(uint32_t type, bf_write& bitbuf, const SourceGameContext& context, void* data)
{
    static const NetMsgBitWriteFn netHandlers[] = DECLARE_NET_HANDLER_ARRAY(BitWrite);
    return netHandlers[type](bitbuf, context, data);
}

bool NetHandlers::NetMsg_JsonRead(uint32_t type, JsonRead& jsonbuf, SourceGameContext& context, void* data)
{
    static const NetMsgJsonReadFn netHandlers[] = DECLARE_NET_HANDLER_ARRAY(JsonRead);
    return netHandlers[type](jsonbuf, context, data);
}

bool NetHandlers::NetMsg_JsonWrite(uint32_t type, JsonWrite& jsonbuf, const SourceGameContext& context, void* data)
{
    static const NetMsgJsonWriteFn netHandlers[] = DECLARE_NET_HANDLER_ARRAY(JsonWrite);
    return netHandlers[type](jsonbuf, context, data);
}

void NetHandlers::NetMsg_ToString(uint32_t type, std::ostringstream& out, void* data)
{
    static const NetMsgToStringFn netHandlers[] = DECLARE_NET_HANDLER_ARRAY(ToString);
    netHandlers[type](out, data);
}
<commit_msg>Fixed typo<commit_after>
#include "nethandlers.h"
#include "netmessages.h"

#define DECLARE_NET_HANDLER_ARRAY(funcname) \
    { \
        &NetHandlers::Net_NOP_##funcname, \
        &NetHandlers::Net_Disconnect_##funcname, \
        &NetHandlers::Net_File_##funcname, \
        &NetHandlers::Net_Tick_##funcname, \
        &NetHandlers::Net_StringCmd_##funcname, \
        &NetHandlers::Net_SetConVar_##funcname, \
        &NetHandlers::Net_SignonState_##funcname, \
        &NetHandlers::SVC_Print_##funcname, \
        &NetHandlers::SVC_ServerInfo_##funcname, \
        &NetHandlers::SVC_SendTable_##funcname, \
        &NetHandlers::SVC_ClassInfo_##funcname, \
        &NetHandlers::SVC_SetPause_##funcname, \
        &NetHandlers::SVC_CreateStringTable_##funcname, \
        &NetHandlers::SVC_UpdateStringTable_##funcname, \
        &NetHandlers::SVC_VoiceInit_##funcname, \
        &NetHandlers::SVC_VoiceData_##funcname, \
        &NetHandlers::SVC_HLTV_##funcname, \
        &NetHandlers::SVC_Sounds_##funcname, \
        &NetHandlers::SVC_SetView_##funcname, \
        &NetHandlers::SVC_FixAngle_##funcname, \
        &NetHandlers::SVC_CrosshairAngle_##funcname, \
        &NetHandlers::SVC_BSPDecal_##funcname, \
        &NetHandlers::SVC_TerrainMod_##funcname, \
        &NetHandlers::SVC_UserMessage_##funcname, \
        &NetHandlers::SVC_EntityMessage_##funcname, \
        &NetHandlers::SVC_GameEvent_##funcname, \
        &NetHandlers::SVC_PacketEntities_##funcname, \
        &NetHandlers::SVC_TempEntities_##funcname, \
        &NetHandlers::SVC_Prefetch_##funcname, \
        &NetHandlers::SVC_Menu_##funcname, \
        &NetHandlers::SVC_GameEventList_##funcname, \
        &NetHandlers::SVC_GetCvarValue_##funcname \
    }

typedef bool (*NetMsgBitReadFn)(bf_read& bitbuf, SourceGameContext& context, void* data);
typedef bool (*NetMsgBitWriteFn)(bf_write& bitbuf, const SourceGameContext& context, void* data);
typedef bool (*NetMsgJsonReadFn)(JsonRead& jsonbuf, SourceGameContext& context, void* data);
typedef bool (*NetMsgJsonWriteFn)(JsonWrite& jsonbuf, const SourceGameContext& context, void* data);
typedef void (*NetMsgToStringFn)(std::ostringstream& out, void* data);

bool NetHandlers::NetMsg_BitRead(uint32_t type, bf_read& bitbuf, SourceGameContext& context, void* data)
{
    static const NetMsgBitReadFn netHandlers[] = DECLARE_NET_HANDLER_ARRAY(BitRead);
    return netHandlers[type](bitbuf, context, data);
}

bool NetHandlers::NetMsg_BitWrite(uint32_t type, bf_write& bitbuf, const SourceGameContext& context, void* data)
{
    static const NetMsgBitWriteFn netHandlers[] = DECLARE_NET_HANDLER_ARRAY(BitWrite);
    return netHandlers[type](bitbuf, context, data);
}

bool NetHandlers::NetMsg_JsonRead(uint32_t type, JsonRead& jsonbuf, SourceGameContext& context, void* data)
{
    static const NetMsgJsonReadFn netHandlers[] = DECLARE_NET_HANDLER_ARRAY(JsonRead);
    return netHandlers[type](jsonbuf, context, data);
}

bool NetHandlers::NetMsg_JsonWrite(uint32_t type, JsonWrite& jsonbuf, const SourceGameContext& context, void* data)
{
    static const NetMsgJsonWriteFn netHandlers[] = DECLARE_NET_HANDLER_ARRAY(JsonWrite);
    return netHandlers[type](jsonbuf, context, data);
}

void NetHandlers::NetMsg_ToString(uint32_t type, std::ostringstream& out, void* data)
{
    static const NetMsgToStringFn netHandlers[] = DECLARE_NET_HANDLER_ARRAY(ToString);
    netHandlers[type](out, data);
}
<|endoftext|>


<commit_before>#include "powerSleep.h"

#include <avr/sleep.h>
#include <avr/power.h>

void enterSleep()
{
  /*** Setup Sleep options ***/

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);  // Lowest powerdown mode
  sleep_enable();                       // Enable sleep

  /*** Put processor to sleep ***/

  sleep_mode();

  /*** Continue ***/

  sleep_disable();

  /*** Re-enable necessary peripherals ***/
  if(/*serialActive*/)
  {
    power_usart0_enable();
  }
  power_spi_enable();

  return;
}
void disableUnneededPeripherals()
{
  /*** Disable Uneeded Peripherals ***/
  ADCSRA = 0;   // Disable ADC
  power_adc_disable();
  power_timer0_disable();
  power_timer1_disable();
  power_timer2_disable();
  power_twi_disable();

  /*** Enable needed Peripherals ***/     // May actually disable these too, and re-enable them later.
  power_usart0_enable();
  power_spi_enable();

  return;
}
<commit_msg>Update powerSleep.cpp<commit_after>#include "powerSleep.h"

#include <avr/sleep.h>
#include <avr/power.h>
#include "state.h"

void enterSleep(State_t* State)
{
  /*** Setup Sleep options ***/

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);  // Lowest powerdown mode
  sleep_enable();                       // Enable sleep

  /*** Put processor to sleep ***/

  sleep_mode();

  /*** Continue ***/

  sleep_disable();

  /*** Re-enable necessary peripherals ***/
  if(State->serialOn)
  {
    power_usart0_enable();
  }
  power_spi_enable();

  return;
}
void disableUnneededPeripherals()
{
  /*** Disable Uneeded Peripherals ***/
  ADCSRA = 0;   // Disable ADC
  power_adc_disable();
  power_timer0_disable();
  power_timer1_disable();
  power_timer2_disable();
  power_twi_disable();
  power_usart0_disable();

  /*** Enable needed Peripherals ***/     // May actually disable this too, and re-enable them later.
  power_spi_enable();

  return;
}
<|endoftext|>


<commit_before>/*****************************************************************************
 * controller.hpp : Controller for the main interface
 ****************************************************************************
 * Copyright (C) 2006-2008 the VideoLAN team
 * $Id$
 *
 * Authors: Jean-Baptiste Kempf <jb@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifndef QVLC_CONTROLLER_H_
#define QVLC_CONTROLLER_H_

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "qt4.hpp"

#include <QFrame>
#include <QString>
#include <QSizeGrip>

#define MAIN_TB1_DEFAULT "64;39;64;38;65"
#define MAIN_TB2_DEFAULT "0-2;64;3;1;4;64;7;9;64;10;20;19;64-4;37;65;35-4"
#define ADV_TB_DEFAULT "12;11;13;14"
#define INPT_TB_DEFAULT "43;33-4;44"
#define FSC_TB_DEFAULT "0-2;64;3;1;4;64;37;64;38;64;8;65;25;35-4;34"

#define I_PLAY_TOOLTIP N_("Play\nIf the playlist is empty, open a medium")

class QPixmap;
class QLabel;

class QGridLayout;
class QBoxLayout;
class QHBoxLayout;
class QVBoxLayout;

class QAbstractSlider;
class QAbstractButton;
class SeekSlider;
class QToolButton;

class VolumeClickHandler;
class WidgetListing;

class QSignalMapper;
class QTimer;

typedef enum buttonType_e
{
    PLAY_BUTTON,
    STOP_BUTTON,
    OPEN_BUTTON,
    PREV_SLOW_BUTTON,
    NEXT_FAST_BUTTON,
    SLOWER_BUTTON,
    FASTER_BUTTON,
    FULLSCREEN_BUTTON,
    DEFULLSCREEN_BUTTON,
    EXTENDED_BUTTON,
    PLAYLIST_BUTTON,
    SNAPSHOT_BUTTON,
    RECORD_BUTTON,
    ATOB_BUTTON,
    FRAME_BUTTON,
    REVERSE_BUTTON,
    SKIP_BACK_BUTTON,
    SKIP_FW_BUTTON,
    QUIT_BUTTON,
    RANDOM_BUTTON,
    LOOP_BUTTON,
    INFO_BUTTON,
    PREVIOUS_BUTTON,
    NEXT_BUTTON,
    OPEN_SUB_BUTTON,
    FULLWIDTH_BUTTON,
    BUTTON_MAX,

    SPLITTER = 0x20,
    INPUT_SLIDER,
    TIME_LABEL,
    VOLUME,
    VOLUME_SPECIAL,
    MENU_BUTTONS,
    TELETEXT_BUTTONS,
    ADVANCED_CONTROLLER,
    PLAYBACK_BUTTONS,
    ASPECT_RATIO_COMBOBOX,
    SPEED_LABEL,
    TIME_LABEL_ELAPSED,
    TIME_LABEL_REMAINING,
    SPECIAL_MAX,

    WIDGET_SPACER = 0x40,
    WIDGET_SPACER_EXTEND,
    WIDGET_MAX,
} buttonType_e;

static const char* const nameL[BUTTON_MAX] = { N_("Play"), N_("Stop"), N_("Open"),
    N_("Previous / Backward"), N_("Next / Forward"), N_("Slower"), N_("Faster"), N_("Fullscreen"),
    N_("De-Fullscreen"), N_("Extended panel"), N_("Playlist"), N_("Snapshot"),
    N_("Record"), N_("A->B Loop"), N_("Frame By Frame"), N_("Trickplay Reverse"),
    N_("Step backward" ), N_("Step forward"), N_("Quit"), N_("Random"),
    N_("Loop / Repeat"), N_("Information"), N_("Previous"), N_("Next"),
    N_("Open subtitles"), N_("Dock fullscreen controller")
};
static const char* const tooltipL[BUTTON_MAX] = { I_PLAY_TOOLTIP,
    N_("Stop playback"), N_("Open a medium"),
    N_("Previous media in the playlist, skip backward when keep-pressed"),
    N_("Next media in the playlist, skip forward when keep-pressed"), N_("Slower"), N_("Faster"),
    N_("Toggle the video in fullscreen"), N_("Toggle the video out fullscreen"),
    N_("Show extended settings" ), N_( "Toggle playlist" ),
    N_( "Take a snapshot" ), N_( "Record" ),
    N_( "Loop from point A to point B continuously." ), N_("Frame by frame"),
    N_("Reverse"), N_("Step backward"), N_("Step forward"), N_("Quit"),
    N_("Random"), N_("Change the loop and repeat modes"), N_("Information"),
    N_("Previous media in the playlist"), N_("Next media in the playlist"),
    N_("Open subtitles file"),
    N_("Dock/undock fullscreen controller to/from bottom of screen")
};
static const QString iconL[BUTTON_MAX] ={ ":/toolbar/play_b", ":/toolbar/stop_b",
    ":/toolbar/eject", ":/toolbar/previous_b", ":/toolbar/next_b",
    ":/toolbar/slower", ":/toolbar/faster", ":/toolbar/fullscreen",
    ":/toolbar/defullscreen", ":/toolbar/extended", ":/toolbar/playlist",
    ":/toolbar/snapshot", ":/toolbar/record", ":/toolbar/atob_nob",
    ":/toolbar/frame", ":/toolbar/reverse", ":/toolbar/skip_back",
    ":/toolbar/skip_fw", ":/toolbar/clear", ":/buttons/playlist/shuffle_on",
    ":/buttons/playlist/repeat_all", ":/menu/info",
    ":/toolbar/previous_b", ":/toolbar/next_b", ":/toolbar/eject", ":/toolbar/space"
};

enum
{
   WIDGET_NORMAL = 0x0,
   WIDGET_FLAT   = 0x1,
   WIDGET_BIG    = 0x2,
   WIDGET_SHINY  = 0x4,
};

class AdvControlsWidget;
class AbstractController : public QFrame
{
    friend class WidgetListing; /* For ToolBar Edition HACKS */

    Q_OBJECT
public:
    AbstractController( intf_thread_t  *_p_i, QWidget *_parent = 0 );

protected:
    intf_thread_t       *p_intf;

    QSignalMapper       *toolbarActionsMapper;
    QBoxLayout          *controlLayout;
    /* Change to BoxLayout if both dir are needed */

    AdvControlsWidget   *advControls;

    void parseAndCreate( const QString& config, QBoxLayout *controlLayout );

    virtual void createAndAddWidget( QBoxLayout *controlLayout, int i_index,
                                     buttonType_e i_type, int i_option );

    QWidget *createWidget( buttonType_e, int options = WIDGET_NORMAL );
private:
    static void setupButton( QAbstractButton * );
    QFrame *discFrame();
    QFrame *telexFrame();
    void applyAttributes( QToolButton *, bool b_flat, bool b_big );

    QHBoxLayout         *buttonGroupLayout;
protected slots:
    virtual void setStatus( int );

signals:
    void inputExists( bool ); /// This might be useful in the IM ?
    void inputPlaying( bool ); /// This might be useful in the IM ?
    void inputIsRecordable( bool ); /// same ?
    void inputIsTrickPlayable( bool ); /// same ?
};

/* Advanced Button Bar */
class AdvControlsWidget : public AbstractController
{
    Q_OBJECT
public:
    AdvControlsWidget( intf_thread_t *, QWidget *_parent = 0 );
};

/* Slider Bar */
class InputControlsWidget : public AbstractController
{
    Q_OBJECT
public:
    InputControlsWidget( intf_thread_t * , QWidget *_parent = 0 );
};

/* Button Bar */
class ControlsWidget : public AbstractController
{
    Q_OBJECT
public:
    /* p_intf, advanced control visible or not, blingbling or not */
    ControlsWidget( intf_thread_t *_p_i, bool b_advControls,
                    QWidget *_parent = 0 );

    void setGripVisible( bool b_visible )
    { grip->setVisible( b_visible ); }

protected:
    friend class MainInterface;

    bool b_advancedVisible;

private:
    QSizeGrip *grip;

protected slots:
    void toggleAdvanced();

signals:
    void advancedControlsToggled( bool );
};

/* to trying transparency with fullscreen controller on windows enable that */
/* it can be enabled on-non windows systems,
   but it will be transparent only with composite manager */
#define HAVE_TRANSPARENCY 1

/* Default value of opacity for FS controller */
#define DEFAULT_OPACITY 0.70

/* Used to restore the minimum width after a full-width switch */
#define FSC_WIDTH 800

#define FSC_HEIGHT 72

/***********************************
 * Fullscreen controller
 ***********************************/
class FullscreenControllerWidget : public AbstractController
{
    Q_OBJECT
public:
    FullscreenControllerWidget( intf_thread_t *, QWidget *_parent = 0  );
    virtual ~FullscreenControllerWidget();

    /* Vout */
    void fullscreenChanged( vout_thread_t *, bool b_fs, int i_timeout );
    void mouseChanged( vout_thread_t *, int i_mousex, int i_mousey );
    void toggleFullwidth();
    void updateFullwidthGeometry( int number );
    int targetScreen();

signals:
    void keyPressed( QKeyEvent * );

public slots:
    void setVoutList( vout_thread_t **, int );

protected:
    friend class MainInterface;

    virtual void mouseMoveEvent( QMouseEvent *event );
    virtual void mousePressEvent( QMouseEvent *event );
    virtual void mouseReleaseEvent( QMouseEvent *event );
    virtual void enterEvent( QEvent *event );
    virtual void leaveEvent( QEvent *event );
    virtual void keyPressEvent( QKeyEvent *event );

    virtual void customEvent( QEvent *event );

private slots:
    void showFSC();
    void planHideFSC();
    void hideFSC() { hide(); }
    void slowHideFSC();
    void restoreFSC();
    void centerFSC( int );

private:
    QTimer *p_hideTimer;
#if HAVE_TRANSPARENCY
    QTimer *p_slowHideTimer;
    bool b_slow_hide_begin;
    int  i_slow_hide_timeout;
    float f_opacity;
#endif

    int i_mouse_last_x, i_mouse_last_y;
    bool b_mouse_over;
    int i_screennumber;
    QRect screenRes;
    QRect previousScreenRes;
    QPoint previousPosition;

    /* List of vouts currently tracked */
    QList<vout_thread_t *> vout;

    /* Shared variable between FSC and VLC (protected by a lock) */
    vlc_mutex_t lock;
    bool        b_fullscreen;
    int         i_hide_timeout;  /* FSC hiding timeout, same as mouse hiding timeout */
    int i_mouse_last_move_x;
    int i_mouse_last_move_y;

    bool isWideFSC;
};

#endif
<commit_msg>Qt4: replace awkward word 'keep-pressed'<commit_after>/*****************************************************************************
 * controller.hpp : Controller for the main interface
 ****************************************************************************
 * Copyright (C) 2006-2008 the VideoLAN team
 * $Id$
 *
 * Authors: Jean-Baptiste Kempf <jb@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifndef QVLC_CONTROLLER_H_
#define QVLC_CONTROLLER_H_

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "qt4.hpp"

#include <QFrame>
#include <QString>
#include <QSizeGrip>

#define MAIN_TB1_DEFAULT "64;39;64;38;65"
#define MAIN_TB2_DEFAULT "0-2;64;3;1;4;64;7;9;64;10;20;19;64-4;37;65;35-4"
#define ADV_TB_DEFAULT "12;11;13;14"
#define INPT_TB_DEFAULT "43;33-4;44"
#define FSC_TB_DEFAULT "0-2;64;3;1;4;64;37;64;38;64;8;65;25;35-4;34"

#define I_PLAY_TOOLTIP N_("Play\nIf the playlist is empty, open a medium")

class QPixmap;
class QLabel;

class QGridLayout;
class QBoxLayout;
class QHBoxLayout;
class QVBoxLayout;

class QAbstractSlider;
class QAbstractButton;
class SeekSlider;
class QToolButton;

class VolumeClickHandler;
class WidgetListing;

class QSignalMapper;
class QTimer;

typedef enum buttonType_e
{
    PLAY_BUTTON,
    STOP_BUTTON,
    OPEN_BUTTON,
    PREV_SLOW_BUTTON,
    NEXT_FAST_BUTTON,
    SLOWER_BUTTON,
    FASTER_BUTTON,
    FULLSCREEN_BUTTON,
    DEFULLSCREEN_BUTTON,
    EXTENDED_BUTTON,
    PLAYLIST_BUTTON,
    SNAPSHOT_BUTTON,
    RECORD_BUTTON,
    ATOB_BUTTON,
    FRAME_BUTTON,
    REVERSE_BUTTON,
    SKIP_BACK_BUTTON,
    SKIP_FW_BUTTON,
    QUIT_BUTTON,
    RANDOM_BUTTON,
    LOOP_BUTTON,
    INFO_BUTTON,
    PREVIOUS_BUTTON,
    NEXT_BUTTON,
    OPEN_SUB_BUTTON,
    FULLWIDTH_BUTTON,
    BUTTON_MAX,

    SPLITTER = 0x20,
    INPUT_SLIDER,
    TIME_LABEL,
    VOLUME,
    VOLUME_SPECIAL,
    MENU_BUTTONS,
    TELETEXT_BUTTONS,
    ADVANCED_CONTROLLER,
    PLAYBACK_BUTTONS,
    ASPECT_RATIO_COMBOBOX,
    SPEED_LABEL,
    TIME_LABEL_ELAPSED,
    TIME_LABEL_REMAINING,
    SPECIAL_MAX,

    WIDGET_SPACER = 0x40,
    WIDGET_SPACER_EXTEND,
    WIDGET_MAX,
} buttonType_e;

static const char* const nameL[BUTTON_MAX] = { N_("Play"), N_("Stop"), N_("Open"),
    N_("Previous / Backward"), N_("Next / Forward"), N_("Slower"), N_("Faster"), N_("Fullscreen"),
    N_("De-Fullscreen"), N_("Extended panel"), N_("Playlist"), N_("Snapshot"),
    N_("Record"), N_("A->B Loop"), N_("Frame By Frame"), N_("Trickplay Reverse"),
    N_("Step backward" ), N_("Step forward"), N_("Quit"), N_("Random"),
    N_("Loop / Repeat"), N_("Information"), N_("Previous"), N_("Next"),
    N_("Open subtitles"), N_("Dock fullscreen controller")
};
static const char* const tooltipL[BUTTON_MAX] = { I_PLAY_TOOLTIP,
    N_("Stop playback"), N_("Open a medium"),
    N_("Previous media in the playlist, skip backward when held"),
    N_("Next media in the playlist, skip forward when held"), N_("Slower"), N_("Faster"),
    N_("Toggle the video in fullscreen"), N_("Toggle the video out fullscreen"),
    N_("Show extended settings" ), N_( "Toggle playlist" ),
    N_( "Take a snapshot" ), N_( "Record" ),
    N_( "Loop from point A to point B continuously." ), N_("Frame by frame"),
    N_("Reverse"), N_("Step backward"), N_("Step forward"), N_("Quit"),
    N_("Random"), N_("Change the loop and repeat modes"), N_("Information"),
    N_("Previous media in the playlist"), N_("Next media in the playlist"),
    N_("Open subtitles file"),
    N_("Dock/undock fullscreen controller to/from bottom of screen")
};
static const QString iconL[BUTTON_MAX] ={ ":/toolbar/play_b", ":/toolbar/stop_b",
    ":/toolbar/eject", ":/toolbar/previous_b", ":/toolbar/next_b",
    ":/toolbar/slower", ":/toolbar/faster", ":/toolbar/fullscreen",
    ":/toolbar/defullscreen", ":/toolbar/extended", ":/toolbar/playlist",
    ":/toolbar/snapshot", ":/toolbar/record", ":/toolbar/atob_nob",
    ":/toolbar/frame", ":/toolbar/reverse", ":/toolbar/skip_back",
    ":/toolbar/skip_fw", ":/toolbar/clear", ":/buttons/playlist/shuffle_on",
    ":/buttons/playlist/repeat_all", ":/menu/info",
    ":/toolbar/previous_b", ":/toolbar/next_b", ":/toolbar/eject", ":/toolbar/space"
};

enum
{
   WIDGET_NORMAL = 0x0,
   WIDGET_FLAT   = 0x1,
   WIDGET_BIG    = 0x2,
   WIDGET_SHINY  = 0x4,
};

class AdvControlsWidget;
class AbstractController : public QFrame
{
    friend class WidgetListing; /* For ToolBar Edition HACKS */

    Q_OBJECT
public:
    AbstractController( intf_thread_t  *_p_i, QWidget *_parent = 0 );

protected:
    intf_thread_t       *p_intf;

    QSignalMapper       *toolbarActionsMapper;
    QBoxLayout          *controlLayout;
    /* Change to BoxLayout if both dir are needed */

    AdvControlsWidget   *advControls;

    void parseAndCreate( const QString& config, QBoxLayout *controlLayout );

    virtual void createAndAddWidget( QBoxLayout *controlLayout, int i_index,
                                     buttonType_e i_type, int i_option );

    QWidget *createWidget( buttonType_e, int options = WIDGET_NORMAL );
private:
    static void setupButton( QAbstractButton * );
    QFrame *discFrame();
    QFrame *telexFrame();
    void applyAttributes( QToolButton *, bool b_flat, bool b_big );

    QHBoxLayout         *buttonGroupLayout;
protected slots:
    virtual void setStatus( int );

signals:
    void inputExists( bool ); /// This might be useful in the IM ?
    void inputPlaying( bool ); /// This might be useful in the IM ?
    void inputIsRecordable( bool ); /// same ?
    void inputIsTrickPlayable( bool ); /// same ?
};

/* Advanced Button Bar */
class AdvControlsWidget : public AbstractController
{
    Q_OBJECT
public:
    AdvControlsWidget( intf_thread_t *, QWidget *_parent = 0 );
};

/* Slider Bar */
class InputControlsWidget : public AbstractController
{
    Q_OBJECT
public:
    InputControlsWidget( intf_thread_t * , QWidget *_parent = 0 );
};

/* Button Bar */
class ControlsWidget : public AbstractController
{
    Q_OBJECT
public:
    /* p_intf, advanced control visible or not, blingbling or not */
    ControlsWidget( intf_thread_t *_p_i, bool b_advControls,
                    QWidget *_parent = 0 );

    void setGripVisible( bool b_visible )
    { grip->setVisible( b_visible ); }

protected:
    friend class MainInterface;

    bool b_advancedVisible;

private:
    QSizeGrip *grip;

protected slots:
    void toggleAdvanced();

signals:
    void advancedControlsToggled( bool );
};

/* to trying transparency with fullscreen controller on windows enable that */
/* it can be enabled on-non windows systems,
   but it will be transparent only with composite manager */
#define HAVE_TRANSPARENCY 1

/* Default value of opacity for FS controller */
#define DEFAULT_OPACITY 0.70

/* Used to restore the minimum width after a full-width switch */
#define FSC_WIDTH 800

#define FSC_HEIGHT 72

/***********************************
 * Fullscreen controller
 ***********************************/
class FullscreenControllerWidget : public AbstractController
{
    Q_OBJECT
public:
    FullscreenControllerWidget( intf_thread_t *, QWidget *_parent = 0  );
    virtual ~FullscreenControllerWidget();

    /* Vout */
    void fullscreenChanged( vout_thread_t *, bool b_fs, int i_timeout );
    void mouseChanged( vout_thread_t *, int i_mousex, int i_mousey );
    void toggleFullwidth();
    void updateFullwidthGeometry( int number );
    int targetScreen();

signals:
    void keyPressed( QKeyEvent * );

public slots:
    void setVoutList( vout_thread_t **, int );

protected:
    friend class MainInterface;

    virtual void mouseMoveEvent( QMouseEvent *event );
    virtual void mousePressEvent( QMouseEvent *event );
    virtual void mouseReleaseEvent( QMouseEvent *event );
    virtual void enterEvent( QEvent *event );
    virtual void leaveEvent( QEvent *event );
    virtual void keyPressEvent( QKeyEvent *event );

    virtual void customEvent( QEvent *event );

private slots:
    void showFSC();
    void planHideFSC();
    void hideFSC() { hide(); }
    void slowHideFSC();
    void restoreFSC();
    void centerFSC( int );

private:
    QTimer *p_hideTimer;
#if HAVE_TRANSPARENCY
    QTimer *p_slowHideTimer;
    bool b_slow_hide_begin;
    int  i_slow_hide_timeout;
    float f_opacity;
#endif

    int i_mouse_last_x, i_mouse_last_y;
    bool b_mouse_over;
    int i_screennumber;
    QRect screenRes;
    QRect previousScreenRes;
    QPoint previousPosition;

    /* List of vouts currently tracked */
    QList<vout_thread_t *> vout;

    /* Shared variable between FSC and VLC (protected by a lock) */
    vlc_mutex_t lock;
    bool        b_fullscreen;
    int         i_hide_timeout;  /* FSC hiding timeout, same as mouse hiding timeout */
    int i_mouse_last_move_x;
    int i_mouse_last_move_y;

    bool isWideFSC;
};

#endif
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2019 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 "modules/prediction/common/semantic_map.h"

#include <string>
#include <vector>

#include "cyber/common/file.h"
#include "cyber/common/log.h"
#include "modules/common/configs/config_gflags.h"
#include "modules/common/util/string_util.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/pose/pose_container.h"

namespace apollo {
namespace prediction {

SemanticMap::SemanticMap() {}

void SemanticMap::Init() {
  const std::string file_path =
      apollo::common::util::StrCat(FLAGS_map_dir, "/base_map.png");
  if (cyber::common::PathExists(file_path)) {
    base_img_ = cv::imread(file_path, CV_LOAD_IMAGE_COLOR);
  }
  curr_img_ = cv::Mat(2000, 2000, CV_8UC3, cv::Scalar(0, 0, 0));
}

void SemanticMap::RunCurrFrame(const FrameEnv& curr_frame_env) {
  // TODO(Hongyi): moving all these magic numbers to conf
  curr_timestamp_ = curr_frame_env.timestamp();
  curr_base_x_ = curr_frame_env.ego_history().feature(0).position().x() - 100.0;
  curr_base_y_ = curr_frame_env.ego_history().feature(0).position().y() - 100.0;
  cv::Rect rect(static_cast<int>((curr_base_x_ - 585950.0) / 0.1),
            static_cast<int>(18000 - (curr_base_y_ - 4140000.0) / 0.1) - 2000,
            2000, 2000);
  base_img_(rect).copyTo(curr_img_);

  // Draw ego_vehicle_history
  DrawHistory(curr_frame_env.ego_history(), cv::Scalar(0, 255, 255));

  // Draw obstacles_history
  for (auto& history : curr_frame_env.obstacles_history()) {
    DrawHistory(history);
  }

  // For disaplay
  cv::namedWindow("Display window", cv::WINDOW_NORMAL);
  cv::imshow("Display window", curr_img_);
  cv::waitKey();
}

void SemanticMap::DrawRect(const Feature& feature, const cv::Scalar& color) {
  double obs_l = feature.length();
  double obs_w = feature.width();
  double obs_x = feature.position().x();
  double obs_y = feature.position().y();
  double theta = feature.theta();
  std::vector<cv::Point> polygon;
  // point 1 (head-right point)
  polygon.push_back(
      GetTransPoint(obs_x + (cos(theta) * obs_l - sin(theta) * obs_w) / 2,
                    obs_y + (sin(theta) * obs_l + cos(theta) * obs_w) / 2));
  // point 2 (head-left point)
  polygon.push_back(
      GetTransPoint(obs_x + (cos(theta) * -obs_l - sin(theta) * obs_w) / 2,
                    obs_y + (sin(theta) * -obs_l + cos(theta) * obs_w) / 2));
  // point 3 (head-left point)
  polygon.push_back(
      GetTransPoint(obs_x + (cos(theta) * -obs_l - sin(theta) * -obs_w) / 2,
                    obs_y + (sin(theta) * -obs_l + cos(theta) * -obs_w) / 2));
  // point 4 (head-left point)
  polygon.push_back(
      GetTransPoint(obs_x + (cos(theta) * obs_l - sin(theta) * -obs_w) / 2,
                    obs_y + (sin(theta) * obs_l + cos(theta) * -obs_w) / 2));
  cv::fillPoly(curr_img_, std::vector<std::vector<cv::Point>>({polygon}),
               color);
}

void SemanticMap::DrawPoly(const Feature& feature, const cv::Scalar& color) {
  std::vector<cv::Point> polygon;
  for (auto& polygon_point : feature.polygon_point()) {
    polygon.push_back(GetTransPoint(polygon_point.x(), polygon_point.y()));
  }
  cv::fillPoly(curr_img_, std::vector<std::vector<cv::Point>>({polygon}),
               color);
}

void SemanticMap::DrawHistory(const ObstacleHistory& history,
                              const cv::Scalar& color) {
  for (int i = history.feature_size() - 1; i >= 0; --i) {
    const Feature& feature = history.feature(i);
    double time_decay = 1.0 - curr_timestamp_ + feature.timestamp();
    cv::Scalar decay_color = color * time_decay;
    if (feature.id() == -1) {
      DrawRect(feature, decay_color);
    } else {
      DrawPoly(feature, decay_color);
    }
  }
}

}  // namespace prediction
}  // namespace apollo
<commit_msg>Update semantic_map.cc<commit_after>/******************************************************************************
 * Copyright 2019 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 "modules/prediction/common/semantic_map.h"

#include <string>
#include <vector>

#include "cyber/common/file.h"
#include "cyber/common/log.h"
#include "modules/common/configs/config_gflags.h"
#include "modules/common/util/string_util.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/pose/pose_container.h"

namespace apollo {
namespace prediction {

SemanticMap::SemanticMap() {}

void SemanticMap::Init() {
  const std::string file_path =
      apollo::common::util::StrCat(FLAGS_map_dir, "/base_map.png");
  if (cyber::common::PathExists(file_path)) {
    base_img_ = cv::imread(file_path, CV_LOAD_IMAGE_COLOR);
  }
  curr_img_ = cv::Mat(2000, 2000, CV_8UC3, cv::Scalar(0, 0, 0));
}

void SemanticMap::RunCurrFrame(const FrameEnv& curr_frame_env) {
  // TODO(Hongyi): moving all these magic numbers to conf
  curr_timestamp_ = curr_frame_env.timestamp();
  curr_base_x_ = curr_frame_env.ego_history().feature(0).position().x() - 100.0;
  curr_base_y_ = curr_frame_env.ego_history().feature(0).position().y() - 100.0;
  cv::Rect rect(static_cast<int>((curr_base_x_ - 585950.0) / 0.1),
            static_cast<int>(18000 - (curr_base_y_ - 4140000.0) / 0.1) - 2000,
            2000, 2000);
  base_img_(rect).copyTo(curr_img_);

  // Draw ego_vehicle_history
  DrawHistory(curr_frame_env.ego_history(), cv::Scalar(0, 255, 255));

  // Draw obstacles_history
  for (auto& history : curr_frame_env.obstacles_history()) {
    DrawHistory(history);
  }

  // For disaplay
  cv::namedWindow("Display window", cv::WINDOW_NORMAL);
  cv::imshow("Display window", curr_img_);
  cv::waitKey();
}

void SemanticMap::DrawRect(const Feature& feature, const cv::Scalar& color) {
  double obs_l = feature.length();
  double obs_w = feature.width();
  double obs_x = feature.position().x();
  double obs_y = feature.position().y();
  double theta = feature.theta();
  std::vector<cv::Point> polygon;
  // point 1 (head-right point)
  polygon.push_back(
      GetTransPoint(obs_x + (cos(theta) * obs_l - sin(theta) * obs_w) / 2,
                    obs_y + (sin(theta) * obs_l + cos(theta) * obs_w) / 2));
  // point 2 (head-left point)
  polygon.push_back(
      GetTransPoint(obs_x + (cos(theta) * -obs_l - sin(theta) * obs_w) / 2,
                    obs_y + (sin(theta) * -obs_l + cos(theta) * obs_w) / 2));
  // point 3 (back-left point)
  polygon.push_back(
      GetTransPoint(obs_x + (cos(theta) * -obs_l - sin(theta) * -obs_w) / 2,
                    obs_y + (sin(theta) * -obs_l + cos(theta) * -obs_w) / 2));
  // point 4 (back-right point)
  polygon.push_back(
      GetTransPoint(obs_x + (cos(theta) * obs_l - sin(theta) * -obs_w) / 2,
                    obs_y + (sin(theta) * obs_l + cos(theta) * -obs_w) / 2));
  cv::fillPoly(curr_img_, std::vector<std::vector<cv::Point>>({polygon}),
               color);
}

void SemanticMap::DrawPoly(const Feature& feature, const cv::Scalar& color) {
  std::vector<cv::Point> polygon;
  for (auto& polygon_point : feature.polygon_point()) {
    polygon.push_back(GetTransPoint(polygon_point.x(), polygon_point.y()));
  }
  cv::fillPoly(curr_img_, std::vector<std::vector<cv::Point>>({polygon}),
               color);
}

void SemanticMap::DrawHistory(const ObstacleHistory& history,
                              const cv::Scalar& color) {
  for (int i = history.feature_size() - 1; i >= 0; --i) {
    const Feature& feature = history.feature(i);
    double time_decay = 1.0 - curr_timestamp_ + feature.timestamp();
    cv::Scalar decay_color = color * time_decay;
    if (feature.id() == -1) {
      DrawRect(feature, decay_color);
    } else {
      DrawPoly(feature, decay_color);
    }
  }
}

}  // namespace prediction
}  // namespace apollo
<|endoftext|>


<commit_before>/****************** <SNX heading BEGIN do not edit this line> *****************
 *
 * sonix
 *
 * Original Authors:
 *   Kevin Meinert, Carolina Cruz-Neira
 *
 ****************** <SNX heading END do not edit this line> ******************/

/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2007 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * 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., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <snx/snxConfig.h>

#include <gmtl/Math.h>
#include <gmtl/Vec.h>
#include <gmtl/MatrixOps.h>
#include <gmtl/VecOps.h>
#include <gmtl/Xforms.h>
#include <vpr/Util/Assert.h>

#include <snx/SoundImplementation.h>

namespace snx
{

void SoundImplementation::copy( const SoundImplementation& si )
{
   // copy over the current state
   mName = si.mName;
   mSounds = si.mSounds;
   mListenerPos = si.mListenerPos;
   mSoundAPIInfo = si.mSoundAPIInfo;
}

void SoundImplementation::configure( const std::string& alias, const snx::SoundInfo& description )
{
   this->unbind( alias );
   snx::SoundInfo temp = mSounds[alias];
   mSounds[alias] = description; // TODO: put is_playing within the SoundInfo.

   // restore fields that should be preserved on a reconfigure...
   mSounds[alias].triggerOnNextBind = temp.triggerOnNextBind;
   //std::cout<<"DEBUG: triggerOnNextBind = "<<mSounds[alias].triggerOnNextBind<<"\n"<<std::flush;

   if (this->isStarted())
   {
      this->bind( alias );
   }
}

void SoundImplementation::remove(const std::string& alias)
{
   if (this->isStarted())
   {
      this->unbind( alias );
   }
   mSounds.erase( alias );
}

void SoundImplementation::bindAll()
{
   std::map< std::string, snx::SoundInfo >::iterator it;
   for( it = mSounds.begin(); it != mSounds.end(); ++it)
   {
      //std::cout<<"DEBUG: loading alias: "<<(*it).first<<"\n"<<std::flush;
      this->bind( (*it).first );
   }
}

void SoundImplementation::unbindAll()
{
   std::map< std::string, snx::SoundInfo >::iterator it;
   for( it = mSounds.begin(); it != mSounds.end(); ++it)
   {
      //std::cout<<"DEBUG: loading alias: "<<(*it).first<<"\n"<<std::flush;
      this->unbind( (*it).first );
   }
   /*
   std::map< std::string, AlSoundInfo >::iterator it;
   for( it = mBindLookup.begin(); it != mBindLookup.end(); ++it)
   {
      this->unbind( (*it).first );
   }

   vprASSERT(mBindLookup.size() == 0 && "unbindAll failed");
   */
}

} // End of snx namespace
<commit_msg>Removed commented out code that has no obvious value.<commit_after>/****************** <SNX heading BEGIN do not edit this line> *****************
 *
 * sonix
 *
 * Original Authors:
 *   Kevin Meinert, Carolina Cruz-Neira
 *
 ****************** <SNX heading END do not edit this line> ******************/

/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2007 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * 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., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <snx/snxConfig.h>

#include <gmtl/Math.h>
#include <gmtl/Vec.h>
#include <gmtl/MatrixOps.h>
#include <gmtl/VecOps.h>
#include <gmtl/Xforms.h>
#include <vpr/Util/Assert.h>

#include <snx/SoundImplementation.h>

namespace snx
{

void SoundImplementation::copy( const SoundImplementation& si )
{
   // copy over the current state
   mName = si.mName;
   mSounds = si.mSounds;
   mListenerPos = si.mListenerPos;
   mSoundAPIInfo = si.mSoundAPIInfo;
}

void SoundImplementation::configure( const std::string& alias, const snx::SoundInfo& description )
{
   this->unbind( alias );
   snx::SoundInfo temp = mSounds[alias];
   mSounds[alias] = description; // TODO: put is_playing within the SoundInfo.

   // restore fields that should be preserved on a reconfigure...
   mSounds[alias].triggerOnNextBind = temp.triggerOnNextBind;
   //std::cout<<"DEBUG: triggerOnNextBind = "<<mSounds[alias].triggerOnNextBind<<"\n"<<std::flush;

   if (this->isStarted())
   {
      this->bind( alias );
   }
}

void SoundImplementation::remove(const std::string& alias)
{
   if (this->isStarted())
   {
      this->unbind( alias );
   }
   mSounds.erase( alias );
}

void SoundImplementation::bindAll()
{
   std::map< std::string, snx::SoundInfo >::iterator it;
   for( it = mSounds.begin(); it != mSounds.end(); ++it)
   {
      //std::cout<<"DEBUG: loading alias: "<<(*it).first<<"\n"<<std::flush;
      this->bind( (*it).first );
   }
}

void SoundImplementation::unbindAll()
{
   std::map< std::string, snx::SoundInfo >::iterator it;
   for( it = mSounds.begin(); it != mSounds.end(); ++it)
   {
      //std::cout<<"DEBUG: loading alias: "<<(*it).first<<"\n"<<std::flush;
      this->unbind( (*it).first );
   }
}

} // End of snx namespace
<|endoftext|>


<commit_before>/* ******************************************************************************
 *
 *
 * This program and the accompanying materials are made available under the
 * terms of the Apache License, Version 2.0 which is available at
 * https://www.apache.org/licenses/LICENSE-2.0.
 *
 *  See the NOTICE file distributed with this work for additional
 *  information regarding copyright ownership.
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 ******************************************************************************/

//
// @author Yurii Shyrma (iuriish@yahoo.com), created on 19.04.2018
// @author raver119@gmail.com
//

#include <ops/declarable/helpers/activations.h>
#include <helpers/ShapeUtils.h>
#include <numeric>
#include <helpers/ConstantTadHelper.h>
#include <execution/Threads.h>

namespace sd    {
namespace ops     {
namespace helpers {

///////////////////////////////////////////////////////////////////
    template <typename T>
    void static _softMaxDerivForVector(sd::LaunchContext * context, const void *input, const Nd4jLong *inShapeInfo, void *output) {

        const T* inBuff  = reinterpret_cast<const T *>(input);
        T* outBuff = reinterpret_cast<T *>(output);

        T max = -DataTypeUtils::max<T>();
        T sum = 0.;
        int length = shape::length(inShapeInfo);

        for (int i = 0; i < length; i++) {
            const Nd4jLong offset = shape::getIndexOffset(i, inShapeInfo);
            max = sd::math::nd4j_max<T>(max, inBuff[offset]);
        }

        for (int i = 0; i < length; i++) {
            const Nd4jLong offset = shape::getIndexOffset(i, inShapeInfo);
            outBuff[offset] = sd::math::nd4j_exp<T, T>(inBuff[offset] - max);
            sum += outBuff[offset];
        }

        for (int i = 0; i < length; i++) {
            const Nd4jLong offset = shape::getIndexOffset(i, inShapeInfo);
            outBuff[offset] /= sum;
            outBuff[offset] *= (1.f - outBuff[offset]);     // derivative
        }
    }

///////////////////////////////////////////////////////////////////
    void softmaxDerivative(sd::LaunchContext * context, const NDArray& input, NDArray& output, const int dimension) {

        const int rank = input.rankOf();
        int temp;

        if(shape::isCommonVector(input.shapeInfo(), temp)) {

            BUILD_SINGLE_SELECTOR(input.dataType(), _softMaxDerivForVector, (context, input.buffer(), input.shapeInfo(), output.buffer()), FLOAT_TYPES);
        }
        else {
            auto maxAlongDim = const_cast<NDArray&>(input).reduceAlongDimension(reduce::Max, {dimension}, true);
            (input - maxAlongDim).applyTransform(transform::Exp, output); // output contains exponents temporarily
            auto sumAlongDim = output.reduceAlongDimension(reduce::Sum, {dimension}, true);
            output /= sumAlongDim;
            output *= (1.f - output);   // derivative
        }
    }

///////////////////////////////////////////////////////////////////
    template <typename T>
    void logSoftMaxForVector_(void const* input, Nd4jLong const* inShapeInfo, void *output, Nd4jLong const* outShapeInfo) {
        auto inBuff  = reinterpret_cast<T const*>(input);
        auto outBuff = reinterpret_cast<T *>(output);

        T max = -DataTypeUtils::max<T>();
        T sum = 0;

        auto inEWS  = shape::elementWiseStride(inShapeInfo);
        auto length = shape::length(inShapeInfo);

        if (inEWS == 1) {
            for (Nd4jLong i = 0; i < length; i++)
                max = sd::math::nd4j_max<T>(max, inBuff[i]);

            PRAGMA_OMP_SIMD_SUM(sum)
            for (Nd4jLong i = 0; i < length; i++) {
                outBuff[i] = sd::math::nd4j_exp<T,T>(inBuff[i] - max);
                sum += outBuff[i];
            }

            PRAGMA_OMP_SIMD
            for (Nd4jLong i = 0; i < length; i++) {
                outBuff[i] /= sum;
                outBuff[i] = sd::math::nd4j_log<T,T>(outBuff[i]);
            }
        }
        else if (inEWS > 1) {

            PRAGMA_OMP_SIMD_MAX(max)
            for (Nd4jLong i = 0; i < length; i++)
                max = sd::math::nd4j_max<T>(max, inBuff[i * inEWS]);

            PRAGMA_OMP_SIMD_SUM(sum)
            for (Nd4jLong i = 0; i < length; i++) {
                outBuff[i * inEWS] = sd::math::nd4j_exp<T,T>(inBuff[i * inEWS] - max);
                sum += outBuff[i * inEWS];
            }

            PRAGMA_OMP_SIMD
            for (Nd4jLong i = 0; i < length; i++) {
                outBuff[i * inEWS] /= sum;
                outBuff[i * inEWS] = sd::math::nd4j_log<T, T>(outBuff[i * inEWS]);
            }
        }
    }

    ///////////////////////////////////////////////////////////////////
    void logSoftMaxForVector(sd::LaunchContext* context, const NDArray& input, NDArray& output) {

        if(!input.isVector() || !output.isVector())
            throw std::runtime_error("ops::helpers::logSoftMaxForVector function input and output arrays must be vectors !");

        auto xType = input.dataType();
        BUILD_SINGLE_SELECTOR(xType, logSoftMaxForVector_, (input.buffer(), input.shapeInfo(), output.buffer(), output.shapeInfo()), FLOAT_TYPES);
    }

//////////////////////////////////////////////////////////////////////////
void prelu(sd::LaunchContext * context, const NDArray& input, const NDArray& alpha, NDArray& output) {
    const Nd4jLong inputLen = input.lengthOf();
    const Nd4jLong* inputShapeInfo = input.shapeInfo();
    const Nd4jLong* alphaShapeInfo = alpha.shapeInfo();

    auto func = PRAGMA_THREADS_FOR {
        for (auto i = start; i < stop; i++) {
            // FIXME: double!
            double x = input.e<double>(i);
            if (x < 0.0) {
                // FIXME: double
                output.p(i, (x * alpha.e<double>(shape::subArrayIndex(i, inputShapeInfo, alphaShapeInfo))));
            } else
                output.p(i, x);
        }
    };

    samediff::Threads::parallel_for(func, 0, inputLen);
}

//////////////////////////////////////////////////////////////////////////
void preluBP(sd::LaunchContext * context, const NDArray& input, const NDArray& alpha, const NDArray& dLdO, NDArray& dLdI, NDArray& dLdA) {

    const Nd4jLong inputLen = input.lengthOf();
    const Nd4jLong* inputShapeInfo = input.shapeInfo();
    const Nd4jLong* alphaShapeInfo = alpha.shapeInfo();

    dLdA.assign(0.0f);

    for(Nd4jLong i = 0; i < inputLen; ++i) {
        // FIXME: double
        double x   = input.e<double>(i);
        double grO = dLdO.e<double>(i);
        if(x < 0.0) {
            Nd4jLong alphaInd = shape::subArrayIndex(i, inputShapeInfo, alphaShapeInfo);
            dLdI.p(i, grO * alpha.e<double>(alphaInd));
            double prevVal = dLdA.e<double>(alphaInd);
            prevVal += (grO * x);
            dLdA.p(alphaInd, prevVal);
        }
        else
            dLdI.p(i, grO);
    }
}

    bool checkAlphaShapeLen(std::vector<Nd4jLong> const& expectedShape, Nd4jLong shapeLen) {
        Nd4jLong expectedAlphaLen = std::accumulate(expectedShape.cbegin(), expectedShape.cend(), 1, std::multiplies<Nd4jLong>());
        return expectedAlphaLen == shapeLen;
    }
    template <typename T>
    static void thresholdRelu_(NDArray const& input, double threshold, NDArray& output) {
        auto routine = LAMBDA_T(_x, threshold) {
            return _x > (T)threshold? _x: (T)0.f;
        };
        const_cast<NDArray&>(input).applyLambda<T>(routine, output);
    }

    void thresholdRelu(sd::LaunchContext * context, NDArray const& input, double threshold, NDArray& output) {
        BUILD_SINGLE_SELECTOR(input.dataType(), thresholdRelu_, (input, threshold, output), FLOAT_TYPES);
    }

    template <typename T>
    static void thresholdReluDerivative_(sd::LaunchContext * context, NDArray* input, double theta, NDArray* dLdO, NDArray* output) {
        auto derivative = LAMBDA_TT(_x, grO, theta) {if (_x > theta) return grO; else return static_cast<T>(0); };

        input->applyPairwiseLambda<T>(*dLdO, derivative, *output);

    }

    void thresholdReluDerivative(sd::LaunchContext * context, NDArray* input, double threshold, NDArray* dLdO, NDArray* output) {
        BUILD_SINGLE_SELECTOR(input->dataType(), thresholdReluDerivative_, (context, input, threshold, dLdO, output), FLOAT_TYPES);
    }

    ///////////////////////////////////////////////////////////////////
    void logSoftmax(sd::LaunchContext * context, const NDArray& input, NDArray& output, const int dimension) {

        const int rank = input.rankOf();

        if(input.isVector()) {

            if(rank == 1 || input.sizeAt(dimension) != 1) {
                BUILD_SINGLE_SELECTOR(input.dataType(), logSoftMaxForVector_, (input.buffer(), input.shapeInfo(), output.buffer(), output.shapeInfo()), FLOAT_TYPES);
            }
            else
                output = 0.;
        }
        else {

            auto maxAlongDim = const_cast<NDArray&>(input).reduceAlongDimension(reduce::Max, {dimension}, true);
            (input - maxAlongDim).applyTransform(transform::Exp, output); // output contains exponents temporarily
            auto sumAlongDim = output.reduceAlongDimension(reduce::Sum, {dimension}, true);
            output /= sumAlongDim;
            output.applyTransform(transform::Log, output);
        }
    }

    BUILD_SINGLE_TEMPLATE(template void thresholdReluDerivative_, (sd::LaunchContext * context, NDArray* input, double threshold, NDArray* dLdO, NDArray* output), FLOAT_TYPES);
    BUILD_SINGLE_TEMPLATE(template void logSoftMaxForVector_, (void const* input, Nd4jLong const* inShapeInfo, void *output, Nd4jLong const* outShapeInfo), FLOAT_TYPES);
    BUILD_SINGLE_TEMPLATE(template void _softMaxDerivForVector, (sd::LaunchContext * context, const void *input, const Nd4jLong *inShapeInfo, void *output), FLOAT_TYPES);

}
}
}

<commit_msg>Update activations.cpp<commit_after>/* ******************************************************************************
 *
 *
 * This program and the accompanying materials are made available under the
 * terms of the Apache License, Version 2.0 which is available at
 * https://www.apache.org/licenses/LICENSE-2.0.
 *
 *  See the NOTICE file distributed with this work for additional
 *  information regarding copyright ownership.
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 ******************************************************************************/

//
// @author Yurii Shyrma (iuriish@yahoo.com), created on 19.04.2018
// @author raver119@gmail.com
//

#include <ops/declarable/helpers/activations.h>
#include <helpers/ShapeUtils.h>
#include <numeric>
#include <helpers/ConstantTadHelper.h>
#include <execution/Threads.h>

namespace sd    {
namespace ops     {
namespace helpers {

///////////////////////////////////////////////////////////////////
    template <typename T>
    void static _softMaxDerivForVector(sd::LaunchContext * context, const void *input, const Nd4jLong *inShapeInfo, void *output) {

        const T* inBuff  = reinterpret_cast<const T *>(input);
        T* outBuff = reinterpret_cast<T *>(output);

        T max = -DataTypeUtils::max<T>();
        T sum = 0.;
        int length = shape::length(inShapeInfo);

        for (int i = 0; i < length; i++) {
            const Nd4jLong offset = shape::getIndexOffset(i, inShapeInfo);
            max = sd::math::nd4j_max<T>(max, inBuff[offset]);
        }

        for (int i = 0; i < length; i++) {
            const Nd4jLong offset = shape::getIndexOffset(i, inShapeInfo);
            outBuff[offset] = sd::math::nd4j_exp<T, T>(inBuff[offset] - max);
            sum += outBuff[offset];
        }

        for (int i = 0; i < length; i++) {
            const Nd4jLong offset = shape::getIndexOffset(i, inShapeInfo);
            outBuff[offset] /= sum;
            outBuff[offset] *= (1.f - outBuff[offset]);     // derivative
        }
    }

///////////////////////////////////////////////////////////////////
    void softmaxDerivative(sd::LaunchContext * context, const NDArray& input, NDArray& output, const int dimension) {

        const int rank = input.rankOf();
        int temp;

        if(shape::isCommonVector(input.shapeInfo(), temp)) {

            BUILD_SINGLE_SELECTOR(input.dataType(), _softMaxDerivForVector, (context, input.buffer(), input.shapeInfo(), output.buffer()), FLOAT_TYPES);
        }
        else {
            auto maxAlongDim = const_cast<NDArray&>(input).reduceAlongDimension(reduce::Max, {dimension}, true);
            (input - maxAlongDim).applyTransform(transform::Exp, output); // output contains exponents temporarily
            auto sumAlongDim = output.reduceAlongDimension(reduce::Sum, {dimension}, true);
            output /= sumAlongDim;
            output *= (1.f - output);   // derivative
        }
    }

///////////////////////////////////////////////////////////////////
    template <typename T>
    void logSoftMaxForVector_(void const* input, Nd4jLong const* inShapeInfo, void *output, Nd4jLong const* outShapeInfo) {
        auto inBuff  = reinterpret_cast<T const*>(input);
        auto outBuff = reinterpret_cast<T *>(output);

        T max = -DataTypeUtils::max<T>();
        T sum = 0;

        auto inEWS  = shape::elementWiseStride(inShapeInfo);
        auto length = shape::length(inShapeInfo);

        if (inEWS == 1) {
            for (Nd4jLong i = 0; i < length; i++)
                max = sd::math::nd4j_max<T>(max, inBuff[i]);
#ifdef __NEC__
            PRAGMA_OMP_SIMD_SUM(sum)
#endif
            for (Nd4jLong i = 0; i < length; i++) {
                outBuff[i] = sd::math::nd4j_exp<T,T>(inBuff[i] - max);
                sum += outBuff[i];
            }

            PRAGMA_OMP_SIMD
            for (Nd4jLong i = 0; i < length; i++) {
                outBuff[i] /= sum;
                outBuff[i] = sd::math::nd4j_log<T,T>(outBuff[i]);
            }
        }
        else if (inEWS > 1) {
#ifndef __NEC__
            PRAGMA_OMP_SIMD_MAX(max)
#endif
            for (Nd4jLong i = 0; i < length; i++)
                max = sd::math::nd4j_max<T>(max, inBuff[i * inEWS]);
#ifndef __NEC__
            PRAGMA_OMP_SIMD_SUM(sum)
#endif
            for (Nd4jLong i = 0; i < length; i++) {
                outBuff[i * inEWS] = sd::math::nd4j_exp<T,T>(inBuff[i * inEWS] - max);
                sum += outBuff[i * inEWS];
            }

            PRAGMA_OMP_SIMD
            for (Nd4jLong i = 0; i < length; i++) {
                outBuff[i * inEWS] /= sum;
                outBuff[i * inEWS] = sd::math::nd4j_log<T, T>(outBuff[i * inEWS]);
            }
        }
    }

    ///////////////////////////////////////////////////////////////////
    void logSoftMaxForVector(sd::LaunchContext* context, const NDArray& input, NDArray& output) {

        if(!input.isVector() || !output.isVector())
            throw std::runtime_error("ops::helpers::logSoftMaxForVector function input and output arrays must be vectors !");

        auto xType = input.dataType();
        BUILD_SINGLE_SELECTOR(xType, logSoftMaxForVector_, (input.buffer(), input.shapeInfo(), output.buffer(), output.shapeInfo()), FLOAT_TYPES);
    }

//////////////////////////////////////////////////////////////////////////
void prelu(sd::LaunchContext * context, const NDArray& input, const NDArray& alpha, NDArray& output) {
    const Nd4jLong inputLen = input.lengthOf();
    const Nd4jLong* inputShapeInfo = input.shapeInfo();
    const Nd4jLong* alphaShapeInfo = alpha.shapeInfo();

    auto func = PRAGMA_THREADS_FOR {
        for (auto i = start; i < stop; i++) {
            // FIXME: double!
            double x = input.e<double>(i);
            if (x < 0.0) {
                // FIXME: double
                output.p(i, (x * alpha.e<double>(shape::subArrayIndex(i, inputShapeInfo, alphaShapeInfo))));
            } else
                output.p(i, x);
        }
    };

    samediff::Threads::parallel_for(func, 0, inputLen);
}

//////////////////////////////////////////////////////////////////////////
void preluBP(sd::LaunchContext * context, const NDArray& input, const NDArray& alpha, const NDArray& dLdO, NDArray& dLdI, NDArray& dLdA) {

    const Nd4jLong inputLen = input.lengthOf();
    const Nd4jLong* inputShapeInfo = input.shapeInfo();
    const Nd4jLong* alphaShapeInfo = alpha.shapeInfo();

    dLdA.assign(0.0f);

    for(Nd4jLong i = 0; i < inputLen; ++i) {
        // FIXME: double
        double x   = input.e<double>(i);
        double grO = dLdO.e<double>(i);
        if(x < 0.0) {
            Nd4jLong alphaInd = shape::subArrayIndex(i, inputShapeInfo, alphaShapeInfo);
            dLdI.p(i, grO * alpha.e<double>(alphaInd));
            double prevVal = dLdA.e<double>(alphaInd);
            prevVal += (grO * x);
            dLdA.p(alphaInd, prevVal);
        }
        else
            dLdI.p(i, grO);
    }
}

    bool checkAlphaShapeLen(std::vector<Nd4jLong> const& expectedShape, Nd4jLong shapeLen) {
        Nd4jLong expectedAlphaLen = std::accumulate(expectedShape.cbegin(), expectedShape.cend(), 1, std::multiplies<Nd4jLong>());
        return expectedAlphaLen == shapeLen;
    }
    template <typename T>
    static void thresholdRelu_(NDArray const& input, double threshold, NDArray& output) {
        auto routine = LAMBDA_T(_x, threshold) {
            return _x > (T)threshold? _x: (T)0.f;
        };
        const_cast<NDArray&>(input).applyLambda<T>(routine, output);
    }

    void thresholdRelu(sd::LaunchContext * context, NDArray const& input, double threshold, NDArray& output) {
        BUILD_SINGLE_SELECTOR(input.dataType(), thresholdRelu_, (input, threshold, output), FLOAT_TYPES);
    }

    template <typename T>
    static void thresholdReluDerivative_(sd::LaunchContext * context, NDArray* input, double theta, NDArray* dLdO, NDArray* output) {
        auto derivative = LAMBDA_TT(_x, grO, theta) {if (_x > theta) return grO; else return static_cast<T>(0); };

        input->applyPairwiseLambda<T>(*dLdO, derivative, *output);

    }

    void thresholdReluDerivative(sd::LaunchContext * context, NDArray* input, double threshold, NDArray* dLdO, NDArray* output) {
        BUILD_SINGLE_SELECTOR(input->dataType(), thresholdReluDerivative_, (context, input, threshold, dLdO, output), FLOAT_TYPES);
    }

    ///////////////////////////////////////////////////////////////////
    void logSoftmax(sd::LaunchContext * context, const NDArray& input, NDArray& output, const int dimension) {

        const int rank = input.rankOf();

        if(input.isVector()) {

            if(rank == 1 || input.sizeAt(dimension) != 1) {
                BUILD_SINGLE_SELECTOR(input.dataType(), logSoftMaxForVector_, (input.buffer(), input.shapeInfo(), output.buffer(), output.shapeInfo()), FLOAT_TYPES);
            }
            else
                output = 0.;
        }
        else {

            auto maxAlongDim = const_cast<NDArray&>(input).reduceAlongDimension(reduce::Max, {dimension}, true);
            (input - maxAlongDim).applyTransform(transform::Exp, output); // output contains exponents temporarily
            auto sumAlongDim = output.reduceAlongDimension(reduce::Sum, {dimension}, true);
            output /= sumAlongDim;
            output.applyTransform(transform::Log, output);
        }
    }

    BUILD_SINGLE_TEMPLATE(template void thresholdReluDerivative_, (sd::LaunchContext * context, NDArray* input, double threshold, NDArray* dLdO, NDArray* output), FLOAT_TYPES);
    BUILD_SINGLE_TEMPLATE(template void logSoftMaxForVector_, (void const* input, Nd4jLong const* inShapeInfo, void *output, Nd4jLong const* outShapeInfo), FLOAT_TYPES);
    BUILD_SINGLE_TEMPLATE(template void _softMaxDerivForVector, (sd::LaunchContext * context, const void *input, const Nd4jLong *inShapeInfo, void *output), FLOAT_TYPES);

}
}
}

<|endoftext|>


<commit_before><commit_msg>Improving kmp<commit_after><|endoftext|>