text:
import React, { Component } from "react";
import PropTypes from "prop-types";
import { EditorState, RichUtils } from "draft-js";
import classNames from "classnames";
import ToolbarItem from "./ToolbarItem";
import { getSelectionCoords } from "../utils";

export default class Toolbar extends Component {
  static defaultProps = {
    shouldDisplayToolbarFn(props, state) {
      return (
        (props.editorHasFocus || state.editingEntity) &&
        !props.editorState.getSelection().isCollapsed()
      );
    }
  };
  static propTypes = {
    editorHasFocus: PropTypes.bool
  };

  constructor(props) {
    super(props);
    this.state = {
      show: false,
      editingEntity: null,
      link: "",
      error: null
    };
    this.renderButton = this.renderButton.bind(this);
    this.cancelEntity = this.cancelEntity.bind(this);
    this.removeEntity = this.removeEntity.bind(this);
    this.setError = this.setError.bind(this);
    this.cancelError = this.cancelError.bind(this);
  }

  toggleInlineStyle(inlineStyle) {
    const newEditorState = RichUtils.toggleInlineStyle(
      this.props.editorState,
      inlineStyle
    );
    this.props.onChange(newEditorState);
  }

  toggleBlockType(blockType) {
    this.props.onChange(
      RichUtils.toggleBlockType(this.props.editorState, blockType)
    );
  }

  toggleEntity(entity) {
    this.setState({ editingEntity: entity });
  }

  renderButton(item, position) {
    let current = null;
    let toggle = null;
    let active = null;
    let key = item.label;

    switch (item.type) {
      case "custom": {
        key = "custom-" + position;
        toggle = () => item.action(this.props.editorState, this.props.onChange);
        active = item.active && item.active(this.props.editorState);
        break;
      }
      case "inline": {
        current = this.props.editorState.getCurrentInlineStyle();
        toggle = () => this.toggleInlineStyle(item.style);
        active = current.has(item.style);
        break;
      }
      case "block": {
        const selection = this.props.editorState.getSelection();
        current = this.props.editorState
          .getCurrentContent()
          .getBlockForKey(selection.getStartKey())
          .getType();
        toggle = () => this.toggleBlockType(item.style);
        active = item.style === current;
        break;
      }
      case "separator": {
        key = "sep-" + position;
        break;
      }
      case "entity": {
        const { entity = "LINK" } = item;
        key = "entity-" + entity;
        toggle = () => this.toggleEntity(entity);
        active = this.hasEntity(entity);
        break;
      }
    }

    return (
      <ToolbarItem key={key} active={active} toggle={toggle} item={item} />
    );
  }

  setError(errorMsg) {
    this.setState({ error: errorMsg });
  }

  cancelError() {
    this.setState({ error: null });
  }

  setBarPosition() {
    this.setState(
      {
        show: true
      },
      () => {
        const editor = this.props.editor;
        const toolbar = this.toolbarEl;
        const selectionCoords = getSelectionCoords(editor, toolbar);

        if (!selectionCoords) {
          return null;
        }

        if (
          (selectionCoords && !this.state.position) ||
          this.state.position.top !== selectionCoords.offsetTop ||
          this.state.position.left !== selectionCoords.offsetLeft ||
          this.state.arrowStyle !== selectionCoords.arrowStyle ||
          !this.state.show
        ) {
          this.setState({
            position: {
              top: selectionCoords.offsetTop,
              left: selectionCoords.offsetLeft
            },
            arrowStyle: selectionCoords.arrowStyle
          });
        }
      }
    );
  }

  handleSetToolbar() {
    if (this.props.shouldDisplayToolbarFn(this.props, this.state)) {
      this.shouldUpdatePos = false;
      return this.setBarPosition();
    } else {
      if (this.state.show) {
        this.setState({
          show: false,
          editingEntity: null,
          link: "",
          error: null
        });
      }
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const currentContentState = this.props.editorState.getCurrentContent();
    const newContentState = nextProps.editorState.getCurrentContent();

    if (currentContentState === newContentState) {
      this.shouldUpdatePos = true;
    }
  }

  componentDidUpdate() {
    if (this.shouldUpdatePos) {
      this.handleSetToolbar();
    }
  }

  getCurrentEntityKey() {
    const selection = this.props.editorState.getSelection();
    const anchorKey = selection.getAnchorKey();
    const contentState = this.props.editorState.getCurrentContent();
    const anchorBlock = contentState.getBlockForKey(anchorKey);
    const offset = selection.anchorOffset;
    const index = selection.isBackward ? offset - 1 : offset;
    return anchorBlock.getEntityAt(index);
  }

  getCurrentEntity() {
    const contentState = this.props.editorState.getCurrentContent();
    const entityKey = this.getCurrentEntityKey();
    if (entityKey) {
      return contentState.getEntity(entityKey);
    }
    return null;
  }

  hasEntity(entityType) {
    const entity = this.getCurrentEntity();
    return entity && entity.getType() === entityType;
  }

  setEntity(entityType, data, mutability = "MUTABLE") {
    const { editorState } = this.props;
    const contentState = editorState.getCurrentContent();
    const contentStateWithEntity = contentState.createEntity(
      entityType,
      mutability,
      data
    );
    const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
    const newState = RichUtils.toggleLink(
      editorState,
      editorState.getSelection(),
      entityKey
    );
    const selectionState = EditorState.forceSelection(
      newState,
      editorState.getSelection()
    );

    this.props.onChange(selectionState);
  }

  removeEntity() {
    const { editorState } = this.props;
    const selection = editorState.getSelection();
    if (!selection.isCollapsed()) {
      // toggleLink should be named toggleEntity: https://github.com/facebook/draft-js/issues/737
      this.props.onChange(RichUtils.toggleLink(editorState, selection, null));
    }
    this.cancelEntity();
  }

  cancelEntity() {
    this.setState(
      {
        editingEntity: null,
        error: null
      },
      () => {
        this.props.draft && this.props.draft.focus();
      }
    );
  }
  renderEntityInput(entityType) {
    if (!this.props.entityInputs) {
      console.warn("no entityInputs provided");
      return null;
    }
    const Component = this.props.entityInputs[entityType];
    const setEntity = (data, mutability) =>
      this.setEntity(entityType, data, mutability);
    let entityData = {};
    let entity = null;
    if (this.hasEntity(entityType)) {
      entity = this.getCurrentEntity();
      if (entity) {
        entityData = entity.getData();
      }
    }
    if (Component) {
      return (
        <Component
          i18n={this.props.i18n}
          editorState={this.props.editorState}
          setEntity={setEntity}
          entityType={entityType}
          onChange={this.props.onChange}
          cancelEntity={this.cancelEntity}
          removeEntity={this.removeEntity}
          setError={this.setError}
          cancelError={this.cancelError}
          entity={entity}
          {...entityData}
        />
      );
    } else {
      console.warn("unknown entity type: " + entityType);
      return null;
    }
  }
  renderToolList() {
    return (

        {this.props.actions.map(this.renderButton)}

    );
  }
  render() {
    if (
      this.props.readOnly ||
      !this.props.shouldDisplayToolbarFn(this.props, this.state)
    ) {
      return null;
    }

    const toolbarClass = classNames("toolbar", {
      "toolbar--open": this.state.show,
      "toolbar--error": this.state.error
    });

    return (

 {
              this.toolbarEl = el;
            }}
            onMouseDown={e => {
              if (
                e.target.localName !== "input" &&
                e.target.localName !== "select"
              ) {
                e.preventDefault();
              }
            }}
          >
            {this.state.editingEntity
              ? this.renderEntityInput(this.state.editingEntity)
              : this.renderToolList()}

{this.state.error}

             {
                this.arrowEl = el;
              }}
              style={this.state.arrowStyle}
            />

    );
  }
}


text:
#pragma once

#include <CPluginD3D.h>

namespace D3DPlugin
{
    class CD3DSystem9 :
        public IPluginD3DEx,
        private ID3DEventListener
    {
        private:
            bool m_bD3DHookInstalled;
            std::vector<ID3DEventListener*> m_vecQueue;

            void hookD3D( bool bHook );
        public:
            int m_nTextureMode;
            void* m_pTempTex;
            void* m_pDevice;

            CD3DSystem9();
            virtual ~CD3DSystem9();

            void Release()
            {
                delete this;
            }

            PluginManager::IPluginBase* GetBase()
            {
                return gPlugin->GetBase();
            };

            void ActivateEventDispatcher( bool bActivate )
            {
                hookD3D( bActivate );
            };

            void* GetDevice();
            eD3DType GetType()
            {
                return m_pDevice ? D3D_DX9 : D3D_NONE;
            };

            void* GetSwapChain()
            {
                return NULL;
            }; // DX11 only
            void* GetDeviceContext()
            {
                return NULL;
            }; // DX11 only

            ITexture* CreateTexture( void** pD3DTextureDst, int width, int height, int numMips, ETEX_Format eTF, int flags );
            ITexture* InjectTexture( void* pD3DTextureSrc, int nWidth, int nHeight, ETEX_Format eTF, int flags );

        public:
            DECLARE_REGISTER_LISTENER( m_vecQueue );
            DECLARE_UNREGISTER_LISTENER( m_vecQueue );
            DECLARE_BROADCAST_EVENT( m_vecQueue, OnPrePresent );
            DECLARE_BROADCAST_EVENT( m_vecQueue, OnPostPresent );
            DECLARE_BROADCAST_EVENT( m_vecQueue, OnPreReset );
            DECLARE_BROADCAST_EVENT( m_vecQueue, OnPostReset );
            DECLARE_BROADCAST_EVENT( m_vecQueue, OnPostBeginScene );
    };

    extern CD3DSystem9* gD3DSystem9;
};

redpajama_set_name: RedPajamaGithub


text:
from typing import Any, Type, List, Dict, TYPE_CHECKING

if TYPE_CHECKING:
    from httpie.sessions import Session

OLD_HEADER_STORE_WARNING = '''\
Outdated layout detected for the current session. Please consider updating it,
in order to use the latest features regarding the header layout.

For fixing the current session:

    $ httpie cli sessions upgrade {hostname} {session_id}
'''

OLD_HEADER_STORE_WARNING_FOR_NAMED_SESSIONS = '''\

For fixing all named sessions:

    $ httpie cli sessions upgrade-all
'''

OLD_HEADER_STORE_LINK = '\nSee $INSERT_LINK for more information.'

def pre_process(session: 'Session', headers: Any) -> List[Dict[str, Any]]:
    """Serialize the headers into a unified form and issue a warning if
    the session file is using the old layout."""

    is_old_style = isinstance(headers, dict)
    if is_old_style:
        normalized_headers = list(headers.items())
    else:
        normalized_headers = [
            (item['name'], item['value'])
            for item in headers
        ]

    if is_old_style:
        warning = OLD_HEADER_STORE_WARNING.format(hostname=session.bound_host, session_id=session.session_id)
        if not session.is_anonymous:
            warning += OLD_HEADER_STORE_WARNING_FOR_NAMED_SESSIONS
        warning += OLD_HEADER_STORE_LINK
        session.warn_legacy_usage(warning)

    return normalized_headers

def post_process(
    normalized_headers: List[Dict[str, Any]],
    *,
    original_type: Type[Any]
) -> Any:
    """Deserialize given header store into the original form it was
    used in."""

    if issubclass(original_type, dict):
        # For the legacy behavior, preserve the last value.
        return {
            item['name']: item['value']
            for item in normalized_headers
        }
    else:
        return normalized_headers

def fix_layout(session: 'Session', *args, **kwargs) -> None:
    from httpie.sessions import materialize_headers

    if not isinstance(session['headers'], dict):
        return None

    session['headers'] = materialize_headers(session['headers'])


text:
<?php

namespace AppBundle\Entity\Core;

use AppBundle\Entity\Core\Invitation;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\UniqueConstraint;
use FOS\UserBundle\Entity\User as BaseUser;
use FR3D\LdapBundle\Model\LdapUserInterface;
use Gedmo\Mapping\Annotation as Gedmo;
use Hateoas\Configuration\Annotation as Hateoas;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Groups;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * User.
 *
 * @ExclusionPolicy("all")
 * @ORM\Table(name="users",
 *     uniqueConstraints={
 *         @UniqueConstraint(name="email_uniq", columns={"email"}),
 *         @UniqueConstraint(name="username_uniq", columns={"username"})
 *     }
 * )
 * @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
 * @UniqueEntity("username")
 * @UniqueEntity("email")
 *
 */
class User extends BaseUser /*implements LdapUserInterface*/
{
    const MAX_ADMIN_USER = 5;

    /**
     * @var int
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * @Groups({"list", "details"})
     * @ORM\Column(name="uuid", type="string", length=36)
     */
    protected $uuid;

    /**
     * @var \DateTime
     * @ORM\Column(name="updated_at", type="datetime")
     * @Gedmo\Timestampable(on="update")
     */
    protected $updatedAt;

    /**
     * @var \DateTime
     * @ORM\Column(name="created_at", type="datetime")
     * @Gedmo\Timestampable(on="create")
     */
    protected $createdAt;

    /**
     * @ORM\OneToOne(targetEntity="AppBundle\Entity\Core\Invitation")
     * @ORM\JoinColumn(referencedColumnName="code")
     * @Assert\NotNull(message="form.error.invitation.code", groups={"Registration"})
     */
    protected $invitation;

    /**
     * Constructor.
     */
    public function __construct()
    {
        parent::__construct();

        $this->roles = array('ROLE_ADMIN');

        $this->uuid = \Ramsey\Uuid\Uuid::uuid4();
    }

    /**
     * setUuid.
     *
     * @param string $uuid
     */
    public function setUuid($uuid)
    {
        $this->uuid = $uuid;
    }

    /**
     * getUuid.
     *
     * @return string
     */
    public function getUuid()
    {
        return $this->uuid;
    }

    /**
     * Get updatedAt.
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * Get createdAt.
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * setInvitation.
     * @param Invitation $invitation
     */
    public function setInvitation(Invitation $invitation)
    {
        $this->invitation = $invitation;
    }

    /**
     * getInvitation.
     * @return string
     */
    public function getInvitation()
    {
        return $this->invitation;
    }
}


text:
<?php

namespace Elcodi\AdminCartBundle\Controller;

use Mmoreram\ControllerExtraBundle\Annotation\Entity as EntityAnnotation;
use Mmoreram\ControllerExtraBundle\Annotation\Form as FormAnnotation;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

use Elcodi\AdminCoreBundle\Controller\Abstracts\AbstractAdminController;
use Elcodi\AdminCoreBundle\Controller\Interfaces\EnableableControllerInterface;
use Elcodi\AdminCoreBundle\Controller\Interfaces\NavegableControllerInterface;
use Elcodi\CartBundle\Entity\Interfaces\CartInterface;
use Elcodi\CoreBundle\Entity\Abstracts\AbstractEntity;

/**
 * Class Controller for Cart
 *
 * @Route(
 *      path = "/cart",
 * )
 */
class CartController
    extends
    AbstractAdminController
    implements
    NavegableControllerInterface,
    EnableableControllerInterface
{
    /**
     * Nav for cart group
     *
     * @return array Result
     *
     * @Route(
     *      path = "s/nav",
     *      name = "admin_cart_nav"
     * )
     * @Method({"GET"})
     * @Template
     */
    public function navAction()
    {
        return [];
    }

    /**
     * List elements of certain entity type.
     *
     * This action is just a wrapper, so should never get any data,
     * as this is component responsability
     *
     * @param Request $request          Request
     * @param integer $page             Page
     * @param integer $limit            Limit of items per page
     * @param string  $orderByField     Field to order by
     * @param string  $orderByDirection Direction to order by
     *
     * @return array Result
     *
     * @Route(
     *      path = "s/{page}/{limit}/{orderByField}/{orderByDirection}",
     *      name = "admin_cart_list",
     *      requirements = {
     *          "page" = "\d*",
     *          "limit" = "\d*",
     *      },
     *      defaults = {
     *          "page" = "1",
     *          "limit" = "50",
     *          "orderByField" = "id",
     *          "orderByDirection" = "DESC",
     *      },
     * )
     * @Template
     * @Method({"GET"})
     */
    public function listAction(
        Request $request,
        $page,
        $limit,
        $orderByField,
        $orderByDirection
    )
    {
        return [
            'page'             => $page,
            'limit'            => $limit,
            'orderByField'     => $orderByField,
            'orderByDirection' => $orderByDirection,
        ];
    }

    /**
     * View element action.
     *
     * This action is just a wrapper, so should never get any data,
     * as this is component responsability
     *
     * @param Request $request Request
     * @param integer $id      Entity id
     *
     * @return array Result
     *
     * @Route(
     *      path = "/{id}",
     *      name = "admin_cart_view",
     *      requirements = {
     *          "id" = "\d*",
     *      }
     * )
     * @Template
     * @Method({"GET"})
     */
    public function viewAction(
        Request $request,
        $id
    )
    {
        return [
            'id' => $id,
        ];
    }

    /**
     * New element action
     *
     * This action is just a wrapper, so should never get any data,
     * as this is component responsability
     *
     * @param Request $request Request
     * @param integer $id      Entity id
     *
     * @return array Result
     *
     * @Route(
     *      path = "/{id}/edit",
     *      name = "admin_cart_edit"
     * )
     * @Template
     * @Method({"GET"})
     */
    public function editAction(
        Request $request,
        $id
    )
    {
        return [
            'id' => $id,
        ];
    }

    /**
     * Updated edited element action
     *
     * Should be POST
     *
     * @param Request        $request Request
     * @param AbstractEntity $entity  Entity to update
     * @param FormInterface  $form    Form view
     * @param boolean        $isValid Request handle is valid
     *
     * @return RedirectResponse Redirect response
     *
     * @Route(
     *      path = "/{id}/update",
     *      name = "admin_cart_update"
     * )
     * @Method({"POST"})
     *
     * @EntityAnnotation(
     *      class = "elcodi.core.cart.entity.cart.class",
     *      mapping = {
     *          "id": "~id~",
     *      }
     * )
     * @FormAnnotation(
     *      class = "elcodi_admin_cart_form_type_cart",
     *      name  = "form",
     *      entity = "entity",
     *      handleRequest = true,
     *      validate = "isValid"
     * )
     */
    public function updateAction(
        Request $request,
        AbstractEntity $entity,
        FormInterface $form,
        $isValid
    )
    {
        $this
            ->getManagerForClass($entity)
            ->flush($entity);

        return $this->redirectRoute("admin_cart_view", [
            'id' => $entity->getId(),
        ]);
    }

    /**
     * Updated edited element action
     *
     * @param Request        $request     Request
     * @param AbstractEntity $entity      Entity to delete
     * @param string         $redirectUrl Redirect url
     *
     * @return RedirectResponse Redirect response
     *
     * @Route(
     *      path = "/{id}/delete",
     *      name = "admin_cart_delete",
     *      defaults = {
     *          "redirectUrl" = "admin_cart_list",
     *      }
     * )
     * @Method({"GET"})
     *
     * @EntityAnnotation(
     *      class = "elcodi.core.cart.entity.cart.class",
     *      mapping = {
     *          "id" = "~id~"
     *      }
     * )
     */
    public function deleteAction(
        Request $request,
        AbstractEntity $entity,
        $redirectUrl = null
    )
    {
        return parent::deleteAction(
            $request,
            $entity,
            $redirectUrl
        );
    }

    /**
     * Convert a Cart into an Order
     *
     * @param CartInterface $cart Cart
     *
     * @return array Result
     *
     * @Route(
     *      path = "/{id}/to-order",
     *      name = "admin_cart_to_order",
     *      requirements = {
     *          "id" = "\d*",
     *      }
     * )
     * @Method({"GET"})
     *
     * @EntityAnnotation(
     *      name = "cart",
     *      class = {
     *          "factory" = "elcodi.core.cart.factory.cart",
     *      },
     *      mapping = {
     *          "id" = "~id~"
     *      }
     * )
     */
    public function viewComponentAction(CartInterface $cart)
    {
        $this
            ->get('elcodi.cart_event_dispatcher')
            ->dispatchCartOnLoadEvent($cart);

        $order = $this
            ->get('elcodi.cart_order_transformer')
            ->createOrderFromCart($cart);

        return $this->redirect(
            $this->generateUrl("admin_order_view", [
                "id" => $order->getId()
            ])
        );
    }
}


text:
<?php

defined('JPATH_PLATFORM') or die;

/**
 * Route handling class
 *
 * @since  11.1
 */
class JRoute
{
	/**
	 * The route object so we don't have to keep fetching it.
	 *
	 * @var    JRouter
	 * @since  12.2
	 */
	private static $_router = null;

	/**
	 * Translates an internal Joomla URL to a humanly readable URL.
	 *
	 * @param   string   $url    Absolute or Relative URI to Joomla resource.
	 * @param   boolean  $xhtml  Replace & by & for XML compliance.
	 * @param   integer  $ssl    Secure state for the resolved URI.
	 *                             0: (default) No change, use the protocol currently used in the request
	 *                             1: Make URI secure using global secure site URI.
	 *                             2: Make URI unsecure using the global unsecure site URI.
	 *
	 * @return string The translated humanly readable URL.
	 *
	 * @since   11.1
	 */
	public static function _($url, $xhtml = true, $ssl = null)
	{
		if (!self::$_router)
		{
			// Get the router.
			$app = JFactory::getApplication();
			self::$_router = $app::getRouter();

			// Make sure that we have our router
			if (!self::$_router)
			{
				return;
			}
		}

		if (!is_array($url) && (strpos($url, '&') !== 0) && (strpos($url, 'index.php') !== 0))
		{
			return $url;
		}

		// Build route.
		$uri = self::$_router->build($url);

		$scheme = array('path', 'query', 'fragment');

		/*
		 * Get the secure/unsecure URLs.
		 *
		 * If the first 5 characters of the BASE are 'https', then we are on an ssl connection over
		 * https and need to set our secure URL to the current request URL, if not, and the scheme is
		 * 'http', then we need to do a quick string manipulation to switch schemes.
		 */
		if ((int) $ssl || $uri->isSsl())
		{
			static $host_port;

			if (!is_array($host_port))
			{
				$uri2 = JUri::getInstance();
				$host_port = array($uri2->getHost(), $uri2->getPort());
			}

			// Determine which scheme we want.
			$uri->setScheme(((int) $ssl === 1 || $uri->isSsl()) ? 'https' : 'http');
			$uri->setHost($host_port[0]);
			$uri->setPort($host_port[1]);
			$scheme = array_merge($scheme, array('host', 'port', 'scheme'));
		}

		$url = $uri->toString($scheme);

		// Replace spaces.
		$url = preg_replace('/\s/u', '%20', $url);

		if ($xhtml)
		{
			$url = htmlspecialchars($url, ENT_COMPAT, 'UTF-8');
		}

		return $url;
	}
}


text:
<?xml version="1.0"?>
<exslt:function xmlns:exslt="http://exslt.org/documentation"
               version="1" module="date" status="new">

<exslt:name>add-duration</exslt:name>

<rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
                 xmlns:dc="http://purl.org/dc/elements/1.1/"
                 ID="date:add-duration">
   <dc:subject>EXSLT</dc:subject>
   <dc:subject>date</dc:subject>
   <dc:subject>add-duration</dc:subject>
   <exslt:revision>
      <rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
                       xmlns:dc="http://purl.org/dc/elements/1.1/"
                       ID="date:add-duration.1">
         <exslt:version>1</exslt:version>
         <dc:creator email="mail@jenitennison.com"
                     url="http://www.jenitennison.com/">
            Jeni Tennison
         </dc:creator>
         <dc:date>2001-05-12</dc:date>
         <dc:description xmlns="http://www.w3.org/1999/xhtml">
            Returns the duration resulting from adding two durations together.
         </dc:description>
      </rdf:Description>
   </exslt:revision>
</rdf:Description>

<exslt:doc xmlns:html="http://www.w3.org/1999/xhtml"
           xmlns="">

         The date:add-duration function returns the duration resulting from adding two durations together.

         Both arguments are strings in the format defined for xs:duration in [3.2.6 duration] of [XML Schema Part 2: Datatypes].  If either argument is not in this format, the function returns an empty string ('').

         The return value is a string in the format defined for xs:duration in [3.2.6 duration] of [XML Schema Part 2: Datatypes].

         The durations can be added by summing the numbers given for each of the components in the durations.

</exslt:doc>

<exslt:definition xmlns:xs="http://www.w3.org/2001/XMLSchema">
   <exslt:return type="string" />
   <exslt:arg name="duration1" type="string"
              optional="no" />
   <exslt:arg name="duration2" type="string"
              optional="no" />
</exslt:definition>

<exslt:implementations />

<exslt:use-cases />

</exslt:function>


text:
using Digiseller.Client.Core.Enums;

namespace Digiseller.Client.Core.Models.Request.Cart
{
    public class DigisellerAddToCartRequest
    {
        public DigisellerAddToCartRequest(int productId, int productCount, Currency currency, string email, string languageCode, string cartUid = "")
        {
            product_id = productId;
            product_cnt = productCount;
            typecurr = currency.ToString();
            this.email = email;
            lang = languageCode;
            cart_uid = cartUid;
        }

        public int product_id { get;  }
        public int product_cnt { get;  }
        public string typecurr { get; }
        public string email { get; }
        public string lang { get; }
        public string cart_uid { get; }
    }
}


text:
/*
	By: facug91
	From: http://coj.uci.cu/24h/problem.xhtml?abb=1106
	Name: All in All
	Number: 1106
	Date: 31/10/2013
*/

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Auxiliar {

	public static void main (String[] args) throws IOException {
		BufferedReader stdin = new BufferedReader
				(new InputStreamReader(System.in));

		int n = Integer.parseInt(stdin.readLine());
		int impar = 0;
		int par = 0;
		for (int i=0; i<n/2; i++) {
			impar += Integer.parseInt(stdin.readLine());
			par += Integer.parseInt(stdin.readLine());
		}

		if (impar > par) {
			System.out.println(impar+" "+par);
		} else {
			System.out.println(par+" "+impar);
		}
	}
}


text:
<?php
namespace Flowpack\JobQueue\Common\Queue;

/**
 * A DTO that wraps arbitrary payload with an identifier and a counter for failures.
 */
class Message
{
    /**
     * The message identifier allows to target messages in the queue, @see QueueInterface
     * The format depends on the implementation
     *
     * @var string Identifier of the message
     */
    protected $identifier;

    /**
     * The message payload, has to be serializable.
     *
     * @var \Serializable The message payload
     */
    protected $payload;

    /**
     * How often this message was released (i.e. after failures for retrial)
     *
     * @var integer
     */
    protected $numberOfReleases;

    /**
     * @param string $identifier
     * @param mixed $payload
     * @param integer $numberOfReleases
     */
    public function __construct(string $identifier, $payload, int $numberOfReleases = 0)
    {
        $this->identifier = $identifier;
        $this->payload = $payload;
        $this->numberOfReleases = $numberOfReleases;
    }

    /**
     * @return string
     */
    public function getIdentifier(): string
    {
        return $this->identifier;
    }

    /**
     * @return mixed
     */
    public function getPayload()
    {
        return $this->payload;
    }

    /**
     * @return int
     */
    public function getNumberOfReleases(): int
    {
        return $this->numberOfReleases;
    }
}


text:
<?php
/**
 * Created by: Jiar
 * Github: https://www.github.com/Jiar/
 */

namespace Admin\Model;

use Think\Model;

class AdminModel extends Model {

    protected $patchValidate = ture;
    protected $_validate = array(
        array('name','4,20','用户名长度范围:4~20',self::EXISTS_VALIDATE,'length'),
        array('name','checkName','该用户名已被使用',self::MODEL_BOTH,'callback'),
        array('email','email','未输入邮箱或格式错误'),
        array('email','checkEmail','该邮箱已被使用',self::MODEL_BOTH,'callback'),
        array('password','6,30','密码长度:6~30',self::EXISTS_VALIDATE,'length'),
        array('password','repassword','两次密码输入不一致',self::EXISTS_VALIDATE,'confirm'),
    );
    protected $autoCheckFields = true;
    protected $_auto = array(
        array('password', 'sha1', self::MODEL_BOTH, 'function'),
    );

    protected $_scope = array(

    );

    protected function checkName($name) {
        if($this->getAdminByName($name)) {
            return false;
        }
        return true;
    }

    protected function checkEmail($email) {
        if($this->getAdminByEmail($email)) {
            return false;
        }
        return true;
    }

    private function getAdminByName($name) {
        $admin = D("Admin");
        $result = $admin->getByName($name);
        if(count($result) == 0) {
            return null;
        } else {
            $result['password'] = null;
            return $result;
        }
    }

    private function getAdminByEmail($email) {
        $admin = D("Admin");
        $result = $admin->getByEmail($email);
        if(count($result) == 0) {
            return null;
        } else {
            $result['password'] = null;
            return $result;
        }
    }

}


text:
(function(){
  var requires, setup, Book, User, Permit, permitFor, PermitMatcher, PermitRegistry, createUser, createRequest, createPermit;
  requires = require('../../../requires');
  requires.test('test_setup');
  setup = require('./permits').setup;
  Book = requires.fix('book');
  User = requires.fix('user');
  Permit = requires.lib('permit');
  permitFor = requires.permit('permit-for');
  PermitMatcher = requires.permit('permit_matcher');
  PermitRegistry = requires.permit('permit-registry');
  createUser = requires.fac('create-user');
  createRequest = requires.fac('create-request');
  createPermit = requires.fac('create-permit');
  describe('PermitMatcher', function(){
    var subject, permitMatcher, book, users, permits, requests, matching, noneMatching;
    users = {};
    permits = {};
    requests = {};
    matching = {};
    noneMatching = {};
    before(function(){
      users.kris = createUser.kris;
      users.emily = createUser.emily;
      requests.user = {
        user: users.kris
      };
      permits.user = setup.userPermit();
      return permitMatcher = new PermitMatcher(permits.user, requests.user);
    });
    return describe('custom-match', function(){
      before(function(){
        book = new Book({
          title: 'far and away'
        });
        requests.subject = {
          user: {},
          subject: book
        };
        requests.ctx = {
          ctx: void 8
        };
        permits.book = setup.bookPermit();
        matching.permitMatcher = new PermitMatcher(permits.book, requests.subject);
        return noneMatching.permitMatcher = new PermitMatcher(permits.book, requests.ctx);
      });
      context('matching permit-matcher', function(){
        before(function(){
          return subject = matching.permitMatcher;
        });
        specify('has permit', function(){
          return subject.permit.should.eql(permits.book);
        });
        return specify('has subject access-request', function(){
          return subject.accessRequest.should.eql(requests.subject);
        });
      });
      context('matching permit-matcher', function(){
        before(function(){
          return subject = noneMatching.permitMatcher;
        });
        specify('has permit', function(){
          return subject.permit.should.eql(permits.book);
        });
        return specify('has access-request', function(){
          return subject.accessRequest.should.eql(requests.ctx);
        });
      });
      specify('matches access-request using permit.match', function(){
        return matching.permitMatcher.customMatch().should.be['true'];
      });
      specify('does NOT match access-request since permit.match does NOT match', function(){
        return noneMatching.permitMatcher.customMatch().should.be['false'];
      });
      return describe('invalid match method', function(){
        before(function(){
          return permits.user = setup.invalidUser();
        });
        return specify('should throw error', function(){
          return function(){
            return noneMatching.permitMatcher.customMatch;
          }.should['throw'];
        });
      });
    });
  });
}).call(this);


text:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
module.exports = function(src) {
	function log(error) {
		(typeof console !== "undefined")
		&& (console.error || console.log)("[Script Loader]", error);
	}

	// Check for IE =< 8
	function isIE() {
		return typeof attachEvent !== "undefined" && typeof addEventListener === "undefined";
	}

	try {
		if (typeof execScript !== "undefined" && isIE()) {
			execScript(src);
		} else if (typeof eval !== "undefined") {
			eval.call(null, src);
		} else {
			log("EvalError: No eval function available");
		}
	} catch (error) {
		log(error);
	}
}


text:
'use strict';

// MODULES //

var Complex128 = require( '@stdlib/complex/float64' );
var Complex64 = require( '@stdlib/complex/float32' );

// MAIN //

var ctors = {
	'Complex128': Complex128,
	'Complex64': Complex64
};

// EXPORTS //

module.exports = ctors;


text:
Sometimes it may be necessary to have custom setters and/or getters for some attributes. Structure allows you to do that using native JavaScript setters and getters. It will even support coercion.

It's important to notice that you **should not** try to access the attribute directly inside its getter or to set it directly inside its setter because it will cause infinite recursion, this is default JavaScript behavior. To access an attribute value inside its getter you should use `this.get(attributeName)`, and to set the value of an attribute a setter you should use `this.set(attributeName, attributeValue)`:

```js
const User = attributes({
  firstName: String,
  lastName: String,
  age: Number,
})(
  class User {
    get firstName() {
      return `-> ${this.get('firstName')}`;
    }

    set lastName(newLastname) {
      return this.set('lastName', `Mac${newLastName}`);
    }

    get age() {
      // do NOT do that. Instead, use this.get and this.set inside getters and setters
      return this.age * 1000;
    }

    // this is NOT an attribute, just a normal getter
    get fullName() {
      return `${this.firstName} ${this.lastName}`;
    }
  }
);

const user = new User({ firstName: 'Connor', lastName: 'Leod' });

user.firstName; // -> Connor
user.lastName; // MacLeod
user.fullName; // -> Connor MacLeod
```

## Inheritance

Custom setters and getters are also inherited, be your superclass a pure JavaScript class or another structure:

```js
class Person {
  // If Person was a structure instead of a pure class, that would work too
  get name() {
    return 'The person';
  }
}

const User = attributes({
  name: String,
})(class User extends Person {});

const user = new User({ name: 'Will not be used' });

user.name; // -> The person
```

**Important**

JavaScript nativelly won't let you inherit only one of the accessors (the getter or the setter) if you define the other accessor in a subclass:

```js
class Person {
  get name() {
    return 'Person';
  }
}

class User extends Person {
  set name(newName) {
    this._name = newName;
  }
}

const user = new Person();
user.name = 'The user';
user.name; // -> The user
```

It happens because _once you define one of the accessors in a subclass_, all the accessors for the same attribute inherited from the superclass will be ignored.

While it's a weird behavior, Structure will follow the same functionality so the Structure classes inheritance work the same way of pure JavaScript classes, avoiding inconsistencies.


text:
package com.wordnik.swagger.sample.exception;

public class ApiException extends Exception{
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	@SuppressWarnings("unused")
	private int code;
	public ApiException (int code, String msg) {
		super(msg);
		this.code = code;
	}
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NeuralNetworks;
using System.IO;

namespace CharacterRecognition
{
    public partial class Training : Form
    {
        public delegate void endTraining();
        public event endTraining Ended;

        delegate void ProgressCallBack(int value, int iter, float cost);

        public Training()
        {
            InitializeComponent();
        }

        public void OnProgress(int progress, int iter, float cost)
        {
            this.setProgress(progress, iter, cost);
        }
        private void setProgress(int value, int iter, float cost)
        {
            if (this.progressBar1.InvokeRequired)
            {
                ProgressCallBack pcb = new ProgressCallBack(setProgress);
                this.Invoke(pcb, new object[] { value, iter, cost });
            }
            else
            {
                progressBar1.Value = value;
                label5.Text = "Training, iteration " + (iter + 1) + "/" + numIter + ", cost = " + cost;
            }
        }

        public delegate void endCallBack(float i, float f);

        public void OnEnd(float init, float final)
        {
            this.end(init, final);
        }

        private void end(float init, float final)
        {
            if (this.InvokeRequired)
            {
                endCallBack callback = new endCallBack(OnEnd);
                Invoke(callback, new object[] { init, final });
            }
            else
            {
                label5.Text = "Completed";
                MessageBox.Show("Cost gone from " + init + " to " + final, "Results!", MessageBoxButtons.OK, MessageBoxIcon.Information);

                Ended();
                Hide();
            }
        }

        NeuralNetwork net;

        public void trainNeuralNetwork(ref NeuralNetwork nn)
        {
            nn = new NeuralNetwork(new int[] { 626, 26, 10 });
            net = nn;
            Console.WriteLine(net.Equals(nn));

            GradientDescent.GetEnd += OnEnd;
            GradientDescent.GetProgress += OnProgress;

            Show();
            label1.Text = "Select Parameters";
            label5.Visible = false;
            progressBar1.Visible = false;
        }

        private void progressBar1_Click(object sender, EventArgs e)
        {

        }
        int samples;

        public void Samples(int numNumeros)
        {
            samples = numNumeros;
            Console.WriteLine(samples);
        }

        int numIter = 0;

        private async void button1_Click(object sender, EventArgs e)
        {
            if(textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
            {
                MessageBox.Show("Enter the parameters", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                Console.WriteLine("XDDDDDDDDDDDDDDDDDDDDD");
                label1.Text = "Training Neural Network...";
                progressBar1.Visible = true;
                label5.Visible = true;
                textBox1.Visible = false;
                textBox2.Visible = false;
                textBox3.Visible = false;
                label2.Visible = false;
                label3.Visible = false;
                label4.Visible = false;
                button1.Enabled = false;
                button1.Visible = false;

                float lambda = float.Parse(textBox3.Text);
                float learningRate = float.Parse(textBox1.Text);
                numIter = int.Parse(textBox2.Text);

                float[][] input = new float[samples][];
                float[][] output = new float[samples][];

                label5.Text = "Reading database...";

                using(StreamReader sr = new StreamReader("database.dat"))
                {
                    string[] pixels;

                    for (int sample = 0; sample < samples; sample++)
                    {
                        input[sample] = new float[625];
                        output[sample] = new float[10];

                        pixels = sr.ReadLine().Split(' ');

                        output[sample][int.Parse(pixels[0])] = 1;
                        for(int i = 0; i < 625; i++)
                        {
                            input[sample][i] = float.Parse(pixels[i + 1]);
                        }
                    }
                }
                label5.Text = "Training, iteration " + 1 + "/" + numIter + ", cost = " + net.ComputeCost(input, output, net.unrollConnections(), lambda);
                Task backProp = new Task(() => net.BackPropagation(input, output, learningRate, lambda, numIter));
                backProp.Start();
            }
        }

        private void Training_FormClosed(object sender, FormClosedEventArgs e)
        {
            Ended();
            Hide();
        }
    }
}


text:
using NUnit.Framework;
using osu.Framework.Graphics;

namespace osu.Game.Tests.Visual.Editing
{
    public class TestSceneTimelineZoom : TimelineTestScene
    {
        public override Drawable CreateTestComponent() => Empty();

        [Test]
        public void TestVisibleRangeUpdatesOnZoomChange()
        {
            double initialVisibleRange = 0;

            AddStep("reset zoom", () => TimelineArea.Timeline.Zoom = 100);
            AddStep("get initial range", () => initialVisibleRange = TimelineArea.Timeline.VisibleRange);

            AddStep("scale zoom", () => TimelineArea.Timeline.Zoom = 200);
            AddStep("range halved", () => Assert.That(TimelineArea.Timeline.VisibleRange, Is.EqualTo(initialVisibleRange / 2).Within(1)));
            AddStep("descale zoom", () => TimelineArea.Timeline.Zoom = 50);
            AddStep("range doubled", () => Assert.That(TimelineArea.Timeline.VisibleRange, Is.EqualTo(initialVisibleRange * 2).Within(1)));

            AddStep("restore zoom", () => TimelineArea.Timeline.Zoom = 100);
            AddStep("range restored", () => Assert.That(TimelineArea.Timeline.VisibleRange, Is.EqualTo(initialVisibleRange).Within(1)));
        }

        [Test]
        public void TestVisibleRangeConstantOnSizeChange()
        {
            double initialVisibleRange = 0;

            AddStep("reset timeline size", () => TimelineArea.Timeline.Width = 1);
            AddStep("get initial range", () => initialVisibleRange = TimelineArea.Timeline.VisibleRange);

            AddStep("scale timeline size", () => TimelineArea.Timeline.Width = 2);
            AddAssert("same range", () => TimelineArea.Timeline.VisibleRange == initialVisibleRange);
            AddStep("descale timeline size", () => TimelineArea.Timeline.Width = 0.5f);
            AddAssert("same range", () => TimelineArea.Timeline.VisibleRange == initialVisibleRange);

            AddStep("restore timeline size", () => TimelineArea.Timeline.Width = 1);
            AddAssert("same range", () => TimelineArea.Timeline.VisibleRange == initialVisibleRange);
        }
    }
}


text:
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.md)
**Assembly:** OfficeDevPnP.Core.dll
## Inheritance Hierarchy
System.Object
## Syntax
```C#
public class Page
```
## Constructors
|**Name**|**Description**|
|:-----|:-----|
| [Page()](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.Page.ctor1.md) |
## Properties
|**Name**|**Description**|
|:-----|:-----|
| [Fields](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.Page.Fields.md) |
| [Layout](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.Page.Layout.md) |
| [Overwrite](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.Page.Overwrite.md) |
| [Security](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.Page.Security.md) |
| [Url](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.Page.Url.md) |
| [WebParts](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.Page.WebParts.md) |
## See also
- [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.md)


text:
Although there is a plugin called [metalsmith-shortcodes](https://github.com/ericgj/metalsmith-shortcodes) it doesn't really work the
way you expected (and how they work in WordPress, unlike stated).

This aims to be a lot closer to the way the shortcodes work in WordPress:
`[foo param1="bar" param2="baz"]`

Internally this plugin uses [shortcode-parser](https://github.com/derdesign/shortcode-parser) to parse and render the shortcodes.

##Examples
```markdown
---
title: Test Page
template: page.hbt
---
This is a cool image:
[flickr src="https://www.flickr.com/photos/curlywurly1st/14438479793/in/explore-2014-06-14"]
```

And in your build file:

```js
shortcodes = require('metalsmith-flexible-shortcodes');

Metalsmith(__dirname)
    // ...
    .use(shortcodes({
        shortcodes: {
            'flickr': function(str, params) {
                return '<img href="' + params.src + '" />';
            }
        }
    }))
```

For more infos on how the shortcodes work check out [shortcode-parser](https://github.com/derdesign/shortcode-parser).

##Options

### `shortcodes`
An object with key value pairs, where each key represents the shortcode name, e. g. `[name]` and its value is the function that will be executed for this shortcode.

####Example
```js
{
    shortcodes: {
        'flickr': function(str, params) {
            return '<img href="' + params.src + '" />';
        }
    }
}
```
Can then be used as `[flickr]` in your files.

### `clean`
If true, it will clean any `<p>`-Tags around the shortcodes, this is needed when you render your files with markdown in some cases.

##Notes
It is recommended you run this plugin after your markdown parser, otherwise you won't be able to use fenced code blocks. If you run into this issue also make sure to turn on the `clean` option.

##Building
This plugin is written in ES6 syntax, therefore you will need to compile it.
Firstly run `$ npm install` and then `$ gulp`.

##License
The MIT License (MIT)

Copyright (c) 2014 Robin Thrift

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
<!DOCTYPE html>

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

        <link rel="icon" type="image/png" href="img/favicon/icon.png" sizes="16x16" />

        <link href="css/bootstrap.min.css" rel="stylesheet">

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

        <link href="css/font-awesome.min.css" rel="stylesheet">

        <link href="css/thiago.css" rel="stylesheet">
        <link rel="stylesheet" href="css/bootstrap.css" type="text/css"/>

Thiago Rodrigo Gomes

                            Olá! Meu nome é Thiago Gomes, sou apaixonado por desenvolvimento e adoro aprender coisas novas.

                            Eu tenho um conjunto diversificado de competências, que vão desde a concepção até a finalização do projeto.

                            Estou constantemente trabalhando minhas habilidades como Full Stack Developer para entregar produtos de qualidade e fazer a diferença como profissional.

Habilidades

Contato

                            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                                Toggle navigation

                            </button>

Home

Habilidades

Contato

Habilidades

Skills front-end e back-end

                            Como desenvolvedor full stack, estou sempre conectado à novas tendências.
                            Procuro fazer os meus códigos da melhor maneira possível, expressando paixão e alegria pelo que faço.

                            Para isso, estou estudando constantemente para melhorar os meus conhecimentos, a fim de produzir uma solução
                            que alcance os objetivos e ao mesmo tempo ofereça a melhor tecnologia disponível.

Outras Tecnologias

                            Além dessas tecnologias, eu adoro trabalhar com linux e gosto de brincar com python também
                            (Descobri o python na faculdade e, desde então, fiquei fascinado pela linguagem).

                            Ah! Antes que me esqueça, eu uso o controle de versionamento git. Alguns do meus códigos
                            estão diponivéis no github, assim como essa página. Se ficar curioso,
                            passa lá depois (github.com/trgomes/trgomes.github.io).

Contato

                      <address>
                          São José dos Campos, SP / Brasil

                          trgomesdev@gmail.com

                      </address>

                          Obrigado pela visita!


text:
import { Component, OnInit } from '@angular/core'
import { FormControl, FormGroup, Validators } from '@angular/forms'
import IDumpConfig from 'src/app/model/dump-config'
import { DataService } from 'src/app/services/data/data.service'
import { Router } from '@angular/router'
import { InputType, StorageKeys } from 'src/app/app.constants'
import { extractSourceDbName } from 'src/app/utils/utils'
import { ClickEventService } from 'src/app/services/click-event/click-event.service'

@Component({
  selector: 'app-load-dump',
  templateUrl: './load-dump.component.html',
  styleUrls: ['./load-dump.component.scss'],
})
export class LoadDumpComponent implements OnInit {
  constructor(
    private data: DataService,
    private router: Router,
    private clickEvent: ClickEventService
  ) {}
  connectForm = new FormGroup({
    dbEngine: new FormControl('mysqldump', [Validators.required]),
    filePath: new FormControl('', [Validators.required]),
  })
  dbEngineList = [
    { value: 'mysqldump', displayName: 'MYSQL' },
    { value: 'pg_dump', displayName: 'PostgreSQL' },
  ]

  ngOnInit(): void {}

  convertFromDump() {
    this.clickEvent.openDatabaseLoader('dump', '')
    this.data.resetStore()
    const { dbEngine, filePath } = this.connectForm.value
    const payload: IDumpConfig = {
      Driver: dbEngine,
      Path: filePath,
    }
    this.data.getSchemaConversionFromDump(payload)
    this.data.conv.subscribe((res) => {
      localStorage.setItem(StorageKeys.Config, JSON.stringify(payload))
      localStorage.setItem(StorageKeys.Type, InputType.DumpFile)
      localStorage.setItem(StorageKeys.SourceDbName, extractSourceDbName(dbEngine))
      this.clickEvent.closeDatabaseLoader()
      this.router.navigate(['/workspace'])
    })
  }
}


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

import io.trino.operator.scalar.ColorFunctions;
import io.trino.spi.block.Block;
import io.trino.spi.connector.ConnectorSession;
import io.trino.spi.type.AbstractIntType;
import io.trino.spi.type.TypeSignature;

import static java.lang.String.format;

public class ColorType
        extends AbstractIntType
{
    public static final ColorType COLOR = new ColorType();
    public static final String NAME = "color";

    private ColorType()
    {
        super(new TypeSignature(NAME));
    }

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

    @Override
    public Object getObjectValue(ConnectorSession session, Block block, int position)
    {
        if (block.isNull(position)) {
            return null;
        }

        int color = block.getInt(position, 0);
        if (color < 0) {
            return ColorFunctions.SystemColor.valueOf(-(color + 1)).getName();
        }

        return format("#%02x%02x%02x",
                (color >> 16) & 0xFF,
                (color >> 8) & 0xFF,
                color & 0xFF);
    }

    @Override
    @SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
    public boolean equals(Object other)
    {
        return other == COLOR;
    }

    @Override
    public int hashCode()
    {
        return getClass().hashCode();
    }
}


text:
ACCEPTED

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

#### Published in
J. R. Perkins, Fragm fl. Philipp. 47. 1904

#### Original name
null

### Remarks
null


text:
"""
Defines all the forms used in the login blueprint.
"""

# Imports
from flask_wtf import Form
from wtforms import TextField, PasswordField, SelectField, DecimalField, BooleanField
from wtforms.validators import StopValidation,DataRequired, Email, Length, EqualTo, NumberRange

# DataRequired validator makes sure the data is present in the field.
# Length validator makes sure the field is between a specific lenght
# EqualTo validator makes sure the field is equal to another field.
# Email validator makes sure the field is a valid email.
# NumberRange makes sure the data is between a specific number range.

def is_a_float(form, field):
    """
    Validator to check the field is a float.
    """
    if field.data is not None:
        try:
            # Try to convert the field to a float.
            float(field.data)
        except ValueError:
            # The field is not a float.
            field.errors[:] = ['Must be a numerical value.']
            # Stop all further validations.
            raise StopValidation()
    else:
        # The field is not a float.
        field.errors[:] = ['This field is required and must be a numerical value.']
        # Stop all further validations.
        raise StopValidation()

def is_alpha_numeric(form, field):
    """
    Validator to check the field is alpha numeric.
    """
    if field.data is not None and not str(field.data).replace(' ','').isalnum():
        # The field is not a float.
        field.errors[:] = ['Must be and alpha-numerical string, and not contain symbols.']
        # Stop all further validations.
        raise StopValidation()

class LoginForm(Form):

    """
    Form for users to login to the site.
    """

    # Text field for the users email.
    email = TextField('email',validators=[DataRequired(),Email(message=None),Length(max=50)])

    # Password field for the users password.
    password = PasswordField('password',validators=[DataRequired(),Length(max=32)])

    # Remember Me field.
    remember = BooleanField('remember me')

class SignUpForm(Form):

    """
    Form for users to signup to the site.
    """

    # Text field for the users firstname.
    firstname = TextField(
        'firstname',
        validators=[DataRequired(),Length(min=2,max=20)]
    )
    # Text field for the users surname.
    surname = TextField(
        'surname',
        validators=[DataRequired(), Length(min=2,max=20)]
    )
    # Text field for the users email.
    email = TextField(
        'email',
        validators=[DataRequired(),Email(message=None),Length(max=50)]
    )
    # Password field for the users chosen password.
    password = PasswordField(
        'password',
        validators=[DataRequired(), Length(min=6,max=32)]
    )
    # Password confirmation field.
    password_confirm = PasswordField(
        'password confirmation',
        validators=[DataRequired(),EqualTo('password', message='Passwords must match.')]
    )
    # Select field for selecting gender.
    gender = SelectField(
        'gender',
        choices=[('male','Male'),('female','Female')]
    )
    # Decimal field for the users height.
    height = DecimalField(
        'height',
        places=2,
        validators=[DataRequired(),NumberRange(min=0,max=3),is_a_float]
    )
    # Decimal field for the users weight.
    weight = DecimalField(
        'weight',
        places=2,
        validators=[DataRequired(),NumberRange(min=0,max=250),is_a_float]
    )
    # Text field for the first line of the users address.
    address_line_1 = TextField(
        'address',
        validators=[DataRequired(),Length(min=5, max=200),is_alpha_numeric]
    )
    # Text field for the users city.
    city = TextField(
        'city',
        validators=[DataRequired(),Length(min=2, max=25),is_alpha_numeric]
    )
    # Text field for the users postcode.
    postcode = TextField(
        'postcode',
        validators=[DataRequired(),Length(min=5,max=9),is_alpha_numeric]
    )

class EditDetailsForm(Form):
    """
    Form for users to edit their personal details.
    """

     # Text field for the users firstname.
    firstname = TextField(
        'firstname',
        validators=[DataRequired(),Length(min=2,max=20)]
    )
    # Text field for the users surname.
    surname = TextField(
        'surname',
        validators=[DataRequired(), Length(min=2,max=20)]
    )
    # Text field for the users email.
    email = TextField(
        'email',
        validators=[DataRequired(),Email(message=None)]
    )
    # Decimal field for the users height.
    height = DecimalField(
        'height',
        places=2,
        validators=[DataRequired(),NumberRange(min=0,max=3)]
    )
    # Text field for the first line of the users address.
    address_line_1 = TextField(
        'address',
        validators=[DataRequired(),Length(min=5, max=200)]
    )
    # Text field for the users city.
    city = TextField(
        'city',
        validators=[DataRequired(),Length(min=2, max=20)]
    )
    # Text field for the users postcode.
    postcode = TextField(
        'postcode',
        validators=[DataRequired(),Length(min=5,max=9)]
    )
    # Password field needed for the user to update their details.
    password = PasswordField(
        'password',
        validators=[DataRequired(), Length(min=6,max=32)]
    )

class ChangePasswordForm(Form):
    """
    Form that allows users to change their password.
    """

    # Password field needed for the user to change their password
    current_password = PasswordField(
        'current_password',
        validators=[DataRequired()]
    )
    # Password field for the new password.
    new_password = PasswordField(
        'new_password',
        validators=[DataRequired(), Length(min=6,max=32)]
    )
    # Password field for the new password confirmation.
    new_password_confirm = PasswordField(
        'new_password_confirm',
        validators=[DataRequired(),EqualTo('new_password', message='Passwords must match.')]
    )


text:
package net.uncontended.precipice.semaphore;

import net.uncontended.precipice.BackPressure;
import net.uncontended.precipice.Failable;
import net.uncontended.precipice.GuardRail;

import java.util.concurrent.atomic.AtomicLong;

public class LongSemaphore<Rejected extends Enum<Rejected>> implements BackPressure<Rejected>, PrecipiceSemaphore {

    private final AtomicLong permitsRemaining;
    private final long maxConcurrencyLevel;
    private final Rejected reason;

    public LongSemaphore(Rejected reason, long maxConcurrencyLevel) {
        this.maxConcurrencyLevel = maxConcurrencyLevel;
        this.reason = reason;
        this.permitsRemaining = new AtomicLong(maxConcurrencyLevel);
    }

    @Override
    public Rejected acquirePermit(long number, long nanoTime) {
        for (; ; ) {
            long permitsRemaining = this.permitsRemaining.get();
            long newRemaining = permitsRemaining - number;
            if (newRemaining >= 0) {
                if (this.permitsRemaining.compareAndSet(permitsRemaining, newRemaining)) {
                    return null;
                }
            } else {
                return reason;
            }
        }
    }

    @Override
    public void releasePermit(long number, long nanoTime) {
        this.permitsRemaining.getAndAdd(number);
    }

    @Override
    public void releasePermit(long number, Failable result, long nanoTime) {
        this.permitsRemaining.getAndAdd(number);
    }

    @Override
    public <Result extends Enum<Result> & Failable> void registerGuardRail(GuardRail<Result, Rejected> guardRail) {
    }

    @Override
    public long maxConcurrencyLevel() {
        return maxConcurrencyLevel;
    }

    @Override
    public long remainingCapacity() {
        return permitsRemaining.get();
    }

    @Override
    public long currentConcurrencyLevel() {
        return maxConcurrencyLevel - permitsRemaining.get();
    }
}


text:
require 'custom_validators'
require 'date_parsing'


text:
package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"syscall"
	"testing"
	"time"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/kubernetes/fake"

	"k8s.io/ingress-nginx/internal/ingress/controller"
	"k8s.io/ingress-nginx/internal/k8s"
	"k8s.io/ingress-nginx/internal/nginx"
)

func TestCreateApiserverClient(t *testing.T) {
	_, err := createApiserverClient("", "", "")
	if err == nil {
		t.Fatal("Expected an error creating REST client without an API server URL or kubeconfig file.")
	}
}

func init() {
	// the default value of nginx.TemplatePath assumes the template exists in
	// the root filesystem and not in the rootfs directory
	path, err := filepath.Abs(filepath.Join("../../rootfs/", nginx.TemplatePath))
	if err == nil {
		nginx.TemplatePath = path
	}
}

func TestHandleSigterm(t *testing.T) {
	const (
		podName   = "test"
		namespace = "test"
	)

	k8s.IngressPodDetails = &k8s.PodInfo{
		ObjectMeta: metav1.ObjectMeta{
			Name:      podName,
			Namespace: namespace,
			Labels: map[string]string{
				"pod-template-hash": "1234",
			},
		},
	}

	clientSet := fake.NewSimpleClientset()

	createConfigMap(clientSet, namespace, t)

	pod := corev1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:      podName,
			Namespace: namespace,
		},
	}

	_, err := clientSet.CoreV1().Pods(namespace).Create(context.TODO(), &pod, metav1.CreateOptions{})
	if err != nil {
		t.Fatalf("error creating pod %v: %v", pod, err)
	}

	resetForTesting(func() { t.Fatal("bad parse") })

	os.Setenv("POD_NAME", podName)
	os.Setenv("POD_NAMESPACE", namespace)

	oldArgs := os.Args

	defer func() {
		os.Setenv("POD_NAME", "")
		os.Setenv("POD_NAMESPACE", "")
		os.Args = oldArgs
	}()

	os.Args = []string{"cmd", "--default-backend-service", "ingress-nginx/default-backend-http", "--http-port", "0", "--https-port", "0"}
	_, conf, err := parseFlags()
	if err != nil {
		t.Errorf("Unexpected error creating NGINX controller: %v", err)
	}
	conf.Client = clientSet

	ngx := controller.NewNGINXController(conf, nil)

	go handleSigterm(ngx, func(code int) {
		if code != 1 {
			t.Errorf("Expected exit code 1 but %d received", code)
		}
	})

	time.Sleep(1 * time.Second)

	t.Logf("Sending SIGTERM to PID %d", syscall.Getpid())
	err = syscall.Kill(syscall.Getpid(), syscall.SIGTERM)
	if err != nil {
		t.Error("Unexpected error sending SIGTERM signal.")
	}
}

func createConfigMap(clientSet kubernetes.Interface, ns string, t *testing.T) string {
	t.Helper()

	configMap := &corev1.ConfigMap{
		ObjectMeta: metav1.ObjectMeta{
			Name:     "config",
			SelfLink: fmt.Sprintf("/api/v1/namespaces/%s/configmaps/config", ns),
		},
	}

	cm, err := clientSet.CoreV1().ConfigMaps(ns).Create(context.TODO(), configMap, metav1.CreateOptions{})
	if err != nil {
		t.Errorf("error creating the configuration map: %v", err)
	}

	return cm.Name
}


text:
$(document).ready(function(){
    DisablePassButton();
    $("#getUserMeida").click(getUserMeida);
    $("#stopUserMeida").click(stopUserMeida);
    $("#errormassage").html("No video");
});

//getUserMedia
function getUserMeida () {
    try {
        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
        navigator.getUserMedia({video: true}, function(s){
            var url = webkitURL.createObjectURL(s);
            $("#localView")[0].src = url;
            $("#localView").show();
            $("#errormassage").hide();
            EnablePassButton();
        }, function(error){
            $("#errormassage").show();
            $("#errormassage").html("Get user media occur error:PERMISSION DENIED");
        });
    } catch (e) {
        $("#localView").hide();
        $("#errormassage").html("Get usr media occur error,with error message:"+e.message+"");
    }
}

//stop getUserMedia
function stopUserMeida () {
    try {
        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
        navigator.getUserMedia();
        $("#errormassage").show();
        $("#errormassage").html("No video");
    } catch (e) {
        $("#localView").hide();
        $("#errormassage").show();
        $("#errormassage").html("No video");
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>elastic-job-lite</artifactId>
        <groupId>com.dangdang</groupId>
        <version>2.1.2</version>
    </parent>
    <artifactId>elastic-job-lite-lifecycle</artifactId>
    <name>${project.artifactId}</name>

    <dependencies>
        <dependency>
            <groupId>com.dangdang</groupId>
            <artifactId>elastic-job-common-restful</artifactId>
            <version>${project.parent.version}</version>
        </dependency>
        <dependency>
            <groupId>com.dangdang</groupId>
            <artifactId>elastic-job-lite-core</artifactId>
            <version>${project.parent.version}</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-test</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-inline</artifactId>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
"""
Created by louis at 2021/11/7
Description:
"""

import torch
import torch.nn as nn
import torch.optim as optim
from torchtext.datasets import Multi30k
from torchtext.data import Field, BucketIterator

import spacy
import numpy as np

import random
import math
import time

SEED = 1234

random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
torch.backends.cudnn.deterministic = True

spacy_de = spacy.load('de_core_news_sm')
spacy_en = spacy.load('en_core_web_sm')

def tokenize_de(text):
    """
    Tokenizes German text from a string into a list of strings (tokens) and reverses it
    """
    return [tok.text for tok in spacy_de.tokenizer(text)][::-1]

def tokenize_en(text):
    """
    Tokenizes English text from a string into a list of strings (tokens)
    """
    return [tok.text for tok in spacy_en.tokenizer(text)]

SRC = Field(tokenize=tokenize_de, init_token='<sos>', eos_token='<eos>', lower=True)

TRG = Field(tokenize=tokenize_en, init_token='<sos>', eos_token='<eos>', lower=True)

train_data, valid_data, test_data = Multi30k.splits(exts=('.de', '.en'), fields=(SRC, TRG))

print(f"Number of training examples: {len(train_data.examples)}")
print(f"Number of validation examples: {len(valid_data.examples)}")
print(f"Number of testing examples: {len(test_data.examples)}")

print(vars(train_data.examples[0]))

# 构建词汇,构建之后,SRC 就多了个 vocab 属性,vocab 中包含有 freqs、itos、stoi 三个属性,其中freqs 表示的是 SRC 中每个单词和该单词的频数,也就是个数。
# itos 是一个列表,包含的的是频数 >= 2 的单词,stoi 用来标记 itos 中每个单词的索引,从0开始。
# 例如 输入是['two', 'two', ',', 'two', 'two', 'are', 'outside', 'near', 'many', 'bushes', 'two', 'young', ',', 'white', 'white', 'near', 'outside', 'near', 'many', 'bushes', '.']
# 则 freqs 是({'two': 5, 'near': 3, ',': 2, 'outside': 2, 'many': 2, 'bushes': 2, 'white': 2, 'are': 1, 'young': 1, '.': 1})
# itos 是 ['<unk>', '<pad>', '<sos>', '<eos>', 'two', 'near', ',', 'bushes', 'many', 'outside', 'white']
# 其中 <sos>:一个句子的开始,<eos>:一句话的结束,<UNK>: 低频词或未在词表中的词,
# <PAD>: 补全字符,由于我们在进行批量计算的时候,每个样本的长度不一样,<PAD>就是用于保证样本长度一样的。参考于 https://github.com/nicolas-ivanov/tf_seq2seq_chatbot/issues/15
# 由于我们的 min_freq = 2 ,所以可以看到频数为1的 'are','young', '.' 都没有在 itos 中。
# stoi 是 {'<unk>': 0, '<pad>': 1, '<sos>': 2, '<eos>': 3, 'two': 4, 'near': 5, ',': 6, 'bushes': 7, 'many': 8, 'outside': 9, 'white': 10})
SRC.build_vocab(train_data, min_freq=2)
TRG.build_vocab(train_data, min_freq=2)

print(f"Unique tokens in source (de) vocabulary: {len(SRC.vocab)}")
print(f"Unique tokens in target (en) vocabulary: {len(TRG.vocab)}")

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

BATCH_SIZE = 128

train_iterator, valid_iterator, test_iterator = BucketIterator.splits(
    (train_data, valid_data, test_data),
    batch_size=BATCH_SIZE,
    device=device)

class Encoder(nn.Module):
    def __init__(self, input_dim, emb_dim, hid_dim, n_layers, dropout):
        super().__init__()

        self.hid_dim = hid_dim
        self.n_layers = n_layers

        self.embedding = nn.Embedding(input_dim, emb_dim)

        self.rnn = nn.LSTM(emb_dim, hid_dim, n_layers, dropout=dropout)

        self.dropout = nn.Dropout(dropout)

    def forward(self, src):
        # src = [src len, batch size]

        embedded = self.dropout(self.embedding(src))

        # embedded = [src len, batch size, emb dim]

        outputs, (hidden, cell) = self.rnn(embedded)

        # outputs = [src len, batch size, hid dim * n directions]
        # hidden = [n layers * n directions, batch size, hid dim]
        # cell = [n layers * n directions, batch size, hid dim]

        # outputs are always from the top hidden layer

        return hidden, cell

class Decoder(nn.Module):
    def __init__(self, output_dim, emb_dim, hid_dim, n_layers, dropout):
        super().__init__()

        self.output_dim = output_dim
        self.hid_dim = hid_dim
        self.n_layers = n_layers

        self.embedding = nn.Embedding(output_dim, emb_dim)

        self.rnn = nn.LSTM(emb_dim, hid_dim, n_layers, dropout=dropout)

        self.fc_out = nn.Linear(hid_dim, output_dim)

        self.dropout = nn.Dropout(dropout)

    def forward(self, input, hidden, cell):
        # input = [batch size]
        # hidden = [n layers * n directions, batch size, hid dim]
        # cell = [n layers * n directions, batch size, hid dim]

        # n directions in the decoder will both always be 1, therefore:
        # hidden = [n layers, batch size, hid dim]
        # context = [n layers, batch size, hid dim]

        input = input.unsqueeze(0)

        # input = [1, batch size]

        embedded = self.dropout(self.embedding(input))

        # embedded = [1, batch size, emb dim]

        output, (hidden, cell) = self.rnn(embedded, (hidden, cell))

        # output = [seq len, batch size, hid dim * n directions]
        # hidden = [n layers * n directions, batch size, hid dim]
        # cell = [n layers * n directions, batch size, hid dim]

        # seq len and n directions will always be 1 in the decoder, therefore:
        # output = [1, batch size, hid dim]
        # hidden = [n layers, batch size, hid dim]
        # cell = [n layers, batch size, hid dim]

        prediction = self.fc_out(output.squeeze(0))

        # prediction = [batch size, output dim]

        return prediction, hidden, cell

class Seq2Seq(nn.Module):
    def __init__(self, encoder, decoder, device):
        super().__init__()

        self.encoder = encoder
        self.decoder = decoder
        self.device = device

        assert encoder.hid_dim == decoder.hid_dim, \
            "Hidden dimensions of encoder and decoder must be equal!"
        assert encoder.n_layers == decoder.n_layers, \
            "Encoder and decoder must have equal number of layers!"

    def forward(self, src, trg, teacher_forcing_ratio=0.5):
        # src = [src len, batch size]
        # trg = [trg len, batch size]
        # teacher_forcing_ratio is probability to use teacher forcing
        # e.g. if teacher_forcing_ratio is 0.75 we use ground-truth inputs 75% of the time

        batch_size = trg.shape[1]
        trg_len = trg.shape[0]
        trg_vocab_size = self.decoder.output_dim

        # tensor to store decoder outputs
        outputs = torch.zeros(trg_len, batch_size, trg_vocab_size).to(self.device)

        # last hidden state of the encoder is used as the initial hidden state of the decoder
        hidden, cell = self.encoder(src)

        # first input to the decoder is the <sos> tokens
        input = trg[0, :]

        for t in range(1, trg_len):
            # insert input token embedding, previous hidden and previous cell states
            # receive output tensor (predictions) and new hidden and cell states
            output, hidden, cell = self.decoder(input, hidden, cell)

            # place predictions in a tensor holding predictions for each token
            outputs[t] = output

            # decide if we are going to use teacher forcing or not
            teacher_force = random.random() < teacher_forcing_ratio

            # get the highest predicted token from our predictions
            top1 = output.argmax(1)

            # if teacher forcing, use actual next token as next input
            # if not, use predicted token
            input = trg[t] if teacher_force else top1

        return outputs

INPUT_DIM = len(SRC.vocab)
OUTPUT_DIM = len(TRG.vocab)
ENC_EMB_DIM = 256
DEC_EMB_DIM = 256
HID_DIM = 512
N_LAYERS = 2
ENC_DROPOUT = 0.5
DEC_DROPOUT = 0.5

enc = Encoder(INPUT_DIM, ENC_EMB_DIM, HID_DIM, N_LAYERS, ENC_DROPOUT)
dec = Decoder(OUTPUT_DIM, DEC_EMB_DIM, HID_DIM, N_LAYERS, DEC_DROPOUT)

model = Seq2Seq(enc, dec, device).to(device)

def init_weights(m):
    for name, param in m.named_parameters():
        nn.init.uniform_(param.data, -0.08, 0.08)

model.apply(init_weights)

def count_parameters(model):
    return sum(p.numel() for p in model.parameters() if p.requires_grad)

print(f'The model has {count_parameters(model):,} trainable parameters')

optimizer = optim.Adam(model.parameters())

TRG_PAD_IDX = TRG.vocab.stoi[TRG.pad_token]

criterion = nn.CrossEntropyLoss(ignore_index=TRG_PAD_IDX)

def train(model, iterator, optimizer, criterion, clip):
    model.train()

    epoch_loss = 0

    for i, batch in enumerate(iterator):
        src = batch.src
        trg = batch.trg

        optimizer.zero_grad()

        output = model(src, trg)

        # trg = [trg len, batch size]
        # output = [trg len, batch size, output dim]

        output_dim = output.shape[-1]

        output = output[1:].view(-1, output_dim)
        trg = trg[1:].view(-1)

        # trg = [(trg len - 1) * batch size]
        # output = [(trg len - 1) * batch size, output dim]

        loss = criterion(output, trg)

        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), clip)

        optimizer.step()

        epoch_loss += loss.item()

    return epoch_loss / len(iterator)

def evaluate(model, iterator, criterion):
    model.eval()

    epoch_loss = 0

    with torch.no_grad():
        for i, batch in enumerate(iterator):
            src = batch.src
            trg = batch.trg

            output = model(src, trg, 0)  # turn off teacher forcing

            # trg = [trg len, batch size]
            # output = [trg len, batch size, output dim]

            output_dim = output.shape[-1]

            output = output[1:].view(-1, output_dim)
            trg = trg[1:].view(-1)

            # trg = [(trg len - 1) * batch size]
            # output = [(trg len - 1) * batch size, output dim]

            loss = criterion(output, trg)

            epoch_loss += loss.item()

    return epoch_loss / len(iterator)

def epoch_time(start_time, end_time):
    elapsed_time = end_time - start_time
    elapsed_mins = int(elapsed_time / 60)
    elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
    return elapsed_mins, elapsed_secs

N_EPOCHS = 10
CLIP = 1

best_valid_loss = float('inf')
is_train = False
if is_train:
    for epoch in range(N_EPOCHS):

        start_time = time.time()

        train_loss = train(model, train_iterator, optimizer, criterion, CLIP)
        valid_loss = evaluate(model, valid_iterator, criterion)

        end_time = time.time()

        epoch_mins, epoch_secs = epoch_time(start_time, end_time)

        if valid_loss < best_valid_loss:
            best_valid_loss = valid_loss
            torch.save(model.state_dict(), 'tut1-model.pt')

        print(f'Epoch: {epoch + 1:02} | Time: {epoch_mins}m {epoch_secs}s')
        print(f'\tTrain Loss: {train_loss:.3f} | Train PPL: {math.exp(train_loss):7.3f}')
        print(f'\t Val. Loss: {valid_loss:.3f} |  Val. PPL: {math.exp(valid_loss):7.3f}')

model.load_state_dict(torch.load('tut1-model.pt'))

test_loss = evaluate(model, test_iterator, criterion)

print(f'| Test Loss: {test_loss:.3f} | Test PPL: {math.exp(test_loss):7.3f} |')


text:
Remote-friendly scrum checkins without the annoying meetings.

A portfolio project for professional developers to highlight skills with modern tech stacks like React, Redux, Serverless, etc. [EricElliottJS.com](https://ericelliottjs.com).

## Instructions

Fork this repository and implement your own Checkin app. To get credit on EricElliottJS.com or DevAnywhere:

* [ ] [Deploy on Vercel](https://vercel.com/).
* [ ] Open an issue and include links to the deployed app and your forked repo.
* [ ] [Ping us on Twitter](https://twitter.com/intent/tweet?text=I%20just%20completed%20the%20Checkin%20app%20on%20EricElliottJS.com%20%40JS_Cheerleader%20%23JavaScript%20%23code) (fastest response)

## Tech Stack Checklist

* [ ] [Use Next.JS](https://nextjs.org/)
* [ ] [Setup automatic lint and prettier runs](https://medium.com/javascript-scene/streamline-code-reviews-with-eslint-prettier-6fb817a6b51d)
* [ ] [Deploy on Vercel](https://vercel.com/)
* [ ] [Authenticate users with Magic](https://magic.link/)
* [ ] [Store data in Firebase](https://firebase.google.com/)
* [ ] [Don't commit secrets to the repo](https://nextjs.org/docs/basic-features/environment-variables)

Related: [The 12-Factor App](https://12factor.net/)

## What's a Scrum Checkin?

In agile development, we strive to implement the minimum effective amount of process to enable [high velocity development](https://medium.com/javascript-scene/how-to-build-a-high-velocity-development-team-4b2360d34021).

The scrum meeting is a common element of that minimal process. Its purpose is to allow team members to check in with each other. On each work day, each small team gathers to answer three questions:

* [ ] What did you do on the last workday?
* [ ] What are you doing today?
* [ ] Is there anything blocking you?

Scrum teams should be small, so these meetings should last less than 15 minutes.

But what about distributed teams working in different timezones? And even a 15 minute meeting is still expensive. What if you could get even better visibility without the inefficiency of a meeting?

That's where this app comes in.

## Basic Requirements

Don't worry about anything but getting the user interfaces to work. No need for user authorization, databases, or API's for now. Feel free to make some fake users and fake checkin data.

* [ ] Allow a user to create and name teams. Users own the teams they create.
* [ ] Allow a user to check in with a specific team.
* [ ] View the team status: A simple display of a running log of all the team's checkins, grouped by day.

Here's a sketch of the checkin feature.

## Screen 1: Previous Day

```

Your last checkin said you would:

* [ ] Write the README for the checkin app
* [ ] Document the stack requirements
* [ ] Complete 2 code reviews
* + Add another item

Were there any blockers? If so, please list briefly below (one line each):

* + Add a blocker from your previous checkin

Please check the items you completed, and add any additional items you completed.

[ Done ]

```

## Screen 2: Today

Carry over unfinished items from the previous day. User should be able to delete tasks.

```

What will you work on today? Try to list 3-5 things you think you can **complete** today.

* [ ] <Priority 1 Task>
* [ ] <Priority 2 Task>
* [ ] <Priority 3 Task>
* + Add another task you can probably complete today

```

Blockers:

Carry over any previous blockers that are not checked off.

```
Do important tasks have any blockers? If so, please list them briefly, below:

* + Add a blocker for today's tasks
```

## Screen 3:

```

1 - 5 words, what are we doing well? (optional)

[ <text input> ]

In 1 - 5 words, what needs improvement? (optional)

[ <text input> ]

Great! How are you feeling today?

🙁 😐 😃

[ Done ]

```

## Screen 4:

```

That's it. Have a great day! 🎉

```

### Mid Level Requirements

* [ ] Allow a user to join an existing team.
* [ ] Store data on a remote server and let other users sign up.
* [ ] Implement the [user stories](user-stories.md).

### Advanced Requirements

* [ ] Integrate with Slack and post reports.
* [ ] Integrate with Github. On the "What will you work on today?" feature, provide an option to link a GitHub issue from their assigned issues.
* [ ] Automate checkin updates to mark items as done when linked issues get closed on GitHub.
* [ ] Add realtime capability and update today's checkins view as checkins are added, statuses change, and checklist items get marked complete.

## License Terms

By implementing the app described above and posting it publicly on GitHub, you agree to the following license terms:

**"You"** or **"Your"** means the rights holder. **"Contributions"** means any software, images, audio, or other creative work produced by you during the course of working on this project. **Recipients** means anyone who recieves the software by any means, in any medium, or through any distribution channel.

* **You Own Your Creative Work.** You reserve all right, title, and interest in and to Your Contributions. You may use your solo projects in your portfolio.
* **Grant of Copyright License.** Subject to the terms and conditions of this Agreement, You hereby grant to Recipients of this software a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute Your Contributions and such derivative works.
* **Grant of Patent License.** Subject to the terms and conditions of this Agreement, you hereby grant to recipients of this software patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work.

You represent that you are legally entitled to grant the above license.


text:
var paginationInstance = (
  <Pagination>
    <Pagination.Item prev href="#">« Prev</Pagination.Item>
    <Pagination.Item next href="#">Next »</Pagination.Item>
  </Pagination>
);

React.render(paginationInstance, mountNode);


text:
namespace RubberPlant
{
    // Required for testing purposes.
    public interface IRandom
    {
        double NextDouble();
    }
}


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;

/**
 * VideosSearch represents the model behind the search form about `app\models\Videos`.
 */
class VideosSearch extends Videos
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['video_id', 'rating', 'user_id'], 'integer'],
            [['url', 'module', 'title', 'description', 'date'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Videos::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'video_id' => $this->video_id,
            'date' => $this->date,
            'rating' => $this->rating,
            'user_id' => $this->user_id,
        ]);

        $query->andFilterWhere(['like', 'url', $this->url])
            ->andFilterWhere(['like', 'module', $this->module])
            ->andFilterWhere(['like', 'title', $this->title])
            ->andFilterWhere(['like', 'description', $this->description]);

        return $dataProvider;
    }
}