text:
package fi.hut.cs.drumbeat.ifc.data.model;

import java.util.List;

import fi.hut.cs.drumbeat.ifc.data.schema.IfcInverseLinkInfo;
import fi.hut.cs.drumbeat.ifc.data.schema.IfcLinkInfo;

public class IfcLink extends IfcAttribute { // implements IRdfTriple {

	private static final long serialVersionUID = 1L;

	protected IfcEntity source;
	protected IfcInverseLinkInfo inverseLinkInfo;
	private boolean useInverseLink;

	public IfcLink(IfcLinkInfo linkInfo, int attributeIndex, IfcEntity source, IfcEntityBase destination) {
		super(linkInfo, attributeIndex, destination);
		this.source = source;
	}

	public IfcLink(IfcLinkInfo linkInfo, int attributeIndex, IfcEntity source, IfcEntityList destinations) {
		super(linkInfo, attributeIndex, destinations);
		this.source = source;
	}

	public IfcEntity getSource() {
		return source;
	}

	public IfcEntity getSingleDestination() {
		return (IfcEntity)getValue();
	}

	public List<IfcEntityBase> getDestinations() {
		return super.getSingleValues();
	}

	public IfcLinkInfo getLinkInfo() {
		return (IfcLinkInfo)getAttributeInfo();
	}

	public IfcInverseLinkInfo getInverseLinkInfo() {
		return inverseLinkInfo;
	}

	public void setInverseLinkInfo(IfcInverseLinkInfo inverseLinkInfo) {
		this.inverseLinkInfo = inverseLinkInfo;
	}

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

	/**
	 * @return the useInverseLink
	 */
	public boolean isUseInverseLink() {
		return useInverseLink;
	}

	/**
	 * @param useInverseLink the useInverseLink to set
	 */
	public void setUseInverseLink(boolean useInverseLink) {
		this.useInverseLink = useInverseLink;
	}

//	@Override
//	public IRdfNode getRdfSubject() {
//		return source;
//	}

}


text:
'use strict';

const fs = require('fs');
const { ObjectDataInput } = require('../../../lib/serialization/ObjectData');
const { HeapData } = require('../../../lib/serialization/HeapData');
const ReferenceObjects = require('./ReferenceObjects');
const { SerializationServiceV1 } = require('../../../lib/serialization/SerializationService');
const { SerializationConfigImpl } = require('../../../lib/config/SerializationConfig');

const AnInnerPortable = require('./AnInnerPortable');
const AnIdentifiedDataSerializable = require('./AnIdentifiedDataSerializable');
const APortable = require('./APortable');
const { CustomByteArraySerializable } = require('./CustomSerializable');
const { CustomStreamSerializable } = require('./CustomSerializable');
const { expectAlmostEqual } = require('../../TestUtil');

describe('BinaryCompatibilityTest', function () {
    const NULL_LENGTH = -1;
    const versions = [1];
    const objects = ReferenceObjects.testObjects;
    const isBigEndianValues = [true, false];

    const dataMap = {};

    function createFileName(version) {
        return version + '.serialization.compatibility.binary';
    }

    function convertEndiannesToByteOrder(isBigEndian) {
        if (isBigEndian) {
            return 'BIG_ENDIAN';
        } else {
            return 'LITTLE_ENDIAN';
        }
    }

    function stripArticle(name) {
        if (name.startsWith('an')) {
            return name.slice(2);
        } else if (name.startsWith('a')) {
            return name.slice(1);
        } else {
            if (name.endsWith('s')) {
                return name.slice(0, -1) + '[]';
            } else {
                return name;
            }
        }
    }

    function createObjectKey(varName, version, isBigEndian) {
        return version + '-' + stripArticle(varName) + '-' + convertEndiannesToByteOrder(isBigEndian);
    }

    function createSerializationService(isBigEndian, defaultNumberType) {
        const cfg = new SerializationConfigImpl();
        cfg.portableFactories[ReferenceObjects.PORTABLE_FACTORY_ID] =
            (classId) => {
                if (classId === ReferenceObjects.INNER_PORTABLE_CLASS_ID) {
                    return new AnInnerPortable();
                } else if (classId === ReferenceObjects.PORTABLE_CLASS_ID) {
                    return new APortable();
                }
            };
        cfg.dataSerializableFactories[ReferenceObjects.IDENTIFIED_DATA_SERIALIZABLE_FACTORY_ID] =
            (classId) => {
                if (classId === ReferenceObjects.IDENTIFIED_DATA_SERIALIZABLE_CLASS_ID) {
                    return new AnIdentifiedDataSerializable();
                }
            };
        cfg.customSerializers = [
            {
                id: ReferenceObjects.CUSTOM_BYTE_ARRAY_SERIALIZABLE_ID,
                write: (out, obj) => {
                    out.writeInt(8);
                    out.writeInt(obj.i);
                    out.writeFloat(obj.f);
                },
                read: (inp) => {
                    const buf = inp.readByteArray();
                    return new CustomByteArraySerializable(buf.readInt32BE(0), buf.readFloatBE(4));
                }
            },
            {
                id: ReferenceObjects.CUSTOM_STREAM_SERIALIZABLE_ID,
                write: (out, obj) => {
                    out.writeInt(obj.int);
                    out.writeFloat(obj.float);
                },
                read: (inp) => {
                    return new CustomStreamSerializable(inp.readInt(), inp.readFloat());
                }
            }
        ];
        cfg.isBigEndian = isBigEndian;
        cfg.defaultNumberType = defaultNumberType;
        return new SerializationServiceV1(cfg);
    }

    before(function () {
        versions.forEach((version) => {
            const input = new ObjectDataInput(fs.readFileSync(__dirname + '/' + createFileName(version)), 0, null, true, true);
            while (input.available() > 0) {
                const utflen = input.readUnsignedShort();
                const namebuf = input.readRaw(utflen);
                const objectKey = namebuf.toString();
                const len = input.readInt();
                if (len !== NULL_LENGTH) {
                    const otherBuffer = input.readRaw(len);
                    dataMap[objectKey] = new HeapData(otherBuffer);
                }
            }
            dataMap[version + '-NULL-' + convertEndiannesToByteOrder(true)] = new HeapData(null);
            dataMap[version + '-NULL-' + convertEndiannesToByteOrder(false)] = new HeapData(null);
        });
    });

    for (const varName in objects) {
        const object = objects[varName];
        if (Object.prototype.hasOwnProperty.call(objects, varName)) {
            versions.forEach((version) => {
                isBigEndianValues.forEach((isBigEndian) => {
                    it(varName + '-' + convertEndiannesToByteOrder(isBigEndian) + '-' + version, function () {
                        const key = createObjectKey(varName, version, isBigEndian);
                        const service = createSerializationService(isBigEndian, 'integer');
                        const deserialized = service.toObject(dataMap[key]);
                        expectAlmostEqual(deserialized, object);
                    });

                    if (!ReferenceObjects.skipOnSerialize[varName]) {
                        it(varName + '-' + convertEndiannesToByteOrder(isBigEndian) + '-' + version + ' serialize deserialize',
                            function () {
                                const service = createSerializationService(isBigEndian, stripArticle(varName).toLowerCase());
                                const data = service.toData(object);
                                const deserialized = service.toObject(data);
                                expectAlmostEqual(deserialized, object);
                            }
                        );
                    }
                });
            });
        }
    }
});

redpajama_set_name: RedPajamaGithub


text:
We are the Portland chapter of Women Who Code. Women Who Code (WWCode) is a U.S. based 501(c)(3) non-profit dedicated to inspiring women to excel in technology careers. We connect amazing women with other like minded amazing women around the globe who unite under one simple notion – the world of technology is much better with women in it. Our events are listed on [Meetup](http://www.meetup.com/Women-Who-Code-Portland/).
* [more extensive info - need copy]
* link to parent organization
* Become a Member (button)
* Become a Sponsor (button)
* UPCOMING EVENTS (button)

Twitter: [@wwcodeportland](http://twitter.com/wwcodeportland) - use the hashtags #wwcode and #wwcodepdx
Medium: [@wwcodeportland](http://medium.com/@wwcodeportland)
Github: [@wwcodeportland](http://github.com/wwcodeportland)
Slack: [Sign up for Slack](http://bit.ly/28SvZLC)

#### LEADERSHIP
Caterina - Director
Paige - Founder (currently inactive)
Sabina - Event Lead
Richa - Skills Development Lead
Amara - Community Lead
Sarah Joy - JavaScript Lead
Shiyuan - Design Lead
Tricia - DevOps Lead

#### GET INVOLVED
* Join Us! Become a Member
* Volunteer (?)
* Become a Sponsor
  * Host an event
  * ...
* Support Us

#### SPONSORS
We are honored to work with companies that value diversity, inclusion, and forward-thinking. Among are partners are:

**2016**
AirBnB
Intel
Nike
New Relic

**2015**
New Relic

[need to source logos]

* Become a sponsor (button)

#### EVENTS
Women Who Code PDX hosts weekly study nights, workshops focused on building useful tech industry skills, and regular networking nights. The best way to keep updated on our events is through Meetup.com.

[calendar]

* Events this week
* Save the date

##### STUDY NIGHTS
Women Who Code Portland holds regular study nights focused on JavaScript, DevOps, Algorithms and Interview Prep, Big Data, and Design. For more info on our current study nights, visit our [Meetup page](http://www.meetup.com/Women-Who-Code-Portland/).
* more info on resources: https://github.com/wwcodeportland/study-nights

##### WORKSHOPS
WWCode Portland hosts workshops on various subjects, including iOS, Android, React Native.
* info: https://github.com/wwcodeportland/workshops

##### NETWORKING
A monthly meetup to hear women speak about technology, make new connections, and help us build a community of technical women in Portland.
* info: https://github.com/wwcodeportland/networking-nights


text:
namespace views {

// Debug information for https://crbug.com/1215247.
int g_instance_count = 0;

////////////////////////////////////////////////////////////////////////////////
// DialogDelegate::Params:
DialogDelegate::Params::Params() = default;
DialogDelegate::Params::~Params() = default;

////////////////////////////////////////////////////////////////////////////////
// DialogDelegate:

DialogDelegate::DialogDelegate() {
  ++g_instance_count;

  WidgetDelegate::RegisterWindowWillCloseCallback(
      base::BindOnce(&DialogDelegate::WindowWillClose, base::Unretained(this)));
  UMA_HISTOGRAM_BOOLEAN("Dialog.DialogDelegate.Create", true);
  creation_time_ = base::TimeTicks::Now();
}

// static
Widget* DialogDelegate::CreateDialogWidget(WidgetDelegate* delegate,
                                           gfx::NativeWindow context,
                                           gfx::NativeView parent) {
  views::Widget* widget = new views::Widget;
  views::Widget::InitParams params =
      GetDialogWidgetInitParams(delegate, context, parent, gfx::Rect());
  widget->Init(std::move(params));
  return widget;
}

// static
Widget* DialogDelegate::CreateDialogWidget(
    std::unique_ptr<WidgetDelegate> delegate,
    gfx::NativeWindow context,
    gfx::NativeView parent) {
  DCHECK(delegate->owned_by_widget());
  return CreateDialogWidget(delegate.release(), context, parent);
}

// static
bool DialogDelegate::CanSupportCustomFrame(gfx::NativeView parent) {
#if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && \
    BUILDFLAG(ENABLE_DESKTOP_AURA)
  // The new style doesn't support unparented dialogs on Linux desktop.
  return parent != nullptr;
#else
#if BUILDFLAG(IS_WIN)
  // The new style doesn't support unparented dialogs on Windows Classic themes.
  if (!ui::win::IsAeroGlassEnabled())
    return parent != nullptr;
#endif
  return true;
#endif
}

// static
Widget::InitParams DialogDelegate::GetDialogWidgetInitParams(
    WidgetDelegate* delegate,
    gfx::NativeWindow context,
    gfx::NativeView parent,
    const gfx::Rect& bounds) {
  views::Widget::InitParams params;
  params.delegate = delegate;
  params.bounds = bounds;
  DialogDelegate* dialog = delegate->AsDialogDelegate();

  if (dialog)
    dialog->params_.custom_frame &= CanSupportCustomFrame(parent);

  if (!dialog || dialog->use_custom_frame()) {
    params.opacity = Widget::InitParams::WindowOpacity::kTranslucent;
    params.remove_standard_frame = true;
#if !BUILDFLAG(IS_MAC)
    // Except on Mac, the bubble frame includes its own shadow; remove any
    // native shadowing. On Mac, the window server provides the shadow.
    params.shadow_type = views::Widget::InitParams::ShadowType::kNone;
#endif
  }
  params.context = context;
  params.parent = parent;
#if !BUILDFLAG(IS_APPLE)
  // Web-modal (ui::MODAL_TYPE_CHILD) dialogs with parents are marked as child
  // widgets to prevent top-level window behavior (independent movement, etc).
  // On Mac, however, the parent may be a native window (not a views::Widget),
  // and so the dialog must be considered top-level to gain focus and input
  // method behaviors.
  params.child = parent && (delegate->GetModalType() == ui::MODAL_TYPE_CHILD);
#endif
  return params;
}

int DialogDelegate::GetDefaultDialogButton() const {
  if (GetParams().default_button.has_value())
    return *GetParams().default_button;
  if (GetDialogButtons() & ui::DIALOG_BUTTON_OK)
    return ui::DIALOG_BUTTON_OK;
  if (GetDialogButtons() & ui::DIALOG_BUTTON_CANCEL)
    return ui::DIALOG_BUTTON_CANCEL;
  return ui::DIALOG_BUTTON_NONE;
}

std::u16string DialogDelegate::GetDialogButtonLabel(
    ui::DialogButton button) const {
  if (!GetParams().button_labels[button].empty())
    return GetParams().button_labels[button];

  if (button == ui::DIALOG_BUTTON_OK)
    return l10n_util::GetStringUTF16(IDS_APP_OK);
  if (button == ui::DIALOG_BUTTON_CANCEL) {
    if (GetDialogButtons() & ui::DIALOG_BUTTON_OK)
      return l10n_util::GetStringUTF16(IDS_APP_CANCEL);
    return l10n_util::GetStringUTF16(IDS_APP_CLOSE);
  }
  NOTREACHED();
  return std::u16string();
}

bool DialogDelegate::IsDialogButtonEnabled(ui::DialogButton button) const {
  return params_.enabled_buttons & button;
}

bool DialogDelegate::Cancel() {
  DCHECK(!already_started_close_);
  if (cancel_callback_)
    RunCloseCallback(std::move(cancel_callback_));
  return true;
}

bool DialogDelegate::Accept() {
  DCHECK(!already_started_close_);
  if (accept_callback_)
    RunCloseCallback(std::move(accept_callback_));
  return true;
}

void DialogDelegate::RunCloseCallback(base::OnceClosure callback) {
  DCHECK(!already_started_close_);
  already_started_close_ = true;
  std::move(callback).Run();
}

View* DialogDelegate::GetInitiallyFocusedView() {
  if (WidgetDelegate::HasConfiguredInitiallyFocusedView())
    return WidgetDelegate::GetInitiallyFocusedView();

  // Focus the default button if any.
  const DialogClientView* dcv = GetDialogClientView();
  if (!dcv)
    return nullptr;
  int default_button = GetDefaultDialogButton();
  if (default_button == ui::DIALOG_BUTTON_NONE)
    return nullptr;

  if ((default_button & GetDialogButtons()) == 0) {
    // The default button is a button we don't have.
    NOTREACHED();
    return nullptr;
  }

  if (default_button & ui::DIALOG_BUTTON_OK)
    return dcv->ok_button();
  if (default_button & ui::DIALOG_BUTTON_CANCEL)
    return dcv->cancel_button();
  return nullptr;
}

DialogDelegate* DialogDelegate::AsDialogDelegate() {
  return this;
}

ClientView* DialogDelegate::CreateClientView(Widget* widget) {
  return new DialogClientView(widget, TransferOwnershipOfContentsView());
}

std::unique_ptr<NonClientFrameView> DialogDelegate::CreateNonClientFrameView(
    Widget* widget) {
  return use_custom_frame() ? CreateDialogFrameView(widget)
                            : WidgetDelegate::CreateNonClientFrameView(widget);
}

void DialogDelegate::WindowWillClose() {
  if (already_started_close_)
    return;

  bool new_callback_present =
      close_callback_ || cancel_callback_ || accept_callback_;

  if (close_callback_)
    RunCloseCallback(std::move(close_callback_));

  if (new_callback_present)
    return;

  // This is set here instead of before the invocations of Accept()/Cancel() so
  // that those methods can DCHECK that !already_started_close_. Otherwise,
  // client code could (eg) call Accept() from inside the cancel callback, which
  // could lead to multiple callbacks being delivered from this class.
  already_started_close_ = true;
}

bool DialogDelegate::EscShouldCancelDialog() const {
  // Use cancel as the Esc action if there's no defined "close" action. If the
  // delegate has either specified a closing action or a close-x they can expect
  // it to be called on Esc.
  return !close_callback_ && !ShouldShowCloseButton();
}

// static
std::unique_ptr<NonClientFrameView> DialogDelegate::CreateDialogFrameView(
    Widget* widget) {
  LayoutProvider* provider = LayoutProvider::Get();
  auto frame = std::make_unique<BubbleFrameView>(
      provider->GetInsetsMetric(INSETS_DIALOG_TITLE), gfx::Insets());

  const BubbleBorder::Shadow kShadow = BubbleBorder::DIALOG_SHADOW;
  std::unique_ptr<BubbleBorder> border = std::make_unique<BubbleBorder>(
      BubbleBorder::FLOAT, kShadow, gfx::kPlaceholderColor);
  border->set_use_theme_background_color(true);
  DialogDelegate* delegate = widget->widget_delegate()->AsDialogDelegate();
  if (delegate) {
    if (delegate->GetParams().round_corners)
      border->SetCornerRadius(delegate->GetCornerRadius());
    frame->SetFootnoteView(delegate->DisownFootnoteView());
  }
  frame->SetBubbleBorder(std::move(border));
  return frame;
}

const DialogClientView* DialogDelegate::GetDialogClientView() const {
  if (!GetWidget())
    return nullptr;
  const views::View* client_view = GetWidget()->client_view();
  return client_view->GetClassName() == DialogClientView::kViewClassName
             ? static_cast<const DialogClientView*>(client_view)
             : nullptr;
}

DialogClientView* DialogDelegate::GetDialogClientView() {
  if (!GetWidget())
    return nullptr;
  views::View* client_view = GetWidget()->client_view();
  return client_view->GetClassName() == DialogClientView::kViewClassName
             ? static_cast<DialogClientView*>(client_view)
             : nullptr;
}

BubbleFrameView* DialogDelegate::GetBubbleFrameView() const {
  if (!use_custom_frame())
    return nullptr;

  const NonClientView* view =
      GetWidget() ? GetWidget()->non_client_view() : nullptr;
  return view ? static_cast<BubbleFrameView*>(view->frame_view()) : nullptr;
}

views::LabelButton* DialogDelegate::GetOkButton() const {
  DCHECK(GetWidget()) << "Don't call this before OnWidgetInitialized";
  auto* client = GetDialogClientView();
  return client ? client->ok_button() : nullptr;
}

views::LabelButton* DialogDelegate::GetCancelButton() const {
  DCHECK(GetWidget()) << "Don't call this before OnWidgetInitialized";
  auto* client = GetDialogClientView();
  return client ? client->cancel_button() : nullptr;
}

views::View* DialogDelegate::GetExtraView() const {
  DCHECK(GetWidget()) << "Don't call this before OnWidgetInitialized";
  auto* client = GetDialogClientView();
  return client ? client->extra_view() : nullptr;
}

views::View* DialogDelegate::GetFootnoteViewForTesting() const {
  if (!GetWidget())
    return footnote_view_.get();

  NonClientFrameView* frame = GetWidget()->non_client_view()->frame_view();

  // CreateDialogFrameView above always uses BubbleFrameView. There are
  // subclasses that override CreateDialogFrameView, but none of them override
  // it to create anything other than a BubbleFrameView.
  // TODO(https://crbug.com/1011446): Make CreateDialogFrameView final, then
  // remove this DCHECK.
  DCHECK_EQ(frame->GetClassName(), BubbleFrameView::kViewClassName);
  return static_cast<BubbleFrameView*>(frame)->GetFootnoteView();
}

void DialogDelegate::AddObserver(DialogObserver* observer) {
  observer_list_.AddObserver(observer);
}

void DialogDelegate::RemoveObserver(DialogObserver* observer) {
  observer_list_.RemoveObserver(observer);
}

void DialogDelegate::DialogModelChanged() {
  for (DialogObserver& observer : observer_list_)
    observer.OnDialogChanged();
}

void DialogDelegate::SetDefaultButton(int button) {
  if (params_.default_button == button)
    return;
  params_.default_button = button;
  DialogModelChanged();
}

void DialogDelegate::SetButtons(int buttons) {
  if (params_.buttons == buttons)
    return;
  params_.buttons = buttons;
  DialogModelChanged();
}

void DialogDelegate::SetButtonEnabled(ui::DialogButton button, bool enabled) {
  if (!!(params_.enabled_buttons & button) == enabled)
    return;
  if (enabled)
    params_.enabled_buttons |= button;
  else
    params_.enabled_buttons &= ~button;
  DialogModelChanged();
}

void DialogDelegate::SetButtonLabel(ui::DialogButton button,
                                    std::u16string label) {
  if (params_.button_labels[button] == label)
    return;
  params_.button_labels[button] = label;
  DialogModelChanged();
}

void DialogDelegate::SetAcceptCallback(base::OnceClosure callback) {
  accept_callback_ = std::move(callback);
}

void DialogDelegate::SetCancelCallback(base::OnceClosure callback) {
  cancel_callback_ = std::move(callback);
}

void DialogDelegate::SetCloseCallback(base::OnceClosure callback) {
  close_callback_ = std::move(callback);
}

std::unique_ptr<View> DialogDelegate::DisownExtraView() {
  return std::move(extra_view_);
}

bool DialogDelegate::Close() {
  WindowWillClose();
  return true;
}

void DialogDelegate::ResetViewShownTimeStampForTesting() {
  GetDialogClientView()->ResetViewShownTimeStampForTesting();
}

void DialogDelegate::SetButtonRowInsets(const gfx::Insets& insets) {
  GetDialogClientView()->SetButtonRowInsets(insets);
}

void DialogDelegate::AcceptDialog() {
  // Copy the dialog widget name onto the stack so it appears in crash dumps.
  DEBUG_ALIAS_FOR_CSTR(last_widget_name, GetWidget()->GetName().c_str(), 64);

  DCHECK(IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
  if (already_started_close_ || !Accept())
    return;

  // Check for Accept() deleting `this` but returning false. Empirically the
  // steady state instance count with no dialogs open is zero, so if it's back
  // to zero `this` is deleted https://crbug.com/1215247
  if (g_instance_count <= 0) {
    // LOG(FATAL) instead of CHECK() to put the widget name into a crash key.
    // See "Product Data" in the crash tool if a crash report shows this line.
    LOG(FATAL) << last_widget_name;
  }

  already_started_close_ = true;
  GetWidget()->CloseWithReason(
      views::Widget::ClosedReason::kAcceptButtonClicked);
}

void DialogDelegate::CancelDialog() {
  // If there's a close button available, this callback should only be reachable
  // if the cancel button is available. Otherwise this can be reached through
  // closing the dialog via Esc.
  if (ShouldShowCloseButton())
    DCHECK(IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));

  if (already_started_close_ || !Cancel())
    return;

  already_started_close_ = true;
  GetWidget()->CloseWithReason(
      views::Widget::ClosedReason::kCancelButtonClicked);
}

DialogDelegate::~DialogDelegate() {
  UMA_HISTOGRAM_LONG_TIMES("Dialog.DialogDelegate.Duration",
                           base::TimeTicks::Now() - creation_time_);
  --g_instance_count;
}

ax::mojom::Role DialogDelegate::GetAccessibleWindowRole() {
  return ax::mojom::Role::kDialog;
}

int DialogDelegate::GetCornerRadius() const {
#if BUILDFLAG(IS_MAC)
  // TODO(crbug.com/1116680): On Mac MODAL_TYPE_WINDOW is implemented using
  // sheets which causes visual artifacts when corner radius is increased for
  // modal types. Remove this after this issue has been addressed.
  if (GetModalType() == ui::MODAL_TYPE_WINDOW)
    return 2;
#endif
  if (params_.corner_radius)
    return *params_.corner_radius;
  return LayoutProvider::Get()->GetCornerRadiusMetric(views::Emphasis::kMedium);
}

std::unique_ptr<View> DialogDelegate::DisownFootnoteView() {
  return std::move(footnote_view_);
}

////////////////////////////////////////////////////////////////////////////////
// DialogDelegateView:

DialogDelegateView::DialogDelegateView() {
  SetOwnedByWidget(true);
  UMA_HISTOGRAM_BOOLEAN("Dialog.DialogDelegateView.Create", true);
}

DialogDelegateView::~DialogDelegateView() = default;

Widget* DialogDelegateView::GetWidget() {
  return View::GetWidget();
}

const Widget* DialogDelegateView::GetWidget() const {
  return View::GetWidget();
}

View* DialogDelegateView::GetContentsView() {
  return this;
}

BEGIN_METADATA(DialogDelegateView, View)
END_METADATA

}  // namespace views


text:
"""
There are two types of functions:
1) defined function like exp or sin that has a name and body
   (in the sense that function can be evaluated).
    e = exp
2) undefined function with a name but no body. Undefined
  functions can be defined using a Function class as follows:
    f = Function('f')
  (the result will be Function instance)
3) this isn't implemented yet: anonymous function or lambda function that has
no name but has body with dummy variables. An anonymous function
   object creation examples:
    f = Lambda(x, exp(x)*x)
    f = Lambda(exp(x)*x)  # free symbols in the expression define the number of arguments
    f = exp * Lambda(x,x)
4) isn't implemented yet: composition of functions, like (sin+cos)(x), this
works in sympycore, but needs to be ported back to SymPy.

Example:
    >>> from sympy import *
    >>> f = Function("f")
    >>> x = Symbol("x")
    >>> f(x)
    f(x)
    >>> print srepr(f(x).func)
    Function('f')
    >>> f(x).args
    (x,)
"""

from basic import Basic, Atom, S, C
from basic import BasicMeta
from cache import cacheit
from itertools import repeat
from numbers import Rational, Integer
from symbol import Symbol
from multidimensional import vectorize
from sympy.utilities.decorator import deprecated

from sympy import mpmath

class PoleError(Exception):
    pass

class FunctionClass(BasicMeta):
    """
    Base class for function classes. FunctionClass is a subclass of type.

    Use Function('<function name>' [ , signature ]) to create
    undefined function classes.
    """

    _new = type.__new__

    def __new__(cls, arg1, arg2, arg3=None, **options):
        assert not options,`options`
        if isinstance(arg1, type):
            # the following code gets executed when one types
            # FunctionClass(Function, "f")
            # i.e. cls = FunctionClass, arg1 = Function, arg2 = "f"
            # and we simply do an equivalent of:
            # class f(Function):
            #     ...
            # return f
            ftype, name, signature = arg1, arg2, arg3
            #XXX this probably needs some fixing:
            assert ftype.__name__.endswith('Function'),`ftype`
            attrdict = ftype.__dict__.copy()
            attrdict['undefined_Function'] = True
            if signature is not None:
                attrdict['signature'] = signature
            bases = (ftype,)
            return type.__new__(cls, name, bases, attrdict)
        else:
            name, bases, attrdict = arg1, arg2, arg3
            return type.__new__(cls, name, bases, attrdict)

    def __repr__(cls):
        return cls.__name__

class Function(Basic):
    """
    Base class for applied functions.
    Constructor of undefined classes.

    """

    __metaclass__ = FunctionClass

    is_Function = True

    nargs = None

    @vectorize(1)
    @cacheit
    def __new__(cls, *args, **options):
        # NOTE: this __new__ is twofold:
        #
        # 1 -- it can create another *class*, which can then be instantiated by
        #      itself e.g. Function('f') creates a new class f(Function)
        #
        # 2 -- on the other hand, we instantiate -- that is we create an
        #      *instance* of a class created earlier in 1.
        #
        # So please keep, both (1) and (2) in mind.

        # (1) create new function class
        #     UC: Function('f')
        if cls is Function:
            #when user writes Function("f"), do an equivalent of:
            #taking the whole class Function(...):
            #and rename the Function to "f" and return f, thus:
            #In [13]: isinstance(f, Function)
            #Out[13]: False
            #In [14]: isinstance(f, FunctionClass)
            #Out[14]: True

            if len(args) == 1 and isinstance(args[0], str):
                #always create Function
                return FunctionClass(Function, *args)
                return FunctionClass(Function, *args, **options)
            else:
                print args
                print type(args[0])
                raise TypeError("You need to specify exactly one string")

        # (2) create new instance of a class created in (1)
        #     UC: Function('f')(x)
        #     UC: sin(x)
        args = map(sympify, args)
        # these lines should be refactored
        for opt in ["nargs", "dummy", "comparable", "noncommutative", "commutative"]:
            if opt in options:
                del options[opt]
        # up to here.
        if options.get('evaluate') is False:
            return Basic.__new__(cls, *args, **options)
        evaluated = cls.eval(*args)
        if evaluated is not None: return evaluated
        # Just undefined functions have nargs == None
        if not cls.nargs and hasattr(cls, 'undefined_Function'):
            r = Basic.__new__(cls, *args, **options)
            r.nargs = len(args)
            return r
        return Basic.__new__(cls, *args, **options)

    @property
    def is_commutative(self):
        return True

    @classmethod
    @deprecated
    def canonize(cls, *args):
        return cls.eval(*args)

    @classmethod
    def eval(cls, *args):
        """
        Returns a canonical form of cls applied to arguments args.

        The eval() method is called when the class cls is about to be
        instantiated and it should return either some simplified instance
        (possible of some other class), or if the class cls should be
        unmodified, return None.

        Example of eval() for the function "sign"
        ---------------------------------------------

        @classmethod
        def eval(cls, arg):
            if arg is S.NaN:
                return S.NaN
            if arg is S.Zero: return S.Zero
            if arg.is_positive: return S.One
            if arg.is_negative: return S.NegativeOne
            if isinstance(arg, C.Mul):
                coeff, terms = arg.as_coeff_terms()
                if coeff is not S.One:
                    return cls(coeff) * cls(C.Mul(*terms))

        """
        return

    @property
    def func(self):
        return self.__class__

    def _eval_subs(self, old, new):
        if self == old:
            return new
        elif old.is_Function and new.is_Function:
            if old == self.func:
                if self.nargs is new.nargs or not new.nargs:
                    return new(*self.args[:])
                # Written down as an elif to avoid a super-long line
                elif isinstance(new.nargs,tuple) and self.nargs in new.nargs:
                    return new(*self.args[:])
        obj = self.func._eval_apply_subs(*(self.args[:] + (old,) + (new,)))
        if obj is not None:
            return obj
        return Basic._seq_subs(self, old, new)

    def _eval_evalf(self, prec):
        # Lookup mpmath function based on name
        fname = self.func.__name__
        try:
            if not hasattr(mpmath, fname):
                from sympy.utilities.lambdify import MPMATH_TRANSLATIONS
                fname = MPMATH_TRANSLATIONS[fname]
            func = getattr(mpmath, fname)
        except (AttributeError, KeyError):
            return

        # Convert all args to mpf or mpc
        try:
            args = [arg._to_mpmath(prec) for arg in self.args]
        except ValueError:
            return

        # Set mpmath precision and apply. Make sure precision is restored
        # afterwards
        orig = mpmath.mp.prec
        try:
            mpmath.mp.prec = prec
            v = func(*args)
        finally:
            mpmath.mp.prec = orig

        return Basic._from_mpmath(v, prec)

    def _eval_is_comparable(self):
        if self.is_Function:
            r = True
            for s in self.args:
                c = s.is_comparable
                if c is None: return
                if not c: r = False
            return r
        return

    def _eval_derivative(self, s):
        # f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s)
        i = 0
        l = []
        r = S.Zero
        for a in self.args:
            i += 1
            da = a.diff(s)
            if da is S.Zero:
                continue
            if isinstance(self.func, FunctionClass):
                df = self.fdiff(i)
                l.append(df * da)
        return Add(*l)

    def _eval_is_commutative(self):
        r = True
        for a in self._args:
            c = a.is_commutative
            if c is None: return None
            if not c: r = False
        return r

    def _eval_eq_nonzero(self, other):
        if isinstance(other.func, self.func.__class__) and len(self)==len(other):
            for a1,a2 in zip(self,other):
                if not (a1==a2):
                    return False
            return True

    def as_base_exp(self):
        return self, S.One

    def count_ops(self, symbolic=True):
        #      f()             args
        return 1   + Add(*[t.count_ops(symbolic) for t in self.args])

    def _eval_nseries(self, x, x0, n):
        assert len(self.args) == 1
        arg = self.args[0]
        arg0 = arg.limit(x, 0)
        from sympy import oo
        if arg0 in [-oo, oo]:
            raise PoleError("Cannot expand around %s" % (arg))
        if arg0 is not S.Zero:
            e = self.func(arg)
            e1 = e.expand()
            if e==e1:
                #for example when e = sin(x+1) or e = sin(cos(x))
                #let's try the general algorithm
                term = e.subs(x, S.Zero)
                series = term
                fact = S.One
                for i in range(n-1):
                    i += 1
                    fact *= Rational(i)
                    e = e.diff(x)
                    term = e.subs(x, S.Zero)*(x**i)/fact
                    term = term.expand()
                    series += term
                return series + C.Order(x**n, x)
            return self.nseries(x, x0, n)
        l = []
        g = None
        for i in xrange(n+2):
            g = self.taylor_term(i, arg, g)
            g = g.nseries(x, x0, n)
            l.append(g)
        return Add(*l) + C.Order(x**n, x)

    def _eval_is_polynomial(self, syms):
        for arg in self.args:
            if arg.has(*syms):
                return False
        return True

    def _eval_expand_basic(self, deep=True, **hints):
        if not deep:
            return self
        sargs, terms = self.args[:], []
        for term in sargs:
            if hasattr(term, '_eval_expand_basic'):
                newterm = term._eval_expand_basic(deep=deep, **hints)
            else:
                newterm = term
            terms.append(newterm)
        return self.new(*terms)

    def _eval_expand_power_exp(self, deep=True, **hints):
        if not deep:
            return self
        sargs, terms = self.args[:], []
        for term in sargs:
            if hasattr(term, '_eval_expand_power_exp'):
                newterm = term._eval_expand_power_exp(deep=deep, **hints)
            else:
                newterm = term
            terms.append(newterm)
        return self.new(*terms)

    def _eval_expand_power_base(self, deep=True, **hints):
        if not deep:
            return self
        sargs, terms = self.args[:], []
        for term in sargs:
            if hasattr(term, '_eval_expand_power_base'):
                newterm = term._eval_expand_power_base(deep=deep, **hints)
            else:
                newterm = term
            terms.append(newterm)
        return self.new(*terms)

    def _eval_expand_mul(self, deep=True, **hints):
        if not deep:
            return self
        sargs, terms = self.args[:], []
        for term in sargs:
            if hasattr(term, '_eval_expand_mul'):
                newterm = term._eval_expand_mul(deep=deep, **hints)
            else:
                newterm = term
            terms.append(newterm)
        return self.new(*terms)

    def _eval_expand_multinomial(self, deep=True, **hints):
        if not deep:
            return self
        sargs, terms = self.args[:], []
        for term in sargs:
            if hasattr(term, '_eval_expand_multinomail'):
                newterm = term._eval_expand_multinomial(deep=deep, **hints)
            else:
                newterm = term
            terms.append(newterm)
        return self.new(*terms)

    def _eval_expand_log(self, deep=True, **hints):
        if not deep:
            return self
        sargs, terms = self.args[:], []
        for term in sargs:
            if hasattr(term, '_eval_expand_log'):
                newterm = term._eval_expand_log(deep=deep, **hints)
            else:
                newterm = term
            terms.append(newterm)
        return self.new(*terms)

    def _eval_expand_complex(self, deep=True, **hints):
        if deep:
            func = self.func(*[ a.expand(deep, **hints) for a in self.args ])
        else:
            func = self.func(*self.args)
        return C.re(func) + S.ImaginaryUnit * C.im(func)

    def _eval_expand_trig(self, deep=True, **hints):
        sargs, terms = self.args[:], []
        for term in sargs:
            if hasattr(term, '_eval_expand_trig'):
                newterm = term._eval_expand_trig(deep=deep, **hints)
            else:
                newterm = term
            terms.append(newterm)
        return self.new(*terms)

    def _eval_expand_func(self, deep=True, **hints):
        sargs, terms = self.args[:], []
        for term in sargs:
            if hasattr(term, '_eval_expand_func'):
                newterm = term._eval_expand_func(deep=deep, **hints)
            else:
                newterm = term
            terms.append(newterm)
        return self.new(*terms)

    def _eval_rewrite(self, pattern, rule, **hints):
        if hints.get('deep', False):
            args = [ a._eval_rewrite(pattern, rule, **hints) for a in self ]
        else:
            args = self.args[:]

        if pattern is None or isinstance(self.func, pattern):
            if hasattr(self, rule):
                rewritten = getattr(self, rule)(*args)

                if rewritten is not None:
                    return rewritten

        return self.func(*args, **self._assumptions)

    def fdiff(self, argindex=1):
        if self.nargs is not None:
            if isinstance(self.nargs, tuple):
                nargs = self.nargs[-1]
            else:
                nargs = self.nargs
            if not (1<=argindex<=nargs):
                raise TypeError("argument index %r is out of range [1,%s]" % (argindex,nargs))
        return Derivative(self,self.args[argindex-1],evaluate=False)

    @classmethod
    def _eval_apply_evalf(cls, arg):
        arg = arg.evalf(prec)

        #if cls.nargs == 1:
        # common case for functions with 1 argument
        #if arg.is_Number:
        if arg.is_number:
            func_evalf = getattr(arg, cls.__name__)
            return func_evalf()

    def _eval_as_leading_term(self, x):
        """General method for the leading term"""
        arg = self.args[0].as_leading_term(x)

        if C.Order(1,x).contains(arg):
            return arg
        else:
            return self.func(arg)

    @classmethod
    def taylor_term(cls, n, x, *previous_terms):
        """General method for the taylor term.

        This method is slow, because it differentiates n-times.  Subclasses can
        redefine it to make it faster by using the "previous_terms".
        """
        x = sympify(x)
        return cls(x).diff(x, n).subs(x, 0) * x**n / C.Factorial(n)

class WildFunction(Function, Atom):
    """
    WildFunction() matches any expression but another WildFunction()
    XXX is this as intended, does it work ?
    """

    nargs = 1

    def __new__(cls, name=None, **assumptions):
        if name is None:
            name = 'Wf%s' % (Symbol.dummycount + 1) # XXX refactor dummy counting
            Symbol.dummycount += 1
        obj = Function.__new__(cls, name, **assumptions)
        obj.name = name
        return obj

    def matches(pattern, expr, repl_dict={}, evaluate=False):
        for p,v in repl_dict.items():
            if p==pattern:
                if v==expr: return repl_dict
                return None
        if pattern.nargs is not None:
            if not hasattr(expr,'nargs') or pattern.nargs != expr.nargs:
                return None
        repl_dict = repl_dict.copy()
        repl_dict[pattern] = expr
        return repl_dict

    @classmethod
    def _eval_apply_evalf(cls, arg):
        return

    @property
    def is_number(self):
        return False

class Derivative(Basic):
    """
    Carries out differentation of the given expression with respect to symbols.

    expr must define ._eval_derivative(symbol) method that returns
    the differentation result or None.

    Examples:

    Derivative(Derivative(expr, x), y) -> Derivative(expr, x, y)
    Derivative(expr, x, 3)  -> Derivative(expr, x, x, x)
    """

    is_Derivative   = True

    @staticmethod
    def _symbolgen(*symbols):
        """
        Generator of all symbols in the argument of the Derivative.

        Example:
        >> ._symbolgen(x, 3, y)
        (x, x, x, y)
        >> ._symbolgen(x, 10**6)
        (x, x, x, x, x, x, x, ...)

        The second example shows why we don't return a list, but a generator,
        so that the code that calls _symbolgen can return earlier for special
        cases, like x.diff(x, 10**6).
        """
        last_s = sympify(symbols[len(symbols)-1])
        for i in xrange(len(symbols)):
            s = sympify(symbols[i])
            next_s = None
            if s != last_s:
                next_s = sympify(symbols[i+1])

            if isinstance(s, Integer):
                continue
            elif isinstance(s, Symbol):
                # handle cases like (x, 3)
                if isinstance(next_s, Integer):
                    # yield (x, x, x)
                    for copy_s in repeat(s,int(next_s)):
                        yield copy_s
                else:
                    yield s
            else:
                yield s

    def __new__(cls, expr, *symbols, **assumptions):
        expr = sympify(expr)
        if not symbols: return expr
        symbols = Derivative._symbolgen(*symbols)
        if expr.is_commutative:
            assumptions["commutative"] = True
        if "evaluate" in assumptions:
            evaluate = assumptions["evaluate"]
            del assumptions["evaluate"]
        else:
            evaluate = False
        if not evaluate and not isinstance(expr, Derivative):
            obj = Basic.__new__(cls, expr, *symbols, **assumptions)
            return obj
        unevaluated_symbols = []
        for s in symbols:
            s = sympify(s)
            if not isinstance(s, Symbol):
                raise ValueError('Invalid literal: %s is not a valid variable' % s)
            if not expr.has(s):
                return S.Zero
            obj = expr._eval_derivative(s)
            if obj is None:
                unevaluated_symbols.append(s)
            elif obj is S.Zero:
                return S.Zero
            else:
                expr = obj

        if not unevaluated_symbols:
            return expr
        return Basic.__new__(cls, expr, *unevaluated_symbols, **assumptions)

    def _eval_derivative(self, s):
        #print
        #print self
        #print s
        #stop
        if s not in self.symbols:
            obj = self.expr.diff(s)
            if isinstance(obj, Derivative):
                return Derivative(obj.expr, *(obj.symbols+self.symbols))
            return Derivative(obj, *self.symbols)
        return Derivative(self.expr, *((s,)+self.symbols), **{'evaluate': False})

    def doit(self):
        return Derivative(self.expr, *self.symbols,**{'evaluate': True})

    @property
    def expr(self):
        return self._args[0]

    @property
    def symbols(self):
        return self._args[1:]

    def _eval_subs(self, old, new):
        if self==old:
            return new
        return Derivative(*map(lambda x: x._eval_subs(old, new), self.args), **{'evaluate': True})

    def matches(pattern, expr, repl_dict={}, evaluate=False):
        # this method needs a cleanup.

        #print "?   :",pattern, expr, repl_dict, evaluate
        #if repl_dict:
        #    return repl_dict
        for p,v in repl_dict.items():
            if p==pattern:
                if v==expr: return repl_dict
                return None
        assert isinstance(pattern, Derivative)
        if isinstance(expr, Derivative):
            if len(expr.symbols) == len(pattern.symbols):
                    #print "MAYBE:",pattern, expr, repl_dict, evaluate
                    return Basic.matches(pattern, expr, repl_dict, evaluate)
        #print "NONE:",pattern, expr, repl_dict, evaluate
        return None
        #print pattern, expr, repl_dict, evaluate
        stop
        if pattern.nargs is not None:
            if pattern.nargs != expr.nargs:
                return None
        repl_dict = repl_dict.copy()
        repl_dict[pattern] = expr
        return repl_dict

    def _eval_lseries(self, x, x0):
        stop
        arg = self.args[0]
        dx = self.args[1]
        for term in arg.lseries(x, x0):
            yield term.diff(dx)

    def _eval_nseries(self, x, x0, n):
        arg = self.args[0]
        arg = arg.nseries(x, x0, n)
        o = arg.getO()
        dx = self.args[1]
        if o:
            return arg.removeO().diff(dx) + arg.getO()/dx
        else:
            return arg.removeO().diff(dx)

class Lambda(Function):
    """
    Lambda(x, expr) represents a lambda function similar to Python's
    'lambda x: expr'. A function of several variables is written as
    Lambda((x, y, ...), expr).

    A simple example:
        >>> from sympy import Symbol
        >>> x = Symbol('x')
        >>> f = Lambda(x, x**2)
        >>> f(4)
        16

    For multivariate functions, use:
        >>> x = Symbol('x')
        >>> y = Symbol('y')
        >>> z = Symbol('z')
        >>> t = Symbol('t')
        >>> f2 = Lambda(x,y,z,t,x+y**z+t**z)
        >>> f2(1,2,3,4)
        73

    Multivariate functions can be curries for partial applications:
        >>> sum2numbers = Lambda(x,y,x+y)
        >>> sum2numbers(1,2)
        3
        >>> plus1 = sum2numbers(1)
        >>> plus1(3)
        4

    A handy shortcut for lots of arguments:
        >>> from sympy import *
        >>> var('x y z')
        (x, y, z)
        >>> p = x, y, z
        >>> f = Lambda(p, x + y*z)
        >>> f(*p)
        x + y*z

    """

    # a minimum of 2 arguments (parameter, expression) are needed
    nargs = 2
    def __new__(cls,*args):
        assert len(args) >= 2,"Must have at least one parameter and an expression"
        if len(args) == 2 and isinstance(args[0], (list, tuple)):
            args = tuple(args[0])+(args[1],)
        obj = Function.__new__(cls,*args)
        obj.nargs = len(args)-1
        return obj

    @classmethod
    @deprecated
    def canonize(cls, *args):
        return cls.eval(*args)

    @classmethod
    def eval(cls,*args):
        obj = Basic.__new__(cls, *args)
        #use dummy variables internally, just to be sure
        nargs = len(args)-1

        expression = args[nargs]
        funargs = [Symbol(arg.name, dummy=True) for arg in args[:nargs]]
        #probably could use something like foldl here
        for arg,funarg in zip(args[:nargs],funargs):
            expression = expression.subs(arg,funarg)
        funargs.append(expression)
        obj._args = tuple(funargs)

        return obj

    def apply(self, *args):
        """Applies the Lambda function "self" to the arguments given.
        This supports partial application.

        Example:
            >>> from sympy import Symbol
            >>> x = Symbol('x')
            >>> y = Symbol('y')
            >>> f = Lambda(x, x**2)
            >>> f.apply(4)
            16
            >>> sum2numbers = Lambda(x,y,x+y)
            >>> sum2numbers(1,2)
            3
            >>> plus1 = sum2numbers(1)
            >>> plus1(3)
            4

        """

        nparams = self.nargs
        assert nparams >= len(args),"Cannot call function with more parameters than function variables: %s (%d variables) called with %d arguments" % (str(self),nparams,len(args))

        #replace arguments
        expression = self.args[self.nargs]
        for arg,funarg in zip(args,self.args[:nparams]):
            expression = expression.subs(funarg,arg)

        #curry the rest
        if nparams != len(args):
            unused_args = list(self.args[len(args):nparams])
            unused_args.append(expression)
            return Lambda(*tuple(unused_args))
        return expression

    def __call__(self, *args):
        return self.apply(*args)

    def __eq__(self, other):
        if isinstance(other, Lambda):
            if not len(self.args) == len(other.args):
                return False

            selfexpr = self.args[self.nargs]
            otherexpr = other.args[other.nargs]
            for selfarg,otherarg in zip(self.args[:self.nargs],other.args[:other.nargs]):
                otherexpr = otherexpr.subs(otherarg,selfarg)
            if selfexpr == otherexpr:
                return True
           # if self.args[1] == other.args[1].subs(other.args[0], self.args[0]):
           #     return True
        return False

@vectorize(0,1,2)
def diff(f, x, times = 1, evaluate=True):
    """Differentiate f with respect to x

    It's just a wrapper to unify .diff() and the Derivative class,
    it's interface is similar to that of integrate()

    see http://documents.wolfram.com/v5/Built-inFunctions/AlgebraicComputation/Calculus/D.html
    """

    return Derivative(f,x,times, **{'evaluate':evaluate})

@vectorize(0)
def expand(e, deep=True, power_base=True, power_exp=True, mul=True, \
           log=True, multinomial=True, basic=True, **hints):
    """
    Expand an expression using methods given as hints.

    Hints are applied with arbitrary order so your code shouldn't
    depend on the way hints are passed to this method.

    Hints evaluated unless explicity set to False are:
      basic, log, multinomial, mul, power_base, and power_exp
    The following hints are supported but not applied unless set to True:
      complex, func, and trig.

    basic is a generic keyword for methods that want to be expanded
    automatically.  For example, Integral uses expand_basic to expand the
    integrand.  If you want your class expand methods to run automatically and
    they don't fit one of the already automatic methods, wrap it around
    _eval_expand_basic.

    If deep is set to True, things like arguments of functions are
    recursively expanded.  Use deep=False to only expand on the top
    level.

    Also see expand_log, expand_mul, expand_complex, expand_trig,
    and expand_func, which are wrappers around those expansion methods.

    >>> from sympy import *
    >>> x,y = symbols('xy')

    mul - Distributes multiplication over addition.
    >>> (y*(x + z)).expand(mul=True)
    x*y + y*z

    complex - Split an expression into real and imaginary parts.
    >>> (x+y).expand(complex=True)
    I*im(x) + I*im(y) + re(x) + re(y)
    >>> cos(x).expand(complex=True)
    cos(re(x))*cosh(im(x)) - I*sin(re(x))*sinh(im(x))

    power_exp - Expand addition in exponents into multiplied bases.
    >>> exp(x+y).expand(power_exp=True)
    exp(x)*exp(y)
    >>> (2**(x+y)).expand(power_exp=True)
    2**x*2**y

    power_base - Split powers of multiplied bases.
    >>> ((x*y)**z)).expand(power_base=True)
    x**z*y**z

    log - Pull out power of an argument as a coefficient and split logs products
    into sums of logs.  Note that these only work if the arguments of the log
    function have the proper assumptions: the arguments must be positive and the
    exponents must be real.
    >>> log(x**2*y).expand(log=True)
    log(x**2*y)
    >>> x, y = symbols('xy', positive=True)
    >>> log(x**2*y).expand(log=True)
    2*log(x)+log(y)

    trig - Do trigonometric expansions.
    >>> cos(x+y).expand(trig=True)
    cos(x)*cos(y) - sin(x)*sin(y)

    func - Expand other functions.
    >>> gamma(x+1).expand(func=True)
    x*gamma(x)

    multinomial - Expand (x + y + ...)**n where n is a positive integer.
    >>> ((x+y+z)**2).expand(multinomial=True)
    2*x*y + 2*x*z + 2*y*z + x**2 + y**2 + z**2

    You can shut off methods that you don't want.
    >>> (exp(x+y)*(x+y)).expand()
    x*exp(x)*exp(y) + y*exp(x)*exp(y)
    >>> (exp(x+y)*(x+y)).expand(power_exp=False)
    x*exp(x + y) + y*exp(x + y)
    >>> (exp(x+y)*(x+y)).expand(mul=False)
    (x + y)*exp(x)*exp(y)

    Use deep=False to only expand on the top level.
    >>> exp(x+exp(x+y)).expand()
    exp(x)*exp(exp(x)*exp(y))
    >>> exp(x+exp(x+y)).expand(deep=False)
    exp(x)*exp(exp(x + y))

    Note: because hints are applied in arbitrary order, some hints may
    prevent expansion by other hints if they are applied first.  In
    particular, mul may distribute multiplications and prevent log and
    power_base from expanding them.  Also, if mul is applied before multinomial,
    the expression might not be fully distributed.  The solution is to expand
    with mul=False first, then run expand_mul if you need further expansion.

    Examples:
    >>> x, y, z = symbols('xyz', positive=True)
    #>>> expand(log(x*(y+z))) # could be either one below
    log(x*y + x*z)
    log(x) + log(y + z)
    >>> expand_log(log(x*y+x*z))
    log(x*y+x*z)
    >>> expand(log(x*(y+z), mul=False)
    log(x) + log(y + z)

    #>>> expand((x*(y+z))**x) # could be either one below
    (x*y + x*z)**x
    x**x*(y + z)**x
    >>> expand((x*(y+z))**x, mul=False)
    x**x*(y + z)**x

    #>>> expand(x*(y+z)**2) # could be either one below
    2*x*y*z + x*y**2 + x*z**2
    x*(y + z)**2
    >>> expand(x*(y+z)**2, mul=False
    x*(2*y*z + y**2 + z**2)
    >>> expand_mul(_)
    2*x*y*z + x*y**2 + x*z**2
       """
    hints['power_base'] = power_base
    hints['power_exp'] = power_exp
    hints['mul'] = mul
    hints['log'] = log
    hints['multinomial'] = multinomial
    hints['basic'] = basic
    return sympify(e).expand(deep=deep, **hints)

# These are simple wrappers around single hints.  Fell free to add ones for
# power_exp, power_base, multinomial, or basic if you need them.
def expand_mul(expr, deep=True):
    """
    Wrapper around expand that only uses the mul hint.  See the expand
    docstring for more information.

    Example:
    >>> from sympy import *
    >>> x, y = symbols('xy', positive=True)
    >>> expand_mul(exp(x+y)*(x+y)*log(x*y**2))
    x*exp(x + y)*log(x*y**2) + y*exp(x + y)*log(x*y**2)
    """
    return sympify(expr).expand(deep=deep, mul=True, power_exp=False,\
    power_base=False, basic=False, multinomial=False, log=False)

def expand_log(expr, deep=True):
    """
    Wrapper around expand that only uses the log hint.  See the expand
    docstring for more information.

    Example:
    >>> from sympy import *
    >>> x, y = symbols('xy', positive=True)
    >>> expand_log(exp(x+y)*(x+y)*log(x*y**2))
    (x + y)*(2*log(y) + log(x))*exp(x + y)
    """
    return sympify(expr).expand(deep=deep, log=True, mul=False,\
    power_exp=False, power_base=False, multinomial=False, basic=False)

def expand_func(expr, deep=True):
    """
    Wrapper around expand that only uses the func hint.  See the expand
    docstring for more information.

    Example:
    >>> from sympy import *
    >>> x = Symbol('x')
    >>> expand_func(gamma(x + 2))
    x*(1 + x)*gamma(x)
    """
    return sympify(expr).expand(deep=deep, func=True, basic=False,\
    log=False, mul=False, power_exp=False, power_base=False, multinomial=False)

def expand_trig(expr, deep=True):
    """
    Wrapper around expand that only uses the trig hint.  See the expand
    docstring for more information.

    Example:
    >>> from sympy import *
    >>> x, y = symbols('xy')
    >>> expand_trig(sin(x+y)*(x+y))
    (x + y)*(cos(x)*sin(y) + cos(y)*sin(x))
    """
    return sympify(expr).expand(deep=deep, trig=True, basic=False,\
    log=False, mul=False, power_exp=False, power_base=False, multinomial=False)

def expand_complex(expr, deep=True):
    """
    Wrapper around expand that only uses the complex hint.  See the expand
    docstring for more information.

    Example:
    >>> from sympy import *
    >>> z = Symbol('z')
    >>> expand_complex(z**(2*I))
    I*im(z**(2*I)) + re(z**(2*I))
    """
    return sympify(expr).expand(deep=deep, complex=True, basic=False,\
    log=False, mul=False, power_exp=False, power_base=False, multinomial=False)

from sympify import sympify
from add    import Add


text:
#include "../../../inc/MarlinConfigPre.h"

#if HAS_TFT_LVGL_UI

#include "draw_ui.h"
#include <lv_conf.h>

#include "../../../inc/MarlinConfig.h"

extern lv_group_t *g;
static lv_obj_t *scr;

enum {
  ID_LEVEL_RETURN = 1,
  ID_LEVEL_POSITION,
  ID_LEVEL_COMMAND,
  ID_LEVEL_ZOFFSET
};

static void event_handler(lv_obj_t *obj, lv_event_t event) {
  if (event != LV_EVENT_RELEASED) return;
  lv_clear_level_settings();
  switch (obj->mks_obj_id) {
    case ID_LEVEL_RETURN:
      draw_return_ui();
      break;
    case ID_LEVEL_POSITION:
      lv_draw_tramming_pos_settings();
      break;
    case ID_LEVEL_COMMAND:
      keyboard_value = autoLevelGcodeCommand;
      lv_draw_keyboard();
      break;
    #if HAS_BED_PROBE
      case ID_LEVEL_ZOFFSET:
        lv_draw_auto_level_offset_settings();
        break;
    #endif
  }
}

void lv_draw_level_settings() {
  scr = lv_screen_create(LEVELING_PARA_UI, machine_menu.LevelingParaConfTitle);
  lv_screen_menu_item(scr, machine_menu.TrammingPosConf, PARA_UI_POS_X, PARA_UI_POS_Y, event_handler, ID_LEVEL_POSITION, 0);
  lv_screen_menu_item(scr, machine_menu.LevelingAutoCommandConf, PARA_UI_POS_X, PARA_UI_POS_Y * 2, event_handler, ID_LEVEL_COMMAND, 1);
  #if HAS_BED_PROBE
    lv_screen_menu_item(scr, machine_menu.LevelingAutoZoffsetConf, PARA_UI_POS_X, PARA_UI_POS_Y * 3, event_handler, ID_LEVEL_ZOFFSET, 2);
  #endif
  lv_big_button_create(scr, "F:/bmp_back70x40.bin", common_menu.text_back, PARA_UI_BACL_POS_X + 10, PARA_UI_BACL_POS_Y, event_handler, ID_LEVEL_RETURN, true);
}

void lv_clear_level_settings() {
  #if HAS_ROTARY_ENCODER
    if (gCfgItems.encoder_enable) lv_group_remove_all_objs(g);
  #endif
  lv_obj_del(scr);
}

#endif // HAS_TFT_LVGL_UI


text:
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
    xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
    xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd
                        http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">

    <property name="now" value="now()" dbms="h2"/>

    <property name="now" value="current_timestamp" dbms="postgresql"/>

    <property name="floatType" value="float4" dbms="postgresql, h2"/>
    <property name="floatType" value="float" dbms="mysql, oracle, mssql"/>

    <!--
        Added the entity Campagne.
    -->
    <changeSet id="20170422204528-1" author="jhipster">
        <createTable tableName="campagne">
            <column name="id" type="bigint" autoIncrement="${autoIncrement}">
                <constraints primaryKey="true" nullable="false"/>
            </column>
            <column name="version" type="varchar(255)">
                <constraints nullable="false" />
            </column>

            <column name="datedebut" type="date">
                <constraints nullable="false" />
            </column>

            <column name="datefin" type="date">
                <constraints nullable="true" />
            </column>

            <column name="commentaire" type="varchar(255)">
                <constraints nullable="true" />
            </column>

            <column name="bloquant" type="integer">
                <constraints nullable="true" />
            </column>

            <column name="majeur" type="integer">
                <constraints nullable="true" />
            </column>

            <column name="mineur" type="integer">
                <constraints nullable="true" />
            </column>

            <column name="evolution" type="integer">
                <constraints nullable="true" />
            </column>

            <column name="termine" type="boolean">
                <constraints nullable="true" />
            </column>

            <column name="application_id" type="bigint">
                <constraints nullable="false" />
            </column>

            <column name="typetest_id" type="bigint">
                <constraints nullable="false" />
            </column>

            <column name="resultat_id" type="bigint">
                <constraints nullable="false" />
            </column>

            <!-- jhipster-needle-liquibase-add-column - JHipster will add columns here, do not remove-->
        </createTable>

    </changeSet>
</databaseChangeLog>


text:
namespace Evidyon {
namespace Network {

PacketEncoder::PacketEncoder() {
  packet_ = NULL;
  next_available_bytes_ = NULL;
  bytes_available_ = 0;
}

PacketEncoder::~PacketEncoder() {
  if (packet_) {
    enet_packet_destroy(packet_);
    packet_ = NULL;
  }
}

void PacketEncoder::allocate(bool reliable, int header_bytes) {
  if (packet_) {
    enet_packet_destroy(packet_);
  }
  enet_uint32 flags = reliable ? ENET_PACKET_FLAG_RELIABLE :
                                 ENET_PACKET_FLAG_UNSEQUENCED;
  packet_ = enet_packet_create(0, MAX_PACKET_BYTES, flags);
  header_bytes += Evidyon::Network::Packet::NETWORK_MESSAGE_SIZE;
  next_available_bytes_ = packet_->data + header_bytes;
  bytes_available_ = packet_->dataLength - header_bytes;
}

void* PacketEncoder::reserve(size_t bytes) {
  if (bytes_available_ < bytes) {
    return NULL;
  } else {
    void* reserved_space = next_available_bytes_;
    next_available_bytes_ = ((unsigned char*)next_available_bytes_) + bytes;
    bytes_available_ -= bytes;
    return reserved_space;
  }
}

NetworkPacket* PacketEncoder::compile(Packet::Message message_type,
                                      const void* header,
                                      size_t header_bytes) {
  NetworkPacket* packet = packet_;
  if (packet) {
    using namespace Evidyon::Network::Packet;
    char* buffer = encodeMessageType(message_type,
                                     (char*)(packet->data),
                                     (const char*)(packet->data + packet->dataLength));
    memcpy(buffer, header, header_bytes);
    size_t bytes_used = (reinterpret_cast<enet_uint8*>(next_available_bytes_)) - packet->data;
    enet_packet_resize(packet, bytes_used);
  }
  packet_ = NULL;
  bytes_available_ = 0;
  next_available_bytes_ = NULL;
  return packet;
}

}
}


text:
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package rx.android.content;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action0;
import rx.subscriptions.Subscriptions;

class OnSubscribeLocalBroadcastRegister implements Observable.OnSubscribe<Intent> {

    private final Context context;
    private final IntentFilter intentFilter;

    public OnSubscribeLocalBroadcastRegister(Context context, IntentFilter intentFilter) {
        this.context = context;
        this.intentFilter = intentFilter;
    }

    @Override
    public void call(final Subscriber<? super Intent> subscriber) {
        final LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context);
        final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                subscriber.onNext(intent);
            }
        };

        final Subscription subscription = Subscriptions.create(new Action0() {
            @Override
            public void call() {
                localBroadcastManager.unregisterReceiver(broadcastReceiver);
            }
        });

        subscriber.add(subscription);
        localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }
}


text:
require "cases/helper"
require 'models/developer'
require 'models/project'
require 'models/company'
require 'models/topic'
require 'models/reply'
require 'models/computer'
require 'models/customer'
require 'models/order'
require 'models/post'
require 'models/author'
require 'models/tag'
require 'models/tagging'
require 'models/comment'

class BelongsToAssociationsTest < ActiveRecord::TestCase
  fixtures :accounts, :companies, :developers, :projects, :topics,
           :developers_projects, :computers, :authors, :posts, :tags, :taggings, :comments

  def test_belongs_to
    Client.find(3).firm.name
    assert_equal companies(:first_firm).name, Client.find(3).firm.name
    assert !Client.find(3).firm.nil?, "Microsoft should have a firm"
  end

  def test_proxy_assignment
    account = Account.find(1)
    assert_nothing_raised { account.firm = account.firm }
  end

  def test_triple_equality
    assert Client.find(3).firm === Firm
    assert Firm === Client.find(3).firm
  end

  def test_type_mismatch
    assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = 1 }
    assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = Project.find(1) }
  end

  def test_natural_assignment
    apple = Firm.create("name" => "Apple")
    citibank = Account.create("credit_limit" => 10)
    citibank.firm = apple
    assert_equal apple.id, citibank.firm_id
  end

  def test_no_unexpected_aliasing
    first_firm = companies(:first_firm)
    another_firm = companies(:another_firm)

    citibank = Account.create("credit_limit" => 10)
    citibank.firm = first_firm
    original_proxy = citibank.firm
    citibank.firm = another_firm

    assert_equal first_firm.object_id, original_proxy.object_id
    assert_equal another_firm.object_id, citibank.firm.object_id
  end

  def test_creating_the_belonging_object
    citibank = Account.create("credit_limit" => 10)
    apple    = citibank.create_firm("name" => "Apple")
    assert_equal apple, citibank.firm
    citibank.save
    citibank.reload
    assert_equal apple, citibank.firm
  end

  def test_building_the_belonging_object
    citibank = Account.create("credit_limit" => 10)
    apple    = citibank.build_firm("name" => "Apple")
    citibank.save
    assert_equal apple.id, citibank.firm_id
  end

  def test_natural_assignment_to_nil
    client = Client.find(3)
    client.firm = nil
    client.save
    assert_nil client.firm(true)
    assert_nil client.client_of
  end

  def test_with_different_class_name
    assert_equal Company.find(1).name, Company.find(3).firm_with_other_name.name
    assert_not_nil Company.find(3).firm_with_other_name, "Microsoft should have a firm"
  end

  def test_with_condition
    assert_equal Company.find(1).name, Company.find(3).firm_with_condition.name
    assert_not_nil Company.find(3).firm_with_condition, "Microsoft should have a firm"
  end

  def test_belongs_to_counter
    debate = Topic.create("title" => "debate")
    assert_equal 0, debate.send(:read_attribute, "replies_count"), "No replies yet"

    trash = debate.replies.create("title" => "blah!", "content" => "world around!")
    assert_equal 1, Topic.find(debate.id).send(:read_attribute, "replies_count"), "First reply created"

    trash.destroy
    assert_equal 0, Topic.find(debate.id).send(:read_attribute, "replies_count"), "First reply deleted"
  end

  def test_belongs_to_counter_with_assigning_nil
    p = Post.find(1)
    c = Comment.find(1)

    assert_equal p.id, c.post_id
    assert_equal 2, Post.find(p.id).comments.size

    c.post = nil

    assert_equal 1, Post.find(p.id).comments.size
  end

  def test_belongs_to_counter_with_reassigning
    t1 = Topic.create("title" => "t1")
    t2 = Topic.create("title" => "t2")
    r1 = Reply.new("title" => "r1", "content" => "r1")
    r1.topic = t1

    assert r1.save
    assert_equal 1, Topic.find(t1.id).replies.size
    assert_equal 0, Topic.find(t2.id).replies.size

    r1.topic = Topic.find(t2.id)

    assert r1.save
    assert_equal 0, Topic.find(t1.id).replies.size
    assert_equal 1, Topic.find(t2.id).replies.size

    r1.topic = nil

    assert_equal 0, Topic.find(t1.id).replies.size
    assert_equal 0, Topic.find(t2.id).replies.size

    r1.topic = t1

    assert_equal 1, Topic.find(t1.id).replies.size
    assert_equal 0, Topic.find(t2.id).replies.size

    r1.destroy

    assert_equal 0, Topic.find(t1.id).replies.size
    assert_equal 0, Topic.find(t2.id).replies.size
  end

  def test_belongs_to_counter_after_save
    topic = Topic.create!(:title => "monday night")
    topic.replies.create!(:title => "re: monday night", :content => "football")
    assert_equal 1, Topic.find(topic.id)[:replies_count]

    topic.save!
    assert_equal 1, Topic.find(topic.id)[:replies_count]
  end

  def test_belongs_to_counter_after_update_attributes
    topic = Topic.create!(:title => "37s")
    topic.replies.create!(:title => "re: 37s", :content => "rails")
    assert_equal 1, Topic.find(topic.id)[:replies_count]

    topic.update_attributes(:title => "37signals")
    assert_equal 1, Topic.find(topic.id)[:replies_count]
  end

  def test_belongs_to_counter_after_save
    topic = Topic.create("title" => "monday night")
    topic.replies.create("title" => "re: monday night", "content" => "football")
    assert_equal 1, Topic.find(topic.id).send(:read_attribute, "replies_count")

    topic.save
    assert_equal 1, Topic.find(topic.id).send(:read_attribute, "replies_count")
  end

  def test_belongs_to_counter_after_update_attributes
    topic = Topic.create("title" => "37s")
    topic.replies.create("title" => "re: 37s", "content" => "rails")
    assert_equal 1, Topic.find(topic.id).send(:read_attribute, "replies_count")

    topic.update_attributes("title" => "37signals")
    assert_equal 1, Topic.find(topic.id).send(:read_attribute, "replies_count")
  end

  def test_assignment_before_parent_saved
    client = Client.find(:first)
    apple = Firm.new("name" => "Apple")
    client.firm = apple
    assert_equal apple, client.firm
    assert apple.new_record?
    assert client.save
    assert apple.save
    assert !apple.new_record?
    assert_equal apple, client.firm
    assert_equal apple, client.firm(true)
  end

  def test_assignment_before_child_saved
    final_cut = Client.new("name" => "Final Cut")
    firm = Firm.find(1)
    final_cut.firm = firm
    assert final_cut.new_record?
    assert final_cut.save
    assert !final_cut.new_record?
    assert !firm.new_record?
    assert_equal firm, final_cut.firm
    assert_equal firm, final_cut.firm(true)
  end

  def test_assignment_before_either_saved
    final_cut = Client.new("name" => "Final Cut")
    apple = Firm.new("name" => "Apple")
    final_cut.firm = apple
    assert final_cut.new_record?
    assert apple.new_record?
    assert final_cut.save
    assert !final_cut.new_record?
    assert !apple.new_record?
    assert_equal apple, final_cut.firm
    assert_equal apple, final_cut.firm(true)
  end

  def test_new_record_with_foreign_key_but_no_object
    c = Client.new("firm_id" => 1)
    assert_equal Firm.find(:first), c.firm_with_basic_id
  end

  def test_forgetting_the_load_when_foreign_key_enters_late
    c = Client.new
    assert_nil c.firm_with_basic_id

    c.firm_id = 1
    assert_equal Firm.find(:first), c.firm_with_basic_id
  end

  def test_field_name_same_as_foreign_key
    computer = Computer.find(1)
    assert_not_nil computer.developer, ":foreign key == attribute didn't lock up" # '
  end

  def test_counter_cache
    topic = Topic.create :title => "Zoom-zoom-zoom"
    assert_equal 0, topic[:replies_count]

    reply = Reply.create(:title => "re: zoom", :content => "speedy quick!")
    reply.topic = topic

    assert_equal 1, topic.reload[:replies_count]
    assert_equal 1, topic.replies.size

    topic[:replies_count] = 15
    assert_equal 15, topic.replies.size
  end

  def test_custom_counter_cache
    reply = Reply.create(:title => "re: zoom", :content => "speedy quick!")
    assert_equal 0, reply[:replies_count]

    silly = SillyReply.create(:title => "gaga", :content => "boo-boo")
    silly.reply = reply

    assert_equal 1, reply.reload[:replies_count]
    assert_equal 1, reply.replies.size

    reply[:replies_count] = 17
    assert_equal 17, reply.replies.size
  end

  def test_store_two_association_with_one_save
    num_orders = Order.count
    num_customers = Customer.count
    order = Order.new

    customer1 = order.billing = Customer.new
    customer2 = order.shipping = Customer.new
    assert order.save
    assert_equal customer1, order.billing
    assert_equal customer2, order.shipping

    order.reload

    assert_equal customer1, order.billing
    assert_equal customer2, order.shipping

    assert_equal num_orders +1, Order.count
    assert_equal num_customers +2, Customer.count
  end

  def test_store_association_in_two_relations_with_one_save
    num_orders = Order.count
    num_customers = Customer.count
    order = Order.new

    customer = order.billing = order.shipping = Customer.new
    assert order.save
    assert_equal customer, order.billing
    assert_equal customer, order.shipping

    order.reload

    assert_equal customer, order.billing
    assert_equal customer, order.shipping

    assert_equal num_orders +1, Order.count
    assert_equal num_customers +1, Customer.count
  end

  def test_store_association_in_two_relations_with_one_save_in_existing_object
    num_orders = Order.count
    num_customers = Customer.count
    order = Order.create

    customer = order.billing = order.shipping = Customer.new
    assert order.save
    assert_equal customer, order.billing
    assert_equal customer, order.shipping

    order.reload

    assert_equal customer, order.billing
    assert_equal customer, order.shipping

    assert_equal num_orders +1, Order.count
    assert_equal num_customers +1, Customer.count
  end

  def test_store_association_in_two_relations_with_one_save_in_existing_object_with_values
    num_orders = Order.count
    num_customers = Customer.count
    order = Order.create

    customer = order.billing = order.shipping = Customer.new
    assert order.save
    assert_equal customer, order.billing
    assert_equal customer, order.shipping

    order.reload

    customer = order.billing = order.shipping = Customer.new

    assert order.save
    order.reload

    assert_equal customer, order.billing
    assert_equal customer, order.shipping

    assert_equal num_orders +1, Order.count
    assert_equal num_customers +2, Customer.count
  end

  def test_association_assignment_sticks
    post = Post.find(:first)

    author1, author2 = Author.find(:all, :limit => 2)
    assert_not_nil author1
    assert_not_nil author2

    # make sure the association is loaded
    post.author

    # set the association by id, directly
    post.author_id = author2.id

    # save and reload
    post.save!
    post.reload

    # the author id of the post should be the id we set
    assert_equal post.author_id, author2.id
  end

  def test_cant_save_readonly_association
    assert_raise(ActiveRecord::ReadOnlyRecord) { companies(:first_client).readonly_firm.save! }
    assert companies(:first_client).readonly_firm.readonly?
  end

  def test_save_fails_for_invalid_belongs_to
    log = AuditLog.new
    assert log.valid?

    log.build_developer # Build invalid association
    assert !log.developer.valid?
    assert !log.valid?
    assert_equal "is invalid", log.errors.on("developer")

    assert !log.save
  end

end


text:
#ifndef Q3MEMARRAY_H
#define Q3MEMARRAY_H

#include <Qt3Support/q3garray.h>
#include <QtCore/qvector.h>

QT_BEGIN_HEADER

QT_BEGIN_NAMESPACE

QT_MODULE(Qt3SupportLight)

template<class type>
class Q3MemArray : public Q3GArray
{
public:
    typedef type* Iterator;
    typedef const type* ConstIterator;
    typedef type ValueType;

protected:
    Q3MemArray(int, int) : Q3GArray(0, 0) {}

public:
    Q3MemArray() {}
    Q3MemArray(int size) : Q3GArray(size*sizeof(type)) {}
    Q3MemArray(const Q3MemArray<type> &a) : Q3GArray(a) {}
    Q3MemArray(const QVector<type> &vector);
   ~Q3MemArray() {}
    Q3MemArray<type> &operator=(const Q3MemArray<type> &a)
				{ return (Q3MemArray<type>&)Q3GArray::assign(a); }
    type *data()    const	{ return (type *)Q3GArray::data(); }
    uint  nrefs()   const	{ return Q3GArray::nrefs(); }
    uint  size()    const	{ return Q3GArray::size()/sizeof(type); }
    uint  count()   const	{ return size(); }
    bool  isEmpty() const	{ return Q3GArray::size() == 0; }
    bool  isNull()  const	{ return Q3GArray::data() == 0; }
    bool  resize(uint size)	{ return Q3GArray::resize(size*sizeof(type)); }
    bool  resize(uint size, Optimization optim) { return Q3GArray::resize(size*sizeof(type), optim); }
    bool  truncate(uint pos)	{ return Q3GArray::resize(pos*sizeof(type)); }
    bool  fill(const type &d, int size = -1)
	{ return Q3GArray::fill((char*)&d,size,sizeof(type)); }
    void  detach()		{ Q3GArray::detach(); }
    Q3MemArray<type>   copy() const
	{ Q3MemArray<type> tmp; return tmp.duplicate(*this); }
    Q3MemArray<type>& assign(const Q3MemArray<type>& a)
	{ return (Q3MemArray<type>&)Q3GArray::assign(a); }
    Q3MemArray<type>& assign(const type *a, uint n)
	{ return (Q3MemArray<type>&)Q3GArray::assign((char*)a,n*sizeof(type)); }
    Q3MemArray<type>& duplicate(const Q3MemArray<type>& a)
	{ return (Q3MemArray<type>&)Q3GArray::duplicate(a); }
    Q3MemArray<type>& duplicate(const type *a, uint n)
	{ return (Q3MemArray<type>&)Q3GArray::duplicate((char*)a,n*sizeof(type)); }
    Q3MemArray<type>& setRawData(const type *a, uint n)
	{ return (Q3MemArray<type>&)Q3GArray::setRawData((char*)a,
						     n*sizeof(type)); }
    void resetRawData(const type *a, uint n)
	{ Q3GArray::resetRawData((char*)a,n*sizeof(type)); }
    int	 find(const type &d, uint i=0) const
	{ return Q3GArray::find((char*)&d,i,sizeof(type)); }
    int	 contains(const type &d) const
	{ return Q3GArray::contains((char*)&d,sizeof(type)); }
    void sort() { Q3GArray::sort(sizeof(type)); }
    int  bsearch(const type &d) const
	{ return Q3GArray::bsearch((const char*)&d,sizeof(type)); }
    // ### Qt 4.0: maybe provide uint overload as work-around for MSVC bug
    type& operator[](int i) const
	{ return (type &)(*(type *)Q3GArray::at(i*sizeof(type))); }
    type& at(uint i) const
	{ return (type &)(*(type *)Q3GArray::at(i*sizeof(type))); }
	 operator const type*() const { return (const type *)Q3GArray::data(); }
    bool operator==(const Q3MemArray<type> &a) const { return isEqual(a); }
    bool operator!=(const Q3MemArray<type> &a) const { return !isEqual(a); }
    Iterator begin() { return data(); }
    Iterator end() { return data() + size(); }
    ConstIterator begin() const { return data(); }
    ConstIterator end() const { return data() + size(); }

    operator QVector<type>() const;
};

template<class type>
Q_OUTOFLINE_TEMPLATE Q3MemArray<type>::Q3MemArray(const QVector<type> &vector)
    : Q3GArray(vector.size()*sizeof(type))
{
    for (int i = 0; i < vector.size(); ++i)
        at(i) = vector.at(i);
}

template<class type>
Q_OUTOFLINE_TEMPLATE Q3MemArray<type>::operator QVector<type>() const
{
    QVector<type> vector;
    for (int i = 0; i < size(); ++i)
        vector.append(at(i));
    return vector;
}

QT_END_NAMESPACE

QT_END_HEADER

#endif // Q3MEMARRAY_H


text:
'use strict';

/* Filters */

angular.module('myApp.filters', [])

  .filter('reverse', [function() {
    return function(text) {
      return text.split("").reverse().join("");
    }
  }])

  .filter('pre', [function() {
    return function(text) {
      return "<pre>"+text+"<pre>";  //this doesn't work.
    }
  }]);


text:
module Rates
  # Gets the exchange price from certain currency amount to other currency.
  # @note BTC units are expected in satoshis. Other currencies units are
  #       expected in cents.
  def spot_prices(amount, from: 'BTC', to: 'MXN')
    same_currencies_error if from.eql? to

    resource :get, 'api/v1/spot-prices',
             currency_from: from,
             currency_to: to,
             amount: amount
  end

  # Gets the exchange price list for the supported currencies.
  def tickers
    resource :get, 'api/v1/tickers'
  end

private

  def same_currencies_error
    raise ArgumentError, 'Currencies must be different.'
  end
end

module Volabit
  module API
    include Rates
  end
end


text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.application.options.codeStyle.arrangement;

import org.jetbrains.annotations.NonNls;

/**
 * @author Denis Zhdanov
 */
public final class ArrangementConstants {

  @NonNls public static final String ACTION_GROUP_GROUPING_RULES_CONTROL_TOOLBAR = "Arrangement.Rule.Group.Control.ToolBar";
  @NonNls public static final String GROUPING_RULES_CONTROL_TOOLBAR_PLACE        = "Arrangement.Rule.Group.Control.ToolBar.Place";

  @NonNls public static final String ACTION_GROUP_MATCHING_RULES_CONTEXT_MENU    = "Arrangement.Rule.Match.Control.Context.Menu";
  @NonNls public static final String ACTION_GROUP_MATCHING_RULES_CONTROL_TOOLBAR = "Arrangement.Rule.Match.Control.ToolBar";
  @NonNls public static final String MATCHING_RULES_CONTROL_TOOLBAR_PLACE        = "Arrangement.Rule.Match.Control.ToolBar.Place";
  @NonNls public static final String MATCHING_RULES_CONTROL_PLACE                = "Arrangement.Rule.Match.Control.Place";
  @NonNls public static final String ALIAS_RULE_CONTEXT_MENU                     = "Arrangement.Alias.Rule.Context.Menu";
  @NonNls public static final String ALIAS_RULE_CONTROL_TOOLBAR                  = "Arrangement.Alias.Rule.ToolBar";
  @NonNls public static final String ALIAS_RULE_CONTROL_TOOLBAR_PLACE            = "Arrangement.Alias.Rule.ToolBar.Place";
  @NonNls public static final String ALIAS_RULE_CONTROL_PLACE                    = "Arrangement.Alias.Rule.Control.Place";

  public static final int HORIZONTAL_PADDING    = 8;
  public static final int VERTICAL_PADDING      = 4;
  public static final int HORIZONTAL_GAP        = 5;
  public static final int VERTICAL_GAP          = 3;
  public static final int CALLOUT_BORDER_HEIGHT = 10;
  public static final int BORDER_ARC_SIZE       = 12;

  public static final int ANIMATION_STEPS_TIME_GAP_MILLIS = 40;
  public static final int TEXT_UPDATE_DELAY_MILLIS        = 1000;

  public static final boolean LOG_RULE_MODIFICATION = Boolean.parseBoolean(System.getProperty("log.arrangement.rule.modification"));

  private ArrangementConstants() {
  }
}


text:
<?php

namespace StyleCI\Tests\StyleCI\Events\Repo;

use StyleCI\StyleCI\Events\Repo\RepoWasEnabledEvent;
use StyleCI\StyleCI\Models\Repo;

/**
 * This is the repo was enabled event test class.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
class RepoWasEnabledEventTest extends AbstractRepoEventTestCase
{
    protected function getObjectAndParams()
    {
        $params = ['repo' => new Repo()];
        $object = new RepoWasEnabledEvent($params['repo']);

        return compact('params', 'object');
    }
}


text:
define(["jquery", "backbone", "ws"], function($, Backbone, WebServices) {

	var currencies = Backbone.Model.extend({
		urlRoot: WebServices.v1.currencies,
		defaults: {

		},
		initialize: function() {
			//alert("Welcome to this world");
		},
		toString: function(amount){
			if(amount === undefined || amount === null){
				return "???";
			}

			var space = "";
			if(this.get('space')){
				space = " ";
			}

			if(this.get('after_amount')){
				return amount.toFixed(2) + space + this.get('sign');
			} else {
				return this.get('sign') + space + amount.toFixed(2);
			}
		}
	});

	return currencies;
});