text:
// Copyright 2022 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

#include "iree/modules/hal/loader/module.h"

#include "iree/base/api.h"
#include "iree/base/tracing.h"
#include "iree/hal/api.h"
#include "iree/hal/local/local_executable.h"
#include "iree/vm/api.h"

#define IREE_HAL_LOADER_MODULE_VERSION_0_0 0x00000000u
#define IREE_HAL_LOADER_MODULE_VERSION_LATEST IREE_HAL_LOADER_MODULE_VERSION_0_0

//===----------------------------------------------------------------------===//
// Module type definitions
//===----------------------------------------------------------------------===//

typedef struct iree_hal_loader_module_t {
  iree_allocator_t host_allocator;
  iree_hal_loader_module_flags_t flags;
  // TODO(benvanik): types.
  iree_host_size_t loader_count;
  iree_hal_executable_loader_t* loaders[];
} iree_hal_loader_module_t;

#define IREE_HAL_LOADER_MODULE_CAST(module)        \
  (iree_hal_loader_module_t*)((uint8_t*)(module) + \
                              iree_vm_native_module_size());

typedef struct iree_hal_loader_module_state_t {
  iree_allocator_t host_allocator;
  iree_hal_loader_module_flags_t flags;
} iree_hal_loader_module_state_t;

static void IREE_API_PTR iree_hal_loader_module_destroy(void* base_module) {
  iree_hal_loader_module_t* module = IREE_HAL_LOADER_MODULE_CAST(base_module);
  for (iree_host_size_t i = 0; i < module->loader_count; ++i) {
    iree_hal_executable_loader_release(module->loaders[i]);
  }
}

static iree_status_t IREE_API_PTR
iree_hal_loader_module_alloc_state(void* self, iree_allocator_t host_allocator,
                                   iree_vm_module_state_t** out_module_state) {
  IREE_TRACE_ZONE_BEGIN(z0);

  iree_hal_loader_module_t* module = IREE_HAL_LOADER_MODULE_CAST(self);
  iree_hal_loader_module_state_t* state = NULL;
  IREE_RETURN_AND_END_ZONE_IF_ERROR(
      z0,
      iree_allocator_malloc(host_allocator, sizeof(*state), (void**)&state));
  memset(state, 0, sizeof(*state));
  state->host_allocator = host_allocator;
  state->flags = module->flags;

  *out_module_state = (iree_vm_module_state_t*)state;
  IREE_TRACE_ZONE_END(z0);
  return iree_ok_status();
}

static void IREE_API_PTR iree_hal_loader_module_free_state(
    void* self, iree_vm_module_state_t* module_state) {
  IREE_TRACE_ZONE_BEGIN(z0);

  iree_hal_loader_module_state_t* state =
      (iree_hal_loader_module_state_t*)module_state;
  iree_allocator_free(state->host_allocator, state);

  IREE_TRACE_ZONE_END(z0);
}

static iree_status_t IREE_API_PTR iree_hal_loader_module_notify(
    void* self, iree_vm_module_state_t* module_state, iree_vm_signal_t signal) {
  switch (signal) {
    case IREE_VM_SIGNAL_SUSPEND:
    case IREE_VM_SIGNAL_LOW_MEMORY:
    default:
      return iree_ok_status();
  }
}

//===----------------------------------------------------------------------===//
// Utilities
//===----------------------------------------------------------------------===//

// Casts a VM value to a C host size.
static iree_host_size_t iree_hal_cast_host_size(int64_t value) {
  // TODO(benvanik): make this return status and check for overflow if host
  // size is 32-bits.
  return (iree_host_size_t)value;
}

// Casts a VM value to a HAL device size.
static iree_device_size_t iree_hal_cast_device_size(int64_t value) {
  // TODO(benvanik): make this return status and check for overflow if device
  // size is 32-bits.
  return (iree_device_size_t)value;
}

//===----------------------------------------------------------------------===//
// Shared argument shims
//===----------------------------------------------------------------------===//

#define IREE_HAL_ABI_EXPORT(function_name, arg_types, ret_types)               \
  IREE_VM_ABI_EXPORT(function_name, iree_hal_loader_module_state_t, arg_types, \
                     ret_types)
#define IREE_HAL_ABI_FIXED_STRUCT(name, types, body) \
  IREE_VM_ABI_FIXED_STRUCT(name, body)
#define IREE_HAL_ABI_DEFINE_SHIM(arg_types, ret_types) \
  static IREE_VM_ABI_DEFINE_SHIM(arg_types, ret_types)

//===----------------------------------------------------------------------===//
// iree_hal_executable_t
//===----------------------------------------------------------------------===//

IREE_HAL_ABI_EXPORT(iree_hal_loader_module_executable_query_support,  //
                    r, i) {
  iree_vm_buffer_t* executable_format = NULL;
  IREE_RETURN_IF_ERROR(
      iree_vm_buffer_check_deref(args->r0, &executable_format));
  iree_string_view_t executable_format_str =
      iree_vm_buffer_as_string(executable_format);

  bool has_support = false;
  iree_hal_loader_module_t* loader_module = IREE_HAL_LOADER_MODULE_CAST(module);
  for (iree_host_size_t i = 0; i < loader_module->loader_count; ++i) {
    iree_hal_executable_loader_t* loader = loader_module->loaders[i];
    if (iree_hal_executable_loader_query_support(loader, 0,
                                                 executable_format_str)) {
      has_support = true;
      break;
    }
  }

  rets->i0 = has_support ? 1 : 0;
  return iree_ok_status();
}

static iree_status_t iree_hal_loader_module_try_load(
    iree_hal_loader_module_t* loader_module,
    const iree_hal_executable_params_t* executable_params,
    iree_hal_executable_t** out_executable) {
  for (iree_host_size_t i = 0; i < loader_module->loader_count; ++i) {
    iree_hal_executable_loader_t* loader = loader_module->loaders[i];
    if (!iree_hal_executable_loader_query_support(
            loader, executable_params->caching_mode,
            executable_params->executable_format)) {
      // Loader definitely can't handle the executable; no use trying so skip.
      continue;
    }
    // The loader _may_ handle the executable; if the specific executable is not
    // supported then the try will fail with IREE_STATUS_CANCELLED and we should
    // continue trying other loaders.
    iree_status_t status = iree_hal_executable_loader_try_load(
        loader, executable_params, /*worker_capacity=*/1, out_executable);
    if (iree_status_is_ok(status)) {
      // Executable was successfully loaded.
      return status;
    } else if (!iree_status_is_cancelled(status)) {
      // Error beyond just the try failing due to unsupported formats.
      return status;
    }
    iree_status_ignore(status);
  }
  return iree_make_status(
      IREE_STATUS_NOT_FOUND,
      "no executable loader registered for the given executable format '%.*s'",
      (int)executable_params->executable_format.size,
      executable_params->executable_format.data);
}

IREE_HAL_ABI_EXPORT(iree_hal_loader_module_executable_load,  //
                    rrr, r) {
  iree_vm_buffer_t* executable_format = NULL;
  IREE_RETURN_IF_ERROR(
      iree_vm_buffer_check_deref(args->r0, &executable_format));
  iree_string_view_t executable_format_str =
      iree_vm_buffer_as_string(executable_format);
  iree_vm_buffer_t* executable_data = NULL;
  IREE_RETURN_IF_ERROR(iree_vm_buffer_check_deref(args->r1, &executable_data));
  iree_host_size_t constant_count = 0;
  const uint32_t* constants = NULL;
  if (iree_vm_buffer_isa(args->r2)) {
    iree_vm_buffer_t* constant_buffer = NULL;
    IREE_RETURN_IF_ERROR(
        iree_vm_buffer_check_deref(args->r2, &constant_buffer));
    if (constant_buffer->data.data_length % 4 != 0) {
      return iree_make_status(IREE_STATUS_INVALID_ARGUMENT,
                              "constant buffer data must contain 4-byte "
                              "elements but data length is %" PRIhsz,
                              constant_buffer->data.data_length);
    }
    constant_count = constant_buffer->data.data_length / sizeof(uint32_t);
    constants = (const uint32_t*)constant_buffer->data.data;
  }

  iree_hal_executable_params_t executable_params;
  iree_hal_executable_params_initialize(&executable_params);
  executable_params.caching_mode |=
      executable_data->access == IREE_VM_BUFFER_ACCESS_ORIGIN_MODULE
          ? IREE_HAL_EXECUTABLE_CACHING_MODE_ALIAS_PROVIDED_DATA
          : 0;
  executable_params.executable_format = executable_format_str;
  executable_params.executable_data = iree_make_const_byte_span(
      executable_data->data.data, executable_data->data.data_length);
  executable_params.pipeline_layout_count = 0;
  executable_params.pipeline_layouts = NULL;
  executable_params.constant_count = constant_count;
  executable_params.constants = constants;

  iree_hal_executable_t* executable = NULL;
  iree_hal_loader_module_t* loader_module = IREE_HAL_LOADER_MODULE_CAST(module);
  iree_status_t status = iree_hal_loader_module_try_load(
      loader_module, &executable_params, &executable);

  rets->r0 = iree_hal_executable_move_ref(executable);
  return status;
}

typedef struct {
  union {
    struct {
      iree_vm_ref_t executable;
      int32_t entry_point;
      int32_t workgroup_x;
      int32_t workgroup_y;
      int32_t workgroup_z;
    };
    iree_vm_abi_riiii_t params;
  };
  iree_vm_size_t push_constant_count;
  const uint32_t* push_constants;
  iree_vm_size_t binding_count;
  const iree_vm_abi_rII_t* bindings;
} iree_hal_loader_dispatch_args_t;

static iree_status_t iree_hal_loader_module_executable_dispatch(
    iree_vm_stack_t* IREE_RESTRICT stack, void* IREE_RESTRICT module,
    iree_hal_loader_module_state_t* IREE_RESTRICT state,
    const iree_hal_loader_dispatch_args_t* IREE_RESTRICT args) {
  iree_hal_executable_t* executable = NULL;
  IREE_RETURN_IF_ERROR(
      iree_hal_executable_check_deref(args->executable, &executable));

  if (args->binding_count > 32) {
    return iree_make_status(IREE_STATUS_RESOURCE_EXHAUSTED,
                            "too many bindings");
  }
  void** binding_ptrs =
      (void**)iree_alloca(args->binding_count * sizeof(void*));
  size_t* binding_lengths =
      (size_t*)iree_alloca(args->binding_count * sizeof(size_t));
  for (iree_host_size_t i = 0; i < args->binding_count; ++i) {
    iree_vm_buffer_t* buffer = NULL;
    IREE_RETURN_IF_ERROR(
        iree_vm_buffer_check_deref(args->bindings[i].r0, &buffer));
    // TODO(benvanik): this is a hack around not having the access permissions
    // currently modeled. This is only used for verification and early errors
    // and not intended to be a last-line defense against writes (you need an
    // MMU for that) so it's just subpar reporting.
    iree_const_byte_span_t span;
    IREE_RETURN_IF_ERROR(iree_vm_buffer_map_ro(
        buffer, iree_hal_cast_host_size(args->bindings[i].i1),
        iree_hal_cast_host_size(args->bindings[i].i2), /*alignment=*/1, &span));
    binding_ptrs[i] = (void*)span.data;
    binding_lengths[i] = span.data_length;
  }

  const iree_hal_executable_dispatch_state_v0_t dispatch_state = {
      .workgroup_size_x = 1,
      .workgroup_size_y = 1,
      .workgroup_size_z = 1,
      .push_constant_count = args->push_constant_count,
      .workgroup_count_x = args->workgroup_x,
      .workgroup_count_y = args->workgroup_y,
      .workgroup_count_z = args->workgroup_z,
      .max_concurrency = 1,
      .binding_count = args->binding_count,
      .push_constants = args->push_constants,
      .binding_ptrs = binding_ptrs,
      .binding_lengths = binding_lengths,
  };

  // TODO(benvanik): environmental information.
  uint32_t processor_id = 0;
  iree_byte_span_t local_memory = iree_byte_span_empty();

  return iree_hal_local_executable_issue_dispatch_inline(
      (iree_hal_local_executable_t*)executable, args->entry_point,
      &dispatch_state, processor_id, local_memory);
}

static iree_status_t iree_vm_shim_dispatch_v(
    iree_vm_stack_t* IREE_RESTRICT stack, iree_vm_native_function_flags_t flags,
    iree_byte_span_t args_storage, iree_byte_span_t rets_storage,
    iree_vm_native_function_target2_t target_fn, void* IREE_RESTRICT module,
    void* IREE_RESTRICT module_state) {
  // TODO(benvanik): support multiple variadic segments in one call.
  // For now we inline what it would do in a very painful way.
  bool args_ok = true;
  if (args_storage.data_length <
      (sizeof(iree_vm_abi_riiii_t) + sizeof(iree_vm_size_t) +
       sizeof(iree_vm_size_t))) {
    // Can't fit even with zero lengths.
    args_ok = false;
  }
  iree_hal_loader_dispatch_args_t args = {
      .params = *(const iree_vm_abi_riiii_t*)args_storage.data,
  };
  if (args_ok) {
    const uint8_t* push_constants_ptr = args_storage.data + sizeof(args.params);
    args.push_constant_count = *(const iree_vm_size_t*)push_constants_ptr;
    args.push_constants =
        (const uint32_t*)(push_constants_ptr + sizeof(iree_vm_size_t));
    const uint8_t* bindings_ptr =
        push_constants_ptr + sizeof(iree_vm_size_t) +
        args.push_constant_count * sizeof(args.push_constants[0]);
    args.binding_count = *(const iree_vm_size_t*)bindings_ptr;
    args.bindings =
        (const iree_vm_abi_rII_t*)(bindings_ptr + sizeof(iree_vm_size_t));
    const uint8_t* max_ptr = (const uint8_t*)args.bindings +
                             args.binding_count * sizeof(args.bindings[0]);
    const uint8_t* end_ptr = args_storage.data + args_storage.data_length;
    if (max_ptr > end_ptr) args_ok = false;
  }
  if (IREE_UNLIKELY(!args_ok || rets_storage.data_length > 0)) {
    return iree_make_status(IREE_STATUS_INVALID_ARGUMENT,
                            "argument/result signature mismatch");
  }
  return iree_hal_loader_module_executable_dispatch(stack, module, module_state,
                                                    &args);
}

//===----------------------------------------------------------------------===//
// VM module interface implementation
//===----------------------------------------------------------------------===//

// NOTE: this must match the ordering of the iree_hal_loader_module_exports_
// table.
static const iree_vm_native_function_ptr_t iree_hal_loader_module_funcs_[] = {
#define EXPORT_FN(name, target_fn, shim_arg_type, arg_types, ret_types) \
  {                                                                     \
      .shim = (iree_vm_native_function_shim_t)                          \
          iree_vm_shim_##shim_arg_type##_##ret_types,                   \
      .target = (iree_vm_native_function_target_t)(target_fn),          \
  },
#include "iree/modules/hal/loader/exports.inl"  // IWYU pragma: keep
#undef EXPORT_FN
};

// NOTE: 0 length, but can't express that in C.
static const iree_vm_native_import_descriptor_t
    iree_hal_loader_module_imports_[1];

static const iree_vm_native_export_descriptor_t
    iree_hal_loader_module_exports_[] = {
#define EXPORT_FN(name, target_fn, shim_arg_type, arg_types, ret_types) \
  {                                                                     \
      .local_name = iree_string_view_literal(name),                     \
      .calling_convention =                                             \
          iree_string_view_literal("0" #arg_types "_" #ret_types),      \
      .attr_count = 0,                                                  \
      .attrs = NULL,                                                    \
  },
#include "iree/modules/hal/loader/exports.inl"  // IWYU pragma: keep
#undef EXPORT_FN
};
static_assert(IREE_ARRAYSIZE(iree_hal_loader_module_funcs_) ==
                  IREE_ARRAYSIZE(iree_hal_loader_module_exports_),
              "function pointer table must be 1:1 with exports");

static const iree_vm_native_module_descriptor_t
    iree_hal_loader_module_descriptor_ = {
        .name = iree_string_view_literal("hal_loader"),
        .version = IREE_HAL_LOADER_MODULE_VERSION_LATEST,
        .attr_count = 0,
        .attrs = NULL,
        .dependency_count = 0,
        .dependencies = NULL,
        .import_count = 0,  // workaround for 0-length C struct
        .imports = iree_hal_loader_module_imports_,
        .export_count = IREE_ARRAYSIZE(iree_hal_loader_module_exports_),
        .exports = iree_hal_loader_module_exports_,
        .function_count = IREE_ARRAYSIZE(iree_hal_loader_module_funcs_),
        .functions = iree_hal_loader_module_funcs_,
};

IREE_API_EXPORT iree_status_t iree_hal_loader_module_create(
    iree_vm_instance_t* instance, iree_hal_loader_module_flags_t flags,
    iree_host_size_t loader_count, iree_hal_executable_loader_t** loaders,
    iree_allocator_t host_allocator, iree_vm_module_t** out_module) {
  IREE_ASSERT_ARGUMENT(instance);
  IREE_ASSERT_ARGUMENT(out_module);
  *out_module = NULL;

  // Setup the interface with the functions we implement ourselves. Any function
  // we omit will be handled by the base native module.
  static const iree_vm_module_t interface = {
      .destroy = iree_hal_loader_module_destroy,
      .alloc_state = iree_hal_loader_module_alloc_state,
      .free_state = iree_hal_loader_module_free_state,
      .notify = iree_hal_loader_module_notify,
  };

  // Allocate shared module state.
  iree_host_size_t total_size =
      iree_vm_native_module_size() + sizeof(iree_hal_loader_module_t) +
      loader_count * sizeof(iree_hal_executable_loader_t*);
  iree_vm_module_t* base_module = NULL;
  IREE_RETURN_IF_ERROR(
      iree_allocator_malloc(host_allocator, total_size, (void**)&base_module));
  memset(base_module, 0, total_size);
  iree_status_t status = iree_vm_native_module_initialize(
      &interface, &iree_hal_loader_module_descriptor_, instance, host_allocator,
      base_module);
  if (!iree_status_is_ok(status)) {
    iree_allocator_free(host_allocator, base_module);
    return status;
  }

  iree_hal_loader_module_t* module = IREE_HAL_LOADER_MODULE_CAST(base_module);
  module->host_allocator = host_allocator;
  module->flags = flags;
  module->loader_count = loader_count;
  for (iree_host_size_t i = 0; i < loader_count; ++i) {
    module->loaders[i] = loaders[i];
    iree_hal_executable_loader_retain(loaders[i]);
  }

  *out_module = base_module;
  return iree_ok_status();
}


text:
package com.plivo.api.models.recording;

import com.plivo.api.models.base.VoiceGetter;
import retrofit2.Call;

public class RecordingGetter extends VoiceGetter<Recording> {

  public RecordingGetter(String id) {
    super(id);
  }

  @Override
  protected Call<Recording> obtainCall() {
    return client().getVoiceApiService().recordingGet(client().getAuthId(), id);
  }

  @Override
  protected Call<Recording> obtainFallback1Call() {
    return client().getVoiceFallback1Service().recordingGet(client().getAuthId(), id);
  }

  @Override
  protected Call<Recording> obtainFallback2Call() {
    return client().getVoiceFallback2Service().recordingGet(client().getAuthId(), id);
  }
}

redpajama_set_name: RedPajamaGithub


text:
param($installPath, $toolsPath, $package, $project)

$analyzersPaths = Join-Path (Join-Path (Split-Path -Path $toolsPath -Parent) "analyzers" ) * -Resolve

foreach($analyzersPath in $analyzersPaths)
{
    # Install the language agnostic analyzers.
    if (Test-Path $analyzersPath)
    {
        foreach ($analyzerFilePath in Get-ChildItem $analyzersPath -Filter *.dll)
        {
            if($project.Object.AnalyzerReferences)
            {
                $project.Object.AnalyzerReferences.Add($analyzerFilePath.FullName)
            }
        }
    }
}

$project.Type # gives the language name like (C# or VB.NET)
$languageFolder = ""
if($project.Type -eq "C#")
{
    $languageFolder = "cs"
}
if($project.Type -eq "VB.NET")
{
    $languageFolder = "vb"
}
if($languageFolder -eq "")
{
    return
}

foreach($analyzersPath in $analyzersPaths)
{
    # Install language specific analyzers.
    $languageAnalyzersPath = join-path $analyzersPath $languageFolder
    if (Test-Path $languageAnalyzersPath)
    {
        foreach ($analyzerFilePath in Get-ChildItem $languageAnalyzersPath -Filter *.dll)
        {
            if($project.Object.AnalyzerReferences)
            {
                $project.Object.AnalyzerReferences.Add($analyzerFilePath.FullName)
            }
        }
    }
}


text:
namespace remoting {

NormalizingInputFilterMac::NormalizingInputFilterMac(
    protocol::InputStub* input_stub)
    : protocol::InputFilter(input_stub) {}

NormalizingInputFilterMac::~NormalizingInputFilterMac() = default;

void NormalizingInputFilterMac::InjectKeyEvent(
    const protocol::KeyEvent& event_arg) {
  DCHECK(event_arg.has_usb_keycode());

  // Mac OS X doesn't have a concept of num lock, so unset the field.
  protocol::KeyEvent event(event_arg);
  event.clear_num_lock_state();

  ui::DomCode dom_code = static_cast<ui::DomCode>(event.usb_keycode());

  bool is_special_key = dom_code == ui::DomCode::CONTROL_LEFT ||
                        dom_code == ui::DomCode::SHIFT_LEFT ||
                        dom_code == ui::DomCode::ALT_LEFT ||
                        dom_code == ui::DomCode::CONTROL_RIGHT ||
                        dom_code == ui::DomCode::SHIFT_RIGHT ||
                        dom_code == ui::DomCode::ALT_RIGHT ||
                        dom_code == ui::DomCode::TAB;

  bool is_cmd_key =
      dom_code == ui::DomCode::META_LEFT || dom_code == ui::DomCode::META_RIGHT;

  if (dom_code == ui::DomCode::CAPS_LOCK) {
    // Mac OS X generates keydown/keyup on lock-state transitions, rather than
    // when the key is pressed & released, so fake keydown/keyup on each event.
    protocol::KeyEvent newEvent(event);

    newEvent.set_pressed(true);
    InputFilter::InjectKeyEvent(newEvent);
    newEvent.set_pressed(false);
    InputFilter::InjectKeyEvent(newEvent);

    return;
  } else if (!is_cmd_key && !is_special_key) {
    // Track keydown/keyup events for non-modifiers, so we can release them if
    // necessary (see below).
    if (event.pressed()) {
      key_pressed_map_[event.usb_keycode()] = event;
    } else {
      key_pressed_map_.erase(event.usb_keycode());
    }
  }

  if (is_cmd_key && !event.pressed()) {
    // Mac OS X will not generate release events for keys pressed while Cmd is
    // pressed, so release all pressed keys when Cmd is released.
    GenerateKeyupEvents();
  }

  InputFilter::InjectKeyEvent(event);
}

void NormalizingInputFilterMac::GenerateKeyupEvents() {
  for (auto i = key_pressed_map_.begin(); i != key_pressed_map_.end(); ++i) {
    // The generated key up event will have the same key code and lock states
    // as the original key down event.
    protocol::KeyEvent event = i->second;
    event.set_pressed(false);
    InputFilter::InjectKeyEvent(event);
  }

  // Clearing the map now that we have released all the pressed keys.
  key_pressed_map_.clear();
}

}  // namespace remoting


text:
<?php

namespace tests\stubs;

use Illuminate\Database\Eloquent\Model;

class ModelStub extends Model
{
    protected $fillable = ['name'];
}


text:
package cubicchunks.asm;

import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin;
import org.spongepowered.asm.launch.MixinBootstrap;
import org.spongepowered.asm.mixin.Mixins;

import java.util.Map;

@IFMLLoadingPlugin.MCVersion(value = "1.10.2")
@IFMLLoadingPlugin.SortingIndex(value = 5000)
@IFMLLoadingPlugin.TransformerExclusions(value = "cubicchunks.asm.")
public class CoreModLoadingPlugin implements IFMLLoadingPlugin {

	public CoreModLoadingPlugin() {
		MixinBootstrap.init();
		Mixins.registerErrorHandlerClass("cubicchunks.asm.MixinErrorHandler");
		Mixins.addConfiguration("cubicchunks.mixins.core.json");
	}

	@Override
	public String[] getASMTransformerClass() {
		return new String[]{};
	}

	@Override
	public String getModContainerClass() {
		return null;
	}

	@Override
	public String getSetupClass() {
		return null;
	}

	@Override
	public void injectData(Map<String, Object> data) { }

	@Override
	public String getAccessTransformerClass() {
		return null;
	}
}


text:
from __future__ import absolute_import, unicode_literals, print_function
import base64
from decimal import Decimal
from django import forms
from mailru_money import settings, api
from mailru_money.models import Notification, MailruOrder

ERROR_GENERIC = 'S0001' # Техническая ошибка на стороне Магазина (например, недоступна база данных)
ERROR_INVALID_NOTIFICATION = 'S0002' # Некорректный формат уведомления (например, не получен item_number)
ERROR_SIGNATURE = 'S0003' # Ошибка проверки цифровой подписи
ERROR_DUPLICATE_ITEM = 'S0004' # Уведомление с указанным item_number уже обработано. Остановить уведомления

def _to_decimal(amount):
    # python 2.6 is not able to convert floats to decimals directly
    if isinstance(amount, float):
        return Decimal("%.15g" % amount)
    return Decimal(amount)

class HiddenForm(forms.Form):
    """ A form with all fields hidden """
    def __init__(self, *args, **kwargs):
        super(HiddenForm, self).__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].widget = forms.HiddenInput()

class MailruMoneyForm(HiddenForm):
    """
    Low-level money.mail.ru helper form. It is not for validating data.
    It can be used to output html.

    Pass all the fields to the form's 'initial' argument::

        form = MailruMoneyForm(initial={
            'description': u'Заказ',
            'issuer_id': u'543-TSH',
            'message': u'Покупка',
            'sum': str(15.5),
        })

    """
    ACTION = 'https://money.mail.ru/pay/light/'
    SECRET_KEY = settings.MAILRU_MONEY_SECRET_KEY
    DEFAULT_SHOP_ID = settings.MAILRU_MONEY_SHOP_ID
    DEFAULT_CURRENCY = 'RUR'

    shop_id = forms.CharField()
    currency = forms.CharField()
    sum = forms.CharField()
    description = forms.CharField()
    issuer_id = forms.CharField()
    signature = forms.CharField()
    message = forms.CharField(required=False)
    keep_uniq = forms.CharField(required=False)

    def __init__(self, *args, **kwargs):
        kwargs['initial'].setdefault('shop_id', self.DEFAULT_SHOP_ID)
        kwargs['initial'].setdefault('currency', self.DEFAULT_CURRENCY)

        super(MailruMoneyForm, self).__init__(*args, **kwargs)

        for key in 'keep_uniq', 'message':
            if key not in self.initial:
                del self.fields[key]

        signature = api.signature(self.SECRET_KEY, self.initial, hash_secret=True)
        self.fields['signature'].initial = signature

class MailruOrderForm(MailruMoneyForm):
    """
    High-level money.mail.ru helper form.
    Auto-creates MailruOrder instances.

    ::

        item = Item.objects.get(pk=item_pk)
        form = MailruOrderForm(15, u'оплата товара',
            user = request.user,
            pay_for = item,
        )

    """
    def __init__(self, amount, description, user=None, pay_for=None, message=None, currency='RUR'):
        self.order = MailruOrder.objects.create(
            amount = _to_decimal(amount),
            user = user,
            pay_for = pay_for,
            currency = currency,
        )
        initial={
            'sum': str(amount),
            'description': description,
            'issuer_id': str(self.order.issuer_id),
            'keep_uniq': '1',
            'currency': currency,
        }
        if message is not None:
            initial['message'] = message
        super(MailruOrderForm, self).__init__(initial=initial)

class ResultForm(forms.ModelForm):
    SECRET_KEY = settings.MAILRU_MONEY_SECRET_KEY

    signature = forms.CharField()
    url_pay = forms.URLField(required=False)

    class Meta:
        model = Notification
        fields = 'type', 'status', 'item_number', 'issuer_id', 'serial', 'auth_method'

#    def clean_item_number(self):
#        item_number = self.cleaned_data['item_number']
#        if SuccessNotification.objects.filter(item_number=item_number).exists():
#            raise forms.ValidationError('S0004')
#        return self.cleaned_data['item_number']

    def clean_issuer_id(self):
        issuer_id = self.cleaned_data['issuer_id']
        if issuer_id:
            try:
                issuer_id.encode('ascii')
            except Exception as e:
                raise forms.ValidationError(e)
        return self.cleaned_data['issuer_id']

    @classmethod
    def _get_signature(cls, data):
        return api.signature(cls.SECRET_KEY, data, hash_secret=False)

    def clean(self):
        sig = self._get_signature(self.cleaned_data)
        if sig != self.cleaned_data['signature']:
            raise forms.ValidationError(ERROR_SIGNATURE)

        self.post_clean_issuer_id()
        return self.cleaned_data

    def post_clean_issuer_id(self):
        issuer_id = self.cleaned_data['issuer_id']
        self.cleaned_data['issuer_id'] = base64.b64decode(issuer_id.encode('ascii'))

    def error_code(self):
        if ERROR_DUPLICATE_ITEM in self.errors.get('item_number', []):
            return ERROR_DUPLICATE_ITEM

        if ERROR_DUPLICATE_ITEM in self.non_field_errors():
            return ERROR_DUPLICATE_ITEM

        if ERROR_SIGNATURE in self.errors.get('signature', []):
            return ERROR_SIGNATURE

        return ERROR_INVALID_NOTIFICATION

class OrderResultForm(ResultForm):
    """
    Result form with mandatory MoneyOrder handling.
    """
    def clean(self):
        data = super(OrderResultForm, self).clean()
        issuer_id = data['issuer_id']
        try:
            self._order = MailruOrder.objects.get(issuer_id=issuer_id)
        except (MailruOrder.DoesNotExist, ValueError):
            raise forms.ValidationError(ERROR_INVALID_NOTIFICATION)
        return data

    def save(self, commit=True):
        assert commit==True, 'commit=False is not supported'
        notification = super(OrderResultForm, self).save(commit)
        notification._update_order(self._order)
        return notification


text:
require_relative '../test_helper'
require 'xbee'

class TestXBeeSensorReadIndicator < Minitest::Test
	UUT = XBee::Frames::XBeeSensorReadIndicator

	def test_packet_parsing
		input = XBee::Packet.escape bytes('7E 00 17 94 00 13 A2 00 40 52 2B AA DD 6C 01 03 00 02 00 CE 00 EA 00 52 01 6A 8B')
		packet = XBee::Packet.from_bytes input
		actual = XBee::Frames::Frame.from_packet packet

		assert_instance_of UUT, actual
		assert_equal [0x00, 0x13, 0xa2, 0x00, 0x40, 0x52, 0x2b, 0xaa], actual.address64.to_a
		assert_equal [0xdd, 0x6c], actual.address16.to_a
		assert_equal 0x01, actual.options
		assert_equal 0x03, actual.one_wire_sensors
		assert_equal 0x0002, actual.analog_values[0]
		assert_equal 0x00CE, actual.analog_values[1]
		assert_equal 0x00EA, actual.analog_values[2]
		assert_equal 0x0052, actual.analog_values[3]
		assert_equal 0x016A, actual.temperature
	end
end


text:
#ifndef MODULES_AUDIO_PROCESSING_TRANSIENT_WPD_TREE_H_
#define MODULES_AUDIO_PROCESSING_TRANSIENT_WPD_TREE_H_

#include <stddef.h>

#include <memory>

#include "modules/audio_processing/transient/wpd_node.h"

namespace webrtc {

// Tree of a Wavelet Packet Decomposition (WPD).
//
// The root node contains all the data provided; for each node in the tree, the
// left child contains the approximation coefficients extracted from the node,
// and the right child contains the detail coefficients.
// It preserves its state, so it can be multiple-called.
//
// The number of nodes in the tree will be 2 ^ levels - 1.
//
// Implementation details: Since the tree always will be a complete binary tree,
// it is implemented using a single linear array instead of managing the
// relationships in each node. For convience is better to use a array that
// starts in 1 (instead of 0). Taking that into account, the following formulas
// apply:
// Root node index: 1.
// Node(Level, Index in that level): 2 ^ Level + (Index in that level).
// Left Child: Current node index * 2.
// Right Child: Current node index * 2 + 1.
// Parent: Current Node Index / 2 (Integer division).
class WPDTree {
 public:
  // Creates a WPD tree using the data length and coefficients provided.
  WPDTree(size_t data_length,
          const float* high_pass_coefficients,
          const float* low_pass_coefficients,
          size_t coefficients_length,
          int levels);
  ~WPDTree();

  // Returns the number of nodes at any given level.
  static int NumberOfNodesAtLevel(int level) { return 1 << level; }

  // Returns a pointer to the node at the given level and index(of that level).
  // Level goes from 0 to levels().
  // Index goes from 0 to the number of NumberOfNodesAtLevel(level) - 1.
  //
  // You can use the following formulas to get any node within the tree:
  // Notation: (Level, Index of node in that level).
  // Root node: (0/0).
  // Left Child: (Current node level + 1, Current node index * 2).
  // Right Child: (Current node level + 1, Current node index * 2 + 1).
  // Parent: (Current node level - 1, Current node index / 2) (Integer division)
  //
  // If level or index are out of bounds the function will return NULL.
  WPDNode* NodeAt(int level, int index);

  // Updates all the nodes of the tree with the new data. |data_length| must be
  // teh same that was used for the creation of the tree.
  // Returns 0 if correct, and -1 otherwise.
  int Update(const float* data, size_t data_length);

  // Returns the total number of levels below the root. Root is cosidered level
  // 0.
  int levels() const { return levels_; }

  // Returns the total number of nodes.
  int num_nodes() const { return num_nodes_; }

  // Returns the total number of leaves.
  int num_leaves() const { return 1 << levels_; }

 private:
  size_t data_length_;
  int levels_;
  int num_nodes_;
  std::unique_ptr<std::unique_ptr<WPDNode>[]> nodes_;
};

}  // namespace webrtc

#endif  // MODULES_AUDIO_PROCESSING_TRANSIENT_WPD_TREE_H_


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using IWshRuntimeLibrary;

namespace lpp.Win32Helper
{
    /// <summary>
    /// 使用Windows Script Host操作
    /// </summary>
    public static class WSHHelper
    {
        /// <summary>
        /// 创建桌面快捷方便方式
        /// </summary>
        /// <param name="name">快捷方便方式名称</param>
        /// <param name="exePath">执行文件路径(默认为调用的程序集路径)</param>
        /// <param name="iconPath">图标路径(默认使用执行文件的图标)</param>
        /// <param name="windowStyle">窗口风格(默认为普通窗口风格)</param>
        public static void CreateShortcut(string name, string exePath = "", string iconPath = "",WindowStyle windowStyle = WindowStyle.NORMAL)
        {
            WshShell wshShell = new WshShell();
            IWshShortcut shortcut = wshShell.CreateShortcut(string.Format("{0}{1}{2}.lnk"
                , Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
                , Path.DirectorySeparatorChar
                , name)) as IWshShortcut;
            shortcut.TargetPath = (string.IsNullOrEmpty(exePath) ? Assembly.GetCallingAssembly().Location : exePath);
            shortcut.WorkingDirectory = Environment.CurrentDirectory;
            shortcut.WindowStyle = (int)windowStyle;
            if (!string.IsNullOrEmpty(iconPath))
                shortcut.IconLocation = iconPath;
            shortcut.Save();
        }
    }

    /// <summary>
    /// 窗口风格
    /// </summary>
    public enum WindowStyle : int
    {
        NORMAL = 1, // 普通窗口
        MAXIMIZED = 3, // 最大化
        MINIMIZED = 7 //最小化
    }
}


text:
package org.olat.modules.vitero.model;

/**
 *
 * Description:

 *
 *

 * Initial Date:  13 oct. 2011

 *
 * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
 */
public class ViteroUser {

	private int userId;
	private String firstName;
	private String lastName;
	private String email;

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
}


text:
function repeat(params, values){
    if (params[2].stack_slots[0] != null){
        for (var i=0; i<values[0][1]; i++){
            params[2].stack_slots[0].chain_exec();
        }
    }
    return true;
}

function ifthen(params, values){
    if (values[0][1] && params[2].stack_slots[0] != null){
        params[2].stack_slots[0].chain_exec();
    }
    return true;
}

function forever_exec(params){
    if (params[2].stack_slots[0] != null && params[3].on_infinite_loop){
        params[2].stack_slots[0].chain_exec();
        var myVar = setTimeout(function(){forever_exec(params)}, 500);
    }
}

function forever(params, values){
    params[3].on_infinite_loop = true;
    forever_exec(params);
    return false;
}

function while_exec(params){
    if (params[2].get_slot_values()[0][1] && params[2].stack_slots[0] != null && params[3].on_infinite_loop){
        params[2].stack_slots[0].chain_exec();
        var myVar = setTimeout(function(){while_exec(params)}, 500);
    } else{
        params[3].on_infinite_loop = false;
        params[2].lower_block[0].chain_exec();
    }
}

function whileb(params, values){
    params[3].on_infinite_loop = true;
    while_exec(params);
    return false;
}

function until(params, values){
    params[3].on_infinite_loop = true;
    if (params[2].stack_slots[0]){
        params[3].on_infinite_loop = true;
        params[2].stack_slots[0].chain_exec();
        var myVar = setTimeout(function(){while_exec(params)}, 500);
        return false;
    } else{
        params[3].on_infinite_loop = false;
        return true;
    }
}

function wait_exec(params){
    params[2].lower_block[0].chain_exec();
}

function wait(params, values){
    var myVar = setTimeout(function(){wait_exec(params)}, values[0][1]);
    return false;
}

function space_block(params, values){
    return true;
}


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="android:windowBackground">@drawable/main_header_selector</item>
    </style>

    <style name="TextStyle">
        <item name="android:textColor">#ff000000</item>
        <item name="android:textSize">20sp</item>
    </style>

</resources>


text:
class Direct3DContentProvider : public Microsoft::WRL::RuntimeClass<
		Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::WinRtClassicComMix>,
		ABI::Windows::Phone::Graphics::Interop::IDrawingSurfaceContentProvider,
		IDrawingSurfaceContentProviderNative>
{
public:
	Direct3DContentProvider(LineGraph::LineGraphInterop^ controller);

	void ReleaseD3DResources();

	// IDrawingSurfaceContentProviderNative
	HRESULT STDMETHODCALLTYPE Connect(_In_ IDrawingSurfaceRuntimeHostNative* host);
	void STDMETHODCALLTYPE Disconnect();

	HRESULT STDMETHODCALLTYPE PrepareResources(_In_ const LARGE_INTEGER* presentTargetTime, _Out_ BOOL* contentDirty);
	HRESULT STDMETHODCALLTYPE GetTexture(_In_ const DrawingSurfaceSizeF* size, _Out_ IDrawingSurfaceSynchronizedTextureNative** synchronizedTexture, _Out_ DrawingSurfaceRectF* textureSubRectangle);

private:
	HRESULT InitializeTexture(_In_ const DrawingSurfaceSizeF* size);

	LineGraph::LineGraphInterop^ m_controller;
	Microsoft::WRL::ComPtr<IDrawingSurfaceRuntimeHostNative> m_host;
	Microsoft::WRL::ComPtr<IDrawingSurfaceSynchronizedTextureNative> m_synchronizedTexture;
};


text:
using Riganti.Utils.Infrastructure.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SnowFur.DAL.Model
{
    public class RoomMateOffer : IEntity<int>
    {
        [Key]
        public int Id { get; set; }
        public string MessageForReceiver { get; set; }
        public bool IsConfirmed { get; set; }

        public int ReceiverId { get; set; }
        public virtual User Receiver { get; set; }

        public int SenderId { get; set; }
        public virtual User Sender { get; set; }
    }
}


text:
<?php
namespace Users\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

use Zend\Http\Headers;

use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter;

use Users\Form\RegisterForm;
use Users\Form\RegisterFilter;

use Users\Model\User;
use Users\Model\UserTable;
use Users\Model\Upload;

use Users\Model\ImageUpload;
use Users\Model\ImageUploadTable;

use ZendGData\ClientLogin;
use ZendGData\Photos;

class MediaManagerController extends AbstractActionController
{
	protected $storage;
	protected $authservice;

	protected $photos;

	const GOOGLE_USER_ID = 'zf2.book@gmail.com';
	const GOOGLE_PASSWORD = 'pa$$w0rd';

	public function getAuthService()
	{
		if (! $this->authservice) {
			$this->authservice = $this->getServiceLocator()->get('AuthService');
		}

		return $this->authservice;
	}

	public function getFileUploadLocation()
	{
		// Fetch Configuration from Module Config
    	$config  = $this->getServiceLocator()->get('config');
    	if ($config instanceof Traversable) {
    		$config = ArrayUtils::iteratorToArray($config);
    	}
    	if (!empty($config['module_config']['image_upload_location'])) {
    		return $config['module_config']['image_upload_location'];
    	} else {
    		return FALSE;
    	}
	}

    public function indexAction()
    {
    	$uploadTable = $this->getServiceLocator()->get('ImageUploadTable');
    	$userTable = $this->getServiceLocator()->get('UserTable');
    	$userEmail = $this->getAuthService()->getStorage()->read();
    	$user = $userTable->getUserByEmail($userEmail);
    	$googleAlbums = $this->getGooglePhotos();
    	$googleVideos = $this->getYoutubeVideos();

    	$viewModel  = new ViewModel(
    			array(
    				'myUploads' => $uploadTable->getUploadsByUserId($user->id),
    				'googleAlbums' => $googleAlbums,
    				'youtubeVideos' => $googleVideos,
    				)
    		);

    	return $viewModel;
    }

    public function processUploadAction()
    {
    	$userTable = $this->getServiceLocator()->get('UserTable');
    	$user_email = $this->getAuthService()->getStorage()->read();
    	$user = $userTable->getUserByEmail($user_email);
		$form = $this->getServiceLocator()->get('ImageUploadForm');
    	$request = $this->getRequest();
    	if ($request->isPost()) {

    		$upload = new ImageUpload();
    		$uploadFile    = $this->params()->fromFiles('imageupload');
    		$form->setData($request->getPost());

    		if ($form->isValid()) {
    			// Fetch Configuration from Module Config
    			$uploadPath    = $this->getFileUploadLocation();
    			// Save Uploaded file
      			$adapter = new \Zend\File\Transfer\Adapter\Http();
    			$adapter->setDestination($uploadPath);

    			if ($adapter->receive($uploadFile['name'])) {

    				$exchange_data = array();
    				$exchange_data['label'] = $request->getPost()->get('label');
    				$exchange_data['filename'] = $uploadFile['name'];
    				$exchange_data['thumbnail'] = $this->generateThumbnail($uploadFile['name']);
    				$exchange_data['user_id'] = $user->id;

    				$upload->exchangeArray($exchange_data);

    				$uploadTable = $this->getServiceLocator()->get('ImageUploadTable');
    				$uploadTable->saveUpload($upload);

    				return $this->redirect()->toRoute('users/media');
    			}
    		}
    	}

    	return array('form' => $form);
    }

    public function generateThumbnail($imageFileName)
    {
    	$path = $this->getFileUploadLocation();
    	$sourceImageFileName = $path . '/' . $imageFileName;
    	$thumbnailFileName = 'tn_' . $imageFileName;

    	$imageThumb    = $this->getServiceLocator()->get('WebinoImageThumb');
    	$thumb          = $imageThumb->create($sourceImageFileName,$options = array());
    	$thumb->resize(75, 75);
    	$thumb->save($path . '/' . $thumbnailFileName);

    	return $thumbnailFileName;
    }

    public function uploadAction()
    {
		$form = $this->getServiceLocator()->get('ImageUploadForm');
		$viewModel  = new ViewModel(array('form' => $form));
		return $viewModel;
    }

    public function deleteAction()
    {
    	$uploadId = $this->params()->fromRoute('id');
    	$uploadTable = $this->getServiceLocator()
    					->get('ImageUploadTable');
    	$upload = $uploadTable->getUpload($uploadId);
    	$uploadPath    = $this->getFileUploadLocation();
    	// Remove File
   		unlink($uploadPath ."/" . $upload->filename);
   		unlink($uploadPath ."/" . $upload->thumbnail);

    	// Delete Records
    	$uploadTable->deleteUpload($uploadId);

    	return $this->redirect()->toRoute('users/media');

    }

    public function viewAction()
    {
    	$uploadId = $this->params()->fromRoute('id');
    	$uploadTable = $this->getServiceLocator()
    	->get('ImageUploadTable');
    	$upload = $uploadTable->getUpload($uploadId);

		$viewModel  = new ViewModel(array('upload' => $upload));
		return $viewModel;

    }

    public function showImageAction()
    {
    	$uploadId = $this->params()->fromRoute('id');
	    $uploadTable = $this->getServiceLocator()->get('ImageUploadTable');
	    $upload = $uploadTable->getUpload($uploadId);

    	// Fetch Configuration from Module Config
    	$uploadPath    = $this->getFileUploadLocation();
    	if ($this->params()->fromRoute('subaction') == 'thumb') {
    		$filename = $uploadPath ."/" . $upload->thumbnail;
    	} else {
    		$filename = $uploadPath ."/" . $upload->filename;

    	}
    	$file = file_get_contents($filename);

		// Directly return the Response
		$response = $this->getEvent()->getResponse();
		$response->getHeaders()->addHeaders(array(
			'Content-Type' => 'application/octet-stream',
			'Content-Disposition' => 'attachment;filename="' .$upload->filename . '"',

		));
		$response->setContent($file);

		return $response;
    }

    public function getGooglePhotos() {

    	$adapter = new \Zend\Http\Client\Adapter\Curl();
    	$adapter->setOptions(array(
    		'curloptions' => array(
    			CURLOPT_SSL_VERIFYPEER => false,
    		)
    	));

    	$httpClient = new \ZendGData\HttpClient();
    	$httpClient->setAdapter($adapter);

    	$client = \ZendGData\ClientLogin::getHttpClient(
    					self::GOOGLE_USER_ID,
    					self::GOOGLE_PASSWORD,
    					\ZendGData\Photos::AUTH_SERVICE_NAME,
    					$httpClient);

    	$gp = new \ZendGData\Photos($client);

    	$gAlbums = array();

    	try {
    		$userFeed = $gp->getUserFeed( self::GOOGLE_USER_ID );
    		foreach ($userFeed as $userEntry) {

    			$albumId = $userEntry->getGphotoId()->getText();
    			$gAlbums[$albumId]['label'] = $userEntry->getTitle()->getText();

    			$query = $gp->newAlbumQuery();
    			$query->setUser( self::GOOGLE_USER_ID );
    			$query->setAlbumId( $albumId  );

    			$albumFeed = $gp->getAlbumFeed($query);

    			foreach ($albumFeed as $photoEntry) {

    				$photoId = $photoEntry->getGphotoId()->getText();
    				if ($photoEntry->getMediaGroup()->getContent() != null) {
    					$mediaContentArray = $photoEntry->getMediaGroup()->getContent();
    					$photoUrl = $mediaContentArray[0]->getUrl();
    				}

    				if ($photoEntry->getMediaGroup()->getThumbnail() != null) {
    					$mediaThumbnailArray = $photoEntry->getMediaGroup()->getThumbnail();
    					$thumbUrl = $mediaThumbnailArray[0]->getUrl();
    				}

    				$albumPhoto = array();
    				$albumPhoto['id'] = $photoId;
    				$albumPhoto['photoUrl'] = $photoUrl;
    				$albumPhoto['thumbUrl'] = $thumbUrl;

    				$gAlbums[$albumId]['photos'][] =$albumPhoto;

    			}
    		}
    	} catch (App\HttpException $e) {
    		echo "Error: " . $e->getMessage() . "
\n";
    		if ($e->getResponse() != null) {
    			echo "Body:
\n" . $e->getResponse()->getBody() .
    			"
\n";
    		}
    		// In new versions of Zend Framework, you also have the option
    		// to print out the request that was made.  As the request
    		// includes Auth credentials, it's not advised to print out
    		// this data unless doing debugging
    		// echo "Request:
\n" . $e->getRequest() . "
\n";
    	} catch (App\Exception $e) {
    		echo "Error: " . $e->getMessage() . "
\n";
    	}

    	return $gAlbums;
    }

    public function getYoutubeVideos()
    {
    	$adapter = new \Zend\Http\Client\Adapter\Curl();
    	$adapter->setOptions(array(
    		'curloptions' => array(
    			CURLOPT_SSL_VERIFYPEER => false,
    		)
    	));

    	$httpClient = new \ZendGData\HttpClient();
    	$httpClient->setAdapter($adapter);

    	$client = \ZendGData\ClientLogin::getHttpClient(
    		self::GOOGLE_USER_ID,
    		self::GOOGLE_PASSWORD,
    		\ZendGData\YouTube::AUTH_SERVICE_NAME,
    		$httpClient);

    	$yt = new \ZendGData\YouTube($client);
    	$yt->setMajorProtocolVersion(2);
    	$query = $yt->newVideoQuery();
    	$query->setOrderBy('relevance');
    	$query->setSafeSearch('none');
    	$query->setVideoQuery('Zend Framework');

    	// Note that we need to pass the version number to the query URL function
    	// to ensure backward compatibility with version 1 of the API.
    	$videoFeed = $yt->getVideoFeed($query->getQueryUrl(2));

    	$yVideos = array();
    	foreach ($videoFeed as $videoEntry) {
    		 $yVideo = array();
    		 $yVideo['videoTitle'] = $videoEntry->getVideoTitle();
    		 $yVideo['videoDescription'] = $videoEntry->getVideoDescription();
    		 $yVideo['watchPage'] = $videoEntry->getVideoWatchPageUrl();
    		 $yVideo['duration'] = $videoEntry->getVideoDuration();
    		 $videoThumbnails = $videoEntry->getVideoThumbnails();

    		 $yVideo['thumbnailUrl'] = $videoThumbnails[0]['url'];
    		 $yVideos[] = $yVideo;
    	}
    	return $yVideos;

    }
}


text:
layout: post
title: Malena Morgan & Rilee Marks - American Girls
titleinfo: pornvd
desc: Watch Malena Morgan & Rilee Marks - American Girls. Pornhub is the ultimate xxx porn and sex site.
---

Malena Morgan & Rilee Marks - American Girls

Watch Malena Morgan & Rilee Marks - American Girls. Pornhub is the ultimate xxx porn and sex site.


text:
/* eslint-disable lines-around-comment */
import React, { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
import { makeStyles } from 'tss-react/mui';

// @ts-ignore
import { Avatar } from '../../../base/avatar';
import Icon from '../../../base/icons/components/Icon';
import { IconCheck, IconCloseLarge } from '../../../base/icons/svg';
import { withPixelLineHeight } from '../../../base/styles/functions.web';
import { admitMultiple } from '../../../lobby/actions.web';
import { getKnockingParticipants, getLobbyEnabled } from '../../../lobby/functions';
// @ts-ignore
import { Drawer, JitsiPortal } from '../../../toolbox/components/web';
import { showOverflowDrawer } from '../../../toolbox/functions.web';
import { useLobbyActions, useParticipantDrawer } from '../../hooks';

// @ts-ignore
import LobbyParticipantItems from './LobbyParticipantItems';

const useStyles = makeStyles()(theme => {
    return {
        drawerActions: {
            listStyleType: 'none',
            margin: 0,
            padding: 0
        },
        drawerItem: {
            alignItems: 'center',
            color: theme.palette.text01,
            display: 'flex',
            padding: '12px 16px',
            ...withPixelLineHeight(theme.typography.bodyShortRegularLarge),

            '&:first-child': {
                marginTop: '15px'
            },

            '&:hover': {
                cursor: 'pointer',
                background: theme.palette.action02
            }
        },
        icon: {
            marginRight: 16
        },
        headingContainer: {
            alignItems: 'center',
            display: 'flex',
            justifyContent: 'space-between'
        },
        heading: {
            // @ts-ignore
            ...withPixelLineHeight(theme.typography.heading7),
            color: theme.palette.text02
        },
        link: {
            ...withPixelLineHeight(theme.typography.labelBold),
            color: theme.palette.link01,
            cursor: 'pointer'
        }
    };
});

/**
 * Component used to display a list of participants waiting in the lobby.
 *
 * @returns {ReactNode}
 */
export default function LobbyParticipants() {
    const lobbyEnabled = useSelector(getLobbyEnabled);
    const participants = useSelector(getKnockingParticipants);
    const { t } = useTranslation();
    const { classes } = useStyles();
    const dispatch = useDispatch();
    const admitAll = useCallback(() => {
        dispatch(admitMultiple(participants));
    }, [ dispatch, participants ]);
    const overflowDrawer = useSelector(showOverflowDrawer);
    const [ drawerParticipant, closeDrawer, openDrawerForParticipant ] = useParticipantDrawer();
    const [ admit, reject ] = useLobbyActions(drawerParticipant, closeDrawer);

    if (!lobbyEnabled || !participants.length) {
        return null;
    }

    return (
        <>

                    {t('participantsPane.headings.lobby', { count: participants.length })}

                {
                    participants.length > 1
                    &&
{t('lobby.admitAll')}

                }

            <LobbyParticipantItems
                openDrawerForParticipant = { openDrawerForParticipant }
                overflowDrawer = { overflowDrawer }
                participants = { participants } />
            <JitsiPortal>
                <Drawer
                    isOpen = { Boolean(drawerParticipant && overflowDrawer) }
                    onClose = { closeDrawer }>

                            <Avatar
                                className = { classes.icon }
                                participantId = { drawerParticipant?.participantID }
                                size = { 20 } />
                            { drawerParticipant?.displayName }

                            <Icon
                                className = { classes.icon }
                                size = { 20 }
                                src = { IconCheck } />
                            { t('lobby.admit') }

                            <Icon
                                className = { classes.icon }
                                size = { 20 }
                                src = { IconCloseLarge } />
                            { t('lobby.reject')}

                </Drawer>
            </JitsiPortal>
        </>
    );
}


text:
import argparse
import collections
import json
import logging
import sys

LF = '%(asctime)s: %(levelname)s: %(message)s'

class PendingOperationType(object):
    Unknown = 0
    CreateVolume = 1
    DeleteVolume = 2
    ExpandVolume = 3
    CreateBlockVolume = 4
    DeleteBlockVolume = 5
    RemoveDevice = 6
    CloneVolume = 7

    def __init__(self):
        self.reverse = collections.defaultdict(lambda: 'Unknown', self.rmap())

    @classmethod
    def rmap(cls):
        return {v: k for k, v in cls.__dict__.items() if isinstance(v, int)}

class PendingChangeType(object):
    Unknown = 0
    AddBrick = 1
    AddVolume = 2
    DeleteBrick = 3
    DeleteVolume = 4
    ExpandVolume = 5
    AddBlockVolume = 6
    DeleteBlockVolume = 7
    RemoveDevice = 8
    CloneVolume = 9
    SnapshotVolume = 10
    AddVolumeClone = 11

    def __init__(self):
        self.reverse = collections.defaultdict(lambda: 'Unknown', self.rmap())

    @classmethod
    def rmap(cls):
        return {v: k for k, v in cls.__dict__.items() if isinstance(v, int)}

class EditSet(object):
    def __init__(self):
        self.volumes = set()
        self.bricks = set()
        self.devices = set()
        self.nodes = set()
        self.block_volumes = set()

OP_TYPE = PendingOperationType()
CHANGE_TYPE = PendingChangeType()

def add_to_pending(pi, optype, changetype, uid):
    if changetype == CHANGE_TYPE.AddBrick:
        pi.bricks.add(uid)
    elif changetype == CHANGE_TYPE.AddVolume:
        pi.volumes.add(uid)
    elif changetype == CHANGE_TYPE.DeleteBrick:
        pi.bricks.add(uid)
    elif changetype == CHANGE_TYPE.DeleteVolume:
        pi.volumes.add(uid)
    elif changetype == CHANGE_TYPE.ExpandVolume:
        raise ValueError('expand not supported', optype, changetype)
    elif changetype == CHANGE_TYPE.AddBlockVolume:
        pi.block_volumes.add(uid)
    elif changetype == CHANGE_TYPE.DeleteBlockVolume:
        pi.block_volumes.add(uid)
    elif changetype == CHANGE_TYPE.RemoveDevice:
        pi.devices.add(uid)
    else:
        raise ValueError('not supported', optype, changetype)

def delete_volume(data, vid):
    log.info('deleting volume %s', vid)
    item = data['volumeentries'].pop(vid, None)
    for c in data['clusterentries'].values():
        if vid in c['Info']['volumes']:
            c['Info']['volumes'].remove(vid)
    if not item:
        return
    log.warning('may need manual cleanup: volume: %s',
        item['Info']['name'])

def delete_block_volume(data, vid):
    log.info('deleting block volume %s', vid)
    item = data['blockvolumeentries'].pop(vid, None)
    # remove any reference (real or dangling) from cluster
    for c in data['clusterentries'].values():
        if vid in c['Info']['blockvolumes']:
            c['Info']['blockvolumes'].remove(vid)
    # if no item in db, just stop
    if not item:
        return
    # remove any reference (real or dangling) from BHV
    vol = data['volumeentries'].get(item['Info']['blockhostingvolume'])
    if vol:
        try:
            vol['Info']['blockinfo']['blockvolume'].remove(vid)
            vol['Info']['blockinfo']['freesize'] += item['Info']['size']
        except ValueError:
            log.warning('block volume %s not listed in hosting volume %s',
                        vid, vol['Info']['id'])
    log.warning('may need manual cleanup: block volume: %s',
        item['Info']['blockvolume'].get('iqn') or '???')

def delete_brick(data, bid, subtract=True):
    log.info('deleting brick %s', bid)
    item = data['brickentries'].pop(bid, None)
    for v in data['volumeentries'].values():
        if bid in v['Bricks']:
            v['Bricks'].remove(bid)
    for d in data['deviceentries'].values():
        if bid in d['Bricks']:
            d['Bricks'].remove(bid)
            if subtract:
                storage_free(d, item)
            else:
                log.warning(
                    'Not subtracting brick space from device: %s',
                    d['Info']['id'])
    if not item:
        return
    log.warning('may need manual cleanup: brick: %s', item['Info']['path'])

def storage_free(device, brick):
    if not brick:
        return
    total_size = brick['TpSize'] + brick['PoolMetadataSize']
    device['Info']['storage']['free'] += total_size
    device['Info']['storage']['used'] -= total_size
    log.info('added back free size %s to device %s, now: %r',
             total_size, device['Info']['id'],
             device['Info']['storage'])
    if device['Info']['storage']['used'] < 0:
        raise ValueError("used size went negative")
    if device['Info']['storage']['free'] < 0:
        raise ValueError("free size went negative")
    if device['Info']['storage']['free'] > device['Info']['storage']['total']:
        raise ValueError("free size greater than total size")
    if device['Info']['storage']['used'] > device['Info']['storage']['total']:
        raise ValueError("used size greater than total size")

def scrub(data, subtract=True):
    log.debug('starting scrub')
    pending_ops = set()
    p1 = EditSet()
    p2 = EditSet()

    # first pass: scan thru pending entries
    for poid, item in data['pendingoperations'].items():
        pending_ops.add(poid)
        log.info('pending operation: %s', poid)
        optype = item['Type']
        log.info('pending operation type: %s -> %s',
                 optype, OP_TYPE.reverse[optype])
        for a in item['Actions']:
            changetype = a['Change']
            log.info('change type: %s -> %s',
                     changetype, CHANGE_TYPE.reverse[changetype])
            log.info('change type id: %s', a['Id'])
            add_to_pending(p1, optype, changetype, a['Id'])

    # 2nd pass: scan thru items looking for pending
    for vid, item in data['volumeentries'].items():
        poid = item.get('Pending', {}).get('Id')
        if poid:
            p2.volumes.add(vid)

    for vid, item in data['blockvolumeentries'].items():
        poid = item.get('Pending', {}).get('Id')
        if poid:
            p2.block_volumes.add(vid)

    for bid, item in data['brickentries'].items():
        poid = item.get('Pending', {}).get('Id')
        if poid:
            p2.bricks.add(bid)

    for did, item in data['deviceentries'].items():
        poid = item.get('Pending', {}).get('Id')
        if poid:
            p2.devices.add(did)

    # check for items marked as pending not found w/in pending ops
    diffs = 0
    for vid in p2.volumes:
        if vid not in p1.volumes:
            log.warning('volume %s is pending but has no pending op', vid)
            diffs += 1
    for vid in p2.block_volumes:
        if vid not in p1.block_volumes:
            log.warning('block volume %s is pending but has no pending op', vid)
            diffs += 1
    for bid in p2.bricks:
        if bid not in p1.bricks:
            log.warning('brick %s is pending but has no pending op', bid)
            diffs += 1
    for did in p2.devices:
        if did not in p1.devices:
            log.warning('device %s is pending but has no pending op', did)
            diffs += 1
    if diffs:
        raise ValueError("%d differences found -- need manual help" % diffs)

    # cleanup the refrences
    if p1.devices:
        for did in p1.devices:
            log.warning("need manual cleanup: device id: %s", did)
        raise ValueError('need manual cleanup: devices')

    log.debug('scrubbing items')
    for vid in p1.volumes:
        delete_volume(data, vid)
    for vid in p1.block_volumes:
        delete_block_volume(data, vid)
    for bid in p1.bricks:
        delete_brick(data, bid, subtract=subtract)
    for poid in pending_ops:
        data['pendingoperations'].pop(poid, None)
    return data

def rm_volumes(data, targets, subtract=True):
    if not targets:
        raise ValueError("volume ids to remove must be provided (use -r)")
    log.debug('starting remove volumes: %s', targets)
    es = EditSet()

    # first pass: find out if the vols are real & gather bricks
    log.debug("checking data")
    for volid in targets:
        if volid not in data['volumeentries']:
            raise KeyError('no such volume: {}'.format(volid))
        vol = data['volumeentries'][volid]
        blockvols = vol["Info"].get("blockinfo", {}).get("blockvolume", [])
        if blockvols:
            raise ValueError("volume contains block volumes: {}".format(volid))
        es.volumes.add(volid)
        for b in vol["Bricks"]:
            es.bricks.add(b)

    log.debug('scrubbing items')
    for vid in es.volumes:
        delete_volume(data, vid)
    for bid in es.bricks:
        delete_brick(data, bid, subtract=subtract)
    return data

def main():
    a = argparse.ArgumentParser()
    a.add_argument('--edit', '-e', default='pending',
                   choices=['pending', 'volumes'])
    a.add_argument('--remove', '-r', action='append', default=[])
    a.add_argument('--no-subtract', action='store_true')
    a.add_argument('--logfile', '-l')
    a.add_argument('source')
    cli = a.parse_args()

    if cli.logfile:
        h = logging.FileHandler(cli.logfile)
        h.setFormatter(logging.Formatter(LF))
        logging.getLogger().addHandler(h)

    if cli.source == '-':
        data = json.load(sys.stdin)
    else:
        with open(cli.source) as fh:
            data = json.load(fh)

    subtract = not cli.no_subtract
    if cli.edit == 'pending':
        op = lambda d: scrub(d, subtract=subtract)
    elif cli.edit == 'volumes':
        op = lambda d: rm_volumes(d, cli.remove, subtract=subtract)
    else:
        raise ValueError('unknown edit: {}'.format(cli.edit))

    # use indent=4 in order to match the output of json.tool this
    # is usefule to diff the reformatted original with the update
    json.dump(op(data), sys.stdout, indent=4)
    sys.stdout.write('\n')

logging.basicConfig(
    stream=sys.stderr,
    format=LF,
    level=logging.DEBUG)
log = logging.getLogger('scrub')
main()


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Modules.Html
{
    using System;
    using System.Collections;
    using System.Collections.Generic;

    using DotNetNuke.Entities.Modules;
    using DotNetNuke.Modules.Html.Components;
    using DotNetNuke.Services.Exceptions;

    ///
    ///   The Settings ModuleSettingsBase is used to manage the
    ///   settings for the HTML Module.
    ///
    /// <remarks>
    /// </remarks>
    public partial class Settings : ModuleSettingsBase
    {
        private HtmlModuleSettings _moduleSettings;

        private new HtmlModuleSettings ModuleSettings
        {
            get
            {
                return this._moduleSettings ?? (this._moduleSettings = new HtmlModuleSettingsRepository().GetSettings(this.ModuleConfiguration));
            }
        }

        ///
        ///   LoadSettings loads the settings from the Database and displays them.
        ///
        /// <remarks>
        /// </remarks>
        public override void LoadSettings()
        {
            try
            {
                if (!this.Page.IsPostBack)
                {
                    var htmlTextController = new HtmlTextController();
                    var workflowStateController = new WorkflowStateController();

                    this.chkReplaceTokens.Checked = this.ModuleSettings.ReplaceTokens;
                    this.cbDecorate.Checked = this.ModuleSettings.UseDecorate;

                    // get workflow/version settings
                    var workflows = new ArrayList();
                    foreach (WorkflowStateInfo state in workflowStateController.GetWorkflows(this.PortalId))
                    {
                        if (!state.IsDeleted)
                        {
                            workflows.Add(state);
                        }
                    }

                    this.cboWorkflow.DataSource = workflows;
                    this.cboWorkflow.DataBind();
                    var workflow = htmlTextController.GetWorkflow(this.ModuleId, this.TabId, this.PortalId);
                    if (this.cboWorkflow.FindItemByValue(workflow.Value.ToString()) != null)
                    {
                        this.cboWorkflow.FindItemByValue(workflow.Value.ToString()).Selected = true;
                    }

                    this.DisplayWorkflowDetails();

                    if (this.rblApplyTo.Items.FindByValue(workflow.Key) != null)
                    {
                        this.rblApplyTo.Items.FindByValue(workflow.Key).Selected = true;
                    }

                    this.txtSearchDescLength.Text = this.ModuleSettings.SearchDescLength.ToString();
                }

                // Module failed to load
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        ///
        ///   UpdateSettings saves the modified settings to the Database.
        ///
        public override void UpdateSettings()
        {
            try
            {
                var htmlTextController = new HtmlTextController();

                // update replace token setting
                this.ModuleSettings.ReplaceTokens = this.chkReplaceTokens.Checked;
                this.ModuleSettings.UseDecorate = this.cbDecorate.Checked;
                this.ModuleSettings.SearchDescLength = int.Parse(this.txtSearchDescLength.Text);
                var repo = new HtmlModuleSettingsRepository();
                repo.SaveSettings(this.ModuleConfiguration, this.ModuleSettings);

                // disable module caching if token replace is enabled
                if (this.chkReplaceTokens.Checked)
                {
                    ModuleInfo module = ModuleController.Instance.GetModule(this.ModuleId, this.TabId, false);
                    if (module.CacheTime > 0)
                    {
                        module.CacheTime = 0;
                        ModuleController.Instance.UpdateModule(module);
                    }
                }

                // update workflow/version settings
                switch (this.rblApplyTo.SelectedValue)
                {
                    case "Module":
                        htmlTextController.UpdateWorkflow(this.ModuleId, this.rblApplyTo.SelectedValue, int.Parse(this.cboWorkflow.SelectedValue), this.chkReplace.Checked);
                        break;
                    case "Page":
                        htmlTextController.UpdateWorkflow(this.TabId, this.rblApplyTo.SelectedValue, int.Parse(this.cboWorkflow.SelectedValue), this.chkReplace.Checked);
                        break;
                    case "Site":
                        htmlTextController.UpdateWorkflow(this.PortalId, this.rblApplyTo.SelectedValue, int.Parse(this.cboWorkflow.SelectedValue), this.chkReplace.Checked);
                        break;
                }

                // Module failed to load
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.cboWorkflow.SelectedIndexChanged += this.OnWorkflowSelectedIndexChanged;
        }

        protected void OnWorkflowSelectedIndexChanged(object sender, EventArgs e)
        {
            this.DisplayWorkflowDetails();
        }

        private void DisplayWorkflowDetails()
        {
            if (this.cboWorkflow.SelectedValue != null)
            {
                var objWorkflow = new WorkflowStateController();
                var strDescription = string.Empty;
                var arrStates = objWorkflow.GetWorkflowStates(int.Parse(this.cboWorkflow.SelectedValue));
                if (arrStates.Count > 0)
                {
                    foreach (WorkflowStateInfo objState in arrStates)
                    {
                        strDescription = strDescription + " >> " + "" + objState.StateName + "";
                    }

                    strDescription = strDescription + "
" + ((WorkflowStateInfo)arrStates[0]).Description;
                }

                this.lblDescription.Text = strDescription;
            }
        }
    }
}


text:
CTEST_CUSTOM_PRE_MEMCHECK
-------------------------

A list of commands to run at the start of the :command:`ctest_memcheck`
command.

.. include:: CTEST_CUSTOM_XXX.txt


text:
package nl.tudelft.ewi.devhub.services;

import java.util.Map;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Singleton;

import nl.tudelft.ewi.devhub.services.continuousintegration.ContinuousIntegrationService;
import nl.tudelft.ewi.devhub.services.versioncontrol.VersionControlService;

import com.google.common.collect.Maps;

@Singleton
public class ServiceProvider {

	private final Map<String, VersionControlService> versioningServices;
	private final Map<String, ContinuousIntegrationService> buildServices;

	@Inject
	public ServiceProvider(Set<VersionControlService> versioningServices, Set<ContinuousIntegrationService> buildServices) {
		this.versioningServices = map(versioningServices);
		this.buildServices = map(buildServices);
	}

	private <T extends Service> Map<String, T> map(Set<T> services) {
		Map<String, T> mapped = Maps.newTreeMap();
		for (T service : services) {
			String name = service.getName();
			if (name == null) {
				throw new NullPointerException("Service: " + service.getClass().getSimpleName() + " must return a unique non-null name!");
			}
			if (mapped.containsKey(name)) {
				throw new IllegalArgumentException("There's already a service registered with the name: " + name);
			}
			mapped.put(name, service);
		}
		return mapped;
	}

	public Set<String> getVersionControlServices() {
		return versioningServices.keySet();
	}

	public VersionControlService getVersionControlService(String name) {
		return versioningServices.get(name);
	}

	public Set<String> getContinuousIntegrationServices() {
		return buildServices.keySet();
	}

	public ContinuousIntegrationService getContinuousIntegrationService(String name) {
		return buildServices.get(name);
	}

}


text:
from django.conf import settings
from django.core.mail.backends.smtp import EmailBackend

class DebugSMTPEmailBackend(EmailBackend):
    """ Overrides SMTP backend to send all emails to 1 debug address
        instead of actual recipients
    """
    subject_template = u'[DEBUG: %(emails)s] %(subject)s'

    def _send(self, email_message):
        if getattr(settings, 'EMAIL_DEBUG', True):
            email_message.subject = self.subject_template % {
                'emails': ','.join(email_message.to),
                'subject': email_message.subject}
            email_message.to = settings.EMAIL_DEBUG_ADDRESSES

        super(DebugSMTPEmailBackend, self)._send(email_message)


text:
/**
 *
 *        Correlations/Covariance computations.
 *
 */
package org.apache.commons.math4.stat.correlation;


text:
<?php

namespace Tienvx\Bundle\MbtBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Tienvx\Bundle\MbtBundle\Model\Progress as ProgressModel;

#[ORM\Embeddable]
class Progress extends ProgressModel
{
    #[ORM\Column(type: 'integer', options: ['default' => 0])]
    #[Assert\Positive]
    protected int $total = 0;

    #[ORM\Column(type: 'integer', options: ['default' => 0])]
    #[Assert\Positive]
    protected int $processed = 0;

    #[Assert\Callback]
    public function validate(ExecutionContextInterface $context, $payload)
    {
        if ($this->processed > $this->total) {
            $context->buildViolation('Processed should be less than or equal to total.')
                ->atPath('processed')
                ->addViolation();
        }
    }
}


text:
namespace Zu.ChromeDevTools.DOMDebugger
{
    using Newtonsoft.Json;

    /// <summary>
    /// Sets breakpoint on particular CSP violations.
    /// </summary>
    public sealed class SetBreakOnCSPViolationCommand : ICommand
    {
        private const string ChromeRemoteInterface_CommandName = "DOMDebugger.setBreakOnCSPViolation";

        [JsonIgnore]
        public string CommandName
        {
            get { return ChromeRemoteInterface_CommandName; }
        }

        /// <summary>
        /// CSP Violations to stop upon.
        /// </summary>
        [JsonProperty("violationTypes")]
        public CSPViolationType[] ViolationTypes
        {
            get;
            set;
        }
    }

    public sealed class SetBreakOnCSPViolationCommandResponse : ICommandResponse<SetBreakOnCSPViolationCommand>
    {
    }
}


text:
'use strict';

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    jshint: {
      all: [
        'Gruntfile.js',
        'tasks/*.js',
        '<%= nodeunit.tests %>'
      ],
      options: {
        jshintrc: '.jshintrc'
      }
    },

    // Before generating any new files, remove any previously-created files.
    clean: {
      tests: ['tmp']
    },

    // Configuration to be run (and then tested).
    'saucelabs-browsers': {
      all: {
        options: {}
      },
      chrome: {
        options: {
          filter: function (browsers) {
            return browsers.filter(function (b) {
              return /chrome/i.test(b.browserName);
            });
          }
        }
      }
    },

    // Unit tests.
    nodeunit: {
      tests: ['test/*-test.js']
    }

  });

  // Actually load this plugin's task(s).
  grunt.loadTasks('tasks');

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-nodeunit');

  // Whenever the "test" task is run, first clean the "tmp" dir, then run this
  // plugin's task(s), then test the result.
  grunt.registerTask('test', ['clean', 'saucelabs-browsers:all', 'nodeunit']);

  // By default, lint and run all tests.
  grunt.registerTask('default', ['jshint', 'test']);

};


text:
package com.amazonaws.services.redshift.model;

import javax.annotation.Generated;

/**
 * <p>
 * The operation would exceed the number of nodes allowed for a cluster.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class NumberOfNodesPerClusterLimitExceededException extends com.amazonaws.services.redshift.model.AmazonRedshiftException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new NumberOfNodesPerClusterLimitExceededException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public NumberOfNodesPerClusterLimitExceededException(String message) {
        super(message);
    }

}


text:
package driver

import (
	"bytes"
	"log"
	"os"
	"os/exec"
)

const rssMultiplier = 1

func RunUnderProfiler(args ...string) (string, string) {
	return "", ""
}

// Size runs size command on the file. Returns filename with output. Any errors are ignored.
func Size(file string) string {
	resf, err := os.Create(tempFilename("size.txt"))
	if err != nil {
		log.Printf("Failed to create output file: %v", err)
		return ""
	}
	defer resf.Close()

	var stderr bytes.Buffer
	cmd := exec.Command("size", "-m", file)
	cmd.Stdout = resf
	cmd.Stderr = &stderr
	if err := cmd.Run(); err != nil {
		log.Printf("Failed to execute 'size -m %v': %v\n%v", file, err, stderr.String())
		return ""
	}

	return resf.Name()
}

func getVMPeak() uint64 {
	return 0
}

func setProcessAffinity(v int) {
}


text:
<?php

namespace Mautic\AssetBundle\EventListener;

use Mautic\AssetBundle\AssetEvents;
use Mautic\AssetBundle\Event\AssetEvent;
use Mautic\AssetBundle\Event\AssetLoadEvent;
use Mautic\CampaignBundle\CampaignEvents;
use Mautic\CampaignBundle\Event\CampaignBuilderEvent;
use Mautic\CampaignBundle\Event\CampaignExecutionEvent;
use Mautic\CoreBundle\EventListener\CommonSubscriber;

/**
 * Class CampaignSubscriber
 *
 * @package Mautic\AssetBundle\EventListener
 */
class CampaignSubscriber extends CommonSubscriber
{

    /**
     * @return array
     */
    static public function getSubscribedEvents()
    {
        return [
            CampaignEvents::CAMPAIGN_ON_BUILD         => ['onCampaignBuild', 0],
            AssetEvents::ASSET_ON_LOAD                => ['onAssetDownload', 0],
            AssetEvents::ON_CAMPAIGN_TRIGGER_DECISION => ['onCampaignTrigger', 0]
        ];
    }

    /**
     * @param CampaignBuilderEvent $event
     */
    public function onCampaignBuild(CampaignBuilderEvent $event)
    {
        $trigger = [
            'label'       => 'mautic.asset.campaign.event.download',
            'description' => 'mautic.asset.campaign.event.download_descr',
            'eventName'   => AssetEvents::ON_CAMPAIGN_TRIGGER_DECISION,
            'formType'    => 'campaignevent_assetdownload'
        ];

        $event->addLeadDecision('asset.download', $trigger);
    }

    /**
     * Trigger point actions for asset download
     *
     * @param AssetEvent $event
     */
    public function onAssetDownload(AssetLoadEvent $event)
    {
        $asset = $event->getRecord()->getAsset();

        if ($asset !== null) {
            $this->factory->getModel('campaign.event')->triggerEvent('asset.download', $asset, 'asset.download.'.$asset->getId());
        }
    }

    /**
     * @param CampaignExecutionEvent $event
     */
    public function onCampaignTriggerDecision(CampaignExecutionEvent $event)
    {
        $eventDetails = $event->getEventDetails();

        if ($eventDetails == null) {
            return $event->setResult(true);
        }

        $assetId       = $eventDetails->getId();
        $limitToAssets = $event->getConfig()['assets'];

        if (!empty($limitToAssets) && !in_array($assetId, $limitToAssets)) {
            //no points change
            return $event->setResult(false);
        }

        $event->setResult(true);
    }
}


text:
@interface NRDirectory : NSObject
- (id)initWithDirectory:(NSString *)dir;
- (void)directoryChanged;
@end


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
    <title>Asset Management - Initiatives</title>

    <link href='http://fonts.googleapis.com/css?family=Montserrat:400,700|Roboto:400,700,700italic,100,300' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/main.css" rel="stylesheet">

Initiatives

A prominent theme of MAP-21 has been to accelerate project delivery through a variety of approaches.  While MAP-21 originally authorized spending on these programs only through FFY 2014, a series of extensions has carried these themes over into FFY2015.

One of the ways MAP-21 accelerates project delivery is through the creation of a new Categorical Exclusion (CE) that would affect projects eligible for assistance under 23 U.S.C. that are located in the existing operational right-of-way (Section 1316).  Another new CE applies to projects receiving less than $5 million in Federal funds, or with a total estimated cost of not more than $30 million and Federal funds comprising less than 15% of total estimated project cost (Section 1318).

MAP-21 creates a new Section for the integration of planning and environmental reviews. The new section allows Federal lead agencies to adopt and use planning products in the environmental review process of a project. Planning products adopted through the process may be relied upon and used by other Federal agencies in carrying out reviews for the project.

Another clause in MAP-21 relates to environmental impact statements and record of decision.  Under Section 1319, the use of an errata sheet attached to the Draft EIS in-lieu of a Final EIS is encouraged under certain conditions. Section 1319 also allows the FEIS and ROD to be combined in certain conditions.


text:
package org.scalaide.core.compiler

import org.scalaide.logging.HasLogger
import scala.tools.nsc.interactive.Global
import scala.reflect.internal.Flags

/** A declaration printer for Scala symbols and types. Designed to be extensible, clients
 *  may subclass this class.
 *
 *  The current implementation borrows almost all the code from the Scala compiler's various
 *  `toString` implementations accros the Symbol and Type hierarchy. The only notable
 *  difference is the way type references are printed. Unlike scalac, this printer uses
 *  simple names (no fully qualified names). An alternative implementatinon would need to
 *  override `showSingleType` and `showThisType` in order to reinstate that. For example:
 *
 *  {{{
 *   def foo[T <: File](x: ArrayBuffer[File])
 *   <vs>
 *   def foo[T <: java.io.File](x: scala.collection.mutable.ArrayBuffer[java.io.File])
 *  }}}
 *
 *  @note All methods should be run on the PC thread.
 */
abstract class DeclarationPrinter extends HasLogger {
  val compiler: Global
  import compiler._

  /** Print the given type
   *
   *  @note Should be run on the presentation compiler thread (inside askOption).
   */
  def apply(tpe: Type): String = showType(tpe)

  /** Print the given declaration, potentially seen as a different type.
   *
   *  This method returns a human-readable string of the given symbol,
   *  trying to be as close as possible to real Scala syntax. It prints
   *  modifiers, type and value parameters, bounds or type aliases.
   *
   *  @note Should be run on the presentation compiler thread (inside askOption).
   */
  def defString(sym: Symbol, flagMask: Long = Flags.ExplicitFlags, showKind: Boolean = true)(seenAs: Type = sym.rawInfo): String = {

    def infoString(tp: Type): String = {
      def isStructuralThisType = (
        // prevents disasters like SI-8158
        sym.owner.isInitialized && sym.owner.isStructuralRefinement && tp == sym.owner.tpe)

      if (sym.isType) {
        typeParamsString(tp) + (
          if (sym.isClass) " extends " + showTypes(tp.parents).mkString(" with ")
          else if (sym.isAliasType) " = " + showType(tp.resultType)
          else tp.resultType match {
            case rt @ TypeBounds(_, _) => showType(rt)
            case rt                    => " <: " + showType(rt)
          })
      } else if (sym.isModule) "" //  avoid "object X of type X.type"
      else tp match {
        case PolyType(tparams, res)    => tp.typeParams.map(defString(_, flagMask)()).mkString("[", ", ", "]") + infoString(res)
        case NullaryMethodType(res)    => infoString(res)
        case MethodType(params, res)   => params.map(s => defString(s, flagMask)()).mkString("(", ", ", ")") + infoString(res)
        case _ if isStructuralThisType => ": " + sym.owner.name
        case _                         => ": " + showType(tp)
      }
    }

    /** Inspired from Symbol, but take into account the mask access modifiers.
     *  The original would always display access modifiers, even when the mask is `0L`.
     */
    def flagString(sym: Symbol, basis: Long): String = {
      import sym._
      import Flags._
      val access = if ((basis & AccessFlags) != 0) accessString else ""
      val nonAccess = flagBitsToString(basis & ~AccessFlags)

      if (access == "") nonAccess
      else if (nonAccess == "") access
      else nonAccess + " " + access
    }

    val gsym= sym.getterIn(sym.owner)
    def hasGetterSetter(sym:Symbol)= gsym != NoSymbol && sym.setterIn(sym.owner) != NoSymbol

    if(hasGetterSetter(sym)){
      compose("", "var",sym.localName.toString.trim+": "+gsym.tpe.resultType)
    } else{

       val name = if (sym.isConstructor) sym.owner.decodedName else sym.nameString
       compose(
         // TODO: Annotations
         flagString(sym, flagMask & sym.flags),
         if (showKind) sym.keyString else "",
          sym.varianceString + name + infoString(seenAs) // don't force the symbol
        )
    }
  }

  /** Print the given type
   *
   *  @note Should be run on the presentation compiler thread (inside askOption).
   */
  def showType(tpe: Type): String = tpe match {
    case ErrorType                             => showErrorType()
    case WildcardType                          => showWildcardType()
    case NoType                                => showNoType()
    case NoPrefix                              => showNoPrefix()
    case bwt @ BoundedWildcardType(bounds)     => showBoundedWildcardType(bwt)
    case tt @ ThisType(sym)                    => showThisType(tt)
    case st @ SuperType(thistpe, supertpe)     => showSuperType(st)
    case st @ SingleType(pre, sym)             => showSingleType(st)
    case ct @ ConstantType(value)              => showConstantType(ct)
    case tref @ TypeRef(pre, sym, args)        => showTypeRef(tref)
    case refTpe @ RefinedType(parents, defs)   => showRefinedType(refTpe)
    case et @ ExistentialType(tparams, result) => showExistentialType(et)
    case at @ AnnotatedType(annots, tp)        => showAnnotatedType(at)
    case mt @ MethodType(params, resultType)   => showMethodType(mt)
    case NullaryMethodType(underlying)         => showType(underlying)
    case pt @ PolyType(tparams, result)        => showPolyType(pt)
    case tb @ TypeBounds(lo, hi)               => showTypeBounds(tb)
    case cit @ ClassInfoType(_, _, _)          => showClassInfoType(cit)

    case _ =>
      logger.info(s"Unknown type: $tpe of class: ${tpe.getClass}")
      tpe.toString // fallback
  }

  //////////////// Below are helper methods for each type case /////////////////

  def showMethodType(mt: MethodType): String = {
    import mt._

    val paramsStr = for (p <- params) yield s"${p.name}: ${showType(p.tpe)}"
    s"${paramsStr.mkString("(", ", ", ")")}${showType(resultType)}"
  }

  def showTypeRef(tpe: TypeRef): String = {
    import tpe._
    import definitions._

    val noArgsString = showPrefix(tpe)
    sym match {
      case RepeatedParamClass | JavaRepeatedParamClass => showType(args.head) + "*"
      case ByNameParamClass                            => "=> " + showType(args.head)
      case _ =>
        if (isFunctionTypeDirect(tpe))
          showFunction(tpe)
        else if (isTupleTypeDirect(tpe))
          showTuple(tpe)
        else if (sym.isAliasType && prefixChain.exists(_.termSymbol.isSynthetic) && (tpe ne dealias))
          "" + showType(dealias)
        else {
          val argsString = if (tpe.args.isEmpty) "" else s"[${showTypes(tpe.args).mkString(", ")}]"
          noArgsString + argsString
        }
    }
  }

  def showPrefix(tpe: TypeRef): String = {
    if (tpe.termSymbol.hasPackageFlag) ""
    else {
      val prefix = showType(tpe.pre)
      if (prefix != "") prefix + "." + tpe.sym.nameString
      else tpe.sym.nameString
    }
  }

  def showThisType(tt: ThisType) = "" // disable all types of the form Foo.this

  def showFunction(tpe: TypeRef): String = {
    import definitions._

    val noArgsString = s"${showSymbolName(tpe.sym)}"

    // Aesthetics: printing Function1 as T => R rather than (T) => R
    // ...but only if it's not a tuple, so ((T1, T2)) => R is distinguishable
    // from (T1, T2) => R.
    unspecializedTypeArgs(tpe) match {
      // See neg/t588 for an example which arrives here - printing
      // the type of a Function1 after erasure.
      case Nil => noArgsString
      case in :: out :: Nil if !isTupleTypeDirect(in) =>
        // A => B => C should be (A => B) => C or A => (B => C).
        // Also if A is byname, then we want (=> A) => B because => is right associative and => A => B
        // would mean => (A => B) which is a different type
        val in_s = if (isFunctionTypeDirect(in) || isByNameParamType(in)) s"(${showType(in)})" else showType(in)
        val out_s = if (isFunctionTypeDirect(out)) s"(${showType(out)})" else showType(out)
        in_s + " => " + out_s
      case xs =>
        showTypes(xs.init).mkString("(", ", ", ")") + " => " + showType(xs.last)
    }
  }

  def showTuple(tpe: TypeRef): String = {
    import tpe._

    args match {
      case Nil        => s"${showSymbolName(tpe.sym)}"
      case arg :: Nil => s"(${showType(arg)},)"
      case _          => showTypes(args).mkString("(", ", ", ")")
    }
  }

  def showSymbolName(sym: Symbol): String = {
    sym.name.toString
  }

  def showTypes(tpes: List[Type]): List[String] = tpes.map(showType)
  def showSymbolNames(syms: List[Symbol]): List[String] = syms.map(showSymbolName)

  def showExistentialType(tpe: ExistentialType) = {
    import tpe._

    def clauses =
      quantified map (_.existentialToString) mkString (" forSome { ", "; ", " }")

    def wildcardArgsString(qset: Set[Symbol], args: List[Type]): List[String] = args map {
      case TypeRef(_, sym, _) if (qset contains sym) =>
        "_" + sym.infoString(sym.info)
      case arg =>
        showType(arg)
    }

    underlying match {
      case TypeRef(pre, sym, args) if isRepresentableWithWildcards =>
        "" + showType(TypeRef(pre, sym, Nil)) + wildcardArgsString(quantified.toSet, args).mkString("[", ", ", "]")
      case MethodType(_, _) | NullaryMethodType(_) | PolyType(_, _) =>
        "(" + showType(underlying) + ")" + clauses
      case _ =>
        showType(underlying) + clauses
    }
  }

  def showRefinedType(refType: RefinedType): String = {
    s"${showTypes(refType.parents).mkString(" with ")} { .. }"
  }

  def showPolyType(pt: PolyType): String = {
    showSymbolNames(pt.typeParams).mkString("[", ", ", "]") + showType(pt.resultType)
  }

  def showTypeBounds(tb: TypeBounds): String = {
    import tb._

    val emptyLowerBound = (lo.typeSymbolDirect eq definitions.NothingClass) || lo.isWildcard
    val emptyHiBound = (hi.typeSymbolDirect eq definitions.AnyClass) || hi.isWildcard

    if (emptyHiBound && emptyLowerBound) ""
    else if (emptyLowerBound) s" <: ${showType(hi)}"
    else if (emptyHiBound) s" >: ${showType(lo)}"
    else s" >: ${showType(lo)} <: ${showType(hi)}"
  }

  def showClassInfoType(cit: ClassInfoType) = {
    import cit._
    import definitions._

    def formattedToString = parents.mkString("\n        with ") + scopeString
    def scopeString: String = {
      fullyInitializeScope(decls)
        .map(sym => defString(sym, Flags.ExplicitFlags)())
        .mkString(" {\n  ", "\n  ", "\n}")
    }

    if (decls.size > 1) formattedToString else parentsString(parents)
  }

  protected def compose(str: String*) =
    str.filter(_ != "").mkString(" ")

  def showSingleType(st: SingleType) = {
    val ending = ""
    val skippable = (st.sym.hasPackageFlag || st.sym.isPackageObject || st.sym == definitions.PredefModule)
    val name = if (skippable) "" else st.sym.nameString
    showType(st.pre) + name + ending
  }

  def showErrorType(): String =
    "<error>"

  def showWildcardType(): String =
    "_"

  def showBoundedWildcardType(bwt: BoundedWildcardType): String =
    "?" + showType(bwt.bounds)

  def showNoType(): String =
    ""

  def showNoPrefix(): String =
    ""

  def showSuperType(st: SuperType): String = {
    s"${showType(st.thistpe)}.super[${showType(st.supertpe)}]"
  }

  def showConstantType(ct: ConstantType): String =
    s"${ct.value}.type"

  def showAnnotatedType(at: AnnotatedType) = {
    def annotString(a: AnnotationInfo) = {
      val args = a.args.mkString("(", ", ", ")")
      s"showType(a.atp)$args"
    }
    s"${showType(at.underlying)} @${at.annotations.map(annotString)}"
  }

}


text:
import create_all_qc
import extract_data_multiscan
import create_fsl_model
import extract_parameters
from utils import *
from .extract_data import run
from .datasource import create_anat_datasource
from .datasource import create_func_datasource
from .datasource import create_roi_mask_dataflow
from .datasource import create_grp_analysis_dataflow
from .datasource import create_spatial_map_dataflow
from .configuration import Configuration


text:
@interface MOBProjectionEPSG4082 : MOBProjection

@end


text:
package message

// TODO: some types in this file will need to be made public at some time.
// Documentation and method names will reflect this by using the exported name.

import (
	"golang.org/x/text/language"
	"golang.org/x/text/message/catalog"
)

// DefaultCatalog is used by SetString.
var DefaultCatalog *catalog.Catalog = defaultCatalog

var defaultCatalog = catalog.New()

// SetString calls SetString on the initial default Catalog.
func SetString(tag language.Tag, key string, msg string) error {
	return defaultCatalog.SetString(tag, key, msg)
}

// Set calls Set on the initial default Catalog.
func Set(tag language.Tag, key string, msg ...catalog.Message) error {
	return defaultCatalog.Set(tag, key, msg...)
}


text:
<?php

namespace LaravelDoctrine\ORM\Configuration\MetaData;

use Doctrine\Persistence\Mapping\Driver\PHPDriver;
use Illuminate\Support\Arr;

class Php extends MetaData
{
    /**
     * @param array $settings
     *
     * @return \Doctrine\Persistence\Mapping\Driver\MappingDriver
     */
    public function resolve(array $settings = [])
    {
        return new PHPDriver(
            Arr::get($settings, 'paths')
        );
    }
}


text:
import React from 'react';

import { storiesOf } from '@storybook/react';

import { LatestFromSection } from './LatestFromSection';

import analyticsStream from '../../fixtures/analytics-actions/analytics-actions';
import { select } from '@storybook/addon-knobs';
import { latestFromSection } from './fixtures/fixtures';

storiesOf('Typescript Component/Article Extras', module).add(
  'Latest from Section',
  () => {
    const sectionIndex = select(
      'Section',
      latestFromSection.reduce(
        (prev, next, index) => ({ ...prev, [next.section]: index }),
        {}
      ),
      4
    );

    return (
      <LatestFromSection
        key={sectionIndex}
        analyticsStream={analyticsStream}
        latestFromSection={latestFromSection[sectionIndex]}
      />
    );
  }
);