text:
#pragma once

namespace humoto
{
    namespace pepper_mpc
    {
        static const char * BASE_VEL_VARIABLES_ID   = "base_vel";
        static const char * BODY_JERK_VARIABLES_ID   = "body_pos";

        /**
         * @brief Parameters of the motion
         */
        class HUMOTO_LOCAL RobotParameters : public humoto::config::ConfigurableBase
        {
            #define HUMOTO_CONFIG_SECTION_ID "RobotParameters"
            #define HUMOTO_CONFIG_CONSTRUCTOR RobotParameters
            #define HUMOTO_CONFIG_ENTRIES \
                HUMOTO_CONFIG_SCALAR_(base_radius) \
                HUMOTO_CONFIG_SCALAR_(max_nominal_base_velocity) \
                HUMOTO_CONFIG_SCALAR_(max_nominal_base_acceleration) \
                HUMOTO_CONFIG_SCALAR_(max_base_velocity) \
                HUMOTO_CONFIG_SCALAR_(max_base_acceleration) \
                HUMOTO_CONFIG_COMPOUND_(body_bounds)
            #include HUMOTO_CONFIG_DEFINE_ACCESSORS

            private:
                // meter
                etools::Matrix2    cop_bounds_;
                // meter / second
                etools::Matrix2    nominal_base_velocity_bounds_;
                // meter / second^2
                etools::Matrix2    nominal_base_acceleration_bounds_;
                // meter / second
                etools::Matrix2    base_velocity_bounds_;
                // meter / second^2
                etools::Matrix2    base_acceleration_bounds_;

            protected:
                /**
                 * @brief Finalize initialization
                 */
                void finalize()
                {
                    double cop_bound = getEncircledSquareSide(base_radius_)/2;

                    cop_bounds_ << -cop_bound, cop_bound,
                                   -cop_bound, cop_bound;

                    // ---

                    double velocity_bound = getEncircledSquareSide(max_nominal_base_velocity_)/2;

                    nominal_base_velocity_bounds_ <<   -velocity_bound, velocity_bound,
                                                       -velocity_bound, velocity_bound;

                    velocity_bound = getEncircledSquareSide(max_base_velocity_)/2;

                    base_velocity_bounds_ <<   -velocity_bound, velocity_bound,
                                               -velocity_bound, velocity_bound;

                    // ---

                    double acceleration_bound = getEncircledSquareSide(max_nominal_base_acceleration_)/2;

                    nominal_base_acceleration_bounds_ <<   -acceleration_bound, acceleration_bound,
                                                           -acceleration_bound, acceleration_bound;

                    acceleration_bound = getEncircledSquareSide(max_base_acceleration_)/2;

                    base_acceleration_bounds_ <<   -acceleration_bound, acceleration_bound,
                                                   -acceleration_bound, acceleration_bound;
                }

            public:
                // meter
                double base_radius_;
                // meter / second
                double max_nominal_base_velocity_;
                // meter / second^2
                double max_nominal_base_acceleration_;
                // meter / second
                double max_base_velocity_;
                // meter / second^2
                double max_base_acceleration_;

                // [lb, ub] meter
                etools::Matrix2 body_bounds_;

            public:
                void setDefaults()
                {
                    base_radius_    = 0.7;
                    max_nominal_base_velocity_      = 0.5;
                    max_nominal_base_acceleration_  = 1.0;
                    max_base_velocity_      = 1.4;
                    max_base_acceleration_  = 1.7;

                    body_bounds_    <<  -0.06, 0.06,
                                        -0.03, 0.03;
                    finalize();
                }

                /**
                 * @brief Default constructor
                 */
                RobotParameters()
                {
                    setDefaults();
                }

                /**
                 * @brief Get respective bounds
                 *
                 * @return [lb, ub] 2x2 matrix
                 */
                etools::Matrix2 getCoPBounds() const
                {
                    return(cop_bounds_);
                }

                /// @copydoc getCoPBounds
                etools::Matrix2 getNominalBaseVelocityBounds() const
                {
                    return(nominal_base_velocity_bounds_);
                }

                /// @copydoc getCoPBounds
                etools::Matrix2 getNominalBaseAccelerationBounds() const
                {
                    return(nominal_base_acceleration_bounds_);
                }

                /// @copydoc getCoPBounds
                etools::Matrix2 getBodyBounds() const
                {
                    return(body_bounds_);
                }
        };

        class MotionMode
        {
            public:
                enum Mode
                {
                    UNDEFINED = 0,
                    MAINTAIN_POSITION  = 1,
                    MAINTAIN_VELOCITY  = 2
                };
        };

        /**
         * @brief Parameters of the motion
         */
        class HUMOTO_LOCAL MotionParameters : public humoto::config::ConfigurableBase
        {
            #define HUMOTO_CONFIG_SECTION_ID "MotionParameters"
            #define HUMOTO_CONFIG_CONSTRUCTOR MotionParameters
            #define HUMOTO_CONFIG_ENTRIES \
                HUMOTO_CONFIG_COMPOUND_(base_velocity)\
                HUMOTO_CONFIG_COMPOUND_(base_position)\
                HUMOTO_CONFIG_SCALAR_(base_angular_velocity)\
                HUMOTO_CONFIG_ENUM_(motion_mode) \
                HUMOTO_CONFIG_SCALAR_(duration_ms)
            #include HUMOTO_CONFIG_DEFINE_ACCESSORS

            public:
                const static  std::ptrdiff_t  UNLIMITED_DURATION = -1;

                etools::Vector2     base_velocity_;
                etools::Vector2     base_position_;

                double              base_angular_velocity_;
                std::ptrdiff_t      duration_ms_;

                MotionMode::Mode    motion_mode_;

            public:
                /**
                 * @brief Default constructor
                 */
                MotionParameters()
                {
                    setDefaults();
                }

                /**
                 * @brief Default parameters of the walk
                 */
                void setDefaults()
                {
                    setIdle();
                }

                /**
                 * @brief Idle parameters of the motion
                 */
                void setIdle()
                {
                    base_velocity_.setZero();
                    base_position_.setZero();
                    base_angular_velocity_ =  0.0;
                    duration_ms_ = UNLIMITED_DURATION;
                    motion_mode_ = MotionMode::MAINTAIN_VELOCITY;
                }

                /**
                 * @brief Finalize & check
                 */
                void finalize()
                {
                }

                /**
                 * @brief Get base reference velocity
                 *
                 * @return base velocity
                 */
                etools::Vector2 getBaseVelocity() const
                {
                    return(base_velocity_);
                }

                /**
                 * @brief Get base reference position
                 *
                 * @return base position
                 */
                etools::Vector2 getBasePosition() const
                {
                    return(base_position_);
                }

                /**
                 * @brief Get theta increment
                 *
                 * @return theta increment
                 */
                double getBaseAngularVelocity() const
                {
                    return(base_angular_velocity_);
                }
        };

        /**
         * @brief Parameters of the MPC problem.
         */
        class HUMOTO_LOCAL MPCParameters : public humoto::config::StrictConfigurableBase
        {
            #define HUMOTO_CONFIG_SECTION_ID "MPCParameters"
            #define HUMOTO_CONFIG_CONSTRUCTOR MPCParameters
            #define HUMOTO_CONFIG_ENTRIES \
                HUMOTO_CONFIG_SCALAR_(preview_horizon_length) \
                HUMOTO_CONFIG_SCALAR_(sampling_time_ms) \
                HUMOTO_CONFIG_SCALAR_(subsampling_time_ms)
            #include HUMOTO_CONFIG_DEFINE_ACCESSORS

            private:
                /// Sampling time in seconds (T)
                double sampling_time_;

                /// Subsampling time in seconds (Ts)
                double subsampling_time_;

            protected:
                /**
                 * @brief Compute some derived variables.
                 */
                void finalize()
                {
                    // convert milliseconds to seconds
                    sampling_time_    = convertMillisecondToSecond(sampling_time_ms_);
                    // convert milliseconds to seconds
                    subsampling_time_ = convertMillisecondToSecond(subsampling_time_ms_);
                }

            public:
                /// Length of the preview horizon (N)
                std::size_t preview_horizon_length_;

                /// Sampling time in milliseconds (T_ms)
                std::size_t sampling_time_ms_;

                /// Subsampling time in milliseconds (Ts_ms)
                std::size_t subsampling_time_ms_;

            public:
                /**
                 * @brief Initialize to default values
                 */
                void setDefaults()
                {
                    preview_horizon_length_         = 15;
                    sampling_time_ms_               = 100;
                    subsampling_time_ms_            = sampling_time_ms_;

                    finalize();
                }

                /**
                 * @brief Constructor.
                 *
                 * @param[in] preview_horizon_len   Length of the preview horizon
                 * @param[in] sampling_time_ms      Sampling time in milliseconds
                 * @param[in] subsampling_time_ms   Subsampling time in milliseconds
                 */
                MPCParameters(  const std::size_t preview_horizon_len = 15,
                                const std::size_t sampling_time_ms = 100,
                                const std::size_t subsampling_time_ms = 100)
                {
                    preview_horizon_length_         = preview_horizon_len;
                    sampling_time_ms_               = sampling_time_ms;
                    subsampling_time_ms_            = subsampling_time_ms;

                    finalize();
                }

                /**
                 * @brief Get sampling time in seconds
                 *
                 * @return sampling time in seconds
                 */
                double getSamplingTime() const
                {
                    return (sampling_time_);
                }

                /**
                 * @brief Get subsampling time in seconds
                 *
                 * @return subsampling time in seconds
                 */
                double getSubsamplingTime() const
                {
                    return (subsampling_time_);
                }
        };
    }
}


text:
package softlayer_network_component

// DO NOT EDIT. THIS FILE WAS AUTOMATICALLY GENERATED

import (
	slapi "github.com/sudorandom/softlayer-go/slapi"

	gentypes "github.com/sudorandom/softlayer-go-gen/types"
)

// AddNetworkVlanTrunks - Add VLANs as trunks to a network component. The VLANs given must be assigned
// to your account, and on the router to which this network component is connected. The current native
// VLAN (networkVlanId/networkVlan) cannot be added as a trunk. This method should be called on a
// network component attached directly to customer assigned hardware, though all trunking operations
// will occur on the uplinkComponent. A current list of VLAN trunks for a network component on a
// customer server can be found at 'uplinkComponent->networkVlanTrunks'. This method returns an array
// of SoftLayer_Network_Vlans which were added as trunks. Any requested trunks which are already
// trunked will be silently ignored, and will not be returned. Configuration of network hardware is
// done asynchronously, do not depend on the return of this call as an indication that the newly
// trunked VLANs will be accessible.
func AddNetworkVlanTrunks(ID interface{}, networkVlans []gentypes.SoftLayer_Network_Vlan) slapi.Request {
	return slapi.Request{
		Service:    "SoftLayer_Network_Component",
		Method:     "addNetworkVlanTrunks",
		ID:         ID,
		Parameters: []interface{}{networkVlans},
	}
}

// ClearNetworkVlanTrunks - This method will remove all VLANs trunked to this network component. The
// native VLAN (networkVlanId/networkVlan) will remain active, and cannot be removed via the API.
// Returns a list of SoftLayer_Network_Vlan objects for which the trunks were removed.
func ClearNetworkVlanTrunks(ID interface{}) slapi.Request {
	return slapi.Request{
		Service: "SoftLayer_Network_Component",
		Method:  "clearNetworkVlanTrunks",
		ID:      ID,
	}
}

// GetCustomBandwidthDataByDate - no documentation
func GetCustomBandwidthDataByDate(ID interface{}, graphData gentypes.SoftLayer_Container_Graph) slapi.Request {
	return slapi.Request{
		Service:    "SoftLayer_Network_Component",
		Method:     "getCustomBandwidthDataByDate",
		ID:         ID,
		Parameters: []interface{}{graphData},
	}
}

// GetObject - no documentation
func GetObject(ID interface{}) slapi.Request {
	return slapi.Request{
		Service: "SoftLayer_Network_Component",
		Method:  "getObject",
		ID:      ID,
	}
}

// GetPortStatistics - **DEPRECATED - This operation will cease to function after April 4th, 2016 and
// will be removed from v3.2** Retrieve various network statistics. The network statistics are
// retrieved from the network device using snmpget. Below is a list of statistics retrieved: *
// Administrative Status * Operational Status * Maximum Transmission Unit * In Octets * Out Octets * In
// Unicast Packets * Out Unicast Packets * In Multicast Packets * Out Multicast Packets
func GetPortStatistics(ID interface{}) slapi.Request {
	return slapi.Request{
		Service: "SoftLayer_Network_Component",
		Method:  "getPortStatistics",
		ID:      ID,
	}
}

// RemoveNetworkVlanTrunks - Remove one or more VLANs currently attached to the uplinkComponent of this
// networkComponent. The VLANs given must be assigned to your account, and on the router the network
// component is connected to. If any VLANs not currently trunked are given, they will be silently
// ignored. This method should be called on a network component attached directly to customer assigned
// hardware, though all trunking operations will occur on the uplinkComponent. A current list of VLAN
// trunks for a network component on a customer server can be found at
// 'uplinkComponent->networkVlanTrunks'. Configuration of network hardware is done asynchronously, do
// not depend on the return of this call as an indication that the removed VLANs will be inaccessible.
func RemoveNetworkVlanTrunks(ID interface{}, networkVlans []gentypes.SoftLayer_Network_Vlan) slapi.Request {
	return slapi.Request{
		Service:    "SoftLayer_Network_Component",
		Method:     "removeNetworkVlanTrunks",
		ID:         ID,
		Parameters: []interface{}{networkVlans},
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace Ilios\Migrations;

use Doctrine\DBAL\Schema\Schema;
use App\Classes\MysqlMigration;

/**
 * Adds url and needs_accommodation columns to learner group table.
 */
final class Version20200902230650 extends MysqlMigration
{
    public function getDescription() : string
    {
        return 'Adds url and needs_accommodation columns to learner group table.';
    }

    public function up(Schema $schema) : void
    {
        $this->addSql('ALTER TABLE `group` ADD url VARCHAR(2000) DEFAULT NULL, ADD needs_accommodation TINYINT(1) NOT NULL');
    }

    public function down(Schema $schema) : void
    {
        $this->addSql('ALTER TABLE `group` DROP url, DROP needs_accommodation');
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Lumbsch & Vezda, Nova Hedwigia 50(1-2): 246 (1990)

#### Original name
Chroodiscus australiensis Vezda & Lumbsch

### Remarks
null


text:
import numpy as np

from robosuite.models.objects import MujocoGeneratedObject, PrimitiveObject
from robosuite.utils.mjcf_utils import get_size

class CylinderObject(PrimitiveObject):
    """
    A cylinder object.

    Args:
        size (2-tuple of float): (radius, half-length) size parameters for this cylinder object
    """

    def __init__(
        self,
        name,
        size=None,
        size_max=None,
        size_min=None,
        density=None,
        friction=None,
        rgba=None,
        solref=None,
        solimp=None,
        material=None,
        joints="default",
        obj_type="all",
        duplicate_collision_geoms=True,
    ):
        size = get_size(size, size_max, size_min, [0.07, 0.07], [0.03, 0.03])

        # We override solref, solimp, and joint default values for better stability
        if friction is None:
            friction = [1, 0.01, 0.001]
        if solref is None:
            solref = [0.01, 0.5]
        if joints == "default":
            joints = [{"type": "free", "damping": "0.0001"}]

        super().__init__(
            name=name,
            size=size,
            rgba=rgba,
            density=density,
            friction=friction,
            solref=solref,
            solimp=solimp,
            material=material,
            joints=joints,
            obj_type=obj_type,
            duplicate_collision_geoms=duplicate_collision_geoms,
        )

    def sanity_check(self):
        """
        Checks to make sure inputted size is of correct length

        Raises:
            AssertionError: [Invalid size length]
        """
        assert len(self.size) == 2, "cylinder size should have length 2"

    def _get_object_subtree(self):
        return self._get_object_subtree_(ob_type="cylinder")

    @staticmethod
    def get_collision_attrib_template():
        """
        Generates template with collision attributes for a given geom

        Extends super method for better stability for contacts

        Returns:
            dict: Initial template with `'pos'` and `'group'` already specified
        """
        template = MujocoGeneratedObject.get_collision_attrib_template()
        # Add condim value
        template["margin"] = "0.001"
        return template

    @property
    def bottom_offset(self):
        return np.array([0, 0, -1 * self.size[1]])

    @property
    def top_offset(self):
        return np.array([0, 0, self.size[1]])

    @property
    def horizontal_radius(self):
        return self.size[0]


text:
Our node-based unit tests system is the preferred way to test
JavaScript/TypeScript code in Zulip.  We prefer it over the [Casper
black-box whole-app testing](../testing/testing-with-casper.md),
system since it is much (>100x) faster and also easier to do correctly
than the Casper system.

You can run tests as follow:
```
    tools/test-js-with-node
```

The JS unit tests are written to work with node.  You can find them
in `frontend_tests/node_tests`.  Here is an example test from
`frontend_tests/node_tests/stream_data.js`:

```
(function test_get_by_id() {
    stream_data.clear_subscriptions();
    var id = 42;
    var sub = {
        name: 'Denmark',
        subscribed: true,
        color: 'red',
        stream_id: id
    };
    stream_data.add_sub('Denmark', sub);
    sub = stream_data.get_sub('Denmark');
    assert.equal(sub.color, 'red');
    sub = stream_data.get_sub_by_id(id);
    assert.equal(sub.color, 'red');
}());
```

The names of the node tests generally align with the names of the
modules they test.  If you modify a JS module in `static/js` you should
see if there are corresponding test in `frontend_tests/node_tests`.  If
there are, you should strive to follow the patterns of the existing tests
and add your own tests.

A good first test to read is
[general.js](https://github.com/zulip/zulip/blob/master/frontend_tests/node_tests/general.js).

## How the node tests work

Unlike the [casper unit tests](../testing/testing-with-casper.md),
which use the `phantomjs` browser connected to a running Zulip
development server, our node unit tests don't have a browser, don't
talk to a server, and generally don't use a complete virtual DOM (a
handful of tests use the `jsdom` library for this purpose) because
those slow down the tests a lot, and often don't add much value.

Instead, the preferred model for our unit tests is to mock DOM
manipulations (which in Zulip are almost exclusively done via
`jQuery`) using a custom library
[zjquery](https://github.com/zulip/zulip/blob/master/frontend_tests/zjsunit/zjquery.js).

The
[unit test file](https://github.com/zulip/zulip/blob/master/frontend_tests/node_tests/zjquery.js)
for `zjquery` is designed to be also serve as nice documentation for
how to use `zjquery`, and is **highly recommended reading** for anyone
working on or debugging the Zulip node tests.

Conceptually, the `zjquery` library provides minimal versions of most
`jQuery` DOM manipulation functions, and has a convenient system for
letting you set up return values for more complex functions.  For
example, if the code you'd like to test calls `$obj.find()`, you can
use `$obj.set_find_results(selector, $value)` to set up `zjquery` so
that calls to `$obj.find(selector)` will return `$value`. See the unit
test file for details.

This process of substituting `jQuery` functions with our own code for
testing purposes is known as "stubbing". `zjquery` does not stub all
possible interactions with the dom, as such, you may need to write out
the stub for a function you're calling in your patch. Typically the stub
is just placed in the test file, to prevent bloating of `zjquery`
with functions that are only used in a single test.

If you need to stub, you will see an error of this form:
`Error: You must create a stub for $("#foo").bar`

The `zjquery` library itself is only about 500 lines of code, and can
also be a useful resource if you're having trouble debugging DOM
access in the unit tests.

It is typically a good idea to figure out how to stub a given function
based on how other functions have been stubbed in the same file.

## Handling dependencies in unit tests

The other big challenge with doing unit tests for a JavaScript project
is that often one wants to limit the scope the production code being
run, just to avoid doing extra setup work that isn't relevant to the
code you're trying to test.  For that reason, each unit test file
explicitly declares all of the modules it depends on, with a few
different types of declarations depending on whether we want to:

-   Exercise the module's real code for deeper, more realistic testing?
-   Stub out the module's interface for more control, speed, and
    isolation?
-   Do some combination of the above?

For all the modules where you want to run actual code, add statements
like the following toward the top of your test file:

>     zrequire('util');
>     zrequire('stream_data');
>     zrequire('Filter', 'js/filter');

For modules that you want to completely stub out, use a pattern like
this:

>     set_global('page_params', {
>         email: 'bob@zulip.com'
>     });
>
>     // then maybe further down
>     page_params.email = 'alice@zulip.com';

One can similarly stub out functions in a module's exported interface
with either `noop` functions or actual code.

Finally, there's the hybrid situation, where you want to borrow some
of a module's real functionality but stub out other pieces. Obviously,
this is a pretty strong code smell that the other module might be
lacking in cohesion, but sometimes it's not worth going down the
rabbit hole of trying to improve that. The pattern here is this:

>     // Import real code.
>     zrequire('narrow_state');
>
>     // And later...
>     narrow_state.stream = function () {
>         return 'office';
>     };

## Creating new test modules

The test runner (`index.js`) automatically runs all .js files in the
`frontend_tests/node_tests` directory, so you can simply start editing a file
in that directory to create a new test.

## Coverage reports

You can automatically generate coverage reports for the JavaScript unit
tests like this:

```
    tools/test-js-with-node --coverage
```

If tests pass, you will get instructions to view coverage reports
in your browser.

Note that modules that we don't test *at all* aren't listed in the
report, so this tends to overstate how good our overall coverage is,
but it's accurate for individual files. You can also click a filename
to see the specific statements and branches not tested. 100% branch
coverage isn't necessarily possible, but getting to at least 80%
branch coverage is a good goal.

The overall project goal is to get to 100% node test coverage on all
data/logic modules (UI modules are lower priority for unit testing).

# Editor debugger integration

Our node test system is pretty simple, and it's possible to configure
the native debugger features of popular editors to allow stepping
through the code.  Below we document the editors where someone has put
together detailed instructions for how to do so.  Contributions of
notes for other editors are welcome!

## Webstorm integration setup

These instructions assume you're using the Vagrant development environment.

1. Set up [Vagrant in WebStorm][vagrant-webstorm].

2. In WebStorm, navigate to `Preferences -> Tools -> Vagrant` and
   configure the following:

    * `Instance folder` should be the root of the `zulip` repository on
      your host (where the Vagrantfile is located).
    * `Provider` should be `virtualbox` on macOS and Docker on Linux
    * In `Boxes`, choose the one used for Zulip (unless you use
      Virtualbox for other things, there should only be one option).

    You shouldn't need to set these additional settings:
    * `Vagrant executable` should already be correctly `vagrant`.
    * `Environment Variables` is not needed.

3. You'll now need to set up a WebStorm "Debug Configuration".  Open
   the `Run/Debug Configuration` menu and create a new `Node.js` config:
    1. Under `Node interpreter:` click the 3 dots to the right side and
      click on the little plus in the bottom left of the `Node.js
      Interpreters` window.
    1. Select `Add Remote...`.
        1. In the `Configure Node.js Remote Interpreter`, window select `Vagrant`
        1. Wait for WebStorm to connect to Vagrant. This will be displayed
           by the `Vagrant Host URL` section updating to contain the Vagrant
           SSH url, e.g. `ssh://vagrant@127.0.0.1:2222`.
        1. **Set the `Node.js interpreter path` to `/usr/local/bin/node`**
        1. Hit `OK` 2 times to get back to the `Run/Debug Configurations` window.
    1. Under `Working Directory` select the root `zulip` directory.
    1. Under `JavaScript file`, enter `frontend_tests/zjsunit/index.js`
     -- this is the root script for Zulip's node unit tests.

Congratulations!  You've now set up the integration.

## Running tests with the debugger

To use Webstorm to debug a given node test file, do the following:

1. Under `Application parameters` choose the node test file that you
   are trying to test (e.g. `frontend_tests/node_tests/message_store.js`).
1. Under `Path Mappings`, set `Project Root` to `/srv/zulip`
   (i.e. where the `zulip` Git repository is mounted in the Vagrant guest).
1. Use the WebStorm debugger; see [this overview][webstorm-debugging]
   for details on how to use it.

[webstorm-debugging]: https://blog.jetbrains.com/webstorm/2018/01/how-to-debug-with-webstorm/
[vagrant-webstorm]: https://www.jetbrains.com/help/webstorm/vagrant-support.html?section=Windows%20or%20Linux


text:
@interface DDPageModel : NSObject

@property (nonatomic, assign) CGFloat originalItemX;
@property (nonatomic, assign) CGFloat originalItemWidth;
@property (nonatomic, assign) CGFloat targetItemX;
@property (nonatomic, strong) UIColor *currentColor;
@property (nonatomic, strong) UIFont *titleFont;
@property (nonatomic, assign) CGFloat targetItemWidth;
@property (nonatomic, strong) UIViewController *viewController;
@property (nonatomic, assign) CGFloat indicatorCenterX;

@end


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

<application name="pa" timeStamp="Sun Mar 30 16:13:29 2014">

<property name="ProjectID" value="24f36759610545bd907b6c2095344dbb" type="ProjectID"/>
<property name="ProjectIteration" value="65" type="ProjectIteration"/>

<item name="Project Data">
<property name="SrcSetCount" value="1" type="SrcSetCount"/>
<property name="ConstraintSetCount" value="1" type="ConstraintSetCount"/>
<property name="DesignMode" value="RTL" type="DesignMode"/>
<property name="SynthesisStrategy" value="Vivado Synthesis Defaults" type="SynthesisStrategy"/>
<property name="ImplStrategy" value="Vivado Implementation Defaults" type="ImplStrategy"/>
</item>
<item name="Java Command Handlers">
<property name="AddSrc" value="2" type="JavaHandler"/>
<property name="CheckForUpdates" value="1" type="JavaHandler"/>
<property name="CloseHardwareSession" value="8" type="JavaHandler"/>
<property name="CloseProject" value="3" type="JavaHandler"/>
<property name="CoreView" value="1" type="JavaHandler"/>
<property name="CreateBlockDesign" value="1" type="JavaHandler"/>
<property name="CreateTopHDL" value="8" type="JavaHandler"/>
<property name="CustomizeCore" value="1" type="JavaHandler"/>
<property name="CustomizeRSBBlock" value="8" type="JavaHandler"/>
<property name="EditDelete" value="9" type="JavaHandler"/>
<property name="EditProperties" value="1" type="JavaHandler"/>
<property name="ExportHardware" value="3" type="JavaHandler"/>
<property name="Generate Target" value="8" type="JavaHandler"/>
<property name="LaunchOpenTarget" value="1" type="JavaHandler"/>
<property name="LaunchProgramFpga" value="8" type="JavaHandler"/>
<property name="NewProject" value="1" type="JavaHandler"/>
<property name="OpenHardwareSession" value="8" type="JavaHandler"/>
<property name="OpenProject" value="1" type="JavaHandler"/>
<property name="ProjectSettings" value="2" type="JavaHandler"/>
<property name="RegenerateRSBLayout" value="2" type="JavaHandler"/>
<property name="RunBitgen" value="32" type="JavaHandler"/>
<property name="RunImplementation" value="23" type="JavaHandler"/>
<property name="RunSynthesis" value="26" type="JavaHandler"/>
<property name="SaveDesign" value="1" type="JavaHandler"/>
<property name="SaveRSBDesign" value="10" type="JavaHandler"/>
<property name="SetTopNode" value="2" type="JavaHandler"/>
<property name="ShowView" value="9" type="JavaHandler"/>
<property name="SimulationRelaunch" value="44" type="JavaHandler"/>
<property name="SimulationRun" value="43" type="JavaHandler"/>
<property name="SimulationRunAll" value="4" type="JavaHandler"/>
<property name="SimulationRunForTime" value="78" type="JavaHandler"/>
<property name="ViewLayoutCmd" value="4" type="JavaHandler"/>
<property name="ViewTaskSynthesis" value="3" type="JavaHandler"/>
</item>

</application>
</document>


text:
using System.Collections.Generic;

namespace MvvmValidation.Internal
{
    internal class ValidationRuleCollection : List<ValidationRule>
    {
    }
}


text:
title: E-pos
inshort: Outlook e-pos
translator: Microsoft Cognitive Services
---

Outlook pos is die ander posprogramme komponent van Outlook op die web. Dit het 'n koppelvlak soortgelyk aan die e-pos deel van Outlook Web-toepassing voor dit. Die verstekaansig is 'n drie kolom vertoon met vouers en groepe aan die linkerkant, e-pos in die Sentrum, en aan die regterkant die geselekteerde boodskap. Assisteer die 2015 Outlook op die web bywerking, Microsoft bekendgestel die vermoë tot pin boodskappe, versorgde, argief, ontdoen en ryker beeld redigering kenmerke. [8] outlook pos bygevoeg die vermoë om aan ander dienste soos GitHub en Twitter deur kantoor 365 verbinders verbind. Vervolgingswaardige boodskappe in e-posse 'n gebruiker toelaat om te voltooi 'n taak van binne die e-pos, soos hertwiet 'n twiet geantwoord op Twitter of stel 'n byeenkoms datum op 'n kalender.


text:
namespace Stripe.BillingPortal
{
    using System.Collections.Generic;
    using Newtonsoft.Json;

    public class ConfigurationFeaturesSubscriptionCancelCancellationReasonOptions : INestedOptions
    {
        /// <summary>
        /// Whether the feature is enabled.
        /// </summary>
        [JsonProperty("enabled")]
        public bool? Enabled { get; set; }

        /// <summary>
        /// Which cancellation reasons will be given as options to the customer.
        /// </summary>
        [JsonProperty("options")]
        public List<string> Options { get; set; }
    }
}


text:
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.impl.gui.main.chat.conference;

import net.java.sip.communicator.service.protocol.*;

/**
 * The <tt>AdHocChatRoomWrapper</tt> is the representation of the
 * <tt>AdHocChatRoom</tt> in the GUI. It stores the information for the ad-hoc
 * chat room even when the corresponding protocol provider is not connected.
 *
 * @author Valentin Martinet
 */
public class AdHocChatRoomWrapper
{
    private final AdHocChatRoomProviderWrapper parentProvider;

    private AdHocChatRoom adHocChatRoom;

    private final String adHocChatRoomName;

    private final String adHocChatRoomID;

    /**
     * Creates a <tt>AdHocChatRoomWrapper</tt> by specifying the protocol
     * provider, the identifier and the name of the ad-hoc chat room.
     *
     * @param parentProvider the protocol provider to which the corresponding
     * ad-hoc chat room belongs
     * @param adHocChatRoomID the identifier of the corresponding ad-hoc chat
     * room
     * @param adHocChatRoomName the name of the corresponding  ad-hoc chat room
     */
    public AdHocChatRoomWrapper(AdHocChatRoomProviderWrapper parentProvider,
                                String adHocChatRoomID,
                                String adHocChatRoomName)
    {
        this.parentProvider = parentProvider;
        this.adHocChatRoomID = adHocChatRoomID;
        this.adHocChatRoomName = adHocChatRoomName;
    }

    /**
     * Creates a <tt>ChatRoomWrapper</tt> by specifying the corresponding chat
     * room.
     *
     * @param adHocChatRoom the chat room to which this wrapper corresponds.
     */
    public AdHocChatRoomWrapper( AdHocChatRoomProviderWrapper parentProvider,
                            AdHocChatRoom adHocChatRoom)
    {
        this(   parentProvider,
                adHocChatRoom.getIdentifier(),
                adHocChatRoom.getName());

        this.adHocChatRoom = adHocChatRoom;
    }

    /**
     * Returns the <tt>AdHocChatRoom</tt> that this wrapper represents.
     *
     * @return the <tt>AdHocChatRoom</tt> that this wrapper represents.
     */
    public AdHocChatRoom getAdHocChatRoom()
    {
        return adHocChatRoom;
    }

    /**
     * Sets the <tt>AdHocChatRoom</tt> that this wrapper represents.
     *
     * @param adHocChatRoom the ad-hoc chat room
     */
    public void setAdHocChatRoom(AdHocChatRoom adHocChatRoom)
    {
        this.adHocChatRoom = adHocChatRoom;
    }

    /**
     * Returns the ad-hoc chat room name.
     *
     * @return the ad-hoc chat room name
     */
    public String getAdHocChatRoomName()
    {
        return adHocChatRoomName;
    }

    /**
     * Returns the identifier of the ad-hoc chat room.
     *
     * @return the identifier of the ad-hoc chat room
     */
    public String getAdHocChatRoomID()
    {
        return adHocChatRoomID;
    }

    /**
     * Returns the parent protocol provider.
     *
     * @return the parent protocol provider
     */
    public AdHocChatRoomProviderWrapper getParentProvider()
    {
        return this.parentProvider;
    }
}


text:
package com.devzb.note.dao.model;

import java.util.Date;

public class NoteTag {
    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column note_tag.id
     *
     * @mbggenerated Sun Jan 22 16:30:49 GMT+08:00 2017
     */
    private Long id;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column note_tag.tag
     *
     * @mbggenerated Sun Jan 22 16:30:49 GMT+08:00 2017
     */
    private String tag;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column note_tag.gmt_created
     *
     * @mbggenerated Sun Jan 22 16:30:49 GMT+08:00 2017
     */
    private Date gmtCreated;

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column note_tag.id
     *
     * @return the value of note_tag.id
     *
     * @mbggenerated Sun Jan 22 16:30:49 GMT+08:00 2017
     */
    public Long getId() {
        return id;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column note_tag.id
     *
     * @param id the value for note_tag.id
     *
     * @mbggenerated Sun Jan 22 16:30:49 GMT+08:00 2017
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column note_tag.tag
     *
     * @return the value of note_tag.tag
     *
     * @mbggenerated Sun Jan 22 16:30:49 GMT+08:00 2017
     */
    public String getTag() {
        return tag;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column note_tag.tag
     *
     * @param tag the value for note_tag.tag
     *
     * @mbggenerated Sun Jan 22 16:30:49 GMT+08:00 2017
     */
    public void setTag(String tag) {
        this.tag = tag;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column note_tag.gmt_created
     *
     * @return the value of note_tag.gmt_created
     *
     * @mbggenerated Sun Jan 22 16:30:49 GMT+08:00 2017
     */
    public Date getGmtCreated() {
        return gmtCreated;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column note_tag.gmt_created
     *
     * @param gmtCreated the value for note_tag.gmt_created
     *
     * @mbggenerated Sun Jan 22 16:30:49 GMT+08:00 2017
     */
    public void setGmtCreated(Date gmtCreated) {
        this.gmtCreated = gmtCreated;
    }
}


text:
<tool id="goenrichment" name="GOEnrichment" version="2.0.1">
    <description>performs GO enrichment analysis of a set of gene products</description>
    <macros>
        <import>macros.xml</import>
    </macros>
    <requirements>
        <requirement type="package" version="2.0.1">goenrichment</requirement>
    </requirements>
    <command detect_errors="exit_code">goenrichment
--go '${go}'
--annotation '${annotation}'
--study '${study}'
#if str($population) != 'None'
--population '${population}'
#end if
--correction ${correction}
$summarize
$singletons
$relations
--graph_format $graph
--cut_off $cutoff
--mf_result '${mf_result}'
--bp_result '${bp_result}'
--cc_result '${cc_result}'
--mf_graph '${mf_graph}'
--bp_graph '${bp_graph}'
--cc_graph '${cc_graph}'
    </command>
    <inputs>
        <param name="go" type="data" format="obo,owl" label="Gene Ontology File" help="Gene Ontology file in OBO or OWL format (see @ONTOLOGY_URL@"/>
        <param name="annotation" type="data" format="tabular,txt" label="Gene Product Annotation File" help="Tabular file containing annotations from gene products to GO terms (in GAF or BLAST2GO format, or a simple two-column table)"/>
        <param name="study" type="data" format="txt" label="Study Set File" help="File containing the gene products corresponding to the study set (one per line)"/>
        <param name="population" type="data" format="txt" optional="true" label="Population Set File (Optional)" help="File containing the gene products corresponding to the population set (one per line). If no file is submitted, the population set will be the set of all gene products listed in the annotation file."/>
        <param name="correction" type="select" label="Multiple Test Correction" help="The multiple test correction method to use (Benjamini-Hochberg is recommended).">
            <option value="Benjamini-Hochberg" selected="true"/>
            <option value="SDA"/>
            <option value="Bonferroni-Holm"/>
            <option value="Sidak"/>
            <option value="Bonferroni"/>
        </param>
        <param name="cutoff" type="select" label="P-Value Cut-Off" help="The corrected p-value (or q-value) cut-off to apply for the graph output.">
            <option value="1.0"/>
            <option value="0.1"/>
            <option value="0.05"/>
            <option value="0.01" selected="true"/>
        </param>
        <param name="graph" type="select" label="Output Graph Format" help="The format of the output graphs (png, svg, or tabular for importing into cytoscape).">
            <option value="png" selected="true"/>
            <option value="svg"/>
            <option value="tabular"/>
        </param>
        <param name="summarize" type="boolean" checked="true" truevalue="--summarize_output" falsevalue="" label="Summarize Output" help="Whether to produce a summarized list of GO terms or the full list of those that are statistically significant"/>
        <param name="singletons" type="boolean" checked="true" truevalue="--ignore_singletons" falsevalue="" label="Exclude Singletons" help="Whether to exclude GO terms that are annotated to a single gene product in the study set"/>
        <param name="relations" type="boolean" checked="false" truevalue="--use_all_relations" falsevalue="" label="Use All Relations" help="Whether to infer annotations through 'part_of' and other non-hierarchical relationships, or only through 'is_a' relations"/>
    </inputs>
    <outputs>
        <data name="mf_result" format="tabular" label="${tool.name} on ${study.name} MF Result File"/>
        <data name="bp_result" format="tabular" label="${tool.name} on ${study.name} BP Result File"/>
        <data name="cc_result" format="tabular" label="${tool.name} on ${study.name} CC Result File"/>
        <data name="mf_graph" format="png" label="${tool.name} on ${study.name} MF Graph File">
            <change_format>
                <when input="graph" value="svg" format="svg"/>
                <when input="graph" value="tabular" format="tabular"/>
            </change_format>
        </data>
        <data name="bp_graph" format="png" label="${tool.name} on ${study.name} BP Graph File">
            <change_format>
                <when input="graph" value="svg" format="svg"/>
                <when input="graph" value="tabular" format="tabular"/>
            </change_format>
        </data>
        <data name="cc_graph" format="png" label="${tool.name} on ${study.name} CC Graph File">
            <change_format>
                <when input="graph" value="svg" format="svg"/>
                <when input="graph" value="tabular" format="tabular"/>
            </change_format>
        </data>
    </outputs>
    <tests>
        <test>
            <param name="go" ftype="obo" value="go.obo"/>
            <param name="annotation" ftype="txt" value="annotations.tab"/>
            <param name="study" ftype="txt" value="study.txt"/>
            <param name="summarize" value="false"/>
            <output name="mf_result" ftype="tabular" file="MF_result.txt" lines_diff="0"/>
        </test>
        <test>
            <param name="go" ftype="obo" value="go.obo"/>
            <param name="annotation" ftype="txt" value="annotations.tab"/>
            <param name="study" ftype="txt" value="study.txt"/>
            <param name="population" ftype="txt" value="population.txt"/>
            <param name="summarize" value="false"/>
            <output name="mf_result" ftype="tabular" file="MF_result.txt" lines_diff="0"/>
        </test>
    </tests>
    <help>
.. class:: infomark

GOEnrichment is a Java application that can be used to analyze gene product sets (e.g., from microarray or RNAseq experiments) for enriched GO terms.

-----

.. class:: infomark

GOEnrichment requires:

- A Gene Ontology file in either OBO or OWL format (see @ONTOLOGY_URL@).
- A tabular annotation file in GAF (@ANNOTATION_URL@) format, BLAST2GO format, or a simple two-column table (e.g. from BioMart) with gene product ids in the first column and GO terms in the second one.
- A list of gene products comprising the study set (a flat text file with one gene product per line).
- Optionally, a list of gene products comprising the population set (if none is submitted, the population set will be the set of gene products listed in the annotation file).

-----

.. class:: infomark

GOEnrichment produces a tabular result file and a graph file for each GO type (MF - Molecular Function, BP - Biological Process and CC - Cellular Component):

- The result file is a tabular list of all GO terms present in the study set and their respective p-values.
- The graph file can be either a png image, an svg image, or a text file for importing into cytoscape (together with the result file).

-----

.. class:: infomark

The graph is colored by p-value: terms with p-value above cut-off appear in white; and the color gets darker as the p-value decreases

.. image:: https://github.com/DanFaria/GOEnrichment/raw/master/Scale.png
   :width: 600
   :height: 315

(see the scale at https://github.com/DanFaria/GOEnrichment/blob/master/Scale.png). In addition to the name of each GO term, the graph
shows its frequency in the study set. Dashed edges indicate that one or more intermediate terms were ommited from the graph.

-----

.. class:: warningmark

Gene products listed in either the study or population set files that are not present in the annotation file will be ignored.
    </help>

    <citations>
        <citation type="bibtex">
@misc{githubgoenrichment,
  author = {Faria, Daniel},
  year = {2017},
  title = {GOEnrichment},
  publisher = {GitHub},
  journal = {GitHub repository},
  url = {https://github.com/DanFaria/GOEnrichment},
}
        </citation>
    </citations>

</tool>


text:
namespace cc {

class CC_EXPORT DebugBorderDrawQuad : public DrawQuad {
 public:
  DebugBorderDrawQuad();

  void SetNew(const SharedQuadState* shared_quad_state,
              const gfx::Rect& rect,
              const gfx::Rect& visible_rect,
              SkColor color,
              int width);

  void SetAll(const SharedQuadState* shared_quad_state,
              const gfx::Rect& rect,
              const gfx::Rect& opaque_rect,
              const gfx::Rect& visible_rect,
              bool needs_blending,
              SkColor color,
              int width);

  SkColor color;
  int width;

  virtual void IterateResources(const ResourceIteratorCallback& callback)
      OVERRIDE;

  static const DebugBorderDrawQuad* MaterialCast(const DrawQuad*);

 private:
  virtual void ExtendValue(base::debug::TracedValue* value) const OVERRIDE;
};

}  // namespace cc

#endif  // CC_QUADS_DEBUG_BORDER_DRAW_QUAD_H_


text:
@implementation UINavigationController (Helper)

- (id)findViewController:(Class)clazz
{
    for (UIViewController *viewController in self.viewControllers) {
        if ([viewController isKindOfClass:clazz]) {
            return viewController;
        }
    }

    return nil;
}
@end


text:
#include "tensorflow/dtensor/mlir/expansions/einsum_spmd_expander.h"

#include <string>

#include "absl/strings/string_view.h"
#include "llvm/Support/FormatVariadic.h"
#include "mlir/IR/BlockAndValueMapping.h"  // from @llvm-project
#include "mlir/IR/BuiltinTypes.h"  // from @llvm-project
#include "tensorflow/dtensor/cc/tensor_layout.h"
#include "tensorflow/dtensor/mlir/collectives.h"
#include "tensorflow/dtensor/mlir/layout_parsing.h"
#include "tensorflow/dtensor/mlir/shape_utils.h"
#include "tensorflow/dtensor/mlir/spmd_expander_common.h"
#include "tensorflow/dtensor/mlir/value_utils.h"

namespace tensorflow {
namespace dtensor {
namespace {

bool Equal(const ShardingSpec& a, const ShardingSpec& b) {
  return a.sharding_spec() == b.sharding_spec();
}

}  // namespace

// Einsum, like reductions, is implemented as a local operation followed by
// an all-reduce over dimensions that have been reduced.
StatusOr<mlir::Operation*> EinsumSPMDExpander::ExpandOp(mlir::Operation* op) {
  std::vector<Layout> input_layouts(op->getNumOperands());
  for (int i = 0; i < op->getNumOperands(); ++i) {
    TF_ASSIGN_OR_RETURN(auto layout,
                        ExtractLayoutFromOperand(op->getOperand(i)));
    if (!layout) return errors::InvalidArgument("missing layout for input ", i);
    input_layouts[i] = layout.value();
  }
  TF_ASSIGN_OR_RETURN(auto output_layout, ExtractSingleLayoutFromOp(op));
  if (!output_layout)
    return errors::InvalidArgument("is missing output layout.");

  std::vector<mlir::Value> new_inputs;
  Layout layout_after_einsum;
  absl::flat_hash_set<std::string> reduce_dims;
  TF_RETURN_IF_ERROR(MaybeRelayoutInputs(input_layouts, op,
                                         output_layout.value(), reduce_dims,
                                         layout_after_einsum, new_inputs));

  mlir::OpBuilder builder(op);
  mlir::BlockAndValueMapping mapping;
  for (int i = 0; i < op->getNumOperands(); ++i)
    mapping.map(op->getOperand(i), new_inputs[i]);
  mlir::Operation* new_op = builder.clone(*op, mapping);
  // Note that the output shape of new_op is cloned from op, so we need to
  // update to the local shape.
  new_op = InferSPMDExpandedLocalShape(new_op);

  if (!reduce_dims.empty()) {
    TF_ASSIGN_OR_RETURN(
        new_op, EmitAllReduce(builder, layout_after_einsum, reduce_dims, new_op,
                              kReduceOpAdd));
  }

  TF_ASSIGN_OR_RETURN(auto final_output,
                      EmitRelayout(new_op->getOpResult(0), layout_after_einsum,
                                   output_layout.value()));

  op->getOpResult(0).replaceAllUsesWith(final_output);
  op->erase();

  return final_output.getDefiningOp();
}

// TODO(power) -- we use a simplified equation parser here. consider
// refactoring einsum_spmd_expander and reusing the TF parser.
//
// Given the input equation, this has 3 outputs:
// reduced_dims: The set of mesh dimesions that we need to all reduce over.
// input_mappings: for each equation input, the map from the equation labels
//   to the tensor dimension of that label.
// output_mapping: as above, but for the equation output.
Status ExtractEquationRelations(
    absl::string_view equation, absl::flat_hash_set<char>& reduced_dims,
    std::vector<absl::flat_hash_map<char, std::vector<int>>>& input_mappings,
    absl::flat_hash_map<char, std::vector<int>>& output_mapping) {
  std::pair<std::string, std::string> parts = absl::StrSplit(equation, "->");
  absl::flat_hash_set<char> non_reduced_dims;

  // Mark kept dimensions from the output.
  for (const auto& char_and_index : llvm::enumerate(parts.second)) {
    // TODO(b/172691887): Support Broadcasting for einsum.
    if (char_and_index.value() == '.')
      return errors::Unimplemented(
          "Broadcasting is unimplemented for einsum. Received equation ",
          equation);
    non_reduced_dims.insert(char_and_index.value());

    // Construct the output mapping, note that output is not allowed to have
    // duplicate labels. This would mean that the datatype of output_mapping
    // should really be absl::flat_hash_map<char, int>, but having the same
    // type as the input_mapping keeps GetSpecsFromLabelsAndMap simpler.
    if (output_mapping.contains(char_and_index.value()))
      return errors::InvalidArgument("received label ", char_and_index.value(),
                                     " multiple times in the "
                                     "output of einsum equation ",
                                     equation);

    output_mapping[char_and_index.value()].emplace_back(char_and_index.index());
  }

  std::vector<std::string> inputs = absl::StrSplit(parts.first, ',');
  // Note that the TF einsum op only supports at most 2 inputs. This is slightly
  // confusing as the tf.einsum interface actually supports > 2 inputs.
  if (inputs.size() > 2)
    return errors::InvalidArgument(
        "einsum only supports at most 2 inputs received equation ", equation,
        " which has ", inputs.size(), " inputs");

  input_mappings.resize(inputs.size());

  // Compute the input mappings and keep track of labels which are reduced.
  for (int i = 0; i < inputs.size(); ++i) {
    for (const auto& char_and_index : llvm::enumerate(inputs[i])) {
      input_mappings[i][char_and_index.value()].emplace_back(
          char_and_index.index());
      if (!non_reduced_dims.contains(char_and_index.value()))
        reduced_dims.insert(char_and_index.value());
    }
  }

  return Status::OK();
}

// For a set of layouts and mappings from labels to offsets in the layouts,
// return a mappings of labels to ShardingSpecs.
// If the label appears multiples with different mesh dimensions in the
// sharding specs we raise an error if replicate_incompatible_dimensions is
// false. Otherwise we treat the dimension as if it were unsharded.
// Labels with unsharded dimensions are not recorded in the output.
StatusOr<absl::flat_hash_map<char, ShardingSpec>> GetLabelToShardingSpec(
    bool replicate_incompatible_dimensions, const std::vector<Layout>& layouts,
    const std::vector<absl::flat_hash_map<char, std::vector<int>>>& mappings) {
  absl::flat_hash_map<char, ShardingSpec> label_to_sharding_spec;
  absl::flat_hash_set<char> incompatible_labels;

  // For each mapping, identify the mesh dimension and whether it has been
  // reduced away.
  for (int index = 0; index < layouts.size(); ++index) {
    for (const auto& mapping : mappings[index]) {
      for (int offset : mapping.second) {
        if (offset >= layouts[index].rank())
          return errors::InvalidArgument(
              llvm::formatv(
                  "specified einsum equation for operand {0} tried to "
                  "read layout at offset {1}, but layout is {2} with rank "
                  "{3}",
                  index, offset, layouts[index].ToString(),
                  layouts[index].rank())
                  .str());

        const ShardingSpec& sharding_spec = layouts[index].dim(offset);

        if (label_to_sharding_spec.contains(mapping.first)) {
          if (Layout::IsShardedSpec(sharding_spec) &&
              !Equal(label_to_sharding_spec[mapping.first], sharding_spec)) {
            if (!replicate_incompatible_dimensions)
              return errors::InvalidArgument(
                  llvm::formatv(
                      "incompatible mesh dimensions in equation, label '{0}' "
                      "is mapped to mesh dimension '{1}' and '{2}'",
                      mapping.first, sharding_spec.sharding_spec(),
                      label_to_sharding_spec[mapping.first].sharding_spec())
                      .str());
            else
              incompatible_labels.insert(mapping.first);
          }
        } else if (Layout::IsShardedSpec(sharding_spec)) {
          label_to_sharding_spec[mapping.first] = sharding_spec;
        }
      }
    }
  }

  // For labels that had incompatible dimensions, treat them as replicated.
  // We would need to insert some all to all in the SPMD expansion for these.
  for (char label : incompatible_labels) label_to_sharding_spec.erase(label);

  return label_to_sharding_spec;
}

// The layout we generated may be invalid as the same dimension may be used
// multiple times. E.g. ab,bc->ac (i.e. matmul) with a and c sharded over the
// same dim. In this case we mark all such dimensions as replicated.
StatusOr<Layout> VerifyOrFixLayout(
    std::pair<std::vector<ShardingSpec>, absl::flat_hash_map<std::string, int>>
        pair,
    const Mesh& mesh) {
  std::vector<ShardingSpec> sharding_specs = pair.first;
  absl::flat_hash_map<std::string, int> dimension_use_count = pair.second;
  for (int i = 0; i < sharding_specs.size(); ++i)
    if (Layout::IsShardedSpec(sharding_specs[i]) &&
        dimension_use_count[sharding_specs[i].sharding_spec()] > 1)
      sharding_specs[i].set_sharding_spec(Layout::kUnshardedDim);
  return Layout::GetLayout(sharding_specs, mesh);
}

// Construct a layout on a given mesh from the label to tensor dimension map
// and the label to mesh_dimension map.
std::pair<std::vector<ShardingSpec>, absl::flat_hash_map<std::string, int>>
GetSpecsFromLabelsAndMap(
    const absl::flat_hash_map<char, std::vector<int>>& label_to_index,
    const absl::flat_hash_map<char, ShardingSpec>& label_to_sharding_spec) {
  int layout_rank = 0;
  for (const auto& label_and_indices : label_to_index)
    layout_rank += label_and_indices.second.size();

  std::vector<ShardingSpec> sharding_specs(layout_rank);
  absl::flat_hash_map<std::string, int> dimension_use_count;
  absl::flat_hash_set<std::string> dimension_use_set;
  for (const auto& label_and_indices : label_to_index) {
    const auto& loc = label_to_sharding_spec.find(label_and_indices.first);
    if (loc != label_to_sharding_spec.end()) {
      const ShardingSpec& sharding_spec = loc->second;
      for (int index : label_and_indices.second)
        sharding_specs[index] = sharding_spec;
      dimension_use_count[sharding_spec.sharding_spec()] +=
          label_and_indices.second.size();
    } else {
      for (int index : label_and_indices.second)
        sharding_specs[index].set_sharding_spec(Layout::kUnshardedDim);
    }
  }
  return std::make_pair(sharding_specs, dimension_use_count);
}

StatusOr<llvm::DenseMap<int, Layout>> EinsumSPMDExpander::ComputeLayoutForward(
    mlir::Operation* op, const llvm::DenseMap<int, Layout>& input_layouts) {
  if (input_layouts.empty()) return llvm::DenseMap<int, Layout>();

  TF_ASSIGN_OR_RETURN(auto mesh, ExtractDeviceMeshEnclosingCluster(op));

  // Need the mapping of input and output labels from the equation.
  auto einsum_op = mlir::cast<mlir::TF::EinsumOp>(op);
  size_t num_inputs = einsum_op.getNumOperands();
  std::string equation = einsum_op.equation().str();
  absl::flat_hash_set<char> reduced_dim_labels;
  std::vector<absl::flat_hash_map<char, std::vector<int>>> input_mappings;
  absl::flat_hash_map<char, std::vector<int>> output_mapping;

  TF_RETURN_IF_ERROR(ExtractEquationRelations(equation, reduced_dim_labels,
                                              input_mappings, output_mapping));
  if (input_mappings.size() != num_inputs)
    return errors::InvalidArgument(
        "Einsum equation ", equation, " has ", input_mappings.size(),
        " inputs but this op has ", num_inputs, " inputs.");

  // GetLabelToShardingSpec requires two inputs if the einsum equation needs
  // two inputs. We may only have one layout, so make other replicated. This
  // will have the same effect as only using the defined layout and using
  // replicated for all the missing dimensions.
  std::vector<Layout> layouts;
  for (int k = 0; k < num_inputs; ++k) {
    if (input_layouts.find(k) != input_layouts.end()) {
      layouts.emplace_back(input_layouts.lookup(k));
    } else {
      int rank = ValueRank(op->getOperand(k));
      if (rank < 0) return errors::InvalidArgument("No rank for input ", k);
      // This case can only happen when there are two inputs. Input 1 - k
      // is the other input. In this case of the if, input k is missing, so
      // this means that input 1 - k must be there.
      layouts.emplace_back(Layout::ReplicatedOnMesh(mesh, rank));
    }
  }

  // For each input, identify the mesh dimension
  TF_ASSIGN_OR_RETURN(
      auto input_label_to_sharding_spec,
      GetLabelToShardingSpec(
          /*replicate_incompatible_dimensions=*/true, layouts, input_mappings));
  // Compute output layout based on retained mesh dimensions
  TF_ASSIGN_OR_RETURN(
      const auto& output_layout,
      VerifyOrFixLayout(GetSpecsFromLabelsAndMap(output_mapping,
                                                 input_label_to_sharding_spec),
                        mesh));
  return llvm::DenseMap<int, Layout>({{0, output_layout}});
}

StatusOr<llvm::DenseMap<int, Layout>> EinsumSPMDExpander::ComputeLayoutBackward(
    mlir::Operation* op, const llvm::DenseMap<int, Layout>& output_layouts) {
  if (output_layouts.find(0) == output_layouts.end())
    return llvm::DenseMap<int, Layout>();

  const Layout output_layout = output_layouts.lookup(0);
  TF_ASSIGN_OR_RETURN(auto mesh, ExtractDeviceMeshEnclosingCluster(op));

  // Need the mapping of input and output labels from the equation.
  auto einsum_op = mlir::cast<mlir::TF::EinsumOp>(op);
  size_t num_inputs = einsum_op.getNumOperands();
  std::string equation = einsum_op.equation().str();
  absl::flat_hash_set<char> reduced_dim_labels;
  std::vector<absl::flat_hash_map<char, std::vector<int>>> input_mappings;
  absl::flat_hash_map<char, std::vector<int>> output_mapping;

  TF_RETURN_IF_ERROR(ExtractEquationRelations(equation, reduced_dim_labels,
                                              input_mappings, output_mapping));
  if (input_mappings.size() != num_inputs)
    return errors::InvalidArgument(
        "Einsum equation ", equation, " has ", input_mappings.size(),
        " inputs but this op has ", num_inputs, " inputs.");

  // Using the output mapping, construct an equation label to mesh dimension
  // mapping.
  TF_ASSIGN_OR_RETURN(auto output_label_to_sharding_spec,
                      GetLabelToShardingSpec(
                          /*replicate_incompatible_dimensions=*/false,
                          {output_layout}, {output_mapping}));

  // Defines a set of labels that could be set to Any. The conditions for an
  // operand label to be set to any are that 1) is not present in the output
  // and 2) is not repeated in any operand.
  absl::flat_hash_set<char> labels_for_any;
  for (const auto& operand_mapping : input_mappings)
    for (const auto& label_to_indices : operand_mapping)
      labels_for_any.insert(label_to_indices.first);

  // Filter repeated labels.
  for (const auto& operand_mapping : input_mappings)
    for (const auto& label_to_indices : operand_mapping)
      if (label_to_indices.second.size() > 1)
        labels_for_any.erase(label_to_indices.first);

  // Filter labels in output.
  for (const auto& label_to_indices : output_mapping)
    labels_for_any.erase(label_to_indices.first);

  llvm::DenseMap<int, Layout> input_layouts(num_inputs);

  // Derive operand sharding specs from output's sharding specs.
  for (size_t i = 0; i < num_inputs; ++i) {
    absl::flat_hash_map<char, std::vector<int>> labels_to_indices =
        input_mappings[i];
    std::pair<std::vector<ShardingSpec>, absl::flat_hash_map<std::string, int>>
        sharding_specs_and_dim_count = GetSpecsFromLabelsAndMap(
            labels_to_indices, output_label_to_sharding_spec);

    std::vector<ShardingSpec> sharding_specs =
        sharding_specs_and_dim_count.first;
    absl::flat_hash_map<std::string, int> dim_count =
        sharding_specs_and_dim_count.second;

    // Flip "unsharded" specs to "any" if they are present in the set.
    for (const auto& label_to_indices : labels_to_indices) {
      char label = label_to_indices.first;
      if (labels_for_any.contains(label)) {
        int index = label_to_indices.second[0];
        sharding_specs[index].set_sharding_spec(Layout::kAny);
      }
    }
    TF_ASSIGN_OR_RETURN(
        const auto& layout,
        VerifyOrFixLayout(std::make_pair(sharding_specs, dim_count), mesh));
    input_layouts[i] = layout;
  }

  return input_layouts;
}

// A few things we don't support, but could:
// * "xx->" or "xx->x": Trace like operation where at least one input dimension
//   for x is sharded. If both are sharded, we can compute the einsum on the
//   diagonal machines in the mesh and 0s on the off diagonals and then all
//   the much smaller matrix.
Status EinsumSPMDExpander::MaybeRelayoutInputs(
    const std::vector<Layout>& input_layouts, mlir::Operation* op,
    const Layout& output_layout, absl::flat_hash_set<std::string>& reduce_dims,
    Layout& einsum_layout, std::vector<mlir::Value>& new_inputs) {
  if (!mlir::isa<mlir::TF::EinsumOp>(op))
    return errors::InvalidArgument(
        "called einsum spmd expander but op is not Einsum.");

  mlir::TF::EinsumOp einsum = mlir::cast<mlir::TF::EinsumOp>(op);
  std::vector<absl::flat_hash_map<char, std::vector<int>>> input_mappings;
  absl::flat_hash_map<char, std::vector<int>> output_mapping;
  absl::flat_hash_set<char> contracting_labels;
  absl::flat_hash_set<char> all_labels;
  TF_RETURN_IF_ERROR(ExtractEquationRelations(einsum.equation().str(),
                                              contracting_labels,
                                              input_mappings, output_mapping));

  for (const auto& input_mapping : input_mappings)
    for (const auto& char_and_positions : input_mapping)
      all_labels.emplace(char_and_positions.first);

  // We will update this array throughout this function with the following rules
  // 1. The sharding of a label which is not in the map is unknown.
  // 2. Once the sharding of label becomes known and is unsharded, we
  //    won't change that.
  TF_ASSIGN_OR_RETURN(auto input_label_to_sharding_spec,
                      GetLabelToShardingSpec(
                          /*replicate_incompatible_dimensions=*/false,
                          input_layouts, input_mappings));

  TF_ASSIGN_OR_RETURN(const auto output_label_to_sharding_spec,
                      GetLabelToShardingSpec(
                          /*replicate_incompatible_dimensions=*/false,
                          {output_layout}, {output_mapping}));

  for (const char label : all_labels) {
    if (input_label_to_sharding_spec.contains(label) &&
        output_label_to_sharding_spec.contains(label) &&
        !Equal(input_label_to_sharding_spec[label],
               output_label_to_sharding_spec.find(label)->second))
      return errors::InvalidArgument(
          "for label ", label, " input and output layouts are sharded on ",
          " non-equal dimensions ",
          input_label_to_sharding_spec[label].sharding_spec(), " and ",
          output_label_to_sharding_spec.find(label)->second.sharding_spec(),
          "respectively");
  }

  // First priority is to ensure that labels which occur at least twice on one
  // side never get sharded, as we cannot deal with that. This corresponds to
  // taking a trace on that input, which will require us to be unsharded.
  for (const auto& input_mapping : input_mappings)
    for (const auto& char_and_positions : input_mapping)
      if (char_and_positions.second.size() > 1)
        input_label_to_sharding_spec[char_and_positions.first]
            .set_sharding_spec(Layout::kUnshardedDim);

  absl::flat_hash_map<std::string, absl::flat_hash_set<char>>
      sharding_dim_to_non_contracting_labels;
  absl::flat_hash_map<std::string, absl::flat_hash_set<char>>
      sharding_dim_to_contracting_labels;
  for (const auto& label_and_spec : input_label_to_sharding_spec) {
    if (Layout::IsShardedSpec(label_and_spec.second)) {
      if (contracting_labels.contains(label_and_spec.first))
        sharding_dim_to_contracting_labels[label_and_spec.second
                                               .sharding_spec()]
            .insert(label_and_spec.first);
      else
        sharding_dim_to_non_contracting_labels[label_and_spec.second
                                                   .sharding_spec()]
            .insert(label_and_spec.first);
    }
  }

  // If a non-contracting dimension is sharded in the output and non-sharded
  // in the input and no other label is sharded on that dimension, then shard
  // it.
  // This handles the *,x . x,* -> *,y case and also if batch dimensions are
  // sharded on the output but not the input.
  for (const char label : all_labels) {
    // Note that only sharded labels are in output_label_to_sharding_spec, so
    // there is no need to check that the spec is sharded.
    if (!contracting_labels.contains(label) &&
        output_label_to_sharding_spec.contains(label) &&
        !input_label_to_sharding_spec.contains(label)) {
      const ShardingSpec& sharding_spec =
          output_label_to_sharding_spec.find(label)->second;
      const std::string& string_spec = sharding_spec.sharding_spec();
      if (!sharding_dim_to_non_contracting_labels.contains(string_spec) &&
          !sharding_dim_to_contracting_labels.contains(string_spec)) {
        input_label_to_sharding_spec[label] = sharding_spec;
        sharding_dim_to_non_contracting_labels[string_spec].insert(label);
      }
    }
  }

  // Handle the case when two non-contracting dimensions are have the same
  // sharding spec.
  // Note that the case of three non-contracting dimensions having the same
  // sharding spec is impossible. Since there are at most two inputs, at least
  // one input would have two dimensions with the same sharing spec.
  // This handles the y,x . x,y -> *,y case.
  absl::flat_hash_set<std::string> dims_with_multiple_labels;
  for (const auto& spec_and_labels : sharding_dim_to_non_contracting_labels) {
    if (spec_and_labels.second.size() > 1) {
      assert(spec_and_labels.second.size() == 2);
      dims_with_multiple_labels.insert(spec_and_labels.first);
    }
  }
  for (const auto& dim : dims_with_multiple_labels) {
    // TODO(bfontain): Update this to pick default label to keep based on shape.
    char label_to_keep = 0xFF;
    // Note that all these conditions evaluated in the loop below are mutually
    // as exclusive as no two labels in the output have the same sharding
    // spec.
    // If the no label is found we choose the lexicographically least label to
    // keep this stable with respect to ordering.
    for (const char label : sharding_dim_to_non_contracting_labels[dim]) {
      if (output_label_to_sharding_spec.contains(label) &&
          output_label_to_sharding_spec.find(label)->second.sharding_spec() ==
              dim) {
        label_to_keep = label;
        break;
      } else if (label < label_to_keep) {
        label_to_keep = label;
      }
    }
    for (const char label : sharding_dim_to_non_contracting_labels[dim])
      if (label != label_to_keep)
        input_label_to_sharding_spec[label].set_sharding_spec(
            Layout::kUnshardedDim);
    sharding_dim_to_non_contracting_labels[dim].clear();
    sharding_dim_to_non_contracting_labels[dim].insert(label_to_keep);
  }

  // Handle the case where a non-contracting and contracting dim have the same
  // sharding spec. For now we always unshard the contracting axis. Note that
  // this is safe.
  // This handles the case x,y . *,y -> x,y
  for (const auto& spec_and_labels : sharding_dim_to_contracting_labels) {
    if (!spec_and_labels.second.empty() &&
        !sharding_dim_to_non_contracting_labels[spec_and_labels.first]
             .empty()) {
      assert(spec_and_labels.second.size() == 1);
      assert(sharding_dim_to_non_contracting_labels[spec_and_labels.first]
                 .size() == 1);
      input_label_to_sharding_spec[*spec_and_labels.second.begin()]
          .set_sharding_spec(Layout::kUnshardedDim);
    }
  }

  // Relayout the inputs
  mlir::OpBuilder builder(op);
  new_inputs.resize(input_mappings.size());
  for (int i = 0; i < input_mappings.size(); ++i) {
    TF_ASSIGN_OR_RETURN(
        const Layout new_input_layout,
        VerifyOrFixLayout(GetSpecsFromLabelsAndMap(
                              input_mappings[i], input_label_to_sharding_spec),
                          output_layout.mesh()));

    TF_ASSIGN_OR_RETURN(
        new_inputs[i],
        EmitRelayout(op->getOperand(i), input_layouts[i], new_input_layout));
  }

  TF_ASSIGN_OR_RETURN(
      einsum_layout,
      VerifyOrFixLayout(GetSpecsFromLabelsAndMap(output_mapping,
                                                 input_label_to_sharding_spec),
                        output_layout.mesh()));

  for (const auto& contracting : contracting_labels)
    reduce_dims.emplace(
        input_label_to_sharding_spec[contracting].sharding_spec());

  return Status::OK();
}

}  // namespace dtensor
}  // namespace tensorflow


text:
CONTRIBUTORS
============

Shapeshifter will get better, bigger and more awesome by a collaborative effort.

The following people have worked on this project:
- John in 't Hout (johnhout)
- Cees van Egmond (ceesvanegmond)
- Emre Koç (Emroni)


text:
package big

import (
	"errors"
	"fmt"
	"io"
	"strconv"
	"strings"
)

func ratTok(ch rune) bool {
	return strings.ContainsRune("+-/0123456789.eE", ch)
}

var ratZero Rat
var _ fmt.Scanner = &ratZero // *Rat must implement fmt.Scanner

// Scan is a support routine for fmt.Scanner. It accepts the formats
// 'e', 'E', 'f', 'F', 'g', 'G', and 'v'. All formats are equivalent.
func (z *Rat) Scan(s fmt.ScanState, ch rune) error {
	tok, err := s.Token(true, ratTok)
	if err != nil {
		return err
	}
	if !strings.ContainsRune("efgEFGv", ch) {
		return errors.New("Rat.Scan: invalid verb")
	}
	if _, ok := z.SetString(string(tok)); !ok {
		return errors.New("Rat.Scan: invalid syntax")
	}
	return nil
}

// SetString sets z to the value of s and returns z and a boolean indicating
// success. s can be given as a (possibly signed) fraction "a/b", or as a
// floating-point number optionally followed by an exponent.
// If a fraction is provided, both the dividend and the divisor may be a
// decimal integer or independently use a prefix of "0b", "0" or "0o",
// or "0x" (or their upper-case variants) to denote a binary, octal, or
// hexadecimal integer, respectively. The divisor may not be signed.
// If a floating-point number is provided, it may be in decimal form or
// use any of the same prefixes as above but for "0" to denote a non-decimal
// mantissa. A leading "0" is considered a decimal leading 0; it does not
// indicate octal representation in this case.
// An optional base-10 "e" or base-2 "p" (or their upper-case variants)
// exponent may be provided as well, except for hexadecimal floats which
// only accept an (optional) "p" exponent (because an "e" or "E" cannot
// be distinguished from a mantissa digit). If the exponent's absolute value
// is too large, the operation may fail.
// The entire string, not just a prefix, must be valid for success. If the
// operation failed, the value of z is undefined but the returned value is nil.
func (z *Rat) SetString(s string) (*Rat, bool) {
	if len(s) == 0 {
		return nil, false
	}
	// len(s) > 0

	// parse fraction a/b, if any
	if sep := strings.Index(s, "/"); sep >= 0 {
		if _, ok := z.a.SetString(s[:sep], 0); !ok {
			return nil, false
		}
		r := strings.NewReader(s[sep+1:])
		var err error
		if z.b.abs, _, _, err = z.b.abs.scan(r, 0, false); err != nil {
			return nil, false
		}
		// entire string must have been consumed
		if _, err = r.ReadByte(); err != io.EOF {
			return nil, false
		}
		if len(z.b.abs) == 0 {
			return nil, false
		}
		return z.norm(), true
	}

	// parse floating-point number
	r := strings.NewReader(s)

	// sign
	neg, err := scanSign(r)
	if err != nil {
		return nil, false
	}

	// mantissa
	var base int
	var fcount int // fractional digit count; valid if <= 0
	z.a.abs, base, fcount, err = z.a.abs.scan(r, 0, true)
	if err != nil {
		return nil, false
	}

	// exponent
	var exp int64
	var ebase int
	exp, ebase, err = scanExponent(r, true, true)
	if err != nil {
		return nil, false
	}

	// there should be no unread characters left
	if _, err = r.ReadByte(); err != io.EOF {
		return nil, false
	}

	// special-case 0 (see also issue #16176)
	if len(z.a.abs) == 0 {
		return z.norm(), true
	}
	// len(z.a.abs) > 0

	// The mantissa may have a radix point (fcount <= 0) and there
	// may be a nonzero exponent exp. The radix point amounts to a
	// division by base**(-fcount), which equals a multiplication by
	// base**fcount. An exponent means multiplication by ebase**exp.
	// Multiplications are commutative, so we can apply them in any
	// order. We only have powers of 2 and 10, and we split powers
	// of 10 into the product of the same powers of 2 and 5. This
	// may reduce the size of shift/multiplication factors or
	// divisors required to create the final fraction, depending
	// on the actual floating-point value.

	// determine binary or decimal exponent contribution of radix point
	var exp2, exp5 int64
	if fcount < 0 {
		// The mantissa has a radix point ddd.dddd; and
		// -fcount is the number of digits to the right
		// of '.'. Adjust relevant exponent accordingly.
		d := int64(fcount)
		switch base {
		case 10:
			exp5 = d
			fallthrough // 10**e == 5**e * 2**e
		case 2:
			exp2 = d
		case 8:
			exp2 = d * 3 // octal digits are 3 bits each
		case 16:
			exp2 = d * 4 // hexadecimal digits are 4 bits each
		default:
			panic("unexpected mantissa base")
		}
		// fcount consumed - not needed anymore
	}

	// take actual exponent into account
	switch ebase {
	case 10:
		exp5 += exp
		fallthrough // see fallthrough above
	case 2:
		exp2 += exp
	default:
		panic("unexpected exponent base")
	}
	// exp consumed - not needed anymore

	// apply exp5 contributions
	// (start with exp5 so the numbers to multiply are smaller)
	if exp5 != 0 {
		n := exp5
		if n < 0 {
			n = -n
			if n < 0 {
				// This can occur if -n overflows. -(-1 << 63) would become
				// -1 << 63, which is still negative.
				return nil, false
			}
		}
		if n > 1e6 {
			return nil, false // avoid excessively large exponents
		}
		pow5 := z.b.abs.expNN(natFive, nat(nil).setWord(Word(n)), nil, false) // use underlying array of z.b.abs
		if exp5 > 0 {
			z.a.abs = z.a.abs.mul(z.a.abs, pow5)
			z.b.abs = z.b.abs.setWord(1)
		} else {
			z.b.abs = pow5
		}
	} else {
		z.b.abs = z.b.abs.setWord(1)
	}

	// apply exp2 contributions
	if exp2 < -1e7 || exp2 > 1e7 {
		return nil, false // avoid excessively large exponents
	}
	if exp2 > 0 {
		z.a.abs = z.a.abs.shl(z.a.abs, uint(exp2))
	} else if exp2 < 0 {
		z.b.abs = z.b.abs.shl(z.b.abs, uint(-exp2))
	}

	z.a.neg = neg && len(z.a.abs) > 0 // 0 has no sign

	return z.norm(), true
}

// scanExponent scans the longest possible prefix of r representing a base 10
// ("e", "E") or a base 2 ("p", "P") exponent, if any. It returns the
// exponent, the exponent base (10 or 2), or a read or syntax error, if any.
//
// If sepOk is set, an underscore character "_" may appear between successive
// exponent digits; such underscores do not change the value of the exponent.
// Incorrect placement of underscores is reported as an error if there are no
// other errors. If sepOk is not set, underscores are not recognized and thus
// terminate scanning like any other character that is not a valid digit.
//
//	exponent = ( "e" | "E" | "p" | "P" ) [ sign ] digits .
//	sign     = "+" | "-" .
//	digits   = digit { [ '_' ] digit } .
//	digit    = "0" ... "9" .
//
// A base 2 exponent is only permitted if base2ok is set.
func scanExponent(r io.ByteScanner, base2ok, sepOk bool) (exp int64, base int, err error) {
	// one char look-ahead
	ch, err := r.ReadByte()
	if err != nil {
		if err == io.EOF {
			err = nil
		}
		return 0, 10, err
	}

	// exponent char
	switch ch {
	case 'e', 'E':
		base = 10
	case 'p', 'P':
		if base2ok {
			base = 2
			break // ok
		}
		fallthrough // binary exponent not permitted
	default:
		r.UnreadByte() // ch does not belong to exponent anymore
		return 0, 10, nil
	}

	// sign
	var digits []byte
	ch, err = r.ReadByte()
	if err == nil && (ch == '+' || ch == '-') {
		if ch == '-' {
			digits = append(digits, '-')
		}
		ch, err = r.ReadByte()
	}

	// prev encodes the previously seen char: it is one
	// of '_', '0' (a digit), or '.' (anything else). A
	// valid separator '_' may only occur after a digit.
	prev := '.'
	invalSep := false

	// exponent value
	hasDigits := false
	for err == nil {
		if '0' <= ch && ch <= '9' {
			digits = append(digits, ch)
			prev = '0'
			hasDigits = true
		} else if ch == '_' && sepOk {
			if prev != '0' {
				invalSep = true
			}
			prev = '_'
		} else {
			r.UnreadByte() // ch does not belong to number anymore
			break
		}
		ch, err = r.ReadByte()
	}

	if err == io.EOF {
		err = nil
	}
	if err == nil && !hasDigits {
		err = errNoDigits
	}
	if err == nil {
		exp, err = strconv.ParseInt(string(digits), 10, 64)
	}
	// other errors take precedence over invalid separators
	if err == nil && (invalSep || prev == '_') {
		err = errInvalSep
	}

	return
}

// String returns a string representation of x in the form "a/b" (even if b == 1).
func (x *Rat) String() string {
	return string(x.marshal())
}

// marshal implements String returning a slice of bytes
func (x *Rat) marshal() []byte {
	var buf []byte
	buf = x.a.Append(buf, 10)
	buf = append(buf, '/')
	if len(x.b.abs) != 0 {
		buf = x.b.Append(buf, 10)
	} else {
		buf = append(buf, '1')
	}
	return buf
}

// RatString returns a string representation of x in the form "a/b" if b != 1,
// and in the form "a" if b == 1.
func (x *Rat) RatString() string {
	if x.IsInt() {
		return x.a.String()
	}
	return x.String()
}

// FloatString returns a string representation of x in decimal form with prec
// digits of precision after the radix point. The last digit is rounded to
// nearest, with halves rounded away from zero.
func (x *Rat) FloatString(prec int) string {
	var buf []byte

	if x.IsInt() {
		buf = x.a.Append(buf, 10)
		if prec > 0 {
			buf = append(buf, '.')
			for i := prec; i > 0; i-- {
				buf = append(buf, '0')
			}
		}
		return string(buf)
	}
	// x.b.abs != 0

	q, r := nat(nil).div(nat(nil), x.a.abs, x.b.abs)

	p := natOne
	if prec > 0 {
		p = nat(nil).expNN(natTen, nat(nil).setUint64(uint64(prec)), nil, false)
	}

	r = r.mul(r, p)
	r, r2 := r.div(nat(nil), r, x.b.abs)

	// see if we need to round up
	r2 = r2.add(r2, r2)
	if x.b.abs.cmp(r2) <= 0 {
		r = r.add(r, natOne)
		if r.cmp(p) >= 0 {
			q = nat(nil).add(q, natOne)
			r = nat(nil).sub(r, p)
		}
	}

	if x.a.neg {
		buf = append(buf, '-')
	}
	buf = append(buf, q.utoa(10)...) // itoa ignores sign if q == 0

	if prec > 0 {
		buf = append(buf, '.')
		rs := r.utoa(10)
		for i := prec - len(rs); i > 0; i-- {
			buf = append(buf, '0')
		}
		buf = append(buf, rs...)
	}

	return string(buf)
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Pdfci extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
         if($this->session->userdata('logged_in')){

        $this->load->library('Html2pdf');
        $this->load->model('Servicio_model','servicio');
        $this->load->model('Empresa_model','empresa',true);
        $this->load->model('Contacto_model','contacto',true);
        $this->load->model('Datos_model','todosdatos',true);
        $this->load->model('Usuario_model','usuario',true);
        $this->load->model('Alumno_model','alumno',true);
        $this->load->model('Historia_model','historia',true);
        $this->load->model('Asistencia_model','asistencia',true);
        $this->load->model('Equipo_model','equipo',true);
        $this->load->model('linea_model','linea',true);
        $this->load->model('Acta_model','acta',true);
        $this->load->model('Evidencia_model','evi',true);
        $this->load->model('Areas_model','area',true);

          }else{
          redirect('login');
        }
    }

    public function index($asi_id)
    {
        $this->html2pdf->folder('./resources/documento_mype/');
        $datos= array();
        $eviden= array();
        $session = $this->session->userdata('logged_in');
        $user = $this->usuario->findById($session["id"]);
               foreach ($user as $value) {
        $datos['area']=$this->area->findById($value->get('usu_are_id'));
        }
        $asistencias = $this->asistencia->showDataAsi($asi_id);
        $empresa     = $this->empresa->findById($asistencias->get('asi_emp_id'));
        $pdfnom = str_replace(" ","_", $empresa->get('emp_rsocial').$empresa->get('emp_id'));
        $this->html2pdf->paper('a4', 'portrait');
        $this->html2pdf->filename($pdfnom.'.pdf');
        $datosempresa = $this->historia->findByIdEmp($asistencias->get("asi_emp_id"));
        $numhis = count($datosempresa);
        $numhisdiv= $numhis/4;
        $acta = $this->acta->findByasi($asistencias->get("asi_id"));
        $evidencias =  array();
        foreach ($acta as  $va) {
            $evidencias[]=$this->evi->findByact($va->get('act_id'));
        }
        $numacta               = $asistencias->countActas();
        $datos['eviden']       = $evidencias;
        $datos['asistencia']   = $asistencias;
        $datos['numact']       = $numacta;
        $datos['acta']         =$acta;
        $datos["historial"]    =$datosempresa;
        $datos["historialnum"] =$numhisdiv;
        $ser                   =$this->servicio->findById($asistencias->get('asi_ser_id'));
        $datos['empresa']      = $empresa;
        $datos['servicio']     = $ser;
        $datos['lineas']       = $this->linea->findById($ser->get('ser_lin_id'));
        $datos['equipo']       =$this->equipo->findAsi($asi_id);
        $datos['sede']         =$this->todosdatos->findSedeById($session["sede"]);
        $this->html2pdf->html(($this->load->view('pdfinformefinal', $datos, true)));
        if($this->html2pdf->create('save'))
        {
            $this->show($pdfnom);
        }
    }

    //funcion que ejecuta la descarga del pdf
    public function downloadPdf($pdfnom)
    {
        //si existe el directorio
        if(is_dir("./resources/documento_mype"))
        {
            //ruta completa al archivo
            $route = base_url("resources/documento_mype/".$pdfnom.".pdf");
            //nombre del archivo
            $filename = $pdfnom.".pdf";
            //si existe el archivo empezamos la descarga del pdf
            if(file_exists("./resources/documento_mype/".$filename))
            {
                header("Cache-Control: public");
                header("Content-Description: File Transfer");
                header('Content-disposition: attachment; filename='.basename($route));
                header("Content-Type: application/pdf");
                header("Content-Transfer-Encoding: binary");
                header('Content-Length: '. filesize($route));
                readfile($route);
            }
        }
    }
    //esta función muestra el pdf en el navegador siempre que existan
    //tanto la carpeta como el archivo pdf
    public function show($pdfnom)
    {
        if(is_dir("./resources/documento_mype"))
        {
            $filename = $pdfnom.".pdf";
            $route = base_url("resources/documento_mype/".$filename);
            if(file_exists("./resources/documento_mype/".$filename))
            {
                header('Content-type: application/pdf');
                readfile($route);
            }
        }
    }
}
/* End of file pdf_ci.php */
/* Location: ./application/controllers/pdf_ci.php */


text:
ljmmm-parse
===========
[LabJack Modbus Map Markup](https://bitbucket.org/labjack/ljm_constants) language parser micro-library for Node.js.

Installation
--------------
``npm install ljmmm-parse``

Usage
---------
```javascript
var ljmmm_parse = require('ljmmm-parse');

/**
 * Logs
 * [
 *     {name: 'Test0', address: 0, type: 'UINT32'},
 *     {name: 'Test1', address: 2, type: 'UNIT32'},
 *     {name: 'Another0', address: 0, type: 'UINT32'},
 *     {name: 'Another1', address: 2, type: 'UNIT32'}
 * ]
**/
ljmmm_parse.expandLJMMMEntries(
    [
        {name: 'Test#(0:1)', address: 0, type: 'UINT32'},
        {name: 'Another#(0:1)', address: 0, type: 'UINT32'}
    ]
    function (err) { console.log(err); },
    function (expandedEntries) { console.log(expandedEntries); }
);

/**
 * Logs
 * [
 *     {name: 'Test0', address: 0, type: 'UINT32'},
 *     {name: 'Test1', address: 2, type: 'UNIT32'}
 * ]
**/
ljmmm_parse.expandLJMMMEntry(
    {name: 'Test#(0:1)', address: 0, type: 'UINT32'},
    function (err) { console.log(err); },
    function (expandedEntries) { console.log(expandedEntries); }
);

// Logs ['Test0', 'Test1', 'Test2']
ljmmm_parse.expandLJMMMName(
    'Test#(0:2)',
    function (err) { console.log(err); },
    function (expandedNames) { console.log(expandedNames); }
);

/**
 * Also available:
 *
 * ljmmm_parse.expandLJMMMEntriesSync(listOfEntries);
 * ljmmm_parse.expandLJMMMEntrySync(entry);
**/
```

License and Copyright
-----------------------------
LabJack Corp, 2013
Sam Pottinger, 2013

Released under the [MIT license](http://opensource.org/licenses/MIT).

Background and motivation
-----------------------------------
To standardize MODBUS map specification, LabJack developed LJMMM or LabJack Modbus Map Markup (see [ljm_constants](https://bitbucket.org/labjack/ljm_constants)). To support software targeting LabJack devices written in Node, this library supports the interpretation of LJMMM fields.

Testing
---------
Requires [rewire](https://github.com/jhnns/rewire) (npm install rewire) and [nodeunit](https://github.com/caolan/nodeunit) (npm install nodeunit).
```
nodeunit ljmmm_test.js
```

Development environment and standards
-----------------------------------------------------
This project maintains 80% code coverage at minimum and conforms to both [jsDoc](http://usejsdoc.org/) and [Google JavaScript style guidelines](http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml).


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 297028 $ -->
<refentry xml:id="function.fbsql-result" xmlns="http://docbook.org/ns/docbook">
 <refnamediv>
  <refname>fbsql_result</refname>
  <refpurpose>Get result data</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>mixed</type><methodname>fbsql_result</methodname>
   <methodparam><type>resource</type><parameter>result</parameter></methodparam>
   <methodparam choice="opt"><type>int</type><parameter>row</parameter></methodparam>
   <methodparam choice="opt"><type>mixed</type><parameter>field</parameter></methodparam>
  </methodsynopsis>
  <para>
   Returns the contents of one cell from a FrontBase
   <parameter>result</parameter> set.
  </para>
  <para>
   When working on large result sets, you should consider using one
   of the functions that fetch an entire row (specified below).  As
   these functions return the contents of multiple cells in one
   function call, they're MUCH quicker than <function>fbsql_result</function>.
  </para>
  <para>
   Calls to <function>fbsql_result</function> should not be mixed
   with calls to other functions that deal with the result set.
  </para>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    &fbsql.result.description;
    <varlistentry>
     <term><parameter>row</parameter></term>
     <listitem>
      <para>
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><parameter>field</parameter></term>
     <listitem>
      <para>
       Can be the field's offset, or the field's name, or the field's table
       dot field's name (tablename.fieldname).
      </para>
      <para>
       If the column name has been aliased ('select foo as bar from...'), use
       the alias instead of the column name.
      </para>
      <note>
       <para>
        Specifying a numeric offset for the field argument is much quicker
        than specifying a fieldname or tablename.fieldname argument.
       </para>
      </note>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
  </para>
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   Recommended high-performance alternatives:
   <simplelist>
    <member><function>fbsql_fetch_row</function></member>
    <member><function>fbsql_fetch_array</function></member>
    <member><function>fbsql_fetch_assoc</function></member>
    <member><function>fbsql_fetch_object</function></member>
   </simplelist>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Django在list_display和search__fields中使用外键 • shiziwen's Tech Blog</title>
    <meta name="description" content="
  本文减少Django在list_display和search__fields中使用外键的方法

">
    <meta name="keywords" content="">

	<meta name="twitter:title" content="Django在list_display和search__fields中使用外键">
	<meta name="twitter:description" content="
  本文减少Django在list_display和search__fields中使用外键的方法

">
	<meta name="twitter:site" content="@shiziwen">
	<meta name="twitter:creator" content="@shiziwen">

	<meta name="twitter:card" content="summary">
	<meta name="twitter:image" content="/images/logo.jpg">

	<meta property="og:locale" content="">
	<meta property="og:type" content="article">
	<meta property="og:title" content="Django在list_display和search__fields中使用外键">
	<meta property="og:description" content="
  本文减少Django在list_display和search__fields中使用外键的方法

">
	<meta property="og:url" content="/python/django-list_display-search_fields/">
	<meta property="og:site_name" content="shiziwen's Tech Blog">

    <link rel="canonical" href="/python/django-list_display-search_fields/">

    <link href="/atom.xml" type="application/atom+xml" rel="alternate" title="shiziwen's Tech Blog Atom Feed">
    <link href="/sitemap.xml" type="application/xml" rel="sitemap" title="Sitemap">

    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="cleartype" content="on">

    <link rel="stylesheet" href="/css/main.css">

    shiziwen's Tech Blog

shiziwen's Tech Blog

Home

Linux

Python

iOS

About Me

			Home

			Linux

			Python

			iOS

			About Me

<button type="button" class="js-menu-trigger sliding-menu-button menulines-button x2" role="button" aria-label="Toggle Navigation">

</button>

        Home
       ›

        Python

Django在list_display和search__fields中使用外键

本文减少Django在list_display和search__fields中使用外键的方法

文章欢迎转载,但转载时请保留本段文字,并置于文章的顶部

作者:张纹华(shiziwen)

本文原文地址:http://shiziwen.github.io/python/django-list_display-search_fields/

一. list_display中使用外键

在admin中定义一个函数,获取想要获得外键的值,然后将函数名写在list_display中。

class HelloAdmin(admin.ModelAdmin):
    list_display = ('user', 'user_email', 'role')
    # ...

    # 显示用户邮箱地址
    def user_email(self, obj):
        return u'%s' % obj.user.email
    user_email.short_description = u'邮箱'

admin.site.register(Hello, HelloAdmin)

二. search_fields中使用外键

将 search_fields 中的外键字段改为 foreign_key__related_fieldname 这种形式就可以了。 这种用法适用于 ForeignKey 及 ManyToManyField。

class Hello(models.Model):
    name = models.CharField(max_length=100)

    #...

class Foo(models.Model):
    hello = models.ForeignKey(Hello)

class FooAdmin(admin.ModelAdmin):
    search_fields = ('hello__name',)  # 搜索 Hello 中的 name 字段

三. 参考资料

[django]list_display 中包含外键内的字段

[django]如何在 search_fields 中包含外键字段

Written by shiziwen(张纹华)

     Share on Twitter

     Share on Facebook
     Share on Google+

Updated <time datetime="2015-11-25T04:44:03Z" itemprop="datePublished">November 25, 2015</time>

Please enable JavaScript to view the comments powered by Disqus.

© 2016 shiziwen's Tech Blog powered by Jekyll + Skinny Bones.


text:
          SpeakEasy

              <input name="email-field" type="text" class="form-control" placeholder="Your email address"
              ng-model="email">

                <button class="btn btn-default" type="button" ng-click="joinWaitlist()">Sign up</button>


text:
namespace BIOS {

namespace Junk {

class Base : public BIOS::Base {
public:
	Base(EmulatorBase *e) : BIOS::Base(e) {}
	virtual void Boot() = 0;
protected:
	EmulatorBase *emu;
};

}
}

#endif


text:
chat.js
=======

A basic chat app written in meteor.js as an exploration into the technology


text:
namespace ouzel
{
    namespace graphics
    {
        class D3D11RenderDevice;

        class D3D11BlendState final: public D3D11RenderResource
        {
        public:
            D3D11BlendState(D3D11RenderDevice& renderDeviceD3D11,
                            bool enableBlending,
                            BlendState::Factor colorBlendSource, BlendState::Factor colorBlendDest,
                            BlendState::Operation colorOperation,
                            BlendState::Factor alphaBlendSource, BlendState::Factor alphaBlendDest,
                            BlendState::Operation alphaOperation,
                            uint8_t colorMask);
            ~D3D11BlendState();

            inline ID3D11BlendState* getBlendState() const { return blendState; }

        private:
            ID3D11BlendState* blendState = nullptr;
        };
    } // namespace graphics
} // namespace ouzel

#endif

#endif // OUZEL_GRAPHICS_D3D11BLENDSTATE_HPP


text:
package net.mostlyoriginal.gwt.system;

import com.artemis.BaseSystem;
import com.artemis.annotations.Wire;
import net.mostlyoriginal.api.event.common.EventSystem;

/**
* @author Daan van Yperen
*/
@Wire
public class DispatchTestSystem extends BaseSystem {

    EventSystem eventSystem;

    @Override
    protected void processSystem() {
        eventSystem.dispatch(new BasicTestEvent());
    }
}