text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <gradient
                android:startColor="#FFFFFF"
                android:endColor="#BBBBBB"
                android:angle="45" />
        </shape>
    </item>
</layer-list>

redpajama_set_name: RedPajamaGithub


text:
namespace Dapper.FastCrud.Dto.Entity.Builders.DtoToDb
{
    using System;
    using System.Linq.Expressions;
    using Dapper.FastCrud.Dto.Mappings;

    public class DtoMappingBuilder<TDto, TDb>
    {
        private readonly AggregatorMapping<TDto, TDb> _mapping;

        public DtoMappingBuilder(AggregatorMapping<TDto, TDb> mapping)
        {
            _mapping = mapping;
        }

        /// <summary>
        /// Creates a mapping on a DTO property
        /// </summary>
        public DtoPropertyMappingBuilder<TDto, TDb> Property(Expression<Func<TDto, object>> property)
        {
            var dtoProperty = _mapping.DtoPropertyRegistrations.Add(property);

            return new DtoPropertyMappingBuilder<TDto, TDb>(dtoProperty, _mapping);
        }

        /// <summary>
        /// Creates a mapping for a set of DTO properties
        /// </summary>
        public DtoPropertiesMappingBuilder<TDto, TDb> Properties(params Expression<Func<TDto, object>>[] properties)
        {
            _mapping.DtoPropertyRegistrations.AddRange(properties);

            return new DtoPropertiesMappingBuilder<TDto, TDb>(_mapping);
        }

    }
}


text:
// Copyright (c) Ratish Philip
//
//
// 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.
//
// This file is part of the CompositionProToolkit project:
// https://github.com/ratishphilip/CompositionProToolkit
//
// CompositionProToolkit v1.0.1
//

using System;
using System.Numerics;
using System.Text;
using System.Text.RegularExpressions;
using CompositionProToolkit.Win2d.Common;
using CompositionProToolkit.Win2d.Core;
using Microsoft.Graphics.Canvas.Geometry;

namespace CompositionProToolkit.Win2d.Geometry.Path
{
    /// <summary>
    /// Class representing the Smooth Quadratic Bezier Element in a Path Geometry
    /// </summary>
    internal class SmoothQuadraticBezierElement : AbstractPathElement
    {
        #region Fields

        private float _x;
        private float _y;
        private Vector2 _absoluteControlPoint;

        #endregion

        #region Construction / Initialization

        /// <summary>
        /// ctor
        /// </summary>
        public SmoothQuadraticBezierElement()
        {
            _x = _y = 0;
            _absoluteControlPoint = Vector2.Zero;
        }

        #endregion

        #region APIs

        /// <summary>
        /// Adds the Path Element to the Path.
        /// </summary>
        /// <param name="pathBuilder">CanvasPathBuilder object</param>
        /// <param name="currentPoint">The last active location in the Path before adding
        /// the Path Element</param>
        /// <param name="lastElement">The previous PathElement in the Path.</param>
        /// <param name="logger">For logging purpose. To log the set of CanvasPathBuilder
        /// commands, used for creating the CanvasGeometry, in string format.</param>
        /// <returns>The latest location in the Path after adding the Path Element</returns>
        public override Vector2 CreatePath(CanvasPathBuilder pathBuilder, Vector2 currentPoint,
            ref ICanvasPathElement lastElement, StringBuilder logger)
        {
            // Calculate coordinates
            // Check if the last element was a Quadratic Bezier
            var quadBezier = lastElement as QuadraticBezierElement;
            if (quadBezier != null)
            {
                // Reflect the control point of the Quadratic Bezier over the current point. The
                // resulting point will be the control point of this Bezier.
                _absoluteControlPoint = Utils.Reflect(quadBezier.GetControlPoint(), currentPoint);
            }
            // Or if the last element was s Smooth Quadratic Bezier
            else
            {
                var smoothQuadBezier = lastElement as SmoothQuadraticBezierElement;
                // If the last element was a Smooth Quadratic Bezier then reflect its control point
                // over the current point. The resulting point will be the control point of this
                // Bezier. Otherwise, if the last element was not a Smooth Quadratic Bezier,
                // then the currentPoint will be the control point of this Bezier.
                _absoluteControlPoint = smoothQuadBezier != null
                    ? Utils.Reflect(smoothQuadBezier.GetControlPoint(), currentPoint)
                    : currentPoint;
            }

            var point = new Vector2(_x, _y);

            if (IsRelative)
            {
                point += currentPoint;
            }

            // Execute command
            pathBuilder.AddQuadraticBezier(_absoluteControlPoint, point);

            // Log command
            logger?.Append($"{Indent}pathBuilder.AddQuadraticBezier(new Vector2({_absoluteControlPoint.X},");
            logger?.AppendLine($" {_absoluteControlPoint.Y}), new Vector2({point.X}, {point.Y}));");

            // Set Last Element
            lastElement = this;
            // Return current point
            return point;
        }

        /// <summary>
        /// Gets the Control Point of this Quadratic Bezier
        /// </summary>
        /// <returns>Vector2</returns>
        public Vector2 GetControlPoint()
        {
            return _absoluteControlPoint;
        }

        #endregion

        #region Helpers

        /// <summary>
        /// Get the Regex for extracting Path Element Attributes
        /// </summary>
        /// <returns></returns>
        protected override Regex GetAttributesRegex()
        {
            return RegexFactory.GetAttributesRegex(PathElementType.SmoothQuadraticBezier);
        }

        /// <summary>
        /// Gets the Path Element Attributes from the Match
        /// </summary>
        /// <param name="match">Match object</param>
        protected override void GetAttributes(Match match)
        {
            Single.TryParse(match.Groups["X"].Value, out _x);
            Single.TryParse(match.Groups["Y"].Value, out _y);
        }

        #endregion
    }
}


text:
namespace WpfTestApp.Features.Error
{
    using Miruken.Mvc.Wpf;

    public partial class Faulty : View
    {
        public Faulty()
        {
            InitializeComponent();
        }
    }
}


text:
use std::future::Future;
use std::pin::Pin;
use tokio::io::{self, AsyncBufRead, AsyncBufReadExt};

use crate::events::Event;
use crate::name::{QName, ResolveResult};
use crate::reader::buffered_reader::impl_buffered_source;
use crate::reader::{
    is_whitespace, BangType, NsReader, ParseState, ReadElementState, Reader, Span,
};
use crate::{Error, Result};

/// A struct for read XML asynchronously from an [`AsyncBufRead`].
///
/// Having own struct allows us to implement anything without risk of name conflicts
/// and does not suffer from the impossibility of having `async` in traits.
struct TokioAdapter<'a, R>(&'a mut R);

impl<'a, R: AsyncBufRead + Unpin> TokioAdapter<'a, R> {
    impl_buffered_source!('b, 0, async, await);
}

////////////////////////////////////////////////////////////////////////////////////////////////////

impl<R: AsyncBufRead + Unpin> Reader<R> {
    /// An asynchronous version of [`read_event_into()`]. Reads the next event into
    /// given buffer.
    ///
    /// > This function should be defined as
    /// > ```ignore
    /// > pub async fn read_event_into_async<'b>(
    /// >     &mut self,
    /// >     buf: &'b mut Vec<u8>
    /// > ) -> Result<Event<'b>>;
    /// > ```
    /// > but Rust does not allow to write that for recursive asynchronous function
    ///
    /// This is the main entry point for reading XML `Event`s when using an async reader.
    ///
    /// See the documentation of [`read_event_into()`] for more information.
    ///
    /// # Examples
    ///
    /// ```
    /// # tokio_test::block_on(async {
    /// # use pretty_assertions::assert_eq;
    /// use quick_xml::events::Event;
    /// use quick_xml::reader::Reader;
    ///
    /// // This explicitly uses `from_reader("...".as_bytes())` to use a buffered
    /// // reader instead of relying on the zero-copy optimizations for reading
    /// // from byte slices, which is provides the sync interface anyway.
    /// let mut reader = Reader::from_reader(r#"
    ///     <tag1 att1 = "test">
    ///        <tag2><!--Test comment-->Test</tag2>
    ///        <tag2>Test 2</tag2>
    ///     </tag1>
    /// "#.as_bytes());
    /// reader.trim_text(true);
    ///
    /// let mut count = 0;
    /// let mut buf = Vec::new();
    /// let mut txt = Vec::new();
    /// loop {
    ///     match reader.read_event_into_async(&mut buf).await {
    ///         Ok(Event::Start(_)) => count += 1,
    ///         Ok(Event::Text(e)) => txt.push(e.unescape().unwrap().into_owned()),
    ///         Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
    ///         Ok(Event::Eof) => break,
    ///         _ => (),
    ///     }
    ///     buf.clear();
    /// }
    /// assert_eq!(count, 3);
    /// assert_eq!(txt, vec!["Test".to_string(), "Test 2".to_string()]);
    /// # }) // tokio_test::block_on
    /// ```
    ///
    /// [`read_event_into()`]: Reader::read_event_into
    pub fn read_event_into_async<'reader, 'b: 'reader>(
        &'reader mut self,
        buf: &'b mut Vec<u8>,
    ) -> Pin<Box<dyn Future<Output = Result<Event<'b>>> + 'reader>> {
        Box::pin(async move {
            read_event_impl!(
                self, buf,
                TokioAdapter(&mut self.reader),
                read_until_open_async,
                read_until_close_async,
                await
            )
        })
    }

    /// An asynchronous version of [`read_to_end_into()`].
    /// Reads asynchronously until end element is found using provided buffer as
    /// intermediate storage for events content. This function is supposed to be
    /// called after you already read a [`Start`] event.
    ///
    /// See the documentation of [`read_to_end_into()`] for more information.
    ///
    /// # Examples
    ///
    /// This example shows, how you can skip XML content after you read the
    /// start event.
    ///
    /// ```
    /// # tokio_test::block_on(async {
    /// # use pretty_assertions::assert_eq;
    /// use quick_xml::events::{BytesStart, Event};
    /// use quick_xml::reader::Reader;
    ///
    /// let mut reader = Reader::from_reader(r#"
    ///     <outer>
    ///         <inner>
    ///             <inner></inner>
    ///             <inner/>
    ///             <outer></outer>
    ///             <outer/>
    ///         </inner>
    ///     </outer>
    /// "#.as_bytes());
    /// reader.trim_text(true);
    /// let mut buf = Vec::new();
    ///
    /// let start = BytesStart::new("outer");
    /// let end   = start.to_end().into_owned();
    ///
    /// // First, we read a start event...
    /// assert_eq!(reader.read_event_into_async(&mut buf).await.unwrap(), Event::Start(start));
    ///
    /// // ...then, we could skip all events to the corresponding end event.
    /// // This call will correctly handle nested <outer> elements.
    /// // Note, however, that this method does not handle namespaces.
    /// reader.read_to_end_into_async(end.name(), &mut buf).await.unwrap();
    ///
    /// // At the end we should get an Eof event, because we ate the whole XML
    /// assert_eq!(reader.read_event_into_async(&mut buf).await.unwrap(), Event::Eof);
    /// # }) // tokio_test::block_on
    /// ```
    ///
    /// [`read_to_end_into()`]: Self::read_to_end_into
    /// [`Start`]: Event::Start
    pub async fn read_to_end_into_async<'n>(
        &mut self,
        // We should name that lifetime due to https://github.com/rust-lang/rust/issues/63033`
        end: QName<'n>,
        buf: &mut Vec<u8>,
    ) -> Result<Span> {
        Ok(read_to_end!(self, end, buf, read_event_into_async, { buf.clear(); }, await))
    }

    /// Read until '<' is found, moves reader to an `OpenedTag` state and returns a `Text` event.
    async fn read_until_open_async<'b>(&mut self, buf: &'b mut Vec<u8>) -> Result<Event<'b>> {
        read_until_open!(self, buf, TokioAdapter(&mut self.reader), read_event_into_async, await)
    }

    /// Private function to read until `>` is found. This function expects that
    /// it was called just after encounter a `<` symbol.
    async fn read_until_close_async<'b>(&mut self, buf: &'b mut Vec<u8>) -> Result<Event<'b>> {
        read_until_close!(self, buf, TokioAdapter(&mut self.reader), await)
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////

impl<R: AsyncBufRead + Unpin> NsReader<R> {
    /// An asynchronous version of [`read_event_into()`]. Reads the next event into
    /// given buffer.
    ///
    /// This method manages namespaces but doesn't resolve them automatically.
    /// You should call [`resolve_element()`] if you want to get a namespace.
    ///
    /// You also can use [`read_resolved_event_into_async()`] instead if you want
    /// to resolve namespace as soon as you get an event.
    ///
    /// # Examples
    ///
    /// ```
    /// # tokio_test::block_on(async {
    /// # use pretty_assertions::assert_eq;
    /// use quick_xml::events::Event;
    /// use quick_xml::name::{Namespace, ResolveResult::*};
    /// use quick_xml::reader::NsReader;
    ///
    /// let mut reader = NsReader::from_reader(r#"
    ///     <x:tag1 xmlns:x="www.xxxx" xmlns:y="www.yyyy" att1 = "test">
    ///        <y:tag2><!--Test comment-->Test</y:tag2>
    ///        <y:tag2>Test 2</y:tag2>
    ///     </x:tag1>
    /// "#.as_bytes());
    /// reader.trim_text(true);
    ///
    /// let mut count = 0;
    /// let mut buf = Vec::new();
    /// let mut txt = Vec::new();
    /// loop {
    ///     match reader.read_event_into_async(&mut buf).await.unwrap() {
    ///         Event::Start(e) => {
    ///             count += 1;
    ///             let (ns, local) = reader.resolve_element(e.name());
    ///             match local.as_ref() {
    ///                 b"tag1" => assert_eq!(ns, Bound(Namespace(b"www.xxxx"))),
    ///                 b"tag2" => assert_eq!(ns, Bound(Namespace(b"www.yyyy"))),
    ///                 _ => unreachable!(),
    ///             }
    ///         }
    ///         Event::Text(e) => {
    ///             txt.push(e.unescape().unwrap().into_owned())
    ///         }
    ///         Event::Eof => break,
    ///         _ => (),
    ///     }
    ///     buf.clear();
    /// }
    /// assert_eq!(count, 3);
    /// assert_eq!(txt, vec!["Test".to_string(), "Test 2".to_string()]);
    /// # }) // tokio_test::block_on
    /// ```
    ///
    /// [`read_event_into()`]: NsReader::read_event_into
    /// [`resolve_element()`]: Self::resolve_element
    /// [`read_resolved_event_into_async()`]: Self::read_resolved_event_into_async
    pub async fn read_event_into_async<'b>(&mut self, buf: &'b mut Vec<u8>) -> Result<Event<'b>> {
        self.pop();
        let event = self.reader.read_event_into_async(buf).await;
        self.process_event(event)
    }

    /// An asynchronous version of [`read_to_end_into()`].
    /// Reads asynchronously until end element is found using provided buffer as
    /// intermediate storage for events content. This function is supposed to be
    /// called after you already read a [`Start`] event.
    ///
    /// See the documentation of [`read_to_end_into()`] for more information.
    ///
    /// # Examples
    ///
    /// This example shows, how you can skip XML content after you read the
    /// start event.
    ///
    /// ```
    /// # tokio_test::block_on(async {
    /// # use pretty_assertions::assert_eq;
    /// use quick_xml::name::{Namespace, ResolveResult};
    /// use quick_xml::events::{BytesStart, Event};
    /// use quick_xml::reader::NsReader;
    ///
    /// let mut reader = NsReader::from_reader(r#"
    ///     <outer xmlns="namespace 1">
    ///         <inner xmlns="namespace 2">
    ///             <outer></outer>
    ///         </inner>
    ///         <inner>
    ///             <inner></inner>
    ///             <inner/>
    ///             <outer></outer>
    ///             <p:outer xmlns:p="ns"></p:outer>
    ///             <outer/>
    ///         </inner>
    ///     </outer>
    /// "#.as_bytes());
    /// reader.trim_text(true);
    /// let mut buf = Vec::new();
    ///
    /// let ns = Namespace(b"namespace 1");
    /// let start = BytesStart::from_content(r#"outer xmlns="namespace 1""#, 5);
    /// let end   = start.to_end().into_owned();
    ///
    /// // First, we read a start event...
    /// assert_eq!(
    ///     reader.read_resolved_event_into_async(&mut buf).await.unwrap(),
    ///     (ResolveResult::Bound(ns), Event::Start(start))
    /// );
    ///
    /// // ...then, we could skip all events to the corresponding end event.
    /// // This call will correctly handle nested <outer> elements.
    /// // Note, however, that this method does not handle namespaces.
    /// reader.read_to_end_into_async(end.name(), &mut buf).await.unwrap();
    ///
    /// // At the end we should get an Eof event, because we ate the whole XML
    /// assert_eq!(
    ///     reader.read_resolved_event_into_async(&mut buf).await.unwrap(),
    ///     (ResolveResult::Unbound, Event::Eof)
    /// );
    /// # }) // tokio_test::block_on
    /// ```
    ///
    /// [`read_to_end_into()`]: Self::read_to_end_into
    /// [`Start`]: Event::Start
    pub async fn read_to_end_into_async<'n>(
        &mut self,
        // We should name that lifetime due to https://github.com/rust-lang/rust/issues/63033`
        end: QName<'n>,
        buf: &mut Vec<u8>,
    ) -> Result<Span> {
        // According to the https://www.w3.org/TR/xml11/#dt-etag, end name should
        // match literally the start name. See `Reader::check_end_names` documentation
        self.reader.read_to_end_into_async(end, buf).await
    }

    /// An asynchronous version of [`read_resolved_event_into()`]. Reads the next
    /// event into given buffer asynchronously and resolves its namespace (if applicable).
    ///
    /// Namespace is resolved only for [`Start`], [`Empty`] and [`End`] events.
    /// For all other events the concept of namespace is not defined, so
    /// a [`ResolveResult::Unbound`] is returned.
    ///
    /// If you are not interested in namespaces, you can use [`read_event_into_async()`]
    /// which will not automatically resolve namespaces for you.
    ///
    /// # Examples
    ///
    /// ```
    /// # tokio_test::block_on(async {
    /// # use pretty_assertions::assert_eq;
    /// use quick_xml::events::Event;
    /// use quick_xml::name::{Namespace, QName, ResolveResult::*};
    /// use quick_xml::reader::NsReader;
    ///
    /// let mut reader = NsReader::from_reader(r#"
    ///     <x:tag1 xmlns:x="www.xxxx" xmlns:y="www.yyyy" att1 = "test">
    ///        <y:tag2><!--Test comment-->Test</y:tag2>
    ///        <y:tag2>Test 2</y:tag2>
    ///     </x:tag1>
    /// "#.as_bytes());
    /// reader.trim_text(true);
    ///
    /// let mut count = 0;
    /// let mut buf = Vec::new();
    /// let mut txt = Vec::new();
    /// loop {
    ///     match reader.read_resolved_event_into_async(&mut buf).await.unwrap() {
    ///         (Bound(Namespace(b"www.xxxx")), Event::Start(e)) => {
    ///             count += 1;
    ///             assert_eq!(e.local_name(), QName(b"tag1").into());
    ///         }
    ///         (Bound(Namespace(b"www.yyyy")), Event::Start(e)) => {
    ///             count += 1;
    ///             assert_eq!(e.local_name(), QName(b"tag2").into());
    ///         }
    ///         (_, Event::Start(_)) => unreachable!(),
    ///
    ///         (_, Event::Text(e)) => {
    ///             txt.push(e.unescape().unwrap().into_owned())
    ///         }
    ///         (_, Event::Eof) => break,
    ///         _ => (),
    ///     }
    ///     buf.clear();
    /// }
    /// assert_eq!(count, 3);
    /// assert_eq!(txt, vec!["Test".to_string(), "Test 2".to_string()]);
    /// # }) // tokio_test::block_on
    /// ```
    ///
    /// [`read_resolved_event_into()`]: NsReader::read_resolved_event_into
    /// [`Start`]: Event::Start
    /// [`Empty`]: Event::Empty
    /// [`End`]: Event::End
    /// [`read_event_into_async()`]: Self::read_event_into_async
    pub async fn read_resolved_event_into_async<'ns, 'b>(
        // Name 'ns lifetime, because otherwise we get an error
        // "implicit elided lifetime not allowed here" on ResolveResult
        &'ns mut self,
        buf: &'b mut Vec<u8>,
    ) -> Result<(ResolveResult<'ns>, Event<'b>)> {
        let event = self.read_event_into_async(buf).await;
        self.resolve_event(event)
    }
}

#[cfg(test)]
mod test {
    use super::TokioAdapter;
    use crate::reader::test::{check, small_buffers};

    check!(
        #[tokio::test]
        read_event_into_async,
        read_until_close_async,
        TokioAdapter,
        &mut Vec::new(),
        async, await
    );

    small_buffers!(
        #[tokio::test]
        read_event_into_async: tokio::io::BufReader<_>,
        async, await
    );
}


text:
<?php

namespace Application\PrizesBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;

use Application\PrizesBundle\Entity\PrizesLottery;
use Application\UsersBundle\Entity\Users;

/**
 * Application\PrizesBundle\Entity\PrizesLotteryMembers
 *
 * @ORM\Table(name="prizes_lottery_members")
 * @ORM\Entity(repositoryClass="Application\PrizesBundle\Repository\PrizesLotteryMembers")
 * @ORM\HasLifecycleCallbacks
 */
class PrizesLotteryMembers
{

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

    /**
     * @var \Application\PrizesBundle\Entity\PrizesLottery
     *
     * @ORM\ManyToOne(targetEntity="PrizesLottery", inversedBy="prizesLotteryMembers")
     * @ORM\JoinColumn(name="prize_lottery__id", referencedColumnName="id")
     */
    protected $prizeLottery;

    /**
     * @var \Application\UsersBundle\Entity\Users
     *
     * @ORM\ManyToOne(targetEntity="Application\UsersBundle\Entity\Users", inversedBy="prizesLotteryMembers")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    protected $user;

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

    /**
     * @var \Application\PrizesBundle\Entity\PrizesLottery
     *
     * @ORM\OneToOne(targetEntity="PrizesLottery", mappedBy="memberWinner")
     */
    protected $prizesLotteryWinner;

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param \DateTime $createdAt
     * @return \Application\PrizesBundle\Entity\PrizesLotteryMembers
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;
        return $this;
    }

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

    /**
     * @param \Application\PrizesBundle\Entity\PrizesLottery $prizeLottery
     * @return \Application\PrizesBundle\Entity\PrizesLotteryMembers
     */
    public function setPrizeLottery(PrizesLottery $prizeLottery)
    {
        $this->prizeLottery = $prizeLottery;
        return $this;
    }

    /**
     * @return \Application\PrizesBundle\Entity\PrizesLottery
     */
    public function getPrizeLottery()
    {
        return $this->prizeLottery;
    }

    /**
     * @param \Application\UsersBundle\Entity\Users $user
     * @return \Application\PrizesBundle\Entity\PrizesLotteryMembers
     */
    public function setUser(Users $user)
    {
        $this->user = $user;
        return $this;
    }

    /**
     * @return \Application\UsersBundle\Entity\Users
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * @param \Application\PrizesBundle\Entity\PrizesLottery $prizesLotteryWinner
     * @return \Application\PrizesBundle\Entity\PrizesLotteryMembers
     */
    public function setPrizesLotteryWinner(PrizesLottery $prizesLotteryWinner)
    {
        $this->prizesLotteryWinner = $prizesLotteryWinner;
        return $this;
    }

    /**
     * @return \Application\PrizesBundle\Entity\PrizesLottery
     */
    public function getPrizesLotteryWinner()
    {
        return $this->prizesLotteryWinner;
    }

}


text:
<?php

use XeroPHP\Application\PublicApplication;
use XeroPHP\Remote\Request;
use XeroPHP\Remote\URL;

// Start a session for the oauth session storage
session_start();

//These are the minimum settings - for more options, refer to examples/config.php
$config = array(
    'oauth' => array(
        'callback'        => 'http://localhost/',
        'consumer_key'    => 'k',
        'consumer_secret' => 's',
    ),
    'curl' => array(
        CURLOPT_CAINFO => __DIR__.'/certs/ca-bundle.crt',
    ),
);

$xero = new PublicApplication($config);

//if no session or if it is expired
if(null === $oauth_session = getOAuthSession()){

    $url = new URL($xero, URL::OAUTH_REQUEST_TOKEN);
    $request = new Request($xero, $url);

    //Here's where you'll see if your keys are valid.  You can catch a BadRequestException.
    try {
        $request->send();
    } catch (Exception $e){
        print_r($e);
        if ($request->getResponse()) {
            print_r($request->getResponse()->getOAuthResponse());
        }
    }

    $oauth_response = $request->getResponse()->getOAuthResponse();

    setOAuthSession($oauth_response['oauth_token'], $oauth_response['oauth_token_secret']);

    printf('Click here to Authorize', $xero->getAuthorizeURL($oauth_response['oauth_token']));
    exit;

} else {

    $xero->getOAuthClient()
        ->setToken($oauth_session['token'])
        ->setTokenSecret($oauth_session['token_secret']);

    if(isset($_REQUEST['oauth_verifier'])){
        $xero->getOAuthClient()->setVerifier($_REQUEST['oauth_verifier']);

        $url = new URL($xero, URL::OAUTH_ACCESS_TOKEN);
        $request = new Request($xero, $url);

        $request->send();
        $oauth_response = $request->getResponse()->getOAuthResponse();

        setOAuthSession($oauth_response['oauth_token'], $oauth_response['oauth_token_secret'], $oauth_response['expires']);

        //drop the qs
        $uri_parts = explode('?', $_SERVER['REQUEST_URI']);

        //Just for demo purposes
        header(sprintf('Location: http%s://%s%s', (isset($_SERVER['HTTPS']) ? 's' : ''), $_SERVER['HTTP_HOST'], $uri_parts[0]));
        exit;

    }
}

//Otherwise, you're in.
print_r($xero->load('Accounting\\Organisation')->execute());

//The following two functions are just for a demo - you should use a more robust mechanism of storing tokens than this!
function setOAuthSession($token, $secret, $expires = null){
    $_SESSION['oauth'] = array(
        'token' => $token,
        'token_secret' => $secret,
        'expires' => $expires
    );
}

function getOAuthSession(){
    //If it doesn't exist or is expired, return null
    if(!isset($_SESSION['oauth']) || ($_SESSION['oauth']['expires'] !== null && $_SESSION['oauth']['expires'] <= time()))
        return null;

    return $_SESSION['oauth'];
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _05.Dict_Ref_Advanced
{
    class DictRefAdvanced
    {
        static void Main(string[] args)
        {
            Dictionary<string, List<int>> nameData = new Dictionary<string, List<int>>();
            while (true)
            {
                string[] input = Console.ReadLine().Split(new string[] {" -> "}, StringSplitOptions.None);
                if (input[0] == "end")
                {
                    break;
                }
                string name = input[0];
                string[] nameOrNumbers = input[1].Split(new string[] {", "}, StringSplitOptions.RemoveEmptyEntries);
                bool isNum = IsNumber(nameOrNumbers[0]);
                if (isNum)
                {
                    int[] numbers = nameOrNumbers.Select(int.Parse).ToArray();
                    if (!nameData.ContainsKey(name))
                    {
                        nameData.Add(name, new List<int>());
                    }
                    nameData[name].AddRange(numbers);
                }
                else
                {
                    string otherName = nameOrNumbers[0];
                    if (nameData.ContainsKey(otherName))
                    {
                        if (!nameData.ContainsKey(name))
                        {
                            nameData.Add(name, new List<int>());
                        }
                        nameData[name].Clear();
                        nameData[name].AddRange(nameData[otherName]);
                    }
                }
            }
            foreach (var data in nameData)
            {
                Console.WriteLine($"{data.Key} === {string.Join(", ",data.Value)}");
            }
        }

        static bool IsNumber(string s)
        {
            foreach (char check in s)
            {
                if (char.IsLetter(check))
                {
                    return false;
                }
            }
            return true;
        }
    }
}


text:
/*
 * The Plaid API
 *
 * The Plaid REST API. Please see https://plaid.com/docs/api for more details.
 *
 * API version: 2020-09-14_1.205.3
 */

// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.

package plaid

import (
	"encoding/json"
	"fmt"
)

// BankTransferDirection Indicates the direction of the transfer: `outbound` for API-initiated transfers, or `inbound` for payments received by the FBO account.
type BankTransferDirection string

var _ = fmt.Printf

// List of BankTransferDirection
const (
	BANKTRANSFERDIRECTION_OUTBOUND BankTransferDirection = "outbound"
	BANKTRANSFERDIRECTION_INBOUND BankTransferDirection = "inbound"
	BANKTRANSFERDIRECTION_NULL BankTransferDirection = "null"
)

var allowedBankTransferDirectionEnumValues = []BankTransferDirection{
	"outbound",
	"inbound",
	"null",
}

func (v *BankTransferDirection) UnmarshalJSON(src []byte) error {
	var value string
	err := json.Unmarshal(src, &value)
	if err != nil {
		return err
	}

	enumTypeValue := BankTransferDirection(value)

	*v = enumTypeValue
	return nil
}

// NewBankTransferDirectionFromValue returns a pointer to a valid BankTransferDirection
// for the value passed as argument, or an error if the value passed is not allowed by the enum
func NewBankTransferDirectionFromValue(v string) (*BankTransferDirection, error) {
	ev := BankTransferDirection(v)

	return &ev, nil
}

// IsValid return true if the value is valid for the enum, false otherwise
func (v BankTransferDirection) IsValid() bool {
	for _, existing := range allowedBankTransferDirectionEnumValues {
		if existing == v {
			return true
		}
	}
	return false
}

// Ptr returns reference to BankTransferDirection value
func (v BankTransferDirection) Ptr() *BankTransferDirection {
	return &v
}

type NullableBankTransferDirection struct {
	value *BankTransferDirection
	isSet bool
}

func (v NullableBankTransferDirection) Get() *BankTransferDirection {
	return v.value
}

func (v *NullableBankTransferDirection) Set(val *BankTransferDirection) {
	v.value = val
	v.isSet = true
}

func (v NullableBankTransferDirection) IsSet() bool {
	return v.isSet
}

func (v *NullableBankTransferDirection) Unset() {
	v.value = nil
	v.isSet = false
}

func NewNullableBankTransferDirection(val *BankTransferDirection) *NullableBankTransferDirection {
	return &NullableBankTransferDirection{value: val, isSet: true}
}

func (v NullableBankTransferDirection) MarshalJSON() ([]byte, error) {
	return json.Marshal(v.value)
}

func (v *NullableBankTransferDirection) UnmarshalJSON(src []byte) error {
	v.isSet = true
	return json.Unmarshal(src, &v.value)
}


text:
run:
	python run.py
req:
	pip install -r requirements.txt
deploy:
	service capuhome-api reload
clean:
	find . -name '*.pyc' -print0 | xargs -0 rm -f
	find . -name '*.swp' -print0 | xargs -0 rm -f
	-@sudo rm -rf whoosh_index
permission:
	chown -R www-data.www-data .
	chown www-data.www-data /tmp/jieba.cache
pyflakes:
	pyflakes app config.sample.py run.py
pep8:
	pep8 app config.sample.py run.py
pylint:
	pylint app config.sample.py run.py
lint: pyflakes pep8 pylint


text:
FactoryGirl.define do
  factory :campaigntype do
    name "Paper Campaign"
  end

  factory :invalidcampaigntype, :parent => :campaigntype do |f|
    name nil
  end
end


text:
<?php
namespace wcf\system\event\listener;

class DailyCleanUpCronjobExecuteTwofaCleanUpListener implements \wcf\system\event\IEventListener {
	/**
	 * @see	\wcf\system\event\IEventListener::execute()
	 */
	public function execute($eventObj, $className, $eventName) {
		// clean up blacklisted codes
		$sql = "DELETE FROM	wcf".WCF_N."_user_twofa_blacklist
			WHERE		time < ?";
		$statement = \wcf\system\WCF::getDB()->prepareStatement($sql);
		$statement->execute(array(
			(TIME_NOW - 86400 * 30)
		));
	}
}


text:
#ifndef TLM_RECORDER_REGISTRY_H_
#define TLM_RECORDER_REGISTRY_H_

#include <scv.h>
#include <tlm>

namespace scv4tlm {
/*! \brief The TLM transaction extensions recorder interface
 *
 * This interface is used by the TLM transaction recorder. It can be used to
 * register custom recorder functionality
 * to also record the payload extensions
 */
template <typename TYPES = tlm::tlm_base_protocol_types> class tlm_extensions_recording_if {
public:
    /*! \brief recording attributes in extensions at the beginning, it is intended
     * to be overload as it does nothing
     *
     */
    virtual void recordBeginTx(scv_tr_handle& handle, typename TYPES::tlm_payload_type& trans) = 0;

    /*! \brief recording attributes in extensions at the end, it is intended to be
     * overload as it does nothing
     *
     */
    virtual void recordEndTx(scv_tr_handle& handle, typename TYPES::tlm_payload_type& trans) = 0;

    virtual ~tlm_extensions_recording_if() = default;
};

/*! \brief The TLM transaction extensions recorder registry
 *
 * This registry is used by the TLM transaction recorder. It can be used to
 * register custom recorder functionality
 * to also record the payload extensions
 */
template <typename TYPES = tlm::tlm_base_protocol_types> class tlm_extension_recording_registry {
public:
    static tlm_extension_recording_registry& inst() {
        static tlm_extension_recording_registry reg;
        return reg;
    }

    void register_ext_rec(size_t id, tlm_extensions_recording_if<TYPES>* ext) {
        if(id == 0)
            return;
        if(id >= ext_rec.size())
            ext_rec.resize(id + 1);
        if(ext_rec[id])
            delete ext_rec[id];
        ext_rec[id] = ext;
    }

    const std::vector<tlm_extensions_recording_if<TYPES>*>& get() { return ext_rec; }

    inline void recordBeginTx(size_t id, scv_tr_handle& handle, typename TYPES::tlm_payload_type& trans) {
        if(ext_rec.size() > id && ext_rec[id])
            ext_rec[id]->recordBeginTx(handle, trans);
    }

    /*! \brief recording attributes in extensions at the end, it is intended to be
     * overload as it does nothing
     *
     */
    inline void recordEndTx(size_t id, scv_tr_handle& handle, typename TYPES::tlm_payload_type& trans) {
        if(ext_rec.size() > id && ext_rec[id])
            ext_rec[id]->recordEndTx(handle, trans);
    }

private:
    tlm_extension_recording_registry() = default;
    ~tlm_extension_recording_registry() {
        for(auto& ext : ext_rec)
            delete(ext);
    }
    std::vector<tlm_extensions_recording_if<TYPES>*> ext_rec;
};

} // namespace scv4tlm

#endif /* TLM_RECORDER_REGISTRY_H_ */


text:
package controllers

import play.api.mvc._
import play.api.data._
import play.api.libs.json._
import play.api.libs.json.Json._
import dispatch._
import utils.dispatch.PlayJsonDispatchHttp._
import utils.neo4j.Neo4JRestService

object Neo4J extends Controller {

  object neo extends Neo4JRestService

  def root = Action {
    val node = Http(neo.neoRestNodeById(neo.root.id) <:< Map("Accept" -> "application/json") >! {
      jsValue =>
        (jsValue \ "self").as[String]
    })
    Ok(node)
  }

  def node(id: Int) = Action {
    val node = Http(neo.neoRestNodeById(id) <:< Map("Accept" -> "application/json") >! {
      jsValue => (jsValue \ "self").as[String]
    })
    Ok(node)
  }

  def createNode = Action {
    val node = Http((neo.neoRestNode POST) <:< Map("Accept" -> "application/json") >! {
      jsValue =>
        (jsValue \ "self").as[String]
    })
    Ok(node)
  }

  def createNodeWithProperties = Action {
    val props = toJson(Map("prop1" -> "value1", "prop2" -> "value2"))

    val (node, data: JsObject) = Http(
      (neo.neoRestNode <<(stringify(props), "application/json"))
        <:< Map("Accept" -> "application/json")
        >! {
        jsValue =>
          ((jsValue \ "self").as[String], (jsValue \ "data").as[JsObject])
      })
    Ok("" + node + " -- " + data.toString)
  }

  def relationship(id: Int) = Action {
    val (rel, start, end) = Http(neo.neoRestRelById(id) <:< Map("Accept" -> "application/json") >! {
      jsValue =>
        ((jsValue \ "self").as[String],
          (jsValue \ "start").as[String],
          (jsValue \ "end").as[String])
    })
    Ok("" + start + " - [" + rel + "] - " + end)
  }

  def createRelationship = Action {
    val create_relationship = Http(neo.neoRestNodeById(neo.root.id) <:< Map("Accept" -> "application/json") >! {
      jsValue =>
        (jsValue \ "create_relationship").as[String]
    })

    val node = Http((neo.neoRestNode POST) <:< Map("Accept" -> "application/json") >! {
      jsValue =>
        (jsValue \ "self").as[String]
    })

    val props = JsObject(Seq(
      "to" -> JsString(node),
      "type" -> JsString("TEST")
    ))

    val (rel, data: JsObject) = Http(
      (url(create_relationship) <<(stringify(props), "application/json"))
        <:< Map("Accept" -> "application/json")
        >! {
        jsValue =>
          ((jsValue \ "self").as[String], (jsValue \ "data").as[JsObject])
      })

    Ok(rel)
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="co.herovitamin.scrollingtechniques" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Technique1Activity"
            android:label="@string/title_activity_technique1" >
        </activity>
        <activity
            android:name=".InitialActivity"
            android:label="@string/title_activity_initial" >
        </activity>
        <activity
            android:name=".Technique2Activity"
            android:label="@string/title_activity_technique2" >
        </activity>
        <activity
            android:name=".Technique3Activity"
            android:label="@string/title_activity_technique3" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
        <activity
            android:name=".Technique4Activity"
            android:label="@string/title_activity_technique4" >
        </activity>
        <activity
            android:name=".Technique5Activity"
            android:label="@string/title_activity_technique5" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
    </application>

</manifest>


text:
package com.grndctl.model.aggregates;

import javax.xml.bind.annotation.*;
import java.util.List;

/**
 *
 * @author Michael Di Salvo
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = {"charts"})
@XmlRootElement
public class Charts {

    @XmlElement
    private List<Chart> charts;

    public Charts(List<Chart> charts) {
        this.charts = charts;
    }

    public Charts() { }

    public List<Chart> getCharts() {
        return charts;
    }

    public void setCharts(List<Chart> charts) {
        this.charts = charts;
    }

    @Override
    public String toString() {
        return "Charts{" +
                "charts=" + charts +
                '}';
    }
}


text:
package org.ethereum.core;

import org.ethereum.config.Constants;
import org.ethereum.config.SystemProperties;
import org.ethereum.crypto.HashUtil;
import org.ethereum.db.BlockStore;
import org.ethereum.db.RepositoryImpl;
import org.ethereum.facade.Blockchain;
import org.ethereum.facade.Repository;
import org.ethereum.listener.EthereumListener;
import org.ethereum.manager.AdminInfo;
import org.ethereum.net.BlockQueue;
import org.ethereum.net.server.ChannelManager;
import org.ethereum.trie.Trie;
import org.ethereum.trie.TrieImpl;
import org.ethereum.util.*;
import org.ethereum.vm.ProgramInvokeFactory;
import org.ethereum.vm.ProgramInvokeFactoryImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import org.apache.commons.io.FileUtils;

import javax.annotation.Resource;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

import javax.inject.Inject;
import javax.inject.Singleton;

import static org.ethereum.config.Constants.*;
import static org.ethereum.config.SystemProperties.CONFIG;
import static org.ethereum.core.Denomination.SZABO;
import static org.ethereum.core.ImportResult.*;

/**
 * The Ethereum blockchain is in many ways similar to the Bitcoin blockchain,
 * although it does have some differences.
 *
 * The main difference between Ethereum and Bitcoin with regard to the blockchain architecture
 * is that, unlike Bitcoin, Ethereum blocks contain a copy of both the transaction list
 * and the most recent state. Aside from that, two other values, the block number and
 * the difficulty, are also stored in the block.
 *
 * The block validation algorithm in Ethereum is as follows:
 *

 *
Check if the previous block referenced exists and is valid.

 *
Check that the timestamp of the block is greater than that of the referenced previous block and less than 15 minutes into the future

 *
Check that the block number, difficulty, transaction root, uncle root and gas limit (various low-level Ethereum-specific concepts) are valid.

 *
Check that the proof of work on the block is valid.

 *
Let S[0] be the STATE_ROOT of the previous block.

 *
Let TX be the block's transaction list, with n transactions.
 * For all in in 0...n-1, set S[i+1] = APPLY(S[i],TX[i]).
 * If any applications returns an error, or if the total gas consumed in the block
 * up until this point exceeds the GASLIMIT, return an error.

 *
Let S_FINAL be S[n], but adding the block reward paid to the miner.

 *
Check if S_FINAL is the same as the STATE_ROOT. If it is, the block is valid; otherwise, it is not valid.

 *

 * See Ethereum Whitepaper
 *
 * @author Roman Mandeleil
 * @author Nick Savers
 * @since 20.05.2014
 */
@Singleton
public class BlockchainImpl implements Blockchain {

    private static final Logger logger = LoggerFactory.getLogger("blockchain");
    private static final Logger stateLogger = LoggerFactory.getLogger("state");

    // to avoid using minGasPrice=0 from Genesis for the wallet
    private static final long INITIAL_MIN_GAS_PRICE = 10 * SZABO.longValue();

    @Resource
    private Set<Transaction> pendingTransactions = new HashSet<>();

    private Repository repository;
    private Repository track;

    private BlockStore blockStore;

    private Block bestBlock;
    private BigInteger totalDifficulty = BigInteger.ZERO;

    Wallet wallet;

    private EthereumListener listener;

    private BlockQueue blockQueue;

    private ChannelManager channelManager;

    private boolean syncDoneCalled = false;

    ProgramInvokeFactory programInvokeFactory;

    private AdminInfo adminInfo;

    private List<Chain> altChains = new ArrayList<>();
    private List<Block> garbage = new ArrayList<>();

    long exitOn = Long.MAX_VALUE;

    public BlockchainImpl() {
    }

    //todo: autowire over constructor
    @Inject
    public BlockchainImpl(BlockStore blockStore, Repository repository,
                          Wallet wallet, AdminInfo adminInfo,
                          EthereumListener listener, ChannelManager channelManager) {
        this.blockStore = blockStore;
        this.repository = repository;
        this.wallet = wallet;
        this.adminInfo = adminInfo;
        this.listener = listener;
        this.channelManager = channelManager;
        this.blockQueue = new BlockQueue(this);
        this.programInvokeFactory = new ProgramInvokeFactoryImpl();
        this.programInvokeFactory.setBlockchain(this);
    }

    @Override
    public byte[] getBestBlockHash() {
        return getBestBlock().getHash();
    }

    @Override
    public long getSize() {
        return bestBlock.getNumber() + 1;
    }

    @Override
    public Block getBlockByNumber(long blockNr) {
        return blockStore.getBlockByNumber(blockNr);
    }

    @Override
    public TransactionReceipt getTransactionReceiptByHash(byte[] hash) {
        throw new UnsupportedOperationException("TODO: will be implemented soon "); // FIXME: go and fix me
    }

    @Override
    public Block getBlockByHash(byte[] hash) {
        return blockStore.getBlockByHash(hash);
    }

    @Override
    public List<byte[]> getListOfHashesStartFrom(byte[] hash, int qty) {
        return blockStore.getListHashesEndWith(hash, qty);
    }

    private byte[] calcTxTrie(List<Transaction> transactions){

        Trie txsState = new TrieImpl(null);

        if (transactions == null || transactions.isEmpty())
            return HashUtil.EMPTY_TRIE_HASH;

        for (int i = 0; i < transactions.size(); i++) {
            txsState.update(RLP.encodeInt(i), transactions.get(i).getEncoded());
        }
        return txsState.getRootHash();
    }

    public ImportResult tryToConnect(Block block) {

        if (logger.isInfoEnabled())
            logger.info("Try connect block hash: {}, number: {}",
                    Hex.toHexString(block.getHash()).substring(0, 6),
                    block.getNumber());

        if (blockStore.getBestBlock().getNumber() >= block.getNumber() &&
                blockStore.getBlockByHash(block.getHash()) != null) {

            if (logger.isDebugEnabled())
                logger.debug("Block already exist hash: {}, number: {}",
                        Hex.toHexString(block.getHash()).substring(0, 6),
                        block.getNumber());

            // retry of well known block
            return EXIST;
        }

        // The simple case got the block
        // to connect to the main chain
        if (bestBlock.isParentOf(block)) {
            add(block);
            recordBlock(block);
            return SUCCESS;
        } else {
            if (1 == 1) // FIXME: WORKARROUND
                return NO_PARENT;
        }

        return SUCCESS;
    }

    @Override
    public void add(Block block) {

        if (exitOn < block.getNumber()){
            System.out.print("Exiting after block.number: " + getBestBlock().getNumber());
            System.exit(-1);
        }

        if(!isValid(block)){
            logger.warn("Invalid block with number: {}", block.getNumber());
            return;
        }

        track = repository.startTracking();
        if (block == null)
            return;

        // keep chain continuity
        if (!Arrays.equals(getBestBlock().getHash(),
                block.getParentHash())) return;

        if (block.getNumber() >= CONFIG.traceStartBlock() && CONFIG.traceStartBlock() != -1) {
            AdvancedDeviceUtils.adjustDetailedTracing(block.getNumber());
        }

        List<TransactionReceipt> receipts = processBlock(block);

        // Sanity checks
        String receiptHash = Hex.toHexString( block.getReceiptsRoot() );
        String receiptListHash = Hex.toHexString(calcReceiptsTrie(receipts));

        if( !receiptHash.equals(receiptListHash) ) {
          logger.error("Block's given Receipt Hash doesn't match: {} != {}", receiptHash, receiptListHash);
          //return false;
        }

        String logBloomHash = Hex.toHexString( block.getLogBloom() );
        String logBloomListHash = Hex.toHexString(calcLogBloom(receipts));

        if( !logBloomHash.equals(logBloomListHash) ) {
          logger.error("Block's given logBloom Hash doesn't match: {} != {}", logBloomHash, logBloomListHash);
          //track.rollback();
          //return;
        }

        //DEBUG
        //System.out.println(" Receipts root is: " + receiptHash + " logbloomhash is " + logBloomHash);
        //System.out.println(" Receipts listroot is: " + receiptListHash + " logbloomlisthash is " + logBloomListHash);

        track.commit();
        storeBlock(block, receipts);

//        if (block.getNumber() == 708_461){
//            System.exit(-1);
//        }

        if (needFlush(block)) {
            repository.flush();
            blockStore.flush();
            System.gc();
        }

        // Remove all wallet transactions as they already approved by the net
        wallet.removeTransactions(block.getTransactionsList());

        // Clear pending transaction from the mem
        clearPendingTransactions(block.getTransactionsList());

        listener.trace(String.format("Block chain size: [ %d ]", this.getSize()));
        listener.onBlock(block, receipts);

        if (blockQueue != null &&
            blockQueue.size() == 0 &&
            !syncDoneCalled &&
                channelManager.isAllSync()) {

            logger.info("Sync done");
            syncDoneCalled = true;
            listener.onSyncDone();
        }
    }

    private boolean needFlush(Block block) {

        boolean possibleFlush = CONFIG.flushBlocksIgnoreConsensus() || adminInfo.isConsensus();
        if (!possibleFlush)return false;

        if (CONFIG.flushBlocksRepoSize() > 0 && repository.getClass().isAssignableFrom(RepositoryImpl.class)) {
            return ((RepositoryImpl) repository).getAllocatedMemorySize() > CONFIG.flushBlocksRepoSize();
        } else {
            boolean isBatchReached = block.getNumber() % CONFIG.flushBlocksBatchSize() == 0;

            return isBatchReached;
        }
    }

    private byte[] calcReceiptsTrie(List<TransactionReceipt> receipts){
        //TODO Fix Trie hash for receipts - doesnt match cpp
        Trie receiptsTrie = new TrieImpl(null);

        if (receipts == null || receipts.isEmpty())
            return HashUtil.EMPTY_TRIE_HASH;

        for (int i = 0; i < receipts.size(); i++) {
            receiptsTrie.update(RLP.encodeInt(i), receipts.get(i).getEncoded());
        }
        return receiptsTrie.getRootHash();
    }

    private byte[] calcLogBloom( List<TransactionReceipt> receipts ) {

        Bloom retBloomFilter = new Bloom();

        if (receipts == null || receipts.isEmpty())
            return retBloomFilter.getData();

        for (int i = 0; i < receipts.size(); i++) {
            retBloomFilter.or(receipts.get(i).getBloomFilter());
        }

        return retBloomFilter.getData();
    }

    public Block getParent(BlockHeader header) {

        return blockStore.getBlockByHash(header.getParentHash());
    }

    public boolean isValid(BlockHeader header) {

        Block parentBlock = getParent(header);

        BigInteger parentDifficulty = parentBlock.getDifficultyBI();
        long parentTimestamp = parentBlock.getTimestamp();

        BigInteger minDifficulty = header.getTimestamp() >= parentTimestamp + DURATION_LIMIT ?
                parentBlock.getDifficultyBI().subtract(parentDifficulty.divide(BigInteger.valueOf(Constants.DIFFICULTY_BOUND_DIVISOR))) :
                parentBlock.getDifficultyBI().add(parentDifficulty.divide(BigInteger.valueOf(Constants.DIFFICULTY_BOUND_DIVISOR)));

        BigInteger difficulty = new BigInteger(1, header.getDifficulty());

        if (header.getNumber() != (parentBlock.getNumber() + 1) ) {
            logger.error("Block invalid: block number is not parentBlock number + 1, ");
            return false;
        }

        if (header.getGasLimit() < header.getGasUsed()) {
            logger.error("Block invalid: header.getGasLimit() < header.getGasUsed()");
            return false;
        }

        if (difficulty.compareTo(minDifficulty) == -1) {
            logger.error("Block invalid: difficulty < minDifficulty");
            return false;
        }

        if (header.getGasLimit() < MIN_GAS_LIMIT) {
            logger.error("Block invalid: header.getGasLimit() < MIN_GAS_LIMIT");
            return false;
        }

        if (header.getExtraData() != null &&  header.getExtraData().length > MAXIMUM_EXTRA_DATA_SIZE) {
            logger.error("Block invalid: header.getExtraData().length > MAXIMUM_EXTRA_DATA_SIZE");
            return false;
        }

        if (header.getGasLimit() < Constants.MIN_GAS_LIMIT ||
                header.getGasLimit() < parentBlock.getGasLimit() * (GAS_LIMIT_BOUND_DIVISOR - 1) / GAS_LIMIT_BOUND_DIVISOR ||
                header.getGasLimit() > parentBlock.getGasLimit() * (GAS_LIMIT_BOUND_DIVISOR + 1) / GAS_LIMIT_BOUND_DIVISOR){

            logger.error("Block invalid: gas limit exceeds parentBlock.getGasLimit() (+-) GAS_LIMIT_BOUND_DIVISOR");
            return false;
        }

        return true;
    }

    /**
     * This mechanism enforces a homeostasis in terms of the time between blocks;
     * a smaller period between the last two blocks results in an increase in the
     * difficulty level and thus additional computation required, lengthening the
     * likely next period. Conversely, if the period is too large, the difficulty,
     * and expected time to the next block, is reduced.
     */
    private boolean isValid(Block block) {

        boolean isValid = true;

        if (!block.isGenesis()) {
            isValid = isValid(block.getHeader());

            // Sanity checks
            String trieHash = Hex.toHexString( block.getTxTrieRoot() );
            String trieListHash = Hex.toHexString(calcTxTrie(block.getTransactionsList()));

/* FIXME: temporary comment out tx.trie validation
            if( !trieHash.equals(trieListHash) ) {
              logger.error("Block's given Trie Hash doesn't match: {} != {}", trieHash, trieListHash);
              return false;
            }
*/

            String unclesHash = Hex.toHexString(block.getHeader().getUnclesHash());
            String unclesListHash = Hex.toHexString( HashUtil.sha3(block.getHeader().getUnclesEncoded( block.getUncleList() ) ) );

            if( !unclesHash.equals(unclesListHash) ) {
              logger.error("Block's given Uncle Hash doesn't match: {} != {}", unclesHash, unclesListHash);
              return false;
            }

            if (block.getUncleList().size() > UNCLE_LIST_LIMIT) {
                logger.error("Uncle list to big: block.getUncleList().size() > UNCLE_LIST_LIMIT");
                return false;
            };

            for (BlockHeader uncle : block.getUncleList()) {

                // - They are valid headers (not necessarily valid blocks)
                if (!isValid(uncle)) return false;

                //if uncle's parent's number is not less than currentBlock - UNCLE_GEN_LIMIT, mark invalid
                isValid = !(getParent(uncle).getNumber() < (block.getNumber() - UNCLE_GENERATION_LIMIT) );
                if (!isValid){
                    logger.error("Uncle too old: generationGap must be under UNCLE_GENERATION_LIMIT");
                    return false;
                }

            }
        }

        return isValid;
    }

    private List<TransactionReceipt> processBlock(Block block) {

        List<TransactionReceipt> receipts = new ArrayList<>();
        if (!block.isGenesis()) {
            if (!CONFIG.blockChainOnly()) {
                wallet.addTransactions(block.getTransactionsList());
                receipts = applyBlock(block);
                wallet.processBlock(block);
            }
        }

        return receipts;
    }

    private List<TransactionReceipt> applyBlock(Block block) {

        logger.info("applyBlock: block: [{}] tx.list: [{}]", block.getNumber(), block.getTransactionsList().size());
        long saveTime = System.nanoTime();
        int i = 1;
        long totalGasUsed = 0;
        List<TransactionReceipt> receipts = new ArrayList<>();

        for (Transaction tx : block.getTransactionsList()) {
            stateLogger.info("apply block: [{}] tx: [{}] ", block.getNumber(), i);

            TransactionExecutor executor = new TransactionExecutor(tx, block.getCoinbase(),
                    track, blockStore,
                    programInvokeFactory, block, listener, totalGasUsed);

            executor.init();
            executor.execute();
            executor.go();
            executor.finalization();

            totalGasUsed += executor.getGasUsed();

            track.commit();
            TransactionReceipt receipt = new TransactionReceipt();
            receipt.setCumulativeGas(totalGasUsed);
            receipt.setPostTxState(repository.getRoot());
            receipt.setTransaction(tx);
            receipt.setLogInfoList(executor.getVMLogs());

            stateLogger.info("block: [{}] executed tx: [{}] \n  state: [{}]", block.getNumber(), i,
                    Hex.toHexString(repository.getRoot()));

            stateLogger.info("[{}] ", receipt.toString());

            if (stateLogger.isInfoEnabled())
                stateLogger.info("tx[{}].receipt: [{}] ", i, Hex.toHexString(receipt.getEncoded()));

            if (block.getNumber() >= CONFIG.traceStartBlock())
                repository.dumpState(block, totalGasUsed, i++, tx.getHash());

            receipts.add(receipt);
        }

        addReward(block);
        updateTotalDifficulty(block);

        track.commit();

        stateLogger.info("applied reward for block: [{}]  \n  state: [{}]",
                block.getNumber(),
                Hex.toHexString(repository.getRoot()));

        if (block.getNumber() >= CONFIG.traceStartBlock())
            repository.dumpState(block, totalGasUsed, 0, null);

        long totalTime = System.nanoTime() - saveTime;
        adminInfo.addBlockExecTime(totalTime);
        logger.info("block: num: [{}] hash: [{}], executed after: [{}]nano", block.getNumber(), block.getShortHash(), totalTime);

        return receipts;
    }

    /**
     * Add reward to block- and every uncle coinbase
     * assuming the entire block is valid.
     *
     * @param block object containing the header and uncles
     */
    private void addReward(Block block) {

        // Add standard block reward
        BigInteger totalBlockReward = Block.BLOCK_REWARD;

        // Add extra rewards based on number of uncles
        if (block.getUncleList().size() > 0) {
            for (BlockHeader uncle : block.getUncleList()) {
                track.addBalance(uncle.getCoinbase(),
                  new BigDecimal(block.BLOCK_REWARD).multiply(BigDecimal.valueOf(8 + uncle.getNumber() - block.getNumber()).divide(new BigDecimal(8))).toBigInteger());

                totalBlockReward = totalBlockReward.add(Block.INCLUSION_REWARD);
            }
        }
        track.addBalance(block.getCoinbase(), totalBlockReward);

    }

    @Override
    public void storeBlock(Block block, List<TransactionReceipt> receipts) {

        /* Debug check to see if the state is still as expected */
        String blockStateRootHash = Hex.toHexString(block.getStateRoot());
        String worldStateRootHash = Hex.toHexString(repository.getRoot());

        if(!SystemProperties.CONFIG.blockChainOnly())
            if (!blockStateRootHash.equals(worldStateRootHash)) {

                stateLogger.error("BLOCK: STATE CONFLICT! block: {} worldstate {} mismatch", block.getNumber(), worldStateRootHash);
                adminInfo.lostConsensus();

                System.out.println("CONFLICT: BLOCK #" + block.getNumber() );
//                System.exit(1);
                // in case of rollback hard move the root
    //                Block parentBlock = blockStore.getBlockByHash(block.getParentHash());
    //                repository.syncToRoot(parentBlock.getStateRoot());
                // todo: after the rollback happens other block should be requested
            }

        blockStore.saveBlock(block, receipts);
        setBestBlock(block);

        if (logger.isDebugEnabled())
            logger.debug("block added to the blockChain: index: [{}]", block.getNumber());
        if (block.getNumber() % 100 == 0)
            logger.info("*** Last block added [ #{} ]", block.getNumber());
    }

    public boolean hasParentOnTheChain(Block block) {
        return getParent(block.getHeader()) != null;
    }

    @Override
    public List<Chain> getAltChains() {
        return altChains;
    }

    @Override
    public List<Block> getGarbage() {
        return garbage;
    }

    @Override
    public BlockQueue getQueue() {
        return blockQueue;
    }

    @Override
    public void setBestBlock(Block block) {
        bestBlock = block;
    }

    @Override
    public Block getBestBlock() {
        return bestBlock;
    }

    @Override
    public void close() {
        blockQueue.close();
    }

    @Override
    public BigInteger getTotalDifficulty() {
        return totalDifficulty;
    }

    @Override
    public void updateTotalDifficulty(Block block) {
        totalDifficulty = totalDifficulty.add(block.getCumulativeDifficulty());
    }

    @Override
    public void setTotalDifficulty(BigInteger totalDifficulty) {
        this.totalDifficulty = totalDifficulty;
    }

    private void recordBlock(Block block) {

        if (!CONFIG.recordBlocks()) return;

        if (block.getNumber() == 1) {
            try {
                FileUtils.forceDelete(new File(CONFIG.dumpDir()));
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }

        String dir = CONFIG.dumpDir() + "/";

        File dumpFile = new File(System.getProperty("user.dir") + "/" + dir + "_blocks_rec.txt");
        FileWriter fw = null;
        BufferedWriter bw = null;

        try {

            dumpFile.getParentFile().mkdirs();
            if (!dumpFile.exists()) dumpFile.createNewFile();

            fw = new FileWriter(dumpFile.getAbsoluteFile(), true);
            bw = new BufferedWriter(fw);

            if (bestBlock.isGenesis()) {
                bw.write(Hex.toHexString(bestBlock.getEncoded()));
                bw.write("\n");
            }

            bw.write(Hex.toHexString(block.getEncoded()));
            bw.write("\n");

        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                if (bw != null) bw.close();
                if (fw != null) fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public void addPendingTransactions(Set<Transaction> transactions) {
        logger.info("Pending transaction list added: size: [{}]", transactions.size());

        if (listener != null)
            listener.onPendingTransactionsReceived(transactions);
        pendingTransactions.addAll(transactions);
    }

    public void clearPendingTransactions(List<Transaction> receivedTransactions) {

        for (Transaction tx : receivedTransactions) {
            logger.info("Clear transaction, hash: [{}]", Hex.toHexString(tx.getHash()));
            pendingTransactions.remove(tx);
        }
    }

    public Set<Transaction> getPendingTransactions() {
        return pendingTransactions;
    }

    public void setRepository(Repository repository) {
        this.repository = repository;
    }

    public void setProgramInvokeFactory(ProgramInvokeFactory factory) {
        this.programInvokeFactory = factory;
    }

    public void startTracking() {
        track = repository.startTracking();
    }

    public void commitTracking() {
        track.commit();
    }

    public void setExitOn(long exitOn) {
        this.exitOn = exitOn;
    }
}


text:
package aima.gui.fx.applications.search;

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

import aima.core.search.csp.*;
import aima.core.search.csp.examples.MapCSP;
import aima.core.search.csp.inference.AC3Strategy;
import aima.core.search.csp.inference.ForwardCheckingStrategy;
import aima.gui.fx.framework.IntegrableApplication;
import aima.gui.fx.framework.Parameter;
import aima.gui.fx.framework.SimulationPaneBuilder;
import aima.gui.fx.framework.SimulationPaneCtrl;
import aima.gui.fx.views.CspViewCtrl;
import javafx.application.Platform;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;

/**
 * Application which demonstrates basic constraint algorithms based on map
 * coloring problems. It shows the constraint graph, lets the user select a
 * solution strategy, and allows then to follow the progress step by step.
 *
 * @author Ruediger Lunde
 */
public class CspMapColoringApp extends IntegrableApplication {

    public static void main(String[] args) {
        launch(args);
    }

    private final static String PARAM_MAP = "map";
    private final static String PARAM_STRATEGY = "strategy";

    private CspViewCtrl<Variable, String> stateViewCtrl;
    private SimulationPaneCtrl simPaneCtrl;

    private CSP<Variable, String> csp;
    private SolutionStrategy<Variable, String> strategy;
    private int stepCounter;

    public CspMapColoringApp() {
    }

    @Override
    public String getTitle() {
        return "CSP Map Coloring App";
    }

    /**
     * Defines state view, parameters, and call-back functions and calls the
     * simulation pane builder to create layout and controller objects.
     */
    @Override
    public Pane createRootPane() {
        BorderPane root = new BorderPane();

        StackPane stateView = new StackPane();
        stateViewCtrl = new CspViewCtrl<>(stateView);

        List<Parameter> params = createParameters();

        SimulationPaneBuilder builder = new SimulationPaneBuilder();
        builder.defineParameters(params);
        builder.defineStateView(stateView);
        builder.defineInitMethod(this::initialize);
        builder.defineSimMethod(this::simulate);
        simPaneCtrl = builder.getResultFor(root);

        return root;
    }

    protected List<Parameter> createParameters() {
        Parameter p1 = new Parameter(PARAM_MAP, "Map of Australia",
                "Map of Australia NSW=BLUE (for LCV)",
                "Map of Australia WA=RED (for LCV)");
        Parameter p2 = new Parameter(PARAM_STRATEGY, "Backtracking",
                "Backtracking + DEG",
                "Backtracking + Forward Checking",
                "Backtracking + Forward Checking + MRV",
                "Backtracking + Forward Checking + LCV",
                "Backtracking + AC3",
                "Backtracking + AC3 + MRV & DEG + LCV",
                "Min-Conflicts (50)");
        return Arrays.asList(p1, p2);
    }

    /**
     * Displays the selected function on the state view.
     */
    @Override
    public void initialize() {
        csp = null;
        switch (simPaneCtrl.getParamValueIndex(PARAM_MAP)) {
            case 0:
                csp = new MapCSP();
                break;
            case 1: // three moves
                csp = new MapCSP();
                csp.setDomain(MapCSP.NSW, new Domain<>(MapCSP.BLUE));
                break;
            case 2: // three moves
                csp = new MapCSP();
                csp.setDomain(MapCSP.WA, new Domain<>(MapCSP.RED));
                break;
        }

        stateViewCtrl.clearMappings();
        int c = 15;
        stateViewCtrl.setPositionMapping(MapCSP.WA, c*5, c*10);
        stateViewCtrl.setPositionMapping(MapCSP.NT, c*15, c*3);
        stateViewCtrl.setPositionMapping(MapCSP.SA, c*20, c*15);
        stateViewCtrl.setPositionMapping(MapCSP.Q, c*30, c*5);
        stateViewCtrl.setPositionMapping(MapCSP.NSW, c*35, c*15);
        stateViewCtrl.setPositionMapping(MapCSP.V, c*30, c*23);
        stateViewCtrl.setPositionMapping(MapCSP.T, c*33, c*30);

        stateViewCtrl.setColorMapping(MapCSP.RED, Color.RED);
        stateViewCtrl.setColorMapping(MapCSP.GREEN, Color.GREEN);
        stateViewCtrl.setColorMapping(MapCSP.BLUE, Color.BLUE);

        switch (simPaneCtrl.getParamValueIndex(PARAM_STRATEGY)) {
            case 0:
                strategy = new BacktrackingStrategy<>();
                break;
            case 1: // DEG
                strategy = new BacktrackingStrategy<Variable, String>().set(CspHeuristics.deg());
                break;
            case 2: // FC
                strategy = new BacktrackingStrategy<Variable, String>().set(new ForwardCheckingStrategy<>());
                break;
            case 3: // MRV + FC
                strategy = new BacktrackingStrategy<Variable, String>().set(CspHeuristics.mrvDeg())
                        .set(new ForwardCheckingStrategy<>());
                break;
            case 4: // LCV + FC
                strategy = new BacktrackingStrategy<Variable, String>().set(CspHeuristics.lcv())
                        .set(new ForwardCheckingStrategy<>());
                break;
            case 5: // AC3
                strategy = new BacktrackingStrategy<Variable, String>().set(new AC3Strategy<>());
                break;
            case 6: // MRV & DEG + LCV + AC3
                strategy = new BacktrackingStrategy<Variable, String>().setAll();
                break;
            case 7:
                strategy = new MinConflictsStrategy<>(50);
                break;
        }

        strategy.addCSPStateListener(new CspListener<Variable, String>() {

            @Override
            public void stateChanged(Assignment<Variable, String> assignment, CSP<Variable, String> csp) {
                stepCounter++;
                updateStateView(csp, assignment);
            }

            @Override
            public void stateChanged(CSP<Variable, String> csp) {
                stepCounter++;
                updateStateView(csp, null);
            }
        });

        stateViewCtrl.initialize(csp);
    }

    @Override
    public void cleanup() {
        simPaneCtrl.cancelSimulation();
    }

    /**
     * Starts the experiment.
     */
    public void simulate() {
        stepCounter = 0;
        strategy.solve(csp.copyDomains());
    }

    /**
     * Caution: While the background thread should be slowed down, updates of
     * the GUI have to be done in the GUI thread!
     */
    private void updateStateView(CSP<Variable, String> csp, Assignment<Variable, String> assignment) {
        Platform.runLater(() -> updateStateViewLater(csp, assignment));
        simPaneCtrl.waitAfterStep();
    }

    /**
     * Must be called by the GUI thread!
     */
    private void updateStateViewLater(CSP<Variable, String> csp, Assignment<Variable, String> assignment) {
        stateViewCtrl.update(csp, assignment);
        String txt1 = "Step " + stepCounter + ": ";
        String txt2 = "Domain reduced";
        if (assignment != null)
            txt2 = assignment.toString() + (assignment.isSolution(csp) ? " (Solution)" : "");
        simPaneCtrl.setStatus(txt1 + txt2);
    }
}


text:
require 'enumerator'
class Pattern
  def initialize(pattern)
    @pattern = pattern.map do |p|
      variable?(p) ? p : p.downcase
    end
  end

  # Does pattern match input? Any variable can match anything
  def match(input, variables = [], pattern = @pattern)
    pattern.enum_for(:zip, input).all? do |p, i|
      (p.is_a?(Array) && i.is_a?(Array) && match(i, variables, p)) ||
        (variable?(p) && (variables << [p, i])) ||
        p == i
    end && variables
  end

  def variable?(pattern)
    pattern.is_a?(String) && pattern[0] == ??
  end
end


text:
#include "math.h"
#include "iostream"
#include "string"
using namespace std;

//Global Variables
int i = 0, max = 0;
float fi = 0;
float TimeToCreateInSec1 = 0, TimeToCreateInSec2 = 0, ItemsProduced = 1, ItemsRequired = 1, CraftingSpeed1 = 1, CraftingSpeed2 = 1, IngredientsMachines = 0, RequiredMachines = 0, RatioMulti = 0, WholeCheck = 0, IngredientRatio = 0, ProductRatio = 0;
bool isEQ = false, isIngredientMore = false, isRequiredMore = false, isEqual = false;

void Number() {
	if (isIngredientMore == true) { cout << RatioMulti << " times more crafting machines creating the product."; }
	if (isRequiredMore == true) { cout << RatioMulti << " times more crafting machines creating the ingredient."; }
	if (isEqual == true) { cout << "equal amount of crafting machines creating the ingredient and the product."; }
}
//Not used to avoid confusion.
/*void Ratio() {
	if (isIngredientMore == true) { cout << "Ratio:   " << ProductRatio << ":" << IngredientRatio; }
	if (isRequiredMore == true) { cout << "Ratio:     " << IngredientRatio << ":" << ProductRatio; }
}*/

int main()
{
	cout << "Enter raw time to complete for the ingredient in seconds: "; cin >> TimeToCreateInSec1;
	cout << endl << "Enter number of produced ingredients in one recipe: "; cin >> ItemsProduced;
	cout << endl << "Enter crafting speed of the machine producing the ingredients: "; cin >> CraftingSpeed1;
	cout << endl << "Enter raw time to complete for the product in seconds: "; cin >> TimeToCreateInSec2;
	cout << endl << "Enter number of required ingredients in one recipe: "; cin >> ItemsRequired;
	cout << endl << "Enter crafting speed of the machine producing the Product: "; cin >> CraftingSpeed2;
	float IngredientTimePerRecipeInSec = (TimeToCreateInSec1 / CraftingSpeed1);
	float RequiredTimePerRecipeInSec = (TimeToCreateInSec2 / CraftingSpeed2);
	float IngredientTimesPerMinute = (60 / IngredientTimePerRecipeInSec);
	float RequiredTimesPerMinute = (60 / RequiredTimePerRecipeInSec);
	float IngredientPerMinute = (IngredientTimesPerMinute * ItemsProduced);
	float RequiredPerMinute = (RequiredTimesPerMinute * ItemsRequired);
	float PerSI = (IngredientPerMinute / 60);
	float PerSR = (RequiredPerMinute / 60);
	cout << endl << endl << "Ingredients produced per minute by one crafting machine: " << IngredientPerMinute;
	cout << endl << "Required ingredients per minute by one crafting machine: " << RequiredPerMinute;
	cout << endl << endl << "Ingredients produced per second by one crafting machine: " << PerSI;
	cout << endl << "Required ingredients per second by one crafting machine: " << PerSR;
	if (IngredientPerMinute > RequiredPerMinute && IngredientPerMinute != RequiredPerMinute) {
		RatioMulti = (IngredientPerMinute / RequiredPerMinute); isIngredientMore = true;
	}
	if (IngredientPerMinute < RequiredPerMinute && IngredientPerMinute != RequiredPerMinute) {
		RatioMulti = (RequiredPerMinute / IngredientPerMinute); isRequiredMore = true;
	}
	if (IngredientPerMinute == RequiredPerMinute) {
		RatioMulti = (RequiredPerMinute / RequiredPerMinute); isEqual = true;
	}
	cout << endl << endl << "Ratio Multiplier: " << RatioMulti;
	cout << endl << "Which means you need "; Number();
	int iIngredientPerMinute = int(IngredientPerMinute);
	int iRequiredPerMinute = int(RequiredPerMinute);
	max = (iIngredientPerMinute > iRequiredPerMinute) ? iIngredientPerMinute : iRequiredPerMinute;
	do {
		if (max % iIngredientPerMinute == 0 && max % iRequiredPerMinute == 0) {
			//cout << endl << "LCM = " << max;
			break;
		}
		else
			++max;
	} while (true);
	IngredientRatio = max / iIngredientPerMinute;
	ProductRatio = max / iRequiredPerMinute;
	cout << endl << endl << "Actual ratio output only works perfectly if both per minute numbers are whole numbers." << endl;
	//Ratio();
	cout << "Ratio:     " << IngredientRatio << ":" << ProductRatio;
	cout << endl << "((Ingredient:Product) in number of crafting machines.)";
	//Not used to avoid confusion.
	/*if (isRequiredMore == true) cout << endl << "((Ingredient:Product) in number of crafting machines.)";
	if (isIngredientMore == true) cout << endl << "((Product:Ingredient) in number of crafting machines.)";*/
	//experimental
	while (isEQ != true) {
		i++;
		RatioMulti = RatioMulti * i;
		if (ceilf(RatioMulti) == RatioMulti) isEQ = true;
	}
	cout << endl << endl << endl << "~~~~~DEBUG~~~~~";
	cout << endl << isEqual << isRequiredMore << isIngredientMore;
	cout << endl << "LCM: " << max;
	cout << endl << "RatioMulti: " << RatioMulti;
	cout << endl << "Times multiplied: " << i;
	cout << endl;
	system("pause");
	return 0;
}


text:
section data
zero: const 0
2teste: const 2   ;token invalido pois comeca com numero
tres/: const 3  ; token invalido apresenta caracter diferente de letra, numero ou _

section text
add 2teste
add tres
div dois


text:
MapBG::MapBG(IMapRender* render)
	: IMapRender(render), _recalc(true), _currLevel(-1), _virtPage(Size(0, 0)),
		_cachePageSize(CACHE_PAGE_SIZE), _cachePageInitSize(CACHE_PAGE_INIT_SIZE)
{}

void MapBG::Render(Draw* w)
{
	if (_currLevel < 0 || _currLevel >= _levels.GetCount() || !GetTopRender())
		return;

	MipMapLevel& level = _levels[_currLevel];

	Point offset = GetTopRender()->GetPageOffset();
	Rect  page   = GetTopRender()->GetPageRect();
	Point lt     = GetTopRender()->GetPagePos();

	for (int i = 0; i < level.GetMipMaps().GetCount(); ++i)
	{
		Rect itemRect(level.GetMipMaps().GetKey(i), level.GetBlockSize());

		if (page.Intersects(itemRect))
			if (level.GetMipMaps()[i])
			{
				level.GetMipMaps()[i]
					->Render(w,
				         itemRect
							.Offseted(-lt)
							.Offseted(offset));
			}
	}

	IMapRender::Render(w);
}

void MapBG::StatePerformed(dword state, const String& param)
{
	if (_currLevel < 0 || _currLevel >= _levels.GetCount())
		return;

	MipMapLevel& level = _levels[_currLevel];
	Rect pageRect = GetPageRect();

	if (_recalc || !_virtPage.Contains(GetPageRect()))
	{
		_virtPage = pageRect.Inflated(level.GetBlockSize() * _cachePageInitSize);
		_recalc = true;
	}

	Rect currVirtualPage = _virtPage.Inflated(level.GetBlockSize() * _cachePageSize);

	if (!_recalc)
		return;

	for (int i = 0; i < level.GetMipMaps().GetCount(); ++i)
	{
		Point pi = level.GetMipMaps().GetKey(i);
		Rect itemRect(pi, level.GetBlockSize());

		if (!level.GetMipMaps()[i])
			continue;

		if (currVirtualPage.Intersects(itemRect))
		{
			level.GetMipMaps()[i]->Prepare(
				AppendFileName(_mapDir, NFormat("%d-%d-%d.png", _currLevel, pi.x, pi.y)),
				level.GetBlockSize()
			);
		}
		else
			level.GetMipMaps()[i]->Release();
	}

	_recalc = false;
}

bool MapBG::Load(const char* fp)
{
	if (!FileExists(fp))
	{
		LOG(NFormat("MapBG: File not exists, \"%s\"", fp));
		return false;
	}

	if (!LoadFromXMLFile(_levels, fp))
	{
		LOG("MapBG: Error while loading map from XML-file!");
		return false;
	}

	_mapDir = AppendFileName(GetFileDirectory(fp), GetFileTitle(fp));
	_currLevel = _levels.GetCount() > 0 ? 0 : -1;
	if (_currLevel < 0)
	{
		LOG("MapBG: No zoom levels found in map!");
		return false;
	}
	_recalc = true;

	return true;
}

bool MapBG::Zoom(int level)
{
	if (level < 0 || level >= _levels.GetCount())
		return false;
	_currLevel = level;
	_recalc = true;
	return true;
}

Rect MapBG::GetRect()
{
	if (_currLevel < 0 || _currLevel >= _levels.GetCount())
		return Size(0, 0);

	return Rect(Point(0, 0), _levels[_currLevel].GetTotalSize());
}


text:
	<?php global $post; ?>
    <time datetime="<?php echo esc_attr( mysql2date( DATE_W3C, $post->post_date_gmt, false ) ); ?>">
		<?php
		echo esc_html(
			sprintf(
				_x( '%s ago', '%s = human-readable time difference', 'accelerated-mobile-pages' ),
				human_time_diff( $this->get( 'post_publish_timestamp' ), current_time( 'timestamp' ) )
			)
		);
		?>
	</time>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using WinCommandPalette.Plugin.CreateCommand;
using WinCommandPalette.PluginSystem;

namespace WinCommandPalette.ViewModels.Options
{
    public class CreateNewCommandViewModel : ViewModelBase
    {
        private Config config;

        public List<ICreateCommand> AvailableCommandCreators => this.GetAvailableCommandCreators();

        private ICreateCommand selectedItem;

        public ICreateCommand SelectedItem
        {
            get => this.selectedItem;

            set
            {
                this.selectedItem = value;
                this.SelectedItem?.ClearAll();
                this.SelectedPlugin = PluginHelper.GetPlugins().Where(p => p.Commands.ContainsValue(this.SelectedItem)).FirstOrDefault();
                this.NotifyPropertyChanged(nameof(this.SelectedItem));
                this.NotifyPropertyChanged(nameof(this.CanManage));
            }
        }

        private int selectedIndex = -1;

        public int SelectedIndex
        {
            get => this.selectedIndex;

            set
            {
                this.selectedIndex = value;
                this.NotifyPropertyChanged(nameof(this.SelectedIndex));
                this.NotifyPropertyChanged(nameof(this.SelectedItem));
            }
        }

        public bool CanManage => this.SelectedItem != null;

        private PluginSystem.Plugin selectedPlugin;

        public PluginSystem.Plugin SelectedPlugin
        {
            get => this.selectedPlugin;

            set
            {
                this.selectedPlugin = value;
                this.NotifyPropertyChanged(nameof(this.SelectedPlugin));
            }
        }

        public CreateNewCommandViewModel(Config config)
        {
            this.config = config ??
                throw new ArgumentNullException(nameof(config));
        }

        internal void Refresh()
        {
            if (this.AvailableCommandCreators.Count > 0)
            {
                this.SelectedItem = null;
                this.SelectedIndex = 0;
            }

            this.SelectedItem?.ClearAll();
            this.NotifyPropertyChanged(nameof(this.SelectedItem));
        }

        internal void TestCommand(object sender, RoutedEventArgs e)
        {
            var command = this.SelectedItem?.GetCommand();
            if (command != null)
            {
                try
                {
                    command.Execute();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Error while executing command.\r\n\r\n{ex.Message}", "WinCommand Palette", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        internal void AddCommand(object sender, RoutedEventArgs e)
        {
            var command = this.SelectedItem?.GetCommand();
            if (command != null)
            {
                if (string.IsNullOrEmpty(command.Name))
                {
                    MessageBox.Show($"Command Name cant be empty", "WinCommand Palette - Options", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                this.config.Commands.Add(command);
                this.SelectedItem.ClearAll();
                MessageBox.Show($"Command '{command.Name}' added!", "WinCommand Palette - Options", MessageBoxButton.OK, MessageBoxImage.None);
            }
        }

        internal void Reset(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Are you sure you want reset all changes to this new command?", "WinCommand Palette - Options", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                this.SelectedItem?.ClearAll();
            }
        }

        private List<ICreateCommand> GetAvailableCommandCreators()
        {
            var commandCreators = new List<ICreateCommand>();
            commandCreators.AddRange(this.GetAllCreateCommandViews());

            return commandCreators;
        }

        private List<ICreateCommand> GetAllCreateCommandViews()
        {
            var createCommandViews = new List<ICreateCommand>();

            foreach (var plugin in PluginHelper.GetPlugins())
            {
                if (plugin.Commands?.Values != null)
                {
                    createCommandViews.AddRange(plugin.Commands.Values.Where(v => v != null));
                }
            }

            return createCommandViews;
        }
    }
}


text:
package aws

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go/service/ec2"
	"golang.org/x/crypto/ssh"

	"github.com/coreos/mantle/platform"
	"github.com/coreos/mantle/util"
)

type machine struct {
	cluster *cluster
	mach    *ec2.Instance
	dir     string
	journal *platform.Journal
	console string
}

func (am *machine) ID() string {
	return *am.mach.InstanceId
}

func (am *machine) IP() string {
	return *am.mach.PublicIpAddress
}

func (am *machine) PrivateIP() string {
	return *am.mach.PrivateIpAddress
}

func (am *machine) RuntimeConf() platform.RuntimeConfig {
	return am.cluster.RuntimeConf()
}

func (am *machine) SSHClient() (*ssh.Client, error) {
	return am.cluster.SSHClient(am.IP())
}

func (am *machine) PasswordSSHClient(user string, password string) (*ssh.Client, error) {
	return am.cluster.PasswordSSHClient(am.IP(), user, password)
}

func (am *machine) SSH(cmd string) ([]byte, []byte, error) {
	return am.cluster.SSH(am, cmd)
}

func (am *machine) Reboot() error {
	return platform.RebootMachine(am, am.journal)
}

func (am *machine) Destroy() {
	origConsole, err := am.cluster.flight.api.GetConsoleOutput(am.ID())
	if err != nil {
		plog.Warningf("Error retrieving console log for %v: %v", am.ID(), err)
	}

	if err := am.cluster.flight.api.TerminateInstances([]string{am.ID()}); err != nil {
		plog.Errorf("Error terminating instance %v: %v", am.ID(), err)
	}

	if am.journal != nil {
		am.journal.Destroy()
	}

	if err := am.saveConsole(origConsole); err != nil {
		plog.Errorf("Error saving console for instance %v: %v", am.ID(), err)
	}

	am.cluster.DelMach(am)
}

func (am *machine) ConsoleOutput() string {
	return am.console
}

func (am *machine) saveConsole(origConsole string) error {
	// If the instance has e.g. been running for several minutes, the
	// returned output will be non-empty but won't necessarily include
	// the most recent log messages. So we loop until the post-termination
	// logs are different from the pre-termination logs.
	err := util.WaitUntilReady(5*time.Minute, 5*time.Second, func() (bool, error) {
		var err error
		am.console, err = am.cluster.flight.api.GetConsoleOutput(am.ID())
		if err != nil {
			return false, err
		}

		if am.console == origConsole {
			plog.Debugf("waiting for console for %v", am.ID())
			return false, nil
		}

		return true, nil
	})
	if err != nil {
		err = fmt.Errorf("retrieving console output of %v: %v", am.ID(), err)
		if origConsole != "" {
			plog.Warning(err)
		} else {
			return err
		}
	}

	// merge the two logs
	overlapLen := 100
	if len(am.console) < overlapLen {
		overlapLen = len(am.console)
	}
	origIdx := strings.LastIndex(origConsole, am.console[0:overlapLen])
	if origIdx != -1 {
		// overlap
		am.console = origConsole[0:origIdx] + am.console
	} else if origConsole != "" {
		// two logs with no overlap; add scissors
		am.console = origConsole + "\n\n8<------------------------\n\n" + am.console
	}

	path := filepath.Join(am.dir, "console.txt")
	f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0644)
	if err != nil {
		return err
	}
	defer f.Close()
	f.WriteString(am.console)

	return nil
}

func (am *machine) JournalOutput() string {
	if am.journal == nil {
		return ""
	}

	data, err := am.journal.Read()
	if err != nil {
		plog.Errorf("Reading journal for instance %v: %v", am.ID(), err)
	}
	return string(data)
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../../../../style.css" type="text/css" media="screen">
<link rel="stylesheet" href="../../../../print.css" type="text/css" media="print">
<meta content="DOFBlur,idv.cjcat.zedbox.actions.DOFBlur,blur,farPlane,farRange,nearPlane,nearRange,quality,restore,update" name="keywords">
<title>idv.cjcat.zedbox.actions.DOFBlur</title>

ZedBox	All Packages | All Classes | Index | FramesNo Frames

Class DOFBlur	Properties | Methods | Events

Package	idv.cjcat.zedbox.actions

Class	public class DOFBlur

Inheritance	DOFBlur  Action  flash.events.EventDispatcher

  Applies a depth-of-field blurring effect.

Public Properties

 Hide Inherited Public Properties

 Show Inherited Public Properties

 	Property	Defined by

 		active : Boolean

   Denotes if the action is active, true by default.

	Action

 	 	blur : Number

	DOFBlur

 	 	farPlane : Number

   The far z plane.

	DOFBlur

 	 	farRange : Number

   The far range of variation.

	DOFBlur

 	 	nearPlane : Number

   The near z plane.

	DOFBlur

 	 	nearRange : Number

   The near range of variation.

	DOFBlur

 		priority : int

   Actions will be sorted according to their priorities.

	Action

 	 	quality : int

	DOFBlur

 		skipThisAction : Boolean

   Reset to false on each render loop.

	Action

Public Methods

 Hide Inherited Public Methods

 Show Inherited Public Methods

 	Method	Defined by

DOFBlur(nearPlane:Number = 700, farPlane:Number = 1300, range:Number = 100, blur:Number = 10, quality:int = 1)

	DOFBlur

doUpdate(data:ZedData):void

	Action

postUpdate():void

   [Template Method] This method is called once each render loop finishes.

	Action

preUpdate():void

   [Template Method] This method is called once upon each render loop,
   before the update() calls with each ZedSprite in the scene.

	Action

restore(data:ZedData):void

	DOFBlur

update(data:ZedData):void

	DOFBlur

Events

 Hide Inherited Events

 Show Inherited Events

 	Event	Summary	Defined by

zedBoxActoinPriorityChange

	 	Action

Property detail

blur	property

blur:Number  [read-write]Implementation

    public function get blur():Number

    public function set blur(value:Number):void

farPlane	property

farPlane:Number  [read-write]

   The far z plane.

Implementation

    public function get farPlane():Number

    public function set farPlane(value:Number):void

farRange	property

farRange:Number  [read-write]

   The far range of variation.

Implementation

    public function get farRange():Number

    public function set farRange(value:Number):void

nearPlane	property

nearPlane:Number  [read-write]

   The near z plane.

Implementation

    public function get nearPlane():Number

    public function set nearPlane(value:Number):void

nearRange	property

nearRange:Number  [read-write]

   The near range of variation.

Implementation

    public function get nearRange():Number

    public function set nearRange(value:Number):void

quality	property

quality:int  [read-write]Implementation

    public function get quality():int

    public function set quality(value:int):void

Constructor detail

DOFBlur	()	constructor

public function DOFBlur(nearPlane:Number = 700, farPlane:Number = 1300, range:Number = 100, blur:Number = 10, quality:int = 1)Parameters

	nearPlane:Number (default = 700)

	farPlane:Number (default = 1300)

	range:Number (default = 100)

	blur:Number (default = 10)

	quality:int (default = 1)

Method detail

restore	()	method

public override function restore(data:ZedData):voidParameters

	data:ZedData

update	()	method

public override function update(data:ZedData):voidParameters

	data:ZedData


text:
package org.springframework.boot.devtools.env;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.mock.env.MockEnvironment;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;

/**
 * Tests for {@link DevToolsHomePropertiesPostProcessor}.
 *
 * @author Phillip Webb
 * @author Andy Wilkinson
 */
public class DevToolsHomePropertiesPostProcessorTests {

	@Rule
	public TemporaryFolder temp = new TemporaryFolder();

	private File home;

	@Before
	public void setup() throws IOException {
		this.home = this.temp.newFolder();
	}

	@Test
	public void loadsHomeProperties() throws Exception {
		Properties properties = new Properties();
		properties.put("abc", "def");
		OutputStream out = new FileOutputStream(
				new File(this.home, ".spring-boot-devtools.properties"));
		properties.store(out, null);
		out.close();
		ConfigurableEnvironment environment = new MockEnvironment();
		MockDevToolHomePropertiesPostProcessor postProcessor = new MockDevToolHomePropertiesPostProcessor();
		postProcessor.postProcessEnvironment(environment, null);
		assertThat(environment.getProperty("abc"), equalTo("def"));
	}

	@Test
	public void ignoresMissingHomeProperties() throws Exception {
		ConfigurableEnvironment environment = new MockEnvironment();
		MockDevToolHomePropertiesPostProcessor postProcessor = new MockDevToolHomePropertiesPostProcessor();
		postProcessor.postProcessEnvironment(environment, null);
		assertThat(environment.getProperty("abc"), nullValue());
	}

	private class MockDevToolHomePropertiesPostProcessor
			extends DevToolsHomePropertiesPostProcessor {

		@Override
		protected File getHomeFolder() {
			return DevToolsHomePropertiesPostProcessorTests.this.home;
		}
	}

}


text:
import uuid
from setuptools import setup, find_packages
from pip.req import parse_requirements

install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1())
reqs = [str(req.req) for req in install_reqs]

setup(
    name='twitter_mysql',
    version='0.1',
    description='Scripts for normalizing a twitter dataset into mysql',
    author='John Robinson',
    author_email='soco@uw.edu',
    url='https://www.geosoco.com/projects/twitter-mysql/',
    packages=['twitter_mysql'],
    install_requires=reqs,
)