text:
using extensions::Extension;
using extensions::ExtensionActionManager;

namespace {

// The width of the browser action buttons.
const int kButtonWidth = 27;

// The padding between browser action buttons.
const int kButtonPadding = 4;

// The padding to the right of the browser action buttons (between the buttons
// and chevron if they are both showing).
const int kButtonChevronPadding = 2;

// The padding to the left, top and bottom of the browser actions toolbar
// separator.
const int kSeparatorPadding = 2;

// Width of the invisible gripper for resizing the toolbar.
const int kResizeGripperWidth = 4;

const char kDragTarget[] = "application/x-chrome-browseraction";

GtkTargetEntry GetDragTargetEntry() {
  GtkTargetEntry drag_target;
  drag_target.target = const_cast<char*>(kDragTarget);
  drag_target.flags = GTK_TARGET_SAME_APP;
  drag_target.info = 0;
  return drag_target;
}

// The minimum width in pixels of the button hbox if |icon_count| icons are
// showing.
gint WidthForIconCount(gint icon_count) {
  return std::max((kButtonWidth + kButtonPadding) * icon_count - kButtonPadding,
                  0);
}

}  // namespace

using ui::SimpleMenuModel;

class BrowserActionButton : public content::NotificationObserver,
                            public ExtensionActionIconFactory::Observer,
                            public ExtensionContextMenuModel::PopupDelegate,
                            public MenuGtk::Delegate {
 public:
  BrowserActionButton(BrowserActionsToolbarGtk* toolbar,
                      const Extension* extension,
                      GtkThemeService* theme_provider)
      : toolbar_(toolbar),
        extension_(extension),
        image_(NULL),
        icon_factory_(extension, browser_action(), this),
        accel_group_(NULL) {
    button_.reset(new CustomDrawButton(
        theme_provider,
        IDR_BROWSER_ACTION,
        IDR_BROWSER_ACTION_P,
        IDR_BROWSER_ACTION_H,
        0,
        NULL));
    gtk_widget_set_size_request(button(), kButtonWidth, kButtonWidth);
    alignment_.Own(gtk_alignment_new(0, 0, 1, 1));
    gtk_container_add(GTK_CONTAINER(alignment_.get()), button());
    gtk_widget_show(button());

    DCHECK(browser_action());

    UpdateState();

    signals_.Connect(button(), "button-press-event",
                     G_CALLBACK(OnButtonPress), this);
    signals_.Connect(button(), "clicked",
                     G_CALLBACK(OnClicked), this);
    signals_.Connect(button(), "drag-begin",
                     G_CALLBACK(OnDragBegin), this);
    signals_.ConnectAfter(widget(), "expose-event",
                     G_CALLBACK(OnExposeEvent), this);
    if (toolbar_->browser()->window()) {
      // If the window exists already, then the browser action button has been
      // recreated after the window was created, for example when the extension
      // is reloaded.
      ConnectBrowserActionPopupAccelerator();
    } else {
      // Window doesn't exist yet, wait for it.
      signals_.Connect(toolbar->widget(), "realize",
                       G_CALLBACK(OnRealize), this);
    }

    registrar_.Add(
        this, chrome::NOTIFICATION_EXTENSION_BROWSER_ACTION_UPDATED,
        content::Source<ExtensionAction>(browser_action()));
    registrar_.Add(
        this, chrome::NOTIFICATION_EXTENSION_UNLOADED,
        content::Source<Profile>(
            toolbar->browser()->profile()->GetOriginalProfile()));
    registrar_.Add(
        this, chrome::NOTIFICATION_EXTENSION_COMMAND_ADDED,
        content::Source<Profile>(
        toolbar->browser()->profile()->GetOriginalProfile()));
    registrar_.Add(
        this, chrome::NOTIFICATION_EXTENSION_COMMAND_REMOVED,
        content::Source<Profile>(
        toolbar->browser()->profile()->GetOriginalProfile()));
  }

  ~BrowserActionButton() {
    DisconnectBrowserActionPopupAccelerator();

    alignment_.Destroy();
  }

  GtkWidget* button() { return button_->widget(); }

  GtkWidget* widget() { return alignment_.get(); }

  const Extension* extension() { return extension_; }

  // NotificationObserver implementation.
  void Observe(int type,
               const content::NotificationSource& source,
               const content::NotificationDetails& details) {
    switch (type) {
     case chrome::NOTIFICATION_EXTENSION_BROWSER_ACTION_UPDATED:
      UpdateState();
      break;
     case chrome::NOTIFICATION_EXTENSION_UNLOADED:
     case chrome::NOTIFICATION_WINDOW_CLOSED:
      DisconnectBrowserActionPopupAccelerator();
      break;
     case chrome::NOTIFICATION_EXTENSION_COMMAND_ADDED:
     case chrome::NOTIFICATION_EXTENSION_COMMAND_REMOVED: {
      std::pair<const std::string, const std::string>* payload =
          content::Details<std::pair<const std::string, const std::string> >(
              details).ptr();
      if (extension_->id() == payload->first &&
          payload->second ==
              extension_manifest_values::kBrowserActionCommandEvent) {
        if (type == chrome::NOTIFICATION_EXTENSION_COMMAND_ADDED)
          ConnectBrowserActionPopupAccelerator();
        else
          DisconnectBrowserActionPopupAccelerator();
      }
      break;
     }
     default:
      NOTREACHED();
      break;
    }
  }

  // ExtensionActionIconFactory::Observer implementation.
  void OnIconUpdated() OVERRIDE {
    UpdateState();
  }

  // Updates the button based on the latest state from the associated
  // browser action.
  void UpdateState() {
    int tab_id = toolbar_->GetCurrentTabId();
    if (tab_id < 0)
      return;

    std::string tooltip = browser_action()->GetTitle(tab_id);
    if (tooltip.empty())
      gtk_widget_set_has_tooltip(button(), FALSE);
    else
      gtk_widget_set_tooltip_text(button(), tooltip.c_str());

    enabled_ = browser_action()->GetIsVisible(tab_id);
    if (!enabled_)
      button_->SetPaintOverride(GTK_STATE_INSENSITIVE);
    else
      button_->UnsetPaintOverride();

    gfx::Image image = icon_factory_.GetIcon(tab_id);
    if (!image.IsEmpty()) {
      if (enabled_) {
        SetImage(image);
      } else {
        SetImage(gfx::Image(gfx::ImageSkiaOperations::CreateTransparentImage(
            image.AsImageSkia(), .25)));
      }
    }

    gtk_widget_queue_draw(button());
  }

  gfx::Image GetIcon() {
    return icon_factory_.GetIcon(toolbar_->GetCurrentTabId());
  }

  MenuGtk* GetContextMenu() {
    if (!extension_->ShowConfigureContextMenus())
      return NULL;

    context_menu_model_ =
        new ExtensionContextMenuModel(extension_, toolbar_->browser(), this);
    context_menu_.reset(
        new MenuGtk(this, context_menu_model_.get()));
    return context_menu_.get();
  }

 private:
  // Activate the browser action.
  void Activate(GtkWidget* widget) {
    ExtensionToolbarModel* model = toolbar_->model();
    const Extension* extension = extension_;
    Browser* browser = toolbar_->browser();
    GURL popup_url;

    switch (model->ExecuteBrowserAction(extension, browser, &popup_url)) {
      case ExtensionToolbarModel::ACTION_NONE:
        break;
      case ExtensionToolbarModel::ACTION_SHOW_POPUP:
        ExtensionPopupGtk::Show(popup_url, browser, widget,
                                ExtensionPopupGtk::SHOW);
        break;
    }
  }

  // MenuGtk::Delegate implementation.
  virtual void StoppedShowing() {
    if (enabled_)
      button_->UnsetPaintOverride();
    else
      button_->SetPaintOverride(GTK_STATE_INSENSITIVE);

    // If the context menu was showing for the overflow menu, re-assert the
    // grab that was shadowed.
    if (toolbar_->overflow_menu_.get())
      gtk_util::GrabAllInput(toolbar_->overflow_menu_->widget());
  }

  virtual void CommandWillBeExecuted() {
    // If the context menu was showing for the overflow menu, and a command
    // is executed, then stop showing the overflow menu.
    if (toolbar_->overflow_menu_.get())
      toolbar_->overflow_menu_->Cancel();
  }

  // ExtensionContextMenuModel::PopupDelegate implementation.
  virtual void InspectPopup(ExtensionAction* action) {
    GURL popup_url = action->GetPopupUrl(toolbar_->GetCurrentTabId());
    ExtensionPopupGtk::Show(popup_url, toolbar_->browser(), widget(),
                            ExtensionPopupGtk::SHOW_AND_INSPECT);
  }

  void SetImage(const gfx::Image& image) {
    if (!image_) {
      image_ = gtk_image_new_from_pixbuf(image.ToGdkPixbuf());
      gtk_button_set_image(GTK_BUTTON(button()), image_);
    } else {
      gtk_image_set_from_pixbuf(GTK_IMAGE(image_), image.ToGdkPixbuf());
    }
  }

  static gboolean OnButtonPress(GtkWidget* widget,
                                GdkEventButton* event,
                                BrowserActionButton* button) {
    if (event->button != 3)
      return FALSE;

    MenuGtk* menu = button->GetContextMenu();
    if (!menu)
      return FALSE;

    button->button_->SetPaintOverride(GTK_STATE_ACTIVE);
    menu->PopupForWidget(widget, event->button, event->time);

    return TRUE;
  }

  static void OnClicked(GtkWidget* widget, BrowserActionButton* button) {
    if (button->enabled_)
      button->Activate(widget);
  }

  static gboolean OnExposeEvent(GtkWidget* widget,
                                GdkEventExpose* event,
                                BrowserActionButton* button) {
    int tab_id = button->toolbar_->GetCurrentTabId();
    if (tab_id < 0)
      return FALSE;

    ExtensionAction* action = button->browser_action();
    if (action->GetBadgeText(tab_id).empty())
      return FALSE;

    gfx::CanvasSkiaPaint canvas(event, false);
    GtkAllocation allocation;
    gtk_widget_get_allocation(widget, &allocation);
    action->PaintBadge(&canvas, gfx::Rect(allocation), tab_id);
    return FALSE;
  }

  static void OnDragBegin(GtkWidget* widget,
                          GdkDragContext* drag_context,
                          BrowserActionButton* button) {
    // Simply pass along the notification to the toolbar. The point of this
    // function is to tell the toolbar which BrowserActionButton initiated the
    // drag.
    button->toolbar_->DragStarted(button, drag_context);
  }

  // The accelerator handler for when the shortcuts to open the popup is struck.
  static gboolean OnGtkAccelerator(GtkAccelGroup* accel_group,
                                   GObject* acceleratable,
                                   guint keyval,
                                   GdkModifierType modifier,
                                   BrowserActionButton* button) {
    // Open the popup for this extension.
    GtkWidget* anchor = button->widget();
    // The anchor might be in the overflow menu. Then we point to the chevron.
    if (!gtk_widget_get_visible(anchor))
      anchor = button->toolbar_->chevron();
    button->Activate(anchor);
    return TRUE;
  }

  // The handler for when the browser action is realized. |user_data| contains a
  // pointer to the BrowserAction shown.
  static void OnRealize(GtkWidget* widget, void* user_data) {
    BrowserActionButton* button = static_cast<BrowserActionButton*>(user_data);
    button->ConnectBrowserActionPopupAccelerator();
  }

  // Connect the accelerator for the browser action popup.
  void ConnectBrowserActionPopupAccelerator() {
    extensions::CommandService* command_service =
        extensions::CommandServiceFactory::GetForProfile(
            toolbar_->browser()->profile());
    extensions::Command command;
    if (command_service->GetBrowserActionCommand(extension_->id(),
        extensions::CommandService::ACTIVE_ONLY,
        &command,
        NULL)) {
      // Found the browser action shortcut command, register it.
      keybinding_.reset(new ui::AcceleratorGtk(
          command.accelerator().key_code(),
          command.accelerator().IsShiftDown(),
          command.accelerator().IsCtrlDown(),
          command.accelerator().IsAltDown()));

      gfx::NativeWindow window =
          toolbar_->browser()->window()->GetNativeWindow();
      accel_group_ = gtk_accel_group_new();
      gtk_window_add_accel_group(window, accel_group_);

      gtk_accel_group_connect(
          accel_group_,
          keybinding_.get()->GetGdkKeyCode(),
          keybinding_.get()->gdk_modifier_type(),
          GtkAccelFlags(0),
          g_cclosure_new(G_CALLBACK(OnGtkAccelerator), this, NULL));

      // Since we've added an accelerator, we'll need to unregister it before
      // the window is closed, so we listen for the window being closed.
      registrar_.Add(this,
                     chrome::NOTIFICATION_WINDOW_CLOSED,
                     content::Source<GtkWindow>(window));
    }
  }

  // Disconnect the accelerator for the browser action popup and delete clean up
  // the accelerator group registration.
  void DisconnectBrowserActionPopupAccelerator() {
    if (accel_group_) {
      gfx::NativeWindow window =
          toolbar_->browser()->window()->GetNativeWindow();
      gtk_accel_group_disconnect_key(
          accel_group_,
          keybinding_.get()->GetGdkKeyCode(),
          static_cast<GdkModifierType>(keybinding_.get()->modifiers()));
      gtk_window_remove_accel_group(window, accel_group_);
      g_object_unref(accel_group_);
      accel_group_ = NULL;
      keybinding_.reset(NULL);

      // We've removed the accelerator, so no need to listen to this anymore.
      registrar_.Remove(this,
                        chrome::NOTIFICATION_WINDOW_CLOSED,
                        content::Source<GtkWindow>(window));
    }
  }

  ExtensionAction* browser_action() const {
    return ExtensionActionManager::Get(toolbar_->browser()->profile())->
        GetBrowserAction(*extension_);
  }

  // The toolbar containing this button.
  BrowserActionsToolbarGtk* toolbar_;

  // The extension that contains this browser action.
  const Extension* extension_;

  // The button for this browser action.
  scoped_ptr<CustomDrawButton> button_;

  // Whether the browser action is enabled (equivalent to whether a page action
  // is visible).
  bool enabled_;

  // The top level widget (parent of |button_|).
  ui::OwnedWidgetGtk alignment_;

  // The one image subwidget in |button_|. We keep this out so we don't alter
  // the widget hierarchy while changing the button image because changing the
  // GTK widget hierarchy invalidates all tooltips and several popular
  // extensions change browser action icon in a loop.
  GtkWidget* image_;

  // The object that will be used to get the browser action icon for us.
  // It may load the icon asynchronously (in which case the initial icon
  // returned by the factory will be transparent), so we have to observe it for
  // updates to the icon.
  ExtensionActionIconFactory icon_factory_;

  // Same as |default_icon_|, but stored as SkBitmap.
  SkBitmap default_skbitmap_;

  ui::GtkSignalRegistrar signals_;
  content::NotificationRegistrar registrar_;

  // The accelerator group used to handle accelerators, owned by this object.
  GtkAccelGroup* accel_group_;

  // The keybinding accelerator registered to show the browser action popup.
  scoped_ptr<ui::AcceleratorGtk> keybinding_;

  // The context menu view and model for this extension action.
  scoped_ptr<MenuGtk> context_menu_;
  scoped_refptr<ExtensionContextMenuModel> context_menu_model_;

  friend class BrowserActionsToolbarGtk;
};

// BrowserActionsToolbarGtk ----------------------------------------------------

BrowserActionsToolbarGtk::BrowserActionsToolbarGtk(Browser* browser)
    : browser_(browser),
      profile_(browser->profile()),
      theme_service_(GtkThemeService::GetFrom(browser->profile())),
      model_(NULL),
      hbox_(gtk_hbox_new(FALSE, 0)),
      button_hbox_(gtk_chrome_shrinkable_hbox_new(TRUE, FALSE, kButtonPadding)),
      drag_button_(NULL),
      drop_index_(-1),
      resize_animation_(this),
      desired_width_(0),
      start_width_(0),
      weak_factory_(this) {
  ExtensionService* extension_service = profile_->GetExtensionService();
  // The |extension_service| can be NULL in Incognito.
  if (!extension_service)
    return;

  overflow_button_.reset(new CustomDrawButton(
      theme_service_,
      IDR_BROWSER_ACTIONS_OVERFLOW,
      IDR_BROWSER_ACTIONS_OVERFLOW_P,
      IDR_BROWSER_ACTIONS_OVERFLOW_H,
      0,
      gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_NONE)));

  GtkWidget* gripper = gtk_button_new();
  gtk_widget_set_size_request(gripper, kResizeGripperWidth, -1);
  gtk_widget_set_can_focus(gripper, FALSE);

  gtk_widget_add_events(gripper, GDK_POINTER_MOTION_MASK);
  signals_.Connect(gripper, "motion-notify-event",
                   G_CALLBACK(OnGripperMotionNotifyThunk), this);
  signals_.Connect(gripper, "expose-event",
                   G_CALLBACK(OnGripperExposeThunk), this);
  signals_.Connect(gripper, "enter-notify-event",
                   G_CALLBACK(OnGripperEnterNotifyThunk), this);
  signals_.Connect(gripper, "leave-notify-event",
                   G_CALLBACK(OnGripperLeaveNotifyThunk), this);
  signals_.Connect(gripper, "button-release-event",
                   G_CALLBACK(OnGripperButtonReleaseThunk), this);
  signals_.Connect(gripper, "button-press-event",
                   G_CALLBACK(OnGripperButtonPressThunk), this);
  signals_.Connect(chevron(), "button-press-event",
                   G_CALLBACK(OnOverflowButtonPressThunk), this);

  // |overflow_alignment| adds padding to the right of the browser action
  // buttons, but only appears when the overflow menu is showing.
  overflow_alignment_ = gtk_alignment_new(0, 0, 1, 1);
  gtk_container_add(GTK_CONTAINER(overflow_alignment_), chevron());

  // |overflow_area_| holds the overflow chevron and the separator, which
  // is only shown in GTK+ theme mode.
  overflow_area_ = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(overflow_area_), overflow_alignment_,
                     FALSE, FALSE, 0);

  separator_ = gtk_vseparator_new();
  gtk_box_pack_start(GTK_BOX(overflow_area_), separator_,
                     FALSE, FALSE, 0);
  gtk_widget_set_no_show_all(separator_, TRUE);

  gtk_widget_show_all(overflow_area_);
  gtk_widget_set_no_show_all(overflow_area_, TRUE);

  gtk_box_pack_start(GTK_BOX(hbox_.get()), gripper, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(hbox_.get()), button_hbox_.get(), TRUE, TRUE, 0);
  gtk_box_pack_start(GTK_BOX(hbox_.get()), overflow_area_, FALSE, FALSE, 0);

  model_ = extension_service->toolbar_model();
  model_->AddObserver(this);
  SetupDrags();

  if (model_->extensions_initialized()) {
    CreateAllButtons();
    SetContainerWidth();
  }

  // We want to connect to "set-focus" on the toplevel window; we have to wait
  // until we are added to a toplevel window to do so.
  signals_.Connect(widget(), "hierarchy-changed",
                   G_CALLBACK(OnHierarchyChangedThunk), this);

  ViewIDUtil::SetID(button_hbox_.get(), VIEW_ID_BROWSER_ACTION_TOOLBAR);

  registrar_.Add(this,
                 chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
                 content::Source<ThemeService>(theme_service_));
  theme_service_->InitThemesFor(this);
}

BrowserActionsToolbarGtk::~BrowserActionsToolbarGtk() {
  if (model_)
    model_->RemoveObserver(this);
  button_hbox_.Destroy();
  hbox_.Destroy();
}

int BrowserActionsToolbarGtk::GetCurrentTabId() const {
  content::WebContents* active_tab = chrome::GetActiveWebContents(browser_);
  if (!active_tab)
    return -1;

  return SessionTabHelper::FromWebContents(active_tab)->session_id().id();
}

void BrowserActionsToolbarGtk::Update() {
  for (ExtensionButtonMap::iterator iter = extension_button_map_.begin();
       iter != extension_button_map_.end(); ++iter) {
    iter->second->UpdateState();
  }
}

void BrowserActionsToolbarGtk::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  DCHECK(chrome::NOTIFICATION_BROWSER_THEME_CHANGED == type);
  gtk_widget_set_visible(separator_, theme_service_->UsingNativeTheme());
}

void BrowserActionsToolbarGtk::SetupDrags() {
  GtkTargetEntry drag_target = GetDragTargetEntry();
  gtk_drag_dest_set(button_hbox_.get(), GTK_DEST_DEFAULT_DROP, &drag_target, 1,
                    GDK_ACTION_MOVE);

  signals_.Connect(button_hbox_.get(), "drag-motion",
                   G_CALLBACK(OnDragMotionThunk), this);
}

void BrowserActionsToolbarGtk::CreateAllButtons() {
  extension_button_map_.clear();

  int i = 0;
  const extensions::ExtensionList& toolbar_items = model_->toolbar_items();
  for (extensions::ExtensionList::const_iterator iter = toolbar_items.begin();
       iter != toolbar_items.end(); ++iter) {
    CreateButtonForExtension(*iter, i++);
  }
}

void BrowserActionsToolbarGtk::SetContainerWidth() {
  int showing_actions = model_->GetVisibleIconCount();
  if (showing_actions >= 0)
    SetButtonHBoxWidth(WidthForIconCount(showing_actions));
}

void BrowserActionsToolbarGtk::CreateButtonForExtension(
    const Extension* extension, int index) {
  if (!ShouldDisplayBrowserAction(extension))
    return;

  if (profile_->IsOffTheRecord())
    index = model_->OriginalIndexToIncognito(index);

  RemoveButtonForExtension(extension);
  linked_ptr<BrowserActionButton> button(
      new BrowserActionButton(this, extension, theme_service_));
  gtk_chrome_shrinkable_hbox_pack_start(
      GTK_CHROME_SHRINKABLE_HBOX(button_hbox_.get()), button->widget(), 0);
  gtk_box_reorder_child(GTK_BOX(button_hbox_.get()), button->widget(), index);
  extension_button_map_[extension->id()] = button;

  GtkTargetEntry drag_target = GetDragTargetEntry();
  gtk_drag_source_set(button->button(), GDK_BUTTON1_MASK, &drag_target, 1,
                      GDK_ACTION_MOVE);
  // We ignore whether the drag was a "success" or "failure" in Gtk's opinion.
  signals_.Connect(button->button(), "drag-end",
                   G_CALLBACK(&OnDragEndThunk), this);
  signals_.Connect(button->button(), "drag-failed",
                   G_CALLBACK(&OnDragFailedThunk), this);

  // Any time a browser action button is shown or hidden we have to update
  // the chevron state.
  signals_.Connect(button->widget(), "show",
                   G_CALLBACK(&OnButtonShowOrHideThunk), this);
  signals_.Connect(button->widget(), "hide",
                   G_CALLBACK(&OnButtonShowOrHideThunk), this);

  gtk_widget_show(button->widget());

  UpdateVisibility();
}

GtkWidget* BrowserActionsToolbarGtk::GetBrowserActionWidget(
    const Extension* extension) {
  ExtensionButtonMap::iterator it = extension_button_map_.find(
      extension->id());
  if (it == extension_button_map_.end())
    return NULL;

  return it->second.get()->widget();
}

void BrowserActionsToolbarGtk::RemoveButtonForExtension(
    const Extension* extension) {
  if (extension_button_map_.erase(extension->id()))
    UpdateVisibility();
  UpdateChevronVisibility();
}

void BrowserActionsToolbarGtk::UpdateVisibility() {
  gtk_widget_set_visible(widget(), button_count() != 0);
}

bool BrowserActionsToolbarGtk::ShouldDisplayBrowserAction(
    const Extension* extension) {
  // Only display incognito-enabled extensions while in incognito mode.
  return (!profile_->IsOffTheRecord() ||
          profile_->GetExtensionService()->IsIncognitoEnabled(extension->id()));
}

void BrowserActionsToolbarGtk::HidePopup() {
  ExtensionPopupGtk* popup = ExtensionPopupGtk::get_current_extension_popup();
  if (popup)
    popup->DestroyPopup();
}

void BrowserActionsToolbarGtk::AnimateToShowNIcons(int count) {
  desired_width_ = WidthForIconCount(count);

  GtkAllocation allocation;
  gtk_widget_get_allocation(button_hbox_.get(), &allocation);
  start_width_ = allocation.width;

  resize_animation_.Reset();
  resize_animation_.Show();
}

void BrowserActionsToolbarGtk::BrowserActionAdded(const Extension* extension,
                                                  int index) {
  overflow_menu_.reset();

  CreateButtonForExtension(extension, index);

  // If we are still initializing the container, don't bother animating.
  if (!model_->extensions_initialized())
    return;

  // Animate the addition if we are showing all browser action buttons.
  if (!gtk_widget_get_visible(overflow_area_)) {
    AnimateToShowNIcons(button_count());
    model_->SetVisibleIconCount(button_count());
  }
}

void BrowserActionsToolbarGtk::BrowserActionRemoved(
    const Extension* extension) {
  overflow_menu_.reset();

  if (drag_button_ != NULL) {
    // Break the current drag.
    gtk_grab_remove(button_hbox_.get());
  }

  RemoveButtonForExtension(extension);

  if (!gtk_widget_get_visible(overflow_area_)) {
    AnimateToShowNIcons(button_count());
    model_->SetVisibleIconCount(button_count());
  }
}

void BrowserActionsToolbarGtk::BrowserActionMoved(const Extension* extension,
                                                  int index) {
  // We initiated this move action, and have already moved the button.
  if (drag_button_ != NULL)
    return;

  GtkWidget* button_widget = GetBrowserActionWidget(extension);
  if (!button_widget) {
    if (ShouldDisplayBrowserAction(extension))
      NOTREACHED();
    return;
  }

  if (profile_->IsOffTheRecord())
    index = model_->OriginalIndexToIncognito(index);

  gtk_box_reorder_child(GTK_BOX(button_hbox_.get()), button_widget, index);
}

void BrowserActionsToolbarGtk::ModelLoaded() {
  SetContainerWidth();
}

void BrowserActionsToolbarGtk::AnimationProgressed(
    const ui::Animation* animation) {
  int width = start_width_ + (desired_width_ - start_width_) *
      animation->GetCurrentValue();
  gtk_widget_set_size_request(button_hbox_.get(), width, -1);

  if (width == desired_width_)
    resize_animation_.Reset();
}

void BrowserActionsToolbarGtk::AnimationEnded(const ui::Animation* animation) {
  gtk_widget_set_size_request(button_hbox_.get(), desired_width_, -1);
  UpdateChevronVisibility();
}

bool BrowserActionsToolbarGtk::IsCommandIdChecked(int command_id) const {
  return false;
}

bool BrowserActionsToolbarGtk::IsCommandIdEnabled(int command_id) const {
  const Extension* extension = model_->toolbar_items()[command_id];
  return ExtensionActionManager::Get(profile_)->
      GetBrowserAction(*extension)->GetIsVisible(GetCurrentTabId());
}

bool BrowserActionsToolbarGtk::GetAcceleratorForCommandId(
    int command_id,
    ui::Accelerator* accelerator) {
  return false;
}

void BrowserActionsToolbarGtk::ExecuteCommand(int command_id) {
  const Extension* extension = model_->toolbar_items()[command_id];
  GURL popup_url;

  switch (model_->ExecuteBrowserAction(extension, browser(), &popup_url)) {
    case ExtensionToolbarModel::ACTION_NONE:
      break;
    case ExtensionToolbarModel::ACTION_SHOW_POPUP:
      ExtensionPopupGtk::Show(popup_url, browser(), chevron(),
                              ExtensionPopupGtk::SHOW);
      break;
  }
}

void BrowserActionsToolbarGtk::StoppedShowing() {
  overflow_button_->UnsetPaintOverride();
}

bool BrowserActionsToolbarGtk::AlwaysShowIconForCmd(int command_id) const {
  return true;
}

void BrowserActionsToolbarGtk::DragStarted(BrowserActionButton* button,
                                           GdkDragContext* drag_context) {
  // No representation of the widget following the cursor.
  GdkPixbuf* pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8, 1, 1);
  gtk_drag_set_icon_pixbuf(drag_context, pixbuf, 0, 0);
  g_object_unref(pixbuf);

  DCHECK(!drag_button_);
  drag_button_ = button;
}

void BrowserActionsToolbarGtk::SetButtonHBoxWidth(int new_width) {
  gint max_width = WidthForIconCount(button_count());
  new_width = std::min(max_width, new_width);
  new_width = std::max(new_width, 0);
  gtk_widget_set_size_request(button_hbox_.get(), new_width, -1);
}

void BrowserActionsToolbarGtk::UpdateChevronVisibility() {
  int showing_icon_count =
      gtk_chrome_shrinkable_hbox_get_visible_child_count(
          GTK_CHROME_SHRINKABLE_HBOX(button_hbox_.get()));
  if (showing_icon_count == 0) {
    gtk_alignment_set_padding(GTK_ALIGNMENT(overflow_alignment_), 0, 0, 0, 0);
  } else {
    gtk_alignment_set_padding(GTK_ALIGNMENT(overflow_alignment_), 0, 0,
                              kButtonChevronPadding, 0);
  }

  if (button_count() > showing_icon_count) {
    if (!gtk_widget_get_visible(overflow_area_)) {
      if (drag_button_) {
        // During drags, when the overflow chevron shows for the first time,
        // take that much space away from |button_hbox_| to make the drag look
        // smoother.
        GtkRequisition req;
        gtk_widget_size_request(chevron(), &req);
        gint overflow_width = req.width;
        gtk_widget_size_request(button_hbox_.get(), &req);
        gint button_hbox_width = req.width;
        button_hbox_width = std::max(button_hbox_width - overflow_width, 0);
        gtk_widget_set_size_request(button_hbox_.get(), button_hbox_width, -1);
      }

      gtk_widget_show(overflow_area_);
    }
  } else {
    gtk_widget_hide(overflow_area_);
  }
}

gboolean BrowserActionsToolbarGtk::OnDragMotion(GtkWidget* widget,
                                                GdkDragContext* drag_context,
                                                gint x, gint y, guint time) {
  // Only handle drags we initiated.
  if (!drag_button_)
    return FALSE;

  if (base::i18n::IsRTL()) {
    GtkAllocation allocation;
    gtk_widget_get_allocation(widget, &allocation);
    x = allocation.width - x;
  }

  drop_index_ = x < kButtonWidth ? 0 : x / (kButtonWidth + kButtonPadding);

  // We will go ahead and reorder the child in order to provide visual feedback
  // to the user. We don't inform the model that it has moved until the drag
  // ends.
  gtk_box_reorder_child(GTK_BOX(button_hbox_.get()), drag_button_->widget(),
                        drop_index_);

  gdk_drag_status(drag_context, GDK_ACTION_MOVE, time);
  return TRUE;
}

void BrowserActionsToolbarGtk::OnDragEnd(GtkWidget* button,
                                         GdkDragContext* drag_context) {
  if (drop_index_ != -1) {
    if (profile_->IsOffTheRecord())
      drop_index_ = model_->IncognitoIndexToOriginal(drop_index_);

    model_->MoveBrowserAction(drag_button_->extension(), drop_index_);
  }

  drag_button_ = NULL;
  drop_index_ = -1;
}

gboolean BrowserActionsToolbarGtk::OnDragFailed(GtkWidget* widget,
                                                GdkDragContext* drag_context,
                                                GtkDragResult result) {
  // We connect to this signal and return TRUE so that the default failure
  // animation (wherein the drag widget floats back to the start of the drag)
  // does not show, and the drag-end signal is emitted immediately instead of
  // several seconds later.
  return TRUE;
}

void BrowserActionsToolbarGtk::OnHierarchyChanged(
    GtkWidget* widget, GtkWidget* previous_toplevel) {
  GtkWidget* toplevel = gtk_widget_get_toplevel(widget);
  if (!gtk_widget_is_toplevel(toplevel))
    return;

  signals_.Connect(toplevel, "set-focus", G_CALLBACK(OnSetFocusThunk), this);
}

void BrowserActionsToolbarGtk::OnSetFocus(GtkWidget* widget,
                                          GtkWidget* focus_widget) {
  ExtensionPopupGtk* popup = ExtensionPopupGtk::get_current_extension_popup();
  // The focus of the parent window has changed. Close the popup. Delay the hide
  // because it will destroy the RenderViewHost, which may still be on the
  // call stack.
  if (!popup || popup->being_inspected())
    return;
  MessageLoop::current()->PostTask(
      FROM_HERE,
      base::Bind(&BrowserActionsToolbarGtk::HidePopup,
                 weak_factory_.GetWeakPtr()));
}

gboolean BrowserActionsToolbarGtk::OnGripperMotionNotify(
    GtkWidget* widget, GdkEventMotion* event) {
  if (!(event->state & GDK_BUTTON1_MASK))
    return FALSE;

  // Calculate how much the user dragged the gripper and subtract that off the
  // button container's width.
  int distance_dragged;
  if (base::i18n::IsRTL()) {
    distance_dragged = -event->x;
  } else {
    GtkAllocation widget_allocation;
    gtk_widget_get_allocation(widget, &widget_allocation);
    distance_dragged = event->x - widget_allocation.width;
  }

  GtkAllocation button_hbox_allocation;
  gtk_widget_get_allocation(button_hbox_.get(), &button_hbox_allocation);
  gint new_width = button_hbox_allocation.width - distance_dragged;
  SetButtonHBoxWidth(new_width);

  return FALSE;
}

gboolean BrowserActionsToolbarGtk::OnGripperExpose(GtkWidget* gripper,
                                                   GdkEventExpose* expose) {
  return TRUE;
}

// These three signal handlers (EnterNotify, LeaveNotify, and ButtonRelease)
// are used to give the gripper the resize cursor. Since it doesn't have its
// own window, we have to set the cursor whenever the pointer moves into the
// button or leaves the button, and be sure to leave it on when the user is
// dragging.
gboolean BrowserActionsToolbarGtk::OnGripperEnterNotify(
    GtkWidget* gripper, GdkEventCrossing* event) {
  gdk_window_set_cursor(gtk_widget_get_window(gripper),
                        gfx::GetCursor(GDK_SB_H_DOUBLE_ARROW));
  return FALSE;
}

gboolean BrowserActionsToolbarGtk::OnGripperLeaveNotify(
    GtkWidget* gripper, GdkEventCrossing* event) {
  if (!(event->state & GDK_BUTTON1_MASK))
    gdk_window_set_cursor(gtk_widget_get_window(gripper), NULL);
  return FALSE;
}

gboolean BrowserActionsToolbarGtk::OnGripperButtonRelease(
    GtkWidget* gripper, GdkEventButton* event) {
  GtkAllocation allocation;
  gtk_widget_get_allocation(gripper, &allocation);
  gfx::Rect gripper_rect(0, 0, allocation.width, allocation.height);

  gfx::Point release_point(event->x, event->y);
  if (!gripper_rect.Contains(release_point))
    gdk_window_set_cursor(gtk_widget_get_window(gripper), NULL);

  // After the user resizes the toolbar, we want to smartly resize it to be
  // the perfect size to fit the buttons.
  int visible_icon_count =
      gtk_chrome_shrinkable_hbox_get_visible_child_count(
          GTK_CHROME_SHRINKABLE_HBOX(button_hbox_.get()));
  AnimateToShowNIcons(visible_icon_count);
  model_->SetVisibleIconCount(visible_icon_count);

  return FALSE;
}

gboolean BrowserActionsToolbarGtk::OnGripperButtonPress(
    GtkWidget* gripper, GdkEventButton* event) {
  resize_animation_.Reset();

  return FALSE;
}

gboolean BrowserActionsToolbarGtk::OnOverflowButtonPress(
    GtkWidget* overflow, GdkEventButton* event) {
  overflow_menu_model_.reset(new SimpleMenuModel(this));

  int visible_icon_count =
      gtk_chrome_shrinkable_hbox_get_visible_child_count(
          GTK_CHROME_SHRINKABLE_HBOX(button_hbox_.get()));
  for (int i = visible_icon_count; i < button_count(); ++i) {
    int model_index = i;
    if (profile_->IsOffTheRecord())
      model_index = model_->IncognitoIndexToOriginal(i);

    const Extension* extension = model_->toolbar_items()[model_index];
    BrowserActionButton* button = extension_button_map_[extension->id()].get();

    overflow_menu_model_->AddItem(model_index, UTF8ToUTF16(extension->name()));
    overflow_menu_model_->SetIcon(overflow_menu_model_->GetItemCount() - 1,
                                  button->GetIcon());

    // TODO(estade): set the menu item's tooltip.
  }

  overflow_menu_.reset(new MenuGtk(this, overflow_menu_model_.get()));
  signals_.Connect(overflow_menu_->widget(), "button-press-event",
                   G_CALLBACK(OnOverflowMenuButtonPressThunk), this);

  overflow_button_->SetPaintOverride(GTK_STATE_ACTIVE);
  overflow_menu_->PopupAsFromKeyEvent(chevron());

  return FALSE;
}

gboolean BrowserActionsToolbarGtk::OnOverflowMenuButtonPress(
    GtkWidget* overflow, GdkEventButton* event) {
  if (event->button != 3)
    return FALSE;

  GtkWidget* menu_item = GTK_MENU_SHELL(overflow)->active_menu_item;
  if (!menu_item)
    return FALSE;

  int item_index = g_list_index(GTK_MENU_SHELL(overflow)->children, menu_item);
  if (item_index == -1) {
    NOTREACHED();
    return FALSE;
  }

  item_index += gtk_chrome_shrinkable_hbox_get_visible_child_count(
      GTK_CHROME_SHRINKABLE_HBOX(button_hbox_.get()));
  if (profile_->IsOffTheRecord())
    item_index = model_->IncognitoIndexToOriginal(item_index);

  const Extension* extension = model_->toolbar_items()[item_index];
  ExtensionButtonMap::iterator it = extension_button_map_.find(
      extension->id());
  if (it == extension_button_map_.end()) {
    NOTREACHED();
    return FALSE;
  }

  MenuGtk* menu = it->second.get()->GetContextMenu();
  if (!menu)
    return FALSE;

  menu->PopupAsContext(gfx::Point(event->x_root, event->y_root),
                       event->time);
  return TRUE;
}

void BrowserActionsToolbarGtk::OnButtonShowOrHide(GtkWidget* sender) {
  if (!resize_animation_.is_animating())
    UpdateChevronVisibility();
}


text:
package com.yahoo.yqlplus.engine.internal.bytecode.types.gambit;

import com.yahoo.yqlplus.engine.internal.plan.types.BytecodeExpression;
import com.yahoo.yqlplus.engine.internal.plan.types.TypeWidget;

public interface InvocableBuilder extends ScopedBuilder {
    BytecodeExpression addArgument(String name, TypeWidget type);

    Invocable complete(BytecodeExpression result);
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * \file
 * @brief Contains the TPZThermicElast3D class which implements a 3D isotropic elasticity material with thermal stress.
 */

//$Id: pzthermicelast3d.h,v 1.3 2009-09-01 19:44:48 phil Exp $

#ifndef PZTHERMICELAST3D
#define PZTHERMICELAST3D

#include "pzelast3d.h"

/**
 * @ingroup material
 * @brief This class implements a 3D isotropic elasticity material with thermal stress.
 */
/**
 * The thermal field can be a constant value or a field obtained from a previous simmulation.
 * In case of using a field previously obtained it is input by using TPZReferredCompEl and the field
 * comes in the TPZVec<REAL> sol parameter of Contribute method.
 *  @since May 10, 2006.
 */
class TPZThermicElast3D : public TPZElasticity3D {

private:

	/**
	 * @brief Flag indicating a constant field of temperature (fReferred = false) or a field obtained \n
	 * in a previous simmulation (fReferred = true). Default value is true
	 */
	bool fReferred;

	/**
	 * @brief When solving problem with a constant field of temperature (fReferred = false) fFinalTemperature \n
	 * is the final temperature of the body. Thermal stress is given by the difference of fFinalTemperature and fRefTemperature. \n
	 * When fReferred = true fFinalTemperature does not make sense and is not used
	 */
	REAL fFinalTemperature;

public:

	/** @brief Thermal expansion coefficient of the material */
	REAL fThermalCoeff;

	/** @brief Temperature of reference. The thermal stress is given by the difference of the temperature field to this reference value */
	REAL fRefTemperature;

	/**
	 * @brief Class constructor.
	 * @param nummat - material ID.
	 * @param ThermalCoeff - thermal expansion coefficient of the material
	 * @param RefTemp - temperature of reference
	 * @param E - Young's modulus.
	 * @param poisson - poisson's ratio
	 * @param force - external forces
	 */
	TPZThermicElast3D(int nummat, REAL ThermalCoeff, REAL RefTemp, REAL E, REAL poisson, TPZVec<REAL> &force);

	/** @brief Default destructor */
	virtual ~TPZThermicElast3D();

	void SetConstantTemperatureField(REAL FinalTemp){
		this->fFinalTemperature = FinalTemp;
		this->fReferred = false;
	}

	void SetReferredTemperatureField(){
		this->fFinalTemperature = 0.; //any value, it will not be used
		this->fReferred = true;
	}

	bool IsReferredTemperatureField(){
		return this->fReferred;
	}

	void ContributeThermalStress(TPZVec<REAL> &sol, TPZFMatrix<REAL> &phi, TPZFMatrix<REAL> &dphi, REAL weight, TPZFMatrix<REAL> &ef);

	/** @brief Contribute to stiff matrix and load vector */
	virtual void Contribute(TPZMaterialData &data,
							REAL weight,
							TPZFMatrix<REAL> &ek,
							TPZFMatrix<REAL> &ef);

	virtual void Contribute(TPZMaterialData &data,
							REAL weight,
							TPZFMatrix<REAL> &ef)
	{
		TPZElasticity3D::Contribute(data,weight,ef);
	}

protected:
	virtual void Solution(TPZVec<REAL> &Sol, TPZFMatrix<REAL> &DSol,
						  TPZFMatrix<REAL> &axes, int var, TPZVec<REAL> &Solout);
public:
	virtual void Solution(TPZMaterialData &data, int var, TPZVec<REAL> &Solout)
	{
        int numbersol = data.sol.size();
        if (numbersol != 1) {
            DebugStop();
        }
		Solution(data.sol[0],data.dsol[0],data.axes,var,Solout);
	}

};

#endif


text:
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/:page', function (req, res, next) {
  res.render(req.params.page);
})

router.get('/:dir/:page', function(req, res) {
  res.render(req.params.dir+'/'+req.params.page);
});

module.exports = router;


text:
c: bbb_bbb_bbb
audio: shot
return_link: 'cc'
type: balloon
keys: 1
---
Before we attempted

to make ourselves right

before God.


text:
package ccf.session

import java.util.UUID

case class ChannelId(id: UUID) {
  override def toString = id.toString
}

object ChannelId {
  def apply(str: String): Option[ChannelId] = {
    try {
      Some(ChannelId(UUID.fromString(str)))
    }
    catch {
      case _ => None
    }
  }

  def randomId = ChannelId(UUID.randomUUID)
}


text:
package com.orangerhymelabs.helenus.exception;

/**
 * @author tfredrich
 * @since May 7, 2015
 */
public class ItemNotFoundException
extends StorageException
{
	private static final long serialVersionUID = -149539551035269112L;

	public ItemNotFoundException()
	{
	}

	/**
	 * @param message
	 */
	public ItemNotFoundException(String message)
	{
		super(message);
	}

	/**
	 * @param cause
	 */
	public ItemNotFoundException(Throwable cause)
	{
		super(cause);
	}

	/**
	 * @param message
	 * @param cause
	 */
	public ItemNotFoundException(String message, Throwable cause)
	{
		super(message, cause);
	}

	/**
	 * @param message
	 * @param cause
	 * @param enableSuppression
	 * @param writableStackTrace
	 */
	public ItemNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)
	{
		super(message, cause, enableSuppression, writableStackTrace);
	}
}


text:
Open source relational storage for [FHIR](http://hl7.org/implement/standards/fhir/) with document API

[![Build Status](https://travis-ci.org/fhirbase/fhirbase.png?branch=master)](https://travis-ci.org/fhirbase/fhirbase)

Powered by [Health Samurai](http://healthsamurai.github.io/)

Sponsored by:

![choice-hs.com](http://choice-hs.com/Images/Shared/Choice-HSLogo.png)

## Live Demo

Here is an [interactive demo](http://try-fhirbase.hospital-systems.com)
where you can get some practice in preparing and executing arbitrary queries on a demo database.

## Motivation

While crafting Health IT systems you begin to understand a value of properly chosen domain model.
FHIR is an open source new generation lightweight standard for health data interoperability, which (we hope) could be used as an internal model for Health IT systems. FHIR is based on a concept of __resource__.

> FHIR® is a next generation standards framework created by HL7.
> FHIR combines the best features of HL7 Version 2,
> Version 3 and CDA® product lines while leveraging the latest
> web standards and applying a tight focus on implementability.

In terms of [Domain Driven Design](), __resource__ is an [aggregate]() which consists of a __root entity__
(having identity) and a set of aggregated __value objects__. In this readme we sometimes use DDD terminology
so don't be confused.

There is a concern – how to persist __resources__.

The simplest solution is just to save them as text blobs in RDBMS or in a distributed file storage system like (S3, Riak & Hadoop).
This solution is simple and scalable but has trade-offs:

* you will have to implement search and querying by creating hand-made indexes or using index engines like elastic search, solr, etc;
* query language will be very limited (in comparison with SQL);
* weak data consistency control: type checks, referential integrity, aggregate invariants;
* complicated batch transformations.

Second option is a usage of document databases like MongoDb, CouchDb, RethinkDb etc. They fit better (removing some part of hand work) but share some of trade-offs.

* Transaction consistency often works only on a document level granularity so you have to manage complex transactions manually.
* Querying is less powerful and declarative than for relational databases (joins, aggregations).
* Document databases sometimes are not yet really matured for enterprise (read mongo fails reports).

Third option – relational schema – solves most of the problems and brings new ones :)

* How to create such a complex schema?
* How to simplify aggregates (__resource__) operations (persistence, retrieval)?
* How to scale?

But we believe that after solving these problems we will get:

* fine-Granularity of data control;
* Rich Querying & Data Abstraction capabilities;
* Enhanced Data Consistency – applying most of FHIR constraints on a database level;
* storage Efficiency.

Most of it is required or desired while programming Health IT systems.

## Why PostgreSQL?

> PostgreSQL is a powerful, open source object-relational database system.
> It has more than 15 years of active development and a proven architecture
> that has earned it a strong reputation for reliability, data integrity, and correctness.

We actively use advanced postgresql features

* [xml](http://www.postgresql.org/docs/9.3/static/functions-xml.html)
* [json](http://www.postgresql.org/docs/9.3/static/functions-json.html)
* [enums](http://www.postgresql.org/docs/9.3/static/datatype-enum.html)
* [arrays](http://www.postgresql.org/docs/9.3/static/arrays.html)
* [inheritance](http://www.postgresql.org/docs/9.3/static/tutorial-inheritance.html)
* [materialized views](http://www.postgresql.org/docs/9.3/static/sql-altermaterializedview.html)
* [pgtap](http://pgtap.org/)
* [uuid-ossp](http://www.postgresql.org/docs/9.3/static/uuid-ossp.html)

## Schema Generation

We code-generate database schema & CRUD views & procedures from
FHIR machine readable specification (http://www.hl7.org/implement/standards/fhir/downloads.html).
All generation is done in postgresql.

Generation steps:

* Convert FHIR meta specification from XML to more convenient relational form
* Generate schema using meta information
  * generate base tables – resource and resource_component
  * generate data types tables, inheriting from resource_component
  * generate enums for FHIR system enumerator types
  * generate tables for each resource
     * root entity table inherits from resource base table
     * components & complex type tables inherits from resource_component base table
* Generate views & procedures for CRUD
  * generate views, which return resource as json aggregate
  * generate insert_resource(resource json) – put resource data in
  * create delete procedure
  * create update procedure as delete & insert
* Run tests
* Dump resulting database as an end-user sql script

## Schema Overview

We heavily use postgresql inheritance for schema infrastructure.

There are two base tables:

* resource – base table for all __root entities__ of resources
* resource_component − base table for all __value objects__ (resource components)

Each resource is represented as a __root entity__ table (for example 'patient')
and a table per component (for example: patient.contact is stored in `patient_contact` table).

This point is illustrated in the picture below:

![schema1](doc/schema1.png)

[edit](http://yuml.me/edit/1f3c8e92)

Due to inheritance we can access all resources throughout  __resource__ table
and all resource components by __resource_component__ table.

### Description of resource table

Base table for all resource aggregate root tables

```sql
  CREATE TABLE resource (
      id uuid NOT NULL, -- surrogate resource id
      _type varchar , -- real table name (i.e. where data are saved)
      _unknown_attributes json, -- json where all unknown attributes will be saved
      resource_type character varying, -- resourceType see FHIR documentation
      language character varying, -- see FHIR documentation
      container_id uuid, -- not null and references aggregating resource if resource is contained
      contained_id character varying -- original contained id from resource aggregate
  );
```

### Description of resource_component table

Base table for all resource components

```sql
  CREATE TABLE resource_component (
      id uuid NOT NULL, -- surrogate component id
      _type character varying NOT NULL, -- real table name
      _unknown_attributes json, -- json where all unknown attributes will be saved
      parent_id uuid NOT NULL, -- reference to parent component if present
      resource_id uuid NOT NULL -- denormalized reference to resource root table, see explanations below
  );
```

### Primitive data type attributes

Here is a mapping table for primitive types from FHIR to postgresql:

```sql

  CREATE TABLE type_to_pg_type (
      type character varying,
      pg_type character varying
  );

  COPY type_to_pg_type (type, pg_type) FROM stdin;
    code	varchar
    date_time	timestamp
    string	varchar
    text	text
    uri		varchar
    datetime	timestamp
    instant	timestamp
    boolean	boolean
    base64_binary	bytea
    integer	integer
    decimal	decimal
    sampled_data_data_type	text
    date	date
    id	varchar
    oid	varchar
  \.

```

### Enumerations

For FHIR system enumerated types we create postgresql ENUMs:

```sql

  CREATE TYPE "AddressUse" AS ENUM (
      'home',
      'work',
      'temp',
      'old'
  );

```

### Complex data type attributes

We create table for each compound data type
inheriting from resource_component table.

Here is how a table for address type is created:

```sql

  CREATE TABLE address (
      use "AddressUse",
      text character varying,
      line character varying[],
      city character varying,
      state character varying,
      zip character varying,
      country character varying
  )
  INHERITS (resource_component);

```

For resource attributes with such compound type we create separate
tables (for the sake of separation of storage and consistency) and
inherit it from type base table:

```sql

  CREATE TABLE organization_address ()
  INHERITS (address);

```

### Table of Abbreviations

Postgresql with default configuration limits length of table names.
We didn't want to rebuild postgresql so we shortened table names
using the following table of abbreviations:

```sql

CREATE TABLE short_names (name varchar, alias varchar);
INSERT INTO short_names (name, alias)
VALUES
    ('capabilities', 'cap'),
    ('chanel', 'chnl'),
    ('codeable_concept', 'cc'),
    ('coding', 'cd'),
    ('identifier', 'idn'),
    ('immunization', 'imm'),
    ('immunization_recommendation', 'imm_rec'),
    ('location', 'loc'),
    ('medication', 'med'),
    ('medication_administration', 'med_adm'),
    ('medication_dispense', 'med_disp'),
    ('medication_prescription', 'med_prs'),
    ('medication_statement', 'med_st'),
    ('observation', 'obs'),
    ('prescription', 'prs'),
    ('recommendation', 'rcm'),
    ('resource_reference', 'res_ref'),
    ('value', 'val'),
    ('value_set', 'vs')
;

```

### Contained Resources

FHIR allows on level resource – resource aggregation,
see http://www.hl7.org/implement/standards/fhir/references.html.

We save __contained resources___ same way as resources, but
in __container_id__ reference to parent resource, and preserve symbolic local resource id
in __contained_id__ field.

### Resource References

Now resource references are saved as other compound types, but we
are looking for a more relational solution for referential integrity
and reference traversing.

### Extensions

TODO: we are working on a solution

### Views

Relational schema is perfect for querying.

Example – select patients with recent visits:

```sql

SELECT p.*
  FROM fhir.encounter_hospitalization_period ehp
    JOIN fhir.encounter_subject es
     ON es.resource_id = ehp.resource_id
    JOIN fhir.patient p
     ON p.id = es.reference::uuid
  WHERE  ehp.start BETWEEN LOCALTIMESTAMP – INTERVAL '1 week' AND LOCALTIMESTAMP

```

But after searching we want to get the resource entirely
(i.e. collect resource aggregate from relational tables).

To simplify this, we generate views with names view_<resource_name>
which return FHIR compliant json resource representation. So, to
accomplish the query we can replace __patient__ table with __view_patient__ view
and get resource json in one hop.

```sql

SELECT vp.id as id, vp.json as resource
  FROM fhir.encounter_hospitalization_period ehp
    JOIN fhir.encounter_subject es
     ON es.resource_id = ehp.resource_id
    JOIN fhir.view_patient vp
     ON vp.id = es.reference::uuid
  WHERE  ehp.start BETWEEN LOCALTIMESTAMP – INTERVAL '1 week' AND LOCALTIMESTAMP

```

### insert_resource(resource json)

Manually inserting resource aggregate into relations is also tricky.
To simplify this we generated procedure
`insert_resource(_resource json)` which puts resource components
into right relations and return new resource id (uuid).

### delete_resource(id uuid)

There are also procedures to delete resources

### update_resource(resource json)

Update resource is implemented as delete and insert with same id.

TODO: we should think about versioning!

## Installation

```bash

# Install postgresql-9.3 and postgresql-contrib
# if you use debian linux or ubuntu see dev/apt.postgresql.org.sh

# Be sure that SUPERUSER "postgres" is exists
psql -d postgres -e 'CREATE USER postgres SUPERUSER;'

# pgtap extension is required. You could install it using your favorite packet manager such as homebrew:
brew install pgtap
# Official guide
http://pgtap.org/documentation.html#installation

# Create database
psql -d postgres -e 'create database mydb'`

# Download fhirbase.sql from repository backup and restore using psql
curl https://raw.github.com/fhirbase/fhirbase/master/fhirbase.sql | psql -d mydb

# check installation

psql -d mydb -e '\dt fhir.*'

# You can install checkout repository,
# install pgtap extension and run tests

git clone git@github.com:fhirbase/fhirbase.git
cd fhirbase
psql -d mydb < fhirbase_test.sql

```

## Usage

* all resource tables lay in __fhir__ schema
* insert_resource(res json) – store resource
* use SQL for querying (select, join, group)
* use resource views to retrieve json aggregates

## Contribution

* Star us on github
* Create an issue – for a bug report or enhancment
* Contribute to FHIRBase − see dev/README.md

## Roadmap

* Extensions
* FHIR server implementation
* FHIR version migrations
* Oracle, MS SQL & Mysql support


text:
- [Installation](#user-content-installation)
- [Usage](#user-content-usage)
- [Termstore](#user-content-termstore)
  - [Exportation](#user-content-exportation)
  - [Importation](#user-content-importation)
- [Solutions](#user-content-solutions)
  - [Exportation](#user-content-exportation-1)
  - [Importation](#user-content-importation-1)

# Installation

Automatic installation (requires an internet connection)

```PowerShell
iex (New-Object System.Net.WebClient).DownloadString("https://raw.github.com/maximebedard/SPU/master/install.ps1")
```

Manual installation

1. Download the latest version [here](https://github.com/maximebedard/SPU/archive/master.zip)
2. Extract the content to ~\Documents\WindowsPowerShell\Modules\SPU

# Usage

To start using the cmdlets :

```PowerShell
Import-Module SPU
```

To see all the available commands :

```PowerShell
Get-Command -Module SPU
```

# Termstore

This section explains how to export an import Taxonomy Groups contained within SharePoint Managed Metadata Service.
The following structure will be used as an example :
![Termstore example](img/termstore.png)

## Exportation

```PowerShell
# Exporting GroupTest Taxonomy Group
Get-SPUTermstore "Managed Metadata Service2" |
  Export-SPUTaxonomyGroup -LiteralPath C:\out.xml -GroupName "GroupTest"

# If the taxonomy group was in the default termstore, the following can be used
Get-SPUTermstore |
  Export-SPUTaxonomyGroup -LiteralPath C:\out.xml -GroupName "GroupTest"

# For more info
Get-Help Export-SPUTaxonomyGroup

```

The following xml is generated at C:\out.xml

```Xml
<Groups>
  <Group Name="GroupTest" Description="">
    <TermSets>
      <TermSet ID="b64862b8-fbfa-4989-bd92-1c72d6deafca">
        <Name LCID="1033">TermsetA-en</Name>
        <Description LCID="1033" />
        <Name LCID="1036">TermsetA-fr</Name>
        <Description LCID="1036" />
        <Terms />
      </TermSet>
      <TermSet ID="9f38e895-da6f-403e-a18a-1545a07937f7">
        <Name LCID="1033">TermsetB-en</Name>
        <Description LCID="1033" />
        <Name LCID="1036">TermsetB-fr</Name>
        <Description LCID="1036" />
        <Terms>
          <Term ID="c8a8a715-f7ec-4257-89a6-31dfee9bd0ec">
            <Labels>
              <Label LCID="1033" IsDefaultForLanguage="True">Term1-en</Label>
              <Label LCID="1036" IsDefaultForLanguage="True">Term1-fr</Label>
            </Labels>
            <Terms>
              <Term ID="7ac37189-f951-4593-b05d-320d645bc64e">
                <Labels>
                  <Label LCID="1033" IsDefaultForLanguage="True">Term1-1-en</Label>
                  <Label LCID="1036" IsDefaultForLanguage="True">Term1-1-fr</Label>
                </Labels>
                <Terms />
              </Term>
              <Term ID="e77695fa-945e-4fa6-8128-6533afbd57d5">
                <Labels>
                  <Label LCID="1033" IsDefaultForLanguage="True">Term1-2-en</Label>
                  <Label LCID="1036" IsDefaultForLanguage="True">Term1-2-fr</Label>
                </Labels>
                <Terms>
                  <Term ID="395a0d1f-350a-404e-9c4e-8f2169eadf1f">
                    <Labels>
                      <Label LCID="1033" IsDefaultForLanguage="True">Term1-2-1-en</Label>
                      <Label LCID="1036" IsDefaultForLanguage="True">Term1-2-1-fr</Label>
                    </Labels>
                    <Terms />
                  </Term>
                </Terms>
              </Term>
            </Terms>
          </Term>
          <Term ID="eee15d9a-bb53-4002-b176-d561a2062f70">
            <Labels>
              <Label LCID="1033" IsDefaultForLanguage="True">Term2-en</Label>
              <Label LCID="1036" IsDefaultForLanguage="True">Term2-fr</Label>
            </Labels>
            <Terms />
          </Term>
          <Term ID="0b133c81-e575-41c4-a355-e6fd5d5a5ebe">
            <Labels>
              <Label LCID="1033" IsDefaultForLanguage="True">Term3-en</Label>
              <Label LCID="1036" IsDefaultForLanguage="True">Term3-fr</Label>
            </Labels>
            <Terms>
              <Term ID="667bce45-dd0f-4cfd-818b-0d08a5d6d794">
                <Labels>
                  <Label LCID="1033" IsDefaultForLanguage="True">Term3-1-en</Label>
                  <Label LCID="1036" IsDefaultForLanguage="True">Term3-1-fr</Label>
                </Labels>
                <Terms />
              </Term>
              <Term ID="b69ca509-761e-4c58-838f-ab6983011a3d">
                <Labels>
                  <Label LCID="1033" IsDefaultForLanguage="True">Term3-2-en</Label>
                  <Label LCID="1036" IsDefaultForLanguage="True">Term3-2-fr</Label>
                </Labels>
                <Terms />
              </Term>
            </Terms>
          </Term>
        </Terms>
      </TermSet>
      <TermSet ID="c3d981f2-67cc-44d6-9507-a8a739cff950">
        <Name LCID="1033">TermsetC-en</Name>
        <Description LCID="1033" />
        <Name LCID="1036">TermsetC-fr</Name>
        <Description LCID="1036" />
        <Terms>
          <Term ID="9881b7d3-15eb-4efe-bb0a-27b30abe0fc3">
            <Labels>
              <Label LCID="1033" IsDefaultForLanguage="True">TermC1-en</Label>
              <Label LCID="1036" IsDefaultForLanguage="True">TermC1-fr</Label>
            </Labels>
            <Terms />
          </Term>
          <Term ID="424a5927-348a-44b6-ae09-39e6bad97ffa">
            <Labels>
              <Label LCID="1033" IsDefaultForLanguage="True">TermC2-en</Label>
              <Label LCID="1036" IsDefaultForLanguage="True">TermC2-fr</Label>
            </Labels>
            <Terms />
          </Term>
        </Terms>
      </TermSet>
    </TermSets>
  </Group>
</Groups>
```

## Importation

```PowerShell
# Import the taxonomy groups in the c:\out.xml file
Get-SPUTermstore -Name "Managed Metadata Service2" |
	Import-SPUTermstore -Path c:\out.xml

# Import the taxonomy groups in the default termstore
Get-SPUTermstore |
	Import-SPUTermstore -Path c:\out.xml
```

# Solutions

## Exportation

Export all the solutions files in the folder 'solutions' :

```PowerShell
Export-SPUSolutions -Path ".\solutions"
```

Export all the solutions and generate a manifest used when importing the solutions :

```PowerShell
Export-SPUSolutions -Path ".\solutions" -GenerateManifest
```

The following xml is generated in .\solutions\manifest.xml :

```Xml
<Solutions>
  <Solution Name="testa.wsp" />
  <Solution Name="testb.wsp" />
  <Solution Name="testc.wsp">
    <WebApplications>
      <WebApplication Url="http://webapp_url/" />
    </WebApplications>
  </Solution>
</Solutions>
```

## Importation

Let's assume the following directory structure :

- .\solutions\testa.wsp
- .\solutions\testb.wsp
- .\solutions\testc.wsp
- .\solutions\manifest.xml

.\solutions\manifest.xml

```Xml
<Solutions>
  <Solution Name="testa.wsp" />
  <Solution Name="testb.wsp" />
  <Solution Name="testc.wsp">
    <WebApplications>
      <WebApplication Url="http://webapp_url/" />
    </WebApplications>
  </Solution>
</Solutions>
```

To import this package :
```PowerShell
cd .\solutions
Import-SPUSolution
```

To remove this package :
```Powershell
cd .\solutions
Import-SPUSolution -Cleanup
```

Here is a more practical example :

.\solutions\manifest.xml
```Xml
<Solutions>
  <Solution Name="testa.wsp" />
  <Solution Name="testb.wsp" />
  <Solution Name="testc.wsp">
    <WebApplications>
      <WebApplication Url="http://$($Parameters.env)mywebapp.com" />
    </WebApplications>
  </Solution>
</Solutions>
```
Notice the embeded powershell variable `$($Parameters.env)` in the manifest. This variable will be expanded at runtime.

```PowerShell
# For developpement environment
Import-SPUSolution -Parameters @{"env" = "dev."}

# For integration environment
Import-SPUSolution -Parameters @{"env" = "int."}

# For qa environment
Import-SPUSolution -Parameters @{"env" = "qa."}

# For production environment
Import-SPUSolution
```


text:
import test from 'ava'

const spotify = require('../../server/lib/spotify')

test('filters artist to return correct artist', t => {
  let filteredArtist = spotify.filterArtists([{name: 'Oasis'}, {name: 'Oasiscasc'}], 'Oasis')
  t.is(filteredArtist[0].name, 'Oasis')
})

test('tracks are filtered', t => {
  let filteredTracks = spotify.filterTracks([{name: 'blah', id: 1}, {name: 'two', id: 2}])
  t.is(filteredTracks.length, 2)
  t.is(filteredTracks[0].id, 1)
})


text:
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.

# [2.0.0](https://github.com/mikl/mordac/compare/v1.0.0...v2.0.0) (2018-11-27)

### Bug Fixes

* minor documentation cleanup ([79aa4d1](https://github.com/mikl/mordac/commit/79aa4d1))

### Features

* converted app to TypeScript ([9cd5521](https://github.com/mikl/mordac/commit/9cd5521))
* rewrite protocol-relative URLs ([3716b13](https://github.com/mikl/mordac/commit/3716b13))

### BREAKING CHANGES

* Changed all the code.


text:
import abc

class Model:
    __metaclass__ = abc.ABCMeta

    def __init__(self, weights=None, bias=None):
        if weights:
            self.__weights = weights
        if bias:
            self.__bias = bias

    def __str__(self):
        return "weights:%s, bias:%s" % (self.weights, self.bias)

    @property
    def weights(self):
        return self.__weights

    @weights.setter
    def weights(self, weights):
        self.__weights = weights

    @property
    def bias(self):
        return self.__bias

    @bias.setter
    def bias(self, bias):
        self.__bias = bias


text:
package com.ms.coco.rpc.server;

import org.apache.curator.test.TestingServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * TODO: 根据配置 rpc 、restful 服务
 *
 * @author netboy
 */
public class CocoSampleServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(CocoSampleServer.class);

    public static void main(String[] args) throws Exception {
        System.out.println("start ms test zookeeper");
        TestingServer zkServer = new TestingServer(2181);
        zkServer.start();
        LOGGER.debug("start server");
        System.out.println("start rpc sample server");
        new ClassPathXmlApplicationContext("spring-rpc-rest.xml");
    }
}


text:
Prefer scoped enums to unscoped enums
=====================================

Base material
-------------

- C++98 style enums are now known as unscoped enums;
- enumerators of scoped enums are visible only within the enum
  (they convert to other types only with a cast);
- both scoped and unscoped enums support specification
  of the underlying type
  (the default underlying type for scoped enums is "int",
  unscoped enums have no default underlying type);
- scoped enums may always be forward-declared
  (unscoped enums may be forward-declared only if their declaration
  specifies an underlying type).


text:
using UnityEngine;
using System.Collections;

[CreateAssetMenu(fileName = "CustomInputControl", menuName = "Finsternis/Input/Scaled Input", order = 1)]
public class ScaledInputControl : InputControl
{
    [SerializeField]
    [Range(0, 100)]
    private float valueMultiplier = 1;

    public override float Value
    {
        get { return base.Value * valueMultiplier; }
    }
}


text:
from datetime import datetime
from uuid import uuid4
import re
import unicodedata
import urllib

from google.appengine.datastore.datastore_query import Cursor
from google.appengine.ext import blobstore
from google.appengine.ext import ndb
import flask

import config

###############################################################################
# Request Parameters
###############################################################################
def param(name, cast=None):
  '''Returns query parameter by its name and optionally casts it to given type.
  Always returns None if the parameter is missing
  '''
  value = None
  if flask.request.json:
    return flask.request.json.get(name, None)

  if value is None:
    value = flask.request.args.get(name, None)
  if value is None and flask.request.form:
    value = flask.request.form.get(name, None)

  if cast and value is not None:
    if cast == bool:
      return value.lower() in ['true', 'yes', '1', '']
    if cast == list:
      return value.split(',') if len(value) > 0 else []
    return cast(value)
  return value

def get_next_url():
  next = param('next')
  if next:
    return next
  referrer = flask.request.referrer
  if referrer and referrer.startswith(flask.request.host_url):
    return referrer
  return flask.url_for('countdown')

###############################################################################
# Model manipulations
###############################################################################
def retrieve_dbs(query, order=None, limit=None, cursor=None, **filters):
  ''' Retrieves entities from datastore, by applying cursor pagination
  and equality filters. Returns dbs and more cursor value
  '''
  limit = limit or config.DEFAULT_DB_LIMIT
  cursor = Cursor.from_websafe_string(cursor) if cursor else None
  model_class = ndb.Model._kind_map[query.kind]
  if order:
    for o in order.split(','):
      if o.startswith('-'):
        query = query.order(-model_class._properties[o[1:]])
      else:
        query = query.order(model_class._properties[o])

  for prop in filters:
    if filters.get(prop, None) is None:
      continue
    if isinstance(filters[prop], list):
      for value in filters[prop]:
        query = query.filter(model_class._properties[prop] == value)
    else:
      query = query.filter(model_class._properties[prop] == filters[prop])

  model_dbs, more_cursor, more = query.fetch_page(limit, start_cursor=cursor)
  more_cursor = more_cursor.to_websafe_string() if more else None
  return list(model_dbs), more_cursor

###############################################################################
# JSON Response Helpers
###############################################################################
def jsonify_model_dbs(model_dbs, more_cursor=None):
  '''Return a response of a list of dbs as JSON service result
  '''
  result_objects = []
  for model_db in model_dbs:
    result_objects.append(model_db_to_object(model_db))

  response_object = {
      'status': 'success',
      'count': len(result_objects),
      'now': datetime.utcnow().isoformat(),
      'result': result_objects,
    }
  if more_cursor:
    response_object['more_cursor'] = more_cursor
    response_object['more_url'] = generate_more_url(more_cursor)
  response = jsonpify(response_object)
  return response

def jsonify_model_db(model_db):
  '''Return response of a db as JSON service result
  '''
  result_object = model_db_to_object(model_db)
  response = jsonpify({
      'status': 'success',
      'now': datetime.utcnow().isoformat(),
      'result': result_object,
    })
  return response

def model_db_to_object(model_db):
  model_db_object = {}
  for prop in model_db._PROPERTIES:
    if prop == 'id':
      try:
        value = json_value(getattr(model_db, 'key', None).id())
      except:
        value = None
    else:
      value = json_value(getattr(model_db, prop, None))
    if value is not None:
      model_db_object[prop] = value
  return model_db_object

def json_value(value):
  if isinstance(value, datetime):
    return value.isoformat()
  if isinstance(value, ndb.Key):
    return value.urlsafe()
  if isinstance(value, blobstore.BlobKey):
    return urllib.quote(str(value))
  if isinstance(value, ndb.GeoPt):
    return '%s,%s' % (value.lat, value.lon)
  if isinstance(value, list):
    return [json_value(v) for v in value]
  if isinstance(value, long):
    # Big numbers are sent as strings for accuracy in JavaScript
    if value > 9007199254740992 or value < -9007199254740992:
      return str(value)
  if isinstance(value, ndb.Model):
    return model_db_to_object(value)
  return value

def jsonpify(*args, **kwargs):
  '''Same as flask.jsonify() but returns JSONP if callback is provided
  '''
  if param('callback'):
    content = '%s(%s)' % (
        param('callback'), flask.jsonify(*args, **kwargs).data,
      )
    mimetype = 'application/javascript'
    return flask.current_app.response_class(content, mimetype=mimetype)
  return flask.jsonify(*args, **kwargs)

###############################################################################
# Helpers
###############################################################################
def generate_more_url(more_cursor, base_url=None, cursor_name='cursor'):
  '''Substitutes or alters the current request URL with a new cursor parameter
  for next page of results
  '''
  if not more_cursor:
    return None
  base_url = base_url or flask.request.base_url
  args = flask.request.args.to_dict()
  args[cursor_name] = more_cursor
  return '%s?%s' % (base_url, urllib.urlencode(args))

def uuid():
  ''' Generates universal unique identifier
  '''
  return uuid4().hex

_slugify_strip_re = re.compile(r'[^\w\s-]')
_slugify_hyphenate_re = re.compile(r'[-\s]+')

def slugify(value):
  if not isinstance(value, unicode):
    value = unicode(value)
  value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
  value = unicode(_slugify_strip_re.sub('', value).strip().lower())
  return _slugify_hyphenate_re.sub('-', value)

def is_valid_username(username):
  return True if re.match('^[a-z0-9]+(?:[\.][a-z0-9]+)*$', username) else False

###############################################################################
# Lambdas
###############################################################################
strip_filter = lambda x: x.strip() if x else ''
email_filter = lambda x: x.lower().strip() if x else ''


text:
#ifndef _MEulerRotation
#define _MEulerRotation
//
//-
// ==========================================================================
// Copyright (C) 1995 - 2006 Autodesk, Inc., and/or its licensors.  All
// rights reserved.
//
// The coded instructions, statements, computer programs, and/or related
// material (collectively the "Data") in these files contain unpublished
// information proprietary to Autodesk, Inc. ("Autodesk") and/or its
// licensors,  which is protected by U.S. and Canadian federal copyright law
// and by international treaties.
//
// The Data may not be disclosed or distributed to third parties or be
// copied or duplicated, in whole or in part, without the prior written
// consent of Autodesk.
//
// The copyright notices in the Software and this entire statement,
// including the above license grant, this restriction and the following
// disclaimer, must be included in all copies of the Software, in whole
// or in part, and all derivative works of the Software, unless such copies
// or derivative works are solely in the form of machine-executable object
// code generated by a source language processor.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
// AUTODESK DOES NOT MAKE AND HEREBY DISCLAIMS ANY EXPRESS OR IMPLIED
// WARRANTIES INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES OF
// NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE,
// OR ARISING FROM A COURSE OF DEALING, USAGE, OR TRADE PRACTICE. IN NO
// EVENT WILL AUTODESK AND/OR ITS LICENSORS BE LIABLE FOR ANY LOST
// REVENUES, DATA, OR PROFITS, OR SPECIAL, DIRECT, INDIRECT, OR
// CONSEQUENTIAL DAMAGES, EVEN IF AUTODESK AND/OR ITS LICENSORS HAS
// BEEN ADVISED OF THE POSSIBILITY OR PROBABILITY OF SUCH DAMAGES.
// ==========================================================================
//+
//
// CLASS:    MEulerRotation
//
// *****************************************************************************
//
// CLASS DESCRIPTION (MEulerRotation)
//
// This class provides methods for working with euler angle rotations.
// Euler angles are described by rotations in radians around the x, y,
// and z axes, and the order in which those rotations occur.
//
// *****************************************************************************

#if defined __cplusplus

// *****************************************************************************

// INCLUDED HEADER FILES

#include <maya/MTypes.h>
#include <maya/MTransformationMatrix.h>
#include <maya/MIOStreamFwd.h>

// *****************************************************************************

// DECLARATIONS

class MMatrix;
class MQuaternion;
#define kEulerRotationEpsilon 1.0e-10

// *****************************************************************************

// CLASS DECLARATION (MEulerRotation)

/// Euler Rotation Math
/**
This class provides methods for working with euler rotations.
*/
#ifdef _WIN32
#pragma warning(disable: 4522)
#endif // _WIN32

class OPENMAYA_EXPORT MEulerRotation
{
public:

	///
	enum RotationOrder {
		///
		kXYZ,
		///
		kYZX,
		///
		kZXY,
		///
		kXZY,
		///
		kYXZ,
		///
		kZYX
	};

	///
						MEulerRotation();
	///
						MEulerRotation(const MEulerRotation &src);
	///
						MEulerRotation(const MVector &v,
									   RotationOrder ord = kXYZ);
	///
						MEulerRotation(double xx, double yy, double zz,
									   RotationOrder ord = kXYZ);
	///
						~MEulerRotation();
	///
	MEulerRotation &	operator=(const MEulerRotation &src);
	///
 	MEulerRotation &	operator=(const MQuaternion &q);
	///
 	MEulerRotation &	operator=(const MMatrix &m);
	///
 	MEulerRotation &	operator=(const MVector &v);
	///
	MEulerRotation &	setValue(const MVector &v,
								 RotationOrder ord = kXYZ);
	///
	MEulerRotation &	setValue(double xx, double yy, double zz,
								 RotationOrder ord = kXYZ);
	///
	MQuaternion			asQuaternion() const;
	///
	MMatrix				asMatrix() const;
	///
 	MVector				asVector() const;
	///
	double &			operator[](unsigned int i);
	///
	double				operator[](unsigned int i) const;
	///
 	MEulerRotation   	operator+(const MEulerRotation &other) const;
	///
	MEulerRotation &	operator+=(const MEulerRotation &other);
	///
 	MEulerRotation   	operator-(const MEulerRotation &other) const;
	///
	MEulerRotation &	operator-=(const MEulerRotation &other);
	///
 	MEulerRotation   	operator-() const;
	///
	MEulerRotation		operator*(const MEulerRotation &other) const;
	///
	MEulerRotation		operator*(const MQuaternion &other) const;
	///
	MEulerRotation		operator*(double other) const;
	///
 	friend OPENMAYA_EXPORT MEulerRotation operator*(double scale,
													const MEulerRotation
													    &other);
	///
	MEulerRotation &	operator*=(const MEulerRotation &other);
	///
	MEulerRotation &	operator*=(const MQuaternion &other);
	///
	MEulerRotation &	operator*=(double other);
	///
 	bool           		operator==(const MEulerRotation &other) const;
	///
 	bool          		operator!=(const MEulerRotation &other) const;
	///
 	bool          		isEquivalent(const MEulerRotation &other,
									 double tolerance = kEulerRotationEpsilon)
		                             const;
	///
 	bool          		isZero(double tolerance = kEulerRotationEpsilon) const;
	///
	MEulerRotation &	incrementalRotateBy(const MVector &axis,
											double angle);
	///
	MEulerRotation		inverse() const;
	///
	MEulerRotation &	invertIt();
	///
	MEulerRotation		reorder(RotationOrder ord) const;
	///
	MEulerRotation &	reorderIt(RotationOrder ord);
	///
	static MEulerRotation bound(const MEulerRotation &src);
	///
	MEulerRotation		bound() const;
	///
	MEulerRotation &	boundIt(const MEulerRotation &src);
	///
	MEulerRotation &	boundIt();
	///
	static MEulerRotation alternateSolution(const MEulerRotation &src);
	///
	MEulerRotation		alternateSolution() const;
	///
	MEulerRotation &	setToAlternateSolution(const MEulerRotation &src);
	///
	MEulerRotation &	setToAlternateSolution();
	///
	static MEulerRotation closestSolution(const MEulerRotation &src,
										  const MEulerRotation &dst);
	///
	MEulerRotation		closestSolution(const MEulerRotation &dst) const;
	///
	MEulerRotation &	setToClosestSolution(const MEulerRotation &src,
											 const MEulerRotation &dst);
	///
	MEulerRotation &	setToClosestSolution(const MEulerRotation &dst);
	///
	static MEulerRotation closestCut(const MEulerRotation &src,
									 const MEulerRotation &dst);
	///
	MEulerRotation		closestCut(const MEulerRotation &dst) const;
	///
	MEulerRotation &	setToClosestCut(const MEulerRotation &src,
										const MEulerRotation &dst);
	///
	MEulerRotation &	setToClosestCut(const MEulerRotation &dst);
	///
	static MEulerRotation decompose(const MMatrix &matrix, RotationOrder ord);
	///
	friend OPENMAYA_EXPORT IOS_REF(ostream) &operator<<(IOS_REF(ostream) &os,
											   const MEulerRotation &rotation);
	/// The euler rotation identity.  The rotation order is XYZ.
	static const MEulerRotation identity;

	/// The x component of the euler rotation in radians
	double x;
	/// The y component of the euler rotation in radians
	double y;
	/// The z component of the euler rotation in radians
	double z;
	/// The rotation order of the euler rotation
	RotationOrder order;
#if defined(LINUX)
	char			_padding[4];		// Pad out sizeof class
#endif

protected:
	// No protected members

private:
	// No private members
};

#if defined(_WIN32)
#pragma warning(default: 4522)
#endif // _WIN32

// *****************************************************************************
#endif /* __cplusplus */
#endif /* _MEulerRotation */


text:
package org.springframework.cloud.contract.verifier.builder;

import java.util.Arrays;

import org.springframework.cloud.contract.verifier.config.TestFramework;
import org.springframework.cloud.contract.verifier.file.SingleContractMetadata;

class JUnit4MethodAnnotation implements MethodAnnotations {

	private final BlockBuilder blockBuilder;

	private final GeneratedClassMetaData generatedClassMetaData;

	private static final String[] ANNOTATIONS = { "@Test" };

	JUnit4MethodAnnotation(BlockBuilder blockBuilder, GeneratedClassMetaData generatedClassMetaData) {
		this.blockBuilder = blockBuilder;
		this.generatedClassMetaData = generatedClassMetaData;
	}

	@Override
	public boolean accept(SingleContractMetadata singleContractMetadata) {
		return this.generatedClassMetaData.configProperties.getTestFramework() == TestFramework.JUNIT;
	}

	@Override
	public MethodVisitor<MethodAnnotations> apply(SingleContractMetadata singleContractMetadata) {
		Arrays.stream(ANNOTATIONS).forEach(this.blockBuilder::addIndented);
		return this;
	}

}


text:
require 'json'
require 'cgi'
require 'net/http' # also requires uri
require 'openssl'

class Fastly
  # The UserAgent to communicate with the API
  class Client #:nodoc: all

    DEFAULT_URL = 'https://api.fastly.com'.freeze

    attr_accessor :api_key, :base_url, :debug, :user, :password, :customer

    def initialize(opts)
      @api_key            = opts.fetch(:api_key, nil)
      @base_url           = opts.fetch(:base_url, DEFAULT_URL)
      @customer           = opts.fetch(:customer, nil)
      @oldpurge           = opts.fetch(:use_old_purge_method, false)
      @password           = opts.fetch(:password, nil)
      @user               = opts.fetch(:user, nil)
      @debug              = opts.fetch(:debug, nil)
      @thread_http_client = if defined?(Concurrent::ThreadLocalVar)
                              Concurrent::ThreadLocalVar.new { build_http_client }
                            end

      if api_key.nil?
        fail Unauthorized, "Invalid auth credentials. Check api_key."
      end

      self
    end

    def require_key!
      raise Fastly::KeyAuthRequired.new("This request requires an API key") if api_key.nil?
      @require_key = true
    end

    def require_key?
      !!@require_key
    end

    def authed?
      !api_key.nil? || fully_authed?
    end

    # Some methods require full username and password rather than just auth token
    def fully_authed?
      !(user.nil? || password.nil?)
    end

    def get(path, params = {})
      extras = params.delete(:headers) || {}
      include_auth = params.key?(:include_auth) ? params.delete(:include_auth) : true
      path += "?#{make_params(params)}" unless params.empty?
      resp  = http.get(path, headers(extras, include_auth))
      fail Error, resp.body unless resp.kind_of?(Net::HTTPSuccess)
      JSON.parse(resp.body)
    end

    def get_stats(path, params = {})
      resp = get(path, params)

      # return meta data, not just the actual stats data
      if resp['status'] == 'success'
        resp
      else
        fail Error, resp['msg']
      end
    end

    def post(path, params = {})
      post_and_put(:post, path, params)
    end

    def put(path, params = {})
      post_and_put(:put, path, params)
    end

    def delete(path, params = {})
      extras = params.delete(:headers) || {}
      include_auth = params.key?(:include_auth) ? params.delete(:include_auth) : true
      resp  = http.delete(path, headers(extras, include_auth))
      resp.kind_of?(Net::HTTPSuccess)
    end

    def purge(url, params = {})
      return post("/purge/#{url}", params) if @oldpurge

      extras = params.delete(:headers) || {}
      uri    = URI.parse(url)
      http   = Net::HTTP.new(uri.host, uri.port)

      if uri.is_a? URI::HTTPS
        http.use_ssl = true
      end

      resp   = http.request Net::HTTP::Purge.new(uri.request_uri, headers(extras))

      fail Error, resp.body unless resp.kind_of?(Net::HTTPSuccess)
      JSON.parse(resp.body)
    end

    def http
      return @thread_http_client.value if @thread_http_client
      return Thread.current[:fastly_net_http] if Thread.current[:fastly_net_http]

      Thread.current[:fastly_net_http] = build_http_client
    end

    private

    def build_http_client
      uri      = URI.parse(base_url)
      net_http = Net::HTTP.new(uri.host, uri.port, :ENV, nil, nil, nil)

      # handle TLS connections outside of development
      net_http.verify_mode = OpenSSL::SSL::VERIFY_PEER
      net_http.use_ssl     = uri.scheme.downcase == 'https'

      # debug http interactions if specified
      net_http.set_debug_output(debug) if debug

      net_http
    end

    def post_and_put(method, path, params = {})
      extras = params.delete(:headers) || {}
      include_auth = params.key?(:include_auth) ? params.delete(:include_auth) : true
      query = make_params(params)
      resp  = http.send(method, path, query, headers(extras, include_auth).merge('Content-Type' =>  'application/x-www-form-urlencoded'))
      fail Error, resp.body unless resp.kind_of?(Net::HTTPSuccess)
      JSON.parse(resp.body)
    end

    def headers(extras={}, include_auth=true)
      headers = {}
      if include_auth
        headers['Fastly-Key'] = api_key if api_key
      end
      headers.merge('Content-Accept' => 'application/json', 'User-Agent' => "fastly-ruby-v#{Fastly::VERSION}").merge(extras.keep_if {|k,v| !v.nil? })
    end

    def make_params(params)
      param_ary = params.map do |key, value|
        next if value.nil?
        key = key.to_s

        if value.is_a?(Hash)
          value.map do |sub_key, sub_value|
            "#{CGI.escape("#{key}[#{sub_key}]")}=#{CGI.escape(sub_value.to_s)}"
          end
        else
          "#{CGI.escape(key)}=#{CGI.escape(value.to_s)}"
        end
      end

      param_ary.flatten.delete_if { |v| v.nil? }.join('&')
    end
  end
end

# See Net::HTTPGenericRequest for attributes and methods.
class Net::HTTP::Purge < Net::HTTPRequest
  METHOD = 'PURGE'
  REQUEST_HAS_BODY = false
  RESPONSE_HAS_BODY = true
end


text:
id: connect-mapstate
title: 'Connect: Extracting Data with mapStateToProps'
hide_title: true
sidebar_label: 'Connect: Extracting Data with mapStateToProps'
---

# Connect: Extracting Data with `mapStateToProps`

As the first argument passed in to `connect`, `mapStateToProps` is used for selecting the part of the data from the store that the connected component needs. It's frequently referred to as just `mapState` for short.

- It is called every time the store state changes.
- It receives the entire store state, and should return an object of data this component needs.

## Defining `mapStateToProps`

`mapStateToProps` should be defined as a function:

```js
function mapStateToProps(state, ownProps?)
```

It should take a first argument called `state`, optionally a second argument called `ownProps`, and return a plain object containing the data that the connected component needs.

This function should be passed as the first argument to `connect`, and will be called every time when the Redux store state changes. If you do not wish to subscribe to the store, pass `null` or `undefined` to `connect` in place of `mapStateToProps`.

**It does not matter if a `mapStateToProps` function is written using the `function` keyword (`function mapState(state) { }` ) or as an arrow function (`const mapState = (state) => { }` )** - it will work the same either way.

### Arguments

1. **`state`**
2. **`ownProps` (optional)**

#### `state`

The first argument to a `mapStateToProps` function is the entire Redux store state (the same value returned by a call to `store.getState()`). Because of this, the first argument is traditionally just called `state`. (While you can give the argument any name you want, calling it `store` would be incorrect - it's the "state value", not the "store instance".)

The `mapStateToProps` function should always be written with at least `state` passed in.

```js
// TodoList.js

function mapStateToProps(state) {
  const { todos } = state
  return { todoList: todos.allIds }
}

export default connect(mapStateToProps)(TodoList)
```

#### `ownProps` (optional)

You may define the function with a second argument, `ownProps`, if your component needs the data from its own props to retrieve data from the store. This argument will contain all of the props given to the wrapper component that was generated by `connect`.

```js
// Todo.js

function mapStateToProps(state, ownProps) {
  const { visibilityFilter } = state
  // ownProps would look like { "id" : 123 }
  const { id } = ownProps
  const todo = getTodoById(state, id)

  // component receives additionally:
  return { todo, visibilityFilter }
}

// Later, in your application, a parent component renders:
<ConnectedTodo id={123} />
// and your component receives props.id, props.todo, and props.visibilityFilter
```

You do not need to include values from `ownProps` in the object returned from `mapStateToProps`. `connect` will automatically merge those different prop sources into a final set of props.

### Return

Your `mapStateToProps` function should return a plain object that contains the data the component needs:

- Each field in the object will become a prop for your actual component
- The values in the fields will be used to determine if your component needs to re-render

For example:

```js
function mapStateToProps(state) {
  return {
    a: 42,
    todos: state.todos,
    filter: state.visibilityFilter,
  }
}

// component will receive: props.a, props.todos, and props.filter
```

> Note: In advanced scenarios where you need more control over the rendering performance, `mapStateToProps` can also return a function. In this case, that function will be used as the final `mapStateToProps` for a particular component instance. This allows you to do per-instance memoization. See the [Advanced Usage: Factory Functions](../api/connect.md) section of the docs for more details, as well as [PR #279](https://github.com/reduxjs/react-redux/pull/279) and the tests it adds. Most apps never need this.

## Usage Guidelines

### Let `mapStateToProps` Reshape the Data from the Store

`mapStateToProps` functions can, and should, do a lot more than just `return state.someSlice`. **They have the responsibility of "re-shaping" store data as needed for that component.** This may include returning a value as a specific prop name, combining pieces of data from different parts of the state tree, and transforming the store data in different ways.

### Use Selector Functions to Extract and Transform Data

We highly encourage the use of "selector" functions to help encapsulate the process of extracting values from specific locations in the state tree. Memoized selector functions also play a key role in improving application performance (see the following sections in this page and the [Advanced Usage: Computing Derived Data](https://redux.js.org/recipes/computing-derived-data) page for more details on why and how to use selectors.)

### `mapStateToProps` Functions Should Be Fast

Whenever the store changes, all of the `mapStateToProps` functions of all of the connected components will run. Because of this, your `mapStateToProps` functions should run as fast as possible. This also means that a slow `mapStateToProps` function can be a potential bottleneck for your application.

As part of the "re-shaping data" idea, `mapStateToProps` functions frequently need to transform data in various ways (such as filtering an array, mapping an array of IDs to their corresponding objects, or extracting plain JS values from Immutable.js objects). These transformations can often be expensive, both in terms of cost to execute the transformation, and whether the component re-renders as a result. If performance is a concern, ensure that these transformations are only run if the input values have changed.

### `mapStateToProps` Functions Should Be Pure and Synchronous

Much like a Redux reducer, a `mapStateToProps` function should always be 100% pure and synchronous. It should only take `state` (and `ownProps`) as arguments, and return the data the component needs as props without mutating those arguments. It should _not_ be used to trigger asynchronous behavior like AJAX calls for data fetching, and the functions should not be declared as `async`.

## `mapStateToProps` and Performance

### Return Values Determine If Your Component Re-Renders

React Redux internally implements the `shouldComponentUpdate` method such that the wrapper component re-renders precisely when the data your component needs has changed. By default, React Redux decides whether the contents of the object returned from `mapStateToProps` are different using `===` comparison (a "shallow equality" check) on each fields of the returned object. If any of the fields have changed, then your component will be re-rendered so it can receive the updated values as props. Note that returning a mutated object of the same reference is a common mistake that can result in your component not re-rendering when expected.

To summarize the behavior of the component wrapped by `connect` with `mapStateToProps` to extract data from the store:

|                              | `(state) => stateProps`                | `(state, ownProps) => stateProps`                                                            |
| ---------------------------- | -------------------------------------- | -------------------------------------------------------------------------------------------- |
| `mapStateToProps` runs when: | store `state` changes                  | store `state` changes
 or
any field of `ownProps` is different                   |
| component re-renders when:   | any field of `stateProps` is different | any field of `stateProps` is different
 or
 any field of `ownProps` is different |

### Only Return New Object References If Needed

React Redux does shallow comparisons to see if the `mapStateToProps` results have changed. It's easy to accidentally return new object or array references every time, which would cause your component to re-render even if the data is actually the same.

Many common operations result in new object or array references being created:

- Creating new arrays with `someArray.map()` or `someArray.filter()`
- Merging arrays with `array.concat`
- Selecting portion of an array with `array.slice`
- Copying values with `Object.assign`
- Copying values with the spread operator `{ ...oldState, ...newData }`

Put these operations in [memoized selector functions](https://redux.js.org/recipes/computing-derived-data#creating-a-memoized-selector) to ensure that they only run if the input values have changed. This will also ensure that if the input values _haven't_ changed, `mapStateToProps` will still return the same result values as before, and `connect` can skip re-rendering.

### Only Perform Expensive Operations When Data Changes

Transforming data can often be expensive (_and_ usually results in new object references being created). In order for your `mapStateToProps` function to be as fast as possible, you should only re-run these complex transformations when the relevant data has changed.

There are a few ways to approach this:

- Some transformations could be calculated in an action creator or reducer, and the transformed data could be kept in the store
- Transformations can also be done in a component's `render()` method
- If the transformation does need to be done in a `mapStateToProps` function, then we recommend using [memoized selector functions](https://redux.js.org/recipes/computing-derived-data#creating-a-memoized-selector) to ensure the transformation is only run when the input values have changed.

#### Immutable.js Performance Concerns

Immutable.js author Lee Byron on Twitter [explicitly advises avoiding `toJS` when performance is a concern](https://twitter.com/leeb/status/746733697093668864?lang=en):

> Perf tip for #immutablejs: avoid .toJS() .toObject() and .toArray() all slow full-copy operations which render structural sharing useless.

There's several other performance concerns to take into consideration with Immutable.js - see the list of links at the end of this page for more information.

## Behavior and Gotchas

### `mapStateToProps` Will Not Run if the Store State is the Same

The wrapper component generated by `connect` subscribes to the Redux store. Every time an action is dispatched, it calls `store.getState()` and checks to see if `lastState === currentState`. If the two state values are identical by reference, then it will _not_ re-run your `mapStateToProps` function, because it assumes that the rest of the store state hasn't changed either.

The Redux `combineReducers` utility function tries to optimize for this. If none of the slice reducers returned a new value, then `combineReducers` returns the old state object instead of a new one. This means that mutation in a reducer can lead to the root state object not being updated, and thus the UI won't re-render.

### The Number of Declared Arguments Affects Behavior

With just `(state)`, the function runs whenever the root store state object is different. With `(state, ownProps)`, it runs any time the store state is different and ALSO whenever the wrapper props have changed.

This means that **you should not add the `ownProps` argument unless you actually need to use it**, or your `mapStateToProps` function will run more often than it needs to.

There are some edge cases around this behavior. **The number of mandatory arguments determines whether `mapStateToProps` will receive `ownProps`**.

If the formal definition of the function contains one mandatory parameter, `mapStateToProps` will _not_ receive `ownProps`:

```js
function mapStateToProps(state) {
  console.log(state) // state
  console.log(arguments[1]) // undefined
}
const mapStateToProps = (state, ownProps = {}) => {
  console.log(state) // state
  console.log(ownProps) // {}
}
```

It _will_ receive `ownProps` when the formal definition of the function contains zero or two mandatory parameters:

```js
function mapStateToProps(state, ownProps) {
  console.log(state) // state
  console.log(ownProps) // ownProps
}

function mapStateToProps() {
  console.log(arguments[0]) // state
  console.log(arguments[1]) // ownProps
}

function mapStateToProps(...args) {
  console.log(args[0]) // state
  console.log(args[1]) // ownProps
}
```

## Links and References

**Tutorials**

- [Practical Redux Series, Part 6: Connected Lists, Forms, and Performance](https://blog.isquaredsoftware.com/2017/01/practical-redux-part-6-connected-lists-forms-and-performance/)
- [Idiomatic Redux: Using Reselect Selectors for Encapsulation and Performance](https://blog.isquaredsoftware.com/2017/12/idiomatic-redux-using-reselect-selectors/)

**Performance**

- [Lee Byron's Tweet Suggesting to avoid `toJS`, `toArray` and `toObject` for Performance](https://twitter.com/leeb/status/746733697093668864)
- [Improving React and Redux performance with Reselect](https://blog.rangle.io/react-and-redux-performance-with-reselect/)
- [Immutable data performance links](https://github.com/markerikson/react-redux-links/blob/master/react-performance.md#immutable-data)

**Q&A**

- [Why Is My Component Re-Rendering Too Often?](https://redux.js.org/faq/react-redux#why-is-my-component-re-rendering-too-often)
- [Why isn't my component re-rendering, or my mapStateToProps running](https://redux.js.org/faq/react-redux#why-isnt-my-component-re-rendering-or-my-mapstatetoprops-running)
- [How can I speed up my mapStateToProps?](https://redux.js.org/faq/react-redux#how-can-i-speed-up-my-mapstatetoprops)
- [Should I only connect my top component, or can I connect multiple components in my tree?](https://redux.js.org/faq/react-redux#should-i-only-connect-my-top-component-or-can-i-connect-multiple-components-in-my-tree)