text:
namespace mongocxx {
MONGOCXX_INLINE_NAMESPACE_BEGIN

class client_session;

///
/// Class representing a client connection to MongoDB.
///
/// Acts as a logical gateway for working with databases contained within a MongoDB server.
///
/// Databases that are created via this client inherit the @c read_concern, @c read_preference, and
/// @c write_concern settings of this client when they are created. The lifetimes of objects created
/// via a client object (databases, collections, cursors, etc...) @b must be a subset of the
/// lifetime of the client that created them.
///
/// Example:
/// @code
///   mongocxx::client mongo_client{mongocxx::uri{}};
///   mongocxx::client mongo_client{mongocxx::uri{"mongodb://localhost:27017"}};
/// @endcode
///
/// Note that client is not thread-safe. See
/// https://mongodb.github.io/mongo-cxx-driver/mongocxx-v3/thread-safety/ for more details.
class MONGOCXX_API client {
   public:
    ///
    /// Default constructs a new client. The client is not connected and is equivalent to the
    /// state of a moved-from client. The only valid actions to take with a default constructed
    /// 'client' are to assign to it, or destroy it.
    ///
    client() noexcept;

    ///
    /// Creates a new client connection to MongoDB.
    ///
    /// @param mongodb_uri
    ///   A MongoDB URI representing the connection parameters
    /// @param options
    ///   Additional options that cannot be specified via the mongodb_uri
    ///
    /// @throws mongocxx::exception if invalid options are provided
    /// (whether from the URI or provided client options).
    ///
    client(const class uri& mongodb_uri, const options::client& options = options::client());

    ///
    /// Move constructs a client.
    ///
    client(client&&) noexcept;

    ///
    /// Move assigns a client.
    ///
    client& operator=(client&&) noexcept;

    ///
    /// Destroys a client.
    ///
    ~client();

    ///
    /// Returns true if the client is valid, meaning it was not default constructed
    /// or moved from.
    ///
    explicit operator bool() const noexcept;

    ///
    /// Sets the read concern for this client.
    ///
    /// Modifications at this level do not affect existing database instances that have been
    /// created by this client but do affect new ones as databases inherit the @c read_concern
    /// settings of their parent upon instantiation.
    ///
    /// @deprecated
    ///   This method is deprecated. Read concerns should be set either in the URI or directly on
    ///   database or collection objects.
    ///
    /// @param rc
    ///   The new @c read_concern
    ///
    /// @see https://docs.mongodb.com/master/reference/read-concern/
    ///
    MONGOCXX_DEPRECATED void read_concern(class read_concern rc);
    void read_concern_deprecated(class read_concern rc);

    ///
    /// Returns the current read concern for this client.
    ///
    /// @return The current @c read_concern
    ///
    class read_concern read_concern() const;

    ///
    /// Sets the read preference for this client.
    ///
    /// Modifications at this level do not affect existing database instances that have been
    /// created by this client but do affect new ones as databases inherit the @c read_preference
    /// settings of their parent upon instantiation.
    ///
    /// @deprecated
    ///   This method is deprecated. Read preferences should be set either in the URI or directly on
    ///   database or collection objects.
    ///
    /// @param rp
    ///   The new @c read_preference
    ///
    /// @see https://docs.mongodb.com/master/core/read-preference/
    ///
    MONGOCXX_DEPRECATED void read_preference(class read_preference rp);
    void read_preference_deprecated(class read_preference rp);

    ///
    /// Returns the current read preference for this client.
    ///
    /// @return The current @c read_preference
    ///
    /// @see https://docs.mongodb.com/master/core/read-preference/
    ///
    class read_preference read_preference() const;

    ///
    /// Returns the current uri for this client.
    ///
    /// @return The @c uri that this client was created with.
    ///
    class uri uri() const;

    ///
    /// Sets the write concern for this client.
    ///
    /// @note Modifications at this level do not affect existing databases or collection instances
    /// that have come from this client but do affect new ones as databases will receive a copy of
    /// this client's @c write_concern upon instantiation.
    ///
    /// @deprecated
    ///   This method is deprecated. Write concerns should be set either in the URI or directly on
    ///   database or collection objects.
    ///
    /// @param wc
    ///   The new write concern
    ///
    MONGOCXX_DEPRECATED void write_concern(class write_concern wc);
    void write_concern_deprecated(class write_concern wc);

    ///
    /// Returns the current write concern for this client.
    ///
    /// @return the current @c write_concern
    class write_concern write_concern() const;

    ///
    /// Obtains a database that represents a logical grouping of collections on a MongoDB server.
    ///
    /// @note A database cannot be obtained from a temporary client object.
    ///
    /// @param name
    ///   The name of the database to get
    ///
    /// @return The database
    ///
    class database database(bsoncxx::string::view_or_value name) const&;
    class database database(bsoncxx::string::view_or_value name) const&& = delete;

    ///
    /// Allows the syntax @c client["db_name"] as a convenient shorthand for the client::database()
    /// method by implementing the array subscript operator.
    ///
    /// @note A database cannot be obtained from a temporary client object.
    ///
    /// @param name
    ///   The name of the database.
    ///
    /// @return Client side representation of a server side database
    ///
    MONGOCXX_INLINE class database operator[](bsoncxx::string::view_or_value name) const&;
    MONGOCXX_INLINE class database operator[](bsoncxx::string::view_or_value name) const&& = delete;

    ///
    /// @{
    ///
    /// Enumerates the databases in the client.
    ///
    /// @return A mongocxx::cursor containing a BSON document for each
    ///   database. Each document contains a name field with the database
    ///   name, a sizeOnDisk field with the total size of the database file on
    ///   disk in bytes, and an empty field specifying whether the database
    ///   has any data.
    ///
    /// @throws mongocxx::operation_exception if the underlying 'listDatabases' command fails.
    ///
    /// @see https://docs.mongodb.com/master/reference/command/listDatabases
    ///
    cursor list_databases() const;

    ///
    /// Enumerates the databases in the client.
    ///
    /// @param session
    ///   The mongocxx::client_session with which to perform the aggregation.
    ///
    /// @return A mongocxx::cursor containing a BSON document for each
    ///   database. Each document contains a name field with the database
    ///   name, a sizeOnDisk field with the total size of the database file on
    ///   disk in bytes, and an empty field specifying whether the database
    ///   has any data.
    ///
    /// @throws mongocxx::operation_exception if the underlying 'listDatabases' command fails.
    ///
    /// @see https://docs.mongodb.com/master/reference/command/listDatabases
    ///
    cursor list_databases(const client_session& session) const;

    ///
    /// Enumerates the databases in the client.
    ///
    /// @param filter
    ///   The filter that documents must match in order to be listed.
    ///
    /// @return A mongocxx::cursor containing a BSON document for each
    ///   database. Each document contains a name field with the database
    ///   name, a sizeOnDisk field with the total size of the database file on
    ///   disk in bytes, and an empty field specifying whether the database
    ///   has any data.
    ///
    /// @throws mongocxx::operation_exception if the underlying 'listDatabases' command fails.
    ///
    /// @see https://docs.mongodb.com/master/reference/command/listDatabases
    ///
    cursor list_databases(const bsoncxx::document::view_or_value filter) const;

    ///
    /// Queries the MongoDB server for a list of known databases.
    ///
    /// @param filter
    ///   An optional query expression to filter the returned database names.
    ///
    /// @return std::vector<std::string> containing the database names.
    ///
    /// @throws mongocxx::operation_exception if the underlying 'listDatabases'
    /// command fails.
    ///
    /// @see https://docs.mongodb.com/master/reference/command/listDatabases
    ///
    std::vector<std::string> list_database_names(
        const bsoncxx::document::view_or_value filter = {}) const;

    ///
    /// @}
    ///

    ///
    /// Create a client session for a sequence of operations.
    ///
    /// @return A client_session object. See `mongocxx::client_session` for more information.
    ///
    /// @throws mongocxx::operation_exception if the driver is not built with crypto support, if
    /// options is misconfigured, or if the session is configured with options that the server does
    /// not support.
    ///
    client_session start_session(const options::client_session& options = {});

    ///
    /// @{
    ///
    /// Gets a change stream on this client with an empty pipeline.
    /// Change streams are only supported with a "majority" read concern or no read concern.
    ///
    /// @param options
    ///   The options to use when creating the change stream.
    ///
    /// @return
    ///  A change stream on this client.
    ///
    /// @see https://docs.mongodb.com/manual/changeStreams/
    ///
    change_stream watch(const options::change_stream& options = {});

    ///
    /// @param session
    ///   The mongocxx::client_session with which to perform the watch operation.
    /// @param options
    ///   The options to use when creating the change stream.
    ///
    /// @return
    ///  A change stream on this client.
    ///
    /// @see https://docs.mongodb.com/manual/changeStreams/
    ///
    change_stream watch(const client_session& session, const options::change_stream& options = {});

    ///
    /// Gets a change stream on this client.
    /// Change streams are only supported with a "majority" read concern or no read concern.
    ///
    /// @param pipe
    ///   The aggregation pipeline to be used on the change notifications.
    ///   Only a subset of pipeline operations are supported for change streams. For more
    ///   information see the change streams documentation.
    /// @param options
    ///   The options to use when creating the change stream.
    ///
    /// @return
    ///  A change stream on this client.
    ///
    /// @see https://docs.mongodb.com/manual/changeStreams/
    ///
    change_stream watch(const pipeline& pipe, const options::change_stream& options = {});

    ///
    /// Gets a change stream on this client.
    ///
    /// @param session
    ///   The mongocxx::client_session with which to perform the watch operation.
    /// @param pipe
    ///   The aggregation pipeline to be used on the change notifications.
    /// @param options
    ///   The options to use when creating the change stream.
    ///
    /// @return
    ///  A change stream on this client.
    ///
    /// @see https://docs.mongodb.com/manual/changeStreams/
    ///
    change_stream watch(const client_session& session,
                        const pipeline& pipe,
                        const options::change_stream& options = {});

    ///
    /// @}
    ///

    ///
    /// Prevents resource cleanup in the child process from interfering
    /// with the parent process after forking.
    ///
    /// Clients should not be reused after forking. Call this method in the
    /// child after forking to safely destroy the client. This method should
    /// not be used with multi-threaded clients.
    ///
    /// This method causes the client to clear its session pool without sending
    /// endSessions.  It also increments an internal generation counter on the
    /// given client. After this method is called, cursors from
    /// previous generations will not issue a killCursors command when
    /// they are destroyed. Client sessions from previous generations
    /// cannot be used and should be destroyed.
    ///
    void reset();

   private:
    friend class collection;
    friend class database;
    friend class pool;
    friend class client_session;
    friend class options::auto_encryption;

    MONGOCXX_PRIVATE explicit client(void* implementation);

    MONGOCXX_PRIVATE change_stream _watch(const client_session* session,
                                          const pipeline& pipe,
                                          const options::change_stream& options);

    class MONGOCXX_PRIVATE impl;

    MONGOCXX_PRIVATE impl& _get_impl();
    MONGOCXX_PRIVATE const impl& _get_impl() const;

    std::unique_ptr<impl> _impl;
};

MONGOCXX_INLINE database client::operator[](bsoncxx::string::view_or_value name) const& {
    return database(name);
}

MONGOCXX_INLINE_NAMESPACE_END
}  // namespace mongocxx

#include <mongocxx/config/postlude.hpp>


text:
package androidx.leanback.leanbackshowcase.app.room.di.androidinject;

import androidx.leanback.leanbackshowcase.app.room.controller.search.SearchFragment;

import androidx.leanback.leanbackshowcase.app.room.di.scope.PerFragment;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;

/**
 * As we have discussed before, this module will be responsible for twoi tasks
 * 1. It will connect to the sub component which is responsible for search fragment's injection
 * 2.
 */
@Module
public abstract class SearchFragmentInjectorInstallmentFactoryBindingModule {
  @PerFragment
  @ContributesAndroidInjector(modules = SearchFragmentUIModule.class)
  abstract SearchFragment contributeSearchFragment();
}

redpajama_set_name: RedPajamaGithub


text:
#include "config.h"
#include "RunLoop.h"

#include "NotImplemented.h"

namespace WebCore {

RunLoop::RunLoop()
{
    notImplemented();
}

RunLoop::~RunLoop()
{
    notImplemented();
}

void RunLoop::wakeUp()
{
    notImplemented();
}

} // namespace WebCore


text:
package io.sarl.lang.tests.bugs.to00699;

import static io.sarl.tests.api.tools.TestEObjects.file;
import static io.sarl.tests.api.tools.TestUtils.multilineString;
import static io.sarl.tests.api.tools.TestValidator.validate;
import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

import io.sarl.lang.SARLVersion;
import io.sarl.lang.sarl.SarlPackage;
import io.sarl.lang.sarl.SarlScript;
import io.sarl.tests.api.AbstractSarlTest;
import io.sarl.tests.api.tools.TestValidator.Validator;

/** Testing class for issue: Anonymous function not working.
 *
 * <p>https://github.com/sarl/sarl/issues/655
 *
 * @author $Author: sgalland$
 * @version $Name$ $Revision$ $Date$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 */
@DisplayName("Bug #655")
@SuppressWarnings("all")
@Tag("core")
public class Bug655Test extends AbstractSarlTest {

	private static final String SNIPSET1 = multilineString(
			"package io.sarl.lang.tests.bug655",
			"import io.sarl.lang.core.Event",
			"import java.util.Timer",
			"import java.util.TimerTask",
			"event InitAgents",
			"capacity MyCapacity {",
			"	def emit(e : Event)",
			"}",
			"agent X {",
			"	uses MyCapacity",
			"	val timer = new Timer",
			"	def initialize {",
			"		timer.schedule(new TimerTask() {",
			"			override run {",
			"				emit(new InitAgents)",
			"			}",
			"		}, 0, 500)",
			"	}",
			"}");

	private final String EXPECTED = multilineString(
			"package io.sarl.lang.tests.bug655;",
			"",
			"import io.sarl.lang.annotation.ImportedCapacityFeature;",
			"import io.sarl.lang.annotation.SarlElementType;",
			"import io.sarl.lang.annotation.SarlSpecification;",
			"import io.sarl.lang.annotation.SyntheticMember;",
			"import io.sarl.lang.core.Agent;",
			"import io.sarl.lang.core.AtomicSkillReference;",
			"import io.sarl.lang.core.DynamicSkillProvider;",
			"import io.sarl.lang.tests.bug655.InitAgents;",
			"import io.sarl.lang.tests.bug655.MyCapacity;",
			"import java.util.Timer;",
			"import java.util.TimerTask;",
			"import java.util.UUID;",
			"import javax.inject.Inject;",
			"import org.eclipse.xtext.xbase.lib.Extension;",
			"import org.eclipse.xtext.xbase.lib.Pure;",
			"",
			"@SarlSpecification(\"" + SARLVersion.SPECIFICATION_RELEASE_VERSION_STRING + "\")",
			"@SarlElementType(" + SarlPackage.SARL_AGENT + ")",
			"@SuppressWarnings(\"all\")",
			"public class X extends Agent {",
			"  private final Timer timer = new Timer();",
			"  ",
			"  protected void initialize() {",
			"    this.timer.schedule(new TimerTask() {",
			"      @Override",
			"      public void run() {",
			"        MyCapacity _$CAPACITY_USE$IO_SARL_LANG_TESTS_BUG655_MYCAPACITY$CALLER = X.this.$CAPACITY_USE$IO_SARL_LANG_TESTS_BUG655_MYCAPACITY$CALLER();",
			"        InitAgents _initAgents = new InitAgents();",
			"        _$CAPACITY_USE$IO_SARL_LANG_TESTS_BUG655_MYCAPACITY$CALLER.emit(_initAgents);",
			"      }",
			"    }, 0, 500);",
			"  }",
			"  ",
			"  @Extension",
			"  @ImportedCapacityFeature(MyCapacity.class)",
			"  @SyntheticMember",
			"  private transient AtomicSkillReference $CAPACITY_USE$IO_SARL_LANG_TESTS_BUG655_MYCAPACITY;",
			"  ",
			"  @SyntheticMember",
			"  @Pure",
			"  private MyCapacity $CAPACITY_USE$IO_SARL_LANG_TESTS_BUG655_MYCAPACITY$CALLER() {",
			"    if (this.$CAPACITY_USE$IO_SARL_LANG_TESTS_BUG655_MYCAPACITY == null || this.$CAPACITY_USE$IO_SARL_LANG_TESTS_BUG655_MYCAPACITY.get() == null) {",
			"      this.$CAPACITY_USE$IO_SARL_LANG_TESTS_BUG655_MYCAPACITY = $getSkill(MyCapacity.class);",
			"    }",
			"    return $castSkill(MyCapacity.class, this.$CAPACITY_USE$IO_SARL_LANG_TESTS_BUG655_MYCAPACITY);",
			"  }",
			"  ",
			"  @Override",
			"  @Pure",
			"  @SyntheticMember",
			"  public boolean equals(final Object obj) {",
			"    return super.equals(obj);",
			"  }",
			"  ",
			"  @Override",
			"  @Pure",
			"  @SyntheticMember",
			"  public int hashCode() {",
			"    int result = super.hashCode();",
			"    return result;",
			"  }",
			"  ",
			"  @SyntheticMember",
			"  public X(final UUID arg0, final UUID arg1) {",
			"    super(arg0, arg1);",
			"  }",
			"  ",
			"  @SyntheticMember",
			"  @Inject",
			"  public X(final UUID arg0, final UUID arg1, final DynamicSkillProvider arg2) {",
			"    super(arg0, arg1, arg2);",
			"  }",
			"}",
			"");

	@Test
	@Tag("sarlValidation")
	public void parsing_01() throws Exception {
		SarlScript mas = file(getParseHelper(), SNIPSET1);
		final Validator validator = validate(getValidationHelper(), getInjector(), mas);
		validator.assertNoErrors();
	}

	@Test
	@Tag("compileToJava")
	public void compiling_01() throws Exception {
		getCompileHelper().compile(SNIPSET1, (it) -> {
			final String actual = it.getGeneratedCode("io.sarl.lang.tests.bug655.X");
			assertEquals(EXPECTED, actual);
		});
	}

}


text:
Usage Tips
==========

General tips
------------

1. Use class inheritance. If your models share common functionality,
create base class which will be responsible for this functionality.

For example - permissions. Don't implement `is_accessible` in  every administrative view. Create your own base class,
implement is_accessible there and use it instead.

2. You can override templates either by using `ModelView` properties or
putting customized version into your `templates/admin/` directory

SQLAlchemy
----------

1. If `synonym_property` does not return SQLAlchemy field, Flask-Admin
won't be able to figure out what to do with it and won't generate form
field. In this case, you need to manually contribute field::

    class MyView(ModelView):
        def scaffold_form(self):
            form_class = super(UserView, self).scaffold_form()
            form_class.extra = wtf.TextField('Extra')
            return form_class


text:
<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width">
  <meta name="description" content="Cascading grid layout library">

  <title>Masonry · Options</title>

    <link rel="stylesheet" href="css/masonry-docs.css?1" media="screen">

          Masonry

          Layout

          Options

          Methods

          Events

          Extras

          FAQ

Options

Recommended

itemSelector

columnWidth

Layout

Element sizing

gutter

horizontalOrder

percentPosition

stamp

fitWidth

originLeft

originTop

Setup

containerStyle

transitionDuration

stagger

resize

initLayout

All options are optional, but columnWidth and itemSelector are recommended.

// jQuery
$('.grid').masonry({
  columnWidth: 200,
  itemSelector: '.grid-item'
});

// vanilla JS
var msnry = new Masonry( '.grid', {
  columnWidth: 200,
  itemSelector: '.grid-item'
});

<!-- in HTML -->
<div class="grid" data-masonry='{ "columnWidth": 200, "itemSelector": ".grid-item" }'>

Recommended

itemSelector

Specifies which child elements will be used as item elements in the layout.

We recommend always setting itemSelector. itemSelector is useful to exclude sizing elements or other elements that are not part of the layout.

itemSelector: '.grid-item'

<div class="grid">
  <!-- do not use banner in Masonry layout -->
  <div class="static-banner">Static banner</div>
  <div class="grid-item"></div>
  <div class="grid-item"></div>
  ...
</div>

Static banner

        Edit this demo on CodePen

columnWidth

Aligns items to a horizontal grid.

We recommend setting columnWidth. If columnWidth is not set, Masonry will use the outer width of the first item.

columnWidth: 80

        Edit this demo on CodePen

Use element sizing for responsive layouts with percentage widths. Set columnWidth to an Element or Selector String to use the outer width of the element for the size of the column.

<div class="grid">
  <!-- .grid-sizer empty element, only used for element sizing -->
  <div class="grid-sizer"></div>
  <div class="grid-item"></div>
  <div class="grid-item grid-item--width2"></div>
  ...
</div>

/* fluid 5 columns */
.grid-sizer,
.grid-item { width: 20%; }
/* 2 columns wide */
.grid-item--width2 { width: 40%; }

// use outer width of grid-sizer for columnWidth
columnWidth: '.grid-sizer',
itemSelector: '.grid-item',
percentPosition: true

        Edit this demo on CodePen

Layout

Element sizing

Sizing options columnWidth and gutter can be set with an element. The size of the element is then used as the value of the option.

<div class="grid">
  <!-- .grid-sizer empty element, only used for element sizing -->
  <div class="grid-sizer"></div>
  <div class="grid-item"></div>
  <div class="grid-item grid-item--width2"></div>
  ...
</div>

/* fluid 5 columns */
.grid-sizer,
.grid-item { width: 20%; }
/* 2 columns wide */
.grid-item--width2 { width: 40%; }

// use outer width of grid-sizer for columnWidth
columnWidth: '.grid-sizer',
// do not use .grid-sizer in layout
itemSelector: '.grid-item',
percentPosition: true

        Edit this demo on CodePen

The option can be set to a Selector String or an Element.

// set to a selector string
// first matching element within container element will be used
columnWidth: '.grid-sizer'

// set to an element
columnWidth: $grid.find('.grid-sizer')[0]

Element sizing options allow you to control the sizing of the Masonry layout within your CSS. This is useful for responsive layouts and media queries.

/* 3 columns by default */
.grid-sizer { width: 33.333%; }

@media screen and (min-width: 768px) {
  /* 5 columns for larger screens */
  .grid-sizer { width: 20%; }
}

gutter

Adds horizontal space between item elements.

gutter: 10

        Edit this demo on CodePen

To set vertical space between elements, use margin CSS.

gutter: 10

.grid-item {
  margin-bottom: 10px;
}

        Edit this demo on CodePen

Use element sizing for responsive layouts with percentage widths. Set gutter to an Element or Selector String to use the outer width of the element.

<div class="grid">
  <div class="grid-sizer"></div>
  <div class="gutter-sizer"></div>
  <div class="grid-item"></div>
  <div class="grid-item grid-item--width2"></div>
  ...
</div>

.grid-sizer,
.grid-item { width: 22%; }

.gutter-sizer { width: 4%; }

.grid-item--width2 { width: 48%; }

columnWidth: '.grid-sizer',
gutter: '.gutter-sizer',
itemSelector: '.grid-item',
percentPosition: true

        Edit this demo on CodePen

horizontalOrder

Lays out items to (mostly) maintain horizontal left-to-right order.

horizontalOrder: true

        Edit this demo on CodePen

Look how items in the second row are ordered.

// default, items have no horizontal order
// horizontalOrder: false

percentPosition

Sets item positions in percent values, rather than pixel values. percentPosition: true works well with percent-width items, as items will not transition their position on resize.

// set positions with percent values
percentPosition: true,
columnWidth: '.grid-sizer',
itemSelector: '.grid-item'

/* fluid 5 columns */
.grid-sizer,
.grid-item { width: 20%; }

        Edit this demo on CodePen

stamp

Specifies which elements are stamped within the layout. Masonry will layout items below stamped elements.

The stamp option stamps elements only when the Masonry instance is first initialized. You can stamp additional elements afterwards with the stamp method.

<div class="grid">
  <div class="stamp stamp1"></div>
  <div class="stamp stamp2"></div>
  <div class="grid-item"></div>
  <div class="grid-item"></div>
  ....
</div>

// specify itemSelector so stamps do get laid out
itemSelector: '.grid-item',
// stamp elements
stamp: '.stamp'

/* position stamp elements with CSS */
.stamp {
  position: absolute;
  background: orange;
  border: 4px dotted black;
}
.stamp1 {
  left: 30%;
  top: 10px;
  width: 20%;
  height: 100px;
}
.stamp2 {
  right: 10%;
  top: 20px;
  width: 70%;
  height: 30px;
}

        Edit this demo on CodePen

fitWidth

Sets the width of the container to fit the available number of columns, based the size of container's parent element. When enabled, you can center the container with CSS.

fitWidth was previously isFitWidth in Masonry v3. isFitWidth will still work in Masonry v4.

fitWidth: true does not work with element sizing with percentage width. Either columnWidth needs to be set to a fixed size, like columnWidth: 120, or items need to have a fixed size in pixels, like width: 120px. Otherwise, the container and item widths will collapse on one another.

fitWidth: true

/* center container with CSS */
.grid {
  margin: 0 auto;
}

        Edit this demo on CodePen

originLeft

Controls the horizontal flow of the layout. By default, item elements start positioning at the left, with originLeft: true. Set originLeft: false for right-to-left layouts.

originLeft was previously isOriginLeft in Masonry v3. isOriginLeft will still work in Masonry v4.

originLeft: false

        Edit this demo on CodePen

originTop

Controls the vertical flow of the layout. By default, item elements start positioning at the top, with originTop: true. Set originTop: false for bottom-up layouts. It’s like Tetris!

originTop was previously isOriginTop in Masonry v3. isOriginTop will still work in Masonry v4.

originTop: false

        Edit this demo on CodePen

Setup

containerStyle

CSS styles that are applied to the container element.

// default
// containerStyle: { position: 'relative' }

// disable any styles being set on container
// useful if using absolute position on container
containerStyle: null

transitionDuration

Duration of the transition when items change position or appearance, set in a CSS time format. Default: transitionDuration: '0.4s'

// fast transitions
transitionDuration: '0.2s'

// slow transitions
transitionDuration: '0.8s'

// no transitions
transitionDuration: 0

stagger

Staggers item transitions, so items transition incrementally after one another. Set as a CSS time format, '0.03s', or as a number in milliseconds, 30.

stagger: 30

Click item to toggle size

        Edit this demo
        or vanilla JS demo on CodePen

resize

Adjusts sizes and positions when window is resized. Enabled by default resize: true.

resize was previously isResizeBound in Masonry v3. isResizeBound will still work in Masonry v4.

// disable window resize behavior
resize: false

/* grid has fixed width */
.grid {
  width: 320px;
}

        Edit this demo on CodePen

initLayout

Enables layout on initialization.
  Enabled by default initLayout: true.

Set initLayout: false to disable layout on initialization, so you can use methods or add events before the initial layout.

initLayout was previously isInitLayout in Masonry v3. isInitLayout will still work in Masonry v4.

var $grid = $('.grid').masonry({
  // disable initial layout
  initLayout: false,
  //...
});
// bind event
$grid.masonry( 'on', 'layoutComplete', function() {
  console.log('layout is complete');
});
// trigger initial layout
$grid.masonry();

    Edit this demo
    or vanilla JS demo on CodePen

          Masonry

          Layout

          Options

          Methods

          Events

          Extras

          FAQ

        Masonry is made by David DeSandro.
        Make something rad with it.

                    <svg class="isotope-illo" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 350 350" width="100" height="100">
                      <path class="isotope-illo__color1" fill="#6C6" d="M80 170H30c-6 0-10-5-10-10v-50c0-6 5-10 10-10h50c6 0 10 5 10 10v50C90 166 86 170 80 170z"/>
                      <path class="isotope-illo__color1" fill="#6C6" d="M80 90H30c-6 0-10-5-10-10V30c0-6 5-10 10-10h50c6 0 10 5 10 10v50C90 86 86 90 80 90z"/>
                      <path class="isotope-illo__color1" fill="#6C6" d="M160 90h-50c-6 0-10-5-10-10V30c0-6 5-10 10-10h50c6 0 10 5 10 10v50C170 86 166 90 160 90z"/>
                      <path class="isotope-illo__color1" fill="#6C6" d="M240 90h-50c-6 0-10-5-10-10V30c0-6 5-10 10-10h50c6 0 10 5 10 10v50C250 86 246 90 240 90z"/>
                      <path class="isotope-illo__color1" fill="#6C6" d="M320 90h-50c-6 0-10-5-10-10V30c0-6 5-10 10-10h50c6 0 10 5 10 10v50C330 86 326 90 320 90z"/>
                      <path class="isotope-illo__color1" fill="#6C6" d="M155 165h-40c-6 0-10-5-10-10v-40c0-6 5-10 10-10h40c6 0 10 5 10 10v40 C165 161 161 165 155 165z"/>
                      <path class="isotope-illo__color1" fill="#6C6" d="M230 160h-30c-6 0-10-5-10-10v-30c0-6 5-10 10-10h30c6 0 10 5 10 10v30 C240 156 236 160 230 160z"/>
                      <path class="isotope-illo__color1" fill="#6C6" d="M305 155h-20c-6 0-10-5-10-10v-20c0-6 5-10 10-10h20c6 0 10 5 10 10v20 C315 151 311 155 305 155z"/>
                      <path class="isotope-illo__color1" fill="#6C6" d="M65 235H45c-6 0-10-5-10-10v-20c0-6 5-10 10-10h20c6 0 10 5 10 10v20C75 231 71 235 65 235z"/>
                      <path class="isotope-illo__color1" fill="#6C6" d="M140 230h-10c-6 0-10-5-10-10v-10c0-6 5-10 10-10h10c6 0 10 5 10 10v10 C150 226 146 230 140 230z"/>
                      <path class="isotope-illo__color2" fill="#19F" d="M305 235h-20c-6 0-10-5-10-10v-20c0-6 5-10 10-10h20c6 0 10 5 10 10v20 C315 231 311 235 305 235z"/>
                      <path class="isotope-illo__color2" fill="#19F" d="M65 315H45c-6 0-10-5-10-10v-20c0-6 5-10 10-10h20c6 0 10 5 10 10v20C75 311 71 315 65 315z"/>
                      <path class="isotope-illo__color2" fill="#19F" d="M150 320h-30c-6 0-10-5-10-10v-30c0-6 5-10 10-10h30c6 0 10 5 10 10v30 C160 316 156 320 150 320z"/>
                      <path class="isotope-illo__color2" fill="#19F" d="M220 230h-10c-6 0-10-5-10-10v-10c0-6 5-10 10-10h10c6 0 10 5 10 10v10 C230 226 226 230 220 230z"/>
                      <path class="isotope-illo__color2" fill="#19F" d="M235 325h-40c-6 0-10-5-10-10v-40c0-6 5-10 10-10h40c6 0 10 5 10 10v40 C245 321 241 325 235 325z"/>
                      <path class="isotope-illo__color2" fill="#19F" d="M320 330h-50c-6 0-10-5-10-10v-50c0-6 5-10 10-10h50c6 0 10 5 10 10v50 C330 326 326 330 320 330z"/>
                    </svg>

Isotope

Filter & sort magical layouts

                    <svg class="infinite-scroll-illo" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 520 520" width="200" height="200">
                      <path class="infinite-scroll-illo__page infinite-scroll-illo__page--back" d="M90,110H10V90c0-22,18-40,40-40h40V110z"/>
                      <path class="infinite-scroll-illo__page infinite-scroll-illo__page--front1" d="M270,90L270,90c0-22-18-40-40-40h0H50h0c22,0,40,18,40,40v0v0v160h180V90z"/>
                      <path class="infinite-scroll-illo__page infinite-scroll-illo__page--front2" d="M170,330v-20H90v20v0c0,22,18,40,40,40h0h40V330z"/>
                      <path class="infinite-scroll-illo__page infinite-scroll-illo__page--back" d="M350,150H210c-22,0-40,18-40,40v140v0c0,22-18,40-40,40h0h220V150z"/>
                      <path class="infinite-scroll-illo__page infinite-scroll-illo__page--front3" d="M430,470V270H250v160c0,22,18,40,40,40H430z"/>
                      <path class="infinite-scroll-illo__page infinite-scroll-illo__page--front2" d="M250,190v20h180v-20c0-22-18-40-40-40H210h0C232,150,250,168,250,190L250,190z"/>
                      <path class="infinite-scroll-illo__page infinite-scroll-illo__page--back" d="M330,410v20v0c0,22-18,40-40,40h0h180c22,0,40-18,40-40v-20H330z"/>
                    </svg>

Infinite Scroll

Automatically add next page

                    <svg class="flickity-illo" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 360 360" width="100" height="100">
                      <path class="flickity-illo__color1" fill="#19F" d="M300 220L300 220c-11 0-20-9-20-20v-80c0-11 9-20 20-20h0V220z"/>
                      <path class="flickity-illo__color1" fill="#19F" d="M340 220L340 220c-11 0-20-9-20-20v-80c0-11 9-20 20-20h0V220z"/>
                      <path class="flickity-illo__color2" fill="#333" d="M320 290V180c0-18-10-35-27-43L240 110v180H320z"/>
                      <path class="flickity-illo__color3" fill="white" d="M240 300H120c-11 0-20-9-20-20V40c0-11 9-20 20-20h120c11 0 20 9 20 20v240C260 291 251 300 240 300z"/>
                      <path class="flickity-illo__color4" fill="#ED0" d="M230 260H130c-6 0-10-5-10-10V70c0-6 5-10 10-10h100c6 0 10 5 10 10v180 C240 256 236 260 230 260z"/>
                      <path class="flickity-illo__color2" fill="#333" d="M260 200h60v81c0 32-26 59-59 59h0c-34 0-61-27-61-61V240h20 C242 240 260 222 260 200L260 200z"/>
                      <path class="flickity-illo__color5" fill="#C25" d="M180 220h-60V100h60c6 0 10 5 10 10v100C190 216 186 220 180 220z"/>
                      <path class="flickity-illo__color1" fill="#19F" d="M240 220h-20c-6 0-10-5-10-10V110c0-6 5-10 10-10h20V220z"/>
                      <rect class="flickity-illo__color2" fill="#333" x="230" y="280" width="90" height="80"/>
                      <circle class="flickity-illo__color4" fill="#ED0" cx="180" cy="280" r="10"/>
                      <line class="flickity-illo__thumb" stroke="#333" stroke-width="60" stroke-linecap="round" x1="262" y1="290" x2="152" y2="240"/>
                      <path class="flickity-illo__color4" fill="#ED0" d="M190 50h-20c-6 0-10-5-10-10v0c0-6 5-10 10-10h20c6 0 10 5 10 10v0C200 46 196 50 190 50z"/>
                      <path class="flickity-illo__color5" fill="#C25" d="M80 220L80 220c-11 0-20-9-20-20v-80c0-11 9-20 20-20h0V220z"/>
                      <path class="flickity-illo__color5" fill="#C25" d="M40 220L40 220c-11 0-20-9-20-20v-80c0-11 9-20 20-20h0V220z"/>
                    </svg>

Flickity

Touch, responsive, flickable carousels

                    <svg class="packery-illo" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 700 700" width="100" height="100">
                      <path class="packery-illo__item" fill="#C09" d="M172 180H48c-4 0-8-4-8-8V48c0-4 4-8 8-8h124c4 0 8 4 8 8v124C180 176 176 180 172 180z"/>
                      <path class="packery-illo__item" fill="#C09" d="M172 340H48c-4 0-8-4-8-8V208c0-4 4-8 8-8h124c4 0 8 4 8 8v124C180 336 176 340 172 340z"/>
                      <path class="packery-illo__item" fill="#C09" d="M492 660H368c-4 0-8-4-8-8V528c0-4 4-8 8-8h124c4 0 8 4 8 8v124C500 656 496 660 492 660z"/>
                      <path class="packery-illo__item" fill="#C09" d="M652 660H528c-4 0-8-4-8-8V528c0-4 4-8 8-8h124c4 0 8 4 8 8v124C660 656 656 660 652 660z"/>
                      <path class="packery-illo__item" fill="#C09" d="M652 500H368c-4 0-8-4-8-8V368c0-4 4-8 8-8h284c4 0 8 4 8 8v124C660 496 656 500 652 500z"/>
                      <path class="packery-illo__item" fill="#C09" d="M332 660H48c-4 0-8-4-8-8V368c0-4 4-8 8-8h284c4 0 8 4 8 8v284C340 656 336 660 332 660z"/>
                      <path class="packery-illo__item" fill="#C09" d="M652 340H528c-4 0-8-4-8-8V48c0-4 4-8 8-8h124c4 0 8 4 8 8v284C660 336 656 340 652 340z"/>
                      <path class="packery-illo__draggie" fill="#EA0" d="M572 440H288c-4 0-8-4-8-8V148c0-4 4-8 8-8h284c4 0 8 4 8 8v284C580 436 576 440 572 440z"/>
                      <g>
                        <path class="packery-illo__hand" fill="white" d="M530 250c-11 0-20 9-20 20v-10c0-11-9-20-20-20s-20 9-20 20c0-11-9-20-20-20s-20 9-20 20c0-11-9-20-20-20
                          s-20 9-20 20v20c-17 0-30 13-30 30c0 11 6 20 14 25l19 35c10 18 30 30 51 30h28
                          c43 0 78-35 78-78V270C550 259 541 250 530 250z"/>
                        <line class="packery-illo__hand-line" stroke="#EA0" fill="none" stroke-width="16" stroke-linecap="round" x1="430" y1="300" x2="430" y2="340"/>
                        <line class="packery-illo__hand-line" stroke="#EA0" fill="none" stroke-width="16" stroke-linecap="round" x1="470" y1="300" x2="470" y2="340"/>
                        <line class="packery-illo__hand-line" stroke="#EA0" fill="none" stroke-width="16" stroke-linecap="round" x1="510" y1="300" x2="510" y2="340"/>
                      </g>
                    </svg>

Packery

Gapless, draggable grid layouts

                    <svg class="witchie-logo" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 1000 1000" width="200" height="200">
                      <circle class="witchie-logo__moon" fill="white" cx="500" cy="500" r="500"/>
                      <path class="witchie-logo__broom" fill="#EA0" d="M582 675a35 35 0 0 0 8-20 3 3 0 0 1 3-2h71a3 3 0 0 1 3 3 59 59 0 0 0 0 20 3 3 0 0 1-3 3h-79A3 3 0 0 1 582 675Zm219 4a13 13 0 0 0 13-14c-1-7-7-12-14-12h-44a3 3 0 0 0-3 3v21a3 3 0 0 0 3 3ZM299 660a203 203 0 0 1-27-36 8 8 0 0 0-4-3L178 582a13 13 0 0 0-18 12v77a8 8 0 0 0 8 8h22a5 5 0 0 1 2 10L164 703a8 8 0 0 0-4 7v28a13 13 0 0 0 18 12l146-63a3 3 0 0 0 1-5A197 197 0 0 1 299 660Z"/>
                      <path class="witchie-logo__dress" fill="#333" d="M326 705h4a13 13 0 0 1 13 13v8a13 13 0 0 0 4 9l13 13a13 13 0 0 1 0 19l-56 56c-10 10-26-0-22-13L314 714A13 13 0 0 1 326 705Zm397-79c-27 0-47 26-37 54 3 7 11 16 17 19a42 42 0 0 0 19 5 38 38 0 0 0 7-1 8 8 0 0 0 6-8v-62a8 8 0 0 0-6-8 38 38 0 0 0-7-1M840 397c-3-15-33-23-77-23a521 521 0 0 0-59 4 5 5 0 0 1-5-2L567 177a8 8 0 0 0-7-4 8 8 0 0 0-8 8l1 227a5 5 0 0 1-4 5c-74 24-123 55-119 76 2 8 11 14 26 18a3 3 0 0 1 1 4l-11 11c-20 20-56 30-92 30-31 0-63-8-84-23a5 5 0 0 0-3-1 5 5 0 0 0-5 5c0 78 68 173 183 173h75a10 10 0 0 0 7-3l38-38a16 16 0 0 0 0-23l-34-34a10 10 0 0 1 0-14l15-15a3 3 0 0 1 5 2v15a5 5 0 0 0 5 5H674a4 4 0 0 0 3-7l-90-90a3 3 0 0 1 1-4c34-19 59-49 67-84a3 3 0 0 1 2-2c6-1 12-1 17-1 22 0 37 5 39 14 1 6 3 11 2 17-5 17 1 31 8 31a6 6 0 0 0 2-0C797 448 845 419 840 397Z"/>
                    </svg>

Fizzy School

Lessons in JavaScript for jQuery newbies


text:
from __future__ import print_function, unicode_literals
from prompt_toolkit import Application, CommandLineInterface
from prompt_toolkit.layout.controls import FillControl
from prompt_toolkit.shortcuts import (
    Buffer, BufferControl, DEFAULT_BUFFER, KeyBindingManager, Keys, Window,
    HSplit, Token, LayoutDimension as D, create_eventloop)
from traceback import print_exc

def instapipe(runner, init_cmd, instant=False, input_lines=1, input_deco=''):
  layout = HSplit([
      Window(content=BufferControl(buffer_name=DEFAULT_BUFFER),
             height=D.exact(1)),
      Window(content=FillControl('-', token=Token.Line), height=D.exact(1)),
      Window(content=BufferControl(buffer_name='OUTPUT'))
  ])
  buffers, keybinds = _setup_buffers(runner, layout.children[-1], instant)
  app = Application(layout=layout, buffers=buffers, mouse_support=True,
                    key_bindings_registry=keybinds, use_alternate_screen=True)

  eventloop = create_eventloop()
  final_cmd = ''
  try:
    final_cmd = CommandLineInterface(application=app, eventloop=eventloop).run()
  except:
    print_exc()
  finally:
    eventloop.close()
    return final_cmd

def _setup_buffers(runner, output_window, instant_mode):
  input_buffer = Buffer(is_multiline=False)
  output_buffer = Buffer(is_multiline=True)

  def _run(_):
    n_head = output_window.render_info.window_height
    result, returncode = runner(input_buffer.text, n_head)
    output_buffer.text = unicode(result, 'utf8')

  reg = KeyBindingManager().registry
  if instant_mode:
    # run the command on every edit
    input_buffer.on_text_changed += _run
  else:
    # run after each carriage return
    reg.add_binding(Keys.ControlJ, eager=True)(_run)

  @reg.add_binding(Keys.ControlC, eager=True)
  @reg.add_binding(Keys.ControlQ, eager=True)
  def _exit(event):
    event.cli.set_return_value(None)

  @reg.add_binding(Keys.ControlD, eager=True)
  def _exit_with_value(event):
    event.cli.set_return_value(input_buffer.text)

  bufmap = {DEFAULT_BUFFER: input_buffer, 'OUTPUT': output_buffer}
  return bufmap, reg


text:
<?php

namespace SQLgreyGUI\Api\v1\Transformers;

use SQLgreyGUI\Models\OptDomain;

abstract class OptDomainTransformer extends Transformer
{
    /**
     * Transform.
     *
     * @param OptDomain $domain
     *
     * @return array
     */
    protected function transformDomain(OptDomain $domain)
    {
        $data = $domain->toArray();
        $data['id'] = $domain->domain;

        return $data;
    }
}


text:
static char const CONTINUE = 0x90;
static char const SUCCESS = 0xA0;
static char const CREATED = 0xA1;
static char const ACCEPTED = 0xA2;
static char const MULTIPLE_CHOICES = 0xB0;
static char const MOVED_PERMANENTLY = 0xB1;
static char const MOVED_TEMPORARILY = 0xB2;
static char const SEE_OTHER = 0xB3;
static char const NOT_MODIFIED = 0xB4;
static char const USE_PROXY = 0xB5;
static char const BAD_REQUEST = 0xC0;
static char const UNAUTHORIZED = 0xC1;
static char const FORBIDDEN = 0xC3;
static char const NOT_FOUND = 0xC4;
static char const METHOD_NOT_ALLOWED = 0xC5;
static char const NOT_ACCEPTABLE = 0xC6;
static char const PROXY_AUTHENTICATION_REQUIRED = 0xC7;
static char const REQUEST_TIME_OUT = 0xC8;
static char const CONFLICT = 0xC9;
static char const GONE = 0xCA;
static char const LENGTH_REQUIRED = 0xCB;
static char const PRECONDITION_FAILED = 0xCC;
static char const REQUEST_ENTITY_TOO_LARGE = 0xCD;
static char const REQUEST_URL_TOO_LARGE = 0xCE;
static char const UNSUPPORTED_MEDIA_TYPE = 0xCF;
static const char INTERNAL_SERVER_ERROR = 0xD0;
static char const NOT_IMPLEMENTED = 0xD1;
static char const BAD_GATEWAY = 0xD2;
static char const SERVICE_UNAVAILABLE = 0xD3;
static char const GATEWAY_TIMEOUT = 0xD4;
static char const HTTP_VERSION_NOT_SUPPORTED = 0xD5;
static char const DATABASE_FULL = 0xE0;
static char const DATABASE_LOCKED = 0xE1;

@interface OBEXFileTransferResponse : NSObject

@property(nonatomic, retain) NSData *data;
@property(nonatomic, retain) NSMutableDictionary *headers;
@property(nonatomic, assign) NSInteger length;
@property(nonatomic, assign) NSInteger maxLength;
@property(nonatomic, readonly) char code;
@property(nonatomic, readonly) char version;
@property(nonatomic, readonly) char flag;

- (id)initWithData:(NSData *)data;
@end


text:
exports.view = function(req, res){
	console.log("TEST");
	res.render('index');
};


text:
namespace gdbplz
{
	struct gdb_version : boost::totally_ordered<gdb_version>
	{
		unsigned major;
		unsigned minor;
		unsigned patch;
		std::string others;

		bool operator<(const gdb_version& other) const;
		bool operator==(const gdb_version& other) const;
		gdb_version(unsigned major, unsigned minor);
		gdb_version(unsigned major, unsigned minor, unsigned patch);
		gdb_version(unsigned major, unsigned minor, unsigned patch, std::string others);
	};
}

#endif


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

/**
 * @fileoverview Directive for the learner's view of a collection.
 */

require(
  'components/common-layout-directives/common-elements/' +
  'attribution-guide.component.ts');
require(
  'components/common-layout-directives/common-elements/' +
  'background-banner.component.ts');
require('components/summary-tile/exploration-summary-tile.directive.ts');

require('domain/collection/CollectionPlaythroughObjectFactory.ts');
require('domain/collection/guest-collection-progress.service.ts');
require('domain/collection/read-only-collection-backend-api.service.ts');
require('domain/utilities/url-interpolation.service.ts');
require('services/alerts.service.ts');
require('services/page-title.service.ts');
require('services/user.service.ts');
require('services/contextual/url.service.ts');

angular.module('oppia').animation(
  '.oppia-collection-animate-slide', function() {
    return {
      enter: function(element) {
        element.hide().slideDown();
      },
      leave: function(element) {
        element.slideUp();
      }
    };
  });

angular.module('oppia').directive('collectionPlayerPage', [
  'UrlInterpolationService', function(UrlInterpolationService) {
    return {
      restrict: 'E',
      scope: {},
      bindToController: {},
      templateUrl: UrlInterpolationService.getDirectiveTemplateUrl(
        '/pages/collection-player-page/collection-player-page.directive.html'),
      controllerAs: '$ctrl',
      controller: [
        '$anchorScroll', '$http', '$location', '$scope', 'AlertsService',
        'CollectionPlaythroughObjectFactory', 'GuestCollectionProgressService',
        'LoaderService', 'PageTitleService',
        'ReadOnlyCollectionBackendApiService', 'UrlInterpolationService',
        'UrlService', 'UserService',
        'WHITELISTED_COLLECTION_IDS_FOR_SAVING_GUEST_PROGRESS',
        function(
            $anchorScroll, $http, $location, $scope, AlertsService,
            CollectionPlaythroughObjectFactory, GuestCollectionProgressService,
            LoaderService, PageTitleService,
            ReadOnlyCollectionBackendApiService, UrlInterpolationService,
            UrlService, UserService,
            WHITELISTED_COLLECTION_IDS_FOR_SAVING_GUEST_PROGRESS) {
          var ctrl = this;
          ctrl.getStaticImageUrl = function(imagePath) {
            return UrlInterpolationService.getStaticImageUrl(imagePath);
          };
          ctrl.setIconHighlight = function(index) {
            ctrl.activeHighlightedIconIndex = index;
          };

          ctrl.unsetIconHighlight = function() {
            ctrl.activeHighlightedIconIndex = -1;
          };

          ctrl.togglePreviewCard = function() {
            ctrl.explorationCardIsShown = !ctrl.explorationCardIsShown;
          };

          ctrl.getCollectionNodeForExplorationId = function(explorationId) {
            var collectionNode = (
              ctrl.collection.getCollectionNodeByExplorationId(explorationId));
            if (!collectionNode) {
              AlertsService.addWarning(
                'There was an error loading the collection.');
            }
            return collectionNode;
          };

          ctrl.getNextRecommendedCollectionNodes = function() {
            return ctrl.getCollectionNodeForExplorationId(
              ctrl.collectionPlaythrough.getNextExplorationId());
          };

          ctrl.getCompletedExplorationNodes = function() {
            return ctrl.getCollectionNodeForExplorationId(
              ctrl.collectionPlaythrough.getCompletedExplorationIds());
          };

          ctrl.getNonRecommendedCollectionNodeCount = function() {
            return ctrl.collection.getCollectionNodeCount() - (
              ctrl.collectionPlaythrough.getNextRecommendedCollectionNodeCount(
              ) + ctrl.collectionPlaythrough.getCompletedExplorationNodeCount(
              ));
          };

          ctrl.updateExplorationPreview = function(explorationId) {
            ctrl.explorationCardIsShown = true;
            ctrl.currentExplorationId = explorationId;
            ctrl.summaryToPreview = ctrl.getCollectionNodeForExplorationId(
              explorationId).getExplorationSummaryObject();
          };

          // Calculates the SVG parameters required to draw the curved path.
          ctrl.generatePathParameters = function() {
            // The pathSvgParameters represents the final string of SVG
            // parameters for the bezier curve to be generated. The default
            // parameters represent the first curve ie. lesson 1 to lesson 3.
            ctrl.pathSvgParameters = 'M250 80  C 470 100, 470 280, 250 300';
            var collectionNodeCount = ctrl.collection.getCollectionNodeCount();
            // The sParameterExtension represents the co-ordinates following
            // the 'S' (smooth curve to) command in SVG.
            var sParameterExtension = '';
            ctrl.pathIconParameters = ctrl.generatePathIconParameters();
            if (collectionNodeCount === 1) {
              ctrl.pathSvgParameters = '';
            } else if (collectionNodeCount === 2) {
              ctrl.pathSvgParameters = 'M250 80  C 470 100, 470 280, 250 300';
            } else {
              // The x and y here represent the co-ordinates of the control
              // points for the bezier curve (path).
              var y = 500;
              for (var i = 1; i < Math.floor(collectionNodeCount / 2); i++) {
                var x = (i % 2) ? 30 : 470;
                sParameterExtension += x + ' ' + y + ', ';
                y += 20;
                sParameterExtension += 250 + ' ' + y + ', ';
                y += 200;
              }
              if (sParameterExtension !== '') {
                ctrl.pathSvgParameters += ' S ' + sParameterExtension;
              }
            }
            if (collectionNodeCount % 2 === 0) {
              if (collectionNodeCount === 2) {
                ctrl.svgHeight = ctrl.MIN_HEIGHT_FOR_PATH_SVG_PX;
              } else {
                ctrl.svgHeight = y - ctrl.EVEN_SVG_HEIGHT_OFFSET_PX;
              }
            } else {
              if (collectionNodeCount === 1) {
                ctrl.svgHeight = ctrl.MIN_HEIGHT_FOR_PATH_SVG_PX;
              } else {
                ctrl.svgHeight = y - ctrl.ODD_SVG_HEIGHT_OFFSET_PX;
              }
            }
          };

          ctrl.generatePathIconParameters = function() {
            var collectionNodes = ctrl.collection.getCollectionNodes();
            var iconParametersArray = [];
            iconParametersArray.push({
              thumbnailIconUrl:
                collectionNodes[0].getExplorationSummaryObject(
                ).thumbnail_icon_url.replace('subjects', 'inverted_subjects'),
              left: '225px',
              top: '35px',
              thumbnailBgColor:
                collectionNodes[0].getExplorationSummaryObject(
                ).thumbnail_bg_color
            });

            // Here x and y represent the co-ordinates for the icons in the
            // path.
            var x = ctrl.ICON_X_MIDDLE_PX;
            var y = ctrl.ICON_Y_INITIAL_PX;
            var countMiddleIcon = 1;

            for (var i = 1; i < ctrl.collection.getCollectionNodeCount(); i++) {
              if (countMiddleIcon === 0 && x === ctrl.ICON_X_MIDDLE_PX) {
                x = ctrl.ICON_X_LEFT_PX;
                y += ctrl.ICON_Y_INCREMENT_PX;
                countMiddleIcon = 1;
              } else if (countMiddleIcon === 1 && x === ctrl.ICON_X_MIDDLE_PX) {
                x = ctrl.ICON_X_RIGHT_PX;
                y += ctrl.ICON_Y_INCREMENT_PX;
                countMiddleIcon = 0;
              } else {
                x = ctrl.ICON_X_MIDDLE_PX;
                y += ctrl.ICON_Y_INCREMENT_PX;
              }
              iconParametersArray.push({
                thumbnailIconUrl:
                  collectionNodes[i].getExplorationSummaryObject(
                  ).thumbnail_icon_url.replace('subjects', 'inverted_subjects'),
                left: x + 'px',
                top: y + 'px',
                thumbnailBgColor:
                  collectionNodes[i].getExplorationSummaryObject(
                  ).thumbnail_bg_color
              });
            }
            return iconParametersArray;
          };

          ctrl.getExplorationUrl = function(explorationId) {
            return (
              '/explore/' + explorationId + '?collection_id=' +
              ctrl.collectionId);
          };

          ctrl.getExplorationTitlePosition = function(index) {
            if (index % 2 === 0) {
              return '8px';
            } else if ((index + 1) % 2 === 0 && (index + 1) % 4 !== 0) {
              return '30px';
            } else if ((index + 1) % 4 === 0) {
              return '-40px';
            }
          };

          ctrl.scrollToLocation = function(id) {
            $location.hash(id);
            $anchorScroll();
          };

          ctrl.closeOnClickingOutside = function() {
            ctrl.explorationCardIsShown = false;
          };

          ctrl.onClickStopPropagation = function($evt) {
            $evt.stopPropagation();
          };
          ctrl.$onInit = function() {
            $scope.$watch('$ctrl.collection', function(newValue) {
              if (newValue !== null) {
                ctrl.generatePathParameters();
              }
            }, true);
            LoaderService.showLoadingScreen('Loading');
            ctrl.collection = null;
            ctrl.collectionPlaythrough = null;
            ctrl.collectionId = UrlService.getCollectionIdFromUrl();
            ctrl.explorationCardIsShown = false;
            // The pathIconParameters is an array containing the co-ordinates,
            // background color and icon url for the icons generated on the
            // path.
            ctrl.pathIconParameters = [];
            ctrl.activeHighlightedIconIndex = -1;
            ctrl.MIN_HEIGHT_FOR_PATH_SVG_PX = 220;
            ctrl.ODD_SVG_HEIGHT_OFFSET_PX = 150;
            ctrl.EVEN_SVG_HEIGHT_OFFSET_PX = 280;
            ctrl.ICON_Y_INITIAL_PX = 35;
            ctrl.ICON_Y_INCREMENT_PX = 110;
            ctrl.ICON_X_MIDDLE_PX = 225;
            ctrl.ICON_X_LEFT_PX = 55;
            ctrl.ICON_X_RIGHT_PX = 395;
            ctrl.svgHeight = ctrl.MIN_HEIGHT_FOR_PATH_SVG_PX;
            ctrl.nextExplorationId = null;
            ctrl.whitelistedCollectionIdsForGuestProgress = (
              WHITELISTED_COLLECTION_IDS_FOR_SAVING_GUEST_PROGRESS);
            $anchorScroll.yOffset = -80;

            // Touching anywhere outside the mobile preview should hide it.
            document.addEventListener('touchstart', function() {
              if (ctrl.explorationCardIsShown === true) {
                ctrl.explorationCardIsShown = false;
              }
            });
            $http.get('/collection_handler/data/' + ctrl.collectionId).then(
              function(response) {
                response = response.data;
                angular.element('meta[itemprop="name"]').attr(
                  'content', response.meta_name);
                angular.element('meta[itemprop="description"]').attr(
                  'content', response.meta_description);
                angular.element('meta[property="og:title"]').attr(
                  'content', response.meta_name);
                angular.element('meta[property="og:description"]').attr(
                  'content', response.meta_description);
              }
            );

            $http.get('/collectionsummarieshandler/data', {
              params: {
                stringified_collection_ids: JSON.stringify([ctrl.collectionId])
              }
            }).then(
              function(response) {
                ctrl.collectionSummary = response.data.summaries[0];
              },
              function() {
                AlertsService.addWarning(
                  'There was an error while fetching the collection summary.');
              }
            );

            // Load the collection the learner wants to view.
            ReadOnlyCollectionBackendApiService.loadCollection(
              ctrl.collectionId).then(
              function(collection) {
                ctrl.collection = collection;

                PageTitleService.setPageTitle(
                  ctrl.collection.getTitle() + ' - Oppia');

                // Load the user's current progress in the collection. If the
                // user is a guest, then either the defaults from the server
                // will be used or the user's local progress, if any has been
                // made and the collection is whitelisted.
                var collectionAllowsGuestProgress = (
                  ctrl.whitelistedCollectionIdsForGuestProgress.indexOf(
                    ctrl.collectionId) !== -1);
                UserService.getUserInfoAsync().then(function(userInfo) {
                  LoaderService.hideLoadingScreen();
                  ctrl.isLoggedIn = userInfo.isLoggedIn();
                  if (!ctrl.isLoggedIn && collectionAllowsGuestProgress &&
                      GuestCollectionProgressService
                        .hasCompletedSomeExploration(ctrl.collectionId)) {
                    var completedExplorationIds = (
                      GuestCollectionProgressService.getCompletedExplorationIds(
                        ctrl.collection));
                    var nextExplorationId = (
                      GuestCollectionProgressService.getNextExplorationId(
                        ctrl.collection, completedExplorationIds));
                    ctrl.collectionPlaythrough = (
                      CollectionPlaythroughObjectFactory.create(
                        nextExplorationId, completedExplorationIds));
                  } else {
                    ctrl.collectionPlaythrough = collection.getPlaythrough();
                  }
                  ctrl.nextExplorationId =
                    ctrl.collectionPlaythrough.getNextExplorationId();

                  ctrl.isCompletedExploration = function(explorationId) {
                    var completedExplorationIds = (
                      ctrl.collectionPlaythrough.getCompletedExplorationIds());
                    return completedExplorationIds.indexOf(explorationId) > -1;
                  };
                });
              },
              function() {
                // TODO(bhenning): Handle not being able to load the collection.
                // NOTE TO DEVELOPERS: Check the backend console for an
                // indication as to why this error occurred; sometimes the
                // errors are noisy, so they are not shown to the user.
                AlertsService.addWarning(
                  'There was an error loading the collection.');
              }
            );
          };
        }
      ]
    };
  }
]);


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django_tasker.models

class Migration(migrations.Migration):

    dependencies = [
        ('django_tasker', '0006_auto_20170120_1122'),
    ]

    operations = [
        migrations.AlterField(
            model_name='taskinfo',
            name='status',
            field=models.IntegerField(choices=[(0, 'Created'), (1, 'Queued'), (2, 'Eager'), (3, 'Retry'), (4, 'Busy'), (5, 'Success'), (6, 'Błąd'), (7, 'Corrupted')], default=django_tasker.models.TaskStatus(0)),
        ),
    ]


text:
import { SystemContextProvider } from "v2/System"
import { SystemContextConsumer } from "v2/System"
import { renderWithLoadProgress } from "v2/System/Relay/renderWithLoadProgress"
import { SystemQueryRenderer } from "v2/System/Relay/SystemQueryRenderer"
import { IMocks } from "graphql-tools/dist/Interfaces"
import React from "react"
/* tslint:disable-next-line:no-query-renderer-import */
import { QueryRenderer } from "react-relay"
import {
  Environment,
  GraphQLTaggedNode,
  INetwork,
  OperationType,
  RecordSource,
  Store,
} from "relay-runtime"
import {
  createMockNetworkLayer,
  createMockNetworkLayer2,
} from "./createMockNetworkLayer"

export interface MockRelayRendererProps<T extends OperationType> {
  Component: React.ComponentType<any>
  componentProps?: object
  variables?: T["variables"]
  query: GraphQLTaggedNode
  /**
   * @deprecated use mockData and mockMutationResults
   */
  mockResolvers?: IMocks
  /**
   * @example
   * mockData={{order: {id: "my-order-id", lineItems: {...}}}}
   */
  mockData?: object
  /**
   * @example
   * mockMutationResults={{
   *   commerceCreateOrderWithArtworkId: {
   *     orderOrError: {
   *       order: {id: "my-order-id"}
   *     }
   *   }
   * }}
   */
  mockMutationResults?: object
  mockNetwork?: INetwork
}

export interface MockRelayRendererState {
  caughtError: {
    error: any
    errorInfo: any
  }
}

/**
 * Renders a tree of Relay containers with a mocked local instance of the
 * metaphysics schema.
 *
 * @note
 * Use this component in storybooks, but not tests. Because Relay works
 * asynchronously _and_ a tree may contain nested `QueryRenderer` components,
 * for tests you should usually use {@link renderRelayTree}.
 *
 * @param params.Component
 * The component that either is a Relay container or has children that are Relay
 * containers.
 *
 * @param params.variables
 * The optional variables that should be used in the operation. In most cases
 * you should be able to just hardcode these into the root query.
 *
 * @param params.query
 * The root GraphQL query.
 *
 * @param params.mockResolvers
 * @deprecated use params.mockData and params.mockMutationResults
 * A list of types/fields, that are part of metaphysics' schema, and the data to
 * return for those. See {@link https://www.apollographql.com/docs/graphql-tools/mocking.html#Customizing-mocks}
 *
 * @example
 *
   ```tsx
   jest.unmock("react-relay")

   const Artwork = createFragmentContainer(
     props => (
       <div>
         <span>{props.artwork.title}}</span>
         <img src={props.artwork.image.url} />
       </div>
     ),
     graphql`
       fragment MockRelayRenderer_artwork on Artwork {
         image {
           url
         }
       }
     `
   )

   it("renders a Relay tree", done => {
     const wrapper = mount(
       <MockRelayRenderer
         Component={Artwork}
         query={graphql`
           query AnotherMockRelayRendererQuery {
             artwork(id: "mona-lisa") {
               ...MockRelayRenderer_artwork
             }
           }
         `}
         mockResolvers={{
           Artwork: () => ({
             title: "Mona Lisa",
             image: {
               url: "http://test/image.jpg",
             },
           }),
         }}
       />
     )
     setTimeout(() => {
       expect(wrapper.find("span").text()).toEqual("Mona Lisa")
       expect(wrapper.find("img").props().src).toEqual("http://test/image.jpg")
       done()
     }, 10)
   })
   ```
  * @param params.mockMutationResults
  * @param params.mockData
  *
  */
export class MockRelayRenderer<T extends OperationType> extends React.Component<
  MockRelayRendererProps<T>,
  MockRelayRendererState
> {
  // @ts-expect-error STRICT_NULL_CHECK
  state = {
    caughtError: undefined,
  }

  componentDidCatch(error, errorInfo) {
    this.setState({ caughtError: { error, errorInfo } })
  }

  getRelayNetwork() {
    const {
      mockResolvers,
      mockData,
      mockMutationResults,
      mockNetwork,
    } = this.props

    if (mockNetwork) {
      if (mockResolvers || mockData || mockMutationResults) {
        throw new Error(
          "You cannot use mockNetwork with mockResolvers, mockData, or mockMutationResults"
        )
      }
      return mockNetwork
    }

    if ((mockData || mockMutationResults) && mockResolvers) {
      throw new Error(
        "You cannot use mockResolvers with either mockData or mockMutationResults"
      )
    }

    if (!mockData && !mockResolvers && !mockMutationResults) {
      throw new Error("You must supply mockData and/or mockMutationResults")
    }

    return mockData
      ? createMockNetworkLayer2({
          mockData,
          mockMutationResults,
        })
      : createMockNetworkLayer({
          Query: () => ({}),
          ...mockResolvers,
        })
  }

  render() {
    // TODO: When extracting these test utils to their own package, this check
    //       should probably become a custom TSLint rule, as there's no good way
    //       to test this in a generic way, plus with the rule we get fixes.
    if (
      typeof __webpack_require__ === "undefined" &&
      QueryRenderer === require("../../../__mocks__/react-relay").QueryRenderer
    ) {
      throw new Error(
        "The `react-relay` module has been mocked, be sure to unmock it with: " +
          '`jest.unmock("react-relay")`'
      )
    }

    if (this.state.caughtError) {
      // @ts-expect-error STRICT_NULL_CHECK
      const { error, errorInfo } = this.state.caughtError
      console.error({ error, errorInfo })
      return `Error occurred while rendering Relay component: ${error}`
    }

    const { Component, variables, query } = this.props

    const network = this.getRelayNetwork()
    const source = new RecordSource()
    const store = new Store(source)
    const environment = new Environment({
      network,
      store,
    })

    return (
      <SystemContextConsumer>
        {contextProps => (
          <SystemContextProvider
            {...contextProps}
            relayEnvironment={environment}
          >
            <SystemQueryRenderer
              // tslint:disable-next-line relay-operation-generics
              query={query}
              environment={environment}
              variables={variables || {}}
              // We rely on renderWithLoadProgress to throw an error in the test
              // env ASAP. When we extract these test helpers to their own package
              // that will need to be handled explicitly.
              render={renderWithLoadProgress(
                Component as any,
                this.props.componentProps
              )}
            />
          </SystemContextProvider>
        )}
      </SystemContextConsumer>
    )
  }
}


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

package com.google.vr180.api;

import com.google.vr180.CameraApi.CameraApiRequest;
import com.google.vr180.CameraApi.CameraApiResponse;
import java.io.IOException;

/**
 * A generic interface to execute commands on the camera.
 */
public interface CameraApiEndpoint {
  /** The priority of the request */
  enum Priority {
    PRIORITY_HIGH,
    PRIORITY_DEFAULT,
    PRIORITY_LOW;
  }

  /** Executes the request. */
  CameraApiResponse doRequest(CameraApiRequest request, Priority priority)
      throws IOException;
}


text:
package de.bund.bva.isyfact.polling.config;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;

import org.springframework.validation.annotation.Validated;

@Validated
public class IsyPollingProperties {

    private final Jmx jmx = new Jmx();

    private final Map<String, Cluster> cluster = new HashMap<>();

    public Jmx getJmx() {
        return jmx;
    }

    public Map<String, Cluster> getCluster() {
        return cluster;
    }

    public static class Jmx {

        private final Map<String, Verbindung> verbindungen = new HashMap<>();

        private String domain = "de.bund.bva.isyfact.polling";

        public String getDomain() {
            return domain;
        }

        public void setDomain(String domain) {
            this.domain = domain;
        }

        public Map<String, Verbindung> getVerbindungen() {
            return verbindungen;
        }

        public static class Verbindung {
            private String host;

            private int port;

            private String benutzer;

            private String passwort;

            @NotBlank
            public String getHost() {
                return host;
            }

            public void setHost(String host) {
                this.host = host;
            }

            @Min(0)
            @Max(65535)
            public int getPort() {
                return port;
            }

            public void setPort(int port) {
                this.port = port;
            }

            public String getBenutzer() {
                return benutzer;
            }

            public void setBenutzer(String benutzer) {
                this.benutzer = benutzer;
            }

            public String getPasswort() {
                return passwort;
            }

            public void setPasswort(String passwort) {
                this.passwort = passwort;
            }
        }
    }

    public static class Cluster {
        private final List<String> jmxverbindungen = new ArrayList<>();

        private String name;

        private int wartezeit;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getWartezeit() {
            return wartezeit;
        }

        public void setWartezeit(int wartezeit) {
            this.wartezeit = wartezeit;
        }

        public List<String> getJmxverbindungen() {
            return jmxverbindungen;
        }

        static class VerbindungsId {
            private String id;

            public String getId() {
                return id;
            }

            public void setId(String id) {
                this.id = id;
            }
        }
    }
}


text:
<?php

namespace Sonata\DoctrineORMAdminBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;

/**
 * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
 */
class AddTemplatesCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $overwrite = $container->getParameter('sonata.admin.configuration.admin_services');
        $templates = $container->getParameter('sonata_doctrine_orm_admin.templates');

        foreach ($container->findTaggedServiceIds('sonata.admin') as $id => $attributes) {
            if (!isset($attributes[0]['manager_type']) || $attributes[0]['manager_type'] != 'orm') {
                continue;
            }

            $definition = $container->getDefinition($id);

            if (!$definition->hasMethodCall('setFormTheme')) {
                $definition->addMethodCall('setFormTheme', [$templates['form']]);
            }

            if (isset($overwrite[$id]['templates']['form'])) {
                $this->mergeMethodCall($definition, 'setFormTheme', $overwrite[$id]['templates']['form']);
            }

            if (!$definition->hasMethodCall('setFilterTheme')) {
                $definition->addMethodCall('setFilterTheme', [$templates['filter']]);
            }

            if (isset($overwrite[$id]['templates']['filter'])) {
                $this->mergeMethodCall($definition, 'setFilterTheme', $overwrite[$id]['templates']['filter']);
            }
        }
    }

    /**
     * @param string $name
     * @param mixed  $value
     */
    public function mergeMethodCall(Definition $definition, $name, $value)
    {
        $methodCalls = $definition->getMethodCalls();

        foreach ($methodCalls as &$calls) {
            foreach ($calls as &$call) {
                if (is_string($call)) {
                    if ($call !== $name) {
                        continue 2;
                    }

                    continue 1;
                }

                $call = [array_merge($call[0], $value)];
            }
        }

        $definition->setMethodCalls($methodCalls);
    }
}


text:
package org.kie.workbench.common.forms.data.modeller.service.dataProvider;

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

import org.apache.commons.lang3.StringUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.forms.data.modeller.service.impl.AbstractDataObjectFinderTest;
import org.kie.workbench.common.forms.data.modeller.service.impl.DataObjectFormModelHandler;
import org.kie.workbench.common.forms.dynamic.model.config.SelectorData;
import org.kie.workbench.common.forms.dynamic.service.shared.FormRenderingContext;
import org.kie.workbench.common.forms.editor.service.shared.FormEditorRenderingContext;
import org.kie.workbench.common.forms.fields.shared.fieldTypes.relations.TableColumnMeta;
import org.kie.workbench.common.forms.fields.shared.fieldTypes.relations.multipleSubform.definition.MultipleSubFormFieldDefinition;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class BeanPropertiesProviderTest extends AbstractDataObjectFinderTest {

    protected FormEditorRenderingContext parentContext;

    protected FormRenderingContext context;

    protected BeanPropertiesProvider provider;

    protected TableColumnMeta currentEditedMeta;

    protected MultipleSubFormFieldDefinition field;

    protected int expectedFields;

    @Before
    public void init() {
        super.init();

        service = spy(service);

        provider = new BeanPropertiesProvider(service);

        currentEditedMeta = new TableColumnMeta();

        context = new FormEditorRenderingContext(path);

        context.setModel(currentEditedMeta);
    }

    @Test
    public void testGetAllModelProperties() {
        testGetModelProperties();
    }

    @Test
    public void testGetAllModelPropertiesWithExistingColumn() {
        currentEditedMeta.setProperty(NAME_PROPERTY);
        currentEditedMeta.setLabel(NAME_PROPERTY);
        testGetModelProperties();
    }

    @Test
    public void testSomeModelProperties() {
        testGetModelProperties(NAME_PROPERTY,
                               LAST_NAME_PROPERTY);
    }

    @Test
    public void testSomeModelPropertiesWithExistingColumn() {
        currentEditedMeta.setProperty(MARRIED_PROPERTY);
        currentEditedMeta.setLabel(MARRIED_PROPERTY);
        testGetModelProperties(NAME_PROPERTY,
                               LAST_NAME_PROPERTY);
    }

    protected void testGetModelProperties(String... columns) {
        field = new MultipleSubFormFieldDefinition();

        for (String column : columns) {
            field.getColumnMetas().add(new TableColumnMeta(column,
                                                           column));
        }

        List<String> bannedColumns = new ArrayList<>(Arrays.asList(columns));

        if (!StringUtils.isEmpty(currentEditedMeta.getProperty())) {
            bannedColumns.remove(currentEditedMeta.getProperty());
        }

        field.setStandaloneClassName(TYPE_NAME);

        parentContext = new FormEditorRenderingContext(path);

        parentContext.setModel(field);

        context.setParentContext(parentContext);

        expectedFields = DATA_OBJECT_VALID_FIELDS - bannedColumns.size();

        SelectorData data = provider.getSelectorData(context);

        verify(service).getDataObjectProperties(any(),
                                                any());

        assertNotNull(data);
        assertNotNull(data.getValues());
        assertNull(data.getSelectedValue());

        assertFalse(data.getValues().isEmpty());
        assertEquals(expectedFields,
                     data.getValues().size());

        for (String column : bannedColumns) {
            assertNull(data.getValues().get(column));
        }

        assertNull(data.getValues().get(DataObjectFormModelHandler.SERIAL_VERSION_UID));
        assertNull(data.getValues().get(PERSISTENCE_ID_PROPERTY));
    }

    @Test
    public void testWithoutParentContext() {
        SelectorData data = provider.getSelectorData(context);

        verify(service,
               never()).getDataObjectProperties(any(),
                                                any());

        assertNotNull(data);
        assertNotNull(data.getValues());
        assertTrue(data.getValues().isEmpty());
        assertNull(data.getSelectedValue());
    }
}


text:
/**
 * SECTION:element-vorbistag
 * @title: vorbistag
 * @see_also: #oggdemux, #oggmux, #vorbisparse, #GstTagSetter
 *
 * The vorbistags element can change the tag contained within a raw
 * vorbis stream. Specifically, it modifies the comments header packet
 * of the vorbis stream.
 *
 * The element will also process the stream as the #vorbisparse element does
 * so it can be used when remuxing an Ogg Vorbis stream, without additional
 * elements.
 *
 * Applications can set the tags to write using the #GstTagSetter interface.
 * Tags contained withing the vorbis bitstream will be picked up
 * automatically (and merged according to the merge mode set via the tag
 * setter interface).
 *
 * ## Example pipelines
 * |[
 * gst-launch-1.0 -v filesrc location=foo.ogg ! oggdemux ! vorbistag ! oggmux ! filesink location=bar.ogg
 * ]|
 *  This element is not useful with gst-launch-1.0, because it does not support
 * setting the tags on a #GstTagSetter interface. Conceptually, the element
 * will usually be used in this order though.
 *
 */

#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif

#include <glib.h>
#include <gst/tag/tag.h>
#include <gst/gsttagsetter.h>

#include <vorbis/codec.h>

#include "gstvorbistag.h"

GST_DEBUG_CATEGORY_EXTERN (vorbisparse_debug);
#define GST_CAT_DEFAULT vorbisparse_debug

static GstFlowReturn gst_vorbis_tag_parse_packet (GstVorbisParse * parse,
    GstBuffer * buffer);

#define gst_vorbis_tag_parent_class parent_class
G_DEFINE_TYPE_WITH_CODE (GstVorbisTag, gst_vorbis_tag,
    GST_TYPE_VORBIS_PARSE, G_IMPLEMENT_INTERFACE (GST_TYPE_TAG_SETTER, NULL));

static void
gst_vorbis_tag_class_init (GstVorbisTagClass * klass)
{
  GstVorbisParseClass *vorbisparse_class = GST_VORBIS_PARSE_CLASS (klass);
  GstElementClass *element_class = GST_ELEMENT_CLASS (klass);

  gst_element_class_set_static_metadata (element_class,
      "VorbisTag", "Formatter/Metadata",
      "Retags vorbis streams", "James Livingston <doclivingston@gmail.com>");

  vorbisparse_class->parse_packet = gst_vorbis_tag_parse_packet;
}

static void
gst_vorbis_tag_init (GstVorbisTag * tagger)
{
  /* nothing to do */
}

static GstFlowReturn
gst_vorbis_tag_parse_packet (GstVorbisParse * parse, GstBuffer * buffer)
{
  GstTagList *old_tags, *new_tags;
  const GstTagList *user_tags;
  GstVorbisTag *tagger;
  gchar *encoder = NULL;
  GstBuffer *new_buf;
  GstMapInfo map;
  gboolean do_parse = FALSE;

  gst_buffer_map (buffer, &map, GST_MAP_READ);
  /* just pass everything except the comments packet */
  if (map.size >= 1 && map.data[0] != 0x03)
    do_parse = TRUE;
  gst_buffer_unmap (buffer, &map);

  if (do_parse) {
    return GST_VORBIS_PARSE_CLASS (parent_class)->parse_packet (parse, buffer);
  }

  tagger = GST_VORBIS_TAG (parse);

  old_tags =
      gst_tag_list_from_vorbiscomment_buffer (buffer, (guint8 *) "\003vorbis",
      7, &encoder);
  user_tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (tagger));

  /* build new tag list */
  new_tags = gst_tag_list_merge (user_tags, old_tags,
      gst_tag_setter_get_tag_merge_mode (GST_TAG_SETTER (tagger)));
  gst_tag_list_unref (old_tags);

  new_buf =
      gst_tag_list_to_vorbiscomment_buffer (new_tags, (guint8 *) "\003vorbis",
      7, encoder);
  gst_buffer_copy_into (new_buf, buffer, GST_BUFFER_COPY_TIMESTAMPS, 0, -1);

  gst_tag_list_unref (new_tags);
  g_free (encoder);
  gst_buffer_unref (buffer);

  return GST_VORBIS_PARSE_CLASS (parent_class)->parse_packet (parse, new_buf);
}


text:
use lsp_server::{ErrorCode, RequestId, ResponseError};
use lsp_types::request::Request;

use crate::{
    lsp::{ServerRequest, ServerRequestId, ServerResponse},
    lsp_runtime_error::{LSPRuntimeError, LSPRuntimeResult},
};

pub(crate) struct LSPRequestDispatch<'state, TState> {
    request: lsp_server::Request,
    state: &'state mut TState,
}

impl<'state, TState> LSPRequestDispatch<'state, TState> {
    pub fn new(request: lsp_server::Request, state: &'state mut TState) -> Self {
        LSPRequestDispatch { request, state }
    }

    /// Calls handler if the LSPRequestDispatch's request's method matches the method
    /// of TRequest. Returns a Result which will be Ok if the handler was not called,
    /// or Err if the handler was called.
    /// Thus, multiple calls to `on_request_sync(...)?` can be chained. Doing so will
    /// cause LSPRequestDispatch to execute the first matching handler, if any.
    pub fn on_request_sync<TRequest: Request>(
        self,
        handler: fn(&mut TState, TRequest::Params) -> LSPRuntimeResult<TRequest::Result>,
    ) -> Result<Self, ServerResponse> {
        if self.request.method == TRequest::METHOD {
            match extract_request_params::<TRequest>(self.request) {
                Ok((request_id, params)) => {
                    let response = handler(self.state, params).and_then(|handler_result| {
                        serde_json::to_value(handler_result).map_err(|_err| {
                            LSPRuntimeError::UnexpectedError(
                                "Unable to serialize request response".to_string(),
                            )
                        })
                    });
                    let server_response = convert_to_lsp_response(request_id, response);

                    return Err(server_response);
                }
                Err(error) => {
                    return Err(convert_to_lsp_response(
                        ServerRequestId::from("default-relay-lsp-id".to_string()),
                        Err(error),
                    ));
                }
            }
        }

        Ok(self)
    }

    pub fn request(self) -> lsp_server::Request {
        self.request
    }
}

fn convert_to_lsp_response(
    id: RequestId,
    result: LSPRuntimeResult<serde_json::Value>,
) -> ServerResponse {
    match result {
        Ok(result) => ServerResponse {
            id,
            result: Some(result),
            error: None,
        },
        Err(runtime_error) => {
            let response_error: Option<ResponseError> = runtime_error.into();
            let response_error = response_error.unwrap_or_else(|| ResponseError {
                code: ErrorCode::RequestCanceled as i32,
                message: "Request Canceled".to_string(),
                data: None,
            });
            ServerResponse {
                id,
                result: None,
                error: Some(response_error),
            }
        }
    }
}

fn extract_request_params<R>(req: ServerRequest) -> LSPRuntimeResult<(ServerRequestId, R::Params)>
where
    R: Request,
{
    std::panic::catch_unwind(|| {
        req.extract(R::METHOD)
            .expect("extract_request_params: could not extract request params")
    })
    .map_err(|err| {
        LSPRuntimeError::UnexpectedError(format!(
            "panic in the `extract_request_params`: {:?}",
            err
        ))
    })
}

#[cfg(test)]
mod test {
    use lsp_types::{
        request::Request,
        request::{GotoDefinition, HoverRequest},
        Position, TextDocumentIdentifier, TextDocumentPositionParams, Url,
    };

    use crate::lsp_runtime_error::LSPRuntimeResult;

    use super::LSPRequestDispatch;

    #[test]
    fn calls_first_matching_request_handler() {
        let mut state: i32 = 0;
        let dispatch = LSPRequestDispatch::new(
            lsp_server::Request {
                id: "id".to_string().into(),
                method: "textDocument/definition".to_string(),
                params: serde_json::to_value(TextDocumentPositionParams {
                    text_document: TextDocumentIdentifier {
                        uri: Url::parse("https://example.net").unwrap(),
                    },
                    position: Position {
                        line: 0,
                        character: 0,
                    },
                })
                .unwrap(),
            },
            &mut state,
        );
        let dispatch = || -> Result<(), super::ServerResponse> {
            dispatch
                .on_request_sync::<HoverRequest>(hover_handler)?
                .on_request_sync::<GotoDefinition>(goto_definition_handler)?;
            Ok(())
        };
        let result = dispatch();
        assert!(result.is_err());
        assert_eq!(state, 2);
    }

    fn hover_handler(
        state: &mut i32,
        _params: <HoverRequest as Request>::Params,
    ) -> LSPRuntimeResult<<HoverRequest as Request>::Result> {
        *state = 1;
        Ok(None)
    }

    fn goto_definition_handler(
        state: &mut i32,
        _params: <GotoDefinition as Request>::Params,
    ) -> LSPRuntimeResult<<GotoDefinition as Request>::Result> {
        *state = 2;
        Ok(None)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use lsp_types::request::CodeActionRequest;
    use serde_json::json;

    #[test]
    fn test_extract_request_params_error() {
        let request_id = ServerRequestId::from("test-id".to_string());
        let request = ServerRequest {
            id: request_id,
            method: "textDocument/codeAction".to_string(),
            params: json!({
                "invalid_key": "invalid_value",
            }),
        };
        let result = extract_request_params::<CodeActionRequest>(request);
        // it returns an error, but not panic
        assert!(result.is_err());
    }
}


text:
require File.dirname(__FILE__) + '/../test_helper'
require 'link_controller'

# Re-raise errors caught by the controller.
class LinkController; def rescue_action(e) raise e end; end

class LinkControllerTest < Test::Unit::TestCase
  def setup
    @controller = LinkController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
  end

  # Replace this with your real tests.
  def test_truth
    assert true
  end
end


text:
module UiBibz::Ui::Concerns::NavigationConcern #:nodoc:
  extend ActiveSupport::Concern

  included do
    def spacer(num = 'auto')
      kls = " me-#{num}"
      @items.last.html_options[:class].nil? ? @items.last.html_options[:class] = kls : @items.last.html_options[:class] << kls
    end
  end
end


text:
require 'spec_helper'

shared_examples :layout do
  it "should have title" do
    render :inline => '<% @view_title = "My Title" -%>', :layout => @layout_name

    expect(response.body).to have_title("My Title - Go")
  end

  it "should display all the tabs" do
    render :inline => '
content
', :layout => @layout_name
    expect(response.body).to have_selector("li a", /AGENTS/)
    expect(response.body).to have_selector("li a", /ENVIRONMENTS/)
  end

  it "should not display auth block when user not logged in" do
    render :inline => '
content
', :layout => @layout_name
    expect(response.body).to_not have_selector('html body ul.principal')
  end

  it "should display username and logout botton if a user is logged in" do
    assign(:user, com.thoughtworks.go.server.domain.Username.new(CaseInsensitiveString.new("maulik suchak")))

    render :inline => '
content
', :layout => @layout_name
    expect(response.body).to have_selector(".current_user a[href='#']", "maulik suchak")
    expect(response.body).to have_selector(".current_user a[href='/preferences/notifications']", "Preferences")
    expect(response.body).to have_selector(".current_user .logout a[href='/auth/logout']", "Sign out")

    expect(response.body).to have_selector(".user .help a[href='https://gocd.io/help']", "Help")
  end

  it "should not display username and logout botton if anonymous user is logged in" do
    assign(:user, com.thoughtworks.go.server.domain.Username::ANONYMOUS)

    render :inline => '
content
', :layout => @layout_name

    expect(response.body).to have_selector(".user .help a[href='https://gocd.io/help']", "Help")

    expect(response.body).to_not have_selector(".current_user a[href='#']", "maulik suchak")
    expect(response.body).to_not have_selector(".current_user a[href='/preferences/notifications']", "Preferences")
    expect(response.body).to_not have_selector(".current_user a[href='/auth/logout']", "Sign out")
  end

  it "should link all the tabs right" do
    allow(view).to receive(:mycruise_available?).and_return(true)
    render :inline => "foo", :layout => @layout_name
    expect(response.body).to have_selector("a[href='/pipelines']", 'PIPELINES')
    expect(response.body).to have_selector("a[href='/path/to/agents']", 'AGENTS')
    expect(response.body).to have_selector("a[href='/path/to/environments']", 'ENVIRONMENTS')
    expect(response.body).to have_selector("a[href='https://gocd.io/help']", 'Help')
    expect(response.body).to have_selector("a[data-toggle='dropdown']", 'ADMIN')
  end

  it "should disable mycruise tab when mycruise is not available" do
    allow(view).to receive(:mycruise_available?).and_return(false)
    render :inline => "foo", :layout => @layout_name
    expect(response.body).to_not(have_selector("ul.current_user"))
  end

  it "should disable admin tab when user is not an administrator" do
    allow(view).to receive(:can_view_admin_page?).and_return(false)
    render :inline => "foo", :layout => @layout_name
    expect(response.body).to have_selector('li span', "ADMIN")
  end

  it "should enable admin tab when user is an administrator" do
    render :inline => "foo", :layout => @layout_name
    expect(response.body).to have_selector("li a[data-toggle='dropdown']", "ADMIN")
  end

  it "should render page error" do
    session[:notice] = FlashMessageModel.new("Some error message", "error")
    render :inline => "foo", :layout => @layout_name
    Capybara.string(response.body).all('div.flash').tap do |flash|
      expect(flash[0]).to have_selector("p.error", :text => "Some error message")
    end
  end

  it "should have a place holder in the header for error and warning counts" do
    render :inline => "foo", :layout => @layout_name
    expect(response.body).to have_selector("div#cruise_message_counts")
  end

  it "should have a place holder in the header for error and warning content" do
    render :inline => "foo", :layout => @layout_name
    expect(response.body).to have_selector("div#cruise_message_body", visible: false)
  end
end