text:
"""
This file contains implementation of getting the swift download URL for the uploaded image file
"""

DOCUMENTATION = '''
---

module: Swift file util
author: Juniper Networks
short_description: Private module to get swift download url of the image file
description:
    - Pass the required swift config info and get the download url of the image file
requirements:
    -
options:
    authtoken:
        description:
            - authentication token string
        required: true
    authurl:
        description:
            - authentication url string
        required: true
    user:
        description:
            - Swift username
        type: string
        required: true
    key:
        description:
            - Swift password
        type: string
        required: true
    tenant_name:
        description:
            - Tenant name.
        type: string
        required: false
        default: 'admin'
    auth_version:
        description:
            - Keystone Auth version.
        required: false
        default: '3.0'
    temp_url_key:
        description:
            - Temp url key
        required: true
    temp_url_key_2:
        description:
            - Temp url key 2
        required: true
    connection_retry_count:
        description:
            - Connection retry count
        type: int
        required: false
        default: 5
    chosen_temp_url_key:
        description:
            - Chosen Temp url key
        required: false
        default: 'temp_url_key'
    container_name:
        description:
            - Name of the container
        required: true
    filename:
        description:
            - Name of the image file
        required: true

'''

EXAMPLES = '''
'''

RETURN = '''
url:
  description:
    - An image file url that can be used to download the file without authentication.
  returned: on success always
  type: str
error_msg:
  description:
    - Its an error message that is returned if there is any exception or error.
  returned: on failure
  type: str
'''

import logging
import requests
import re
import time
from urlparse import urlparse
import swiftclient
import swiftclient.utils
from ansible.module_utils.fabric_utils import FabricAnsibleModule
from threading import RLock

connection_lock = RLock()

class FileSvcUtil(object):  # pragma: no cover
    def __init__(self, authtoken, authurl, user, key, tenant_name,
                 auth_version, container_name, temp_url_key,
                 temp_url_key2, connection_retry_count, chosen_temp_url_key):
        self.requests = requests
        self.authurl = authurl
        self.preauthtoken = authtoken
        self.user = user
        self.key = key
        self.auth_version = auth_version
        self.container_name = container_name
        self.temp_url_key = temp_url_key
        self.temp_url_key_2 = temp_url_key2
        self.connection_retry_count = connection_retry_count
        self.chosen_temp_url_key = chosen_temp_url_key
        self.conn_timeout_sec = 10
        self.tenant_name = tenant_name
        self.generateToken()
        self.updateAccount()

    def generateToken(self):
        retry_count = 0
        incr_sleep = 10
        while retry_count <= self.connection_retry_count:
            try:
                acquired = connection_lock.acquire()
                swiftconn = swiftclient.client.Connection(authurl=self.authurl,
                                                          user=self.user,
                                                          key=self.key,
                                                          preauthtoken=self.preauthtoken,
                                                          tenant_name=self.tenant_name,
                                                          auth_version=self.auth_version,
                                                          timeout=self.conn_timeout_sec,
                                                          insecure=True)
                self.swift_conn = swiftconn
                swiftconn.get_account()
                self.storageurl = swiftconn.url
                break
            except Exception as e:
                retry_count += 1
                err_msg = e.message
                logging.error(err_msg)
                if retry_count == self.connection_retry_count:
                    raise Exception("Connection failed with swift file server: " + str(err_msg))
                logging.error("Connection failed with swift file server, retrying to connect")
                incr_sleep *= 2
                time.sleep(incr_sleep)
            finally:
                if acquired:
                    connection_lock.release()

    def updateAccount(self):
        headers = {'Temp-URL-Key': self.temp_url_key}
        if self.temp_url_key_2 is not None:
            headers['Temp-URL-Key-2'] = self.temp_url_key_2
        try:
            self.swift_conn.post_account(headers)
        except Exception as err:
            logging.error(str(err))
            raise Exception("Update account failed with swift file server: " + str(err))

    def getobjectFileUri(self, filename):
        return self.getFileObjUri(self.container_name, filename)

    def getFileObjUri(self, container_name, fileobj_name):
        return urlparse('/%s/%s' % (container_name, fileobj_name)).path

    def getObjUrl(self, filename):
        image_path = self.getobjectFileUri(filename)
        try:
            image_url = self.getPublicDownloadUrl(image_path)
            return image_url
        except Exception as e:
            logging.error(str(e))
            raise Exception("Get object url failed with swift file server: " + str(e))

    def getPublicDownloadUrl(self, image_path):
        return '%s/%s' % (
            re.sub(r'([^/])/*$', r'\1', self.storageurl),
            re.sub(r'^/*([^/])', r'\1', image_path))

    def close(self):
        if self.swift_conn:
            self.swift_conn.close()

def main():
    module = FabricAnsibleModule(
        argument_spec=dict(
            authtoken=dict(required=True),
            authurl=dict(required=True),
            user=dict(required=True),
            key=dict(required=True),
            tenant_name=dict(required=False, default="admin"),
            auth_version=dict(required=False, default='3.0'),
            temp_url_key=dict(required=True),
            temp_url_key_2=dict(required=True),
            chosen_temp_url_key=dict(required=False, default="temp_url_key"),
            container_name=dict(required=True),
            filename=dict(required=True),
            connection_retry_count=dict(required=False, default=5, type='int')),
        supports_check_mode=False)

    m_args = module.params
    authtoken = m_args['authtoken']
    authurl = m_args['authurl']
    user = m_args['user']
    key = m_args['key']
    tenant_name = m_args['tenant_name']
    auth_version = m_args['auth_version']
    temp_url_key = m_args['temp_url_key']
    temp_url_key_2 = m_args['temp_url_key_2']
    chosen_temp_url_key = m_args['chosen_temp_url_key']
    container_name = m_args['container_name']
    filename = m_args['filename']
    connection_retry_count = m_args['connection_retry_count']

    url = None
    error_msg = ''
    try:
        fileutil = FileSvcUtil(authtoken, authurl, user, key, tenant_name,
                               auth_version, container_name, temp_url_key,
                               temp_url_key_2, connection_retry_count, chosen_temp_url_key)

        url = fileutil.getObjUrl(filename)

        fileutil.close()

    except Exception as e:
        error_msg = "Exception occurred in swift_fileutil: " + str(e)

    results = {}
    results['url'] = url
    results['error_msg'] = error_msg

    module.exit_json(**results)

if __name__ == '__main__':
    main()


text:
sudo apt-get install libffi-dev libcairo2
sudo apt-get install libjpeg8-dev zlib1g-dev libfreetype6-dev

redpajama_set_name: RedPajamaGithub


text:
title: "How to Install Spotify Client on Fedora 25"
layout: post
date: 2017-04-13 11:39
tag:
- Linux
- Fedora
- Installation
comments: true
author: nurulfajar
---

Since i moved my main linux distro from Ubuntu to Fedora, i'm felt a big different flavors. Ubuntu or Debian based distro is easy for software installation, but on fedora i feel a bit bleeding.

lets trying to install Spotify desktop client on Fedora 25.

## With lpf installation
**Step-1**:
* Download the latest rpmfusion-nonfree-release-stable rpm from:
```
http://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-25.noarch.rpm
```

**Step-2**:
* Install rpmfusion-nonfree-release-stable rpm:
```
# rpm -Uvh rpmfusion-nonfree-release-stable*rpm
```

**Step-3**:
* Install lpf-spotify-client rpm package:
```
# dnf install lpf-spotify-client
```

**Step-4**:
* Open app menu and search "lpf spotify-client", then add your user to lpf group (just click "OK"). And wait for Downloading Spotify client.

**Step-5**:
* Open terminal and follow command.
```
lpf install spotify-client
```
* Then click "OK" in pop up lpf dialog.

## Update
i found simple installation with [Flatpak](http://flatpak.org){:target="_blank"}

## With Flatpak Installation (Preffered way)
**Step-1**:
* Install Flatpak framework:
```
$ sudo dnf install flatpak
```

* Then build and install Spotify desktop client:
```
$ flatpak install --from https://s3.amazonaws.com/alexlarsson/spotify-repo/spotify.flatpakref
$ flatpak run com.spotify.Client
```

![File.png]({{images.baseurl}}/assets/images/spotify-fedora.png)


text:
package com.facebook.litho.specmodels.generator;

import static com.facebook.litho.specmodels.generator.PreambleGenerator.generateConstructor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.facebook.litho.specmodels.internal.ImmutableList;
import com.facebook.litho.specmodels.model.DelegateMethod;
import com.facebook.litho.specmodels.model.DependencyInjectionHelper;
import com.facebook.litho.specmodels.model.SpecMethodModel;
import com.facebook.litho.specmodels.model.SpecModel;
import com.facebook.litho.specmodels.model.SpecModelImpl;
import com.squareup.javapoet.MethodSpec;
import javax.lang.model.element.Modifier;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests {@link PreambleGenerator} */
@RunWith(JUnit4.class)
public class PreambleGeneratorTest {
  private static final String TEST_QUALIFIED_SPEC_NAME = "com.facebook.litho.TestSpec";

  private final DependencyInjectionHelper mDependencyInjectionHelper =
      mock(DependencyInjectionHelper.class);

  private SpecModel mSpecModelWithoutDI;
  private SpecModel mSpecModelWithDI;

  @Before
  public void setUp() {
    mSpecModelWithoutDI =
        SpecModelImpl.newBuilder()
            .qualifiedSpecClassName(TEST_QUALIFIED_SPEC_NAME)
            .delegateMethods(ImmutableList.<SpecMethodModel<DelegateMethod, Void>>of())
            .representedObject(new Object())
            .build();

    mSpecModelWithDI =
        SpecModelImpl.newBuilder()
            .qualifiedSpecClassName(TEST_QUALIFIED_SPEC_NAME)
            .delegateMethods(ImmutableList.<SpecMethodModel<DelegateMethod, Void>>of())
            .dependencyInjectionHelper(mDependencyInjectionHelper)
            .representedObject(new Object())
            .build();
  }

  @Test
  public void testGenerateConstructorWithoutDependencyInjection() {
    TypeSpecDataHolder typeSpecDataHolder = generateConstructor(mSpecModelWithoutDI);

    assertThat(typeSpecDataHolder.getFieldSpecs()).isEmpty();
    assertThat(typeSpecDataHolder.getMethodSpecs()).hasSize(1);
    assertThat(typeSpecDataHolder.getTypeSpecs()).isEmpty();

    assertThat(typeSpecDataHolder.getMethodSpecs().get(0).toString())
        .isEqualTo("private Constructor() {\n  super(\"Test\");\n" + "}\n");
  }

  @Test
  public void testGenerateConstructorWithDependencyInjection() {
    final MethodSpec constructor =
        MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addStatement("final Object testObject = new TestObject()")
            .build();

    when(mDependencyInjectionHelper.generateConstructor(mSpecModelWithDI)).thenReturn(constructor);

    TypeSpecDataHolder typeSpecDataHolder = generateConstructor(mSpecModelWithDI);

    assertThat(typeSpecDataHolder.getFieldSpecs()).isEmpty();
    assertThat(typeSpecDataHolder.getMethodSpecs()).hasSize(1);
    assertThat(typeSpecDataHolder.getTypeSpecs()).isEmpty();

    assertThat(typeSpecDataHolder.getMethodSpecs().get(0).toString())
        .isEqualTo(
            "public Constructor() {\n"
                + "  super(\"Test\");\n  final Object testObject = new TestObject();\n"
                + "}\n");
  }
}


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/third_party/quic/core/quic_time_wait_list_manager.h"

#include <cerrno>
#include <memory>
#include <ostream>

#include "net/third_party/quic/core/crypto/crypto_protocol.h"
#include "net/third_party/quic/core/crypto/null_encrypter.h"
#include "net/third_party/quic/core/crypto/quic_decrypter.h"
#include "net/third_party/quic/core/crypto/quic_encrypter.h"
#include "net/third_party/quic/core/quic_data_reader.h"
#include "net/third_party/quic/core/quic_framer.h"
#include "net/third_party/quic/core/quic_packet_writer.h"
#include "net/third_party/quic/core/quic_packets.h"
#include "net/third_party/quic/core/quic_utils.h"
#include "net/third_party/quic/platform/api/quic_flags.h"
#include "net/third_party/quic/platform/api/quic_ptr_util.h"
#include "net/third_party/quic/platform/api/quic_test.h"
#include "net/third_party/quic/platform/api/quic_uint128.h"
#include "net/third_party/quic/test_tools/mock_quic_session_visitor.h"
#include "net/third_party/quic/test_tools/quic_test_utils.h"
#include "net/third_party/quic/test_tools/quic_time_wait_list_manager_peer.h"
#include "starboard/types.h"

using testing::_;
using testing::Args;
using testing::Assign;
using testing::DoAll;
using testing::Matcher;
using testing::NiceMock;
using testing::Return;
using testing::ReturnPointee;
using testing::StrictMock;
using testing::Truly;

namespace quic {
namespace test {
namespace {

class FramerVisitorCapturingPublicReset : public NoOpFramerVisitor {
 public:
  FramerVisitorCapturingPublicReset(QuicConnectionId connection_id)
      : connection_id_(connection_id) {}
  ~FramerVisitorCapturingPublicReset() override = default;

  void OnPublicResetPacket(const QuicPublicResetPacket& public_reset) override {
    public_reset_packet_ = public_reset;
  }

  const QuicPublicResetPacket public_reset_packet() {
    return public_reset_packet_;
  }

  bool IsValidStatelessResetToken(QuicUint128 token) const override {
    return token == QuicUtils::GenerateStatelessResetToken(connection_id_);
  }

  void OnAuthenticatedIetfStatelessResetPacket(
      const QuicIetfStatelessResetPacket& packet) override {
    stateless_reset_packet_ = packet;
  }

  const QuicIetfStatelessResetPacket stateless_reset_packet() {
    return stateless_reset_packet_;
  }

 private:
  QuicPublicResetPacket public_reset_packet_;
  QuicIetfStatelessResetPacket stateless_reset_packet_;
  QuicConnectionId connection_id_;
};

class MockAlarmFactory;
class MockAlarm : public QuicAlarm {
 public:
  explicit MockAlarm(QuicArenaScopedPtr<Delegate> delegate,
                     int alarm_index,
                     MockAlarmFactory* factory)
      : QuicAlarm(std::move(delegate)),
        alarm_index_(alarm_index),
        factory_(factory) {}
  virtual ~MockAlarm() {}

  void SetImpl() override;
  void CancelImpl() override;

 private:
  int alarm_index_;
  MockAlarmFactory* factory_;
};

class MockAlarmFactory : public QuicAlarmFactory {
 public:
  ~MockAlarmFactory() override {}

  // Creates a new platform-specific alarm which will be configured to notify
  // |delegate| when the alarm fires. Returns an alarm allocated on the heap.
  // Caller takes ownership of the new alarm, which will not yet be "set" to
  // fire.
  QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
    return new MockAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate),
                         alarm_index_++, this);
  }
  QuicArenaScopedPtr<QuicAlarm> CreateAlarm(
      QuicArenaScopedPtr<QuicAlarm::Delegate> delegate,
      QuicConnectionArena* arena) override {
    if (arena != nullptr) {
      return arena->New<MockAlarm>(std::move(delegate), alarm_index_++, this);
    }
    return QuicArenaScopedPtr<MockAlarm>(
        new MockAlarm(std::move(delegate), alarm_index_++, this));
  }
  MOCK_METHOD2(OnAlarmSet, void(int, QuicTime));
  MOCK_METHOD1(OnAlarmCancelled, void(int));

 private:
  int alarm_index_ = 0;
};

void MockAlarm::SetImpl() {
  factory_->OnAlarmSet(alarm_index_, deadline());
}

void MockAlarm::CancelImpl() {
  factory_->OnAlarmCancelled(alarm_index_);
}

class QuicTimeWaitListManagerTest : public QuicTest {
 protected:
  QuicTimeWaitListManagerTest()
      : time_wait_list_manager_(&writer_, &visitor_, &clock_, &alarm_factory_),
        connection_id_(TestConnectionId(45)),
        peer_address_(TestPeerIPAddress(), kTestPort),
        writer_is_blocked_(false) {}

  ~QuicTimeWaitListManagerTest() override = default;

  void SetUp() override {
    EXPECT_CALL(writer_, IsWriteBlocked())
        .WillRepeatedly(ReturnPointee(&writer_is_blocked_));
  }

  void AddConnectionId(QuicConnectionId connection_id,
                       QuicTimeWaitListManager::TimeWaitAction action) {
    AddConnectionId(connection_id, QuicVersionMax(), action, nullptr);
  }

  void AddStatelessConnectionId(QuicConnectionId connection_id) {
    std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets;
    termination_packets.push_back(std::unique_ptr<QuicEncryptedPacket>(
        new QuicEncryptedPacket(nullptr, 0, false)));
    time_wait_list_manager_.AddConnectionIdToTimeWait(
        connection_id, false, QuicTimeWaitListManager::SEND_TERMINATION_PACKETS,
        ENCRYPTION_NONE, &termination_packets);
  }

  void AddConnectionId(
      QuicConnectionId connection_id,
      ParsedQuicVersion version,
      QuicTimeWaitListManager::TimeWaitAction action,
      std::vector<std::unique_ptr<QuicEncryptedPacket>>* packets) {
    time_wait_list_manager_.AddConnectionIdToTimeWait(
        connection_id, version.transport_version > QUIC_VERSION_43, action,
        ENCRYPTION_NONE, packets);
  }

  bool IsConnectionIdInTimeWait(QuicConnectionId connection_id) {
    return time_wait_list_manager_.IsConnectionIdInTimeWait(connection_id);
  }

  void ProcessPacket(QuicConnectionId connection_id) {
    time_wait_list_manager_.ProcessPacket(
        self_address_, peer_address_, connection_id, GOOGLE_QUIC_PACKET,
        QuicMakeUnique<QuicPerPacketContext>());
  }

  QuicEncryptedPacket* ConstructEncryptedPacket(
      QuicConnectionId destination_connection_id,
      QuicConnectionId source_connection_id,
      uint64_t packet_number) {
    return quic::test::ConstructEncryptedPacket(destination_connection_id,
                                                source_connection_id, false,
                                                false, packet_number, "data");
  }

  MockClock clock_;
  MockAlarmFactory alarm_factory_;
  NiceMock<MockPacketWriter> writer_;
  StrictMock<MockQuicSessionVisitor> visitor_;
  QuicTimeWaitListManager time_wait_list_manager_;
  QuicConnectionId connection_id_;
  QuicSocketAddress self_address_;
  QuicSocketAddress peer_address_;
  bool writer_is_blocked_;
};

bool ValidPublicResetPacketPredicate(
    QuicConnectionId expected_connection_id,
    const testing::tuple<const char*, int>& packet_buffer) {
  FramerVisitorCapturingPublicReset visitor(expected_connection_id);
  QuicFramer framer(AllSupportedVersions(), QuicTime::Zero(),
                    Perspective::IS_CLIENT);
  framer.set_visitor(&visitor);
  QuicEncryptedPacket encrypted(testing::get<0>(packet_buffer),
                                testing::get<1>(packet_buffer));
  framer.ProcessPacket(encrypted);
  QuicPublicResetPacket packet = visitor.public_reset_packet();
  bool public_reset_is_valid =
      expected_connection_id == packet.connection_id &&
      TestPeerIPAddress() == packet.client_address.host() &&
      kTestPort == packet.client_address.port();

  QuicIetfStatelessResetPacket stateless_reset =
      visitor.stateless_reset_packet();

  QuicUint128 expected_stateless_reset_token =
      QuicUtils::GenerateStatelessResetToken(expected_connection_id);

  bool stateless_reset_is_valid =
      stateless_reset.stateless_reset_token == expected_stateless_reset_token;

  return public_reset_is_valid || stateless_reset_is_valid;
}

Matcher<const testing::tuple<const char*, int>> PublicResetPacketEq(
    QuicConnectionId connection_id) {
  return Truly(
      [connection_id](const testing::tuple<const char*, int> packet_buffer) {
        return ValidPublicResetPacketPredicate(connection_id, packet_buffer);
      });
}

TEST_F(QuicTimeWaitListManagerTest, CheckConnectionIdInTimeWait) {
  EXPECT_FALSE(IsConnectionIdInTimeWait(connection_id_));
  EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_));
  AddConnectionId(connection_id_, QuicTimeWaitListManager::DO_NOTHING);
  EXPECT_EQ(1u, time_wait_list_manager_.num_connections());
  EXPECT_TRUE(IsConnectionIdInTimeWait(connection_id_));
}

TEST_F(QuicTimeWaitListManagerTest, CheckStatelessConnectionIdInTimeWait) {
  EXPECT_FALSE(IsConnectionIdInTimeWait(connection_id_));
  EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_));
  AddStatelessConnectionId(connection_id_);
  EXPECT_EQ(1u, time_wait_list_manager_.num_connections());
  EXPECT_TRUE(IsConnectionIdInTimeWait(connection_id_));
}

TEST_F(QuicTimeWaitListManagerTest, SendVersionNegotiationPacket) {
  std::unique_ptr<QuicEncryptedPacket> packet(
      QuicFramer::BuildVersionNegotiationPacket(connection_id_, false,
                                                AllSupportedVersions()));
  EXPECT_CALL(writer_, WritePacket(_, packet->length(), self_address_.host(),
                                   peer_address_, _))
      .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1)));

  time_wait_list_manager_.SendVersionNegotiationPacket(
      connection_id_, false, AllSupportedVersions(), self_address_,
      peer_address_, QuicMakeUnique<QuicPerPacketContext>());
  EXPECT_EQ(0u, time_wait_list_manager_.num_connections());
}

TEST_F(QuicTimeWaitListManagerTest, SendConnectionClose) {
  const size_t kConnectionCloseLength = 100;
  EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_));
  std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets;
  termination_packets.push_back(
      std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket(
          new char[kConnectionCloseLength], kConnectionCloseLength, true)));
  AddConnectionId(connection_id_, QuicVersionMax(),
                  QuicTimeWaitListManager::SEND_TERMINATION_PACKETS,
                  &termination_packets);
  EXPECT_CALL(writer_, WritePacket(_, kConnectionCloseLength,
                                   self_address_.host(), peer_address_, _))
      .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1)));

  ProcessPacket(connection_id_);
}

TEST_F(QuicTimeWaitListManagerTest, SendTwoConnectionCloses) {
  const size_t kConnectionCloseLength = 100;
  EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_));
  std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets;
  termination_packets.push_back(
      std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket(
          new char[kConnectionCloseLength], kConnectionCloseLength, true)));
  termination_packets.push_back(
      std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket(
          new char[kConnectionCloseLength], kConnectionCloseLength, true)));
  AddConnectionId(connection_id_, QuicVersionMax(),
                  QuicTimeWaitListManager::SEND_TERMINATION_PACKETS,
                  &termination_packets);
  EXPECT_CALL(writer_, WritePacket(_, kConnectionCloseLength,
                                   self_address_.host(), peer_address_, _))
      .Times(2)
      .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1)));

  ProcessPacket(connection_id_);
}

TEST_F(QuicTimeWaitListManagerTest, SendPublicReset) {
  EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_));
  AddConnectionId(connection_id_,
                  QuicTimeWaitListManager::SEND_STATELESS_RESET);
  EXPECT_CALL(writer_,
              WritePacket(_, _, self_address_.host(), peer_address_, _))
      .With(Args<0, 1>(PublicResetPacketEq(connection_id_)))
      .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0)));

  ProcessPacket(connection_id_);
}

TEST_F(QuicTimeWaitListManagerTest, SendPublicResetWithExponentialBackOff) {
  EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_));
  AddConnectionId(connection_id_,
                  QuicTimeWaitListManager::SEND_STATELESS_RESET);
  EXPECT_EQ(1u, time_wait_list_manager_.num_connections());
  for (int packet_number = 1; packet_number < 101; ++packet_number) {
    if ((packet_number & (packet_number - 1)) == 0) {
      EXPECT_CALL(writer_, WritePacket(_, _, _, _, _))
          .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1)));
    }
    ProcessPacket(connection_id_);
    // Send public reset with exponential back off.
    if ((packet_number & (packet_number - 1)) == 0) {
      EXPECT_TRUE(QuicTimeWaitListManagerPeer::ShouldSendResponse(
          &time_wait_list_manager_, packet_number));
    } else {
      EXPECT_FALSE(QuicTimeWaitListManagerPeer::ShouldSendResponse(
          &time_wait_list_manager_, packet_number));
    }
  }
}

TEST_F(QuicTimeWaitListManagerTest, NoPublicResetForStatelessConnections) {
  EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_));
  AddStatelessConnectionId(connection_id_);

  EXPECT_CALL(writer_,
              WritePacket(_, _, self_address_.host(), peer_address_, _))
      .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1)));

  ProcessPacket(connection_id_);
}

TEST_F(QuicTimeWaitListManagerTest, CleanUpOldConnectionIds) {
  const size_t kConnectionIdCount = 100;
  const size_t kOldConnectionIdCount = 31;

  // Add connection_ids such that their expiry time is time_wait_period_.
  for (uint64_t conn_id = 1; conn_id <= kOldConnectionIdCount; ++conn_id) {
    QuicConnectionId connection_id = TestConnectionId(conn_id);
    EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id));
    AddConnectionId(connection_id, QuicTimeWaitListManager::DO_NOTHING);
  }
  EXPECT_EQ(kOldConnectionIdCount, time_wait_list_manager_.num_connections());

  // Add remaining connection_ids such that their add time is
  // 2 * time_wait_period_.
  const QuicTime::Delta time_wait_period =
      QuicTimeWaitListManagerPeer::time_wait_period(&time_wait_list_manager_);
  clock_.AdvanceTime(time_wait_period);
  for (uint64_t conn_id = kOldConnectionIdCount + 1;
       conn_id <= kConnectionIdCount; ++conn_id) {
    QuicConnectionId connection_id = TestConnectionId(conn_id);
    EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id));
    AddConnectionId(connection_id, QuicTimeWaitListManager::DO_NOTHING);
  }
  EXPECT_EQ(kConnectionIdCount, time_wait_list_manager_.num_connections());

  QuicTime::Delta offset = QuicTime::Delta::FromMicroseconds(39);
  // Now set the current time as time_wait_period + offset usecs.
  clock_.AdvanceTime(offset);
  // After all the old connection_ids are cleaned up, check the next alarm
  // interval.
  QuicTime next_alarm_time = clock_.Now() + time_wait_period - offset;
  EXPECT_CALL(alarm_factory_, OnAlarmSet(_, next_alarm_time));

  time_wait_list_manager_.CleanUpOldConnectionIds();
  for (uint64_t conn_id = 1; conn_id <= kConnectionIdCount; ++conn_id) {
    QuicConnectionId connection_id = TestConnectionId(conn_id);
    EXPECT_EQ(conn_id > kOldConnectionIdCount,
              IsConnectionIdInTimeWait(connection_id))
        << "kOldConnectionIdCount: " << kOldConnectionIdCount
        << " connection_id: " << connection_id;
  }
  EXPECT_EQ(kConnectionIdCount - kOldConnectionIdCount,
            time_wait_list_manager_.num_connections());
}

TEST_F(QuicTimeWaitListManagerTest, SendQueuedPackets) {
  QuicConnectionId connection_id = TestConnectionId(1);
  EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id));
  AddConnectionId(connection_id, QuicTimeWaitListManager::SEND_STATELESS_RESET);
  std::unique_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket(
      connection_id, EmptyQuicConnectionId(), /*packet_number=*/234));
  // Let first write through.
  EXPECT_CALL(writer_,
              WritePacket(_, _, self_address_.host(), peer_address_, _))
      .With(Args<0, 1>(PublicResetPacketEq(connection_id)))
      .WillOnce(Return(WriteResult(WRITE_STATUS_OK, packet->length())));
  ProcessPacket(connection_id);

  // write block for the next packet.
  EXPECT_CALL(writer_,
              WritePacket(_, _, self_address_.host(), peer_address_, _))
      .With(Args<0, 1>(PublicResetPacketEq(connection_id)))
      .WillOnce(DoAll(Assign(&writer_is_blocked_, true),
                      Return(WriteResult(WRITE_STATUS_BLOCKED, EAGAIN))));
  EXPECT_CALL(visitor_, OnWriteBlocked(&time_wait_list_manager_));
  ProcessPacket(connection_id);
  // 3rd packet. No public reset should be sent;
  ProcessPacket(connection_id);

  // write packet should not be called since we are write blocked but the
  // should be queued.
  QuicConnectionId other_connection_id = TestConnectionId(2);
  EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(other_connection_id));
  AddConnectionId(other_connection_id,
                  QuicTimeWaitListManager::SEND_STATELESS_RESET);
  std::unique_ptr<QuicEncryptedPacket> other_packet(ConstructEncryptedPacket(
      other_connection_id, EmptyQuicConnectionId(), /*packet_number=*/23423));
  EXPECT_CALL(writer_, WritePacket(_, _, _, _, _)).Times(0);
  EXPECT_CALL(visitor_, OnWriteBlocked(&time_wait_list_manager_));
  ProcessPacket(other_connection_id);
  EXPECT_EQ(2u, time_wait_list_manager_.num_connections());

  // Now expect all the write blocked public reset packets to be sent again.
  writer_is_blocked_ = false;
  EXPECT_CALL(writer_,
              WritePacket(_, _, self_address_.host(), peer_address_, _))
      .With(Args<0, 1>(PublicResetPacketEq(connection_id)))
      .WillOnce(Return(WriteResult(WRITE_STATUS_OK, packet->length())));
  EXPECT_CALL(writer_,
              WritePacket(_, _, self_address_.host(), peer_address_, _))
      .With(Args<0, 1>(PublicResetPacketEq(other_connection_id)))
      .WillOnce(Return(WriteResult(WRITE_STATUS_OK, packet->length())));
  time_wait_list_manager_.OnBlockedWriterCanWrite();
}

TEST_F(QuicTimeWaitListManagerTest, AddConnectionIdTwice) {
  // Add connection_ids such that their expiry time is time_wait_period_.
  EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_));
  AddConnectionId(connection_id_, QuicTimeWaitListManager::DO_NOTHING);
  EXPECT_TRUE(IsConnectionIdInTimeWait(connection_id_));
  const size_t kConnectionCloseLength = 100;
  std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets;
  termination_packets.push_back(
      std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket(
          new char[kConnectionCloseLength], kConnectionCloseLength, true)));
  AddConnectionId(connection_id_, QuicVersionMax(),
                  QuicTimeWaitListManager::SEND_TERMINATION_PACKETS,
                  &termination_packets);
  EXPECT_TRUE(IsConnectionIdInTimeWait(connection_id_));
  EXPECT_EQ(1u, time_wait_list_manager_.num_connections());

  EXPECT_CALL(writer_, WritePacket(_, kConnectionCloseLength,
                                   self_address_.host(), peer_address_, _))
      .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1)));

  ProcessPacket(connection_id_);

  const QuicTime::Delta time_wait_period =
      QuicTimeWaitListManagerPeer::time_wait_period(&time_wait_list_manager_);

  QuicTime::Delta offset = QuicTime::Delta::FromMicroseconds(39);
  clock_.AdvanceTime(offset + time_wait_period);
  // Now set the current time as time_wait_period + offset usecs.
  QuicTime next_alarm_time = clock_.Now() + time_wait_period;
  EXPECT_CALL(alarm_factory_, OnAlarmSet(_, next_alarm_time));

  time_wait_list_manager_.CleanUpOldConnectionIds();
  EXPECT_FALSE(IsConnectionIdInTimeWait(connection_id_));
  EXPECT_EQ(0u, time_wait_list_manager_.num_connections());
}

TEST_F(QuicTimeWaitListManagerTest, ConnectionIdsOrderedByTime) {
  // Simple randomization: the values of connection_ids are randomly swapped.
  // If the container is broken, the test will be 50% flaky.
  const uint64_t conn_id1 = QuicRandom::GetInstance()->RandUint64() % 2;
  const QuicConnectionId connection_id1 = TestConnectionId(conn_id1);
  const QuicConnectionId connection_id2 = TestConnectionId(1 - conn_id1);

  // 1 will hash lower than 2, but we add it later. They should come out in the
  // add order, not hash order.
  EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id1));
  AddConnectionId(connection_id1, QuicTimeWaitListManager::DO_NOTHING);
  clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(10));
  EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id2));
  AddConnectionId(connection_id2, QuicTimeWaitListManager::DO_NOTHING);
  EXPECT_EQ(2u, time_wait_list_manager_.num_connections());

  const QuicTime::Delta time_wait_period =
      QuicTimeWaitListManagerPeer::time_wait_period(&time_wait_list_manager_);
  clock_.AdvanceTime(time_wait_period - QuicTime::Delta::FromMicroseconds(9));

  EXPECT_CALL(alarm_factory_, OnAlarmSet(_, _));

  time_wait_list_manager_.CleanUpOldConnectionIds();
  EXPECT_FALSE(IsConnectionIdInTimeWait(connection_id1));
  EXPECT_TRUE(IsConnectionIdInTimeWait(connection_id2));
  EXPECT_EQ(1u, time_wait_list_manager_.num_connections());
}

TEST_F(QuicTimeWaitListManagerTest, MaxConnectionsTest) {
  // Basically, shut off time-based eviction.
  FLAGS_quic_time_wait_list_seconds = 10000000000;
  FLAGS_quic_time_wait_list_max_connections = 5;

  uint64_t current_conn_id = 0;
  // Add exactly the maximum number of connections
  for (int64_t i = 0; i < FLAGS_quic_time_wait_list_max_connections; ++i) {
    ++current_conn_id;
    QuicConnectionId current_connection_id = TestConnectionId(current_conn_id);
    EXPECT_FALSE(IsConnectionIdInTimeWait(current_connection_id));
    EXPECT_CALL(visitor_,
                OnConnectionAddedToTimeWaitList(current_connection_id));
    AddConnectionId(current_connection_id, QuicTimeWaitListManager::DO_NOTHING);
    EXPECT_EQ(current_conn_id, time_wait_list_manager_.num_connections());
    EXPECT_TRUE(IsConnectionIdInTimeWait(current_connection_id));
  }

  // Now keep adding.  Since we're already at the max, every new connection-id
  // will evict the oldest one.
  for (int64_t i = 0; i < FLAGS_quic_time_wait_list_max_connections; ++i) {
    ++current_conn_id;
    QuicConnectionId current_connection_id = TestConnectionId(current_conn_id);
    const QuicConnectionId id_to_evict = TestConnectionId(
        current_conn_id - FLAGS_quic_time_wait_list_max_connections);
    EXPECT_TRUE(IsConnectionIdInTimeWait(id_to_evict));
    EXPECT_FALSE(IsConnectionIdInTimeWait(current_connection_id));
    EXPECT_CALL(visitor_,
                OnConnectionAddedToTimeWaitList(current_connection_id));
    AddConnectionId(current_connection_id, QuicTimeWaitListManager::DO_NOTHING);
    EXPECT_EQ(static_cast<size_t>(FLAGS_quic_time_wait_list_max_connections),
              time_wait_list_manager_.num_connections());
    EXPECT_FALSE(IsConnectionIdInTimeWait(id_to_evict));
    EXPECT_TRUE(IsConnectionIdInTimeWait(current_connection_id));
  }
}

// Regression test for b/116200989.
TEST_F(QuicTimeWaitListManagerTest,
       SendStatelessResetInResponseToShortHeaders) {
  // This test mimics a scenario where an ENCRYPTION_NONE connection close is
  // added as termination packet for an IETF connection ID. However, a short
  // header packet is received later.
  const size_t kConnectionCloseLength = 100;
  EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_));
  std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets;
  termination_packets.push_back(
      std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket(
          new char[kConnectionCloseLength], kConnectionCloseLength, true)));
  // Add an ENCRYPTION_NONE termination packet.
  time_wait_list_manager_.AddConnectionIdToTimeWait(
      connection_id_, /*ietf_quic=*/true,
      QuicTimeWaitListManager::SEND_TERMINATION_PACKETS, ENCRYPTION_NONE,
      &termination_packets);

  if (GetQuicReloadableFlag(quic_always_reset_short_header_packets)) {
    // Termination packet is not encrypted, instead, send stateless reset.
    EXPECT_CALL(writer_,
                WritePacket(_, _, self_address_.host(), peer_address_, _))
        .With(Args<0, 1>(PublicResetPacketEq(connection_id_)))
        .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0)));
  } else {
    // An unprocessable connection close is sent to peer.
    EXPECT_CALL(writer_, WritePacket(_, kConnectionCloseLength,
                                     self_address_.host(), peer_address_, _))
        .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1)));
  }
  // Processes IETF short header packet.
  time_wait_list_manager_.ProcessPacket(
      self_address_, peer_address_, connection_id_,
      IETF_QUIC_SHORT_HEADER_PACKET, QuicMakeUnique<QuicPerPacketContext>());
}

}  // namespace
}  // namespace test
}  // namespace quic


text:
/**
 * The MapControlsPresenter class for the MapControlsPresenter view.
 *º
 * @return MapControlsPresenter class.
 */
define(['underscore', 'mps', 'map/presenters/PresenterClass'], function(
  _,
  mps,
  PresenterClass
) {
  'use strict';

  var MapControlsPresenter = PresenterClass.extend({
    init: function(view) {
      this.view = view;
      this._super();
    },

    // /**
    //  * Application subscriptions.
    //  */
    _subscriptions: [
      {
        'Map/set-zoom': function(zoom) {
          this.view.setZoom(zoom);
        }
      },
      {
        'Map/fit-bounds': function(bounds) {
          this.view.saveBounds(bounds);
        }
      },
      {
        'AnalysisResults/delete-analysis': function() {
          this.view.saveBounds(null);
        }
      },
      {
        'AnalysisTool/stop-drawing': function() {
          this.view.model.set({
            hidden: false
          });
        }
      },
      {
        'AnalysisTool/start-drawing': function() {
          this.view.model.set({
            hidden: true
          });
        }
      },
      {
        'Timeline/toggle': function(toggle) {
          this.view.toogleTimeline(toggle);
        }
      },
      {
        'Layers/toggle': function(toggle) {
          this.view.toogleTimeline(false);
        }
      },
      {
        'Analysis/toggle': function(toggle) {
          this.view.toogleTimeline(false);
        }
      }
    ],

    // *
    //  * Used by ToggleWidgets view to handle a fitbounds.
    //  *
    //  * @return {object} Map bounds

    // fitBounds: function(bounds) {
    //   mps.publish('Map/fit-bounds', [bounds]);
    // },

    // setCenter: function(lat, lng) {
    //   mps.publish('Map/set-center', [lat, lng]);
    // }

    /**
     * Used by MapView to delegate zoom change UI events. Results in the
     * Map/zoom-change event getting published with the new zoom.
     *
     * @param  {integer} zoom the new map zoom
     */
    onZoomChange: function(zoom) {
      mps.publish('Map/zoom-change', [zoom]);
      mps.publish('Place/update', [{ go: false }]);
    },

    onAutolocate: function() {
      mps.publish('Map/autolocate');
    },

    /**
     * Used by searchbox view to handle a fitbounds.
     *
     * @return {object} Map bounds
     */
    fitBounds: function(bounds) {
      mps.publish('Map/fit-bounds', [bounds]);
    },

    notificate: function(id) {
      mps.publish('Notification/open', [id]);
    },

    openLegend: function() {
      mps.publish('LegendMobile/open');
      this.view.toogleTimeline(false);
    },

    openAnalysis: function() {
      mps.publish('Analysis/toggle');
    }
  });

  return MapControlsPresenter;
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CExtensions.Patch.Mapper.Patch
{
    public class PatchException : Exception
    {
        public PatchException(string p) : base(p)
        {
        }
    }
}


text:
[![NPM version][npm-image]][npm-url]
[![Build Status][travis-image]][travis-url]
[![Dependency Status][depstat-image]][depstat-url]

> Angular File Saver is an AngularJS service that leverages
[FileSaver.js](https://github.com/eligrey/FileSaver.js/) and
[Blob.js](https://github.com/eligrey/Blob.js/) to implement the HTML5 W3C
saveAs() interface in browsers that do not natively support it

## Dependencies
- [Angular](https://github.com/angular/angular.js)
- [FileSaver.js](https://github.com/eligrey/FileSaver.js/)
- [Blob.js](https://github.com/eligrey/Blob.js/)

File `dist/angular-file-saver.bundle.js` contains all required dependencies and
grants access to both `Blob.js` and `FileSaver.js` polyfills via `Blob` and
`SaveAs` services.

## Installation

```sh
# Using bower:
$ bower install angular-file-saver

# Using npm:
$ npm install angular-file-saver
```

## Basic usage
- Include the `ngFileSaver` module into your project;
- Pass both `FileSaver` and `Blob` services as dependencies;
- Create a [Blob object](https://developer.mozilla.org/en/docs/Web/API/Blob)
passing an array with data as a first argument and an object with set of options
as the second one: `new Blob(['text'], { type: 'text/plain;charset=utf-8' })`;
- Invoke `FileSaver.saveAs` with the following arguments:
  - `data` **Blob**: a Blob instance;
  - `filename` **String**: Custom filename (extension is optional);
  - `disableAutoBOM` **Boolean**: (optional) Disable automatically provided Unicode text encoding hints;

[Demo](http://alferov.github.io/angular-file-saver/#demo)

## API
### `FileSaver`
#### `#saveAs(data, filename[, disableAutoBOM])`
Immediately starts saving a file

#### Parameters
- **Blob** `data`: a Blob instance;
- **String** `filename`: Custom filename (extension is optional);
- **Boolean** `disableAutoBOM` : (optional) Disable automatically provided Unicode text encoding hints;

### `Blob(blobParts[, options]))`
An Angular factory that returns a Blob instance.
[Blob API on MDN](https://developer.mozilla.org/en/docs/Web/API/Blob)

### `SaveAs(data, filename[, disableAutoBOM])`
An Angular factory that returns a FileSaver.js `saveAs` polyfill.
[FileSaver.js documentationruvy](https://github.com/eligrey/FileSaver.js/#syntax)

## Example
**JS**
```js
function ExampleCtrl(FileSaver, Blob) {
  var vm = this;

  vm.val = {
    text: 'Hey ho lets go!'
  };

  vm.download = function(text) {
    var data = new Blob([text], { type: 'text/plain;charset=utf-8' });
    FileSaver.saveAs(data, 'text.txt');
  };
}

angular
  .module('fileSaverExample', ['ngFileSaver'])
  .controller('ExampleCtrl', ['FileSaver', 'Blob', ExampleCtrl]);
```

**HTML**
```html
<div class="wrapper" ng-controller="ExampleCtrl as vm">
  <textarea
    ng-model="vm.val.text"
    name="textarea" rows="5" cols="20">
      Hey ho let's go!
  </textarea>
  <a href="" class="btn btn-dark btn-small" ng-click="vm.download(vm.val.text)">
    Download
  </a>
</div>
```

## License
MIT © [Philipp Alferov](https://github.com/alferov)

[npm-url]: https://npmjs.org/package/angular-file-saver
[npm-image]: https://img.shields.io/npm/v/angular-file-saver.svg?style=flat-square

[travis-url]: https://travis-ci.org/alferov/angular-file-saver
[travis-image]: https://img.shields.io/travis/alferov/angular-file-saver.svg?style=flat-square

[depstat-url]: https://david-dm.org/alferov/angular-file-saver
[depstat-image]: https://david-dm.org/alferov/angular-file-saver.svg?style=flat-square


text:
import * as format from "string-template";
import * as compile from "string-template/compile";

// Format tests
{
    let greeting: string;

    // Format using an object hash with keys matching [0-9a-zA-Z]+
    greeting = format("Hello {name}, you have {count} unread messages", { name: "Robert", count: 12 })
    // greeting -> "Hello Robert, you have 12 unread messages"

    // Format using a number indexed array
    greeting = format("Hello {0}, you have {1} unread messages", ["Robert", 12])
    // greeting -> "Hello Robert, you have 12 unread messages"

    // Format using optional arguments
    greeting = format("Hello {0}, you have {1} unread messages", "Robert", 12)
    // greeting -> "Hello Robert, you have 12 unread messages"

    // Escape {} pairs by using double {{}}
    let text: string = format("{{0}}")
    // text -> "{0}"
}

// Compile tests
{
    {
        let greetingTemplate = compile("Hello {0}, you have {1} unread messages", true)
        // -> greetingTemplate generated using new Function
        let greeting = greetingTemplate("Robert", 12)
        // -> "Hello Robert, you have 12 unread messages"
    }

    {
        let greetingTemplate = compile("Hello {0}, you have {1} unread messages", true)
        // -> greetingTemplate generated using new Function

        let greeting = greetingTemplate(["Robert", 12])
        // -> "Hello Robert, you have 12 unread messages"
    }

    {
        let template = compile("{likes} people have liked this")
        let result = template({ likes: 123 })
    }
}


text:
<?php

class Global_Model_DbTable_DbSituation extends Zend_Db_Table_Abstract
{

    protected $_name = 'rms_situation';
    public function getUserId(){
    	$session_user=new Zend_Session_Namespace('auth');
    	return $session_user->user_id;

    }
	public function addNewSituation($_data){
		$_arr=array(
				'situ_name'	  => $_data['situ_name'],
				'create_date' => Zend_Date::now(),
				'status'   => $_data['status'],
				'user_id'	  => $this->getUserId()
		);
		return  $this->insert($_arr);
	}
	public function getSituationById($id){
		$db = $this->getAdapter();
		$sql = "SELECT * FROM rms_situation WHERE situ_id = ".$db->quote($id);
		$sql.=" LIMIT 1 ";
		$row=$db->fetchRow($sql);
		return $row;
	}
	public function updateSituation($data){
		$_arr=array(
				'situ_name'	  => $data['situ_name'],
				'create_date' => Zend_Date::now(),
				'status'   => $data['status'],
				'user_id'	  => $this->getUserId()
		);
		$where=$this->getAdapter()->quoteInto("situ_id=?", $data["id"]);
		$this->update($_arr, $where);
	}
	function getAllSituations($search=null){
		$db = $this->getAdapter();
		$sql = " SELECT situ_id AS id,situ_name, create_date,status,(SELECT  CONCAT(first_name,' ', last_name) FROM rms_users WHERE id=user_id )AS user_name

		FROM rms_situation
		WHERE 1 ";
		return $db->fetchAll($sql);
	}
	public function addSituation($_data){//ajax
		$_arr=array(
				'situ_name'	  => $_data['txt_situation'],
				'create_date' => Zend_Date::now(),
				'status'   => 1,
				'user_id'	  => $this->getUserId()
		);
		return  $this->insert($_arr);
	}
}


text:
Adding entries to a list

Key points:

 - callbacks as props
 - child -> parent communication


text:
package org.apache.flink.api.common.typeutils.base;

import java.io.IOException;
import java.math.BigInteger;
import org.apache.flink.annotation.Internal;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.MemorySegment;

/**
 * Comparator for comparing BigInteger values. Does not support null values.
 */
@Internal
public final class BigIntComparator extends BasicTypeComparator<BigInteger> {

	private static final long serialVersionUID = 1L;

	public BigIntComparator(boolean ascending) {
		super(ascending);
	}

	@Override
	public int compareSerialized(DataInputView firstSource, DataInputView secondSource) throws IOException {
		BigInteger bi1 = BigIntSerializer.readBigInteger(firstSource);
		BigInteger bi2 = BigIntSerializer.readBigInteger(secondSource);
		int comp = bi1.compareTo(bi2); // null is not supported
		return ascendingComparison ? comp : -comp;
	}

	@Override
	public boolean supportsNormalizedKey() {
		return true;
	}

	@Override
	public boolean supportsSerializationWithKeyNormalization() {
		return false;
	}

	@Override
	public int getNormalizeKeyLen() {
		return Integer.MAX_VALUE;
	}

	@Override
	public boolean isNormalizedKeyPrefixOnly(int keyBytes) {
		return true;
	}

	/**
	 * Adds a normalized key containing the normalized number of bits and MSBs of the given record.
	 * 1 bit determines the sign (negative, zero/positive), 31 bit the bit length of the record.
	 * Remaining bytes contain the most significant bits of the record.
	 */
	@Override
	public void putNormalizedKey(BigInteger record, MemorySegment target, int offset, int len) {
		// add normalized bit length (the larger the length, the larger the value)
		int bitLen = 0;
		if (len > 0) {
			final int signum = record.signum();
			bitLen = record.bitLength();

			// normalize dependent on sign
			// from 0 to Integer.MAX
			// OR from Integer.MAX to 0
			int normBitLen = signum < 0 ? Integer.MAX_VALUE - bitLen : bitLen;

			// add sign
			if (signum >= 0) {
				normBitLen |= (1 << 31);
			}

			for (int i = 0; i < 4 && len > 0; i++, len--) {
				final byte b = (byte) (normBitLen >>> (8 * (3 - i)));
				target.put(offset++, b);
			}
		}

		// fill remaining bytes with most significant bits
		int bitPos = bitLen - 1;
		for (; len > 0; len--) {
			byte b = 0;
			for (int bytePos = 0; bytePos < 8 && bitPos >= 0; bytePos++, bitPos--) {
				b <<= 1;
				if (record.testBit(bitPos)) {
					b |= 1;
				}
			}
			// the last byte might be partially filled, but that's ok within an equal bit length.
			// no need for padding bits.
			target.put(offset++, b);
		}
	}

	@Override
	public BigIntComparator duplicate() {
		return new BigIntComparator(ascendingComparison);
	}
}


text:
@implementation NWSDialogue

#pragma mark - Object life cycle

- (id)initWithCall:(NWSCall *)call
{
    self = [super init];
    if (self) {
        _call = call;
        _indicator = call.indicator;
    }
    return self;
}

#pragma mark - Operation

- (void)start // COV_NF_START
{
    NWSLogWarn(@"Abstract method requires implementation");
} // COV_NF_END

- (void)cancel // COV_NF_START
{
    NWSLogWarn(@"Abstract method requires implementation");
} // COV_NF_END

- (id)mapData:(NSData *)data useTransactionStore:(BOOL)useStore
{
    if (!data.length) {
        NWSLogWarn(@"empty response");
        return nil;
    }

    // parsing
    NWSParser *parser = _call.responseParser;
    if (!parser) {
        parser = NWSParser.defaultParser;
    }
    NWSLogSpag(@"parsing data (expected:%.3fs)", _call.endpoint.parseTime.average);
    DEBUG_STAT_START(parseTime);
    id parsed = [parser parse:data];
    DEBUG_STAT_STOP(parseTime, _call.endpoint);
    if (!parsed) {
        NWSLogWarn(@"failed to parse");
        return nil;
    }

    // take value at response path
    NWSPath *p = _call.responsePath;
    if (!p) {
        p = NWSSelfPath.shared;
    }
    id value = [parsed valueForPath:p];
    if (!value) {
        NWSLogWarn(@"no value at response path");
        return nil;
    }

    id result = nil;
    NWSMapping *mapping = _call.responseMapping;
    if (mapping) {
        // if needed, default to amnesic store
        NWSStore *store = _call.store;
        if (!store) {
            store = NWSAmnesicStore.shared;
        }

        // if required, create transaction store
        NWSStore *tempStore = nil;
        if (useStore) {
            // split off store to perform mapping with
            tempStore = [store beginTransaction];
        } else {
            tempStore = store;
        }

        // perform actual mapping
        NWSLogSpag(@"mapping tree (expected:%.3fs)", _call.endpoint.mappingTime.average);
        DEBUG_STAT_START(mappingTime);
        NWSObjectID *identifier = [mapping mapElement:value store:tempStore];
        DEBUG_STAT_STOP(mappingTime, _call.endpoint);
        if (!identifier) {
            NWSLogWarn(@"mapping result is nil");
            return nil;
        }

        // parent assignment
        if (_call.parent) {
            NWSLogWarnIfNot(_call.parentPath, @"Parent was set, but no path provided");
            NWSLogWarnIfNot(_call.parentPolicy, @"Parent was set, but no setter policy");
            NWSObjectID *parentIdentifier = [tempStore identifierForObject:_call.parent];
            [tempStore setRelationForIdentifier:parentIdentifier value:identifier path:_call.parentPath policy:_call.parentPolicy baseStore:nil];
        }

        // extract result
        NWSObjectReference *reference = [tempStore referenceForIdentifier:identifier];
        if (useStore) {
            // merge-back the split-off store (this will automatically migrate object references)
            [store mergeTransaction:tempStore];
        }
        // cleanup (migrated) references
        result = reference.dereference;
    } else {
        result = value;
    }

    // report done
    return result;
}

- (NSData *)mapObject:(NSObject *)object
{
    if (!object) {
        NWSLogWarn(@"no object to serialize");
        return nil;
    }

    id data = nil;
    NWSMapping *mapping = _call.requestMapping;
    if (mapping) {
        NWSStore *store = _call.store;
        NWSLogWarnIfNot(store, @"Unable to map request without a store (with objects)");
        NWSObjectID *identifier = [store identifierForObject:object];
        data = [mapping mapIdentifier:identifier store:store];
    } else {
        data = object;
    }

    NWSParser *parser = _call.requestParser;
    if (!parser) {
        parser = NWSParser.defaultParser;
    }
    NWSLogSpag(@"serializing object");
    NSData *result = [parser serialize:data];
    if (!result) {
        NWSLogWarn(@"failed to serialize");
        return nil;
    }
    return result;
}

@end


text:
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.

using System.IO;
using ImageMagick;

namespace Magick.NET.Samples
{
    public static class ConvertImageSamples
    {
        public static void ConvertImageFromOneFormatToAnother()
        {
            // Read first frame of gif image
            using (var image = new MagickImage(SampleFiles.SnakewareGif))
            {
                // Save frame as jpg
                image.Write(SampleFiles.OutputDirectory + "Snakeware.jpg");
            }

            var settings = new MagickReadSettings();
            // Tells the xc: reader the image to create should be 800x600
            settings.Width = 800;
            settings.Height = 600;

            using (var memStream = new MemoryStream())
            {
                // Create image that is completely purple and 800x600
                using (var image = new MagickImage("xc:purple", settings))
                {
                    // Sets the output format to png
                    image.Format = MagickFormat.Png;

                    // Write the image to the memorystream
                    image.Write(memStream);
                }
            }

            // Read image from file
            using (var image = new MagickImage(SampleFiles.SnakewarePng))
            {
                // Sets the output format to jpeg
                image.Format = MagickFormat.Jpeg;

                // Create byte array that contains a jpeg file
                byte[] data = image.ToByteArray();
            }
        }

        public static void ConvertCmykToRgb()
        {
            // Uses sRGB.icm, eps/pdf produce better result when you set this before loading.
            var settings = new MagickReadSettings();
            settings.ColorSpace = ColorSpace.sRGB;

            // Create empty image
            using (var image = new MagickImage())
            {
                // Reads the eps image, the specified settings tell Ghostscript to create an sRGB image
                image.Read(SampleFiles.SnakewareEps, settings);

                // Save image as tiff
                image.Write(SampleFiles.OutputDirectory + "Snakeware.tiff");
            }

            // Read image from file
            using (var image = new MagickImage(SampleFiles.SnakewareJpg))
            {
                // Will use the CMYK profile if the image does not contain a color profile.
                // The second profile will transform the colorspace from CMYK to RGB
                image.TransformColorSpace(ColorProfile.USWebCoatedSWOP, ColorProfile.SRGB);

                // Save image as png
                image.Write(SampleFiles.OutputDirectory + "Snakeware.png");
            }

            // Read image from file
            using (var image = new MagickImage(SampleFiles.SnakewareJpg))
            {
                // Will use the CMYK profile if your image does not contain a color profile.
                // The second profile will transform the colorspace from your custom icc profile
                image.TransformColorSpace(ColorProfile.USWebCoatedSWOP, new ColorProfile(SampleFiles.YourProfileIcc));

                // Save image as tiff
                image.Write(SampleFiles.OutputDirectory + "Snakeware.tiff");
            }
        }
    }
}


text:
<?php

namespace DOMPDFModule\View\Renderer;

use Zend\View\Renderer\RendererInterface as Renderer;
use Zend\View\Resolver\ResolverInterface as Resolver;
use DOMPDF;

class PdfRenderer implements Renderer
{
    private $dompdf = null;
    private $resolver = null;
    private $htmlRenderer = null;

    public function setHtmlRenderer(Renderer $renderer)
    {
        $this->htmlRenderer = $renderer;
        return $this;
    }

    public function getHtmlRenderer()
    {
        return $this->htmlRenderer;
    }

    public function setEngine(DOMPDF $dompdf)
    {
        $this->dompdf = $dompdf;
        return $this;
    }

    public function getEngine()
    {
        return $this->dompdf;
    }

    /**
     * Renders values as a PDF
     *
     * @param  string|Model $name The script/resource process, or a view model
     * @param  null|array|\ArrayAccess Values to use during rendering
     * @return string The script output.
     */
    public function render($nameOrModel, $values = null)
    {
        $html = $this->getHtmlRenderer()->render($nameOrModel, $values);

        $paperSize = $nameOrModel->getOption('paperSize');
        $paperOrientation = $nameOrModel->getOption('paperOrientation');
        $basePath = $nameOrModel->getOption('basePath');

        $pdf = $this->getEngine();
        $pdf->set_paper($paperSize, $paperOrientation);
        $pdf->set_base_path($basePath);

        $pdf->load_html($html);
        $pdf->render();

        return $pdf->output();
    }

    public function setResolver(Resolver $resolver)
    {
        $this->resolver = $resolver;
        return $this;
    }
}


text:
from Sink import Sink, SinkInfo
from pyjamas.ui.Button import Button
from pyjamas.ui.CheckBox import CheckBox
from pyjamas.ui.VerticalPanel import VerticalPanel
from pyjamas.ui.HorizontalPanel import HorizontalPanel
from pyjamas.ui.RadioButton import RadioButton

class Buttons(Sink):
    def __init__(self):

        Sink.__init__(self)

        disabledButton = Button("Disabled Button")
        disabledCheck = CheckBox("Disabled Check")
        normalButton = Button("Normal Button")
        normalCheck = CheckBox("Normal Check")
        panel = VerticalPanel()
        radio0 = RadioButton("group0", "Choice 0")
        radio1 = RadioButton("group0", "Choice 1")
        radio2 = RadioButton("group0", "Choice 2 (Disabled)")
        radio3 = RadioButton("group0", "Choice 3")

        hp=HorizontalPanel()
        panel.add(hp)
        hp.setSpacing(8)
        hp.add(normalButton)
        hp.add(disabledButton)

        hp=HorizontalPanel()
        panel.add(hp)
        hp.setSpacing(8)
        hp.add(normalCheck)
        hp.add(disabledCheck)

        hp=HorizontalPanel()
        panel.add(hp)
        hp.setSpacing(8)
        hp.add(radio0)
        hp.add(radio1)
        hp.add(radio2)
        hp.add(radio3)

        disabledButton.setEnabled(False)
        disabledCheck.setEnabled(False)
        radio2.setEnabled(False)

        panel.setSpacing(8)
        self.initWidget(panel)

    def onShow(self):
        pass

def init():
    text="GWT supports all the myriad types of buttons that exist in HTML.  Here are a few for your viewing pleasure."
    return SinkInfo("Buttons", text, Buttons)


text:
'use strict';

// External libs.
var UglifyJS = require('uglify-js');
var fs = require('fs');

exports.init = function(grunt) {
  var exports = {};

  // Minify with UglifyJS.
  // From https://github.com/mishoo/UglifyJS2
  // API docs at http://lisperator.net/uglifyjs/
  exports.minify = function(files, dest, options) {
    options = options || {};

    grunt.verbose.write('Minifying with UglifyJS...');

    var topLevel = null;
    var totalCode = '';

    var outputOptions = getOutputOptions(options, dest);
    var output = UglifyJS.OutputStream(outputOptions);

    // Grab and parse all source files
    files.forEach(function(file){
      var code = grunt.file.read(file);
      totalCode += code;
      topLevel = UglifyJS.parse(code, {
        filename: file,
        toplevel: topLevel
      });
    });

    // Need to call this before we mangle or compress,
    // and call after any compression or ast altering
    topLevel.figure_out_scope();

    if (options.compress !== false) {
      if (options.compress.warnings !== true) {
        options.compress.warnings = false;
      }
      var compressor = UglifyJS.Compressor(options.compress);
      topLevel = topLevel.transform(compressor);

      // Need to figure out scope again after source being altered
      topLevel.figure_out_scope();
    }

    if (options.mangle !== false) {
      // compute_char_frequency optimizes names for compression
      topLevel.compute_char_frequency(options.mangle);

      // Requires previous call to figure_out_scope
      // and should always be called after compressor transform
      topLevel.mangle_names(options.mangle);
    }

    // Print the ast to OutputStream
    topLevel.print(output);

    var min = output.get();

    if (options.sourceMappingURL || options.sourceMap) {
      min += '\n//@ sourceMappingURL=' + (options.sourceMappingURL || options.sourceMap);
    }

    var result = {
      max: totalCode,
      min: min,
      sourceMap: outputOptions.source_map
    };

    grunt.verbose.ok();

    return result;
  };

  var getOutputOptions = function(options, dest) {
    var outputOptions = {
      beautify: false,
      source_map: null
    };

    if (options.preserveComments) {
      if (options.preserveComments === 'all' || options.preserveComments === true) {

        // preserve all the comments we can
        outputOptions.comments = true;
      } else if (options.preserveComments === 'some') {

        // preserve comments with directives or that start with a bang (!)
        outputOptions.comments = function(node, comment) {
          return (/^!|@preserve|@license|@cc_on/i).test(comment.value);
        };
      } else if (grunt.util._.isFunction(options.preserveComments)) {

        // support custom functions passed in
        outputOptions.comments = options.preserveComments;
      }
    }

    if (options.beautify) {
      if (grunt.util._.isObject(options.beautify)) {
        // beautify options sent as an object are merged
        // with outputOptions and passed to the OutputStream
        grunt.util._.extend(outputOptions, options.beautify);
      } else {
        outputOptions.beautify = true;
      }
    }

    if (options.sourceMap) {
      var sourceMapIn;
      if (options.sourceMapIn) {
        sourceMapIn = grunt.file.readJSON(options.sourceMapIn);
      }
      outputOptions.source_map = UglifyJS.SourceMap({
        file: dest,
        root: options.sourceMapRoot,
        orig: sourceMapIn
      });
    }

    return outputOptions;
  };

  return exports;
};


text:
using RestClient.Definitions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RestClient.Tests
{
    interface IHeaders
    {
        [Post]
        [Route(TestData.Routes.Empty)]
        Response PrimitiveWithDefaultName([InHeader]int number);

        [Post]
        [Route(TestData.Routes.Empty)]
        Response PrimitiveWithSpecifiedName([InHeader(Name = "SpecifiedName")]int number);
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>librdpmux: display_switch Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

librdpmux
    0.2.0

Library to provide low-level hypervisor guest interaction capabilties outside the hypervisor.

Main Page

Related Pages

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Data Structures

Data Structure Index

Data Fields

Data Fields

display_switch Struct Reference

Parameters for a display switch event.
 More...

#include <common.h>

Data Fields

int 	shm_fd

 	file descriptor for the shared memory region.

pixman_format_code_t 	format

 	format code describing the pixel layout of the framebuffer.

int 	w

 	width of framebuffer in px.

int 	h

 	height of framebuffer in px.

Detailed Description

Parameters for a display switch event.

The documentation for this struct was generated from the following file:

src/common.h

display_switch

Generated by

     1.8.10


text:
<?php

namespace Shop\Entity;

use Doctrine\ORM\Mapping as ORM;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;

/**
 * @ORM\Entity(repositoryClass="ProductRepository")
 * @ORM\Table(name="product")
 */

class Product implements InputFilterAwareInterface {

    public function __construct() {

    }

    /**
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    * @ORM\Column(type="integer")
    */

    protected $id;

    public function getId() {

        return $this->id;
    }

    /**
     * @ORM\Column(type="string", length=100, nullable=false, unique=true)
     */

    protected $slug;

    public function getSlug() {

        return $this->slug;
    }

    public function setSlug($slug) {

        $this->slug = $slug;
    }

    /**
     * @ORM\Column(type="string", length=100, nullable=false)
     */

    protected $title;

    public function getTitle() {

        return $this->title;
    }

    public function setTitle($title) {

        $this->title = $title;
    }

    /**
     * Method used by form
     * @param unknown $data
     */

    public function exchangeArray($data)
    {
        $this->id     = (isset($data['id'])) ? $data['id'] : null;
        $this->slug = (isset($data['slug'])) ? $data['slug'] : null;
        $this->title  = (isset($data['title'])) ? $data['title'] : null;
    }

    public function getArrayCopy()
    {
        return get_object_vars($this);
    }

    /**
     * Validation
     * @var InputFilterInterface
     */

    protected $inputFilter;

    public function setInputFilter(InputFilterInterface $inputFilter)
    {
        throw new \Exception("Not used");
    }

    public function getInputFilter()
    {
        if (!$this->inputFilter) {

            $inputFilter = new InputFilter();
            $factory     = new InputFactory();

            $inputFilter->add($factory->createInput(array(
                'name'     => 'id',
                'required' => true,
                'filters'  => array(
                    array('name' => 'Int'),
                ),
            )));

            $inputFilter->add($factory->createInput(array(
                'name'     => 'slug',
                'required' => true,
                'filters'  => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
                'validators' => array(
                    array(
                        'name'    => 'StringLength',
                        'options' => array(
                            'encoding' => 'UTF-8',
                            'min'      => 1,
                            'max'      => 100,
                        ),
                    ),
                ),
            )));

            $inputFilter->add($factory->createInput(array(
                'name'     => 'title',
                'required' => true,
                'filters'  => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
                'validators' => array(
                    array(
                        'name'    => 'StringLength',
                        'options' => array(
                            'encoding' => 'UTF-8',
                            'min'      => 1,
                            'max'      => 100,
                        ),
                    ),
                ),
            )));

            $this->inputFilter = $inputFilter;
        }

        return $this->inputFilter;
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ec.edu.espe.isi.educat04.model;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 *
 * @author pablo
 * Entidad que guarda información de la capacitación del alumno.
 */
@Embeddable
public class CapacitacionAlumnoPK implements Serializable {

    @Basic(optional = false)
    @NotNull
    @Column(name = "COD_CAPACITACION")
    private int codCapacitacion;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 10)
    @Column(name = "COD_ALUMNO")
    private String codAlumno;

    public CapacitacionAlumnoPK() {
    }

    public CapacitacionAlumnoPK(int codCapacitacion, String codAlumno) {
        this.codCapacitacion = codCapacitacion;
        this.codAlumno = codAlumno;
    }

    public int getCodCapacitacion() {
        return codCapacitacion;
    }

    public void setCodCapacitacion(int codCapacitacion) {
        this.codCapacitacion = codCapacitacion;
    }

    public String getCodAlumno() {
        return codAlumno;
    }

    public void setCodAlumno(String codAlumno) {
        this.codAlumno = codAlumno;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (int) codCapacitacion;
        hash += (codAlumno != null ? codAlumno.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof CapacitacionAlumnoPK)) {
            return false;
        }
        CapacitacionAlumnoPK other = (CapacitacionAlumnoPK) object;
        if (this.codCapacitacion != other.codCapacitacion) {
            return false;
        }
        if ((this.codAlumno == null && other.codAlumno != null) || (this.codAlumno != null && !this.codAlumno.equals(other.codAlumno))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "ec.edu.espe.isi.educat04.model.CapacitacionAlumnoPK[ codCapacitacion=" + codCapacitacion + ", codAlumno=" + codAlumno + " ]";
    }

}


text:
package maru.core;

import maru.core.model.CoreModel;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
 * The activator class that controls the plugin's life cycle.
 *

 * This core plugin defines the application model. The model is the information
 * that is read and written to disk. The plugin provides various interfaces and
 * abstract classes to be used when extending the model. It also provides an
 * API to manipulate the model ({@link maru.core.model.CoreModel}) and to listen
 * to model changes ({@link maru.core.model.ScenarioModelAdapter}).
 *

 * External plugins are meant to implement the interfaces or extend provided
 * abstract classes and use {@link maru.core.model.CoreModel} to add them to
 * the model. The plugin takes care of saving modifications to disk.
 */
public class MaruCorePlugin extends AbstractUIPlugin
{
    public static final String PLUGIN_ID = "maru.core"; //$NON-NLS-1$

    private static MaruCorePlugin plugin;
    private CoreModel coreModel;

    @Override
    public void start(BundleContext context) throws Exception
    {
        super.start(context);
        plugin = this;

        coreModel = CoreModel.getDefault();
        coreModel.startup();
    }

    @Override
    public void stop(BundleContext context) throws Exception
    {
        if (coreModel != null) {
            coreModel.shutdown();
        }

        plugin = null;
        super.stop(context);
    }

    /**
     * Get the shared plugin instance.
     *
     * @return the shared instance
     */
    public static MaruCorePlugin getDefault()
    {
        return plugin;
    }

    public CoreModel getCoreModel()
    {
        return coreModel;
    }

    /**
     * Get an image descriptor for the image file.
     *
     * @param path a path relative to the plug-in
     * @return the image descriptor
     */
    public static ImageDescriptor getImageDescriptor(String path)
    {
        return imageDescriptorFromPlugin(PLUGIN_ID, path);
    }
}


text:
package com.google.android.gms.internal;

import android.os.Parcel;
import com.google.android.gms.common.internal.safeparcel.SafeParcelable;
import java.util.Arrays;

public class hu
  implements SafeParcelable
{
  public static final hw CREATOR = new hw();
  private final String[] DR;
  private final String[] DS;
  private final String[] DT;
  private final String DU;
  private final String DV;
  private final String DW;
  private final String DX;
  private final String jG;
  private final int kg;

  hu(int paramInt, String paramString1, String[] paramArrayOfString1, String[] paramArrayOfString2, String[] paramArrayOfString3, String paramString2, String paramString3, String paramString4, String paramString5)
  {
    this.kg = paramInt;
    this.jG = paramString1;
    this.DR = paramArrayOfString1;
    this.DS = paramArrayOfString2;
    this.DT = paramArrayOfString3;
    this.DU = paramString2;
    this.DV = paramString3;
    this.DW = paramString4;
    this.DX = paramString5;
  }

  public hu(String paramString1, String[] paramArrayOfString1, String[] paramArrayOfString2, String[] paramArrayOfString3, String paramString2, String paramString3, String paramString4)
  {
    this.kg = 1;
    this.jG = paramString1;
    this.DR = paramArrayOfString1;
    this.DS = paramArrayOfString2;
    this.DT = paramArrayOfString3;
    this.DU = paramString2;
    this.DV = paramString3;
    this.DW = paramString4;
    this.DX = null;
  }

  public int describeContents()
  {
    return 0;
  }

  public String[] eR()
  {
    return this.DR;
  }

  public String[] eS()
  {
    return this.DS;
  }

  public String[] eT()
  {
    return this.DT;
  }

  public String eU()
  {
    return this.DU;
  }

  public String eV()
  {
    return this.DV;
  }

  public String eW()
  {
    return this.DW;
  }

  public String eX()
  {
    return this.DX;
  }

  public boolean equals(Object paramObject)
  {
    if (!(paramObject instanceof hu))
      return false;
    hu localhu = (hu)paramObject;
    return (this.kg == localhu.kg) && (ee.equal(this.jG, localhu.jG)) && (Arrays.equals(this.DR, localhu.DR)) && (Arrays.equals(this.DS, localhu.DS)) && (Arrays.equals(this.DT, localhu.DT)) && (ee.equal(this.DU, localhu.DU)) && (ee.equal(this.DV, localhu.DV)) && (ee.equal(this.DW, localhu.DW)) && (ee.equal(this.DX, localhu.DX));
  }

  public String getAccountName()
  {
    return this.jG;
  }

  public int getVersionCode()
  {
    return this.kg;
  }

  public int hashCode()
  {
    Object[] arrayOfObject = new Object[9];
    arrayOfObject[0] = Integer.valueOf(this.kg);
    arrayOfObject[1] = this.jG;
    arrayOfObject[2] = this.DR;
    arrayOfObject[3] = this.DS;
    arrayOfObject[4] = this.DT;
    arrayOfObject[5] = this.DU;
    arrayOfObject[6] = this.DV;
    arrayOfObject[7] = this.DW;
    arrayOfObject[8] = this.DX;
    return ee.hashCode(arrayOfObject);
  }

  public String toString()
  {
    return ee.e(this).a("versionCode", Integer.valueOf(this.kg)).a("accountName", this.jG).a("requestedScopes", this.DR).a("visibleActivities", this.DS).a("requiredFeatures", this.DT).a("packageNameForAuth", this.DU).a("callingPackageName", this.DV).a("applicationName", this.DW).toString();
  }

  public void writeToParcel(Parcel paramParcel, int paramInt)
  {
    hw.a(this, paramParcel, paramInt);
  }
}

/* Location:           /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
 * Qualified Name:     com.google.android.gms.internal.hu
 * JD-Core Version:    0.6.2
 */