text:
package ru.job4j.battlegame.units.human;

import ru.job4j.battlegame.Squad;
import ru.job4j.battlegame.units.AbstractUnit;

import java.util.Random;

/**
 * Mage.
 *
 * @author Ruzhev Alexander
 * @since on 24.06.2017.
 */
public class Mage extends AbstractUnit {
    /**
     * Name.
     */
    private static final String NAME = "human mage";
    /**
     * Damage in magic.
     */
    private double damage = 4;

    /**
     * Constructor.
     */
    public Mage() {
        super(NAME);
    }

    /**
     * First spell - improved units.
     *
     * @param unit improved unit
     */
    @Override
    public void firstAction(AbstractUnit unit) {
        printToConsole(unit, "cast improvement");
        unit.setImproved(true);
    }

    /**
     * Second - magic attack.
     *
     * @param unit attacked unit
     */
    @Override
    public void secondAction(AbstractUnit unit) {
        double realDamage = getImproved() ? damage * 1.5 / getDisease() : damage / getDisease();
        printToConsole(unit, realDamage, "attacks with magic");
        unit.toDamage(realDamage);
        if (getDisease() != 1) {
            toDisease();
        }
    }

    /**
     * Select random action.
     *
     * @param lightSquad - ally squad
     * @param darkSquad  - enemy squad
     */
    @Override
    public void randomAction(Squad lightSquad, Squad darkSquad) {
        Random random = new Random();
        if (random.nextInt(50) < 25) {
            if (lightSquad.getNormalIndex() > 0) {
                AbstractUnit objAction = lightSquad.getNormalUnits()[random.nextInt(lightSquad.getNormalIndex())];
                firstAction(objAction);
            } else {
                System.out.println("spell break");
            }
        } else {
            AbstractUnit objAction = darkSquad.getSquad()[random.nextInt(darkSquad.getSquad().length)];
            secondAction(objAction);
        }
    }

    /**
     * Create new clone mage.
     *
     * @return new clone
     */
    @Override
    public AbstractUnit clone() {
        return new Mage();
    }

}

redpajama_set_name: RedPajamaGithub


text:
package mat.client.shared;

import com.google.gwt.i18n.client.HasDirection;
import com.google.gwt.user.cellview.client.AbstractPager;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.view.client.HasRows;
import com.google.gwt.view.client.Range;

/**
 * A pager that displays the current range without any controls to change the
 * range.
 */
public class RangeLabelPager extends AbstractPager {

  /**
   * The label that shows the current range.
   */
  private final HTML label = new HTML();

  /**
   * Construct a new {@link RangeLabelPager}.
   */
  public RangeLabelPager() {
    initWidget(label);
  }

  /* (non-Javadoc)
   * @see com.google.gwt.user.cellview.client.AbstractPager#onRangeOrRowCountChanged()
   */
  @Override
  protected void onRangeOrRowCountChanged() {
    HasRows display = getDisplay();
    Range range = display.getVisibleRange();
    int start = range.getStart();
    int end = start + range.getLength();
    label.setText("( "+start + " - " + end + " ) of " + display.getRowCount(),
        HasDirection.Direction.LTR);
  }
}


text:
package com.hubspot.mesos;

public enum SingularityContainerType {
  MESOS, DOCKER
}


text:
FFI structs and constants for linux's input subsystem found in linux/input.h

Have a look at the [Libevdev](https://github.com/christopheraue/ruby-libevdev)
gem for an easier to use interface to the input subsystem.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'linux_input'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install linux_input

## Usage

```ruby
require 'linux_input'
```

All constants and structures are accessible through the LinuxInput module.

snake_case C structure names are transformed into CamelCase Ruby constant names:

```ruby
LinuxInput::InputEvent   # input_event struct
LinuxInput::FfEffect     # ff_effect struct
# and so on ...
```

Constant names are left untouched:

```ruby
LinuxInput::EV_KEY     # => 0x01 (key event bit)
LinuxInput::KEY_A      # => 30 (key code of the a key)
# and so on ...
```

Ioctl constants and macros:

```ruby
LinuxInput::EVIOCGID
LinuxInput::EVIOCGNAME(len)
# and so on ...
```

Mapping a received event to the input_event struct:

```ruby
file = File.open('/dev/input/event0')

loop do
    raw_event = file.read LinuxInput::InputEvent.size
    raw_event_ptr = FFI::MemoryPointer.from_string(raw_event)
    event = LinuxInput::InputEvent.new(raw_event_ptr)
    puts Time.at(event[:time][:tv_sec])
    puts event[:type]
    puts event[:code]
    puts event[:value]
end
```

## (Re-)Compiling the interface on a linux machine

Reads your local linux/input.h

```
$ rake ffi:generate
```


text:
namespace ROC
{

class Camera;
class Light;
class Model;
class RenderTarget;
class Shader;

class Scene final : public Element, public virtual IScene
{
    Camera *m_camera;
    RenderTarget *m_renderTarget;
    Shader *m_shader;
    std::vector<Light*> m_lights;
    std::vector<Model*> m_models;

    bool m_active;

    Scene(const Scene &that) = delete;
    Scene& operator=(const Scene &that) = delete;

    static bool SceneModelSorting(const Model *f_modelA, const Model *f_modelB);

    // ROC::Element
    void OnChildRemoved(Element *f_child) override;

    // ROC::IScene
    bool SetICamera(ICamera *f_cam);
    ICamera* GetICamera() const;
    bool SetIRenderTarget(IRenderTarget *f_rt);
    IRenderTarget* GetIRenderTarget() const;
    bool SetIShader(IShader *f_shader);
    bool RemoveIShader();
    IShader* GetIShader() const;
    bool AddILight(ILight *f_light);
    bool RemoveILight(ILight *f_light);
    bool HasILight(ILight *f_light) const;
    bool AddIModel(IModel *f_model);
    bool RemoveIModel(IModel *f_model);
    bool HasIModel(IModel *f_model) const;
public:
    bool SetCamera(Camera *f_cam);
    bool RemoveCamera();
    Camera* GetCamera() const;

    bool SetRenderTarget(RenderTarget *f_rt);
    bool RemoveRenderTarget();
    RenderTarget* GetRenderTarget() const;

    bool AddLight(Light *f_light);
    bool RemoveLight(Light *f_light);
    bool HasLight(Light *f_light) const;
    size_t GetLightsCount() const;

    bool SetShader(Shader *f_shader);
    bool RemoveShader();
    Shader* GetShader() const;

    bool AddModel(Model *f_model);
    bool RemoveModel(Model *f_model);
    bool HasModel(Model *f_model) const;

    bool IsActive() const;
    bool IsRenderValid() const;
protected:
    Scene();
    ~Scene();

    const std::vector<Light*>& GetLights() const;
    const std::vector<Model*>& GetModels() const;

    void Enable();
    void Disable();

    friend class ElementManager;
    friend class RenderManager;
};

}


text:
namespace v8 {
namespace internal {

RUNTIME_FUNCTION(Runtime_CheckIsBootstrapping) {
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 0);
  RUNTIME_ASSERT(isolate->bootstrapper()->IsActive());
  return isolate->heap()->undefined_value();
}

RUNTIME_FUNCTION(Runtime_ExportFromRuntime) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 1);
  CONVERT_ARG_HANDLE_CHECKED(JSObject, container, 0);
  RUNTIME_ASSERT(isolate->bootstrapper()->IsActive());
  JSObject::NormalizeProperties(container, KEEP_INOBJECT_PROPERTIES, 10,
                                "ExportFromRuntime");
  Bootstrapper::ExportFromRuntime(isolate, container);
  JSObject::MigrateSlowToFast(container, 0, "ExportFromRuntime");
  return *container;
}

RUNTIME_FUNCTION(Runtime_ExportExperimentalFromRuntime) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 1);
  CONVERT_ARG_HANDLE_CHECKED(JSObject, container, 0);
  RUNTIME_ASSERT(isolate->bootstrapper()->IsActive());
  JSObject::NormalizeProperties(container, KEEP_INOBJECT_PROPERTIES, 10,
                                "ExportExperimentalFromRuntime");
  Bootstrapper::ExportExperimentalFromRuntime(isolate, container);
  JSObject::MigrateSlowToFast(container, 0, "ExportExperimentalFromRuntime");
  return *container;
}

RUNTIME_FUNCTION(Runtime_InstallToContext) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 1);
  CONVERT_ARG_HANDLE_CHECKED(JSArray, array, 0);
  RUNTIME_ASSERT(array->HasFastElements());
  RUNTIME_ASSERT(isolate->bootstrapper()->IsActive());
  Handle<Context> native_context = isolate->native_context();
  Handle<FixedArray> fixed_array(FixedArray::cast(array->elements()));
  int length = Smi::cast(array->length())->value();
  for (int i = 0; i < length; i += 2) {
    RUNTIME_ASSERT(fixed_array->get(i)->IsString());
    Handle<String> name(String::cast(fixed_array->get(i)));
    RUNTIME_ASSERT(fixed_array->get(i + 1)->IsJSObject());
    Handle<JSObject> object(JSObject::cast(fixed_array->get(i + 1)));
    int index = Context::ImportedFieldIndexForName(name);
    if (index == Context::kNotFound) {
      index = Context::IntrinsicIndexForName(name);
    }
    RUNTIME_ASSERT(index != Context::kNotFound);
    native_context->set(index, *object);
  }
  return isolate->heap()->undefined_value();
}

RUNTIME_FUNCTION(Runtime_Throw) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 1);
  return isolate->Throw(args[0]);
}

RUNTIME_FUNCTION(Runtime_ReThrow) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 1);
  return isolate->ReThrow(args[0]);
}

RUNTIME_FUNCTION(Runtime_ThrowStackOverflow) {
  SealHandleScope shs(isolate);
  DCHECK_LE(0, args.length());
  return isolate->StackOverflow();
}

RUNTIME_FUNCTION(Runtime_UnwindAndFindExceptionHandler) {
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 0);
  return isolate->UnwindAndFindHandler();
}

RUNTIME_FUNCTION(Runtime_PromoteScheduledException) {
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 0);
  return isolate->PromoteScheduledException();
}

RUNTIME_FUNCTION(Runtime_ThrowReferenceError) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 1);
  CONVERT_ARG_HANDLE_CHECKED(Object, name, 0);
  THROW_NEW_ERROR_RETURN_FAILURE(
      isolate, NewReferenceError(MessageTemplate::kNotDefined, name));
}

RUNTIME_FUNCTION(Runtime_NewTypeError) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 2);
  CONVERT_INT32_ARG_CHECKED(template_index, 0);
  CONVERT_ARG_HANDLE_CHECKED(Object, arg0, 1);
  auto message_template =
      static_cast<MessageTemplate::Template>(template_index);
  return *isolate->factory()->NewTypeError(message_template, arg0);
}

RUNTIME_FUNCTION(Runtime_NewReferenceError) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 2);
  CONVERT_INT32_ARG_CHECKED(template_index, 0);
  CONVERT_ARG_HANDLE_CHECKED(Object, arg0, 1);
  auto message_template =
      static_cast<MessageTemplate::Template>(template_index);
  return *isolate->factory()->NewReferenceError(message_template, arg0);
}

RUNTIME_FUNCTION(Runtime_NewSyntaxError) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 2);
  CONVERT_INT32_ARG_CHECKED(template_index, 0);
  CONVERT_ARG_HANDLE_CHECKED(Object, arg0, 1);
  auto message_template =
      static_cast<MessageTemplate::Template>(template_index);
  return *isolate->factory()->NewSyntaxError(message_template, arg0);
}

RUNTIME_FUNCTION(Runtime_ThrowIllegalInvocation) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 0);
  THROW_NEW_ERROR_RETURN_FAILURE(
      isolate, NewTypeError(MessageTemplate::kIllegalInvocation));
}

RUNTIME_FUNCTION(Runtime_ThrowIteratorResultNotAnObject) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 1);
  CONVERT_ARG_HANDLE_CHECKED(Object, value, 0);
  THROW_NEW_ERROR_RETURN_FAILURE(
      isolate,
      NewTypeError(MessageTemplate::kIteratorResultNotAnObject, value));
}

RUNTIME_FUNCTION(Runtime_ThrowApplyNonFunction) {
  HandleScope scope(isolate);
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
  Handle<String> type = Object::TypeOf(isolate, object);
  THROW_NEW_ERROR_RETURN_FAILURE(
      isolate, NewTypeError(MessageTemplate::kApplyNonFunction, object, type));
}

RUNTIME_FUNCTION(Runtime_PromiseRejectEvent) {
  DCHECK(args.length() == 3);
  HandleScope scope(isolate);
  CONVERT_ARG_HANDLE_CHECKED(JSObject, promise, 0);
  CONVERT_ARG_HANDLE_CHECKED(Object, value, 1);
  CONVERT_BOOLEAN_ARG_CHECKED(debug_event, 2);
  if (debug_event) isolate->debug()->OnPromiseReject(promise, value);
  Handle<Symbol> key = isolate->factory()->promise_has_handler_symbol();
  // Do not report if we actually have a handler.
  if (JSReceiver::GetDataProperty(promise, key)->IsUndefined()) {
    isolate->ReportPromiseReject(promise, value,
                                 v8::kPromiseRejectWithNoHandler);
  }
  return isolate->heap()->undefined_value();
}

RUNTIME_FUNCTION(Runtime_PromiseRevokeReject) {
  DCHECK(args.length() == 1);
  HandleScope scope(isolate);
  CONVERT_ARG_HANDLE_CHECKED(JSObject, promise, 0);
  Handle<Symbol> key = isolate->factory()->promise_has_handler_symbol();
  // At this point, no revocation has been issued before
  RUNTIME_ASSERT(JSReceiver::GetDataProperty(promise, key)->IsUndefined());
  isolate->ReportPromiseReject(promise, Handle<Object>(),
                               v8::kPromiseHandlerAddedAfterReject);
  return isolate->heap()->undefined_value();
}

RUNTIME_FUNCTION(Runtime_StackGuard) {
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 0);

  // First check if this is a real stack overflow.
  StackLimitCheck check(isolate);
  if (check.JsHasOverflowed()) {
    return isolate->StackOverflow();
  }

  return isolate->stack_guard()->HandleInterrupts();
}

RUNTIME_FUNCTION(Runtime_Interrupt) {
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 0);
  return isolate->stack_guard()->HandleInterrupts();
}

RUNTIME_FUNCTION(Runtime_AllocateInNewSpace) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 1);
  CONVERT_SMI_ARG_CHECKED(size, 0);
  RUNTIME_ASSERT(IsAligned(size, kPointerSize));
  RUNTIME_ASSERT(size > 0);
  RUNTIME_ASSERT(size <= Page::kMaxRegularHeapObjectSize);
  return *isolate->factory()->NewFillerObject(size, false, NEW_SPACE);
}

RUNTIME_FUNCTION(Runtime_AllocateInTargetSpace) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 2);
  CONVERT_SMI_ARG_CHECKED(size, 0);
  CONVERT_SMI_ARG_CHECKED(flags, 1);
  RUNTIME_ASSERT(IsAligned(size, kPointerSize));
  RUNTIME_ASSERT(size > 0);
  RUNTIME_ASSERT(size <= Page::kMaxRegularHeapObjectSize);
  bool double_align = AllocateDoubleAlignFlag::decode(flags);
  AllocationSpace space = AllocateTargetSpace::decode(flags);
  return *isolate->factory()->NewFillerObject(size, double_align, space);
}

// Collect the raw data for a stack trace.  Returns an array of 4
// element segments each containing a receiver, function, code and
// native code offset.
RUNTIME_FUNCTION(Runtime_CollectStackTrace) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 2);
  CONVERT_ARG_HANDLE_CHECKED(JSReceiver, error_object, 0);
  CONVERT_ARG_HANDLE_CHECKED(Object, caller, 1);

  if (!isolate->bootstrapper()->IsActive()) {
    // Optionally capture a more detailed stack trace for the message.
    RETURN_FAILURE_ON_EXCEPTION(
        isolate, isolate->CaptureAndSetDetailedStackTrace(error_object));
    // Capture a simple stack trace for the stack property.
    RETURN_FAILURE_ON_EXCEPTION(
        isolate, isolate->CaptureAndSetSimpleStackTrace(error_object, caller));
  }
  return isolate->heap()->undefined_value();
}

RUNTIME_FUNCTION(Runtime_MessageGetStartPosition) {
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 1);
  CONVERT_ARG_CHECKED(JSMessageObject, message, 0);
  return Smi::FromInt(message->start_position());
}

RUNTIME_FUNCTION(Runtime_MessageGetScript) {
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 1);
  CONVERT_ARG_CHECKED(JSMessageObject, message, 0);
  return message->script();
}

RUNTIME_FUNCTION(Runtime_FormatMessageString) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 4);
  CONVERT_INT32_ARG_CHECKED(template_index, 0);
  CONVERT_ARG_HANDLE_CHECKED(String, arg0, 1);
  CONVERT_ARG_HANDLE_CHECKED(String, arg1, 2);
  CONVERT_ARG_HANDLE_CHECKED(String, arg2, 3);
  Handle<String> result;
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
      isolate, result,
      MessageTemplate::FormatMessage(template_index, arg0, arg1, arg2));
  isolate->native_context()->IncrementErrorsThrown();
  return *result;
}

#define CALLSITE_GET(NAME, RETURN)                          \
  RUNTIME_FUNCTION(Runtime_CallSite##NAME##RT) {            \
    HandleScope scope(isolate);                             \
    DCHECK(args.length() == 1);                             \
    CONVERT_ARG_HANDLE_CHECKED(JSObject, call_site_obj, 0); \
    Handle<String> result;                                  \
    CallSite call_site(isolate, call_site_obj);             \
    RUNTIME_ASSERT(call_site.IsValid());                    \
    return RETURN(call_site.NAME(), isolate);               \
  }

static inline Object* ReturnDereferencedHandle(Handle<Object> obj,
                                               Isolate* isolate) {
  return *obj;
}

static inline Object* ReturnPositiveNumberOrNull(int value, Isolate* isolate) {
  if (value >= 0) return *isolate->factory()->NewNumberFromInt(value);
  return isolate->heap()->null_value();
}

static inline Object* ReturnBoolean(bool value, Isolate* isolate) {
  return isolate->heap()->ToBoolean(value);
}

CALLSITE_GET(GetFileName, ReturnDereferencedHandle)
CALLSITE_GET(GetFunctionName, ReturnDereferencedHandle)
CALLSITE_GET(GetScriptNameOrSourceUrl, ReturnDereferencedHandle)
CALLSITE_GET(GetMethodName, ReturnDereferencedHandle)
CALLSITE_GET(GetLineNumber, ReturnPositiveNumberOrNull)
CALLSITE_GET(GetColumnNumber, ReturnPositiveNumberOrNull)
CALLSITE_GET(IsNative, ReturnBoolean)
CALLSITE_GET(IsToplevel, ReturnBoolean)
CALLSITE_GET(IsEval, ReturnBoolean)
CALLSITE_GET(IsConstructor, ReturnBoolean)

#undef CALLSITE_GET

RUNTIME_FUNCTION(Runtime_IS_VAR) {
  UNREACHABLE();  // implemented as macro in the parser
  return NULL;
}

namespace {

bool ComputeLocation(Isolate* isolate, MessageLocation* target) {
  JavaScriptFrameIterator it(isolate);
  if (!it.done()) {
    JavaScriptFrame* frame = it.frame();
    JSFunction* fun = frame->function();
    Object* script = fun->shared()->script();
    if (script->IsScript() &&
        !(Script::cast(script)->source()->IsUndefined())) {
      Handle<Script> casted_script(Script::cast(script));
      // Compute the location from the function and the relocation info of the
      // baseline code. For optimized code this will use the deoptimization
      // information to get canonical location information.
      List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
      it.frame()->Summarize(&frames);
      FrameSummary& summary = frames.last();
      int pos = summary.abstract_code()->SourcePosition(summary.code_offset());
      *target = MessageLocation(casted_script, pos, pos + 1, handle(fun));
      return true;
    }
  }
  return false;
}

Handle<String> RenderCallSite(Isolate* isolate, Handle<Object> object) {
  MessageLocation location;
  if (ComputeLocation(isolate, &location)) {
    Zone zone(isolate->allocator());
    base::SmartPointer<ParseInfo> info(
        location.function()->shared()->is_function()
            ? new ParseInfo(&zone, location.function())
            : new ParseInfo(&zone, location.script()));
    if (Parser::ParseStatic(info.get())) {
      CallPrinter printer(isolate, location.function()->shared()->IsBuiltin());
      const char* string = printer.Print(info->literal(), location.start_pos());
      if (strlen(string) > 0) {
        return isolate->factory()->NewStringFromAsciiChecked(string);
      }
    } else {
      isolate->clear_pending_exception();
    }
  }
  return Object::TypeOf(isolate, object);
}

}  // namespace

RUNTIME_FUNCTION(Runtime_ThrowCalledNonCallable) {
  HandleScope scope(isolate);
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
  Handle<String> callsite = RenderCallSite(isolate, object);
  THROW_NEW_ERROR_RETURN_FAILURE(
      isolate, NewTypeError(MessageTemplate::kCalledNonCallable, callsite));
}

RUNTIME_FUNCTION(Runtime_ThrowConstructedNonConstructable) {
  HandleScope scope(isolate);
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
  Handle<String> callsite = RenderCallSite(isolate, object);
  THROW_NEW_ERROR_RETURN_FAILURE(
      isolate, NewTypeError(MessageTemplate::kNotConstructor, callsite));
}

RUNTIME_FUNCTION(Runtime_ThrowDerivedConstructorReturnedNonObject) {
  HandleScope scope(isolate);
  DCHECK_EQ(0, args.length());
  THROW_NEW_ERROR_RETURN_FAILURE(
      isolate, NewTypeError(MessageTemplate::kDerivedConstructorReturn));
}

// ES6 section 7.3.17 CreateListFromArrayLike (obj)
RUNTIME_FUNCTION(Runtime_CreateListFromArrayLike) {
  HandleScope scope(isolate);
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
  Handle<FixedArray> result;
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
      isolate, result,
      Object::CreateListFromArrayLike(isolate, object, ElementTypes::kAll));
  return *result;
}

RUNTIME_FUNCTION(Runtime_IncrementUseCounter) {
  HandleScope scope(isolate);
  DCHECK_EQ(1, args.length());
  CONVERT_SMI_ARG_CHECKED(counter, 0);
  isolate->CountUsage(static_cast<v8::Isolate::UseCounterFeature>(counter));
  return isolate->heap()->undefined_value();
}

RUNTIME_FUNCTION(Runtime_GetOrdinaryHasInstance) {
  HandleScope scope(isolate);
  DCHECK_EQ(0, args.length());

  return isolate->native_context()->ordinary_has_instance();
}

RUNTIME_FUNCTION(Runtime_GetAndResetRuntimeCallStats) {
  HandleScope scope(isolate);
  DCHECK_EQ(0, args.length());
  std::stringstream stats_stream;
  isolate->counters()->runtime_call_stats()->Print(stats_stream);
  Handle<String> result =
      isolate->factory()->NewStringFromAsciiChecked(stats_stream.str().c_str());
  isolate->counters()->runtime_call_stats()->Reset();
  return *result;
}

}  // namespace internal
}  // namespace v8


text:
//
//  SMReferralsManager.h
//  SessionM
//
//  Copyright © 2016 SessionM. All rights reserved.
//

#ifndef __SM_REFERRALS_MANAGER__
#define __SM_REFERRALS_MANAGER__

#import "SMBaseDelegate.h"
#import "SMReferralError.h"
#import "SMReferralRequest.h"
#import "SMReferral.h"

NS_ASSUME_NONNULL_BEGIN

/*!
 @const SM_REFERRALS_MANAGER_NOTIFICATION_ERRORS_KEY
 @abstract Used to access an NSArray of @link SMReferralError @/link objects from a failed Referrals API notification's userInfo property.
 */
extern NSString *const SM_REFERRALS_MANAGER_NOTIFICATION_ERRORS_KEY NS_SWIFT_NAME(kReferralErrors);

/*!
 @const SM_REFERRALS_MANAGER_REQUEST_DID_FAIL_NOTIFICATION
 @abstract Notifies observers that an API request failed.
 @discussion An @link SMError @/link object containing information about why the request failed can be accessed from the notification's userInfo property with the @link SM_MANAGER_NOTIFICATION_ERROR_KEY @/link key.
 */
extern NSString *const SM_REFERRALS_MANAGER_REQUEST_DID_FAIL_NOTIFICATION NS_SWIFT_NAME(referralsRequestFailureNotification);
/*!
 @const SM_REFERRALS_MANAGER_VALIDATION_DID_FAIL_NOTIFICATION
 @abstract Notifies observers that a Referrals API validation failed.
 @discussion An @link SMError @/link object containing information about why the validation failed can be accessed from the notification's userInfo property with the @link SM_MANAGER_NOTIFICATION_ERROR_KEY @/link key.
 */
extern NSString *const SM_REFERRALS_MANAGER_VALIDATION_DID_FAIL_NOTIFICATION NS_SWIFT_NAME(referralsValidationFailureNotification);

/*!
 @const SM_REFERRALS_MANAGER_DID_SEND_REFERRALS_NOTIFICATION
 @abstract Notifies observers that referrals were sent.
 @discussion An NSArray of successfully sent @link SMReferral @/link objects can be accessed from the notification's userInfo property with the @link SM_MANAGER_NOTIFICATION_DATA_KEY @/link key. If any referral requests were denied, then an NSArray of @link SMReferralError @/link objects containing information about why a particular referral was denied can be accessed with the @link SM_REFERRALS_MANAGER_NOTIFICATION_ERRORS_KEY @/link key - and a general @link SMError @/link object can be accessed with the @link SM_MANAGER_NOTIFICATION_ERROR_KEY @/link key.
 */
extern NSString *const SM_REFERRALS_MANAGER_DID_SEND_REFERRALS_NOTIFICATION NS_SWIFT_NAME(sentReferralsNotification);
/*!
 @const SM_REFERRALS_MANAGER_DID_FETCH_REFERRALS_NOTIFICATION
 @abstract Notifies observers that referrals sent by the current user were fetched.
 @discussion An NSArray of @link SMReferral @/link objects can be accessed from the notification's userInfo property with the @link SM_MANAGER_NOTIFICATION_DATA_KEY @/link key.
 */
extern NSString *const SM_REFERRALS_MANAGER_DID_FETCH_REFERRALS_NOTIFICATION NS_SWIFT_NAME(fetchedReferralsNotification);

/*!
 @protocol SMReferralsDelegate
 @abstract Defines callbacks for @link SMReferralsManager @/link methods.
 */
@protocol SMReferralsDelegate <SMBaseDelegate>

@optional

/*!
 @abstract Notifies delegate that referral requests were created and sent.
 @discussion This method is called in response to @link sendReferrals: @/link.
 @param referrals The newly created referrals.
 @param referralErrors Errors for individual referrals.
 @param error Error for entire referral request.
 @deprecated Use block methods instead.
 */
- (void)didSendReferrals:(NSArray<SMReferral *> * _Nullable)referrals referralErrors:(NSArray<SMReferralError *> * _Nullable)referralErrors error:(SMError * _Nullable)error __attribute__((deprecated("Use block methods instead"))) NS_SWIFT_NAME(didSendReferrals(_:referralErrors:error:));
/*!
 @abstract Notifies delegate that the current user's sent referrals were fetched.
 @discussion This method is called in response to @link fetchReferrals @/link.
 @param referrals Referrals that have been sent by the current user.
 @deprecated Use block methods instead.
 */
- (void)didFetchReferrals:(NSArray<SMReferral *> *)referrals __attribute__((deprecated("Use block methods instead"))) NS_SWIFT_NAME(didFetchReferrals(_:));
/*!
 @abstract Notifies delegate that one of the current user's sent referrals was fetched.
 @discussion This method is called in response to @link fetchReferralWithID: @/link.
 @param referral A referral that has been sent by the current user.
 @deprecated Use block methods instead.
 */
- (void)didFetchSingleReferral:(SMReferral *)referral __attribute__((deprecated("Use block methods instead"))) NS_SWIFT_NAME(didFetchSingleReferral(_:));

@end

/*!
 @typedef didSendReferrals
 @abstract Completion handler block type for @link sendReferrals:completionHandler: @/link.
 */
typedef void (^didSendReferrals)(NSArray<SMReferral *>* _Nullable successfulReferrals, NSArray<SMReferralError *>* _Nullable referralErrors, SMError * _Nullable error) NS_SWIFT_NAME(SendReferralsCompletionHandler);
/*!
 @typedef didFetchReferrals
 @abstract Completion handler block type for @link fetchReferralsWithCompletionHandler: @/link.
 */
typedef void (^didFetchReferrals)(NSArray<SMReferral *>* _Nullable referrals, SMError * _Nullable error) NS_SWIFT_NAME(FetchReferralsCompletionHandler);
/*!
 @typedef didFetchSingleReferral
 @abstract Completion handler block type for @link fetchReferralWithID:completionHandler: @/link.
 */
typedef void (^didFetchSingleReferral)(SMReferral * _Nullable referral, SMError * _Nullable error) NS_SWIFT_NAME(FetchSingleReferralCompletionHandler);

/*!
 @class SMReferralsManager
 @abstract This API manager contains methods for sending and fetching registration referral requests.
 */
@interface SMReferralsManager : NSObject

/*!
 @property delegate
 @abstract Object that implements @link SMReferralsDelegate @/link callbacks.
 */
@property(nonatomic, weak) id<SMReferralsDelegate> _Nullable delegate;
/*!
 @property referrals
 @abstract Referrals that have been sent by the current user.
 @discussion This property is updated in response to a successful @link fetchReferralsWithCompletionHandler: @/link call.
 */
@property(nonatomic, strong, readonly) NSArray<SMReferral *> *referrals;

/*!
 @abstract Makes a request to send the specified referrals.
 @discussion @link didSendReferrals:referralErrors:error: @/link is called in response to this method.
 @param referrals The referrals request to be sent.
 @result BOOL indicating whether the request will be sent.
 @deprecated Use @link sendReferrals:completionHandler: @/link.
 */
- (BOOL)sendReferrals:(SMReferralsRequest *)referrals __attribute__((deprecated("Use sendReferrals:completionHandler:"))) NS_SWIFT_NAME(sendReferrals(_:));
/*!
 @abstract Makes a request to send the specified referrals.
 @param referrals The referrals request to be sent.
 @param completionHandler The block to execute after the request is processed.
 @result BOOL indicating whether the request will be sent.
 */
- (BOOL)sendReferrals:(SMReferralsRequest *)referrals completionHandler:(didSendReferrals)completionHandler NS_SWIFT_NAME(sendReferrals(_:completionHandler:));
/*!
 @abstract Makes a request to update @link referrals @/link with the current user's referrals.
 @discussion @link didFetchReferrals: @/link is called in response to this method.
 @result BOOL indicating whether the request will be sent.
 @deprecated Use @link fetchReferralsWithCompletionHandler: @/link.
 */
- (BOOL)fetchReferrals __attribute__((deprecated("Use fetchReferralsWithCompletionHandler:")));
/*!
 @abstract Makes a request to update @link referrals @/link with the current user's referrals.
 @param completionHandler The block to execute after the request is processed.
 @result BOOL indicating whether the request will be sent.
 */
- (BOOL)fetchReferralsWithCompletionHandler:(didFetchReferrals)completionHandler NS_SWIFT_NAME(fetchReferrals(completionHandler:));
/*!
 @abstract Makes a request to fetch the referral with the specified identifier.
 @discussion @link didFetchReferrals: @/link is called in response to this method.
 @param referralID The identifier of the referral to be fetched.
 @result BOOL indicating whether the request will be sent.
 @deprecated Use @link fetchReferralWithID:completionHandler: @/link.
 */
- (BOOL)fetchReferralWithID:(NSString *)referralID __attribute__((deprecated("Use fetchReferralWithID:completionHandler:"))) NS_SWIFT_NAME(fetchReferral(havingID:));
/*!
 @abstract Makes a request to fetch the referral with the specified identifier.
 @param referralID The identifier of the referral to be fetched.
 @param completionHandler The block to execute after the request is processed.
 @result BOOL indicating whether the request will be sent.
 */
- (BOOL)fetchReferralWithID:(NSString *)referralID completionHandler:(didFetchSingleReferral)completionHandler NS_SWIFT_NAME(fetchReferral(havingID:completionHandler:));

@end

NS_ASSUME_NONNULL_END

#endif /* __SM_REFERRALS_MANAGER__ */


text:
namespace rpcz {
namespace {
static bool g_interrupted = false;
void signal_handler(int signal_value) {
  g_interrupted = true;
}
}  // unnamed namespace

reactor::reactor() : should_quit_(false) {
};

reactor::~reactor() {
  delete_container_pair_pointers(sockets_.begin(), sockets_.end());
  for (closure_run_map::const_iterator it = closure_run_map_.begin();
       it != closure_run_map_.end(); ++it) {
    delete_container_pointers(it->second.begin(), it->second.end());
  }
}

void reactor::add_socket(zmq::socket_t* socket, closure* closure) {
  sockets_.push_back(std::make_pair(socket, closure));
  is_dirty_ = true;
}

namespace {
void rebuild_poll_items(
    const std::vector<std::pair<zmq::socket_t*, closure*> >& sockets,
    std::vector<zmq::pollitem_t>* pollitems) {
  pollitems->resize(sockets.size());
  for (size_t i = 0; i < sockets.size(); ++i) {
    zmq::socket_t& socket = *sockets[i].first;
    zmq::pollitem_t pollitem = {socket, 0, ZMQ_POLLIN, 0};
    (*pollitems)[i] = pollitem;
  }
}
}  // namespace

void reactor::run_closure_at(uint64 timestamp, closure* closure) {
  closure_run_map_[timestamp].push_back(closure);
}

int reactor::loop() {
  while (!should_quit_) {
    if (is_dirty_) {
      rebuild_poll_items(sockets_, &pollitems_);
      is_dirty_ = false;
    }
    long poll_timeout = process_closure_run_map();

    int rc = zmq_poll(&pollitems_[0], pollitems_.size(), poll_timeout);

    if (rc == -1) {
      int zmq_err = zmq_errno();
      CHECK_NE(zmq_err, EFAULT);
      if (zmq_err == ETERM) {
        return -1;
      }
    }
    for (size_t i = 0; i < pollitems_.size(); ++i) {
      if (!pollitems_[i].revents & ZMQ_POLLIN) {
        continue;
      }
      pollitems_[i].revents = 0;
      sockets_[i].second->run();
    }
  }
  if (g_interrupted) {
    return -1;
  } else {
    return 0;
  }
}

long reactor::process_closure_run_map() {
  uint64 now = zclock_time();
  closure_run_map::iterator ub(closure_run_map_.upper_bound(now));
  for (closure_run_map::const_iterator it = closure_run_map_.begin();
       it != ub;
       ++it) {
    for (std::vector<closure*>::const_iterator vit = it->second.begin();
         vit != it->second.end(); ++vit) {
      (*vit)->run();
    }
  }
  long poll_timeout = -1;
  if (ub != closure_run_map_.end()) {
		// zmq3 patch
    if (ZMQ_VERSION_MAJOR >= 3) {
    	poll_timeout = ub->first - now;
    } else {
    	poll_timeout = 1000 * (ub->first - now);
		}
  }
  closure_run_map_.erase(closure_run_map_.begin(), ub);
  return poll_timeout;
}

void reactor::set_should_quit() {
  should_quit_ = true;
}

void install_signal_handler() {
  struct sigaction action;
  action.sa_handler = signal_handler;
  action.sa_flags = 0;
  sigemptyset(&action.sa_mask);
  sigaction(SIGINT, &action, NULL);
  sigaction(SIGTERM, &action, NULL);
}
}  // namespace rpcz


text:
package com.telefonica.euro_iaas.paasmanager.model.dto;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

import com.telefonica.euro_iaas.paasmanager.model.Attribute;
import com.telefonica.euro_iaas.paasmanager.model.Network;
import com.telefonica.euro_iaas.paasmanager.model.ProductRelease;
import com.telefonica.euro_iaas.paasmanager.model.Tier;

/**
 * Represents an artifact to be installed on a ProductRelease.
 *
 * @author Henar Mu�oz
 * @version $Id: $
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class TierDto {

    private String name;
    private String flavour;
    private String image;

    private Integer maximumNumberInstances;
    private Integer minimumNumberInstances;
    private Integer initialNumberInstances;

    private List<ProductReleaseDto> productReleaseDtos;

    private List<NetworkDto> networkDto;

    private String icono = "";
    private String securityGroup = "";
    private String keypair = "";
    private String floatingip = "";

    private String region = "";

    /**
     * Default Constructor.
     */
    public TierDto() {
        this.networkDto = new ArrayList<NetworkDto>();
        this.productReleaseDtos = new ArrayList<ProductReleaseDto>();
    }

    /**
     * Constructor.
     *
     * @param name
     * @param maximumNumberInstances
     * @param minimumNumberInstances
     * @param initialNumberInstances
     * @param productReleaseDtos
     */

    public TierDto(String name, Integer maximumNumberInstances, Integer minimumNumberInstances,
            Integer initialNumberInstances, List<ProductReleaseDto> productReleaseDtos) {

        this.name = name;
        this.maximumNumberInstances = maximumNumberInstances;
        this.minimumNumberInstances = minimumNumberInstances;
        this.initialNumberInstances = initialNumberInstances;
        this.productReleaseDtos = productReleaseDtos;

        this.networkDto = new ArrayList<NetworkDto>();
    }

    /**
     * Constructor.
     *
     * @param name
     * @param maximumNumberInstances
     * @param minimumNumberInstances
     * @param initialNumberInstances
     * @param productReleaseDtos
     * @param flavour
     * @param image
     * @param icono
     * @param keypair
     * @param floatingip
     */

    public TierDto(String name, Integer maximumNumberInstances, Integer minimumNumberInstances,
            Integer initialNumberInstances, List<ProductReleaseDto> productReleaseDtos, String flavour, String image,
            String icono, String keypair, String floatingip) {

        this.name = name;
        this.maximumNumberInstances = maximumNumberInstances;
        this.minimumNumberInstances = minimumNumberInstances;
        this.initialNumberInstances = initialNumberInstances;
        this.productReleaseDtos = productReleaseDtos;
        this.flavour = flavour;
        this.image = image;
        this.icono = icono;
        this.keypair = keypair;
        this.floatingip = floatingip;
        this.networkDto = new ArrayList<NetworkDto>();
    }

    /**
     * Constructor.
     *
     * @param name
     * @param maximumNumberInstances
     * @param minimumNumberInstances
     * @param initialNumberInstances
     * @param productReleaseDtos
     * @param flavour
     * @param image
     * @param icono
     * @param securityGroup
     * @param keypair
     * @param floatingip
     */

    public TierDto(String name, Integer maximumNumberInstances, Integer minimumNumberInstances,
            Integer initialNumberInstances, List<ProductReleaseDto> productReleaseDtos, String flavour, String image,
            String icono, String securityGroup, String keypair, String floatingip) {

        this.name = name;
        this.maximumNumberInstances = maximumNumberInstances;
        this.minimumNumberInstances = minimumNumberInstances;
        this.initialNumberInstances = initialNumberInstances;
        this.productReleaseDtos = productReleaseDtos;
        this.flavour = flavour;
        this.image = image;
        this.icono = icono;
        this.keypair = keypair;
        this.floatingip = floatingip;
        this.securityGroup = securityGroup;
        this.networkDto = new ArrayList<NetworkDto>();
    }

    /**
     * Add network dto.
     *
     * @param networkDto
     *            the network do to be add to the array.
     */
    public void addNetworkDto(NetworkDto networkDto) {
        if (networkDto == null) {
            this.networkDto = new ArrayList<NetworkDto>();
        }
        this.networkDto.add(networkDto);
    }

    /**
     * Add product release.
     *
     * @param productReleaseDto
     *            the product release to be added.
     */
    public void addProductRelease(ProductReleaseDto productReleaseDto) {
        if (this.productReleaseDtos == null) {
            productReleaseDtos = new ArrayList<ProductReleaseDto>();
        }
        productReleaseDtos.add(productReleaseDto);
    }

    /**
     * It obtains the Tier object associated.
     *
     * @tier
     */
    public Tier fromDto(String vdc, String envName) {

        Tier tier = new Tier();
        tier.setName(getName());
        tier.setInitialNumberInstances(getInitialNumberInstances());
        tier.setMaximumNumberInstances(getMaximumNumberInstances());
        tier.setMinimumNumberInstances(getMinimumNumberInstances());
        tier.setIcono(getIcono());
        tier.setFlavour(getFlavour());
        tier.setImage(getImage());
        tier.setKeypair(getKeypair());
        tier.setFloatingip(getFloatingip());
        tier.setRegion(getRegion());
        tier.setVdc(vdc);
        tier.setEnviromentName(envName);

        for (ProductReleaseDto pReleaseDto : getProductReleaseDtos()) {
            ProductRelease pRelease = new ProductRelease();
            pRelease.setProduct(pReleaseDto.getProductName());
            pRelease.setVersion(pReleaseDto.getVersion());

            if (pReleaseDto.getProductDescription() != null) {
                pRelease.setDescription(pReleaseDto.getProductDescription());
            }

            if (pReleaseDto.getPrivateAttributes() != null) {
                Set<Attribute> attrs = new HashSet<Attribute>();
                for (Attribute attr: pReleaseDto.getPrivateAttributes()){
                    attrs.add(attr);
                }
                pRelease.setAttributes(attrs);
            }
            tier.addProductRelease(pRelease);
        }

        for (NetworkDto networkDto : this.getNetworksDto()) {
            Network network ;
            if (vdc == null) {
                network = networkDto.fromDto("");
            } else {
                network = networkDto.fromDto(vdc);
            }
            tier.addNetwork(network);
        }
        return tier;
    }

    public String getFlavour() {
        return flavour;
    }

    public String getFloatingip() {
        return this.floatingip;
    }

    public String getIcono() {
        return this.icono;
    }

    public String getImage() {
        return this.image;
    }

    /**
     * @return the initialNumberInstances
     */
    public Integer getInitialNumberInstances() {
        return initialNumberInstances;
    }

    public String getKeypair() {
        return this.keypair;
    }

    /**
     * @return the maximum_number_instances
     */
    public Integer getMaximumNumberInstances() {
        return maximumNumberInstances;
    }

    /**
     * @return the minimumNumberInstances
     */
    public Integer getMinimumNumberInstances() {
        return minimumNumberInstances;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @return the list of networks associated
     */
    public List<NetworkDto> getNetworksDto() {
        return networkDto;
    }

    /**
     * @return the productReleases
     */
    public List<ProductReleaseDto> getProductReleaseDtos() {
        if (productReleaseDtos == null) {
            this.productReleaseDtos = new ArrayList<ProductReleaseDto>();
        }
        return productReleaseDtos;
    }

    /**
     * Get the security group.
     *
     * @return
     */
    public String getSecurityGroup() {
        return this.securityGroup;
    }

    /**
     * It removes the product release.
     *
     * @param productReleaseDto
     */
    public void removeProductRelease(ProductReleaseDto productReleaseDto) {

        productReleaseDtos.remove(productReleaseDto);
    }

    /**
     * @param flavour
     *            the flavour to set
     */
    public void setFlavour(String flavour) {
        this.flavour = flavour;
    }

    public void setFloatingip(String floatingip) {
        this.floatingip = floatingip;
    }

    public void setIcono(String icono) {
        this.icono = icono;
    }

    public void setImage(String image) {
        this.image = image;
    }

    /**
     * @param initialNumberInstances
     *            the initialNumberInstances to set
     */
    public void setInitialNumberInstances(Integer initialNumberInstances) {
        this.initialNumberInstances = initialNumberInstances;
    }

    public void setKeypair(String keypair) {
        this.keypair = keypair;
    }

    /**
     * @param maximumNumberInstances
     *            the maximumNumberInstances to set
     */
    public void setMaximumNumberInstances(Integer maximumNumberInstances) {
        this.maximumNumberInstances = maximumNumberInstances;
    }

    /**
     * @param minimumNumberInstances
     *            the minimumNumberInstances to set
     */
    public void setMinimumNumberInstances(Integer minimumNumberInstances) {
        this.minimumNumberInstances = minimumNumberInstances;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @param networkDto
     *            the network do to be add to the array
     */
    public void setNetworksDto(List<NetworkDto> networkDto) {
        this.networkDto = networkDto;
    }

    /**
     * @param productReleaseDtos
     *            the productReleases to set
     */
    public void setProductReleaseDtos(List<ProductReleaseDto> productReleaseDtos) {
        this.productReleaseDtos = productReleaseDtos;
    }

    /**
     * @param securityGroup
     *            the securityGroup to set
     */
    public void setSecurityGroup(String securityGroup) {
        this.securityGroup = securityGroup;

    }

    public String getRegion() {
        return region;
    }

    public void setRegion(String region) {
        this.region = region;
    }
}


text:
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}

-----------------------------------------------------------------------------
-- |
-- Module      :  Distribution.Simple.Program.Ld
-- Copyright   :  Duncan Coutts 2009
--
-- Maintainer  :  cabal-devel@haskell.org
-- Portability :  portable
--
-- This module provides an library interface to the @ld@ linker program.

module Distribution.Simple.Program.Ld (
    combineObjectFiles,
  ) where

import Prelude ()
import Distribution.Compat.Prelude

import Distribution.Simple.Program.Types
         ( ConfiguredProgram(..) )
import Distribution.Simple.Program.Run
         ( programInvocation, multiStageProgramInvocation
         , runProgramInvocation )
import Distribution.Verbosity
         ( Verbosity )

import System.Directory
         ( renameFile )
import System.FilePath
         ( (<.>) )

-- | Call @ld -r@ to link a bunch of object files together.
--
combineObjectFiles :: Verbosity -> ConfiguredProgram
                   -> FilePath -> [FilePath] -> IO ()
combineObjectFiles verbosity ld target files =

  -- Unlike "ar", the "ld" tool is not designed to be used with xargs. That is,
  -- if we have more object files than fit on a single command line then we
  -- have a slight problem. What we have to do is link files in batches into
  -- a temp object file and then include that one in the next batch.

  let simpleArgs  = ["-r", "-o", target]

      initialArgs = ["-r", "-o", target]
      middleArgs  = ["-r", "-o", target, tmpfile]
      finalArgs   = middleArgs

      simple      = programInvocation ld simpleArgs
      initial     = programInvocation ld initialArgs
      middle      = programInvocation ld middleArgs
      final       = programInvocation ld finalArgs

      invocations = multiStageProgramInvocation
                      simple (initial, middle, final) files

   in run invocations

  where
    tmpfile        = target <.> "tmp" -- perhaps should use a proper temp file

    run []         = return ()
    run [inv]      = runProgramInvocation verbosity inv
    run (inv:invs) = do runProgramInvocation verbosity inv
                        renameFile target tmpfile
                        run invs


text:
#include "vu2.h"
#include "vu_priv.h"

/** vu database global definition. */
VuDatabase *vuDatabase = 0;

#if VU_ALL_FILTERED

VuDatabase::VuDatabase(unsigned int tableSize, unsigned int key)
    : dbHash_(new VuHashTable(NULL, tableSize, key))
{
}

VuDatabase::~VuDatabase()
{
    Purge(TRUE);
}

unsigned int VuDatabase::Purge(VU_BOOL all)
{
    // this is a bit different from hash db since we need to save entities before purging
    // to avoid self destruction CTD (entity is destroyed and its callback removes other entities
    // from vudb
    // suspend calls removal callback
    std::list<VuEntityBin> toBePurged;
    int ret = 0;

    for (unsigned int i = 0; i < dbHash_->capacity_; ++i)
    {
        VuListIterator li(&dbHash_->table_[i]);
        VuEntity *e;

        for (
            e = li.GetFirst();
            e not_eq NULL;
            e = li.GetNext()
        )
        {
            // run calling all callbacks and seting as removed... purge will do the actual removal
            if ( not ( not all and ((e->IsPrivate() and e->IsPersistent()) or e->IsGlobal())))
            {
                toBePurged.push_back(VuEntityBin(e));
            }
        }
    }

    ret = dbHash_->Purge(all);
    // now delete all
    toBePurged.clear();
    return ret;
}

int VuDatabase::Suspend(VU_BOOL all)
{
    // suspend calls removal callback
    int ret = 0;
    // similar to purge here...
    std::list<VuEntityBin> toBeSuspended;

    for (unsigned int i = 0; i < dbHash_->capacity_; ++i)
    {
        VuListIterator li(&dbHash_->table_[i]);
        VuEntity *e;

        for (
            e = li.GetFirst();
            e not_eq NULL;
            e = li.GetNext()
        )
        {
            // run calling all callbacks and seting as removed... purge will do the actual removal
            if ( not ( not all and ((e->IsPrivate() and e->IsPersistent()) or e->IsGlobal())))
            {
                toBeSuspended.push_back(VuEntityBin(e));
                e->RemovalCallback();
                e->SetVuState(VU_MEM_REMOVED);
            }
        }
    }

    ret = dbHash_->Purge(all);
    // now remove all all
    toBeSuspended.clear();
    return ret;
}

VU_ERRCODE VuDatabase::Handle(VuMessage *msg)
{
    // note: this should work on Create bitand Delete messages, but those are
    // currently handled elsewhere... for now... just pass on to collection mgr
    return vuCollectionManager->Handle(msg);
}

void VuDatabase::HandleMove(VuEntity *ent, BIG_SCALAR coord1, BIG_SCALAR coord2)
{
    if (ent->VuState() == VU_MEM_ACTIVE)
    {
        vuCollectionManager->HandleMove(ent, coord1, coord2);
    }
}

VU_ERRCODE VuDatabase::Insert(VuEntity *entity)
{
    if (entity == NULL)
    {
        return VU_NO_OP;
    }

#if 0//BIRTH_LIST

    // already in
    if ((entity->VuState() == VU_MEM_ACTIVE) or (entity->VuState() == VU_MEM_TO_BE_INSERTED))
    {
        return VU_ERROR;
    }

    VuScopeLock l(GetMutex());
    entity->SetVuState(VU_MEM_TO_BE_INSERTED);
    vuCollectionManager->AddToBirthList(entity);
    VuEntity::VU_SEND_TYPE sendType = entity->SendCreate();

    if (entity->IsLocal() and ( not entity->IsPrivate()) and (sendType not_eq VuEntity::VU_SC_DONT_SEND))
    {
        VuCreateEvent *event = 0;
        VuTargetEntity *target = vuGlobalGroup;

        if ( not entity->IsGlobal())
        {
            target = vuLocalSessionEntity->Game();
        }

        event = new VuCreateEvent(entity, target);
        event->RequestReliableTransmit();

        if (sendType == VuEntity::VU_SC_SEND_OOB)
        {
            event->RequestOutOfBandTransmit();
        }

        VuMessageQueue::PostVuMessage(event);
    }

    entity->InsertionCallback();
    return VU_SUCCESS;

#else

    // no duplicates allowed
    if ((entity->VuState() == VU_MEM_ACTIVE) or (dbHash_->Find(entity->Id()) not_eq NULL))
    {
        return VU_ERROR;
    }

    entity->SetVuState(VU_MEM_ACTIVE);
    dbHash_->Insert(entity);
    vuCollectionManager->Add(entity);

    VuEntity::VU_SEND_TYPE sendType = entity->SendCreate();

    if (entity->IsLocal() and ( not entity->IsPrivate()) and (sendType not_eq VuEntity::VU_SC_DONT_SEND))
    {
        VuCreateEvent *event = 0;
        VuTargetEntity *target = vuGlobalGroup;

        if ( not entity->IsGlobal())
        {
            target = vuLocalSessionEntity->Game();
        }

        event = new VuCreateEvent(entity, target);
        event->RequestReliableTransmit();

        if (sendType == VuEntity::VU_SC_SEND_OOB)
        {
            event->RequestOutOfBandTransmit();
        }

        VuMessageQueue::PostVuMessage(event);
    }

    // sfr: its possible this is being called twice (because of the create event)
    entity->InsertionCallback();
    return VU_SUCCESS;
#endif
}

#define IMMEDIATE_REMOVAL_CALLBACK 0

VU_ERRCODE VuDatabase::CommonRemove(VuEntity *entity)
{
    if ( not entity or entity->VuState() not_eq VU_MEM_ACTIVE)
    {
        return VU_NO_OP;
    }

    vuCollectionManager->AddToGc(entity);
    entity->SetVuState(VU_MEM_INACTIVE);

#if IMMEDIATE_REMOVAL_CALLBACK
    entity->RemovalCallback();
#endif

    return VU_SUCCESS;
}

VU_ERRCODE VuDatabase::Remove(VuEntity *entity)
{
    VU_ERRCODE ret = CommonRemove(entity);

    if (ret not_eq VU_SUCCESS)
    {
        return ret;
    }

#if NO_RELEASE_EVENT

    if (entity->IsLocal() and not entity->IsPrivate())
    {
        VuEvent *event = new VuDeleteEvent(entity);
        event->RequestReliableTransmit();
        VuMessageQueue::PostVuMessage(event);
    }

#else
    VuEvent *event;

    if (entity->IsLocal() and not entity->IsPrivate())
    {
        event = new VuDeleteEvent(entity);
        event->RequestReliableTransmit();
    }
    else
    {
        event = new VuReleaseEvent(entity);
    }

    VuMessageQueue::PostVuMessage(event);
#endif
    return VU_SUCCESS;
}

VU_ERRCODE VuDatabase::SilentRemove(VuEntity *entity)
{
    return CommonRemove(entity);
}

#if not NO_RELEASE_EVENT
VU_ERRCODE VuDatabase::DeleteRemove(VuEntity *entity)
{
    return CommonRemove(entity);
}
#endif

VU_ERRCODE VuDatabase::Remove(VU_ID entityId)
{
    return Remove(dbHash_->Find(entityId));
}

#if BIRTH_LIST
void VuDatabase::ReallyInsert(VuEntity *entity)
{
    entity->SetVuState(VU_MEM_ACTIVE);
    dbHash_->Insert(entity);
    vuCollectionManager->Add(entity);
}
#endif

void VuDatabase::ReallyRemove(VuEntity *entity)
{
    // play it safe
    VuBin<VuEntity> safe(entity);
#if not IMMEDIATE_REMOVAL_CALLBACK
    entity->RemovalCallback();
#endif
    dbHash_->Remove(entity);
    vuCollectionManager->Remove(entity);
    entity->SetVuState(VU_MEM_REMOVED);
}

VuEntity *VuDatabase::Find(VU_ID entityId) const
{
    return dbHash_->Find(entityId);
}

#else

VuDatabase::VuDatabase(unsigned int tableSize, unsigned int key)
    : VuHashTable(tableSize, key)
{
}

VuDatabase::~VuDatabase()
{
    Purge(TRUE);
}

unsigned int VuDatabase::Purge(VU_BOOL all)
{
    unsigned int ret = 0;

    for (unsigned int i = 0; i < capacity_; ++i)
    {
        VuListIterator li(&table_[i]);
        VuEntity *e;

        for (
            e = li.GetFirst();
            e not_eq NULL;
            e = li.GetNext()
        )
        {
            if ( not ( not all and ((e->IsPrivate() and e->IsPersistent()) or e->IsGlobal())))
            {
                e->SetVuState(VU_MEM_REMOVED);
            }
        }

        ret += table_[i].Purge(all);
    }

    return ret;
}

int VuDatabase::Suspend(VU_BOOL all)
{
    // suspend calls removal callback
    int ret = 0;

    for (unsigned int i = 0; i < capacity_; ++i)
    {
        VuListIterator li(&table_[i]);
        VuEntity *e;

        for (
            e = li.GetFirst();
            e not_eq NULL;
            e = li.GetNext()
        )
        {
            if ( not ( not all and ((e->IsPrivate() and e->IsPersistent()) or e->IsGlobal())))
            {
                e->RemovalCallback();
                e->SetVuState(VU_MEM_REMOVED);
            }
        }

        ret += table_[i].Purge(all);
    }

    return ret;
}

VU_ERRCODE VuDatabase::Handle(VuMessage *msg)
{
    // note: this should work on Create bitand Delete messages, but those are
    // currently handled elsewhere... for now... just pass on to collection mgr
    vuCollectionManager->Handle(msg);
    return VU_SUCCESS;
}

void VuDatabase::HandleMove(VuEntity *ent, BIG_SCALAR coord1, BIG_SCALAR coord2)
{
    if (ent->VuState() == VU_MEM_ACTIVE)
    {
        vuCollectionManager->HandleMove(ent, coord1, coord2);
    }
}

VU_ERRCODE VuDatabase::Insert(VuEntity *entity)
{
    if (entity == NULL)
    {
        return VU_NO_OP;
    }

#if 0//BIRTH_LIST

    // already in
    if ((entity->VuState() == VU_MEM_ACTIVE) or (entity->VuState() == VU_MEM_TO_BE_INSERTED))
    {
        return VU_ERROR;
    }

    VuScopeLock l(GetMutex());
    entity->SetVuState(VU_MEM_TO_BE_INSERTED);
    vuCollectionManager->AddToBirthList(entity);
    VuEntity::VU_SEND_TYPE sendType = entity->SendCreate();

    if (entity->IsLocal() and ( not entity->IsPrivate()) and (sendType not_eq VuEntity::VU_SC_DONT_SEND))
    {
        VuCreateEvent *event = 0;
        VuTargetEntity *target = vuGlobalGroup;

        if ( not entity->IsGlobal())
        {
            target = vuLocalSessionEntity->Game();
        }

        event = new VuCreateEvent(entity, target);
        event->RequestReliableTransmit();

        if (sendType == VuEntity::VU_SC_SEND_OOB)
        {
            event->RequestOutOfBandTransmit();
        }

        VuMessageQueue::PostVuMessage(event);
    }

    entity->InsertionCallback();
    return VU_SUCCESS;

#else

    // no duplicates allowed
    if ((entity->VuState() == VU_MEM_ACTIVE) or (Find(entity->Id()) not_eq NULL))
    {
        return VU_ERROR;
    }

    VuScopeLock lock(GetMutex());

    entity->SetVuState(VU_MEM_ACTIVE);
    VuHashTable::Insert(entity);
    vuCollectionManager->Add(entity);

    VuEntity::VU_SEND_TYPE sendType = entity->SendCreate();

    if (entity->IsLocal() and ( not entity->IsPrivate()) and (sendType not_eq VuEntity::VU_SC_DONT_SEND))
    {
        VuCreateEvent *event = 0;
        VuTargetEntity *target = vuGlobalGroup;

        if ( not entity->IsGlobal())
        {
            target = vuLocalSessionEntity->Game();
        }

        event = new VuCreateEvent(entity, target);
        event->RequestReliableTransmit();

        if (sendType == VuEntity::VU_SC_SEND_OOB)
        {
            event->RequestOutOfBandTransmit();
        }

        VuMessageQueue::PostVuMessage(event);
    }

    // sfr: its possible this is being called twice (because of the create event)
    entity->InsertionCallback();
    return VU_SUCCESS;
#endif
}

VU_ERRCODE VuDatabase::CommonRemove(VuEntity *entity)
{
    if ( not entity or entity->VuState() not_eq VU_MEM_ACTIVE)
    {
        return VU_NO_OP;
    }

    VuScopeLock l(GetMutex());
    vuCollectionManager->AddToGc(entity);
    entity->SetVuState(VU_MEM_INACTIVE);
    entity->RemovalCallback();
    return VU_SUCCESS;
}

VU_ERRCODE VuDatabase::Remove(VuEntity *entity)
{
    VU_ERRCODE ret = CommonRemove(entity);

    if (ret not_eq VU_SUCCESS)
    {
        return ret;
    }

    VuEvent *event;

    if (entity->IsLocal() and not entity->IsPrivate())
    {
        event = new VuDeleteEvent(entity);
        event->RequestReliableTransmit();
    }

#if not NO_RELEASE_EVENT
    else
    {
        event = new VuReleaseEvent(entity);
    }

#endif
    VuMessageQueue::PostVuMessage(event);
    return VU_SUCCESS;
}

VU_ERRCODE VuDatabase::SilentRemove(VuEntity *entity)
{
    return CommonRemove(entity);
}

#if not NO_RELEASE_EVENT
VU_ERRCODE VuDatabase::DeleteRemove(VuEntity *entity)
{
    return CommonRemove(entity);
}
#endif

VU_ERRCODE VuDatabase::Remove(VU_ID entityId)
{
    return Remove(Find(entityId));
}

#if BIRTH_LIST
void VuDatabase::ReallyInsert(VuEntity *entity)
{
    entity->SetVuState(VU_MEM_ACTIVE);
    VuHashTable::Insert(entity);
    vuCollectionManager->Add(entity);
}
#endif

void VuDatabase::ReallyRemove(VuEntity *entity)
{
    // play it safe
    VuBin<VuEntity> safe(entity);
    VuHashTable::Remove(entity);
    vuCollectionManager->Remove(entity);
    entity->SetVuState(VU_MEM_REMOVED);
}

#endif


text:
[![npm version](https://img.shields.io/npm/v/marx-css.svg)](https://www.npmjs.com/package/marx-css)

**The classless CSS reset (perfect for Communists).**

    No JavaScript. No Classes. Just raw CSS.

## Is Marx for you?

Marx is a CSS stylesheet to be used in any projects (namely small ones). If you don't need the weight of heavy frameworks or you would just like to make an edible website quickly, Marx is perfect for you. It can be used out of the minified box but it can also be customised and styled through the use of HTML classes.

## Key features

- Built atop of Sanitize.css, meaning all browsers render consistently.
- Responsive and mobile-friendly.
- Clean, beautiful typography.
- Forms, tables, buttons and navigation.
- Zero classes, so it already works with your HTML.
- Drop-dead gorgeous.
- It just works.

## [Demo](http://codepen.io/mblode/details/JdYbJj)

## Quick Start

Several quick start options are available:

- Install with [NPM](https://www.npmjs.com/): `npm install marx-css` (recommended).
- Use the latest Marx CDN

``` html

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://unpkg.com/marx-css/css/marx.min.css">

```
- [Source code.](https://raw.githubusercontent.com/mblode/marx/master/css/marx.min.css)
- [Download the latest release](https://github.com/mblode/marx/archive/master.zip).
- Clone the repo: `git clone https://github.com/mblode/marx.git`.

If you have cloned the repo or downloaded from .zip, there are a few steps you must take within the terminal:

1. Change directory: `cd marx`.
2. Install node modules: `npm install`.
4. To run gulp: `gulp`.

## Running Github Pages

The gh-pages branch is built using Jekyll and must therefore be install with `gem install jekyll`.

1. Checkout in to gh-pages: `git checkout gh-pages`.
2. Install marx dependency: `npm install`.
3. Run middleman: `bundle exec middleman serve`.
4. Open in browser: `localhost:4567`.

## What's Included

These are the files that are generated from `npm install marx-css`

```

.
├── LICENSE.md
├── README.md
├── css
│   ├── marx.css
│   ├── marx.min.css
│   ├── marx.min.css.map
├── gulpfile.js
├── index.html
├── package.json
└── src
    ├── _base.css
    ├── _buttons.css
    ├── _form.css
    ├── _sanitize.css
    ├── _tables.css
    ├── _typography.css
    ├── _variables.css
    └── marx.css

```

## Documentation

### Basic HTML Template

```html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Marx Template</title>

  <!-- Marx CSS -->
  <link rel="stylesheet" href="css/marx.min.css">
</head>

<body>
  <!-- main is the container -->
  <main>
    <!-- Navigation -->
    <nav>
      <ul>
        <li><a href="#"><b>First</b></a></li>
        <li><a href="#">Second</a></li>
        <li><a href="#">Third</a></li>
        <li><a href="#">Fourth</a></li>
      </ul>
    </nav>

    <!-- article -->
    <article>
      <h1>Article</h1>
    </article>

    <!-- aside -->
    <aside>
      <h1>Aside</h1>
    </aside>

    <!-- section -->
    <section>
      <h1>Section</h1>
    </section>

    <!-- footer -->
    <footer>
      <p>© Matthew Blode</p>
    </footer>
  </main>

</body>
</html>

```

## Contributing to Marx

Pull requests are the way to go.

## Creators

**Matthew Blode**

- <https://github.com/mblode>
- <http://codepen.io/mblode>

## License

MIT © [Matthew Blode](http://matthewblode.com)


text:
package com.easytoolsoft.easyreport.web.config.mvc;

import com.easytoolsoft.easyreport.support.consts.AppEnvConsts;
import com.easytoolsoft.easyreport.support.filter.ContextInitDataFilter;
import com.easytoolsoft.easyreport.web.config.properties.EnvProperties;
import org.apache.catalina.servlets.DefaultServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ErrorProperties.IncludeStacktrace;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.filter.DelegatingFilterProxy;

/**
 * @author Tom Deng
 **/
@Configuration
@EnableConfigurationProperties(EnvProperties.class)
public class ServletConfig {
    @Autowired
    private EnvProperties envProperties;

    /**
     * 让static下的静态资源走DefaultServlet, 不走SpringMVC DispatchServlet
     *
     * @return ServletRegistrationBean
     */
    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        return new ServletRegistrationBean(new DefaultServlet(), "/static/*");
    }

    /**
     * 在系统启动时加一些初始化数据到request上下文中
     *
     * @return FilterRegistrationBean
     */
    @Bean
    public FilterRegistrationBean contextInitDataFilterRegistrationBean() {
        final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new ContextInitDataFilter());
        registrationBean.addUrlPatterns("/*");
        registrationBean.addInitParameter(AppEnvConsts.APP_NAME_ITEM, this.envProperties.getAppName());
        registrationBean.addInitParameter(AppEnvConsts.ENV_NAME_ITEM, this.envProperties.getName());
        registrationBean.addInitParameter(AppEnvConsts.VERSION_ITEM, this.envProperties.getVersion());
        registrationBean.setName("contextInitDataFilter");
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        final FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
        filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));
        filterRegistration.addInitParameter("targetFilterLifecycle", "true");
        filterRegistration.setEnabled(true);
        filterRegistration.addUrlPatterns("/*");
        return filterRegistration;
    }

    @Bean
    public ConfigurableServletWebServerFactory containerCustomizer() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();

        factory.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/customError/401"));
        factory.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, "/customError/403"));
        factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/customError/404"));
        factory.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/customError"));
        return factory;
    }

    @Bean
    public ErrorProperties errorProperties() {
        final ErrorProperties properties = new ErrorProperties();
        properties.setIncludeStacktrace(IncludeStacktrace.ALWAYS);
        return properties;
    }
}


text:
from traits.api import *

class Employee(HasTraits):
    name = Str
    sick_days = Int

class Department(HasTraits):
    name = Str
    employees = List(Employee)

class Corporation(HasTraits):
    name = Str
    departments = List(Department)

    # Define a corporate 'whistle blower' method:
    @on_trait_change('departments:employees.sick_days')
    def sick_again(self, object, name, old, new):
        print '%s just took sick day number %d for this year!' % (
              object.name, new)

# Create some sample employees:
millie = Employee(name='Millie', sick_days=2)
ralph = Employee(name='Ralph', sick_days=3)
tom = Employee(name='Tom', sick_days=1)
slick = Employee(name='Slick', sick_days=16)
marcelle = Employee(name='Marcelle', sick_days=7)
reggie = Employee(name='Reggie', sick_days=11)
dave = Employee(name='Dave', sick_days=0)
bob = Employee(name='Bob', sick_days=1)
alphonse = Employee(name='Alphonse', sick_days=5)

# Create some sample departments:
accounting = Department(name='accounting',
                        employees=[millie, ralph, tom])

sales = Department(name='Sales',
                   employees=[slick, marcelle, reggie])

development = Department(name='Development',
                         employees=[dave, bob, alphonse])

# Create a sample corporation:
acme = Corporation(name='Acme, Inc.',
                   departments=[accounting, sales, development])

# Now let's try out our 'reporting' system:
slick.sick_days += 1
reggie.sick_days += 1


text:
<idea-plugin xmlns:xi="http://www.w3.org/2001/XInclude">
  <name>ReStructuredText Support</name>
  <id>org.jetbrains.plugins.rest</id>
  <description>This plugin enables support for reStructuredText files (*.rst)</description>
  <vendor>JetBrains</vendor>
  <depends>com.intellij.modules.lang</depends>

  <xi:include href="/META-INF/rest.xml" xpointer="xpointer(/idea-plugin/*)"/>
  <change-notes><![CDATA[

Added inspection for title & underline length math (PY-10998)

]]></change-notes>
</idea-plugin>


text:
/********************************************************************************
** Form generated from reading UI file 'exampledlg5.ui'
**
** Created by: Qt User Interface Compiler version 5.4.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_EXAMPLEDLG5_H
#define UI_EXAMPLEDLG5_H

#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDialog>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QTableWidget>
#include <QtWidgets/QVBoxLayout>

QT_BEGIN_NAMESPACE

class Ui_ExampleDlg5
{
public:
    QVBoxLayout *verticalLayout;
    QTableWidget *tableWidget;
    QHBoxLayout *horizontalLayout;
    QSpacerItem *horizontalSpacer;
    QPushButton *btnPrint;
    QPushButton *btnClose;

    void setupUi(QDialog *ExampleDlg5)
    {
        if (ExampleDlg5->objectName().isEmpty())
            ExampleDlg5->setObjectName(QStringLiteral("ExampleDlg5"));
        ExampleDlg5->resize(596, 352);
        verticalLayout = new QVBoxLayout(ExampleDlg5);
        verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
        tableWidget = new QTableWidget(ExampleDlg5);
        if (tableWidget->columnCount() < 4)
            tableWidget->setColumnCount(4);
        QTableWidgetItem *__qtablewidgetitem = new QTableWidgetItem();
        tableWidget->setHorizontalHeaderItem(0, __qtablewidgetitem);
        QTableWidgetItem *__qtablewidgetitem1 = new QTableWidgetItem();
        tableWidget->setHorizontalHeaderItem(1, __qtablewidgetitem1);
        QTableWidgetItem *__qtablewidgetitem2 = new QTableWidgetItem();
        tableWidget->setHorizontalHeaderItem(2, __qtablewidgetitem2);
        QTableWidgetItem *__qtablewidgetitem3 = new QTableWidgetItem();
        tableWidget->setHorizontalHeaderItem(3, __qtablewidgetitem3);
        tableWidget->setObjectName(QStringLiteral("tableWidget"));

        verticalLayout->addWidget(tableWidget);

        horizontalLayout = new QHBoxLayout();
        horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
        horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);

        horizontalLayout->addItem(horizontalSpacer);

        btnPrint = new QPushButton(ExampleDlg5);
        btnPrint->setObjectName(QStringLiteral("btnPrint"));

        horizontalLayout->addWidget(btnPrint);

        btnClose = new QPushButton(ExampleDlg5);
        btnClose->setObjectName(QStringLiteral("btnClose"));

        horizontalLayout->addWidget(btnClose);

        verticalLayout->addLayout(horizontalLayout);

        retranslateUi(ExampleDlg5);
        QObject::connect(btnClose, SIGNAL(clicked()), ExampleDlg5, SLOT(close()));

        QMetaObject::connectSlotsByName(ExampleDlg5);
    } // setupUi

    void retranslateUi(QDialog *ExampleDlg5)
    {
        ExampleDlg5->setWindowTitle(QApplication::translate("ExampleDlg5", "Dialog", 0));
        QTableWidgetItem *___qtablewidgetitem = tableWidget->horizontalHeaderItem(0);
        ___qtablewidgetitem->setText(QApplication::translate("ExampleDlg5", "Goods", 0));
        QTableWidgetItem *___qtablewidgetitem1 = tableWidget->horizontalHeaderItem(1);
        ___qtablewidgetitem1->setText(QApplication::translate("ExampleDlg5", "Quant", 0));
        QTableWidgetItem *___qtablewidgetitem2 = tableWidget->horizontalHeaderItem(2);
        ___qtablewidgetitem2->setText(QApplication::translate("ExampleDlg5", "Price", 0));
        QTableWidgetItem *___qtablewidgetitem3 = tableWidget->horizontalHeaderItem(3);
        ___qtablewidgetitem3->setText(QApplication::translate("ExampleDlg5", "Sum", 0));
        btnPrint->setText(QApplication::translate("ExampleDlg5", "Print", 0));
        btnClose->setText(QApplication::translate("ExampleDlg5", "Close", 0));
    } // retranslateUi

};

namespace Ui {
    class ExampleDlg5: public Ui_ExampleDlg5 {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_EXAMPLEDLG5_H


text:
using Q42.WinRT.Controls;
using Q42.WinRT.UniversalSampleApp.UserControls;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace Q42.WinRT.UniversalSampleApp.Views
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class ControlsExamplePage : Page
    {
      Random _random = new Random();
      Random _random2 = new Random();

      public ControlsExamplePage()
      {
        this.InitializeComponent();
      }

      protected override void OnNavigatedTo(NavigationEventArgs e)
      {
        RandomColors = new List<Color>();
        RandomColors.Add(Colors.LightSkyBlue);
        RandomColors.Add(Colors.MidnightBlue);
        RandomColors.Add(Colors.LightPink);
        RandomColors.Add(Colors.YellowGreen);
        RandomColors.Add(Colors.Yellow);
        RandomColors.Add(Colors.Firebrick);
        RandomColors.Add(Colors.OldLace);

#if WINDOWS_PHONE_APP
        Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
#endif
      }

      protected override void OnNavigatedFrom(NavigationEventArgs e)
      {
#if WINDOWS_PHONE_APP
        Windows.Phone.UI.Input.HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
#endif
      }

#if WINDOWS_PHONE_APP
      void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
      {
        e.Handled = true;
        if (this.Frame.CanGoBack)
          this.Frame.GoBack();
      }
#endif

      public List<Color> RandomColors { get; set; }

      private void Button_Click_1(object sender, RoutedEventArgs e)
      {
        UserControlFlyout flyout = new UserControlFlyout();
        flyout.ShowFlyout(new FlyoutContentUserControl());
      }

      private void AddButton_Click_1(object sender, RoutedEventArgs e)
      {
        Border border = new Border();
        border.Height = RandomSize();
        border.Width = RandomSize();
        border.Margin = new Thickness(5);
        border.Background = RandomBackgroundColor();

        WrapPanel.Children.Add(border);
      }

      private double RandomSize()
      {
        int size = _random.Next(100);

        return 40 + size;
      }

      private Brush RandomBackgroundColor()
      {
        int index = _random2.Next(RandomColors.Count() - 1);

        return new SolidColorBrush(RandomColors[index]);
      }

    }
}


text:
/*
 * Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
 * From ASN.1 module "PKIX1Implicit88"
 * 	found in "asn1/rfc3280-PKIX1Implicit88.asn1"
 * 	`asn1c -S asn1c/skeletons -pdu=all -pdu=Certificate -fwide-types`
 */

#include "CertPolicyId.h"

/*
 * This type is implemented using OBJECT_IDENTIFIER,
 * so here we adjust the DEF accordingly.
 */
static const ber_tlv_tag_t asn_DEF_CertPolicyId_tags_1[] = {
	(ASN_TAG_CLASS_UNIVERSAL | (6 << 2))
};
asn_TYPE_descriptor_t asn_DEF_CertPolicyId = {
	"CertPolicyId",
	"CertPolicyId",
	&asn_OP_OBJECT_IDENTIFIER,
	OBJECT_IDENTIFIER_constraint,
	asn_DEF_CertPolicyId_tags_1,
	sizeof(asn_DEF_CertPolicyId_tags_1)
		/sizeof(asn_DEF_CertPolicyId_tags_1[0]), /* 1 */
	asn_DEF_CertPolicyId_tags_1,	/* Same as above */
	sizeof(asn_DEF_CertPolicyId_tags_1)
		/sizeof(asn_DEF_CertPolicyId_tags_1[0]), /* 1 */
	0,	/* No OER visible constraints */
	0,	/* No PER visible constraints */
	0, 0,	/* No members */
	0	/* No specifics */
};


text:
layout: post
title: Buildins from Hackerrank

tags:
- Python Study
---
Study notes about Buildins

### Zip
zip([iterable, ...])

This function returns a list of tuples. The (i)th tuple contains the (i)th element from each of the argument sequences or iterables.

If the argument sequences are of unequal lengths, then the returned list is truncated to the length of the shortest argument sequence.

* Example:

Task

The National University conducts an examination of  N students in X subjects.
Your task is to compute the average scores of each student.

Average score = (sum of scores obtained in all subjects by a student)/ (Total number of subjects)

The format for the general mark sheet is:

Student ID | 1 2 3 4 5
Subject  1 |  89     90      78     93     80

Subject 2   |  90     91      85     88    86
Subject 3   |  91     92      83      89    90.5

Average    |  90    91    82    90    85.5

Input Format

The first line contains N and X separated by a space.
The next X  lines contains the space separated marks obtained by students in a particular subject.

Constraints

0 < N <= 100

0 < X <= 100

Output Format

Print the averages of all students on separate lines.

The averages must be correct up to 1 decimal place.

```python
N, X = map(int, raw_input().split())

subjects = list()

for i in range(0, X):
    subjects.append(list(map(float, raw_input().split())))

students = zip(*subjects)

for i in range(0, N):
    marks = 0.0
    for j in range(0, X):
        marks += students[i][j]
    print marks / X
```
```
input:
5 3
89 90 78 93 80
90 91 85 88 86
91 92 83 89 90.5
output:
90.0
91.0
82.0
90.0
85.5
```
<https://www.hackerrank.com/challenges/zipped>

### eval
The eval() expression is a very powerful built-in function of Python. It helps in evaluating an expression. The expression can be a Python statement, or a code object.

For example:

```
>>> eval("9 + 5")
14
>>> x = 2
>>> eval("x + 3")
5
```
Here, eval() can also be used to work with Python keywords or defined functions and variables. These would normally be stored as strings.

For example:

```
>>> type(eval("len"))
<type 'builtin_function_or_method'>

Without eval()

>>> type("len")
<type 'str'>
```
Task
You are given an expression in a line. Read that line as a string variable, such as var, and print the result using eval(var).

NOTE: Python2 users, please import from _ _future__ import print_function.

Constraint
Input string is less than 100 characters.

* Code:

```python
from __future__ import print_function
x = str(raw_input())
eval(x)
```
```
input:
print (2+4)
output:
6
```
<https://www.hackerrank.com/challenges/python-eval>

### reduce
* Example:
You are given a string S.
S contains alphanumeric characters only.
Your task is to sort the string S in the following manner:

All sorted lowercase letters are ahead of uppercase letters.
All sorted uppercase letters are ahead of digits.
All sorted odd digits are ahead of sorted even digits.
Input Format

A single line of input contains the string S.

Constraints

0<len(S) < 1000

Output Format

Output the sorted string S.

```python
from string import ascii_lowercase, ascii_uppercase

order = ascii_lowercase + ascii_uppercase + "1357902468"

print (reduce(lambda x,y: x+y, sorted(raw_input(), key=order.index)))
```
```
input:
Sorting1234
output:
ginortS1324
```
<https://www.hackerrank.com/challenges/ginorts>


text:
namespace caffe {

template <typename Dtype>
BBTXTBBLayer<Dtype>::BBTXTBBLayer (const LayerParameter &param)
    : NeuronLayer<Dtype>(param)
{
    CHECK(param.has_bbtxt_bb_param()) << "BBTXTScalingParameter is mandatory!";
    CHECK(param.bbtxt_bb_param().has_ideal_size()) << "Ideal size is mandatory!";
    CHECK(param.bbtxt_bb_param().has_downsampling()) << "Downsampling is mandatory!";
}

template <typename Dtype>
void BBTXTBBLayer<Dtype>::Forward_cpu (const vector<Blob<Dtype>*> &bottom, const vector<Blob<Dtype>*> &top)
{
    const Dtype ideal_size   = this->layer_param_.bbtxt_bb_param().ideal_size();
    const Dtype downsampling = this->layer_param_.bbtxt_bb_param().downsampling();

    // For each image in the batch
    for (int b = 0; b < bottom[0]->shape(0); ++b)
    {
        // For each channel
        for (int c = 1; c < 5; ++c)
        {
            const Dtype* bottom_data = bottom[0]->cpu_data() + bottom[0]->offset(b, c);
            Dtype* top_data          = top[0]->mutable_cpu_data() + top[0]->offset(b, c);

            for (int i = 0; i < bottom[0]->shape(2); ++i)
            {
                for (int j = 0; j < bottom[0]->shape(3); ++j)
                {
                    // Convert the local normalized coordinate into a global unnormalized value in pixels
                    if (c == 1 || c == 3)
                    {
                        // xmin, xmax
                        *top_data = int(downsampling*(j+0.5f)) + ideal_size * (*bottom_data - Dtype(0.5f));
                    }
                    else // (c == 2 || c == 4)
                    {
                        // ymin, ymax
                        *top_data = int(downsampling*(i+0.5f)) + ideal_size * (*bottom_data - Dtype(0.5f));
                    }

                    bottom_data++;
                    top_data++;
                }
            }
        }
    }
}

template <typename Dtype>
void BBTXTBBLayer<Dtype>::Backward_cpu (const vector<Blob<Dtype>*> &top, const vector<bool> &propagate_down,
                                        const vector<Blob<Dtype>*> &bottom)
{
    CHECK(false) << "BBTXTBBLayer implements only the forward pass!";
}

// ----------------------------------------  LAYER INSTANTIATION  ---------------------------------------- //

#ifdef CPU_ONLY
//STUB_GPU(BBTXTBBLayer);
#endif

INSTANTIATE_CLASS(BBTXTBBLayer);
REGISTER_LAYER_CLASS(BBTXTBB);

}  // namespace caffe


text:
/* global module */
module.exports = function (grunt) {

    // grunt task config
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        tag: {
            banner: '/*  <%= pkg.name %>\n' +
                ' *  version <%= pkg.version %>\n' +
                ' *  Project: <%= pkg.homepage %>\n' +
                ' */\n'
        },
        copy: {
            build: {
                src: ['**', '!cmv/**', '!wab/**', '!node_modules/**', '!tests/**', '!package.json', '!gruntfile.js'],
                dest: 'dist',
                expand: true
            }
        },
        clean: {
            build: {
                src: ['dist']
            }
        },
        postcss: {
            build: {
                expand: true,
                cwd: 'dist/widgets',
                src: ['widgets/**/*.css'],
                dest: 'dist/widgets'
            }
        },
        cssmin: {
            build: {
                expand: true,
                cwd: 'dist',
                src: ['**/*.css'],
                dest: 'dist'
            }
        },

        csslint: {
            build: {
                src: ['widgets/**/*.css'],
                options: {
                    csslintrc: '.csslintrc'
                }
            }
        },

        eslint: {
            build: {
                src: ['cmv/js/viewer/_WABMixin.js', 'config/**/*.js'],
                options: {
                    eslintrc: '.eslintrc'
                }
            }
        },

        uglify: {
            build: {
                files: [{
                    expand: true,
                    cwd: 'dist',
                    src: ['**/*.js', '!**/config/**', '!**/cmv/**', '!**/wab/**'],
                    dest: 'dist',
                    ext: '.js'
                }],
                options: {
                    banner: '<%= tag.banner %>',
                    sourceMap: true,
                    sourceMapIncludeSources: true,
                    compress: {
                        'drop_console': false
                    }
                }
            }
        },

        watch: {
            dev: {
                files: ['widgets/**'],
                tasks: ['eslint', 'csslint']
            },
            build: {
                files: ['widgets/**'],
                tasks: ['eslint', 'csslint']
            }
        },

        connect: {
            dev: {
                options: {
                    port: 3000,
                    base: '.',
                    hostname: '*'
                }
            },
            build: {
                options: {
                    port: 3001,
                    base: 'dist/viewer',
                    hostname: '*'
                }
            }
        },
        open: {
            'dev_browser': {
                path: 'http://localhost:3000/demo.html'
            },
            'build_browser': {
                path: 'http://localhost:3001/demo.html'
            }
        },
        compress: {
            build: {
                options: {
                    archive: 'dist/cmv-wab-widgets.zip'
                },
                files: [{
                    expand: true,
                    cwd: 'dist'
                }]
            }
        }
    });

    // load the tasks
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-postcss');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-csslint');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-eslint');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-newer');
    grunt.loadNpmTasks('grunt-open');
    grunt.loadNpmTasks('grunt-contrib-compress');

    // define the tasks
    grunt.registerTask('default', 'Watches the project for changes, automatically builds them and runs a web server and opens default browser to preview.', ['eslint', 'csslint', 'connect:dev', 'open:dev_browser', 'watch:dev']);
    grunt.registerTask('build', 'Compiles all of the assets and copies the files to the build directory.', ['clean', 'copy', 'scripts', 'stylesheets', 'compress:build']);
    grunt.registerTask('build-view', 'Compiles all of the assets and copies the files to the build directory starts a web server and opens browser to preview app.', ['clean', 'copy', 'scripts', 'stylesheets', 'compress:build', 'connect:build', 'open:build_browser', 'watch:build']);
    grunt.registerTask('scripts', 'Compiles the JavaScript files.', ['eslint', 'uglify']);
    grunt.registerTask('stylesheets', 'Auto prefixes css and compiles the stylesheets.', ['csslint', 'postcss', 'cssmin']);
    grunt.registerTask('lint', 'Run simple eslint and csslint.', ['eslint', 'csslint']);
};