text:
scientific_library = 'OpenCV'    # Set this to 'OpenCV' or 'SciPy'
input_filename = 'Greist_Building.JPG'
output_width = 1000
output_height = 850

#######################################################
# Imports
#######################################################

import numpy as np
import matplotlib.pyplot as plt
import benswidgets    # local import

if scientific_library == 'OpenCV':
    import cv2

elif scientific_library == 'SciPy':
    import scipy.ndimage
    import scipy.misc

#######################################################
# Get Input Image
#######################################################

if scientific_library == 'OpenCV':
    input_image = cv2.imread(input_filename, cv2.IMREAD_UNCHANGED)
    input_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2RGB)

elif scientific_library == 'SciPy':
    input_image = scipy.misc.imread(input_filename)

#######################################################
# Figure 1 - Select Quadrilateral from Input Image
#######################################################

fig1 = plt.figure(1)
fig1.canvas.set_window_title('Figure 1 - Select Quadrilateral from Input Image')
ax1 = fig1.add_subplot(1, 1, 1)
img1 = ax1.imshow(input_image)
ax1.set_xticks(())
ax1.set_yticks(())
ax1.set_aspect('equal')
quadrilateral = benswidgets.InteractiveQuadrilateral(
                                axes = ax1,
                                xdata = np.array([100, 900, 900, 100]),
                                ydata = np.array([100, 100, 900, 900])
                            )
fig1.tight_layout(pad=0, w_pad=0, h_pad=0)

#################################################
# Generate Output Image
#################################################

output_image = np.zeros((output_height,output_width,3), dtype=np.uint8)

def generate_output_image():
    """Get projective transform, apply it to input_image,
       and save the result to output_image.
       This function should be called immediately after it's definition
       and whenever the user makes changes that affect this function."""

    global output_image

    # Get four input points of the transform
    X = quadrilateral.xdata.astype(np.float32).reshape(4,1)
    Y = quadrilateral.ydata.astype(np.float32).reshape(4,1)

    # Get corresponding output points of the transform
    x = np.array((0, output_width,  output_width,    0     ), dtype=np.float32).reshape(4,1)
    y = np.array((0,    0    , output_height, output_height), dtype=np.float32).reshape(4,1)

    if scientific_library == 'OpenCV':

        # Get projective transform matrix M which maps the input points (X,Y)
        # to the output points (x,y)
        M = cv2.getPerspectiveTransform( src = np.hstack((X, Y)),
                                         dst = np.hstack((x, y)) )

        # Map input_image to output_image using the projective transform matrix M.
        # For every pixel in the output_image, OpenCV will use the inverse of M
        # to obtain the corresponding subpixel position in the input_image.
        # The input_image will then be sampled using linear interpolation.
        cv2.warpPerspective( src = input_image,
                             M = M,
                             dsize = (output_width, output_height),
                             dst = output_image,
                             flags = cv2.INTER_LINEAR )

    elif scientific_library == 'SciPy':

        # Get projective transform matrix M which maps the output points (x,y)
        # to the input points (X,Y).
        # Todo: Add a description of the math.
        one = np.ones((4,1), dtype=np.float32)
        zero = np.zeros((4,1), dtype=np.float32)
        A = np.vstack((
                np.hstack((   x ,    y ,   one,  zero,  zero,  zero,  -x*X,  -y*X )) ,
                np.hstack(( zero,  zero,  zero,    x ,    y ,   one,  -x*Y,  -y*Y ))
                ))
        b = np.vstack((
                X,
                Y
                ))
        m = np.linalg.solve(A, b)    # solves A @ m = b for m
        M = np.append(m, 1.0).reshape(3,3)

        # Map input_image to output_image using projective transform matrix M.
        # For every pixel in the output_image, we will use matrix M
        # to obtain the corresponding position in the input_image.
        # The input_image will then be sampled at this position using linear interpolation.
        output_coordinates_x, output_coordinates_y = \
            np.meshgrid(np.arange(0,output_width), np.arange(0,output_height), indexing='xy')

        output_coordinates = np.vstack((
                                 output_coordinates_x.ravel(),
                                 output_coordinates_y.ravel(),
                                 np.ones(output_width*output_height)
                                 ))

        # Apply the projective transform M
        temp = M.dot(output_coordinates)
        input_coordinates_x = temp[0,:] / temp[2,:]
        input_coordinates_y = temp[1,:] / temp[2,:]

        # Put input coordinates into an array with shape (2, output_height, output_width)
        # This is the (strange) shape required by the map_coordinates function.
        coords = np.array((
                     input_coordinates_y.reshape(output_height, output_width),
                     input_coordinates_x.reshape(output_height, output_width)
                     ))

        # Subsample the input_image at the coordinates given by coords using linear interpolation.
        # We will process each channel (0=red, 1=green, 2=blue) separately.
        output_image[:,:,0] = scipy.ndimage.map_coordinates(input_image[:,:,0], coords, order=1)
        output_image[:,:,1] = scipy.ndimage.map_coordinates(input_image[:,:,1], coords, order=1)
        output_image[:,:,2] = scipy.ndimage.map_coordinates(input_image[:,:,2], coords, order=1)

generate_output_image()

#################################################
# Figure 2 - Display Output Image
#################################################

fig2 = plt.figure(2)
fig2.canvas.set_window_title('Figure 2 - Output Image')
ax2 = fig2.add_subplot(1, 1, 1)
img2 = ax2.imshow(output_image, animated=True)
ax2.set_xticks(())
ax2.set_yticks(())
ax2.set_aspect('equal')
fig2.tight_layout(pad=0, w_pad=0, h_pad=0)

#################################################
# Event Handlers
#################################################

def update_figures():
    generate_output_image()
    img2.set_array(output_image)
    img2.axes.draw_artist(img2)
    img2.axes.figure.canvas.blit(img2.axes.bbox)

quadrilateral.on_changed(update_figures)

#################################################
# GUI Loop
#################################################

# Call plt.show() to display all figures and handle user interactivity.
# This is a blocking call; this script will hault here until the user closes all windows.
plt.show()

#################################################
# Save the Output Image
#################################################

if scientific_library == 'OpenCV':
    output_image = cv2.cvtColor(output_image, cv2.COLOR_RGB2BGR)
    cv2.imwrite('output_image.jpg', output_image)

elif scientific_library == 'SciPy':
    scipy.misc.imsave('output_image.jpg', output_image)


text:
namespace System.IO.Compression
{
    public partial struct BrotliDecoder : System.IDisposable
    {
        private object _dummy;
        private int _dummyPrimitive;
        public System.Buffers.OperationStatus Decompress(System.ReadOnlySpan<byte> source, System.Span<byte> destination, out int bytesConsumed, out int bytesWritten) { throw null; }
        public void Dispose() { }
        public static bool TryDecompress(System.ReadOnlySpan<byte> source, System.Span<byte> destination, out int bytesWritten) { throw null; }
    }
    public partial struct BrotliEncoder : System.IDisposable
    {
        private object _dummy;
        private int _dummyPrimitive;
        public BrotliEncoder(int quality, int window) { throw null; }
        public System.Buffers.OperationStatus Compress(System.ReadOnlySpan<byte> source, System.Span<byte> destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock) { throw null; }
        public void Dispose() { }
        public System.Buffers.OperationStatus Flush(System.Span<byte> destination, out int bytesWritten) { throw null; }
        public static int GetMaxCompressedLength(int inputSize) { throw null; }
        public static bool TryCompress(System.ReadOnlySpan<byte> source, System.Span<byte> destination, out int bytesWritten) { throw null; }
        public static bool TryCompress(System.ReadOnlySpan<byte> source, System.Span<byte> destination, out int bytesWritten, int quality, int window) { throw null; }
    }
    public sealed partial class BrotliStream : System.IO.Stream
    {
        public BrotliStream(System.IO.Stream stream, System.IO.Compression.CompressionLevel compressionLevel) { }
        public BrotliStream(System.IO.Stream stream, System.IO.Compression.CompressionLevel compressionLevel, bool leaveOpen) { }
        public BrotliStream(System.IO.Stream stream, System.IO.Compression.CompressionMode mode) { }
        public BrotliStream(System.IO.Stream stream, System.IO.Compression.CompressionMode mode, bool leaveOpen) { }
        public System.IO.Stream BaseStream { get { throw null; } }
        public override bool CanRead { get { throw null; } }
        public override bool CanSeek { get { throw null; } }
        public override bool CanWrite { get { throw null; } }
        public override long Length { get { throw null; } }
        public override long Position { get { throw null; } set { } }
        public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback asyncCallback, object asyncState) { throw null; }
        public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback asyncCallback, object asyncState) { throw null; }
        protected override void Dispose(bool disposing) { }
        public override System.Threading.Tasks.ValueTask DisposeAsync() { throw null; }
        public override int EndRead(System.IAsyncResult asyncResult) { throw null; }
        public override void EndWrite(System.IAsyncResult asyncResult) { }
        public override void Flush() { }
        public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
        public override int Read(byte[] buffer, int offset, int count) { throw null; }
        public override int Read(System.Span<byte> buffer) { throw null; }
        public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; }
        public override System.Threading.Tasks.ValueTask<int> ReadAsync(System.Memory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
        public override long Seek(long offset, System.IO.SeekOrigin origin) { throw null; }
        public override void SetLength(long value) { }
        public override void Write(byte[] buffer, int offset, int count) { }
        public override void Write(System.ReadOnlySpan<byte> buffer) { }
        public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; }
        public override System.Threading.Tasks.ValueTask WriteAsync(System.ReadOnlyMemory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
class ContentSettingsPattern;

namespace content_settings {

class RuleIterator;

class ProviderInterface {
 public:
  virtual ~ProviderInterface() = default;

  // Returns a |RuleIterator| over the content setting rules stored by this
  // provider. If |incognito| is true, the iterator returns only the content
  // settings which are applicable to the incognito mode and differ from the
  // normal mode. Otherwise, it returns the content settings for the normal
  // mode. It is not allowed to call other |ProviderInterface| functions
  // (including |GetRuleIterator|) for the same provider until the
  // |RuleIterator| is destroyed.
  // Returns nullptr to indicate the RuleIterator is empty.
  //
  // This method needs to be thread-safe and continue to work after
  // |ShutdownOnUIThread| has been called.
  virtual std::unique_ptr<RuleIterator> GetRuleIterator(
      ContentSettingsType content_type,
      bool incognito) const = 0;

  // Asks the provider to set the website setting for a particular
  // |primary_pattern|, |secondary_pattern|, |content_type| tuple. If the
  // provider accepts the setting it returns true and takes the ownership of the
  // |value|. Otherwise false is returned and the ownership of the |value| stays
  // with the caller.
  //
  // This should only be called on the UI thread, and not after
  // ShutdownOnUIThread has been called.
  virtual bool SetWebsiteSetting(
      const ContentSettingsPattern& primary_pattern,
      const ContentSettingsPattern& secondary_pattern,
      ContentSettingsType content_type,
      base::Value&& value,
      const ContentSettingConstraints& constraints) = 0;

  // Resets all content settings for the given |content_type| and empty resource
  // identifier to CONTENT_SETTING_DEFAULT.
  //
  // This should only be called on the UI thread, and not after
  // ShutdownOnUIThread has been called.
  virtual void ClearAllContentSettingsRules(
      ContentSettingsType content_type) = 0;

  // Detaches the Provider from all Profile-related objects like PrefService.
  // This methods needs to be called before destroying the Profile.
  // Afterwards, none of the methods above that should only be called on the UI
  // thread should be called anymore.
  virtual void ShutdownOnUIThread() = 0;
};

}  // namespace content_settings

#endif  // COMPONENTS_CONTENT_SETTINGS_CORE_BROWSER_CONTENT_SETTINGS_PROVIDER_H_


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Inheritance of CSS Overscroll Behavior properties</title>
<link rel="help" href="https://drafts.csswg.org/css-overscroll-behavior/#property-index">
<meta name="assert" content="Properties inherit or not according to the spec.">
<meta name="assert" content="Properties have initial values according to the spec.">


text:
require 'spec_helper'

describe PZS::Cart, type: :model do

  before :each do
    @cart = FactoryGirl.create(:cart)
  end

  describe 'create' do
    it "creates a new instance given a valid attribute" do
      @cart.should be_valid
    end
  end

  describe "#Relations" do
    it "has one order" do
      @cart.should have_one(:order)
    end

    it "has many cart_variants" do
      @cart.should have_many :cart_variants
    end

    it "has many variants" do
      @cart.should have_many(:variants).through(:cart_variants)
    end

    it "belongs to a user (fake relation)" do
      @cart.user.should_not be_nil
    end
  end

  describe "#Validations" do
    it "requires user to be set" do
      @cart.should validate_presence_of :user_id
    end
  end

end


text:
set -e

# Make sure we're in the correct directory, at the root of the source tree.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd ${SCRIPT_DIR}/../../../

source "${SCRIPT_DIR}/build_helper.subr"
JOB_COUNT="${JOB_COUNT:-$(get_job_count)}"

# Remove any old files first.
make -f tensorflow/contrib/makefile/Makefile clean
rm -rf tensorflow/contrib/makefile/downloads

# Pull down the required versions of the frameworks we need.
tensorflow/contrib/makefile/download_dependencies.sh

# Compile protobuf.
tensorflow/contrib/makefile/compile_linux_protobuf.sh

# Build TensorFlow.
make -j"${JOB_COUNT}" -f tensorflow/contrib/makefile/Makefile OPTFLAGS="-O3"


text:
#include <qsessionmanager.h>
#include <qguiapplication.h>
#include <qpa/qplatformsessionmanager.h>
#include <qpa/qplatformintegration.h>

#include <private/qobject_p.h>
#include <private/qguiapplication_p.h>
#include <private/qsessionmanager_p.h>

#ifndef QT_NO_SESSIONMANAGER

QT_BEGIN_NAMESPACE

/*!
    \class QSessionManager
    \brief The QSessionManager class provides access to the session manager.

    \inmodule QtWidgets

    A session manager in a desktop environment (in which Qt GUI applications
    live) keeps track of a session, which is a group of running applications,
    each of which has a particular state. The state of an application contains
    (most notably) the documents the application has open and the position and
    size of its windows.

    The session manager is used to save the session, e.g., when the machine is
    shut down, and to restore a session, e.g., when the machine is started up.
    We recommend that you use QSettings to save an application's settings,
    for example, window positions, recently used files, etc. When the
    application is restarted by the session manager, you can restore the
    settings.

    QSessionManager provides an interface between the application and the
    session manager so that the program can work well with the session manager.
    In Qt, session management requests for action are handled by the two
    signals QGuiApplication::commitDataRequest() and
    QGuiApplication::saveStateRequest(). Both provide a reference to a session
    manager object as argument, to allow the application to communicate with
    the session manager. The session manager can only be accessed through these
    functions.

    No user interaction is possible \e unless the application gets explicit
    permission from the session manager. You ask for permission by calling
    allowsInteraction() or, if it is really urgent, allowsErrorInteraction().
    Qt does not enforce this, but the session manager may.

    You can try to abort the shutdown process by calling cancel(). The default
    commitData() function does this if some top-level window rejected its
    closeEvent().

    For sophisticated session managers provided on Unix/X11, QSessionManager
    offers further possibilities to fine-tune an application's session
    management behavior: setRestartCommand(), setDiscardCommand(),
    setRestartHint(), setProperty(), requestPhase2(). See the respective
    function descriptions for further details.

    \sa QGuiApplication, {Session Management}
*/

/*! \enum QSessionManager::RestartHint

    This enum type defines the circumstances under which this application wants
    to be restarted by the session manager. The current values are:

    \value  RestartIfRunning    If the application is still running when the
                                session is shut down, it wants to be restarted
                                at the start of the next session.

    \value  RestartAnyway       The application wants to be started at the
                                start of the next session, no matter what.
                                (This is useful for utilities that run just
                                after startup and then quit.)

    \value  RestartImmediately  The application wants to be started immediately
                                whenever it is not running.

    \value  RestartNever        The application does not want to be restarted
                                automatically.

    The default hint is \c RestartIfRunning.
*/

QSessionManagerPrivate::QSessionManagerPrivate(const QString &id,
                                               const QString &key)
    : QObjectPrivate()
{
    platformSessionManager = QGuiApplicationPrivate::platformIntegration()->createPlatformSessionManager(id, key);
    Q_ASSERT_X(platformSessionManager, "Platform session management",
               "No platform session management, should use the default implementation");
}

QSessionManagerPrivate::~QSessionManagerPrivate()
{
    delete platformSessionManager;
    platformSessionManager = 0;
}

QSessionManager::QSessionManager(QGuiApplication *app, QString &id, QString &key)
    : QObject(*(new QSessionManagerPrivate(id, key)), app)
{
}

QSessionManager::~QSessionManager()
{
}

/*!
    Returns the identifier of the current session.

    If the application has been restored from an earlier session, this
    identifier is the same as it was in the earlier session.

    \sa sessionKey(), QGuiApplication::sessionId()
*/
QString QSessionManager::sessionId() const
{
    Q_D(const QSessionManager);
    return d->platformSessionManager->sessionId();
}

/*!
    \fn QString QSessionManager::sessionKey() const

    Returns the session key in the current session.

    If the application has been restored from an earlier session, this key is
    the same as it was when the previous session ended.

    The session key changes with every call of commitData() or saveState().

    \sa sessionId(), QGuiApplication::sessionKey()
*/
QString QSessionManager::sessionKey() const
{
    Q_D(const QSessionManager);
    return d->platformSessionManager->sessionKey();
}

/*!
    Asks the session manager for permission to interact with the user. Returns
    true if interaction is permitted; otherwise returns \c false.

    The rationale behind this mechanism is to make it possible to synchronize
    user interaction during a shutdown. Advanced session managers may ask all
    applications simultaneously to commit their data, resulting in a much
    faster shutdown.

    When the interaction is completed we strongly recommend releasing the user
    interaction semaphore with a call to release(). This way, other
    applications may get the chance to interact with the user while your
    application is still busy saving data. (The semaphore is implicitly
    released when the application exits.)

    If the user decides to cancel the shutdown process during the interaction
    phase, you must tell the session manager that this has happened by calling
    cancel().

    Here's an example of how an application's QGuiApplication::commitDataRequest()
    might be implemented:

    \snippet code/src_gui_kernel_qguiapplication.cpp 8

    If an error occurred within the application while saving its data, you may
    want to try allowsErrorInteraction() instead.

    \sa QGuiApplication::commitDataRequest(), release(), cancel()
*/
bool QSessionManager::allowsInteraction()
{
    Q_D(QSessionManager);
    return d->platformSessionManager->allowsInteraction();
}

/*!
    Returns \c true if error interaction is permitted; otherwise returns \c false.

    This is similar to allowsInteraction(), but also enables the application to
    tell the user about any errors that occur. Session managers may give error
    interaction requests higher priority, which means that it is more likely
    that an error interaction is permitted. However, you are still not
    guaranteed that the session manager will allow interaction.

    \sa allowsInteraction(), release(), cancel()
*/
bool QSessionManager::allowsErrorInteraction()
{
    Q_D(QSessionManager);
    return d->platformSessionManager->allowsErrorInteraction();
}

/*!
    Releases the session manager's interaction semaphore after an interaction
    phase.

    \sa allowsInteraction(), allowsErrorInteraction()
*/
void QSessionManager::release()
{
    Q_D(QSessionManager);
    d->platformSessionManager->release();
}

/*!
    Tells the session manager to cancel the shutdown process.  Applications
    should not call this function without asking the user first.

    \sa allowsInteraction(), allowsErrorInteraction()
*/
void QSessionManager::cancel()
{
    Q_D(QSessionManager);
    d->platformSessionManager->cancel();
}

/*!
    Sets the application's restart hint to \a hint. On application startup, the
    hint is set to \c RestartIfRunning.

    \note These flags are only hints, a session manager may or may not respect
    them.

    We recommend setting the restart hint in QGuiApplication::saveStateRequest()
    because most session managers perform a checkpoint shortly after an
    application's
    startup.

    \sa restartHint()
*/
void QSessionManager::setRestartHint(QSessionManager::RestartHint hint)
{
    Q_D(QSessionManager);
    d->platformSessionManager->setRestartHint(hint);
}

/*!
    \fn QSessionManager::RestartHint QSessionManager::restartHint() const

    Returns the application's current restart hint. The default is
    \c RestartIfRunning.

    \sa setRestartHint()
*/
QSessionManager::RestartHint QSessionManager::restartHint() const
{
    Q_D(const QSessionManager);
    return d->platformSessionManager->restartHint();
}

/*!
    If the session manager is capable of restoring sessions it will execute
    \a command in order to restore the application. The command defaults to

    \snippet code/src_gui_kernel_qguiapplication.cpp 9

    The \c -session option is mandatory; otherwise QGuiApplication cannot
    tell whether it has been restored or what the current session identifier
    is.
    See QGuiApplication::isSessionRestored() and
    QGuiApplication::sessionId() for details.

    If your application is very simple, it may be possible to store the entire
    application state in additional command line options. This is usually a
    very bad idea because command lines are often limited to a few hundred
    bytes. Instead, use QSettings, temporary files, or a database for this
    purpose. By marking the data with the unique sessionId(), you will be able
    to restore the application in a future  session.

    \sa restartCommand(), setDiscardCommand(), setRestartHint()
*/
void QSessionManager::setRestartCommand(const QStringList &command)
{
    Q_D(QSessionManager);
    d->platformSessionManager->setRestartCommand(command);
}

/*!
    Returns the currently set restart command.

    To iterate over the list, you can use the \l foreach pseudo-keyword:

    \snippet code/src_gui_kernel_qguiapplication.cpp 10

    \sa setRestartCommand(), restartHint()
*/
QStringList QSessionManager::restartCommand() const
{
    Q_D(const QSessionManager);
    return d->platformSessionManager->restartCommand();
}

/*!
    Sets the discard command to the given \a command.

    \sa discardCommand(), setRestartCommand()
*/
void QSessionManager::setDiscardCommand(const QStringList &command)
{
    Q_D(QSessionManager);
    d->platformSessionManager->setDiscardCommand(command);
}

/*!
    Returns the currently set discard command.

    To iterate over the list, you can use the \l foreach pseudo-keyword:

    \snippet code/src_gui_kernel_qguiapplication.cpp 11

    \sa setDiscardCommand(), restartCommand(), setRestartCommand()
*/
QStringList QSessionManager::discardCommand() const
{
    Q_D(const QSessionManager);
    return d->platformSessionManager->discardCommand();
}

/*!
    \overload

    Low-level write access to the application's identification and state
    records are kept in the session manager.

    The property called \a name has its value set to the string \a value.
*/
void QSessionManager::setManagerProperty(const QString &name,
                                         const QString &value)
{
    Q_D(QSessionManager);
    d->platformSessionManager->setManagerProperty(name, value);
}

/*!
    Low-level write access to the application's identification and state record
    are kept in the session manager.

    The property called \a name has its value set to the string list \a value.
*/
void QSessionManager::setManagerProperty(const QString &name,
                                         const QStringList &value)
{
    Q_D(QSessionManager);
    d->platformSessionManager->setManagerProperty(name, value);
}

/*!
    Returns \c true if the session manager is currently performing a second
    session management phase; otherwise returns \c false.

    \sa requestPhase2()
*/
bool QSessionManager::isPhase2() const
{
    Q_D(const QSessionManager);
    return d->platformSessionManager->isPhase2();
}

/*!
    Requests a second session management phase for the application. The
    application may then return immediately from the
    QGuiApplication::commitDataRequest() or QApplication::saveStateRequest()
    function, and they will be called again once most or all other
    applications have finished their session management.

    The two phases are useful for applications such as the X11 window manager
    that need to store information about another application's windows and
    therefore have to wait until these applications have completed their
    respective session management tasks.

    \note If another application has requested a second phase it may get called
    before, simultaneously with, or after your application's second phase.

    \sa isPhase2()
*/
void QSessionManager::requestPhase2()
{
    Q_D(QSessionManager);
    d->platformSessionManager->requestPhase2();
}

QT_END_NAMESPACE

#endif // QT_NO_SESSIONMANAGER


text:
/* Problem: Find All Numbers Disappeared in an Array

  Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

  Find all the elements of [1, n] inclusive that do not appear in this array.

  Note:
  - Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

  Example:

    Input: [4,3,2,7,8,2,3,1]

    Output: [5,6]

*/

var findDisappearedNumbers = function(nums) {
  var arr = [];

  for (var i = 0; i < nums.length; i++) {
    arr[nums[i]] = true;
  }

  for (var i = 0; i < nums.length; i++) {
    if (arr[i + 1]) {
      arr[i + 1] = false;
    } else arr[i + 1] = i + 1;
  }

  arr = arr.filter((num, index) => (num ? index : null));

  return arr;
};

findDisappearedNumbers([4, 3, 2, 7, 8, 2, 3, 1]); // [5, 6]

// Time Complexity: O(N)
// Space Complexity: O(N)


text:
package arez.integration.observe;

import arez.Arez;
import arez.ArezContext;
import arez.ObservableValue;
import arez.Observer;
import arez.annotations.ArezComponent;
import arez.annotations.DepType;
import arez.annotations.Observe;
import arez.annotations.ObserverRef;
import arez.integration.AbstractArezIntegrationTest;
import arez.spy.ObserverInfo;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public final class ObserveArezOrNoDependenciesTest
  extends AbstractArezIntegrationTest
{
  @ArezComponent
  static abstract class TestComponent1
  {
    final ObservableValue<?> _observableValue = Arez.context().observable();
    int _renderCallCount;

    @Observe( depType = DepType.AREZ_OR_NONE )
    void render()
    {
      if ( 0 == _renderCallCount )
      {
        _observableValue.reportObserved();
      }
      _renderCallCount++;
    }

    @ObserverRef
    abstract Observer getRenderObserver();
  }

  @Test
  public void scenario()
  {
    final TestComponent1 component = new ObserveArezOrNoDependenciesTest_Arez_TestComponent1();

    final ArezContext context = Arez.context();
    final ObserverInfo info = context.getSpy().asObserverInfo( component.getRenderObserver() );

    assertEquals( component._renderCallCount, 1 );
    assertEquals( info.getDependencies().size(), 1 );

    // should result in re-render invocation but dependencies will go to zero
    context.safeAction( component._observableValue::reportChanged );

    assertEquals( component._renderCallCount, 2 );
    assertEquals( info.getDependencies().size(), 0 );
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<merge
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:hashtagger="http://schemas.android.com/apk/res/net.thetranquilpsychonaut.hashtagger"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <net.thetranquilpsychonaut.hashtagger.sites.twitter.ui.TwitterHeader
        android:id="@+id/twitter_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <RelativeLayout
        android:id="@id/rl_wrapper"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/twitter_header">

        <net.thetranquilpsychonaut.hashtagger.widgets.LinkifiedTextView
            android:id="@+id/tv_status_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@+id/popup_menu_anchor"
            style="@style/MainMessage"/>

        <ImageView
            android:id="@id/popup_menu_anchor"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            style="@style/PopupMenuAnchor"/>

    </RelativeLayout>

    <net.thetranquilpsychonaut.hashtagger.sites.twitter.ui.TwitterButtons
        android:id="@+id/twitter_buttons"
        android:layout_below="@id/rl_wrapper"
        android:layout_width="match_parent"
        hashtagger:showViewDetailsButton="true"
        hashtagger:showSmallButtons="true"
        android:layout_height="0dp"/>

</merge>


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1"/>

  <title>Como é Cruel Viver Assim</title>
  <meta name="author" content="" />
  <meta name="description"
        content="Um “pai de família” procura um emprego de taxista. E nem como taxista ele é aceito. Então ele caminha pela rua, observa os transeuntes em uma praça, e avista uma senhora idosa vendendo..."/>

  <meta name="yandex-verification" content="48a8210fc043c5e8" />

  <meta name="generator" content="Hugo 0.54.0" />

  <meta itemprop="name" content="Como é Cruel Viver Assim"/>
  <meta itemprop="description"
        content="Um “pai de família” procura um emprego de taxista. E nem como taxista ele é aceito. Então ele caminha pela rua, observa os transeuntes em uma praça, e avista uma senhora idosa vendendo..."/>
  <meta itemprop="image"
        content="/img/logo.svg"/>

  <meta property="og:title" content="Como é Cruel Viver Assim"/>
  <meta property="og:type"
        content="article"/>
  <meta property="og:url" content="http://www.cinetenisverde.com.br/como-e-cruel-viver-assim/"/>
  <meta property="og:image"
        content="/img/logo.svg"/>
  <meta property="og:description"
        content="Um “pai de família” procura um emprego de taxista. E nem como taxista ele é aceito. Então ele caminha pela rua, observa os transeuntes em uma praça, e avista uma senhora idosa vendendo..."/>
  <meta property="og:site_name" content="Cine Tênis Verde"/>
  <meta property="article:published_time"
        content="2018-08-28T14:21:05-03:00"/>
  <meta property="article:section" content="post"/>

  <meta name="twitter:card" content="summary"/>
  <meta name="twitter:site"
        content=""/>
  <meta name="twitter:title" content="Como é Cruel Viver Assim"/>
  <meta name="twitter:description"
        content="Um “pai de família” procura um emprego de taxista. E nem como taxista ele é aceito. Então ele caminha pela rua, observa os transeuntes em uma praça, e avista uma senhora idosa vendendo..."/>
  <meta name="twitter:creator"
        content=""/>
  <meta name="twitter:image:src"
        content="/img/logo.svg"/>

  <link rel="stylesheet" type="text/css" href="/css/capsule.min.css"/>
  <link rel="stylesheet" type="text/css" href="/css/custom.css"/>

  <link rel="apple-touch-icon" href="/img/apple-touch-icon.png"/>
  <link rel="icon" href="/img/favicon.ico"/>

 Cine Tênis Verde

    <input type="checkbox" id="navbar-burger-state"/>

      search

      twitter

      rss

Como é Cruel Viver Assim

    ★★★☆☆

 Wanderley Caloni, August 28, 2018

Um “pai de família” procura um emprego de taxista. E nem como taxista ele é aceito. Então ele caminha pela rua, observa os transeuntes em uma praça, e avista uma senhora idosa vendendo alguma coisa de aspecto sujo em uma forma levantada pelo seu único braço. O outro braço ela não tinha. Ele tem um insight, e decide que precisa fazer um sequestro para conseguir ter meios para viver.

O filme de Julia Rezende baseado na peça de Fernando Ceylão (que assina o roteiro) não deixa de ser teatral, por ter muitas falas, embora os cenários e a movimentação estilo “câmera na mão” aliado a enquadramentos distorcidos daquelas pessoas tentem tornar a história mais dinâmica e mais caricata. Consegue parcialmente. Quem completa é a fotografia de Dante Belluti, que narra uma comédia usando tons opacos que deixam o humor triste.

Isso porque, apesar de ser comédia, “Como é Cruel Viver Assim” tenta ao mesmo tempo ser uma crítica social sobre as injustiças do mundo. Conseque parcialmente. As interpretações inspiradas de Silvio Guindane, como o Primo (esse é o apelido dele) do protagonista que mora com a mãe protetora e tem problemas de temperamento, e de Fabiula Nascimento, como Clivia, a esposa amorosa que faz comentários aleatórios a qualquer hora do dia, pincelam de maneira tão carismática e realista aquele mundo de desajustados tentando sobreviver que ambos já valem o ingresso.

Esta é uma história que você já viu tantas e tantas vezes: filme de sequestro. O planejamento, o contato com o pessoal do crime e, obviamente, quando as coisas dão errado. É por isso que essa pincelada de realidade brasileira, ou melhor dizendo, carioca, é tão vital para tornar o resultado acima da média. Se bem que, vez ou outra, a história tropece em momentos onde o humor escracha, como uma ponta de Otávio Augusto como “O Velho” que tenta ser uma caricatura de Poderoso Chefão de pobre, sentado imponente na metade de uma banheira acariciando um gato mais bem cuidado do que ele. E é uma ponta porque, veja bem, O Velho aparece e some da história em uma cena.

A parte mais corajosa do filme é seu final, inesperado e que faz o expectador refletir por mais tempo que todo o resto. É um final que nos avisa que esta foi apenas uma janela na vida daquelas pessoas, que vão continuar vivendo nessa tragicomédia leve até o final de suas vidas.

           Imagens e créditos no IMDB.

    ★★★☆☆

 Como é Cruel Viver Assim ● Idem. Brasil, 2018. Comédia escrita por Fernando Ceylão e dirigida por Julia Rezende. Com Silvio Guindane, Débora Lamm, Fabiula Nascimento. ● Nota: 3/5. Categoria: movies.  Publicado em 2018-08-28.  Texto escrito por Wanderley Caloni.

Quer comentar?

      Share


text:
package org.broadleafcommerce.core.catalog.domain;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.broadleafcommerce.common.admin.domain.AdminMainEntity;
import org.broadleafcommerce.common.copy.CreateResponse;
import org.broadleafcommerce.common.copy.MultiTenantCopyContext;
import org.broadleafcommerce.common.extensibility.jpa.clone.ClonePolicy;
import org.broadleafcommerce.common.extensibility.jpa.copy.DirectCopyTransform;
import org.broadleafcommerce.common.extensibility.jpa.copy.DirectCopyTransformMember;
import org.broadleafcommerce.common.extensibility.jpa.copy.DirectCopyTransformTypes;
import org.broadleafcommerce.common.media.domain.Media;
import org.broadleafcommerce.common.persistence.ArchiveStatus;
import org.broadleafcommerce.common.persistence.Status;
import org.broadleafcommerce.common.presentation.AdminPresentation;
import org.broadleafcommerce.common.presentation.AdminPresentationAdornedTargetCollection;
import org.broadleafcommerce.common.presentation.AdminPresentationClass;
import org.broadleafcommerce.common.presentation.AdminPresentationCollection;
import org.broadleafcommerce.common.presentation.AdminPresentationMap;
import org.broadleafcommerce.common.presentation.AdminPresentationToOneLookup;
import org.broadleafcommerce.common.presentation.PopulateToOneFieldsEnum;
import org.broadleafcommerce.common.presentation.RequiredOverride;
import org.broadleafcommerce.common.presentation.ValidationConfiguration;
import org.broadleafcommerce.common.presentation.client.VisibilityEnum;
import org.broadleafcommerce.common.presentation.override.AdminPresentationMergeEntry;
import org.broadleafcommerce.common.presentation.override.AdminPresentationMergeOverride;
import org.broadleafcommerce.common.presentation.override.AdminPresentationMergeOverrides;
import org.broadleafcommerce.common.presentation.override.PropertyType;
import org.broadleafcommerce.common.template.TemplatePathContainer;
import org.broadleafcommerce.common.util.DateUtil;
import org.broadleafcommerce.common.vendor.service.type.ContainerShapeType;
import org.broadleafcommerce.common.vendor.service.type.ContainerSizeType;
import org.broadleafcommerce.common.web.Locatable;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Index;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.SQLDelete;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MapKey;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.OrderBy;
import javax.persistence.Transient;

/**
 * The Class ProductImpl is the default implementation of {@link Product}. A
 * product is a general description of an item that can be sold (for example: a
 * hat). Products are not sold or added to a cart. {@link Sku}s which are
 * specific items (for example: a XL Blue Hat) are sold or added to a cart.

 *

 * If you want to add fields specific to your implementation of
 * BroadLeafCommerce you should extend this class and add your fields. If you
 * need to make significant changes to the ProductImpl then you should implement
 * your own version of {@link Product}.

 *

 * This implementation uses a Hibernate implementation of JPA configured through
 * annotations. The Entity references the following tables: BLC_PRODUCT,
 * BLC_PRODUCT_SKU_XREF, BLC_PRODUCT_IMAGE
 * @author btaylor
 * @see {@link Product}, {@link SkuImpl}, {@link CategoryImpl}
 */
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@javax.persistence.Table(name="BLC_PRODUCT")
//multi-column indexes don't appear to get exported correctly when declared at the field level, so declaring here as a workaround
@org.hibernate.annotations.Table(appliesTo = "BLC_PRODUCT", indexes = {
    @Index(name = "PRODUCT_URL_INDEX",
            columnNames = {"URL","URL_KEY"}
    )
})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blProducts")
@AdminPresentationMergeOverrides(
    {
        @AdminPresentationMergeOverride(name = "defaultSku.displayTemplate", mergeEntries =
            @AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.EXCLUDED, booleanOverrideValue = true)),
        @AdminPresentationMergeOverride(name = "defaultSku.urlKey", mergeEntries =
            @AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.EXCLUDED, booleanOverrideValue = true)),
        @AdminPresentationMergeOverride(name = "defaultSku.retailPrice", mergeEntries =
            @AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.REQUIREDOVERRIDE, overrideValue = "REQUIRED")),
        @AdminPresentationMergeOverride(name = "defaultSku.name", mergeEntries =
            @AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.REQUIREDOVERRIDE, overrideValue = "REQUIRED"))
    }
)
@AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "baseProduct")
@SQLDelete(sql="UPDATE BLC_PRODUCT SET ARCHIVED = 'Y' WHERE PRODUCT_ID = ?")
@DirectCopyTransform({
        @DirectCopyTransformMember(templateTokens = DirectCopyTransformTypes.SANDBOX, skipOverlaps=true),
        @DirectCopyTransformMember(templateTokens = DirectCopyTransformTypes.MULTITENANT_CATALOG)
})
public class ProductImpl implements Product, Status, AdminMainEntity, Locatable, TemplatePathContainer {

    private static final Log LOG = LogFactory.getLog(ProductImpl.class);
    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = 1L;

    /** The id. */
    @Id
    @GeneratedValue(generator= "ProductId")
    @GenericGenerator(
        name="ProductId",
        strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
        parameters = {
            @Parameter(name="segment_value", value="ProductImpl"),
            @Parameter(name="entity_name", value="org.broadleafcommerce.core.catalog.domain.ProductImpl")
        }
    )
    @Column(name = "PRODUCT_ID")
    @AdminPresentation(friendlyName = "ProductImpl_Product_ID", visibility = VisibilityEnum.HIDDEN_ALL)
    protected Long id;

    @Column(name = "URL")
    @AdminPresentation(friendlyName = "ProductImpl_Product_Url", order = Presentation.FieldOrder.URL,
        group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General,
        prominent = true, gridOrder = 3, columnWidth = "200px",
            requiredOverride = RequiredOverride.REQUIRED,
            validationConfigurations = { @ValidationConfiguration(validationImplementation = "blUriPropertyValidator") })
    protected String url;

    @Column(name = "OVERRIDE_GENERATED_URL")
    @AdminPresentation(friendlyName = "ProductImpl_Override_Generated_Url", group = Presentation.Group.Name.General,
            order = Presentation.FieldOrder.URL + 10)
    protected Boolean overrideGeneratedUrl = false;

    @Column(name = "URL_KEY")
    @AdminPresentation(friendlyName = "ProductImpl_Product_UrlKey",
        tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
        group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General,
        excluded = true)
    protected String urlKey;

    @Column(name = "DISPLAY_TEMPLATE")
    @AdminPresentation(friendlyName = "ProductImpl_Product_Display_Template",
        tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
        group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced)
    protected String displayTemplate;

    @Column(name = "MODEL")
    @AdminPresentation(friendlyName = "ProductImpl_Product_Model",
        tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
        group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced)
    protected String model;

    @Column(name = "MANUFACTURE")
    @AdminPresentation(friendlyName = "ProductImpl_Product_Manufacturer", order = Presentation.FieldOrder.MANUFACTURER,
        group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General,
        prominent = true, gridOrder = 4)
    protected String manufacturer;

    @Column(name = "IS_FEATURED_PRODUCT", nullable=false)
    @AdminPresentation(friendlyName = "ProductImpl_Is_Featured_Product", requiredOverride = RequiredOverride.NOT_REQUIRED,
        tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing,
        group = Presentation.Group.Name.Badges, groupOrder = Presentation.Group.Order.Badges)
    protected Boolean isFeaturedProduct = false;

    @OneToOne(targetEntity = SkuImpl.class, cascade={CascadeType.ALL})
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blProducts")
    @Cascade(value={org.hibernate.annotations.CascadeType.ALL})
    @JoinColumn(name = "DEFAULT_SKU_ID")
    @ClonePolicy(toOneProperty = "defaultProduct")
    protected Sku defaultSku;

    @Column(name = "CAN_SELL_WITHOUT_OPTIONS")
    @AdminPresentation(friendlyName = "ProductImpl_Can_Sell_Without_Options",
        tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
        group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced)
    protected Boolean canSellWithoutOptions = false;

    @Transient
    protected List<Sku> skus = new ArrayList<Sku>();

    @Transient
    protected String promoMessage;

    @OneToMany(mappedBy = "product", targetEntity = CrossSaleProductImpl.class, cascade = {CascadeType.ALL})
    @Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blProducts")
    @OrderBy(value="sequence")
    @AdminPresentationAdornedTargetCollection(friendlyName = "crossSaleProductsTitle", order = 1000,
        tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing,
        targetObjectProperty = "relatedSaleProduct",
        sortProperty = "sequence",
        maintainedAdornedTargetFields = { "promotionMessage" },
        gridVisibleFields = { "defaultSku.name", "promotionMessage" })
    protected List<RelatedProduct> crossSaleProducts = new ArrayList<RelatedProduct>();

    @OneToMany(mappedBy = "product", targetEntity = UpSaleProductImpl.class, cascade = {CascadeType.ALL})
    @Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blProducts")
    @OrderBy(value="sequence")
    @AdminPresentationAdornedTargetCollection(friendlyName = "upsaleProductsTitle", order = 2000,
        tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing,
        targetObjectProperty = "relatedSaleProduct",
        sortProperty = "sequence",
        maintainedAdornedTargetFields = { "promotionMessage" },
        gridVisibleFields = { "defaultSku.name", "promotionMessage" })
    protected List<RelatedProduct> upSaleProducts  = new ArrayList<RelatedProduct>();

    @OneToMany(fetch = FetchType.LAZY, targetEntity = SkuImpl.class, mappedBy = "product", cascade = CascadeType.ALL)
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blProducts")
    @BatchSize(size = 50)
    @AdminPresentationCollection(friendlyName = "ProductImpl_Additional_Skus", order = 1000,
        tab = Presentation.Tab.Name.ProductOptions, tabOrder = Presentation.Tab.Order.ProductOptions)
    protected List<Sku> additionalSkus = new ArrayList<Sku>();

    @ManyToOne(targetEntity = CategoryImpl.class)
    @JoinColumn(name = "DEFAULT_CATEGORY_ID")
    @Index(name="PRODUCT_CATEGORY_INDEX", columnNames={"DEFAULT_CATEGORY_ID"})
    @AdminPresentation(friendlyName = "ProductImpl_Product_Default_Category", order = Presentation.FieldOrder.DEFAULT_CATEGORY,
        group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General,
        prominent = true, gridOrder = 2,
        requiredOverride = RequiredOverride.REQUIRED)
    @AdminPresentationToOneLookup()
    @Deprecated
    protected Category defaultCategory;

    @OneToMany(targetEntity = CategoryProductXrefImpl.class, mappedBy = "product", orphanRemoval = true,
            cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @OrderBy(value="displayOrder")
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blProducts")
    @BatchSize(size = 50)
    @AdminPresentationAdornedTargetCollection(friendlyName = "allParentCategoriesTitle", order = 3000,
        tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing,
        targetObjectProperty = "category",
        parentObjectProperty = "product",
        gridVisibleFields = { "name" })
    protected List<CategoryProductXref> allParentCategoryXrefs = new ArrayList<CategoryProductXref>();

    @OneToMany(mappedBy = "product", targetEntity = ProductAttributeImpl.class, cascade = { CascadeType.ALL }, orphanRemoval = true)
    @Cache(usage=CacheConcurrencyStrategy.READ_WRITE, region="blProducts")
    @MapKey(name="name")
    @BatchSize(size = 50)
    @AdminPresentationMap(friendlyName = "productAttributesTitle",
        tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
        deleteEntityUponRemove = true, forceFreeFormKeys = true, keyPropertyFriendlyName = "ProductAttributeImpl_Attribute_Name"
    )
    protected Map<String, ProductAttribute> productAttributes = new HashMap<String, ProductAttribute>();

    @OneToMany(targetEntity = ProductOptionXrefImpl.class, mappedBy = "product",
            cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blProducts")
    @BatchSize(size = 50)
    @AdminPresentationAdornedTargetCollection(friendlyName = "productOptionsTitle",
        tab = Presentation.Tab.Name.ProductOptions, tabOrder = Presentation.Tab.Order.ProductOptions,
        joinEntityClass = "org.broadleafcommerce.core.catalog.domain.ProductOptionXrefImpl",
        targetObjectProperty = "productOption",
        parentObjectProperty = "product",
        gridVisibleFields = {"label", "required"})
    protected List<ProductOptionXref> productOptions = new ArrayList<ProductOptionXref>();

    @Transient
    protected Map<String, Set<String>> productOptionMap;

    @Embedded
    protected ArchiveStatus archiveStatus = new ArchiveStatus();

    @Override
    public Long getId() {
        return id;
    }

    @Override
    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public String getName() {
        return getDefaultSku().getName();
    }

    @Override
    public void setName(String name) {
        getDefaultSku().setName(name);
    }

    @Override
    public String getDescription() {
        return getDefaultSku().getDescription();
    }

    @Override
    public void setDescription(String description) {
        getDefaultSku().setDescription(description);
    }

    @Override
    public String getLongDescription() {
        return getDefaultSku().getLongDescription();
    }

    @Override
    public void setLongDescription(String longDescription) {
        getDefaultSku().setLongDescription(longDescription);
    }

    @Override
    public Date getActiveStartDate() {
        return  getDefaultSku().getActiveStartDate();
    }

    @Override
    public void setActiveStartDate(Date activeStartDate) {
        getDefaultSku().setActiveStartDate(activeStartDate);
    }

    @Override
    public Date getActiveEndDate() {
        return getDefaultSku().getActiveEndDate();
    }

    @Override
    public void setActiveEndDate(Date activeEndDate) {
        getDefaultSku().setActiveEndDate(activeEndDate);
    }

    @Override
    public boolean isActive() {
        if (LOG.isDebugEnabled()) {
            if (!DateUtil.isActive(getActiveStartDate(), getActiveEndDate(), true)) {
                LOG.debug("product, " + id + ", inactive due to date");
            }
            if ('Y'==getArchived()) {
                LOG.debug("product, " + id + ", inactive due to archived status");
            }
        }
        return DateUtil.isActive(getActiveStartDate(), getActiveEndDate(), true) && 'Y'!=getArchived();
    }

    @Override
    public String getModel() {
        return model;
    }

    @Override
    public void setModel(String model) {
        this.model = model;
    }

    @Override
    public String getManufacturer() {
        return manufacturer;
    }

    @Override
    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }

    @Override
    public boolean isFeaturedProduct() {
        return isFeaturedProduct;
    }

    @Override
    public void setFeaturedProduct(boolean isFeaturedProduct) {
        this.isFeaturedProduct = isFeaturedProduct;
    }

    @Override
    public Sku getDefaultSku() {
        return defaultSku;
    }

    @Override
    public Boolean getCanSellWithoutOptions() {
        return canSellWithoutOptions == null ? false : canSellWithoutOptions;
    }

    @Override
    public void setCanSellWithoutOptions(Boolean canSellWithoutOptions) {
        this.canSellWithoutOptions = canSellWithoutOptions;
    }

    @Override
    public void setDefaultSku(Sku defaultSku) {
        if (defaultSku != null) {
            defaultSku.setDefaultProduct(this);

        }
        this.defaultSku = defaultSku;
    }

    @Override
    public String getPromoMessage() {
        return promoMessage;
    }

    @Override
    public void setPromoMessage(String promoMessage) {
        this.promoMessage = promoMessage;
    }

    @Override
    public List<Sku> getAllSkus() {
        List<Sku> allSkus = new ArrayList<Sku>();
        allSkus.add(getDefaultSku());
        for (Sku additionalSku : additionalSkus) {
            if (!additionalSku.getId().equals(getDefaultSku().getId())) {
                allSkus.add(additionalSku);
            }
        }
        return Collections.unmodifiableList(allSkus);
    }

    @Override
    @Deprecated
    public List<Sku> getSkus() {
        if (skus.size() == 0) {
            List<Sku> additionalSkus = getAdditionalSkus();
            for (Sku sku : additionalSkus) {
                if (sku.isActive()) {
                    skus.add(sku);
                }
            }
        }
        return Collections.unmodifiableList(skus);
    }

    @Override
    public List<Sku> getAdditionalSkus() {
        return additionalSkus;
    }

    @Override
    @Deprecated
    public void setAdditionalSkus(List<Sku> skus) {
        this.additionalSkus.clear();
        for(Sku sku : skus){
            this.additionalSkus.add(sku);
        }
    }

    @Override
    @Deprecated
    public Category getDefaultCategory() {
        Category response;
        if (defaultCategory != null) {
            response = defaultCategory;
        } else {
            response = getCategory();
        }
        return response;
    }

    @Override
    @Deprecated
    public void setDefaultCategory(Category defaultCategory) {
        this.defaultCategory = defaultCategory;
    }

    @Override
    public Category getCategory() {
        Category response = null;
        List<CategoryProductXref> xrefs = getAllParentCategoryXrefs();
        if (!CollectionUtils.isEmpty(xrefs)) {
            for (CategoryProductXref xref : xrefs) {
                if (xref.getCategory().isActive() && xref.getDefaultReference() != null && xref.getDefaultReference()) {
                    response = xref.getCategory();
                    break;
                }
            }
        }
        if (response == null) {
            if (!CollectionUtils.isEmpty(xrefs)) {
                for (CategoryProductXref xref : xrefs) {
                   if (xref.getCategory().isActive()) {
                        response = xref.getCategory();
                        break;
                    }
                }
            }
        }
        return response;
    }

    @Override
    public void setCategory(Category category) {
        List<CategoryProductXref> xrefs = getAllParentCategoryXrefs();
        boolean found = false;
        for (CategoryProductXref xref : xrefs) {
            if (xref.getCategory().equals(category)) {
                xref.setDefaultReference(true);
                found = true;
            } else if (xref.getDefaultReference() != null && xref.getDefaultReference()) {
                xref.setDefaultReference(null);
            }
        }
        if (!found && category != null) {
            CategoryProductXref xref = new CategoryProductXrefImpl();
            xref.setProduct(this);
            xref.setCategory(category);
            xref.setDefaultReference(true);
            allParentCategoryXrefs.add(xref);
        }
    }

    @Override
    public Map<String, Media> getMedia() {
        return getDefaultSku().getSkuMedia();
    }

    @Override
    public void setMedia(Map<String, Media> media) {
        getDefaultSku().setSkuMedia(media);
    }

    @Override
    public Map<String, Media> getAllSkuMedia() {
        Map<String, Media> result = new HashMap<String, Media>();
        result.putAll(getMedia());
        for (Sku additionalSku : getAdditionalSkus()) {
            if (!additionalSku.getId().equals(getDefaultSku().getId())) {
                result.putAll(additionalSku.getSkuMedia());
            }
        }
        return result;
    }

    @Override
    public List<CategoryProductXref> getAllParentCategoryXrefs() {
        return allParentCategoryXrefs;
    }

    @Override
    public void setAllParentCategoryXrefs(List<CategoryProductXref> allParentCategories) {
        this.allParentCategoryXrefs.clear();
        allParentCategoryXrefs.addAll(allParentCategories);
    }

    @Override
    @Deprecated
    public List<Category> getAllParentCategories() {
        List<Category> parents = new ArrayList<Category>();
        for (CategoryProductXref xref : allParentCategoryXrefs) {
            parents.add(xref.getCategory());
        }
        return Collections.unmodifiableList(parents);
    }

    @Override
    @Deprecated
    public void setAllParentCategories(List<Category> allParentCategories) {
        throw new UnsupportedOperationException("Not Supported - Use setAllParentCategoryXrefs()");
    }

    @Override
    public Dimension getDimension() {
        return getDefaultSku().getDimension();
    }

    @Override
    public void setDimension(Dimension dimension) {
        getDefaultSku().setDimension(dimension);
    }

    @Override
    public BigDecimal getWidth() {
        return getDefaultSku().getDimension().getWidth();
    }

    @Override
    public void setWidth(BigDecimal width) {
        getDefaultSku().getDimension().setWidth(width);
    }

    @Override
    public BigDecimal getHeight() {
        return getDefaultSku().getDimension().getHeight();
    }

    @Override
    public void setHeight(BigDecimal height) {
        getDefaultSku().getDimension().setHeight(height);
    }

    @Override
    public BigDecimal getDepth() {
        return getDefaultSku().getDimension().getDepth();
    }

    @Override
    public void setDepth(BigDecimal depth) {
        getDefaultSku().getDimension().setDepth(depth);
    }

    @Override
    public BigDecimal getGirth() {
        return getDefaultSku().getDimension().getGirth();
    }

    @Override
    public void setGirth(BigDecimal girth) {
        getDefaultSku().getDimension().setGirth(girth);
    }

    @Override
    public ContainerSizeType getSize() {
        return getDefaultSku().getDimension().getSize();
    }

    @Override
    public void setSize(ContainerSizeType size) {
        getDefaultSku().getDimension().setSize(size);
    }

    @Override
    public ContainerShapeType getContainer() {
        return getDefaultSku().getDimension().getContainer();
    }

    @Override
    public void setContainer(ContainerShapeType container) {
        getDefaultSku().getDimension().setContainer(container);
    }

    @Override
    public String getDimensionString() {
        return getDefaultSku().getDimension().getDimensionString();
    }

    @Override
    public Weight getWeight() {
        return getDefaultSku().getWeight();
    }

    @Override
    public void setWeight(Weight weight) {
        getDefaultSku().setWeight(weight);
    }

    @Override
    public List<RelatedProduct> getCrossSaleProducts() {
        return crossSaleProducts;
    }

    @Override
    public void setCrossSaleProducts(List<RelatedProduct> crossSaleProducts) {
        this.crossSaleProducts.clear();
        for(RelatedProduct relatedProduct : crossSaleProducts){
            this.crossSaleProducts.add(relatedProduct);
        }
    }

    @Override
    public List<RelatedProduct> getUpSaleProducts() {
        return upSaleProducts;
    }

    @Override
    public void setUpSaleProducts(List<RelatedProduct> upSaleProducts) {
        this.upSaleProducts.clear();
        for(RelatedProduct relatedProduct : upSaleProducts){
            this.upSaleProducts.add(relatedProduct);
        }
        this.upSaleProducts = upSaleProducts;
    }

    @Override
    public List<RelatedProduct> getCumulativeCrossSaleProducts() {
        List<RelatedProduct> returnProducts = getCrossSaleProducts();
        if (defaultCategory != null) {
            List<RelatedProduct> categoryProducts = defaultCategory.getCumulativeCrossSaleProducts();
            if (categoryProducts != null) {
                returnProducts.addAll(categoryProducts);
            }
        }
        Iterator<RelatedProduct> itr = returnProducts.iterator();
        while(itr.hasNext()) {
            RelatedProduct relatedProduct = itr.next();
            if (relatedProduct.getRelatedProduct().equals(this)) {
                itr.remove();
            }
        }
        return returnProducts;
    }

    @Override
    public List<RelatedProduct> getCumulativeUpSaleProducts() {
        List<RelatedProduct> returnProducts = getUpSaleProducts();
        if (defaultCategory != null) {
            List<RelatedProduct> categoryProducts = defaultCategory.getCumulativeUpSaleProducts();
            if (categoryProducts != null) {
                returnProducts.addAll(categoryProducts);
            }
        }
        Iterator<RelatedProduct> itr = returnProducts.iterator();
        while(itr.hasNext()) {
            RelatedProduct relatedProduct = itr.next();
            if (relatedProduct.getRelatedProduct().equals(this)) {
                itr.remove();
            }
        }
        return returnProducts;
    }

    @Override
    public Map<String, ProductAttribute> getProductAttributes() {
        return productAttributes;
    }

    @Override
    public void setProductAttributes(Map<String, ProductAttribute> productAttributes) {
        this.productAttributes = productAttributes;
    }

    @Override
    public List<ProductOptionXref> getProductOptionXrefs() {
        List<ProductOptionXref> sorted = new ArrayList<ProductOptionXref>(productOptions);
        Collections.sort(sorted, new Comparator<ProductOptionXref>() {

            @Override
            public int compare(ProductOptionXref o1, ProductOptionXref o2) {
                return ObjectUtils.compare(o1.getProductOption().getDisplayOrder(), o2.getProductOption().getDisplayOrder(), true);
            }

        });
        return sorted;
    }

    @Override
    public void setProductOptionXrefs(List<ProductOptionXref> productOptions) {
        this.productOptions = productOptions;
    }

    @Override
    public List<ProductOption> getProductOptions() {
        List<ProductOption> response = new ArrayList<ProductOption>();
        for (ProductOptionXref xref : getProductOptionXrefs()) {
            response.add(xref.getProductOption());
        }
        return Collections.unmodifiableList(response);
    }

    @Override
    public void setProductOptions(List<ProductOption> productOptions) {
        throw new UnsupportedOperationException("Use setProductOptionXrefs(..) instead");
    }

    @Override
    public String getUrl() {
        if (url == null) {
            return getGeneratedUrl();
        } else {
            return url;
        }
    }

    @Override
    public Boolean getOverrideGeneratedUrl() {
        return overrideGeneratedUrl == null ? false : overrideGeneratedUrl;
    }

    @Override
    public void setOverrideGeneratedUrl(Boolean overrideGeneratedUrl) {
        this.overrideGeneratedUrl = overrideGeneratedUrl == null ? false : overrideGeneratedUrl;
    }

    @Override
    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    public String getDisplayTemplate() {
        return displayTemplate;
    }

    @Override
    public void setDisplayTemplate(String displayTemplate) {
        this.displayTemplate = displayTemplate;
    }

    @Override
    public Character getArchived() {
       ArchiveStatus temp;
       if (archiveStatus == null) {
           temp = new ArchiveStatus();
       } else {
           temp = archiveStatus;
       }
       return temp.getArchived();
    }

    @Override
    public void setArchived(Character archived) {
        if (archiveStatus == null) {
            archiveStatus = new ArchiveStatus();
        }
        archiveStatus.setArchived(archived);
    }

    @Override
    public Map<String, Set<String>> getProductOptionValuesMap() {
        if (productOptionMap == null) {
            productOptionMap = new HashMap<String, Set<String>>();
            List<ProductOptionXref> xrefs = getProductOptionXrefs();
            if (xrefs != null) {
                for (ProductOptionXref xref : xrefs) {
                    List<ProductOptionValue> productOptionValues = xref.getProductOption().getAllowedValues();
                    if (productOptionValues != null && !productOptionValues.isEmpty()) {
                        HashSet<String> values = new HashSet<String>();
                        for (ProductOptionValue value : productOptionValues) {
                            values.add(value.getAttributeValue());
                        }
                        productOptionMap.put(xref.getProductOption().getAttributeName(), values);
                    }
                }
            }
        }

        return productOptionMap;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((skus == null) ? 0 : skus.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!getClass().isAssignableFrom(obj.getClass()))
            return false;
        ProductImpl other = (ProductImpl) obj;

        if (id != null && other.id != null) {
            return id.equals(other.id);
        }

        if (skus == null) {
            if (other.skus != null)
                return false;
        } else if (!skus.equals(other.skus))
            return false;
        return true;
    }

    @Override
    public String getUrlKey() {
        if (urlKey != null) {
            return urlKey;
        } else {
            if (getName() != null) {
                String returnKey = getName().toLowerCase();

                returnKey = returnKey.replaceAll(" ","-");
                return returnKey.replaceAll("[^A-Za-z0-9/-]", "");
            }
        }
        return null;
    }

    @Override
    public void setUrlKey(String urlKey) {
        this.urlKey = urlKey;
    }

    @Override
    public String getGeneratedUrl() {
        if (getDefaultCategory() != null && getDefaultCategory().getGeneratedUrl() != null) {
            String generatedUrl = getDefaultCategory().getGeneratedUrl();
            if (generatedUrl.endsWith("//")) {
                return generatedUrl + getUrlKey();
            } else {
                return generatedUrl + "//" + getUrlKey();
            }
        }
        return null;
    }

    @Override
    public void clearDynamicPrices() {
        for (Sku sku : getAllSkus()) {
            sku.clearDynamicPrices();
        }
    }

    @Override
    public String getMainEntityName() {
        return getName();
    }

    @Override
    public <G extends Product> CreateResponse<G> createOrRetrieveCopyInstance(MultiTenantCopyContext context) throws CloneNotSupportedException {
        CreateResponse<G> createResponse = context.createOrRetrieveCopyInstance(this);
        if (createResponse.isAlreadyPopulated()) {
            return createResponse;
        }
        Product cloned = createResponse.getClone();
        cloned.setCanSellWithoutOptions(canSellWithoutOptions);
        cloned.setFeaturedProduct(isFeaturedProduct);
        cloned.setUrl(url);
        cloned.setUrlKey(urlKey);
        cloned.setManufacturer(manufacturer);
        cloned.setPromoMessage(promoMessage);
        if (defaultCategory != null) {
            cloned.setDefaultCategory(defaultCategory.createOrRetrieveCopyInstance(context).getClone());
        }
        cloned.setModel(model);
        if (defaultSku != null) {
            cloned.setDefaultSku(defaultSku.createOrRetrieveCopyInstance(context).getClone());
        }
        for(Sku entry : additionalSkus){
            Sku clonedEntry = entry.createOrRetrieveCopyInstance(context).getClone();
            cloned.getAdditionalSkus().add(clonedEntry);
        }
        for(ProductOptionXref entry : productOptions){
            ProductOptionXref clonedEntry = entry.createOrRetrieveCopyInstance(context).getClone();
            cloned.getProductOptionXrefs().add(clonedEntry);

        }
        for(Map.Entry<String, ProductAttribute> entry : productAttributes.entrySet()){
            ProductAttribute clonedEntry = entry.getValue().createOrRetrieveCopyInstance(context).getClone();
            cloned.getProductAttributes().put(entry.getKey(),clonedEntry);
        }

        //Don't clone references to other Product and Category collections - those will be handled by another MultiTenantCopier call

        return createResponse;
    }

    public static class Presentation {
        public static class Tab {
            public static class Name {
                public static final String Marketing = "ProductImpl_Marketing_Tab";
                public static final String Media = "SkuImpl_Media_Tab";
                public static final String ProductOptions = "ProductImpl_Product_Options_Tab";
                public static final String Inventory = "ProductImpl_Inventory_Tab";
                public static final String Shipping = "ProductImpl_Shipping_Tab";
                public static final String Advanced = "ProductImpl_Advanced_Tab";

            }

            public static class Order {
                public static final int Marketing = 2000;
                public static final int Media = 3000;
                public static final int ProductOptions = 4000;
                public static final int Inventory = 5000;
                public static final int Shipping = 6000;
                public static final int Advanced = 7000;
            }
        }

        public static class Group {
            public static class Name {
                public static final String General = "ProductImpl_Product_Description";
                public static final String Price = "SkuImpl_Price";
                public static final String ActiveDateRange = "ProductImpl_Product_Active_Date_Range";
                public static final String Advanced = "ProductImpl_Advanced";
                public static final String Inventory = "SkuImpl_Sku_Inventory";
                public static final String Badges = "ProductImpl_Badges";
                public static final String Shipping = "ProductWeight_Shipping";
                public static final String Financial = "ProductImpl_Financial";
            }

            public static class Order {
                public static final int General = 1000;
                public static final int Price = 2000;
                public static final int ActiveDateRange = 3000;
                public static final int Advanced = 1000;
                public static final int Inventory = 1000;
                public static final int Badges = 1000;
                public static final int Shipping = 1000;
            }

        }

        public static class FieldOrder {

            public static final int NAME = 1000;
            public static final int SHORT_DESCRIPTION = 2000;
            public static final int PRIMARY_MEDIA = 3000;
            public static final int LONG_DESCRIPTION = 4000;
            public static final int DEFAULT_CATEGORY = 5000;
            public static final int MANUFACTURER = 6000;
            public static final int URL = 7000;
        }
    }

    @Override
    public String getTaxCode() {
        return getDefaultSku().getTaxCode();
    }

    @Override
    public void setTaxCode(String taxCode) {
        getDefaultSku().setTaxCode(taxCode);
    }

    @Override
    public String getLocation() {
        return getUrl();
    }

}


text:
set -o errexit
set -o nounset
set -o pipefail

source $(dirname $0)/../vendor/knative.dev/test-infra/scripts/library.sh

CODEGEN_PKG=${CODEGEN_PKG:-$(cd ${REPO_ROOT_DIR}; ls -d -1 $(dirname $0)/../vendor/k8s.io/code-generator 2>/dev/null || echo ../code-generator)}
KNATIVE_CODEGEN_PKG=${KNATIVE_CODEGEN_PKG:-$(cd ${REPO_ROOT_DIR}; ls -d -1 $(dirname $0)/../vendor/knative.dev/pkg 2>/dev/null || echo ../pkg)}

GENCLIENT_PKG=knative.dev/pkg/test/genclient

echo "Pre-deleting $(dirname $0)/genclient"
rm -rf $(dirname $0)/genclient

header "Test Generated Reconciler Builds."

${CODEGEN_PKG}/generate-groups.sh "deepcopy,client,informer,lister" \
  ${GENCLIENT_PKG} knative.dev/pkg/apis/test \
  "example:v1alpha1" \
  --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt

# Knative Injection
${KNATIVE_CODEGEN_PKG}/hack/generate-knative.sh "injection" \
  ${GENCLIENT_PKG} knative.dev/pkg/apis/test \
  "example:v1alpha1" \
  --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt \
  --force-genreconciler-kinds "Foo"

${CODEGEN_PKG}/generate-groups.sh "deepcopy,client,informer,lister" \
  ${GENCLIENT_PKG}/pub knative.dev/pkg/apis/test \
  "pub:v1alpha1" \
  --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt

# Knative Injection
${KNATIVE_CODEGEN_PKG}/hack/generate-knative.sh "injection" \
  ${GENCLIENT_PKG}/pub knative.dev/pkg/apis/test \
  "pub:v1alpha1" \
  --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt

if ! go build -v $(dirname $0)/genclient/... ; then
    exit 1
fi

echo "Finished, deleting $(dirname $0)/genclient"
rm -rf $(dirname $0)/genclient


text:
package org.apache.lens.cli.commands;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.lens.api.APIResult;
import org.apache.lens.api.metastore.XDimension;
import org.apache.lens.cli.commands.annotations.UserDocumentation;

import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.stereotype.Component;

import lombok.NonNull;

/**
 * The Class LensDimensionCommands.
 */
@Component
@UserDocumentation(title = "Dimension Management", description = "These commands provide CRUD for Dimensions")
public class LensDimensionCommands extends ConceptualTableCrudCommand<XDimension> {

  /**
   * Show dimensions.
   *
   * @return the string
   */
  @CliCommand(value = "show dimensions", help = "show list of all dimensions in current database")
  public String showDimensions() {
    return showAll();
  }

  /**
   * Creates the dimension.
   *
   * @param path the dimension spec
   * @return the string
   */
  @CliCommand(value = "create dimension",
    help = "Create a new Dimension, taking spec from <path-to-dimension-spec file>")
  public String createDimension(
    @CliOption(key = {"", "path"}, mandatory = true, help =
      "<path-to-dimension-spec file>") @NonNull final File path) {
    return create(path, false);
  }

  /**
   * Describe dimension.
   *
   * @param name the dimension name
   * @return the string
   */
  @CliCommand(value = "describe dimension", help = "describe dimension <dimension_name>")
  public String describeDimension(
    @CliOption(key = {"", "name"}, mandatory = true, help = "<dimension_name>") String name) {
    try {
      return formatJson(mapper.writer(pp).writeValueAsString(getClient().getDimension(name)));
    } catch (IOException e) {
      throw new IllegalArgumentException(e);
    }
  }

  /**
   * Update dimension.
   *
   * @param name the dimension to be updated
   * @param path  path to spec fild
   * @return the string
   */
  @CliCommand(value = "update dimension",
    help = "update dimension <dimension_name>, taking spec from <path-to-dimension-spec file>")
  public String updateDimension(
    @CliOption(key = {"", "name"}, mandatory = true, help = "<dimension_name>") String name,
    @CliOption(key = {"", "path"}, mandatory = true, help = "<path-to-dimension-spec-file>") @NonNull final File path) {
    return update(name, path);
  }

  /**
   * Drop dimension.
   *
   * @param name the dimension
   * @return the string
   */
  @CliCommand(value = "drop dimension", help = "drop dimension <dimension_name>")
  public String dropDimension(
    @CliOption(key = {"", "name"}, mandatory = true, help = "<dimension_name>") String name) {
    return drop(name, false);
  }

  @CliCommand(value = "dimension show fields",
    help = "Show queryable fields of the given dimension <dimension_name>. "
      + "Optionally specify <flattened> to include chained fields")
  public String showQueryableFields(
    @CliOption(key = {"", "name"}, mandatory = true, help = "<dimension_name>") String table,
    @CliOption(key = {"flattened"}, mandatory = false, unspecifiedDefaultValue = "false",
      specifiedDefaultValue = "true", help = "<flattened>") boolean flattened) {
    return getAllFields(table, flattened);
  }

  @CliCommand(value = "dimension show joinchains",
    help = "Show joinchains of the given dimension <dimension_name>. ")
  public String showJoinChains(
    @CliOption(key = {"", "name"}, mandatory = true, help = "<dimension_name>") String table) {
    return getAllJoinChains(table);
  }

  @Override
  public List<String> getAll() {
    return getClient().getAllDimensions();
  }

  @Override
  protected APIResult doCreate(String path, boolean ignoreIfExists) {
    return getClient().createDimension(path);
  }

  @Override
  protected XDimension doRead(String name) {
    return getClient().getDimension(name);
  }

  @Override
  public APIResult doUpdate(String name, String path) {
    return getClient().updateDimension(name, path);
  }

  @Override
  protected APIResult doDelete(String name, boolean cascade) {
    return getClient().dropDimension(name);
  }
}


text:
importScripts('utils.js');
importScripts('solver.js');

onmessage = OnCreatorMessage;

// default all to true
var subscribedEvents = {
    onTileCheckedCountChanged: true,
    onTilePlaced: true,
    onTileRemoved: true,
    onSolutionFound: true
};

var tileCheckedCount = 0;

function postTileCheckedCountChangedMessage() {
    if (!subscribedEvents.onTileCheckedCountChanged) return;
    postMessage({ event: 'onTileCheckedCountChanged', amount: tileCheckedCount });
}

function onTileChecked() {
    tileCheckedCount++;
    // only send in incrememnts to improve performance;
    // send 987 cos it makes the counter look more exciting than 1000
    if (tileCheckedCount == 987) {
        postTileCheckedCountChangedMessage();
        tileCheckedCount = 0;
    }
}

function onTilePlaced(position, tile) {
    if (!subscribedEvents.onTilePlaced) return;
    postMessage({ event: 'onTilePlaced', position: position, tile: tile.toMessage() });
}

function onTileRemoved(position) {
    if (!subscribedEvents.onTileRemoved) return;
    postMessage({ event: 'onTileRemoved', position: position });
}

function onSolutionFound(tiles) {
    if (tileCheckedCount > 0) {
        postTileCheckedCountChangedMessage();
    }
    if (!subscribedEvents.onSolutionFound) return;
    postMessage({ event: 'onSolutionFound', tiles: tiles.map(function(t) { return t.toMessage(); }) });
}

function OnCreatorMessage(evt) {
    if (evt.data.subscribedEvents) {
        for (var e in subscribedEvents) {
            subscribedEvents[e] = (evt.data.subscribedEvents.indexOf(e) >= 0);
        }
    }
    var solver = new Solver(evt.data.tiles, onTileChecked, onTilePlaced, onTileRemoved);
    var solution = solver.solve();
    onSolutionFound(solution);
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: minhao
 * Date: 2016-04-19
 * Time: 12:26
 */
use Doctrine\ORM\Tools\Console\ConsoleRunner;
use Oasis\DynamodbExporter\EntityManagerProvider;

require_once __DIR__ . "/../bootstrap.php";

return ConsoleRunner::createHelperSet(EntityManagerProvider::getEntityManager());


text:
namespace http
{
template<typename Thread>
class JoinableThread
{
public:
	JoinableThread() = default;
	JoinableThread(const JoinableThread&) = default;
	JoinableThread& operator=(const JoinableThread&) = default;

	template<typename T>
	JoinableThread(T&& f)
		: m_thread(std::forward<T>(f))
	{
	}

	JoinableThread(JoinableThread&& x)
		: m_thread(std::move(x.m_thread))
	{
	}

	JoinableThread& operator=(JoinableThread&& x)
	{
		return *this = std::move(x.m_thread);
	}

	JoinableThread& operator=(Thread&& thread)
	{
		if (&m_thread != &thread)
		{
			JoinIfJoinable();
			m_thread = std::move(thread);
		}
		return *this;
	}

	~JoinableThread()
	{
		JoinIfJoinable();
	}

	bool joinable() const
	{
		return m_thread.joinable();
	}

	void join()
	{
		m_thread.join();
	}

	void JoinIfJoinable()
	{
		if (m_thread.joinable())
		{
			m_thread.join();
		}
	}

private:
	Thread m_thread;
};
}


text:
package cn.imrhj.pushmsg.DataLoader;

import android.util.Log;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;

import java.util.ArrayList;
import java.util.List;

import cn.imrhj.pushmsg.Utils.ListData;

/**
 * Created by rhj on 16/3/17.
 */
public class NetDataCache implements DataCache {
    private static final String TAG = "NetDataCache";
    private List<ListData> mDatas = null;
    private boolean flag = false;

    @Override
    public List<ListData> get() {
        if (mDatas == null) {
            getAVObject();
        }
        while (!flag);
        return mDatas;
    }

    private void getAVObject() {
        AVQuery<AVObject> query = new AVQuery<>("Post");
//        query.whereEqualTo("pubUser", AVUser.getCurrentUser().getUsername());
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (e == null) {
                    Log.d(TAG, "done: find ok");
                    for (AVObject object : list) {
                        mDatas.add(ListData.get(object));
                    }
                } else {
                    Log.e(TAG, "done: " + e.toString());
                }
                flag = true;
            }
        });

//        try {
//            List<AVObject> list = query.find();
//            for (AVObject object : list) {
//                mDatas.add(ListData.get(object));
//            }
//        } catch (AVException e) {
//            e.printStackTrace();
//        }
    }

    @Override
    public void put(List<ListData> datas) {

    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <ListView android:id="@+id/ListView"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:stackFromBottom="true"
        android:transcriptMode="alwaysScroll"
        android:layout_weight="1.0"
        />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/NameEditText"
            android:layout_width="115dp"
            android:layout_height="52dp"
            android:ems="10"
            android:hint="@string/Name" />

        <EditText
            android:id="@+id/MessageEditText"
            android:layout_width="wrap_content"
            android:layout_height="52dp"
            android:ems="10"
            android:hint="@string/enterMessageHint" />
    </LinearLayout>
</LinearLayout>


text:
require "rubygems"
require "sitemap_generator"

SitemapGenerator.verbose = false
SitemapGenerator::Sitemap.default_host = "https://sleepinnovate.org"
SitemapGenerator::Sitemap.sitemaps_host = ENV["website_url"]
SitemapGenerator::Sitemap.public_path = "carrierwave/sitemaps/"
SitemapGenerator::Sitemap.sitemaps_path = ""
SitemapGenerator::Sitemap.create do
  add "/landing", changefreq: "weekly", priority: 0.5
end


text:
#include <aws/lakeformation/model/GetDataLakeSettingsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

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

GetDataLakeSettingsRequest::GetDataLakeSettingsRequest() :
    m_catalogIdHasBeenSet(false)
{
}

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

  if(m_catalogIdHasBeenSet)
  {
   payload.WithString("CatalogId", m_catalogId);

  }

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


text:
var gulp = require('gulp');
var del = require('del');
var gulpSass = require('gulp-sass');
var gulpAutoprefixer = require('gulp-autoprefixer');
var gulpRename = require('gulp-rename');
var gulpSourceMaps = require('gulp-sourcemaps');

var sep = require('path').sep;

var src = [__dirname, 'src'].join(sep);
var srcPartials = [src, 'partials'].join(sep);
var srcScss = [src, 'scss'].join(sep);

var dist = [__dirname, 'dist'].join(sep);

gulp.task('del', function () {
    'use strict';
    del.sync([srcPartials, '*'].join(sep));
    del.sync([dist, '*'].join(sep));
});

gulp.task('partials', function () {
    'use strict';
    return gulp.src([srcScss, '*'].join(sep), { base: process.cwd() })
        .pipe(gulpRename({
            dirname: ['partials'].join(sep),
            prefix: '_'
        }))
        .pipe(gulp.dest(src));
});

gulp.task('sass', ['partials'], function () {
    'use strict';
    gulp.src([srcScss + '/*.scss', '!' + srcScss + '/idd-responsive*'])
        .pipe(gulpSass().on('error', gulpSass.logError))
        .pipe(gulpAutoprefixer({
            browsers: ['last 2 versions']
        }))
        .pipe(gulp.dest(dist + '/css'));
    gulp.src([srcScss + '/*.scss', '!' + srcScss + '/idd-responsive*'])
        .pipe(gulpSourceMaps.init())
        .pipe(gulpSass({outputStyle: 'compressed'}).on('error', gulpSass.logError))
        .pipe(gulpAutoprefixer({
            browsers: ['last 2 versions']
        }))
        .pipe(gulpRename(function (path) {
            path.extname = '.min.css';
        }))
        .pipe(gulpSourceMaps.write('.'))
        .pipe(gulp.dest(dist + '/css'));
});

gulp.task('default', ['del', 'partials', 'sass']);


text:
Plugin
========

Simple Laravel Plugin system


text:
package org.elasticsearch.discovery;

import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.coordination.JoinHelper;
import org.elasticsearch.cluster.coordination.PublicationTransportHandler;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.disruption.NetworkDisruption;
import org.elasticsearch.test.disruption.ServiceDisruptionScheme;
import org.elasticsearch.test.disruption.SlowClusterStateProcessing;
import org.elasticsearch.test.transport.MockTransportService;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.transport.TransportService;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;

import static org.elasticsearch.cluster.metadata.IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING;
import static org.elasticsearch.cluster.metadata.IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING;

/**
 * Tests for discovery during disruptions.
 */
@ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.TEST, numDataNodes = 0)
public class DiscoveryDisruptionIT extends AbstractDisruptionTestCase {

    /**
     * Test cluster join with issues in cluster state publishing *
     */
    public void testClusterJoinDespiteOfPublishingIssues() throws Exception {
        String masterNode = internalCluster().startMasterOnlyNode();
        String nonMasterNode = internalCluster().startDataOnlyNode();

        DiscoveryNodes discoveryNodes = internalCluster().getInstance(ClusterService.class, nonMasterNode).state().nodes();

        TransportService masterTranspotService =
                internalCluster().getInstance(TransportService.class, discoveryNodes.getMasterNode().getName());

        logger.info("blocking requests from non master [{}] to master [{}]", nonMasterNode, masterNode);
        MockTransportService nonMasterTransportService = (MockTransportService) internalCluster().getInstance(TransportService.class,
                nonMasterNode);
        nonMasterTransportService.addFailToSendNoConnectRule(masterTranspotService);

        assertNoMaster(nonMasterNode);

        logger.info("blocking cluster state publishing from master [{}] to non master [{}]", masterNode, nonMasterNode);
        MockTransportService masterTransportService =
                (MockTransportService) internalCluster().getInstance(TransportService.class, masterNode);
        TransportService localTransportService =
                internalCluster().getInstance(TransportService.class, discoveryNodes.getLocalNode().getName());
        if (randomBoolean()) {
            masterTransportService.addFailToSendNoConnectRule(localTransportService, PublicationTransportHandler.PUBLISH_STATE_ACTION_NAME);
        } else {
            masterTransportService.addFailToSendNoConnectRule(localTransportService, PublicationTransportHandler.COMMIT_STATE_ACTION_NAME);
        }

        logger.info("allowing requests from non master [{}] to master [{}], waiting for two join request", nonMasterNode, masterNode);
        final CountDownLatch countDownLatch = new CountDownLatch(2);
        nonMasterTransportService.addSendBehavior(masterTransportService, (connection, requestId, action, request, options) -> {
            if (action.equals(JoinHelper.JOIN_ACTION_NAME)) {
                countDownLatch.countDown();
            }
            connection.sendRequest(requestId, action, request, options);
        });

        nonMasterTransportService.addConnectBehavior(masterTransportService, Transport::openConnection);

        countDownLatch.await();

        logger.info("waiting for cluster to reform");
        masterTransportService.clearOutboundRules(localTransportService);
        nonMasterTransportService.clearOutboundRules(localTransportService);

        ensureStableCluster(2);

        // shutting down the nodes, to avoid the leakage check tripping
        // on the states associated with the commit requests we may have dropped
        internalCluster().stopRandomNonMasterNode();
    }

    public void testClusterFormingWithASlowNode() {

        SlowClusterStateProcessing disruption = new SlowClusterStateProcessing(random(), 0, 0, 1000, 2000);

        // don't wait for initial state, we want to add the disruption while the cluster is forming
        internalCluster().startNodes(3);

        logger.info("applying disruption while cluster is forming ...");

        internalCluster().setDisruptionScheme(disruption);
        disruption.startDisrupting();

        ensureStableCluster(3);
    }

    public void testElectMasterWithLatestVersion() throws Exception {
        final Set<String> nodes = new HashSet<>(internalCluster().startNodes(3));
        ensureStableCluster(3);
        ServiceDisruptionScheme isolateAllNodes =
                new NetworkDisruption(new NetworkDisruption.IsolateAllNodes(nodes), NetworkDisruption.DISCONNECT);
        internalCluster().setDisruptionScheme(isolateAllNodes);

        logger.info("--> forcing a complete election to make sure \"preferred\" master is elected");
        isolateAllNodes.startDisrupting();
        for (String node : nodes) {
            assertNoMaster(node);
        }
        internalCluster().clearDisruptionScheme();
        ensureStableCluster(3);
        final String preferredMasterName = internalCluster().getMasterName();
        final DiscoveryNode preferredMaster = internalCluster().clusterService(preferredMasterName).localNode();
        logger.info("--> preferred master is {}", preferredMaster);
        final Set<String> nonPreferredNodes = new HashSet<>(nodes);
        nonPreferredNodes.remove(preferredMasterName);
        final ServiceDisruptionScheme isolatePreferredMaster = isolateMasterDisruption(NetworkDisruption.DISCONNECT);
        internalCluster().setDisruptionScheme(isolatePreferredMaster);
        isolatePreferredMaster.startDisrupting();

        client(randomFrom(nonPreferredNodes)).admin().indices().prepareCreate("test").setSettings(
            Settings.builder().put(INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 1).put(INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), 0)).get();

        internalCluster().clearDisruptionScheme(false);
        internalCluster().setDisruptionScheme(isolateAllNodes);

        logger.info("--> forcing a complete election again");
        isolateAllNodes.startDisrupting();
        for (String node : nodes) {
            assertNoMaster(node);
        }

        isolateAllNodes.stopDisrupting();

        final ClusterState state = client().admin().cluster().prepareState().get().getState();
        if (state.metadata().hasIndex("test") == false) {
            fail("index 'test' was lost. current cluster state: " + state);
        }

    }

    /**
     * Adds an asymmetric break between a master and one of the nodes and makes
     * sure that the node is removed form the cluster, that the node start pinging and that
     * the cluster reforms when healed.
     */
    public void testNodeNotReachableFromMaster() throws Exception {
        startCluster(3);

        String masterNode = internalCluster().getMasterName();
        String nonMasterNode = null;
        while (nonMasterNode == null) {
            nonMasterNode = randomFrom(internalCluster().getNodeNames());
            if (nonMasterNode.equals(masterNode)) {
                nonMasterNode = null;
            }
        }

        logger.info("blocking request from master [{}] to [{}]", masterNode, nonMasterNode);
        MockTransportService masterTransportService = (MockTransportService) internalCluster().getInstance(TransportService.class,
                masterNode);
        if (randomBoolean()) {
            masterTransportService.addUnresponsiveRule(internalCluster().getInstance(TransportService.class, nonMasterNode));
        } else {
            masterTransportService.addFailToSendNoConnectRule(internalCluster().getInstance(TransportService.class, nonMasterNode));
        }

        logger.info("waiting for [{}] to be removed from cluster", nonMasterNode);
        ensureStableCluster(2, masterNode);

        logger.info("waiting for [{}] to have no master", nonMasterNode);
        assertNoMaster(nonMasterNode);

        logger.info("healing partition and checking cluster reforms");
        masterTransportService.clearAllRules();

        ensureStableCluster(3);
    }

}


text:
function doIT() {
  var init = document.getElementById('start').value.split('/');
  var end = document.getElementById('finish').value.split('/');

  init = init[2] + '-' + init[1] + '-' + init[0];
  end = end[2] + '-' + end[1] + '-' + end[0];

  window.open("http://localhost:5000/table?initial="+init+"&final="+end);
}