text:
public interface IDataManager
{
	void SaveToJSON<T>(T classToSave, string optionalInstanceID = "");
}

redpajama_set_name: RedPajamaGithub


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

#include "ui/ozone/platform/flatland/client_native_pixmap_factory_flatland.h"

#include <lib/zx/vmar.h>
#include <lib/zx/vmo.h>
#include <vector>

#include "base/bits.h"
#include "base/check_op.h"
#include "base/fuchsia/fuchsia_logging.h"
#include "base/fuchsia/koid.h"
#include "base/numerics/safe_conversions.h"
#include "base/system/sys_info.h"
#include "ui/gfx/buffer_format_util.h"
#include "ui/gfx/client_native_pixmap.h"
#include "ui/gfx/client_native_pixmap_factory.h"
#include "ui/gfx/native_pixmap_handle.h"

namespace ui {

namespace {

bool AlignUpToPageSizeChecked(size_t size, size_t* aligned_size) {
  static_assert(base::IsValueInRangeForNumericType<size_t>(ZX_PAGE_SIZE) &&
                    base::bits::IsPowerOfTwo(ZX_PAGE_SIZE),
                "The page size must fit in a size_t and be a power of 2.");
  constexpr size_t kPageSizeMinusOne = ZX_PAGE_SIZE - 1;
  base::CheckedNumeric<size_t> aligned_size_checked =
      base::CheckAdd(size, kPageSizeMinusOne) & (~kPageSizeMinusOne);
  if (!aligned_size_checked.IsValid())
    return false;
  *aligned_size = aligned_size_checked.ValueOrDie();
  return true;
}

}  // namespace

class ClientNativePixmapFuchsia : public gfx::ClientNativePixmap {
 public:
  explicit ClientNativePixmapFuchsia(gfx::NativePixmapHandle handle)
      : handle_(std::move(handle)) {}

  ~ClientNativePixmapFuchsia() override {
    if (mapping_)
      Unmap();
  }

  ClientNativePixmapFuchsia(const ClientNativePixmapFuchsia&) = delete;
  ClientNativePixmapFuchsia& operator=(const ClientNativePixmapFuchsia&) =
      delete;

  bool Map() override {
    if (mapping_)
      return true;

    if (handle_.planes.empty() || !handle_.planes[0].vmo)
      return false;

    // Assume that the last plane is at the end of the VMO. If this assumption
    // is violated, we shouldn't get here because
    // FlatlandClientNativePixmapFactory::ImportFromHandle() validates (through
    // CanFitImageForSizeAndFormat()) that the (offset + size) for each plane is
    // less than or equal to |last_plane_end|.
    //
    // Note: the |last_plane_end| computation has been determined to not
    // overflow in FlatlandClientNativePixmapFactory::ImportFromHandle()
    // (through CanFitImageForSizeAndFormat()).
    const size_t last_plane_end =
        base::CheckAdd(handle_.planes.back().offset, handle_.planes.back().size)
            .ValueOrDie<size_t>();

#if DCHECK_IS_ON()
    // All planes should fall within the range that ends with the last plane.
    // This has been verified by
    // FlatlandClientNativePixmapFactory::ImportFromHandle() (through
    // CanFitImageForSizeAndFormat()).
    for (auto& plane : handle_.planes) {
      DCHECK(base::CheckAdd(plane.offset, plane.size).ValueOrDie<size_t>() <=
             last_plane_end);
    }
#endif

    // Round mapping size to align with the page size. Mapping
    // |aligned_mapping_size| bytes should be safe because
    // FlatlandClientNativePixmapFactory::ImportFromHandle() ensures that
    // |last_plane_end| <= <size of the VMO> where <size of the VMO> is
    // page_aligned which implies that |aligned_mapping_size| <= <size of the
    // VMO>.
    size_t aligned_mapping_size;
    if (!AlignUpToPageSizeChecked(last_plane_end, &aligned_mapping_size))
      return false;
    mapping_size_ = aligned_mapping_size;

    zx_vaddr_t addr;
    zx_status_t status = zx::vmar::root_self()->map(
        ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0, handle_.planes[0].vmo, 0,
        mapping_size_, &addr);
    if (status != ZX_OK) {
      ZX_DLOG(ERROR, status) << "zx_vmar_map";
      return false;
    }
    mapping_ = reinterpret_cast<uint8_t*>(addr);

    return true;
  }

  void Unmap() override {
    DCHECK(mapping_);

    // Flush the CPu cache in case the GPU reads the data directly from RAM.
    if (handle_.ram_coherency) {
      zx_status_t status =
          zx_cache_flush(mapping_, mapping_size_,
                         ZX_CACHE_FLUSH_DATA | ZX_CACHE_FLUSH_INVALIDATE);
      ZX_DCHECK(status == ZX_OK, status) << "zx_cache_flush";
    }

    zx_status_t status = zx::vmar::root_self()->unmap(
        reinterpret_cast<uintptr_t>(mapping_), mapping_size_);
    ZX_DCHECK(status == ZX_OK, status) << "zx_vmar_unmap";
    mapping_ = nullptr;
  }

  size_t GetNumberOfPlanes() const override { return handle_.planes.size(); }

  void* GetMemoryAddress(size_t plane) const override {
    DCHECK_LT(plane, handle_.planes.size());
    DCHECK(mapping_);
    return mapping_ + handle_.planes[plane].offset;
  }

  int GetStride(size_t plane) const override {
    DCHECK_LT(plane, handle_.planes.size());
    return base::checked_cast<int>(handle_.planes[plane].stride);
  }

  gfx::NativePixmapHandle CloneHandleForIPC() const override {
    return gfx::CloneHandleForIPC(handle_);
  }

 private:
  gfx::NativePixmapHandle handle_;

  uint8_t* mapping_ = nullptr;
  size_t mapping_size_ = 0;
};

class FlatlandClientNativePixmapFactory
    : public gfx::ClientNativePixmapFactory {
 public:
  FlatlandClientNativePixmapFactory() = default;
  ~FlatlandClientNativePixmapFactory() override = default;
  FlatlandClientNativePixmapFactory(const FlatlandClientNativePixmapFactory&) =
      delete;
  FlatlandClientNativePixmapFactory& operator=(
      const FlatlandClientNativePixmapFactory&) = delete;

  std::unique_ptr<gfx::ClientNativePixmap> ImportFromHandle(
      gfx::NativePixmapHandle handle,
      const gfx::Size& size,
      gfx::BufferFormat format,
      gfx::BufferUsage usage) override {
    // |planes| may be empty for non-mappable pixmaps. No need to validate the
    // handle in that case.
    if (handle.planes.empty())
      return std::make_unique<ClientNativePixmapFuchsia>(std::move(handle));

    // Validate that all planes refer to a single memory object.
    const absl::optional<zx_koid_t> first_plane_koid =
        base::GetKoid(handle.planes[0].vmo);
    if (!first_plane_koid)
      return nullptr;
    for (const auto& plane : handle.planes) {
      const absl::optional<zx_koid_t> plane_koid = base::GetKoid(plane.vmo);
      DCHECK(plane.vmo.is_valid() || !plane_koid);
      if (plane_koid != first_plane_koid)
        return nullptr;
    }

    if (!CanFitImageForSizeAndFormat(handle, size, format,
                                     /*assume_single_memory_object=*/true)) {
      return nullptr;
    }

    // The |last_plane_end| computation should not overflow if the
    // CanFitImageForSizeAndFormat() check passed.
    const size_t last_plane_end =
        base::CheckAdd(handle.planes.back().offset, handle.planes.back().size)
            .ValueOrDie<size_t>();

    uint64_t vmo_size;
    if (handle.planes.back().vmo.get_size(&vmo_size) != ZX_OK ||
        !base::IsValueInRangeForNumericType<size_t>(vmo_size) ||
        base::checked_cast<size_t>(vmo_size) < last_plane_end) {
      return nullptr;
    }

#if DCHECK_IS_ON()
    // zx_vmo_get_size() should return a page-aligned size. This is important
    // because we request a page-aligned size in
    // ClientNativePixmapFuchsia::Map().
    DCHECK_EQ(vmo_size % ZX_PAGE_SIZE, 0u);

    // The CanFitImageForSizeAndFormat() call above should guarantee that the
    // (offset + size) for each plane is <= |last_plane_end|, and since we now
    // know that |last_plane_end| <= |vmo_size|, then (offset + size) for each
    // plane <= |vmo_size|.
    for (const auto& plane : handle.planes) {
      DCHECK_LE(plane.offset + plane.size, vmo_size);
    }
#endif

    return std::make_unique<ClientNativePixmapFuchsia>(std::move(handle));
  }
};

gfx::ClientNativePixmapFactory* CreateClientNativePixmapFactoryFlatland() {
  return new FlatlandClientNativePixmapFactory();
}

}  // namespace ui


text:
@protocol FBSDKInfoDictionaryProviding;
@protocol FBSDKEventLogging;

NS_ASSUME_NONNULL_BEGIN

NS_SWIFT_NAME(BackgroundEventLogger)
@interface FBSDKBackgroundEventLogger : NSObject<FBSDKBackgroundEventLogging>

- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
- (instancetype)initWithInfoDictionaryProvider:(id<FBSDKInfoDictionaryProviding>)infoDictionaryProvider
                                   eventLogger:(id<FBSDKEventLogging>)eventLogger NS_DESIGNATED_INITIALIZER;

- (void)logBackgroundRefresStatus:(UIBackgroundRefreshStatus)status;

@end

NS_ASSUME_NONNULL_END

#endif


text:
class CreateFirstResponderIncidents < ActiveRecord::Migration
  def change
    create_table :first_responder_incidents do |t|
      t.references :first_responder, index: true
      t.references :incident, index: true

      t.timestamps
    end
    add_foreign_key :first_responder_incidents, :first_responders
    add_foreign_key :first_responder_incidents, :incidents
  end
end


text:
namespace {
// Controls the retry count of the simple url loader.
const int kNumFamilyInfoFetcherRetries = 1;

using ::base::BindOnce;
using ::base::JoinString;
using ::base::StrCat;
using ::base::StringPiece;
using ::base::TimeDelta;
using ::base::TimeTicks;
using ::base::UmaHistogramEnumeration;
using ::base::UmaHistogramTimes;
using ::base::Unretained;
using ::kids_chrome_management::ListFamilyMembersRequest;
using ::kids_chrome_management::ListFamilyMembersResponse;
using ::network::ResourceRequest;
using ::signin::IdentityManager;

bool IsLoadingSuccessful(const network::SimpleURLLoader& loader) {
  return loader.NetError() == net::OK;
}

bool HasHttpOkResponse(const network::SimpleURLLoader& loader) {
  if (!loader.ResponseInfo()) {
    return false;
  }
  if (!loader.ResponseInfo()->headers) {
    return false;
  }
  return net::HttpStatusCode(loader.ResponseInfo()->headers->response_code()) ==
         net::HTTP_OK;
}

std::unique_ptr<network::SimpleURLLoader> InitializeSimpleUrlLoader(
    StringPiece payload,
    StringPiece access_token,
    const GURL& url,
    net::NetworkTrafficAnnotationTag traffic_annotation) {
  std::unique_ptr<ResourceRequest> resource_request =
      std::make_unique<ResourceRequest>();
  resource_request->url = url;
  resource_request->method = "GET";
  resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit;
  resource_request->headers.SetHeader(
      net::HttpRequestHeaders::kAuthorization,
      base::StringPrintf(supervised_users::kAuthorizationHeaderFormat,
                         access_token));
  std::unique_ptr<network::SimpleURLLoader> simple_url_loader =
      network::SimpleURLLoader::Create(std::move(resource_request),
                                       traffic_annotation);
  simple_url_loader->SetRetryOptions(
      kNumFamilyInfoFetcherRetries,
      network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE);
  return simple_url_loader;
}

template <typename Request>
std::string ConvertRequestTypeToMetricLabel();
template <>
std::string ConvertRequestTypeToMetricLabel<ListFamilyMembersRequest>() {
  return "ListFamilyMembersRequest";
}

// Metric key
template <typename Request>
std::string CreateMetricKey(StringPiece metric_id) {
  return JoinString(
      {"Signin", ConvertRequestTypeToMetricLabel<Request>(), metric_id}, ".");
}
template <typename Request>
std::string CreateMetricKey(StringPiece metric_id, StringPiece metric_suffix) {
  return JoinString({"Signin", ConvertRequestTypeToMetricLabel<Request>(),
                     metric_id, metric_suffix},
                    ".");
}

std::string ConvertStateToMetricLabel(KidsExternalFetcherStatus::State state) {
  switch (state) {
    case KidsExternalFetcherStatus::NO_ERROR:
      return "NoError";
    case KidsExternalFetcherStatus::GOOGLE_SERVICE_AUTH_ERROR:
      return "AuthError";
    case KidsExternalFetcherStatus::HTTP_ERROR:
      return "HttpError";
    case KidsExternalFetcherStatus::INVALID_RESPONSE:
      return "InvalidResponse";
  }
}

// Determines the response type. See go/system-parameters to verity list of
// possible One Platform system params.
const std::string& GetSystemParameters() {
  static const base::NoDestructor<std::string> nonce("alt=proto");
  return *nonce;
}

// Controls what endpoint to call for given Request.
template <typename Request>
const std::string& GetPathForRequest(const Request& request);

template <>
const std::string& GetPathForRequest(const ListFamilyMembersRequest& request) {
  static const base::NoDestructor<std::string> nonce(
      StrCat({"families/mine/members?", GetSystemParameters()}));
  return *nonce;
}

template <typename Request>
net::NetworkTrafficAnnotationTag GetDefaultNetworkTrafficAnnotationTag();

template <>
net::NetworkTrafficAnnotationTag
GetDefaultNetworkTrafficAnnotationTag<ListFamilyMembersRequest>() {
  return net::DefineNetworkTrafficAnnotation(
      "kids_chrome_management_list_family_members", R"(
        semantics {
          sender: "Supervised Users"
          description:
            "Fetches information about the user's family group from the Google "
            "Family API."
          trigger:
            "Triggered in regular intervals to update profile information."
          data:
            "The request is authenticated with an OAuth2 access token "
            "identifying the Google account. No other information is sent."
          destination: GOOGLE_OWNED_SERVICE
        }
        policy {
          cookies_allowed: NO
          setting:
            "This feature cannot be disabled in settings and is only enabled "
            "for child accounts. If sign-in is restricted to accounts from a "
            "managed domain, those accounts are not going to be child accounts."
          chrome_policy {
            RestrictSigninToPattern {
              policy_options {mode: MANDATORY}
              RestrictSigninToPattern: "*@manageddomain.com"
            }
          }
        })");
}

// A fetcher with underlying network::SharedURLLoaderFactory.
template <typename Request, typename Response>
class FetcherImpl final : public KidsExternalFetcher<Request, Response> {
 private:
  using Callback = typename KidsExternalFetcher<Request, Response>::Callback;

 public:
  FetcherImpl() = delete;
  explicit FetcherImpl(
      IdentityManager& identity_manager,
      scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
      StringPiece url,
      Request request,
      Callback callback) {
    access_token_fetcher_ = std::make_unique<KidsAccessTokenFetcher>(
        identity_manager,
        BindOnce(&FetcherImpl::StartRequest, Unretained(this),
                 url_loader_factory, GURL(url), request,
                 std::move(callback)));  // Unretained(.) is safe because `this`
                                         // owns `access_token_fetcher_`.
  }

  // Not copyable
  FetcherImpl(const FetcherImpl&) = delete;
  FetcherImpl& operator=(const FetcherImpl&) = delete;

 private:
  static void WrapCallbackWithMetrics(Callback callback,
                                      TimeTicks start_time,
                                      KidsExternalFetcherStatus status,
                                      std::unique_ptr<Response> response) {
    TimeDelta latency = TimeTicks::Now() - start_time;
    UmaHistogramEnumeration(CreateMetricKey<Request>("Status"), status.state());
    UmaHistogramTimes(CreateMetricKey<Request>("Latency"), latency);
    UmaHistogramTimes(CreateMetricKey<Request>(
                          "Latency", ConvertStateToMetricLabel(status.state())),
                      latency);

    DCHECK(
        callback);  // https://chromium.googlesource.com/chromium/src/+/main/docs/callback.md#creating-a-callback-that-does-nothing
    std::move(callback).Run(status, std::move(response));
  }

  void StartRequest(
      scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
      GURL endpoint,
      Request request,
      Callback callback,
      base::expected<signin::AccessTokenInfo, GoogleServiceAuthError>
          access_token) {
    DCHECK(
        callback);  // https://chromium.googlesource.com/chromium/src/+/main/docs/callback.md#creating-a-callback-that-does-nothing

    Callback callback_with_metrics = BindOnce(
        WrapCallbackWithMetrics, std::move(callback), TimeTicks::Now());

    if (!access_token.has_value()) {
      std::move(callback_with_metrics)
          .Run(KidsExternalFetcherStatus::GoogleServiceAuthError(
                   access_token.error()),
               std::make_unique<Response>());
      return;
    }

    StringPiece token_value = access_token.value().token;
    net::NetworkTrafficAnnotationTag traffic_annotation =
        GetDefaultNetworkTrafficAnnotationTag<Request>();

    simple_url_loader_ = InitializeSimpleUrlLoader(
        request.SerializeAsString(), token_value,
        endpoint.Resolve(GetPathForRequest(request)), traffic_annotation);

    simple_url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
        url_loader_factory.get(),
        BindOnce(
            &FetcherImpl::OnSimpleUrlLoaderComplete, Unretained(this),
            std::move(
                callback_with_metrics)));  // Unretained(.) is safe because
                                           // `this` owns `simple_url_loader_`.
  }

  void OnSimpleUrlLoaderComplete(Callback callback,
                                 std::unique_ptr<std::string> response_body) {
    if (!IsLoadingSuccessful(*simple_url_loader_) ||
        !HasHttpOkResponse(*simple_url_loader_)) {
      std::move(callback).Run(KidsExternalFetcherStatus::HttpError(),
                              std::make_unique<Response>());
      return;
    }

    std::unique_ptr<Response> response = std::make_unique<Response>();
    if (!response->ParseFromString(*response_body)) {
      std::move(callback).Run(KidsExternalFetcherStatus::InvalidResponse(),
                              std::move(response));
      return;
    }

    std::move(callback).Run(std::move(KidsExternalFetcherStatus::Ok()),
                            std::move(response));
  }

  std::unique_ptr<KidsAccessTokenFetcher> access_token_fetcher_;
  std::unique_ptr<network::SimpleURLLoader> simple_url_loader_;
};

template class FetcherImpl<ListFamilyMembersRequest, ListFamilyMembersResponse>;

ListFamilyMembersRequest CreateListFamilyMembersRequest() {
  ListFamilyMembersRequest request;
  request.set_family_id("mine");  // Required by the contract of the protocol,
                                  // see proto definition.
  return request;
}
}  // namespace

// Main constructor, referenced by the rest.
KidsExternalFetcherStatus::KidsExternalFetcherStatus(
    State state,
    class GoogleServiceAuthError google_service_auth_error)
    : state_(state), google_service_auth_error_(google_service_auth_error) {}
KidsExternalFetcherStatus::~KidsExternalFetcherStatus() = default;

KidsExternalFetcherStatus::KidsExternalFetcherStatus(State state)
    : state_(state) {
  DCHECK(state != State::GOOGLE_SERVICE_AUTH_ERROR);
}
KidsExternalFetcherStatus::KidsExternalFetcherStatus(
    class GoogleServiceAuthError google_service_auth_error)
    : KidsExternalFetcherStatus(GOOGLE_SERVICE_AUTH_ERROR,
                                google_service_auth_error) {}

KidsExternalFetcherStatus::KidsExternalFetcherStatus(
    const KidsExternalFetcherStatus& other) = default;
KidsExternalFetcherStatus& KidsExternalFetcherStatus::operator=(
    const KidsExternalFetcherStatus& other) = default;

KidsExternalFetcherStatus KidsExternalFetcherStatus::Ok() {
  return KidsExternalFetcherStatus(State::NO_ERROR);
}
KidsExternalFetcherStatus KidsExternalFetcherStatus::GoogleServiceAuthError(
    class GoogleServiceAuthError error) {
  return KidsExternalFetcherStatus(error);
}
KidsExternalFetcherStatus KidsExternalFetcherStatus::HttpError() {
  return KidsExternalFetcherStatus(State::HTTP_ERROR);
}
KidsExternalFetcherStatus KidsExternalFetcherStatus::InvalidResponse() {
  return KidsExternalFetcherStatus(State::INVALID_RESPONSE);
}

bool KidsExternalFetcherStatus::IsOk() const {
  return state_ == State::NO_ERROR;
}
bool KidsExternalFetcherStatus::IsTransientError() const {
  if (state_ == State::HTTP_ERROR) {
    return true;
  }
  if (state_ == State::GOOGLE_SERVICE_AUTH_ERROR) {
    return google_service_auth_error_.IsTransientError();
  }
  return false;
}
bool KidsExternalFetcherStatus::IsPersistentError() const {
  if (state_ == State::INVALID_RESPONSE) {
    return true;
  }
  if (state_ == State::GOOGLE_SERVICE_AUTH_ERROR) {
    return google_service_auth_error_.IsPersistentError();
  }
  return false;
}

KidsExternalFetcherStatus::State KidsExternalFetcherStatus::state() const {
  return state_;
}
const GoogleServiceAuthError&
KidsExternalFetcherStatus::google_service_auth_error() const {
  return google_service_auth_error_;
}

std::unique_ptr<
    KidsExternalFetcher<ListFamilyMembersRequest, ListFamilyMembersResponse>>
FetchListFamilyMembers(
    IdentityManager& identity_manager,
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
    StringPiece url,
    KidsExternalFetcher<ListFamilyMembersRequest,
                        ListFamilyMembersResponse>::Callback callback) {
  return std::make_unique<
      FetcherImpl<ListFamilyMembersRequest, ListFamilyMembersResponse>>(
      identity_manager, url_loader_factory, url,
      CreateListFamilyMembersRequest(), std::move(callback));
}


text:
if [ $1 = 0 ]; then
   echo "Removing dotnet host symbolic link"
   unlink /usr/bin/dotnet
fi


text:
package com.microsoft.azure.management.databox.v2019_09_01.implementation;

import com.microsoft.azure.arm.resources.models.implementation.GroupableResourceCoreImpl;
import com.microsoft.azure.management.databox.v2019_09_01.JobResource;
import rx.Observable;
import com.microsoft.azure.management.databox.v2019_09_01.JobResourceUpdateParameter;
import java.util.List;
import com.microsoft.azure.management.databox.v2019_09_01.Sku;
import com.microsoft.azure.management.databox.v2019_09_01.StageName;
import org.joda.time.DateTime;
import com.microsoft.azure.management.databox.v2019_09_01.Error;
import com.microsoft.azure.management.databox.v2019_09_01.JobDetails;
import com.microsoft.azure.management.databox.v2019_09_01.JobDeliveryType;
import com.microsoft.azure.management.databox.v2019_09_01.JobDeliveryInfo;
import com.microsoft.azure.management.databox.v2019_09_01.DestinationAccountDetails;
import com.microsoft.azure.management.databox.v2019_09_01.UpdateJobDetails;
import rx.functions.Func1;

class JobResourceImpl extends GroupableResourceCoreImpl<JobResource, JobResourceInner, JobResourceImpl, DataBoxManager> implements JobResource, JobResource.Definition, JobResource.Update {
    private String uifMatch;
    private JobResourceUpdateParameter updateParameter;
    JobResourceImpl(String name, JobResourceInner inner, DataBoxManager manager) {
        super(name, inner, manager);
        this.updateParameter = new JobResourceUpdateParameter();
    }

    @Override
    public Observable<JobResource> createResourceAsync() {
        JobsInner client = this.manager().inner().jobs();
        return client.createAsync(this.resourceGroupName(), this.name(), this.inner())
            .map(new Func1<JobResourceInner, JobResourceInner>() {
               @Override
               public JobResourceInner call(JobResourceInner resource) {
                   resetCreateUpdateParameters();
                   return resource;
               }
            })
            .map(innerToFluentMap(this));
    }

    @Override
    public Observable<JobResource> updateResourceAsync() {
        JobsInner client = this.manager().inner().jobs();
        return client.updateAsync(this.resourceGroupName(), this.name(), this.updateParameter, this.uifMatch)
            .map(new Func1<JobResourceInner, JobResourceInner>() {
               @Override
               public JobResourceInner call(JobResourceInner resource) {
                   resetCreateUpdateParameters();
                   return resource;
               }
            })
            .map(innerToFluentMap(this));
    }

    @Override
    protected Observable<JobResourceInner> getInnerAsync() {
        JobsInner client = this.manager().inner().jobs();
        return client.getByResourceGroupAsync(this.resourceGroupName(), this.name());
    }

    @Override
    public boolean isInCreateMode() {
        return this.inner().id() == null;
    }

    private void resetCreateUpdateParameters() {
        this.updateParameter = new JobResourceUpdateParameter();
    }

    @Override
    public String cancellationReason() {
        return this.inner().cancellationReason();
    }

    @Override
    public JobDeliveryInfo deliveryInfo() {
        return this.inner().deliveryInfo();
    }

    @Override
    public JobDeliveryType deliveryType() {
        return this.inner().deliveryType();
    }

    @Override
    public JobDetails details() {
        return this.inner().details();
    }

    @Override
    public Error error() {
        return this.inner().error();
    }

    @Override
    public Boolean isCancellable() {
        return this.inner().isCancellable();
    }

    @Override
    public Boolean isCancellableWithoutFee() {
        return this.inner().isCancellableWithoutFee();
    }

    @Override
    public Boolean isDeletable() {
        return this.inner().isDeletable();
    }

    @Override
    public Boolean isShippingAddressEditable() {
        return this.inner().isShippingAddressEditable();
    }

    @Override
    public Sku sku() {
        return this.inner().sku();
    }

    @Override
    public DateTime startTime() {
        return this.inner().startTime();
    }

    @Override
    public StageName status() {
        return this.inner().status();
    }

    @Override
    public JobResourceImpl withSku(Sku sku) {
        this.inner().withSku(sku);
        return this;
    }

    @Override
    public JobResourceImpl withDeliveryInfo(JobDeliveryInfo deliveryInfo) {
        this.inner().withDeliveryInfo(deliveryInfo);
        return this;
    }

    @Override
    public JobResourceImpl withDeliveryType(JobDeliveryType deliveryType) {
        this.inner().withDeliveryType(deliveryType);
        return this;
    }

    @Override
    public JobResourceImpl withDetails(JobDetails details) {
        this.inner().withDetails(details);
        return this;
    }

    @Override
    public JobResourceImpl withIfMatch(String ifMatch) {
        this.uifMatch = ifMatch;
        return this;
    }

    @Override
    public JobResourceImpl withDestinationAccountDetails(List<DestinationAccountDetails> destinationAccountDetails) {
        this.updateParameter.withDestinationAccountDetails(destinationAccountDetails);
        return this;
    }

    @Override
    public JobResourceImpl withDetails(UpdateJobDetails details) {
        this.updateParameter.withDetails(details);
        return this;
    }

}


text:
import argparse
import hashlib
import json
import os

BEATLES_INDEX_PATH = '../mir_dataset_loaders/indexes/beatles_index.json'
BEATLES_ANNOTATION_SCHEMA = ['beat', 'chordlab', 'keylab', 'seglab']

def md5(file_path):
    """Get md5 hash of a file.

    Parameters
    ----------
    file_path: str
        File path.

    Returns
    -------
    md5_hash: str
        md5 hash of data in file_path
    """
    hash_md5 = hashlib.md5()
    with open(file_path, 'rb') as fhandle:
        for chunk in iter(lambda: fhandle.read(4096), b''):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

def make_beatles_index(data_path):
    annotations_dir = os.path.join(data_path, 'Beatles', 'annotations')
    cds_dir = os.path.join(annotations_dir, 'all', 'The Beatles')
    audio_dir = os.path.join(data_path, 'Beatles', 'audio')
    cds = os.listdir(cds_dir)
    track_ids = []
    beatles_index = {}
    totfiles = []
    for c in cds:

        for t in sorted(os.listdir(os.path.join(cds_dir, c))):
            if 'ttl' in t:
                totfiles.append(t)

                track_id = '{}{}'.format(
                    os.path.basename(c).split('_')[0][:2],
                    os.path.basename(t).split('_')[0],
                )
                if 'CD' in t:
                    track_id = '10{}{}'.format(
                        os.path.basename(c).split('_')[0][-1],
                        os.path.basename(t).split('_')[2][:2],
                    )
                track_ids.append(track_id)

                # checksum
                audio_checksum = md5(
                    os.path.join(audio_dir, c, '{}.wav'.format(t[:-4]))
                )
                audio_path = '{}/{}'.format(
                    'audio', os.path.join(c, '{}.wav'.format(t[:-4]))
                )

                annot_checksum, annot_rels = [], []

                for annot_type in BEATLES_ANNOTATION_SCHEMA:
                    cds_dir = os.path.join(annotations_dir, annot_type, 'The Beatles')
                    annot_path = os.path.join(cds_dir, c)
                    if annot_type is 'beat':
                        annot_file = '{}.txt'.format(t[:-4])
                    else:
                        annot_file = '{}.lab'.format(t[:-4])

                    if os.path.exists(os.path.join(annot_path, annot_file)):
                        annot_checksum.append(md5(os.path.join(annot_path, annot_file)))
                        annot_rels.append(
                            os.path.join(
                                'annotations', annot_type, 'The Beatles', c, annot_file
                            )
                        )
                    else:
                        annot_checksum.append(None)
                        annot_rels.append(None)

                beatles_index[track_id] = {
                    'audio': (audio_path, audio_checksum),
                    'beat': (annot_rels[0], annot_checksum[0]),
                    'chords': (annot_rels[1], annot_checksum[1]),
                    'keys': (annot_rels[2], annot_checksum[2]),
                    'sections': (annot_rels[3], annot_checksum[3]),
                }
    with open(BEATLES_INDEX_PATH, 'w') as fhandle:
        json.dump(beatles_index, fhandle, indent=2)

def main(args):
    make_beatles_index(args.beatles_data_path)

if __name__ == '__main__':
    PARSER = argparse.ArgumentParser(description='Make Beatles index file.')
    PARSER.add_argument(
        'beatles_data_path', type=str, help='Path to Beatles data folder.'
    )

    main(PARSER.parse_args())


text:
# property-no-unknown

Disallow unknown properties.

<!-- prettier-ignore -->
```css
a { heigth: 100%; }
/** ↑
 * This property */
```

This rule considers properties defined in the [CSS Specifications and browser specific properties](https://github.com/betit/known-css-properties#source) to be known.

This rule ignores:

- variables (`$sass`, `@less`, `--custom-property`)
- vendor-prefixed properties (e.g., `-moz-align-self`, `-webkit-align-self`)

Use option `checkPrefixed` described below to turn on checking of vendor-prefixed properties.

## Options

### `true`

The following patterns are considered violations:

<!-- prettier-ignore -->
```css
a {
  colr: blue;
}
```

<!-- prettier-ignore -->
```css
a {
  my-property: 1;
}
```

The following patterns are _not_ considered violations:

<!-- prettier-ignore -->
```css
a {
  color: green;
}
```

<!-- prettier-ignore -->
```css
a {
  fill: black;
}
```

<!-- prettier-ignore -->
```css
a {
  -moz-align-self: center;
}
```

<!-- prettier-ignore -->
```css
a {
  -webkit-align-self: center;
}
```

<!-- prettier-ignore -->
```css
a {
  align-self: center;
}
```

## Optional secondary options

### `ignoreProperties: ["/regex/", /regex/, "string"]`

Given:

```
["/^my-/", "custom"]
```

The following patterns are _not_ considered violations:

<!-- prettier-ignore -->
```css
a {
  my-property: 10px;
}
```

<!-- prettier-ignore -->
```css
a {
  my-other-property: 10px;
}
```

<!-- prettier-ignore -->
```css
a {
  custom: 10px;
}
```

### `ignoreSelectors: ["/regex/", /regex/, "string"]`

Skips checking properties of the given selectors against this rule.

Given:

```
[":root"]
```

The following patterns are _not_ considered violations:

<!-- prettier-ignore -->
```css
:root {
  my-property: blue;
}
```

### `ignoreAtRules: ["/regex/", /regex/, "string"]`

Ignores properties nested within specified at-rules.

Given:

```
["supports"]
```

The following patterns are _not_ considered violations:

<!-- prettier-ignore -->
```css
@supports (display: grid) {
  a {
    my-property: 1;
  }
}
```

### `checkPrefixed: true | false` (default: `false`)

If `true`, this rule will check vendor-prefixed properties.

For example with `true`:

The following patterns are _not_ considered violations:

<!-- prettier-ignore -->
```css
a {
  -webkit-overflow-scrolling: auto;
}
```

<!-- prettier-ignore -->
```css
a {
  -moz-box-flex: 0;
}
```

The following patterns are considered violations:

<!-- prettier-ignore -->
```css
a {
  -moz-align-self: center;
}
```

<!-- prettier-ignore -->
```css
a {
  -moz-overflow-scrolling: center;
}
```


text:
package chartutil

import (
	"io/ioutil"

	"github.com/ghodss/yaml"

	"k8s.io/helm/pkg/proto/hapi/chart"
)

// UnmarshalChartfile takes raw Chart.yaml data and unmarshals it.
func UnmarshalChartfile(data []byte) (*chart.Metadata, error) {
	y := &chart.Metadata{}
	err := yaml.Unmarshal(data, y)
	if err != nil {
		return nil, err
	}
	return y, nil
}

// LoadChartfile loads a Chart.yaml file into a *chart.Metadata.
func LoadChartfile(filename string) (*chart.Metadata, error) {
	b, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	return UnmarshalChartfile(b)
}

// SaveChartfile saves the given metadata as a Chart.yaml file at the given path.
//
// 'filename' should be the complete path and filename ('foo/Chart.yaml')
func SaveChartfile(filename string, cf *chart.Metadata) error {
	out, err := yaml.Marshal(cf)
	if err != nil {
		return err
	}
	return ioutil.WriteFile(filename, out, 0755)
}


text:
qx.Class.define("ms123.ckeditor.toolbar.fontfamily.Button", {
	extend: ms123.ckeditor.toolbar.AbstractToolbarEntry,
	include: ms123.ckeditor.toolbar.fontfamily.MAction,

	construct: function (_ckrte, fonts) {
		var control;

		// Call the superclass constructor
		this.base(arguments, _ckrte);

		// Instantiate the control.
		control = new qx.ui.form.SelectBox();

		// Set common button properties
		control.set({
			toolTipText: "Change Font Family",
			focusable: false,
			keepFocus: true,
			width: 120,
			height: 16,
			margin: [0, 0]
		});

		// If the list of fonts wasn't provided...
		if (!fonts) {
			// ... then use the default list
			fonts = this.constructor.fonts;
		}

		// Add each of the fonts to the select box
		fonts.forEach(

		function (font, i) {
			var listItem = new qx.ui.form.ListItem(font.nickname);
			listItem.setUserData("family", font.family);
			listItem.set({
				focusable: false,
				keepFocus: true,
				font: qx.bom.Font.fromString("12px " + font.nickname)
			});
			control.add(listItem);

			// If this is the first element in the list...
			if (i == 0) {
				// ... then select this one.
				control.setSelection([listItem]);
			}
		});

		// When the selection changes, call the appropriate action
		control.addListener("changeSelection", function (e) {
			// Retrieve event data
			var data = e.getData()[0];
			var nickname = data.getLabel();
			var family = data.getUserData("family");

			// Call the action function
			this._action(nickname, family);
		}, this);

		// Save this control
		this.setControl(control);
	},

	statics: {
		/**
		 * The default list of fonts to be available in the Font combo in the
		 * toolbar. The nickname is displayed in the toolbar, and the complete
		 * family is used in the editor.
		 */
		fonts: [{
			nickname: "Arial",
			family: "Arial, Helvetica, sans-serif;"
		},
		{
			nickname: "Comic Sans MS",
			family: "Comic Sans MS, cursive;"
		},
		{
			nickname: "Courier New",
			family: "Courier New, Courier, monospace;"
		},
		{
			nickname: "Georgia",
			family: "Georgia, serif;"
		},
		{
			nickname: "Lucida Sans Unicode",
			family: "Lucida Sans Unicode, Lucida Grande, sans-serif;"
		},
		{
			nickname: "Tahoma",
			family: "Tahoma, Geneva, sans-serif;"
		},
		{
			nickname: "Times New Roman",
			family: "Times New Roman, Times, serif;"
		},
		{
			nickname: "Trebuchet MS",
			family: "Trebuchet MS, Helvetica, sans-serif;"
		},
		{
			nickname: "Verdana",
			family: "Verdana, Geneva, sans-serif"
		}]
	}
});


text:
@interface ViewController () {
    float oldHeightView0;
    float oldHeightView1;
    float oldHeightView2;
    float oldHeightView3;
    NSInteger selectedIndex;
    NSArray *allViews;

    NSArray *arrayData;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.contraintHeightView1.constant = SCREEN_HEIGHT - BotSelectedRow;
    self.contraintHeightView2.constant = HeightUnSelectedRow;
    self.contraintHeightView3.constant = HeightUnSelectedRow;
    self.contraintHeightView4.constant = HeightUnSelectedRow;
    self.contraintHeightView5.constant = HeightUnSelectedRow;

    arrayData = @[@"http://stuffpoint.com/nature/image/371042-nature-autumns-natural-beauty.jpg",
                  @"https://s-media-cache-ak0.pinimg.com/736x/60/b7/01/60b7019827cf8f7affd921f02793adf0.jpg",
                  @"http://www.bluesunhotels.com/EasyEdit/UserFiles/PageImages/natural-beauty-of-croatia/natural-beauty-of-croatia-635350572813900157-5_570_320.jpeg",
                  @"http://pinnest.net/newpinnest/wp-content/uploads/2013/08/13772501252d1a5.jpg",
                  @"https://image.freepik.com/free-photo/natural-beauty-of-hidden-lake-gardens--plants--trees_19-107081.jpg",
                  @"http://images.all-free-download.com/images/graphiclarge/nature_555955.jpg",
                  @"http://media-cdn.tripadvisor.com/media/photo-s/01/5f/fd/59/natural-beauty.jpg",
                  @"http://full.creative.touchtalent.com/natural-beauty-of-mountain-roses-8545.jpg"];
    allViews = @[self.view1, self.view2, self.view3, self.view4, self.view5];

    [self reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private methods

-(IBAction)move:(UIPanGestureRecognizer *)sender {
    [self.view bringSubviewToFront:[sender view]];
    CGPoint translatedPoint = [sender translationInView:self.view];
    static BOOL isScrollDown2Rows = NO;
    static BOOL isScrollUp2Rows = NO;

    if ([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) {
        oldHeightView0 = self.contraintHeightView0.constant;
        oldHeightView1 = self.contraintHeightView1.constant;
        oldHeightView2 = self.contraintHeightView2.constant;
        oldHeightView3 = self.contraintHeightView3.constant;

        [self updateViews];
    }
    else if ([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateChanged) {
//        NSLog(@"%@", NSStringFromCGPoint(translatedPoint));
        if (translatedPoint.y < 0) { // scroll DOWN
            if (selectedIndex < arrayData.count - 1) {
                self.contraintHeightView1.constant = oldHeightView1 + translatedPoint.y;
                self.contraintHeightView2.constant = oldHeightView2 - translatedPoint.y > SCREEN_HEIGHT - BotSelectedRow ? SCREEN_HEIGHT - BotSelectedRow : oldHeightView2 - translatedPoint.y;

                // scroll 2 rows
                if (self.contraintHeightView1.constant <= 0) {
                    isScrollDown2Rows = YES;
                    self.contraintHeightView2.constant = SCREEN_HEIGHT - BotSelectedRow + self.contraintHeightView1.constant;
                    self.contraintHeightView3.constant = oldHeightView3 - self.contraintHeightView1.constant;
                }
            }
            else {
                self.contraintHeightView1.constant = oldHeightView1 + translatedPoint.y / 8;
            }
        }
        else { // scroll UP
            if (selectedIndex > 0){
                self.contraintHeightView0.constant = oldHeightView0 + translatedPoint.y;
                self.contraintHeightView1.constant = oldHeightView1 - translatedPoint.y < HeightUnSelectedRow ? HeightUnSelectedRow : oldHeightView1 - translatedPoint.y;

                // scroll 2 rows
                if (self.contraintHeightView0.constant > SCREEN_HEIGHT - BotSelectedRow) {
                    isScrollUp2Rows = YES;
                    if (selectedIndex == 1) {
                        self.contraintHeightView_1.constant = (self.contraintHeightView0.constant - (SCREEN_HEIGHT - BotSelectedRow)) / 8;
                        self.contraintHeightView0.constant = SCREEN_HEIGHT - BotSelectedRow;
                    } else {
                        self.contraintHeightView0.constant = 2 * (SCREEN_HEIGHT - BotSelectedRow) - self.contraintHeightView0.constant;
                        self.contraintHeightView_1.constant = SCREEN_HEIGHT - BotSelectedRow - self.contraintHeightView0.constant;
                    }
                }
            }
            else {
                self.contraintHeightView0.constant = oldHeightView0 + translatedPoint.y / 8;
            }
        }
    }
    else if ([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) {
        [UIView animateWithDuration:0.25 animations:^{

            if (translatedPoint.y < 0) { // scroll DOWN
                if (selectedIndex < arrayData.count - 1) {
                    self.contraintHeightView1.constant = 0;
                    self.contraintHeightView2.constant = SCREEN_HEIGHT - BotSelectedRow;
                    self.contraintHeightView3.constant = HeightUnSelectedRow;

                    if (isScrollDown2Rows && selectedIndex < arrayData.count - 2) {
                        self.contraintHeightView2.constant = 0;
                        self.contraintHeightView3.constant = SCREEN_HEIGHT - BotSelectedRow;
                    }
                }
                else {
                    self.contraintHeightView1.constant = SCREEN_HEIGHT - BotSelectedRow;
                }
            }
            else { // scroll UP
                if (selectedIndex > 0){
                    self.contraintHeightView0.constant = SCREEN_HEIGHT - BotSelectedRow;
                    self.contraintHeightView1.constant = HeightUnSelectedRow;
                    self.contraintHeightView2.constant = HeightUnSelectedRow;

                    if (isScrollUp2Rows && selectedIndex > 1) {
                        self.contraintHeightView_1.constant = SCREEN_HEIGHT - BotSelectedRow;
                        self.contraintHeightView0.constant = HeightUnSelectedRow;
                    } else if (isScrollUp2Rows && selectedIndex == 1) {
                        self.contraintHeightView_1.constant = 0;
                        self.contraintHeightView0.constant = SCREEN_HEIGHT - BotSelectedRow;
                    }
                }
                else {
                    self.contraintHeightView0.constant = 0;
                }
            }
            [self.view setNeedsLayout];
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {

            // scroll DOWN
            if (translatedPoint.y < 0 && selectedIndex < arrayData.count - 1) {
                if (isScrollDown2Rows && selectedIndex < arrayData.count - 2) {
                    selectedIndex += 2;
                } else {
                    selectedIndex++;
                }
                isScrollDown2Rows = NO;
                [self reloadData];
            }

            // scroll UP
            if (translatedPoint.y > 0 && selectedIndex > 0) {
                if (isScrollUp2Rows && selectedIndex > 1) {
                    selectedIndex -= 2;
                } else {
                    selectedIndex--;
                }
                isScrollUp2Rows = NO;
                [self reloadData];
            }
            [self updateViews];

            self.contraintHeightView_1.constant = 0;
            self.contraintHeightView0.constant = 0;
            self.contraintHeightView1.constant = SCREEN_HEIGHT - BotSelectedRow;
            self.contraintHeightView2.constant = HeightUnSelectedRow;
            self.contraintHeightView3.constant = HeightUnSelectedRow;
            [self.view setNeedsLayout];
            [self.view layoutIfNeeded];
        }];
    }
}

-(IBAction)tap:(UITapGestureRecognizer *)sender {
    CGPoint point = [sender locationInView:sender.view];
//    NSLog(@"%@", NSStringFromCGPoint(point));

    NSInteger index = -1;
    for (int i = 0; i < allViews.count; i++) {
        if (CGRectContainsPoint(((UIView *)allViews[i]).frame, point)) {
            index = i + selectedIndex;
        }
    }

    if (index >= 0 && index < arrayData.count) {
        [self didTapAtIndex:index];
    }
}

- (void) updateViews{
    for (int i = 1; i < allViews.count; i++) {
        if (i + selectedIndex >= arrayData.count) {
            ((UIView *)allViews[i]).hidden = YES;
        }
        else {
            ((UIView *)allViews[i]).hidden = NO;
        }
    }
}

- (void) reloadData{
//    NSLog(@"%ld", (long) selectedIndex);

    if (selectedIndex > 0) {
        NSInteger index = selectedIndex - 1 < 0 ? 0 : selectedIndex - 1;
        [ImageViewInView(self.view0) sd_setImageWithURL:[NSURL URLWithString:[self imageUrlAtIndex:index]]];
        LabelInView(self.view0).text = [self textAtIndex:index];
    }
    else {
        ImageViewInView(self.view0).image = nil;
        LabelInView(self.view0).text = @"";
    }
    if (selectedIndex > 1) {
        NSInteger index = selectedIndex - 2 < 0 ? 0 : selectedIndex - 2;
        [ImageViewInView(self.view_1) sd_setImageWithURL:[NSURL URLWithString:[self imageUrlAtIndex:index]]];
        LabelInView(self.view_1).text = [self textAtIndex:index];
    }
    else {
        ImageViewInView(self.view_1).image = nil;
        LabelInView(self.view_1).text = @"";
    }
    for (NSInteger i = 0; i < allViews.count; i++) {
        NSInteger index = i + selectedIndex < arrayData.count ? i + selectedIndex : arrayData.count - 1;
        [ImageViewInView(allViews[i]) sd_setImageWithURL:[NSURL URLWithString:[self imageUrlAtIndex:index]]];
        LabelInView(allViews[i]).text = [self textAtIndex:index];
    }

    SubLabelInView(self.view1).text = [self subTextAtIndex:selectedIndex];
}

#pragma mark - Override methods

- (NSString *) imageUrlAtIndex: (NSInteger) index{
    if (index < 0 || index >= arrayData.count) {
        return @"";
    }
    return arrayData[index];
}

- (NSString *) textAtIndex: (NSInteger) index{
    if (index < 0 || index >= arrayData.count) {
        return @"";
    }
    return arrayData[index];
}

- (NSString *) subTextAtIndex: (NSInteger) index{
    if (index < 0 || index >= arrayData.count) {
        return @"";
    }
    return arrayData[index];
}

- (void) didTapAtIndex: (NSInteger) index{
    NSLog(@"%ld", index);
}

@end


text:
function commandDeop(player, btn) {
	var _ = $(btn);
	console.log("command deop from", _);
	sendCommand("deop "+player, function() {
//		_.closest("li").addClass("kicked");
	});
}

function commandOp(player, btn) {
	var _ = $(btn);
	console.log("command op from", _);
	sendCommand("op "+player, function() {
//		_.closest("li").addClass("kicked");
	});
}

function commandKick(player, btn) {
	var _ = $(btn);
	console.log("command kick from", _);
	sendCommand("kick "+player, function() {
		_.closest("li").addClass("kicked");
	});
}

function commandBan(player, btn) {
	var _ = $(btn);
	sendCommand("kick "+player, function() {
		_.closest("li").addClass("banned");
	});
}

function sendCommand(command, success, fail) {
	console.log("Send command => "+command);
	$.post(CONSOLE_INPUT, {"command":command}, function(data) {
		console.log("Command success", data);
		if( success ) {
			success(data);
		}

	}).fail( function(xhr, textStatus, errorThrown) {
		console.log("Command fail", xhr.responseJSON);
		if( fail ) {
			fail(xhr.responseJSON);
		}
    });
}

$(function() {
	//https://developer.mozilla.org/fr/docs/Server-sent_events/Using_server-sent_events
// 	$(".consolestream")
	var consoleTitle = $(".consolestream").closest(".panel").find(".panel-title").first();
	if( !consoleTitle.length ) {
		return;
	}
// 	var consolePing = $('');
	var consoleIcon = $('');
	var consoleStartButton = $('<button class="btn btn-primary btn-xs pull-right" type="button">Connecter</button>');
	var consoleStopButton = $('<button class="btn btn-primary btn-xs pull-right" type="button">Déconnecter</button>');
	var consoleList = $(".consolestream").first();
	var consoleMaxRows = 200;
	var scrollMax = consoleList.height();
	var attachedScroll = true;

	var playerCount = $(".playercount");
	var playersList = $(".playerslist").first();
	var playersNone = $(".noplayer");

	consoleTitle.append(consoleIcon);
// 	consoleTitle.append(consolePing);
	consoleTitle.append(consoleStartButton);
	consoleTitle.append(consoleStopButton.hide());

	var source;
	function startConsole() {
		consoleStartButton.hide();
		consoleList.empty();
		source = new EventSource(CONSOLE_STREAM);
// 		source = new EventSource('http://flo.mcm.sowapps.com/user/server/8/console.html');
	// 	console.log('consoleList.height', consoleList.height());
	// 	console.log('consoleList.innerHeight', consoleList.innerHeight());
	// 	console.log('consoleList.outerHeight', consoleList.outerHeight());
	// 	console.log("source", source);
		source.addEventListener('message', function(e) {
// 			console.log(e.data);
			consoleList.append('
'+e.data+'
');
			consoleList.children("li").slice(0, -consoleMaxRows).remove();
// 			if( consoleList.children("li").length > consoleMaxRows ) {

// 			}
			if( attachedScroll ) {
				consoleList.scrollTop(consoleList[0].scrollHeight);
			}
		}, false);

		source.addEventListener('process', function(e) {
			var process = JSON.parse(e.data);
			process.mem_res = Math.ceil(process.mem_res/1024)+'Mo';
			process.mem_virt = Math.ceil(process.mem_virt/1024)+'Mo';
			$("body").fill("process-", process);
		});

		source.addEventListener('players', function(e) {
// 			console.log(e.data, e);
			var players = JSON.parse(e.data);
// 			console.log("players", players);
			var c = 0;
			playersList.empty();
			for( var k in players ) {
				var player = players[k];
// 				console.log("isString(player) ", typeof player, player);
				if( !isString(player) ) {
					continue;
				}
// 					console.log("Append "+player);
				var playerRow = $('
'+player+'
');
				var buttons = $('

');
				buttons.append('<button class="btn btn-default" onClick="commandDeop(\''+player+'\', this);" title="Rétrograder"></button>');
				buttons.append('<button class="btn btn-default" onClick="commandOp(\''+player+'\', this);" title="Promouvoir"></button>');
				buttons.append('<button class="btn btn-default" onClick="commandKick(\''+player+'\', this);" title="Éjecter"></button>');
				buttons.append('<button class="btn btn-default"onClick="commandBan(\''+player+'\', this);" title="Bannir"></button>');
				playerRow.append(buttons);
				playersList.append(playerRow);
				c++;
			}
// 			console.log("Number fo players online ? "+c);
			if( c ) {
				playersNone.filter(":visible").hide();
				playersList.filter(":hidden").show();
			} else {
				playersNone.filter(":hidden").show();
				playersList.filter(":visible").hide();
			}
			playerCount.text(c);

		}, false);

// 		source.addEventListener('ping', function(e) {
// 			// Connection was opened.
// 			var now = Date.now();
// 	// 		console.log("Ping - result", e);
// 			consolePing.text((now-e.data)+"ms");
// 	// 		console.log("Ping - ping", (e.data-now)*1000);
// 		}, false);

		source.addEventListener('open', function(e) {
			// Connection was opened.
	// 		console.log("Open");
			consoleIcon.css("color", consoleIcon.data("online"));
		}, false);

		source.addEventListener('error', function(e) {
			console.log("Error", e);
			if( e.readyState == EventSource.CLOSED ) {
				// Connection was closed.
				consoleIcon.css("color", consoleIcon.data("offline"));
// 				consolePing.text("");
			}
		}, false);

		consoleStopButton.show();
	}

	function stopConsole() {
		if( !source ) {
			return;
		}
		consoleStopButton.hide();
		source.close();
// 		consoleList.empty();
// 		consolePing.text("");
		consoleIcon.css("color", consoleIcon.data("offline"));
// 		console.log('consoleStartButton', consoleStartButton);
		consoleStartButton.show();
	}

	consoleStartButton.click(startConsole);
	consoleStopButton.click(stopConsole);

	consoleList.scroll(function(e) {
		var scrollDelta = consoleList[0].scrollHeight-consoleList.height()-consoleList.scrollTop();
// 		console.log("scrollDelta => "+scrollDelta);
// 		console.log("scrollMax => "+scrollMax);
		attachedScroll = scrollDelta < scrollMax;
// 		console.log("attachedScroll ? "+attachedScroll);
	});

	var consoleInput = $("#ConsoleInput");
	var consoleSendBtn = $("#ConsoleSendButton");
	consoleInput.pressEnter(function() {
		consoleSendBtn.click();
	});
	var sendingCommand;
	consoleSendBtn.click(function() {
		if( sendingCommand ) {
			return;
		}
		var command = consoleInput.val();
		if( command.length < 2 ) {
			return;
		}
		sendingCommand = true;
		consoleInput.prop("disabled", true);
		$(".rcon_alert").remove();
		sendCommand(command, function(data) {
			sendingCommand = false;
//			console.log("Command success", data);
			consoleInput.val("");
			consoleInput.prop("disabled", false);
			consoleInput.focus();
			if( !data ) {
				return;
			}
// 			console.log("data ", data);
// 			console.log("data.length => "+data.length);
			consoleInput.parent().after('
<button type="button" class="close" data-dismiss="alert" aria-label="Fermer">×</button>'+data+'
');
		}, function(response) {
			sendingCommand = false;
// 			console.log(xhr, textStatus, errorThrown);
//			console.log("Command fail", response);
			// There is result and translated one
			var error = response && response.code != response.description ? response.description : 'Une erreur est survenue.';
			consoleInput.parent().after('
<button type="button" class="close" data-dismiss="alert" aria-label="Fermer">×</button>'+error+'
');
			consoleInput.prop("disabled", false);
			consoleInput.focus();
	    });
	});
// 	source.onmessage = function (e) {
// 		console.log("Message", e);
// // 		var message = JSON.parse(e.data);
// 		// handle message
// 	};

	$(".showpassword").each(function() {
		var input = $(this);
		var showBtn = input.next().find(".showbtn");
		var hideBtn = input.next().find(".hidebtn");
// 		console.log("showpassword", showBtn, input);
		showBtn.click(function() {
			input.attr("type", "text");
			showBtn.hide();
			hideBtn.show();
		});
		hideBtn.click(function() {
			input.attr("type", "password");
			showBtn.show();
			hideBtn.hide();
		});
	});

	$(".consolewrapper").click(function() {
// 		console.log("Console click, selection ["+getSelection()+"]");
		if( getSelection() != "" ) { return; }
		consoleInput.focus();
	});
});


text:
#include <aws/kinesisanalyticsv2/model/RollbackApplicationRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::KinesisAnalyticsV2::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

RollbackApplicationRequest::RollbackApplicationRequest() :
    m_applicationNameHasBeenSet(false),
    m_currentApplicationVersionId(0),
    m_currentApplicationVersionIdHasBeenSet(false)
{
}

Aws::String RollbackApplicationRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_applicationNameHasBeenSet)
  {
   payload.WithString("ApplicationName", m_applicationName);

  }

  if(m_currentApplicationVersionIdHasBeenSet)
  {
   payload.WithInt64("CurrentApplicationVersionId", m_currentApplicationVersionId);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection RollbackApplicationRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "KinesisAnalytics_20180523.RollbackApplication"));
  return headers;

}


text:
package easy.data.xml;

import easy.data.util.XML;

/**
 * Performs some processing on XML data after it has been
 * loaded by an XMLDataSource
 *
 * @author Nadeem Abdul Hamid
 *
 */
public interface IPostProcessor {
	public XML process(XML xml);
}


text:
<?php

namespace Mmi\Cache;

/**
 * Interfejs handlerów bufora
 */
interface CacheHandlerInterface
{
    /**
     * Ładuje dane o podanym kluczu
     * @param string $key klucz
     */
    public function load($key);

    /**
     * Zapisuje dane pod podanym kluczem
     * @param string $key klucz
     * @param string $data
     * @param int $lifeTime wygaśnięcie danych w buforze (informacja dla bufora)
     */
    public function save($key, $data, $lifeTime);

    /**
     * Kasuje dane o podanym kluczu
     * @param string $key klucz
     */
    public function delete($key);

    /**
     * Kasuje wszystkie dane
     */
    public function deleteAll();
}


text:
1. spring项目官网:[https://spring.io/projects](https://spring.io/projects) ,其中的`spring-framework`即是spring框架内容
2. 历史:(1) spring 1.x,xml配置时代 (2) spring 2.x,注解时代 (3) **spring 3.x,java配置**
3. spring模块(每个模块有个jar包):
    - 核心容器:`spring-core`, `spring-beans`, `spring-context`(运行时spring容器), `spring-context-support`(spring对第三方包的集成支持), `spring-expression`(使用表达式语言在运行时查询和操作对象)
    - AOP:spring-aop, spring-aspects
    - 消息:spring-messaging
    - 数据访问:`spring-jdbc`, `spring-tx`(提供编程式和声明明式事物支持), `spring-orm`, `spring-oxm`(提供对对象/xml映射技术支持), `spring-jms`(提供jms支持)
    - Web: `spring-web`(在web项目中提供spring容器), `spring-webmvc`(基于Servlet的SpringMVC), `spring-websocket`, `spring-webmvc-portlet`
4. spring生态:`Spring Boot`(使用默认开发配置来快速开发)、`Spring Cloud`(为分布式系统开发提供工具集)等
5. 本文档基于spring4.3.8

## Hello World

- maven依赖

    ```xml
        <dependency>
            <groupId>org.springframework</groupId>
            <!--包含spring-core、spring-beans、spring-aop、spring-expression、spring-instrument-->
            <artifactId>spring-context</artifactId>
            <version>4.3.8.RELEASE</version>
        </dependency>
    ```
- 依赖注入
    - 声明Bean的注解(下面几个注解效果一样):
        - `@Component` 没有明确的角色
        - `@Service` 在业务逻辑层(cn.aezo.spring.aop_spel.service)使用
        - `@Repository` 在数据访问层(cn.aezo.spring.aop_spel.dao)使用
        - `@Controller` 在展现层使用
    - 注入Bean的注解(效果一样)
        - `@Autowired` Spring提供(默认按类型by type,如果想用byName,使用`@Qulifier`)
        - `@Resource` JSR-250提供(常用)
        - `@Inject` JSR-330提供
- java配置
    - `@Configuration` 注解类表示此类是一个配置类,里面有0个或者多个`@Bean`
        - `@ComponetScan("cn.aezo")` 定义需要扫描的包名,并将里面的`@Component`、`@Service`、`@Repository`、`@Controller`注解的类注册为Bean
    - `@Bean` 注解方法,表示当前方法的返回值是一个Bean,Bean的名称是方法名
    - 一般公共类使用java配置进行Bean声明,业务相关类使用注解进行Bean声明
- 调用

    ```java
       // ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
       ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); // AppConfig为定义的java配置类

       Hello hello = context.getBean("hello", Hello.class);
       hello.hello();
    ```

## 知识点

### AOP

- 相关注解
    - `@Aspect` 声明一个切面
    - `@Before`、`@After`、`@Around` 定义建言(advice)
- maven依赖

    ```xml
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId><!--不要也可测试成功-->
        <version>1.8.10</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.10</version>
    </dependency>
    ```
- 编写切面

    ```java
    @Aspect // 声明一个切面
    @Component
    public class LogAspect {
        // 法一:简单
        @Before("execution(* cn.aezo.spring.base.annotation.aop.DemoMethodService.*(..))")
        public void before(JoinPoint joinPoint) {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            System.out.println("方法规则式拦截[@Before-execution]:" + method.getName());
        }
    }
    ```
- 调用service

### Scope

- `@Scope("prototype")` 注解类(配置Bean的作用域)
    - `singleton` 整个容器共享一个实例(默认配置)
    - `prototype` 每次调用新建一个实例
    - `request` Web项目中,每一个Http Request新建一个实例
    - `session`
    - `globalSession` 用于portal应用

### EL(Spring-EL)

- `@Value` 在其中输入EL表达式。可对资源进行注入
- 实例

    ```java
    @Configuration
    @ComponentScan("cn.aezo.spring.base.annotation.el")
    @PropertySource("classpath:cn/aezo/spring/base/annotation/el/el.properties") // 注入配置文件
    public class ELConfig {
        @Value("I Love You")
        private String normal;

        @Value("#{systemProperties['os.name']}")
        private String osName;

        @Value("#{T(java.lang.Math).random() * 100.0}")
        private String randomNumber;

        @Value("${site.url}") // 读取配置文件(需要注入配置文件),使用$而不是#
        private Resource siteUrl;

        @Value("#{demoService.another}") // 读取其他类属性的@Value注解值
        private String fromAnother;

        @Value("classpath:cn/aezo/spring/base/annotation/el/test.txt")
        private Resource testFile;

        @Value("http://www.baidu.com")
        private Resource testUrl;

        @Autowired
        private Environment environment;

        // @Bean
        // public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
        //     return new PropertySourcesPlaceholderConfigurer();
        // }

        public void outputResource() {
            System.out.println("normal = " + normal);
            System.out.println("osName = " + osName);
            System.out.println("randomNumber = " + randomNumber);
            System.out.println("normal = " + siteUrl);
            System.out.println("fromAnother = " + fromAnother);
            System.out.println("environment = " + environment.getProperty("site.url"));

            try {
                System.out.println("testFile = " + IOUtils.toString(testFile.getInputStream(), "UTF-8"));
                System.out.println("testUrl = " + IOUtils.toString(testUrl.getInputStream(), "UTF-8"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    ```

### Profile

- 不同的环境读取不同的配置文件:`dev`/`prod`

### Application Event

- 事件:一个Bean(A)完成某个任务后,可以给另外一个Bean(B)发送事件,前提是B对A进行了监听
- 方法:
    - 继承`ApplicationEvent` 进行事件定义

        ```java
        public class DemoEvent extends ApplicationEvent {
            private String message;

            public DemoEvent(Object source, String message) {
                super(source);
                this.message = message;
            }

            public String getMessage() {
                return message;
            }

            public void setMessage(String message) {
                this.message = message;
            }
        }
        ```
    - 实现`ApplicationListener` 进行事件监听

        ```java
        @Component
        public class DemoListener implements ApplicationListener<DemoEvent> {
            @Override
            public void onApplicationEvent(DemoEvent demoEvent) {
                String message = demoEvent.getMessage();
                System.out.println("DemoListener.onApplicationEvent==" + message);
            }
        }
        ```
    - `applicationContext.publishEvent(new DemoEvent(this, message));` 发布事件

        ```java
        @Component
        public class DemoPublisher {
            @Autowired
            ApplicationContext applicationContext;

            public void publish(String message) {
                applicationContext.publishEvent(new DemoEvent(this, message));
            }
        }
        ```

### Spring Aware

- Spring依赖注入最大的亮点就是你所有的Bean对Spring容器的存在是无意识的。即你可以将容器换成其他容器,如Google Guice,这是Bean之间的耦合度很低。
- Spring Aware可以让你的Bean调用Spring提供的资源,缺点是Bean会和Spring框架耦合。
- 相关接口
    - `BeanNameAware` 获得容器中Bean的名称
    - `BeanFactoryAware` 获得当前Bean Factory,这样就有可以调用容器服务
    - `ApplicationContextAware` 获得当前Application Context,这样就有可以调用容器服务
    - `MessageSourceAware` 获得当前Message Source,可以获得文本信息
    - `ApplicationEventPublisherAware` 应用事件发布器,可以发布事件
    - `ResourceLoaderAware` 获得资源加载器,可以获取外部资源
- 实例

    ```java
    @Component
    public class AwareService implements BeanNameAware, ResourceLoaderAware {
        private String beanName;
        private ResourceLoader loader;

        @Override
        public void setBeanName(String s) {
            this.beanName = s;
        }

        @Override
        public void setResourceLoader(ResourceLoader resourceLoader) {
            this.loader = resourceLoader;
        }

        public void outputResult() {
            System.out.println("beanName = " + beanName);
            Resource resource = loader.getResource("classpath:cn/aezo/spring/base/annotation/springaware/test.txt");
            try {
                String test = IOUtils.toString(resource.getInputStream(), "UTF-8");
                System.out.println("test = " + test);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    ```

### 多线程

- Spring通过任务执行器(TaskExecutor)来实现多线程和并发编程。使用`ThreadPoolTaskExecutor`可实现一个基于线程池的TaskExecutor。
- `@EnableAsync` 可开启对异步任务的支持。需要对应的配置类实现
- `@Async` 注解执行异步任务的方法
- 示例

    ```java
    // 获取线程池
    @Configuration
    @ComponentScan("cn.aezo.spring.base.annotation.thread")
    @EnableAsync // 开启异步任务支持
    public class TaskExecutorConfig implements AsyncConfigurer {
        @Override
        public Executor getAsyncExecutor() {
            ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
            taskExecutor.setCorePoolSize(5);
            taskExecutor.setMaxPoolSize(10);
            taskExecutor.setQueueCapacity(25);
            taskExecutor.initialize();
            return taskExecutor;
        }

        @Override
        public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
            return null;
        }
    }

    // 定义异步方法
    @Service
    public class AsyncTaskService {
        @Async
        public void executeAsyncTask(Integer i) {
            System.out.println("i = " + i);
        }

        @Async
        public void executeAsyncTaskPlus(Integer i) {
            System.out.println("i+1 = " + (i+1));
        }
    }
    ```

### 计划任务

- `@EnableScheduling` 开启定时任务
- `@Scheduled` 执行任务的方法

    ```java
    @Configuration
    @ComponentScan("cn.aezo.spring.base.annotation.scheduled")
    @EnableScheduling
    public class TaskScheduledConfig {
    }

    @Service
    public class ScheduledTaskService {
        private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

        @Scheduled(fixedRate = 5000) // 5000毫秒. fixedRate每隔固定时间执行
        public void reportCurrentTime() {
            System.out.println("每隔5秒执行一次:" + dateFormat.format(new Date()));
        }

        @Scheduled(cron = "0 50 14 ? * *") // 每天14.50执行
        public void fixTimeException() {
            System.out.println("在指定时间执行:" + dateFormat.format(new Date()));
        }
    }
    ```

### 条件注解(Condition)

- `@Condition` 根据满足某一特定条件来创建某个特定的Bean. 如某个Bean创建后才会创建另一个Bean(Spring 4.x)
- 方法
    - 条件类实现`Condition`接口
    - 自定义服务接口,并有多种实现
    - 在`@Configuration`中`@Bean`的方法上注解`@Conditional(条件类.class)`表示符合此条件才会创建对应的Bean

### 组合注解、元注解

- 元注解是指可以注解到其他注解上的注解,被元注解注解之后的注解称之为组合注解
- 如`@Configuration`是包含`@Component`的组合注解,`@Component`为元注解
- 示例,将`@Configuration`和`@ComponentScan`组合成一个注解

    ```java
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Configuration
    @ComponentScan
    public @interface WiselyConfiguration {
        String[] value() default {};
    }
    ```


text:
package.path = "./conf/?.txt;" .. package.path
package.path = "./script/?.lua;" .. package.path
package.path = "./db/?.lua;" .. package.path
package.path = "./script/lib/?.lua;" .. package.path
package.cpath = "./script/lib/?.so;" .. package.cpath

io.stdout:setvbuf("line")

protobuf = require "protobuf"
parser = require "parser"

watchdog = require "watchdog"

require "config"
require "timer"
require "uri"
require "db"

parser.register("client.proto", "./proto/")

function dispatch(tsid, sid, uid, pname, data)
    watchdog.dispatch(tsid, sid, uid, pname, data)
end

function SendMsg(pname, msg, uids, tsid, sid)
    local p = string.format("%s%s", "proto.", pname)
    local _msg = protobuf.encode(p, msg)
    local uri = URI[p]
    GoSendMsg(uri, _msg, tsid, sid, uids)
end

function update()
    TimerUpdate()
end

function giftCb(op, sid, uid, touid, giftid, giftcout, orderid)
    watchdog.giftCb(op, sid, uid, touid, giftid, giftcout, orderid)
end

function netCtrl(s)
    watchdog.netCtrl(s)
end

----- POST
local post_sn = 1
local post_callbacks = {} -- sn = cb
function GoPostAsync(url, s, func)
    local sn = post_sn
    post_sn = post_sn + 1
    goPostAsync(url, s, sn)
    if func then
        post_callbacks[sn] = func
    end
end

function postDone(sn, ret)
    local cb = post_callbacks[sn]
    if cb then
        cb(ret)
        post_callbacks[sn] = cb
    end
end


text:
/**
 *
 * @author greg (at) myrobotlab.org
 *
 * This file is part of MyRobotLab (http://myrobotlab.org).
 *
 * MyRobotLab 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 (subject to the "Classpath" exception
 * as provided in the LICENSE.txt file that accompanied this code).
 *
 * MyRobotLab is distributed in the hope that it will be useful or fun,
 * 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.
 *
 * All libraries in thirdParty bundle are subject to their own license
 * requirements - please refer to http://myrobotlab.org/libraries for
 * details.
 *
 * Enjoy !
 *
 * */

/*
 * TODO - this service should be depricated and all functionality rolled into GUIService
 * such that one could dynamically create an new tabbed panel, video widget, etc... !
 */

package org.myrobotlab.control;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;

import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JTabbedPane;

import org.myrobotlab.image.SerializableImage;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.service.GUIService;
import org.myrobotlab.service.interfaces.VideoGUISource;
import org.slf4j.Logger;

public class GraphicsGUI extends ServiceGUI implements VideoGUISource {

	static final long serialVersionUID = 1L;
	public final static Logger log = LoggerFactory.getLogger(GraphicsGUI.class.toString());

	VideoWidget video = null;
	BufferedImage graph = null;
	Graphics g = null;

	public GraphicsGUI(final String boundServiceName, final GUIService myService, final JTabbedPane tabs) {
		super(boundServiceName, myService, tabs);
	}

	@Override
	public void attachGUI() {
		video.attachGUI();
		// subscribe(outMethod, inMethod, parameterType)
		myService.send(boundServiceName, "attach", (Object) myService.getName());
	}

	public void clearRect(Integer x, Integer y, Integer width, Integer height) {
		g.clearRect(x, y, width, height);
		// video.displayFrame(graph);
	}

	public void createGraph(Dimension d) {
		graph = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
		g = graph.getGraphics();
		video.displayFrame(new SerializableImage(graph, boundServiceName));
	}

	@Override
	public void detachGUI() {
		video.detachGUI();
		myService.send(boundServiceName, "detach");
	}

	// TODO - com....Sensor interface
	public void displayFrame(SerializableImage img) {
		video.displayFrame(img);
	}

	public void drawGrid(int width, int height) {
		for (int i = 0; i < graph.getHeight(); i += height) {
			g.drawLine(0, i, graph.getWidth(), i);
		}

		for (int i = 0; i < graph.getWidth(); i += width) {
			g.drawLine(i, 0, i, graph.getHeight());
		}

		Color old = g.getColor();
		g.setColor(Color.RED);

		// center - x y + heading degree
		// g.drawArc(300, 300, 10, 10, 0, 360);
		g.drawOval(295, 295, 10, 10); // cg.drawOval(xCenter-r, yCenter-r, 2*r,
										// 2*r);
		g.drawLine(300, 300, 300, 290); // polar to cart
		g.setColor(old);
	}

	// wrappers begin --------------------------
	public void drawLine(Integer x1, Integer y1, Integer x2, Integer y2) {
		g.drawLine(x1, y1, x2, y2);
		refreshDisplay();
		// video.displayFrame(graph);
	}

	public void drawRect(Integer x, Integer y, Integer width, Integer height) {
		g.drawRect(x, y, width, height);
		// video.displayFrame(graph);
	}

	public void drawString(String str, Integer x, Integer y) {
		g.drawString(str, x, y);
		// video.displayFrame(graph);
	}

	public void fillOval(Integer x, Integer y, Integer width, Integer height) {
		g.fillOval(x, y, width, height);
	}

	public void fillRect(Integer x, Integer y, Integer width, Integer height) {
		g.fillRect(x, y, width, height);
	}

	@Override
	public VideoWidget getLocalDisplay() {
		// TODO Auto-generated method stub
		return video;
	}

	@Override
	public void init() {

		JButton cg = new JButton("create graph");
		cg.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				myService.send(boundServiceName, "createGraph");
			}
		});

		video = new VideoWidget(boundServiceName, myService, tabs);
		video.init();
		display.add(cg);
		display.add(video.display, gc);

	}

	// wrappers end --------------------------

	// refresh display
	public void refreshDisplay() {
		video.displayFrame(new SerializableImage(graph, boundServiceName));
	}

	public void setColor(Color c) {
		g.setColor(c);
		// video.displayFrame(graph);
	}

	// TODO - encapsulate this
	// MouseListener mouseListener = new MouseAdapter() {
	public void setCurrentFilterMouseListener() {
		MouseListener mouseListener = new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent mouseEvent) {
				JList theList = (JList) mouseEvent.getSource();
				if (mouseEvent.getClickCount() == 2) {
					int index = theList.locationToIndex(mouseEvent.getPoint());
					if (index >= 0) {
						Object o = theList.getModel().getElementAt(index);
						System.out.println("Double-clicked on: " + o.toString());
					}
				}
			}
		};

		// traces.addMouseListener(mouseListener);
	}

}


text:
// <copyright file="ParallelExample.cs" company="Basho Technologies, Inc.">
// Copyright 2011 - OJ Reeves & Jeremiah Peschka
// Copyright 2014 - Basho Technologies, Inc.
//
// This file is provided to you 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.
// </copyright>

namespace RiakClientTests.Live.GeneralIntegrationTests
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Threading.Tasks;
    using NUnit.Framework;
    using RiakClient;
    using RiakClient.Config;
    using RiakClient.Models;

    [TestFixture, Example]
    public class ParallelExample : LiveRiakConnectionTestBase
    {
        [Test, Ignore("Example")]
        public void Parallel_ForEach_Can_Be_Used_To_Put_And_Get_Objects()
        {
            /* NB: this example assumes a 4-node devrel available
             * with localhost PB ports at 10017, 10027, 10037 and 10047 */
            const int numNodes = 4;
            const int poolSize = 8;
            const int totalConnectionCount = poolSize * numNodes;
            const ushort portInterval = 10;
            const ushort startingPort = 10017;
            const ushort endingPort = startingPort + ((numNodes - 1) * portInterval);
            const int totalObjects = 65536;

            byte[] data = new byte[65536];
            Random.NextBytes(data);

            int batchSize = totalConnectionCount;
            int totalBatches = totalObjects / batchSize;
            Assert.AreEqual(0, totalObjects % batchSize);
            Debug.WriteLine("batchSize: {0}, totalBatches: {1}", batchSize, totalBatches);

            string riakHost = Environment.GetEnvironmentVariable("RIAK_HOST");
            if (String.IsNullOrWhiteSpace(riakHost))
            {
                riakHost = "riak-test";
            }

            Debug.WriteLine("Riak host: {0}", riakHost);

            Assert.AreEqual(10047, endingPort);

            var objs = new List<RiakObject>();
            for (int i = 0; i < totalObjects; i++)
            {
                var key = String.Format("{0}_{1}", TestKey, i);
                var id = new RiakObjectId(TestBucket, key);
                var obj = new RiakObject(id, data, RiakConstants.ContentTypes.ApplicationOctetStream, null);
                objs.Add(obj);
            }

            IRiakClusterConfiguration clusterConfig = new RiakClusterConfiguration();

            for (ushort port = startingPort; port <= endingPort; port += portInterval)
            {
                IRiakNodeConfiguration nc = new RiakNodeConfiguration();
                nc.PoolSize = poolSize;
                nc.HostAddress = riakHost;
                nc.PbcPort = port;
                nc.Name = String.Format("dev_{0}", port);
                clusterConfig.AddNode(nc);
            }

            var batchObjs = new RiakObject[batchSize];
            var p = new int[] { 1, batchSize };

            foreach (int parallelism in p)
            {
                var parallelOptions = new ParallelOptions();
                parallelOptions.MaxDegreeOfParallelism = parallelism;

                using (var cluster = new RiakCluster(clusterConfig))
                {
                    var client = cluster.CreateClient();

                    var sw = new Stopwatch();
                    sw.Start();

                    for (int i = 0; i < totalObjects; i += batchSize)
                    {
                        objs.CopyTo(i, batchObjs, 0, batchSize);
                        Parallel.ForEach(batchObjs, parallelOptions, (obj) =>
                        {
                            try
                            {
                                client.Put(obj);
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine("[ERROR] put exception: {0}", e.ToString());
                            }
                        });
                    }

                    sw.Stop();
                    Debug.WriteLine("parallelism: {0} - put {1} objects in {2}", parallelism, totalObjects, sw.Elapsed);

                    sw.Reset();

                    sw.Start();
                    for (int i = 0; i < totalObjects; i += batchSize)
                    {
                        objs.CopyTo(i, batchObjs, 0, batchSize);
                        Parallel.ForEach(batchObjs, parallelOptions, (obj) =>
                        {
                            try
                            {
                                var id = new RiakObjectId(obj.Bucket, obj.Key);
                                client.Get(id);
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine("[ERROR] put exception: {0}", e.ToString());
                            }
                        });
                    }

                    sw.Stop();
                    Debug.WriteLine("parallelism: {0} - fetched {1} objects in {2}", parallelism, totalObjects, sw.Elapsed);
                }
            }
        }
    }
}


text:
package org.arquillian.extension.governor.api;

import java.lang.annotation.Annotation;
import java.util.Map;

/**
 * Intefrace <tt>ClosePassedDecider</tt> gives us information if we can close issues defined in governor annotations.
 *
 * @author Martin Basovnik
 */
public interface ClosePassedDecider {

    /**
     * Returns {@code Map} with annotations and their closable flags in the scope of the whole test suite.
     *
     * @return {@code Map} with annotations and their closable flags.
     */
    Map<Annotation, Boolean> get();

    /**
     * Sets the closable flag to the issue specified in {@code annotation} in the scope of related test method.
     *
     * @param annotation Governor annotation.
     * @param closeable  if {@code true}, the issue specified in annotation can be closed.
     */
    void setClosable(Annotation annotation, boolean closeable);

    /**
     * Returns {@code true} if the issue specified in {@code annotation} can be closed in the scope of the whole test suite.
     *
     * @param annotation Governor annotation.
     * @return {@code true} if the issue specified in annotation can be closed, otherwise {@code false}.
     */
    boolean isCloseable(Annotation annotation);
}


text:
<?php

use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use kartik\widgets\ActiveForm;
use kartik\widgets\FileInput;

/* @var $this yii\web\View */
/* @var $model common\models\Topic */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(['options' => ['class' => 'form-horizontal','enctype'=>'multipart/form-data']]); ?>
    <?php echo $form->field($messageForm, 'topicId')->hiddenInput(['value'=>$messageForm->topicId])->label(false) ?>
    <?php echo $form->field($messageForm, 'userId')->hiddenInput(['value'=>$messageForm->userId])->label(false) ?>
    <?php echo $form->field($messageForm, 'message_to')->hiddenInput(['value'=>$messageForm->message_to])->label(false) ?>
    <div class="form-group"
        Reply

    <?php echo $form->field($messageForm, 'content')->textArea(['rows' => '6','placeholder' => 'Write your message here'])->label(false) ?>
    <?php echo $form->field($messageForm, 'attach_file')->widget(FileInput::classname(), [
                'options' => ['accept' => 'image/*','showUpload' => false,],
            ]);
    ?>

       <?= Html::submitButton('Send', ['class' => 'btn btn-primary pull-right']) ?>

    <?php ActiveForm::end(); ?>


text:
package org.assertj.core.api;

import static org.assertj.core.api.Assertions.assertThat;

import java.lang.reflect.Method;

import org.junit.jupiter.api.Test;

/**
 * @author Filip Hrisafov
 */
@SuppressWarnings("deprecation")
public class Java6Assertions_sync_assertThat_with_BDD_and_Soft_variants_Test extends BaseAssertionsTest {

  @Test
  public void standard_assertions_and_bdd_assertions_should_have_the_same_assertions_methods() {
    Method[] assertThatMethods = findMethodsWithName(Java6Assertions.class, "assertThat");
    Method[] thenMethods = findMethodsWithName(Java6BDDAssertions.class, "then");

    assertThat(assertThatMethods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_METHOD_NAME)
                                 .containsExactlyInAnyOrder(thenMethods);
  }

  @Test
  public void standard_assertions_and_soft_assertions_should_have_the_same_assertions_methods() {
    // Until the SpecialIgnoredReturnTypes like AssertProvider, XXXNavigableXXXAssert are implemented for
    // the soft assertions we need to ignore them
    Method[] assertThatMethods = findMethodsWithName(Java6Assertions.class, "assertThat", SPECIAL_IGNORED_RETURN_TYPES);
    Method[] assertThatSoftMethods = findMethodsWithName(Java6AbstractStandardSoftAssertions.class, "assertThat");

    // ignore the return type of soft assertions until they have the same as the Assertions
    assertThat(assertThatMethods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_RETURN_TYPE)
                                 .containsExactlyInAnyOrder(assertThatSoftMethods);

  }

  @Test
  public void bdd_assertions_and_bdd_soft_assertions_should_have_the_same_assertions_methods() {
    // Until the SpecialIgnoredReturnTypes like AssertProvider, XXXNavigableXXXAssert are implemented for
    // the soft assertions we need to ignore them
    Method[] thenMethods = findMethodsWithName(Java6BDDAssertions.class, "then", SPECIAL_IGNORED_RETURN_TYPES);
    Method[] thenSoftMethods = findMethodsWithName(Java6AbstractBDDSoftAssertions.class, "then");

    // ignore the return type of soft assertions until they have the same as the Assertions
    assertThat(thenMethods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_RETURN_TYPE)
                           .containsExactlyInAnyOrder(thenSoftMethods);

  }
}


text:
SwiftRandom
==============

[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/SwiftRandom.svg)](https://img.shields.io/cocoapods/v/SwiftRandom.svg)

SwiftRandom is a tiny help suite for generating random data such as
* Random human stuff like: names, gender, titles, tags, conversations
* Random data types like: Int, CGFloat, Bool, UIColor, NSDate, NSURL, element in Array

## Usage

```swift
func asExtension() {
	Int.random(2, 77) // Random between 2-77
	Int.random(2...77)
	Int32.random(13, 37) // Random between 13-37
	Int32.random(13...37)
	Double.random()
	Float.random(3.2, 4.5) // Random between 3.2-4.5
	CGFloat.random()
	NSDate.random()
	NSDate.randomWithinDaysBeforeToday(7)
	UIColor.random()
	NSURL.random()

	// Array Extensions
	var someArray = ["hello", "world"]
	someArray[0..<someArray.count].randomItem() // Array slice
	someArray.randomItem()
}
```

```swift
func asMethods() {
	// Return random Int >= 10 and <= 20
	// Example Output: 13
	Randoms.randomInt(10,20)

	// Return random Int32 >= 10 and <= 20
	// Example Output: 13
	Randoms.randomInt32(10,20)

	// Return random Double >= 10 and <= 20
	// Example Output: 11.511219042938
	Randoms.randomDouble(10,20)

	// Return random Float >= 10 and <= 20
	// Example Output: 17.0361
	Randoms.randomFloat(10,20)

	// Return random CGFloat between 1 >= and >= 0
	// Example Output: 0.622616
	Randoms.randomCGFloat()

	// Return true 30%, false %70
	// Example Output: false
	Randoms.randomPercentageisOver(70)

	// Return true or false
	// Example Output: false
	Randoms.randomBool()

	// Return random NSDate today > and > today - 7.
	// Example Output: 2015-10-08 03:55:09 +0000
	Randoms.randomDateWithinDaysBeforeToday(7)

	// Random Date since 1970
	// Example Output: 1997-02-01 15:27:08 +0000
	Randoms.randomDate()

	// Return UIColor. Alpha channel always 1.
	// Example Output: UIDeviceRGBColorSpace 0.645737 0.126625 0.52535 1
	Randoms.randomColor()

	// Return random NSURL
	// Example Output: http://leagueoflegends.com/
	Randoms.randomNSURL()

	// ==================== Fake Generators for Fake Datasources ==================== //

	// Return random name
	// Example Output: "Megan Freeman"
	Randoms.randomFakeName()

	// Return random fake name prefixed by English honorific
	// Example Output: "Dr. Megan Freeman"
	Randoms.randomFakeNameAndEnglishHonorific()

	// Return "Male" or "Female" as String
	// Example Output: "Female"
	Randoms.randomFakeGender()

	// Return random conversation
	// Example Output: "No! I'm tired of doing what you say."
	Randoms.randomFakeConversation()

	// Return random title
	// Example Output: "B2 Pilot @ USAF"
	Randoms.randomFakeTitle()

	// Return random tag as string
	// Example Output: "question"
	Randoms.randomFakeTag()

	// Return random currency as String
	// Example Output: "EUR"
	Randoms.randomCurrency()

	// Return random (non-existing) gravatar as UIImage?
	// The image is optional in case of network issues
	Randoms.randomGravatar { (image, error) -> Void in
		// Handle the image/error
	}

	// For consistance behaviour you can create custom Gravatar
	Randoms.createGravatar(Randoms.GravatarStyle.Retro) { (image, error) -> Void in
		// Handle the image/error
	}
}

```

###Requirements

- Swift version 2.0

## Installation

### Install via Carthage

* Create a `Cartfile` with the following specification and run `carthage update`.

```
github "thellimist/SwiftRandom" >= 1.0.0
```

* Follow the [instructions](https://github.com/Carthage/Carthage#if-youre-building-for-ios) to add the framework to an iOS project.

### Install via CocoaPods

You can use [CocoaPods](http://cocoapods.org/) to install `SwiftRandom` by adding it to your `Podfile`:
```ruby
platform :ios, '8.0'
use_frameworks!
pod  'SwiftRandom' #Stable release for Swift 3.0
```

To download older version you can use
```
pod 'SwiftRandom', :git => 'https://github.com/thellimist/SwiftRandom.git' #Latest release for Swift 3.0
pod 'SwiftRandom', :git => 'https://github.com/thellimist/SwiftRandom.git', :branch => '2.x' #For Swift 2.3

```

### Install Manually

- Download and drop 'Randoms.swift' in your project.

###Improvement
- Feel free adding your own random data functions and sending pull requests.

#####Possible features:
- Random wildlife pictures (Should not include the image inside project, should load it from web when needed)
- Make OSX compatiable and add here: https://github.com/AndrewSB/awesome-osx
- Random JSON
- Random Gifs (Should not include gifs inside the project, should load it from web when needed)
- Random Videos (Should not include videos inside the project, should load it from web when needed)
- Implement `SwiftRandom` as a protocol any class can conform to (`Post.random()` would give you a random post)

###License
- SwiftRandom is available under the MIT license. See the [LICENSE file](https://github.com/thellimist/SwiftRandom/blob/master/LICENSE).

##Keywords
random, swift, data, generator, faker, fake, gravatar