text:
using System;
using System.Linq;

namespace Blog.Model
{
    public class Posts : IPosts
    {
        private const int PageSize = 10;

        private static readonly Post[] _posts;

        static Posts()
        {
            _posts = new []
            {
                new Post
                {
                    Id = 1,
                    Title = "How to run a website on nginx with a SSL certificate from PositiveSSL",
                    Abstract = "Offering a secure connection has not only become a good practice in the previous years, but also a ranking signal for Google lately. Here is a short guide on how to install a cheap but solid certificate on nginx.",
                    Slug = "how-to-run-a-website-on-nginx-with-a-ssl-certificate-from-positivessl",
                    PublishingDate = new DateTime(2015, 1, 12)
                },
                new Post
                {
                    Id = 2,
                    Title = "Hosting Node.js and MongoDB",
                    Abstract = "After digging into web development with Node.js the last couple of months I had to choose where to host this blog, which I had decided to rewrite and run with Node as a result of my research.",
                    Slug = "hosting-nodejs-and-mongodb",
                    PublishingDate = new DateTime(2015, 1, 13)
                },
                new Post
                {
                    Id = 3,
                    Title = "Is Node.js better than ASP.NET?",
                    Abstract = "Coming a long way down the Microsoft Bubble Avenue and being a Microsoft MVP for ASP.NET since 2006, I always felt productive with my personal stack.",
                    Slug = "is-nodejs-better-than-aspnet",
                    PublishingDate = new DateTime(2015, 1, 16)
                },
                new Post
                {
                    Id = 4,
                    Title = "Startup Lesson Learned: Think About Your Shares",
                    Abstract = "Giving away shares of your company too early or too much is a dangerous and often irreversible thing. You should think twice before offering shares or accepting deals where you pay with them.",
                    Slug = "startup-lesson-learned-think-about-your-shares",
                    PublishingDate = new DateTime(2015, 1, 23)
                },
                new Post
                {
                    Id = 5,
                    Title = "Startup Lesson Learned: Technology Doesn't Matter",
                    Abstract = "I once read a nice quote which nails it and which read as follows: "It's not the tools you use that have to be cutting-edge, it is the product you build."",
                    Slug = "startup-lesson-learned-technology-doesnt-matter",
                    PublishingDate = new DateTime(2015, 1, 27)
                },
                new Post
                {
                    Id = 6,
                    Title = "TDD Is A Tool, Not A Religion",
                    Abstract = "People talking about Test Driven Development often split into two camps: fundamentalists, preaching no line of code should be written without a test, and deniers, refusing to use TDD at all.",
                    Slug = "tdd-is-a-tool-not-a-religion",
                    PublishingDate = new DateTime(2015, 2, 2)
                },
                new Post
                {
                    Id = 7,
                    Title = "Developing iOS Views: Custom Code And XIB",
                    Abstract = "While developing native mobile applications for iOS you generally have two options for creating (reusable) visual elements: writing them by hand or designing them visually with the Xcode Interface Builder.",
                    Slug = "developing-ios-views-custom-code-and-xib",
                    PublishingDate = new DateTime(2015, 2, 9),
                    Category = PostCategory.Xamarin
                },
                new Post
                {
                    Id = 8,
                    Title = "Startup Lesson Learned: The Minimum Lovable Product Is King",
                    Abstract = "Many people in the startup industry are talking about the 'MVP' – the Minimum Viable Product. But that term is useless unless you figure out what viable means to your customers.",
                    Slug = "startup-lesson-learned-the-minimum-lovable-product-is-king",
                    PublishingDate = new DateTime(2015, 2, 25)
                },
                new Post
                {
                    Id = 9,
                    Title = "Simple Feature Toggles For Xamarin Apps (And Everything Else)",
                    Abstract = "I consider continuous delivery a cool thing, particularly but not only in mobile app projects. It's nice to have the client see and touch new features as soon as they're ready. But sometimes it could be useful to disable those features. This is when Feature Toggles come into play.",
                    Slug = "simple-feature-toggles-for-xamarin-apps-and-everything-else",
                    PublishingDate = new DateTime(2015, 3, 9),
                    Category = PostCategory.Xamarin
                },
                new Post
                {
                    Id = 10,
                    Title = "Xamarin.iOS Memory Pitfalls",
                    Abstract = "One of the huge benefits of using Xamarin for developing cross-platform applications is clearly C#. But that often leads to bad coding practices which can put your app in jeopardy.",
                    Slug = "xamarinios-memory-pitfalls",
                    PublishingDate = new DateTime(2015, 4, 13),
                    Category = PostCategory.Xamarin
                },
                new Post
                {
                    Id = 11,
                    Title = "Startup Lesson Learned: Get Out Now!",
                    Abstract = "Everyone is talking about that Zuckerberg mantra \"Move fast and break things\" – but let's face it: It is much easier said than done.",
                    Slug = "startup-lesson-learned-get-out-now",
                    PublishingDate = new DateTime(2015, 4, 29)
                },
                new Post
                {
                    Id = 12,
                    Title = "How To Check Network Reachability With Xamarin.iOS on iOS 8",
                    Abstract = "Some features of your app may only be useful if the device of your user is currently connected to the internet, so you can make API calls, load images or do some other stuff.",
                    Slug = "how-to-check-network-reachability-with-xamarinios-on-ios-8",
                    PublishingDate = new DateTime(2015, 5, 15),
                    Category = PostCategory.Xamarin
                },
                new Post
                {
                    Id = 13,
                    Title = "How To Enable Dynamic Row Heights With UITableViews On iOS 8 And Later",
                    Abstract = "One of the rather annoying things of developing native iOS apps has always been a relatively common task: Displaying data with a varying size in UITableViews. Since iOS 8 it is easier than ever before – once you know the trick.",
                    Slug = "how-to-enable-dynamic-row-heights-with-uitableviews-on-ios-8-and-later",
                    PublishingDate = new DateTime(2015, 6, 14),
                    Category = PostCategory.Xamarin
                },
                new Post
                {
                    Id = 14,
                    Title = "Join Me At Developer Open Space 2015 in Leipzig",
                    Abstract = "I'm not a guy you are likely to meet at a classical tech conference. I don't like to waste my time with marketing bullshit and presentations of unprepared speakers. But I do like to meet like-minded people, good conversations, and some Schnitzel and beer.",
                    Slug = "join-me-at-developer-open-space-2015-in-leipzig",
                    PublishingDate = new DateTime(2015, 9, 28)
                },
                new Post
                {
                    Id = 15,
                    Title = "When 4K Isn't Enough Anymore",
                    Abstract = "Six months ago I made a serious mistake: I replaced my beloved MacBook Air with a MacBook Pro. In the period that followed I tried to be strong, but eventually I gave up last week. Now I am running my best hardware setup ever.",
                    Slug = "when-4k-isnt-enough-anymore",
                    PublishingDate = new DateTime(2015, 10, 6)
                },
                new Post
                {
                    Id = 16,
                    Title = "Developer Walk – A Great Idea Put Into Practice",
                    Abstract = "Three weeks ago the (probably) first official Developer Walk took place in Dresden, the lovely capital of Saxony in Germany – an event that should and will be repeated.",
                    Slug = "the-developer-walk-a-great-idea-put-into-practice",
                    PublishingDate = new DateTime(2015, 10, 9)
                },
                new Post
                {
                    Id = 17,
                    Title = "Automate All The Things: Distributing Xamarin iOS Apps To The AppStore And TestFlight Without Pain",
                    Abstract = "Everyone who has already built and shipped an iOS app to the AppStore knows the pain. That awful feeling when dealing with provisioning profiles, development and distribution certificates.",
                    Slug = "automate-all-the-things-distributing-xamarin-ios-apps-to-the-appstore-and-testflight-without-pain",
                    PublishingDate = new DateTime(2015, 11, 27),
                    Category = PostCategory.Xamarin
                },
                new Post
                {
                    Id = 18,
                    Title = "A Nicer Messaging Interface For Xamarin.Forms",
                    Abstract = "Xamarin.Forms provides cross-platform messaging capabilities for Android, iOS and Windows Phone with its MessagingCenter – but in a really strange fashion. I thought there must be a simpler way.",
                    Slug = "a-nicer-messaging-interface-for-xamarinforms",
                    PublishingDate = new DateTime(2016, 1, 18),
                    Category = PostCategory.Xamarin
                },
                new Post
                {
                    Id = 19,
                    Title = "Announcing MvvmNano – An MVVM Framework Tailored For Xamarin.Forms",
                    Abstract = "When digging around Xamarin.Forms over the past holidays I almost accidentally created a new MVVM Framework. Here is the story behind.",
                    Slug = "announcing-mvvmnano-a-mvvm-framework-tailored-for-xamarinforms",
                    PublishingDate = new DateTime(2016, 2, 12),
                    Category = PostCategory.Xamarin
                },
                new Post
                {
                    Id = 21,
                    Title = "Build Your Xamarin App For iOS Once, Deploy It Twice – Both To Your Testers And To The AppStore.",
                    Abstract = "The ordinary process of building and shipping an (iOS) app often includes at least two builds: The first for your internal tests, the second for the public (AppStore). That's somewhat less than perfect and we can do better.",
                    Slug = "build-your-xamarin-app-for-ios-once-deploy-it-twice-both-to-your-testers-and-to-the-appstore",
                    PublishingDate = new DateTime(2016, 5, 14),
                    Category = PostCategory.Xamarin
                },
                new Post
                {
                    Id = 22,
                    Title = "You Need To Think In Versions For Your Software? A Good Place To Start Is Git.",
                    Abstract = "Today it is often common to just deploy updates as they are ready to go. But if that's not possible you need to plan and manage versions thoroughly. Starting with this right in Git can make things really fast and easy.",
                    Slug = "you-need-to-think-in-versions-for-your-software-a-good-place-to-start-is-git",
                    PublishingDate = new DateTime(2016, 12, 1),
                    Category = PostCategory.Xamarin
                },/*
                new Post
                {
                    Id = 23,
                    Title = "Back To Sender: Some Thoughts On The MacBook Pro 13\" 2016",
                    Abstract = "There has been written a lot about the new 2016 MacBook Pro models. Albeit those reviews often include fundamental criticism, I made the decision to not cancel my order and give it a try anyway. But the experiment didn't last long.",
                    Slug = "back-to-sender-some-thoughts-on-the-macbook-pro-13-2016",
                    PublishingDate = new DateTime(2016, 12, 5),
                    Category = PostCategory.Xamarin
                },*/
                new Post
                {
                    Id = 24,
                    Title = "Certificate And Public Key Pinning With Xamarin",
                    Abstract = "Are you securing the communication between your app and its backend with HTTPS (SSL/TLS)? Fantastic. But how do you make sure the other side is authentic? Read on on how to do this with Xamarin for iOS and Android.",
                    Slug = "certificate-and-public-key-pinning-with-xamarin",
                    PublishingDate = new DateTime(2017, 1, 31),
                    Category = PostCategory.Xamarin
                },
                new Post
                {
                    Id = 25,
                    Title = "Moving From Node.js To ASP.NET Core",
                    Abstract = "In late 2014 I made the decision to leave ASP.NET behind and give Node.js a try. Fast forward two years and I am back in my beloved .NET environment but still developing on macOS and able to host on Linux.",
                    Slug = "moving-from-nodejs-to-aspnet-core",
                    PublishingDate = new DateTime(2017, 4, 2)
                },
                new Post
                {
                    Id = 26,
                    Title = "Powerful Scripting With F#",
                    Abstract = "There are plenty of options available when it comes to automating  processes with (more or less) simple scripts, even PowerShell on Mac and Linux nowadays. But there's an alternative right at your fingertips: F# Scripts.",
                    Slug = "powerful-scripting-with-fsharp",
                    PublishingDate = new DateTime(2017, 5, 14)
                },
                new Post
                {
                    Id = 27,
                    Title = "The Problem With F# Evangelism",
                    Abstract = "There seems to be a constant struggle to convince seasoned C# developers to give F# a try. Which is a pity because language and concepts deserve better.",
                    Slug = "the-problem-with-fsharp-evangelism",
                    PublishingDate = new DateTime(2017, 8, 16)
                },
                new Post
                {
                    Id = 28,
                    Title = "Building An F# Redux Store For C# Xamarin Apps",
                    Abstract = "Managing local data involves challenges the architecture of every mobile app needs to address. Redux is a JavaScript library to solve that very issue for web apps, but its core concepts also fit perfectly into the the mobile app space.",
                    Slug = "fsharp-redux-store-for-xamarin-apps",
                    PublishingDate = new DateTime(2018, 2, 20)
                }
            };
        }

        public Post[] Published()
        {
            return _posts
                .Where(p => p.IsPublished)
                .OrderByDescending(p => p.PublishingDate)
                .ToArray();
        }

        public IOrderedEnumerable<IGrouping<int, Post>> Archive()
        {
            return Published()
                .GroupBy(p => p.PublishingDate.Year)
                .OrderByDescending(g => g.Key);
        }

        public Post SingleOrDefault(string slug)
        {
            return Published()
                .SingleOrDefault(p => p.Slug.Equals(slug, StringComparison.OrdinalIgnoreCase));
        }

        public PostCollection Paged(int page)
        {
            Post[] publishedPosts = Published();

            var postsForPage = publishedPosts
                .Skip((page - 1) * PageSize)
                .Take(PageSize);

            return new PostCollection(postsForPage)
            {
                PreviousPage = page - 1,
                NextPage = page + 1,
                HasPreviousPage = page > 1,
                HasNextPage = publishedPosts.Length > page * PageSize
            };
        }
    }
}


text:
export default function reduce(state, action) {
  if (state === void 0) {
    state = [];
  }

  if (action === void 0) {
    action = {};
  }

  var _action = action,
      type = _action.type,
      payload = _action.payload,
      error = _action.error;

  if (error) {
    // Avoid adding the same error over and over
    if (state.length === 0 || state[state.length - 1] !== payload.message) {
      return state.concat([payload.message]);
    }
  } else if (type === 'errors/DISMISS') {
    return state.slice(1);
  }

  return state;
}
//# sourceMappingURL=errors.js.map

redpajama_set_name: RedPajamaGithub


text:
Rails.application.routes.draw do
  namespace :flash_s3 do
    resources :s3_files
  end
end


text:
"""Module provides a partition class for ``HdkOnNativeDataframe`` frame."""

import pandas

from modin.core.dataframe.pandas.partitioning.partition import PandasDataframePartition
from ..db_worker import DbWorker
import pyarrow

class HdkOnNativeDataframePartition(PandasDataframePartition):
    """
    A partition of ``HdkOnNativeDataframe`` frame.

    Class holds either a ``pandas.DataFrame`` or ``pyarrow.Table``.

    Parameters
    ----------
    frame_id : str, optional
        A corresponding HDK table name or None.
    pandas_df : pandas.DataFrame, optional
        Partition data in pandas format.
    arrow_table : pyarrow.Table, optional
        Partition data in Arrow format.
    length : int, optional
        Length of the partition.
    width : int, optional
        Width of the partition.

    Attributes
    ----------
    frame_id : str
        A corresponding HDK table name if partition was imported
        into HDK. Otherwise None.
    pandas_df : pandas.DataFrame, optional
        Partition data in pandas format.
    arrow_table : pyarrow.Table
        Partition data in Arrow format. None for partitions holding
        `pandas.DataFrame`.
    _length_cache : int
        Length of the partition.
    _width_cache : int
        Width of the partition.
    """

    def __init__(
        self, frame_id=None, pandas_df=None, arrow_table=None, length=None, width=None
    ):
        self.pandas_df = pandas_df
        self.frame_id = frame_id
        self.arrow_table = arrow_table
        self._length_cache = length
        self._width_cache = width
        self._server = DbWorker

    def __del__(self):
        """Deallocate HDK resources related to the partition."""
        if self.frame_id is not None:
            self._server.dropTable(self.frame_id)

    def to_pandas(self):
        """
        Transform to pandas format.

        Returns
        -------
        pandas.DataFrame
        """
        obj = self.get()
        if isinstance(obj, (pandas.DataFrame, pandas.Series)):
            return obj
        assert isinstance(obj, pyarrow.Table)
        return obj.to_pandas()

    def get(self):
        """
        Get partition data.

        Returns
        -------
        pandas.DataFrame or pyarrow.Table
        """
        if self.arrow_table is not None:
            return self.arrow_table
        return self.pandas_df

    @classmethod
    def put(cls, obj):
        """
        Create partition from ``pandas.DataFrame`` or ``pandas.Series``.

        Parameters
        ----------
        obj : pandas.Series or pandas.DataFrame
            Source frame.

        Returns
        -------
        HdkOnNativeDataframePartition
            The new partition.
        """
        return HdkOnNativeDataframePartition(
            pandas_df=obj.copy(), length=len(obj.index), width=len(obj.columns)
        )

    def wait(self):
        """
        Wait until the partition data is ready for use.

        Returns
        -------
        pandas.DataFrame
            The partition that is ready to be used.
        """
        if self.arrow_table is not None:
            return self.arrow_table
        return self.pandas_df

    @classmethod
    def put_arrow(cls, obj):
        """
        Create partition from ``pyarrow.Table``.

        Parameters
        ----------
        obj : pyarrow.Table
            Source table.

        Returns
        -------
        HdkOnNativeDataframePartition
            The new partition.
        """
        return HdkOnNativeDataframePartition(
            arrow_table=obj,
            length=len(obj),
            width=len(obj.columns),
        )


text:
/*! \file $Id: WinRobotService.h 94 2011-10-08 15:36:05Z caoym $
*  \author caoym
*  \brief CWinRobotService
*/

#pragma once
#include "resource.h"
#include "WinRobotCore_i.h"
#include "sync/cslock.h"
#include <map>
#include "reference/IReference.h"

//! manager WinRobot sessions
/*
	run as a Windows service,while GetActiveConsoleSession is called
	,create a child process on active console session(if the child
	process specified does not exist)
*/
class /*ATL_NO_VTABLE*/ CWinRobotService :
	public CComObjectRootEx<CComMultiThreadModel>,
	public CComCoClass<CWinRobotService, &CLSID_WinRobotService>,
	public IConnectionPointContainerImpl<CWinRobotService>,
	public IDispatchImpl<IWinRobotService, &IID_IWinRobotService, &LIBID_WinRobotCoreLib, /*wMajor =*/ 1, /*wMinor =*/ 0>
{
public:
	CWinRobotService()
		:m_hNewReg(0)
		,m_hExit(0)
	{
	}

DECLARE_REGISTRY_RESOURCEID(IDR_WINROBOTSERVICE)

BEGIN_COM_MAP(CWinRobotService)
	COM_INTERFACE_ENTRY(IWinRobotService)
	COM_INTERFACE_ENTRY(IDispatch)
	COM_INTERFACE_ENTRY(IConnectionPointContainer)
END_COM_MAP()

BEGIN_CONNECTION_POINT_MAP(CWinRobotService)

END_CONNECTION_POINT_MAP()

	DECLARE_PROTECT_FINAL_CONSTRUCT()

	HRESULT FinalConstruct();

	void FinalRelease();

public:
	//! receive the session currently attached to the physical console
	STDMETHOD(GetActiveConsoleSession)(IUnknown** ppSession);

	//! register WinRobot session
	/*!
		called by WinRobotSession when it starts.
		\param sid session id
		\param pSession point to IWinRobotSession
		\param processid id of the WinRobotSession process
	*/
	STDMETHOD(RegSession)(ULONG sid, ULONG processid,IUnknown* pSession);

private:
	struct SESSION
	{
		HANDLE m_hProcess;
		CComPtr<IWinRobotSession> pSession;
		SESSION(HANDLE hd = 0)
			:m_hProcess(hd){

		}
		~SESSION(){
			if(m_hProcess){
				CloseHandle(m_hProcess);
			}
		}
		bool IsOK()
		{
			if(m_hProcess == 0) return false;
			return WaitForSingleObject(m_hProcess,0) == WAIT_TIMEOUT;
		}
	};
	typedef std::map<ULONG , CRefObj< CReference_T<SESSION> > > SESSIONS;

	CCrtSection m_csLock; // lock for GetActiveConsoleSession
	CCrtSection m_csLockSessions; //lock for m_sessions
	SESSIONS m_sessions;
	HANDLE m_hNewReg; //signed when new session registered
	HANDLE m_hExit;// signed when stop

	HANDLE CreateChildProcess(ULONG sid);
};

OBJECT_ENTRY_AUTO(__uuidof(WinRobotService), CWinRobotService)


text:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import AppLink from '~/_components/appLink';
import './styles.scss';

const mapDispatchToProps = dispatch => {
	return {}
};

const mapStateToProps = state => {
	return {}
}

class ConnectedAccountsList extends Component {
	constructor(props) {
		super(props);
		this.state = {};
	}
	componentWillReceiveProps(nextProps){
	}
	getAccountLink(accountId){
		return "/money_maps/"+this.props.moneyMapId+"/accounts/"+accountId;
	}
	render() {
		let accounts = this.props.accounts;
		return (

						Account Name
						Account Type
						Balance

				{accounts.length > 5 &&

							Account Name
							Account Type
							Balance

				}

					{Object.keys(accounts).map((id) =>

								<AppLink to={this.getAccountLink(id)}>
									{accounts[id].name}
								</AppLink>

								{accounts[id].account_type}

					)}

		);
	}
}

const AccountsList = connect(mapStateToProps, mapDispatchToProps)(ConnectedAccountsList);

AccountsList.defaultProps = {
	accounts:{}
}

AccountsList.propTypes = {
	accounts: PropTypes.object.isRequired
}

export default AccountsList;


text:
namespace xziar::nailang
{
using namespace std::string_view_literals;
#define NLRT_THROW_EX(...) HandleException(CREATE_EXCEPTIONEX(NailangRuntimeException, __VA_ARGS__))

std::u32string_view EmbedOpHelper::GetOpName(EmbedOps op) noexcept
{
    switch (op)
    {
    #define RET_NAME(op) case EmbedOps::op: return U"" STRINGIZE(op)
    RET_NAME(Equal);
    RET_NAME(NotEqual);
    RET_NAME(Less);
    RET_NAME(LessEqual);
    RET_NAME(Greater);
    RET_NAME(GreaterEqual);
    RET_NAME(And);
    RET_NAME(Or);
    RET_NAME(Add);
    RET_NAME(Sub);
    RET_NAME(Mul);
    RET_NAME(Div);
    RET_NAME(Rem);
    RET_NAME(BitAnd);
    RET_NAME(BitOr);
    RET_NAME(BitXor);
    RET_NAME(ValueOr);
    RET_NAME(CheckExist);
    RET_NAME(Not);
    default: return U"Unknwon"sv;
    }
}

std::u32string_view Expr::TypeName(const Expr::Type type) noexcept
{
    switch (type)
    {
    case Expr::Type::Empty:   return U"empty"sv;
    case Expr::Type::Func:    return U"func-call"sv;
    case Expr::Type::Unary:   return U"unary-expr"sv;
    case Expr::Type::Binary:  return U"binary-expr"sv;
    case Expr::Type::Ternary: return U"ternary-expr"sv;
    case Expr::Type::Query:   return U"query-expr"sv;
    case Expr::Type::Assign:  return U"assign-expr"sv;
    case Expr::Type::Var:     return U"variable"sv;
    case Expr::Type::Str:     return U"string"sv;
    case Expr::Type::Uint:    return U"uint"sv;
    case Expr::Type::Int:     return U"int"sv;
    case Expr::Type::FP:      return U"fp"sv;
    case Expr::Type::Bool:    return U"bool"sv;
    default:                  return U"error"sv;
    }
}

#define NATIVE_TYPE_MAP BOOST_PP_VARIADIC_TO_SEQ(   \
    (Any,    Arg),                  \
    (Bool,   bool),                 \
    (U8,     uint8_t),              \
    (I8,     int8_t),               \
    (U16,    uint16_t),             \
    (I16,    int16_t),              \
    (F16,    half_float::half),     \
    (U32,    uint32_t),             \
    (I32,    int32_t),              \
    (F32,    float),                \
    (U64,    uint64_t),             \
    (I64,    int64_t),              \
    (F64,    double),               \
    (Str8,   common::str::u8string),\
    (Str16,  std::u16string),       \
    (Str32,  std::u32string),       \
    (Sv8,    std::string_view),     \
    (Sv16,   std::u16string_view),  \
    (Sv32,   std::u32string_view))

#define NATIVE_TYPE_EACH_(r, func, tp) func(BOOST_PP_TUPLE_ELEM(2, 0, tp), BOOST_PP_TUPLE_ELEM(2, 1, tp))
#define NATIVE_TYPE_EACH(func) BOOST_PP_SEQ_FOR_EACH(NATIVE_TYPE_EACH_, func, NATIVE_TYPE_MAP)

std::u32string_view NativeWrapper::TypeName(NativeWrapper::Type type) noexcept
{
#define RET(tenum, type) case Type::tenum: return U"" STRINGIZE(tenum) ""sv;
    switch (type)
    {
    NATIVE_TYPE_EACH(RET)
    default: return U"Unknown"sv;
    }
#undef RET
}

template<typename T>
struct NativeGetSet final : public GetSet::Handler
{
    static constexpr auto DisableSet = common::is_specialization<T, std::basic_string_view>::value;
    [[nodiscard]] ArgAccess GetAccess(const GetSet& data) const noexcept override
    {
        auto ret = ArgAccess::Empty;
        if (data.Meta & NativeWrapper::MetaType::EnableGet)
            ret |= ArgAccess::ReadOnly;
        if constexpr(!DisableSet)
            if (data.Meta & NativeWrapper::MetaType::EnableSet)
                ret |= ArgAccess::WriteOnly;
        return ret;
    }
    [[nodiscard]] Arg Get(const GetSet& data) const override
    {
        Expects(data.Meta & NativeWrapper::MetaType::EnableGet);
        [[maybe_unused]] const bool shouldMove = data.Meta & NativeWrapper::MetaType::MoveGet;
        const auto ptr = reinterpret_cast<T*>(static_cast<uintptr_t>(data.Ptr)) + data.Idx;
        if constexpr (std::is_floating_point_v<T> || std::is_same_v<T, half_float::half>)
            return static_cast<double>(*ptr);
        else if constexpr (std::is_unsigned_v<T>)
            return static_cast<uint64_t>(*ptr);
        else if constexpr (std::is_signed_v<T>)
            return static_cast<int64_t>(*ptr);
        else if constexpr (std::is_same_v<T, Arg>)
        {
            if (shouldMove)
                return std::move(*ptr);
            else
                return *ptr;
        }
        else if constexpr (std::is_same_v<T, std::u32string>)
        {
            if (shouldMove)
                return *ptr;
            else
                return std::u32string_view(*ptr);
        }
        else if constexpr (std::is_same_v<T, std::u32string_view>)
        {
            if (shouldMove)
                return std::u32string(*ptr);
            else
                return *ptr;
        }
        else if constexpr (common::is_specialization<T, std::basic_string>::value || common::is_specialization<T, std::basic_string_view>::value)
        {
            using Char = typename T::value_type;
            constexpr auto chset = std::is_same_v<Char, char> ? common::str::Encoding::UTF8 : common::str::DefaultEncoding<Char>;
            return common::str::to_u32string(*ptr, chset);
        }
        else if constexpr (std::is_same_v<T, bool>)
            return *ptr;
        else
        {
            Expects(false);
            return {};
        }
    }
    [[nodiscard]] bool Set(const GetSet& data, Arg arg) const override
    {
        Expects(data.Meta & NativeWrapper::MetaType::EnableSet);
        [[maybe_unused]] const auto ptr = reinterpret_cast<T*>(static_cast<uintptr_t>(data.Ptr)) + data.Idx;
        if constexpr (std::is_floating_point_v<T>)
        {
            if (const auto val = arg.GetFP(); val.has_value())
            {
                *ptr = static_cast<T>(*val);
                return true;
            }
        }
        else if constexpr (std::is_same_v<T, half_float::half>)
        {
            if (const auto val = arg.GetFP(); val.has_value())
            {
                *ptr = static_cast<T>(static_cast<float>(*val));
                return true;
            }
        }
        else if constexpr (std::is_unsigned_v<T>)
        {
            if (const auto val = arg.GetUint(); val.has_value())
            {
                *ptr = static_cast<T>(*val);
                return true;
            }
        }
        else if constexpr (std::is_signed_v<T>)
        {
            if (const auto val = arg.GetInt(); val.has_value())
            {
                *ptr = static_cast<T>(*val);
                return true;
            }
        }
        else if constexpr (std::is_same_v<T, Arg>)
        {
            *ptr = std::move(arg);
            return true;
        }
        else if constexpr (common::is_specialization<T, std::basic_string>::value)
        {
            if (const auto val = arg.GetStr(); val.has_value())
            {
                using U = typename T::value_type;
                if constexpr (std::is_same_v<U, char32_t>)
                    *ptr = *val;
                else if constexpr (std::is_same_v<U, u8ch_t>)
                    *ptr = common::str::to_u8string(*val);
                else if constexpr (std::is_same_v<U, char16_t>)
                    *ptr = common::str::to_u16string(*val);
                else
                    static_assert(!common::AlwaysTrue<T>, "unsupported char type");
                return true;
            }
        }
        else
            Expects(false);
        return false;
    }
};

const GetSet::Handler* NativeWrapper::GetGetSet(Type type) noexcept
{
#define RET(tenum, t) case Type::tenum: { static NativeGetSet<t> Host; return &Host; }
    switch (type)
    {
    NATIVE_TYPE_EACH(RET)
    default: return nullptr;
    }
#undef RET
}

template<typename T> struct U8StrFix { using Type = T; };
#if defined(__cpp_char8_t) && __cpp_char8_t >= 201811L
template<> struct U8StrFix<std::u8string> { using Type = std::string; };
template<> struct U8StrFix<std::u8string_view> { using Type = std::string_view; };
#endif
ArrayRef::SpanVariant ArrayRef::GetSpan() const noexcept
{
#define SP(type) common::span<type>{ reinterpret_cast<type*>(DataPtr), static_cast<size_t>(Length) }
#define RET(tenum, type) case Type::tenum:                              \
        if (IsReadOnly) return SP(const typename U8StrFix<type>::Type); \
        else return SP(typename U8StrFix<type>::Type);                  \

    switch (ElementType)
    {
    NATIVE_TYPE_EACH(RET)
    default: return {};
    }
#undef RET
#undef SP
}

struct ArrayEleFormatter : common::str::Formatter<char32_t>
{
    using Formatter::PutFloat;
    using Formatter::PutInteger;
    using Formatter::PutString;
};
static ArrayEleFormatter ArrayEleFmter;

void ArrayRef::PrintToStr(std::u32string& str, std::u32string_view delim) const
{
    const auto Append = [&](std::u32string& str, auto delim, auto ptr, const size_t len)
    {
        for (uint32_t idx = 0; idx < len; ++idx)
        {
            if (idx > 0) str.append(delim);
            using T = std::decay_t<decltype(*ptr)>;
            if constexpr (std::is_same_v<Arg, T>)
                str.append(ptr[idx].ToString().StrView());
            else if constexpr (common::is_specialization<T, std::basic_string>::value || common::is_specialization<T, std::basic_string_view>::value)
            {
                using namespace common::str;
                using Char = typename T::value_type;
                if constexpr (sizeof(Char) == sizeof(char32_t))
                    str.append(reinterpret_cast<const char32_t*>(ptr[idx].data()), ptr[idx].size());
                else
                {
                    const auto data32 = to_u32string(ptr[idx], sizeof(Char) == sizeof(char) ? Encoding::UTF8 : DefaultEncoding<Char>);
                    str.append(data32);
                }
            }
            else if constexpr (std::is_same_v<T, bool>)
                str.append(ptr[idx] ? U"true"sv : U"false"sv);
            else if constexpr (std::is_same_v<T, half_float::half>)
                ArrayEleFmter.PutFloat(str, (float)ptr[idx], nullptr);
            else if constexpr (std::is_floating_point_v<T>)
                ArrayEleFmter.PutFloat(str, ptr[idx], nullptr);
            else if constexpr (std::is_integral_v<T>)
            {
                constexpr auto isSigned = std::is_signed_v<T>;
                using U = std::conditional_t<(sizeof(T) > 4), uint64_t, uint32_t>;
                ArrayEleFmter.PutInteger(str, static_cast<U>(ptr[idx]), isSigned, nullptr);
            }
            else
                static_assert(!common::AlwaysTrue<T>, "unexpected");
        }
    };
#define PRT(tenum, type) case Type::tenum:                              \
    Append(str, delim, reinterpret_cast<const type*>(DataPtr), Length); \
    return;

    switch (ElementType)
    {
    NATIVE_TYPE_EACH(PRT)
    default: return;
    }
#undef PRT
}

#undef NATIVE_TYPE_EACH
#undef NATIVE_TYPE_EACH_
#undef NATIVE_TYPE_MAP

Arg::Arg(const Arg& other) noexcept :
    Data0(other.Data0), Data1(other.Data1), Data2(other.Data2), Data3(other.Data3), TypeData(other.TypeData)
{
    if (IsCustom())
    {
        const auto& var = GetCustom();
        var.Host->IncreaseRef(var);
    }
    else if (TypeData == Type::U32Str && Data1 > 0)
    {
        auto str = other.GetVar<Type::U32Str>();
        common::SharedString<char32_t>::PlacedIncrease(str);
    }
}

Arg& Arg::operator=(const Arg& other) noexcept
{
    if (HAS_FIELD(TypeData, Type::OwnershipBit))
        Release();
    Data0 = other.Data0;
    Data1 = other.Data1;
    Data2 = other.Data2;
    Data3 = other.Data3;
    TypeData = other.TypeData;
    if (IsCustom())
    {
        const auto& var = GetCustom();
        var.Host->IncreaseRef(var);
    }
    else if (TypeData == Type::U32Str && Data1 > 0)
    {
        auto str = other.GetVar<Type::U32Str>();
        common::SharedString<char32_t>::PlacedIncrease(str);
    }
    return *this;
}

void Arg::Release() noexcept
{
    if (IsCustom())
    {
        auto& var = GetCustom();
        var.Host->DecreaseRef(var);
    }
    else if (TypeData == Type::U32Str && Data1 > 0)
    {
        auto str = GetVar<Type::U32Str>();
        common::SharedString<char32_t>::PlacedDecrease(str);
    }
    TypeData = Type::Empty;
}

std::optional<bool> Arg::GetBool() const noexcept
{
    if (IsCustom())
        return GetCustom().Call<&CustomVar::Handler::ConvertToCommon>(Type::BoolBit).GetBool();
    switch (TypeData)
    {
    case Type::Uint:    return  GetVar<Type::Uint>() != 0;
    case Type::Int:     return  GetVar<Type::Int>() != 0;
    case Type::FP:      return  GetVar<Type::FP>() != 0;
    case Type::Bool:    return  GetVar<Type::Bool>();
    case Type::U32Str:  return !GetVar<Type::U32Str>().empty();
    case Type::U32Sv:   return !GetVar<Type::U32Sv>().empty();
    default:            return {};
    }
}
std::optional<uint64_t> Arg::GetUint() const noexcept
{
    if (IsCustom())
        return GetCustom().Call<&CustomVar::Handler::ConvertToCommon>(Type::NumberBit | Type::BoolBit).GetUint();
    switch (TypeData)
    {
    case Type::Uint:    return GetVar<Type::Uint>();
    case Type::Int:     return static_cast<uint64_t>(GetVar<Type::Int>());
    case Type::FP:      return static_cast<uint64_t>(GetVar<Type::FP>());
    case Type::Bool:    return GetVar<Type::Bool>() ? 1u : 0u;
    default:            return {};
    }

}
std::optional<int64_t> Arg::GetInt() const noexcept
{
    if (IsCustom())
        return GetCustom().Call<&CustomVar::Handler::ConvertToCommon>(Type::NumberBit | Type::BoolBit).GetUint();
    switch (TypeData)
    {
    case Type::Uint:    return static_cast<int64_t>(GetVar<Type::Uint>());
    case Type::Int:     return GetVar<Type::Int>();
    case Type::FP:      return static_cast<int64_t>(GetVar<Type::FP>());
    case Type::Bool:    return GetVar<Type::Bool>() ? 1 : 0;
    default:            return {};
    }

}
std::optional<double> Arg::GetFP() const noexcept
{
    if (IsCustom())
        return GetCustom().Call<&CustomVar::Handler::ConvertToCommon>(Type::NumberBit | Type::BoolBit).GetFP();
    switch (TypeData)
    {
    case Type::Uint:    return static_cast<double>(GetVar<Type::Uint>());
    case Type::Int:     return static_cast<double>(GetVar<Type::Int>());
    case Type::FP:      return GetVar<Type::FP>();
    case Type::Bool:    return GetVar<Type::Bool>() ? 1. : 0.;
    default:            return {};
    }
}
std::optional<std::u32string_view> Arg::GetStr() const noexcept
{
    if (IsCustom())
        return GetCustom().Call<&CustomVar::Handler::ConvertToCommon>(Type::StringBit).GetStr();
    switch (TypeData)
    {
    case Type::U32Str:  return GetVar<Type::U32Str>();
    case Type::U32Sv:   return GetVar<Type::U32Sv>();
    default:            return {};
    }
}

common::str::StrVariant<char32_t> Arg::ToString() const noexcept
{
    if (IsCustom())
    {
        return GetCustom().Call<&CustomVar::Handler::ToString>();
    }
    switch (REMOVE_MASK(TypeData, Type::ConstBit))
    {
    default:
    case Type::Var:     return {};
    case Type::U32Str:  return GetVar<Type::U32Str>();
    case Type::U32Sv:   return GetVar<Type::U32Sv>();
    case Type::Bool:    return GetVar<Type::Bool>() ? U"true"sv : U"false"sv;
    case Type::Uint:
    {
        std::u32string ret;
        ArrayEleFmter.PutInteger(ret, GetVar<Type::Uint>(), false, nullptr);
        return ret;
    }
    case Type::Int:
    {
        std::u32string ret;
        ArrayEleFmter.PutInteger(ret, GetVar<Type::Uint, false> (), true, nullptr);
        return ret;
    }
    case Type::FP:
    {
        std::u32string ret;
        ArrayEleFmter.PutFloat(ret, GetVar<Type::FP>(), nullptr);
        return ret;
    }
    case Type::Array:
    {
        std::u32string ret = U"[";
        GetVar<Type::Array>().PrintToStr(ret, U", "sv);
        ret.append(U"]"sv);
        return std::move(ret);
    }
    }
}

#define TYPE_ITEM(type, name) { common::enum_cast(type), U"" name ""sv }
static constexpr auto ArgTypeMapping = BuildStaticLookup(uint16_t, std::u32string_view,
    TYPE_ITEM(Arg::Type::CategoryGetSet, "getset"),
    TYPE_ITEM(Arg::Type::CategoryArgPtr, "argptr"),
    TYPE_ITEM(Arg::Type::Empty,     "empty"),
    TYPE_ITEM(Arg::Type::Var   | Arg::Type::ConstBit, "variable"),
    TYPE_ITEM(Arg::Type::Var,       "variable"),
    TYPE_ITEM(Arg::Type::Array | Arg::Type::ConstBit, "array"),
    TYPE_ITEM(Arg::Type::Array,     "array"),
    TYPE_ITEM(Arg::Type::U32Str,    "string"),
    TYPE_ITEM(Arg::Type::U32Sv,     "string_view"),
    TYPE_ITEM(Arg::Type::Uint,      "uint"),
    TYPE_ITEM(Arg::Type::Int,       "int"),
    TYPE_ITEM(Arg::Type::FP,        "fp"),
    TYPE_ITEM(Arg::Type::Bool,      "bool"),
    TYPE_ITEM(Arg::Type::Boolable,  "boolable"),
    TYPE_ITEM(Arg::Type::String,    "string-ish"),
    TYPE_ITEM(Arg::Type::ArrayLike, "array-like"),
    TYPE_ITEM(Arg::Type::Number,    "number"),
    TYPE_ITEM(Arg::Type::Integer,   "integer"),
    TYPE_ITEM(Arg::Type::BoolBit,   "(bool)"),
    TYPE_ITEM(Arg::Type::StringBit, "(str)"),
    TYPE_ITEM(Arg::Type::NumberBit, "(num)"),
    TYPE_ITEM(Arg::Type::ArrayBit,  "(arr)"),
    TYPE_ITEM(Arg::Type::BoolBit   | Arg::Type::StringBit,  "(bool|str)"),
    TYPE_ITEM(Arg::Type::BoolBit   | Arg::Type::NumberBit,  "(bool|num)"),
    TYPE_ITEM(Arg::Type::BoolBit   | Arg::Type::ArrayBit,   "(bool|arr)"),
    TYPE_ITEM(Arg::Type::StringBit | Arg::Type::NumberBit,  "(str|num)"),
    TYPE_ITEM(Arg::Type::StringBit | Arg::Type::ArrayBit,   "(str|arr)"),
    TYPE_ITEM(Arg::Type::NumberBit | Arg::Type::ArrayBit,   "(num|arr)"),
    TYPE_ITEM(Arg::Type::BoolBit   | Arg::Type::StringBit | Arg::Type::NumberBit,   "(bool|str|num)"),
    TYPE_ITEM(Arg::Type::BoolBit   | Arg::Type::StringBit | Arg::Type::ArrayBit,    "(bool|str|arr)"),
    TYPE_ITEM(Arg::Type::BoolBit   | Arg::Type::NumberBit | Arg::Type::ArrayBit,    "(bool|num|arr)"),
    TYPE_ITEM(Arg::Type::StringBit | Arg::Type::NumberBit | Arg::Type::ArrayBit,    "(str|num|arr)"),
    TYPE_ITEM(Arg::Type::BoolBit   | Arg::Type::StringBit | Arg::Type::NumberBit | Arg::Type::ArrayBit, "(bool|str|num|arr)"));
#undef TYPE_ITEM
std::u32string_view Arg::TypeName(const Arg::Type type) noexcept
{
    return ArgTypeMapping(common::enum_cast(type)).value_or(U"unknown"sv);
}

void Arg::Decay()
{
    if (IsGetSet())
        *this = GetGetSet().Get();
    else if (IsArgPtr())
    {
        const auto isConst = !HAS_FIELD(static_cast<ArgAccess>(Data3), ArgAccess::WriteOnly);
        *this = *reinterpret_cast<const Arg*>(Data0.Uint);
        if (IsCustom() && isConst)
            TypeData |= Type::ConstBit;
    }
}
bool Arg::Set(Arg val)
{
    if (IsGetSet())
        return GetGetSet().Set(std::move(val));
    else if (IsArgPtr())
    {
        if (!MATCH_FIELD(static_cast<ArgAccess>(Data3), ArgAccess::Assignable))
            return false;
        *reinterpret_cast<Arg*>(Data0.Uint) = std::move(val);
        return true;
    }
    if (IsCustom())
        return GetCustom().Call<&CustomVar::Handler::HandleAssign>(std::move(val));
    return false;
}

static CompareResult NumCompare(const Arg& left, const Arg& right) noexcept
{
    // Expects(HAS_FIELD(right.TypeData, Arg::Type::NumberBit));
    if (!HAS_FIELD(right.TypeData, Arg::Type::NumberBit))
        return {};
    if (const bool isLeftFP = HAS_FIELD(left.TypeData, Arg::Type::FPBit), isRightFP = HAS_FIELD(right.TypeData, Arg::Type::FPBit);
        isLeftFP || isRightFP)
    {
        static_assert(std::numeric_limits<double>::is_iec559, "Need support for IEEE 754");
        const auto l = left.GetFP().value(), r = right.GetFP().value();
        if (std::isnan(l) || std::isnan(r))
            return CompareResultCore::NotEqual | CompareResultCore::Equality;
        if (l < r) return CompareResultCore::Less    | CompareResultCore::StrongOrder;
        if (l > r) return CompareResultCore::Greater | CompareResultCore::StrongOrder;
        return CompareResultCore::Equal | CompareResultCore::StrongOrder;
    }
    const bool isLeftUnsigned  = HAS_FIELD( left.TypeData, Arg::Type::UnsignedBit);
    const bool isRightUnsigned = HAS_FIELD(right.TypeData, Arg::Type::UnsignedBit);
    const bool isLeftNeg  = !isLeftUnsigned  &&  left.GetVar<Arg::Type::Int, false>() < 0;
    const bool isRightNeg = !isRightUnsigned && right.GetVar<Arg::Type::Int, false>() < 0;
    if (isLeftNeg && !isRightNeg)
        return CompareResultCore::Less | CompareResultCore::StrongOrder;
    if (!isLeftNeg && isRightNeg)
        return CompareResultCore::Greater | CompareResultCore::StrongOrder;
    if (isLeftNeg) // both neg
    {
        const auto l =  left.GetVar<Arg::Type::Int>();
        const auto r = right.GetVar<Arg::Type::Int>();
        if (l < r) return CompareResultCore::Less    | CompareResultCore::StrongOrder;
        if (l > r) return CompareResultCore::Greater | CompareResultCore::StrongOrder;
        return CompareResultCore::Equal | CompareResultCore::StrongOrder;
    }
    else // both pos
    {
        const auto l =  left.GetVar<Arg::Type::Uint, false>();
        const auto r = right.GetVar<Arg::Type::Uint, false>();
        if (l < r) return CompareResultCore::Less    | CompareResultCore::StrongOrder;
        if (l > r) return CompareResultCore::Greater | CompareResultCore::StrongOrder;
        return CompareResultCore::Equal | CompareResultCore::StrongOrder;
    }
}
CompareResult Arg::NativeCompare(const Arg& right) const noexcept
{
    Expects(!IsCustom());
    if (HAS_FIELD(TypeData, Type::StringBit)) // direct process string, no decay
    {
        const auto r_ = right.GetStr();
        if (r_.has_value())
        {
            const auto l = GetVar<Type::U32Sv, false>(), r = r_.value();
            const auto ret = std::char_traits<char32_t>::compare(l.data(), r.data(), std::min(l.size(), r.size()));
            if (ret < 0)             return CompareResultCore::StrongOrder | CompareResultCore::Less;
            if (ret > 0)             return CompareResultCore::StrongOrder | CompareResultCore::Greater;
            if (l.size() < r.size()) return CompareResultCore::StrongOrder | CompareResultCore::Less;
            if (l.size() > r.size()) return CompareResultCore::StrongOrder | CompareResultCore::Greater;
            return CompareResultCore::StrongOrder | CompareResultCore::Equal;
        }
    }
    else if (HAS_FIELD(TypeData, Type::NumberBit))
    {
        if (right.IsCustom())
            return NumCompare(*this, right.GetCustom().Call<&CustomVar::Handler::ConvertToCommon>(Type::NumberBit));
        else
            return NumCompare(*this, right);
    }
    else if (IsBool())
    {
        const auto r = right.GetBool();
        if (r.has_value())
            return CompareResultCore::Equality |
                (GetVar<Type::Bool>() == *r ? CompareResultCore::Equal : CompareResultCore::NotEqual);
    }
    return {};
}
static Arg NumArthOp(const EmbedOps op, const Arg& left, const Arg& right) noexcept
{
    // Expects(HAS_FIELD(right.TypeData, Arg::Type::NumberBit | Arg::Type::BoolBit));
    if (!HAS_FIELD(right.TypeData, Arg::Type::NumberBit | Arg::Type::BoolBit))
        return {};
    if (const bool isLeftFP = HAS_FIELD(left.TypeData, Arg::Type::FPBit), isRightFP = HAS_FIELD(right.TypeData, Arg::Type::FPBit);
        isLeftFP || isRightFP)
    {
        const auto l = left.GetFP().value(), r = right.GetFP().value();
        switch (op)
        {
        case EmbedOps::Add: return l + r;
        case EmbedOps::Sub: return l - r;
        case EmbedOps::Mul: return l * r;
        case EmbedOps::Div: return l / r;
        case EmbedOps::Rem: return std::fmod(l, r);
        default:            return {};
        }
    }
    if (const bool isLeftUnsigned = HAS_FIELD(left.TypeData, Arg::Type::UnsignedBit),
        isRightUnsigned = HAS_FIELD(right.TypeData, Arg::Type::UnsignedBit); isLeftUnsigned || isRightUnsigned)
    {
        const auto l = left.GetUint().value(), r = right.GetUint().value();
        switch (op)
        {
        case EmbedOps::Add: return l + r;
        case EmbedOps::Sub: return l - r;
        case EmbedOps::Mul: return l * r;
        case EmbedOps::Div: return l / r;
        case EmbedOps::Rem: return l % r;
        default:            return {};
        }
    }
    {
        const auto l = left.GetInt().value(), r = right.GetInt().value();
        switch (op)
        {
        case EmbedOps::Add: return l + r;
        case EmbedOps::Sub: return l - r;
        case EmbedOps::Mul: return l * r;
        case EmbedOps::Div: return l / r;
        case EmbedOps::Rem: return l % r;
        default:            return {};
        }
    }
}

Arg Arg::HandleUnary(const EmbedOps op) const
{
    Expects(op == EmbedOps::Not || op == EmbedOps::BitNot);
    if (op == EmbedOps::Not)
    {
        const auto val = GetBool();
        if (val.has_value())
            return !val.value();
    }
    else if (op == EmbedOps::BitNot)
    {
        if (MATCH_FIELD(TypeData, Type::Integer)) // only accept integer
            return ~GetVar<Type::Uint, false>();
    }
    return {};
}
Arg Arg::HandleBinary(const EmbedOps op, const Arg& right) const
{
    const auto opCat = EmbedOpHelper::GetCategory(op);
    Expects(opCat != EmbedOpHelper::OpCategory::Other); // should not be handled here
    switch (opCat)
    {
    case EmbedOpHelper::OpCategory::Logic: // should not enter in most cases
    {
        const auto l_ = GetBool();
        if (!l_.has_value())
            return {};
        const auto r_ = right.GetBool();
        if (!r_.has_value())
            return {};
        return op == EmbedOps::And ? (*l_ && *r_) : (*l_ || *r_);
    }
    case EmbedOpHelper::OpCategory::Compare:
    {
        const auto ret1 = Compare(right);
        const auto val1 = ret1.GetResult();
        using CR = CompareResultCore;
        switch (op)
        {
        case EmbedOps::Equal:           if (ret1.HasEuqality())  return val1 == CR::Equal;
            break;
        case EmbedOps::NotEqual:        if (ret1.HasEuqality())  return val1 != CR::Equal;
            break;
        case EmbedOps::Less:            if (ret1.HasOrderable()) return val1 == CR::Less;
            break;
        case EmbedOps::LessEqual:       if (ret1.HasOrderable()) return val1 == CR::Less || val1 == CR::Equal;
            break;
        case EmbedOps::Greater:         if (ret1.HasOrderable()) return val1 == CR::Greater;
            break;
        case EmbedOps::GreaterEqual:    if (ret1.HasOrderable()) return val1 == CR::Greater || val1 == CR::Equal;
            break;
        default: return {}; // should not happen
        }
        // try reverse compare
        const auto ret2 = right.Compare(*this);
        const auto val2 = ret2.GetResult();
        switch (op)
        {
        case EmbedOps::Equal:           if (ret2.HasEuqality())  return val2 == CR::Equal;
            break;
        case EmbedOps::NotEqual:        if (ret2.HasEuqality())  return val2 != CR::Equal;
            break;
        case EmbedOps::Less:            if (ret1.HasReverseOrderable()) return val2 == CR::Greater || val2 == CR::Equal;
            break;
        case EmbedOps::LessEqual:       if (ret1.HasReverseOrderable()) return val2 == CR::Greater;
            break;
        case EmbedOps::Greater:         if (ret1.HasReverseOrderable()) return val2 == CR::Less || val2 == CR::Equal;
            break;
        case EmbedOps::GreaterEqual:    if (ret1.HasReverseOrderable()) return val2 == CR::Less;
            break;
        default: return {}; // should not happen
        }
        return {};
    }
    case EmbedOpHelper::OpCategory::Bitwise:
    {
        if (!MATCH_FIELD(TypeData, Type::Integer) || !MATCH_FIELD(right.TypeData, Type::Integer)) // only accept integer
            return {};
        const auto l = GetVar<Type::Uint, false>(), r = right.GetVar<Type::Uint, false>();
        switch (op)
        {
        case EmbedOps::BitAnd:  return l & r;
        case EmbedOps::BitOr:   return l | r;
        case EmbedOps::BitXor:  return l ^ r;
        case EmbedOps::BitShiftLeft:    return HAS_FIELD(TypeData, Type::UnsignedBit) ? Arg(l << r) : Arg(static_cast<int64_t>(l) << r);
        case EmbedOps::BitShiftRight:   return HAS_FIELD(TypeData, Type::UnsignedBit) ? Arg(l >> r) : Arg(static_cast<int64_t>(l) >> r);
        default:                return {}; // should not happen
        }
    }
    default:
        Expects(opCat == EmbedOpHelper::OpCategory::Arth);
        if (HAS_FIELD(TypeData, Type::StringBit)) // direct process string
        {
            if (op == EmbedOps::Add) // only support add
            {
                const auto r_ = right.GetStr();
                if (r_.has_value())
                {
                    const auto l = GetVar<Type::U32Sv, false>(), r = r_.value();
                    std::u32string ret;
                    ret.reserve(l.size() + r.size());
                    ret.append(l).append(r);
                    return ret;
                }
            }
            return {};
        }
        if (HAS_FIELD(TypeData, Type::NumberBit)) // process as number
        {
            if (right.IsCustom())
                return NumArthOp(op, *this, right.GetCustom().Call<&CustomVar::Handler::ConvertToCommon>(Type::NumberBit));
            else
                return NumArthOp(op, *this, right);
        }
        else if (TypeData == Type::Bool) // consider right can be number
        {
            if (right.IsCustom())
                return NumArthOp(op, *this, right.GetCustom().Call<&CustomVar::Handler::ConvertToCommon>(Type::NumberBit));
            if (HAS_FIELD(TypeData, Type::NumberBit))
                return NumArthOp(op, *this, right);
        }
        return {};
    }
}

bool Arg::HandleBinaryOnSelf(const EmbedOps op, const Arg& right)
{
    if (IsCustom())
    {
        auto& var = GetCustom();
        return var.Call<&CustomVar::Handler::HandleBinaryOnSelf>(op, right);
    }
    return false; // for native type, always use HandleBinary + Assign
}

Arg Arg::HandleSubFields(SubQuery<const Expr>& subfields)
{
    Expects(subfields.Size() > 0);
    if (IsCustom())
    {
        return GetCustom().Call<&CustomVar::Handler::HandleSubFields>(subfields);
    }
    const auto field = subfields[0].GetVar<Expr::Type::Str>();
    if (IsArray())
    {
        const auto arr = GetVar<Type::Array>();
        if (field == U"Length"sv)
        {
            subfields.Consume();
            return static_cast<uint64_t>(arr.Length);
        }
        return {};
    }
    if (IsStr())
    {
        const auto str = GetStr().value();
        if (field == U"Length"sv)
        {
            subfields.Consume();
            return uint64_t(str.size());
        }
        return {};
    }
    return {};
}
Arg Arg::HandleIndexes(SubQuery<Arg>& indexes)
{
    Expects(indexes.Size() > 0);
    if (IsCustom())
    {
        return GetCustom().Call<&CustomVar::Handler::HandleIndexes>(indexes);
    }
    const auto& idxval = indexes[0];
    if (IsArray())
    {
        const auto arr = GetVar<Type::Array>();
        const auto idx = NailangHelper::BiDirIndexCheck(arr.Length, idxval, &indexes.GetRaw(0));
        indexes.Consume();
        return arr.Access(idx);
    }
    if (IsStr())
    {
        const auto str = GetStr().value();
        const auto idx = NailangHelper::BiDirIndexCheck(str.size(), idxval, &indexes.GetRaw(0));
        indexes.Consume();
        if (TypeData == Type::U32Str)
            return std::u32string(1, str[idx]);
        else // (TypeData == Type::U32Sv)
            return str.substr(idx, 1);
    }
    return {};
}

std::u32string_view CustomVar::Handler::GetTypeName(const CustomVar&) noexcept
{
    return U"CustomVar"sv;
}
void CustomVar::Handler::IncreaseRef(const CustomVar&) noexcept { }
void CustomVar::Handler::DecreaseRef(CustomVar&) noexcept { }
Arg::Type CustomVar::Handler::QueryConvertSupport(const CustomVar&) noexcept
{
    return Arg::Type::Empty;
}
Arg CustomVar::Handler::IndexerGetter(const CustomVar&, const Arg&, const Expr&)
{
    return {};
}
Arg CustomVar::Handler::SubfieldGetter(const CustomVar&, std::u32string_view)
{
    return {};
}
Arg CustomVar::Handler::HandleSubFields(const CustomVar& var, SubQuery<const Expr>& subfields)
{
    Expects(subfields.Size() > 0);
    auto result = SubfieldGetter(var, subfields[0].GetVar<Expr::Type::Str>());
    if (!result.IsEmpty())
    {
        subfields.Consume();
        return result;
    }
    return {};
}
Arg CustomVar::Handler::HandleIndexes(const CustomVar& var, SubQuery<Arg>& indexes)
{
    Expects(indexes.Size() > 0);
    auto result = IndexerGetter(var, indexes[0], indexes.GetRaw(0));
    if (!result.IsEmpty())
    {
        indexes.Consume();
        return result;
    }
    return {};
}
bool CustomVar::Handler::HandleBinaryOnSelf(CustomVar&, const EmbedOps, const Arg&)
{
    return false;
}
bool CustomVar::Handler::HandleAssign(CustomVar&, Arg)
{
    return false;
}
CompareResult CustomVar::Handler::CompareSameClass(const CustomVar&, const CustomVar&)
{
    return { };
}
CompareResult CustomVar::Handler::Compare(const CustomVar& var, const Arg& other)
{
    if (other.IsCustom())
    {
        if (const auto& rhs = other.GetCustom(); rhs.Host == var.Host)
            return CompareSameClass(var, rhs);
    }
    return { };
}
common::str::StrVariant<char32_t> CustomVar::Handler::ToString(const CustomVar& var) noexcept
{
    return GetTypeName(var);
}
Arg CustomVar::Handler::ConvertToCommon(const CustomVar&, Arg::Type) noexcept
{
    return {};
}

void Serializer::Stringify(std::u32string& output, const Expr& arg, const bool requestParenthese)
{
    arg.Visit([&](const auto& data)
        {
            using T = std::decay_t<decltype(data)>;
            if constexpr (std::is_same_v<T, std::nullopt_t>)
                Expects(false);
            else if constexpr (std::is_same_v<T, const BinaryExpr*>)
                Stringify(output, data, requestParenthese);
            else if constexpr (std::is_same_v<T, const TernaryExpr*>)
                Stringify(output, data, requestParenthese);
            else
                Stringify(output, data);
        });
}

void Serializer::Stringify(std::u32string& output, const FuncCall* call)
{
    output.append(call->FullFuncName()).push_back(U'(');
    size_t i = 0;
    for (const auto& arg : call->Args)
    {
        if (i++ > 0)
            output.append(U", "sv);
        Stringify(output, arg);
    }
    output.push_back(U')');
}

void Serializer::Stringify(std::u32string& output, const UnaryExpr* expr)
{
    Expects(EmbedOpHelper::IsUnaryOp(expr->Operator));
    switch (expr->Operator)
    {
    case EmbedOps::BitNot:
        output.append(U"~"sv);
        Stringify(output, expr->Operand, true);
        break;
    case EmbedOps::Not:
        output.append(U"!"sv);
        Stringify(output, expr->Operand, true);
        break;
    case EmbedOps::CheckExist:
        output.append(U"?"sv);
        Stringify(output, expr->Operand, true);
        break;
    default:
        Expects(false);
        break;
    }
}

void Serializer::Stringify(std::u32string& output, const BinaryExpr* expr, const bool requestParenthese)
{
    Expects(!EmbedOpHelper::IsUnaryOp(expr->Operator));
    std::u32string_view opStr;
#define SET_OP_STR(op, str) case EmbedOps::op: opStr = U##str##sv; break;
    switch (expr->Operator)
    {
        SET_OP_STR(Equal,           " == ");
        SET_OP_STR(NotEqual,        " != ");
        SET_OP_STR(Less,            " < ");
        SET_OP_STR(LessEqual,       " <= ");
        SET_OP_STR(Greater,         " > ");
        SET_OP_STR(GreaterEqual,    " >= ");
        SET_OP_STR(And,             " && ");
        SET_OP_STR(Or,              " || ");
        SET_OP_STR(Add,             " + ");
        SET_OP_STR(Sub,             " - ");
        SET_OP_STR(Mul,             " * ");
        SET_OP_STR(Div,             " / ");
        SET_OP_STR(Rem,             " % ");
        SET_OP_STR(BitAnd,          " & ");
        SET_OP_STR(BitOr,           " | ");
        SET_OP_STR(BitXor,          " ^ ");
        SET_OP_STR(BitShiftLeft,    " << ");
        SET_OP_STR(BitShiftRight,   " >> ");
        SET_OP_STR(ValueOr,         " ?? ");
    default:
        assert(false); // Expects(false);
        return;
    }
#undef SET_OP_STR
    if (requestParenthese)
        output.push_back(U'(');
    Stringify(output, expr->LeftOperand, true);
    output.append(opStr);
    Stringify(output, expr->RightOperand, true);
    if (requestParenthese)
        output.push_back(U')');
}

void Serializer::Stringify(std::u32string& output, const TernaryExpr* expr, const bool requestParenthese)
{
    if (requestParenthese)
        output.push_back(U'(');
    Stringify(output, expr->Condition, true);
    output.append(U" ? "sv);
    Stringify(output, expr->LeftOperand, true);
    output.append(U" : "sv);
    Stringify(output, expr->RightOperand, true);
    if (requestParenthese)
        output.push_back(U')');
}

void Serializer::Stringify(std::u32string& output, const QueryExpr* expr)
{
    Stringify(output, expr->Target);
    Stringify(output, expr->GetQueries(), expr->TypeData);
}

void Serializer::Stringify(std::u32string& output, const AssignExpr* expr)
{
    Stringify(output, expr->Target);
    output.append(U" = "sv);
    Stringify(output, expr->Statement);
}

void Serializer::Stringify(std::u32string& output, const LateBindVar& var)
{
    if (HAS_FIELD(var.Info, LateBindVar::VarInfo::Root))
        output.push_back(U'`');
    else if (HAS_FIELD(var.Info, LateBindVar::VarInfo::Local))
        output.push_back(U':');
    output.append(var.Name);
}

void Serializer::Stringify(std::u32string& output, const std::u32string_view str)
{
    output.push_back(U'"');
    output.append(str); //TODO:
    output.push_back(U'"');
}

void Serializer::Stringify(std::u32string& output, const uint64_t u64)
{
    ArrayEleFmter.PutInteger(output, u64, false, nullptr);
}

void Serializer::Stringify(std::u32string& output, const int64_t i64)
{
    ArrayEleFmter.PutInteger(output, static_cast<uint64_t>(i64), true, nullptr);
}

void Serializer::Stringify(std::u32string& output, const double f64)
{
    ArrayEleFmter.PutFloat(output, f64, nullptr);
}

void Serializer::Stringify(std::u32string& output, const bool boolean)
{
    output.append(boolean ? U"true"sv : U"false"sv);
}

void Serializer::Stringify(std::u32string& output, const common::span<const Expr> queries, QueryExpr::QueryType type)
{
    for (const auto& query : queries)
    {
        if (type == QueryExpr::QueryType::Index)
        {
            output.push_back(U'[');
            Stringify(output, query, false);
            output.push_back(U']');
        }
        else
        {
            output.push_back(U'.');
            output.append(query.GetVar<Expr::Type::Str>());
        }
    }
}

}


text:
AngularJSLab
============
Check out the [demo](http://karolikl.github.io/AngularJSLab/) of AngularJSLab!
This lab contains AngularJS exercises to kick start your AngularJS learning, giving you hands on exercises to work with. The project will be continuously updated with more exercises, so check in now and then when you've finished the lab.

How does it work?
-----------------
Download the code and open the index.html file in a browser. The instructions will take you from there.
Note: In IE you might be asked to allow blocked content. If asked this question, click "Allow".

Feedback or questions?
----------------------
Feel free to contact me on [Twitter](http://www.twitter.com/karolikl).

Did you enjoy this lab?
-----------------------
Help me promote the project, tweet about it using the hashtag #AngularJSLab

License
-------
The MIT license


text:
namespace sql {
  class ErrorDelegate;
}

// The following three factories create the error handlers that we use when
// issuing sqlite commands during normal browser operation.
sql::ErrorDelegate* GetErrorHandlerForThumbnailDb();
sql::ErrorDelegate* GetErrorHandlerForTextDb();
sql::ErrorDelegate* GetErrorHandlerForWebDb();

// Factories for the db integrity tests we run in diagnostic mode.
DiagnosticTest* MakeSqliteWebDbTest();
DiagnosticTest* MakeSqliteCookiesDbTest();
DiagnosticTest* MakeSqliteHistoryDbTest();
DiagnosticTest* MakeSqliteArchivedHistoryDbTest();
DiagnosticTest* MakeSqliteThumbnailsDbTest();
DiagnosticTest* MakeSqliteAppCacheDbTest();
DiagnosticTest* MakeSqliteWebDatabaseTrackerDbTest();

#endif  // CHROME_BROWSER_DIAGNOSTICS_SQLITE_DIAGNOSTICS_H_


text:
namespace System.Buffers.Text
{
    public abstract partial class SymbolTable
    {
        #region Private data

        private readonly byte[][] _symbols;                     // this could be flattened into a single array
        private readonly ParsingTrie.Node[] _parsingTrie;       // prefix tree used for parsing

        #endregion Private data

        #region Constructors

        protected SymbolTable(byte[][] symbols)
        {
            _symbols = symbols;
            _parsingTrie = ParsingTrie.Create(symbols);
        }

        #endregion Constructors

        #region Static instances

        public readonly static SymbolTable InvariantUtf8 = new Utf8InvariantSymbolTable();

        public readonly static SymbolTable InvariantUtf16 = new Utf16InvariantSymbolTable();

        #endregion Static instances

        public bool TryEncode(Symbol symbol, Span<byte> destination, out int bytesWritten)
        {
            byte[] bytes = _symbols[(int)symbol];
            bytesWritten = bytes.Length;
            if (bytesWritten > destination.Length)
            {
                bytesWritten = 0;
                return false;
            }

            if (bytesWritten == 2)
            {
                destination[0] = bytes[0];
                destination[1] = bytes[1];
                return true;
            }

            if (bytesWritten == 1)
            {
                destination[0] = bytes[0];
                return true;
            }

            new Span<byte>(bytes).CopyTo(destination);
            return true;
        }

        public abstract bool TryEncode(byte utf8, Span<byte> destination, out int bytesWritten);

        public abstract bool TryEncode(ReadOnlySpan<byte> utf8, Span<byte> destination, out int bytesConsumed, out int bytesWritten);

        public bool TryParse(ReadOnlySpan<byte> source, out Symbol symbol, out int bytesConsumed)
        {
            int trieIndex = 0;
            int codeUnitIndex = 0;
            bytesConsumed = 0;
            while (true)
            {
                if (_parsingTrie[trieIndex].ValueOrNumChildren == 0)    // if numChildren == 0, we're on a leaf & we've found our value and completed the code unit
                {
                    symbol = (Symbol)_parsingTrie[trieIndex].IndexOrSymbol;  // return the parsed value
                    if (VerifySuffix(source, codeUnitIndex, symbol))
                    {
                        bytesConsumed = _symbols[(int)symbol].Length;
                        return true;
                    }
                    else
                    {
                        symbol = 0;
                        bytesConsumed = 0;
                        return false;
                    }
                }
                else
                {
                    int search = BinarySearch(trieIndex, codeUnitIndex, source[codeUnitIndex]);    // we search the _parsingTrie for the nextByte

                    if (search > 0)   // if we found a node
                    {
                        trieIndex = _parsingTrie[search].IndexOrSymbol;
                        bytesConsumed++;
                        codeUnitIndex++;
                    }
                    else
                    {
                        symbol = 0;
                        bytesConsumed = 0;
                        return false;
                    }
                }
            }
        }

        public abstract bool TryParse(ReadOnlySpan<byte> source, out byte utf8, out int bytesConsumed);

        public abstract bool TryParse(ReadOnlySpan<byte> source, Span<byte> utf8, out int bytesConsumed, out int bytesWritten);

        #region Public UTF-16 to UTF-8 helpers

        public bool TryEncode(ReadOnlySpan<char> source, Span<byte> destination, out int bytesConsumed, out int bytesWritten)
        {
            ReadOnlySpan<byte> srcBytes = source.AsBytes();

            if (this == SymbolTable.InvariantUtf16)
                return TryEncodeUtf16(srcBytes, destination, out bytesConsumed, out bytesWritten);

            const int BufferSize = 256;

            int srcLength = srcBytes.Length;
            if (srcLength <= 0)
            {
                bytesConsumed = bytesWritten = 0;
                return true;
            }

            Span<byte> temp = stackalloc byte[BufferSize];

            bytesWritten = 0;
            bytesConsumed = 0;
            while (srcLength > bytesConsumed)
            {
                if(Encodings.Utf16.ToUtf8(srcBytes, temp, out int consumed, out int written) == OperationStatus.InvalidData)                     goto ExitFailed;

                srcBytes = srcBytes.Slice(consumed);
                bytesConsumed += consumed;

                if (!TryEncode(temp.Slice(0, written), destination, out consumed, out written))
                    goto ExitFailed;

                destination = destination.Slice(written);
                bytesWritten += written;
            }

            return true;

        ExitFailed:
            return false;
        }

        private bool TryEncodeUtf16(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesConsumed, out int bytesWritten)
        {
            // NOTE: There is no validation of this UTF-16 encoding. A caller is expected to do any validation on their own if
            //       they don't trust the data.
            bytesConsumed = source.Length;
            bytesWritten = destination.Length;
            if (bytesConsumed > bytesWritten)
            {
                source = source.Slice(0, bytesWritten);
                bytesConsumed = bytesWritten;
            }
            else
            {
                bytesWritten = bytesConsumed;
            }

            source.CopyTo(destination);
            return true;
        }

        #endregion Public UTF-16 to UTF-8 helpers

        #region Private helpers

        // This binary search implementation returns an int representing either:
        //      - the index of the item searched for (if the value is positive)
        //      - the index of the location where the item should be placed to maintain a sorted list (if the value is negative)
        private int BinarySearch(int nodeIndex, int level, byte value)
        {
            int maxMinLimits = _parsingTrie[nodeIndex].IndexOrSymbol;
            if (maxMinLimits != 0 && value > (uint)maxMinLimits >> 24 && value < (uint)(maxMinLimits << 16) >> 24)
            {
                // See the comments on the struct above for more information about this format
                return (int)(nodeIndex + ((uint)(maxMinLimits << 8) >> 24) + value - ((uint)maxMinLimits >> 24));
            }

            int leftBound = nodeIndex + 1, rightBound = nodeIndex + _parsingTrie[nodeIndex].ValueOrNumChildren;
            int midIndex = 0;
            while (true)
            {
                if (leftBound > rightBound)  // if the search failed
                {
                    // this loop is necessary because binary search takes the floor
                    // of the middle, which means it can give incorrect indices for insertion.
                    // we should never iterate up more than two indices.
                    while (midIndex < nodeIndex + _parsingTrie[nodeIndex].ValueOrNumChildren
                        && _parsingTrie[midIndex].ValueOrNumChildren < value)
                    {
                        midIndex++;
                    }
                    return -midIndex;
                }

                midIndex = (leftBound + rightBound) / 2; // find the middle value

                byte mValue = _parsingTrie[midIndex].ValueOrNumChildren;

                if (mValue < value)
                    leftBound = midIndex + 1;
                else if (mValue > value)
                    rightBound = midIndex - 1;
                else
                    return midIndex;
            }
        }

        private bool VerifySuffix(ReadOnlySpan<byte> buffer, int codeUnitIndex, Symbol symbol)
        {
            int codeUnitLength = _symbols[(int)symbol].Length;
            if (codeUnitIndex == codeUnitLength - 1)
                return true;

            for (int i = 0; i < codeUnitLength - codeUnitIndex; i++)
            {
                if (buffer[i + codeUnitIndex] != _symbols[(int)symbol][i + codeUnitIndex])
                    return false;
            }

            return true;
        }

        #endregion Private helpers
    }
}


text:
package sn.topo;

import backtype.storm.LocalCluster;
import backtype.storm.LocalDRPC;

/**
 *
 * Created by sumanthn on 2/4/14.
 */
public abstract  class AbstractTopology {

    protected String topologyName;
    protected LocalCluster localCluster;
    protected LocalDRPC localDRPC;

    protected void shutdown(){
        if (localCluster!=null)
            localCluster.shutdown();

        if (localDRPC!=null)
            localDRPC.shutdown();
    }

}


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe "Janitor" do
  describe " #count" do
    it "should call number_of_matches on Finder with the given path" do
      path    = "a_path"
      pattern = "a_pattern"
      mock_finder(pattern, path)
      Janitor.count(pattern, path)
    end

    it "should return the value returned by the call to number_of_matches" do
      path    = "a_path"
      pattern = "a_pattern"
      mock_finder(pattern, path, :number_of_matches => 1)
      Janitor.count(pattern, path).should == 1
    end
  end

  describe " #hits" do
    it "should call #hits on Finder and return the result" do
      path    = "a_path"
      pattern = "a_pattern"
      hits    = ['result']
      mock_finder(pattern, path, :hits => hits)
      Janitor.hits(pattern, path).should == hits
    end
  end

  describe " integration testing" do
    it " should find debugger once in 'tmp/'" do
      Janitor.count('console\.log', 'tmp/').should == 3
    end
  end

  def mock_finder(pattern, path, *args)
    options = args.first ? args.first : {}
    options = {:number_of_matches => 0}.merge options
    options = {:hits              => 0}.merge options
    finder = mock('finder',
      :number_of_matches => options[:number_of_matches],
      :hits              => options[:hits])
    Finder.should_receive(:new).and_return(finder)
  end
end


text:
/**
 * Created by liu on 16/9/19.
 */

fetchName = function (name) {
    return "call back--"+name;
};
demo = function () {
   // alert("customize js call back");
};
pClick = function (index) {
    alert(index);
};
(function () {
    var pList = document.getElementsByTagName("p");
    for (var i=0 ; i<pList.length;i++){
        pList[i].onclick = function () {
            alert("className="+this.className);
        }
    }
}());


text:
#include "mitkIShaderRepository.h"

#include "usGetModuleContext.h"
#include "usModuleContext.h"
#include "usServiceReference.h"

#include "mitkTestingMacros.h"

#include <sstream>

int mitkShaderRepositoryTest(int /*argc*/, char * /*argv*/ [])
{
  MITK_TEST_BEGIN("ShaderRepository")

  us::ModuleContext *context = us::GetModuleContext();
  us::ServiceReference<mitk::IShaderRepository> serviceRef = context->GetServiceReference<mitk::IShaderRepository>();
  MITK_TEST_CONDITION_REQUIRED(serviceRef, "IShaderRepository service ref")

  mitk::IShaderRepository *shaderRepo = context->GetService(serviceRef);
  MITK_TEST_CONDITION_REQUIRED(shaderRepo, "Check non-empty IShaderRepositry")

  mitk::IShaderRepository::Shader::Pointer shader = shaderRepo->GetShader("mitkShaderLighting");
  MITK_TEST_CONDITION_REQUIRED(shader.IsNotNull(), "Non-null mitkShaderLighting shader")

  MITK_TEST_CONDITION(shader->GetName() == "mitkShaderLighting", "Shader name")
  MITK_TEST_CONDITION(!shader->GetMaterialXml().empty(), "Shader content")

  const std::string testShader =
    "<Material name=\"SmoothPlastic\" number_of_properties=\"1\" number_of_vertex_shaders=\"0\" "
    "number_of_fragment_shaders=\"0\">"
    "<Property name=\"ShinyProperty\">"
    "<Member name=\"DiffuseColor\" number_of_elements=\"3\" type=\"Double\" value=\"1.0 0.0 0.0\"/>"
    "</Property>"
    "</Material>";

  const std::size_t shaderCount = shaderRepo->GetShaders().size();

  std::stringstream testShaderStream(testShader);
  const std::string testShaderName = "SmoothPlastic";
  int id = shaderRepo->LoadShader(testShaderStream, testShaderName);
  MITK_TEST_CONDITION_REQUIRED(id > -1, "New shader id")
  MITK_TEST_CONDITION(shaderRepo->GetShaders().size() == shaderCount + 1, "Shader count")
  mitk::IShaderRepository::Shader::Pointer shader2 = shaderRepo->GetShader(testShaderName);
  MITK_TEST_CONDITION_REQUIRED(shader2.IsNotNull(), "Non-null shader")
  MITK_TEST_CONDITION(shader2->GetId() == id, "Shader id")
  MITK_TEST_CONDITION(shader2->GetName() == testShaderName, "Shader name")
  mitk::IShaderRepository::Shader::Pointer shader3 = shaderRepo->GetShader(id);
  MITK_TEST_CONDITION_REQUIRED(shader3.IsNotNull(), "Non-null shader")
  MITK_TEST_CONDITION(shader3->GetId() == id, "Shader id")
  MITK_TEST_CONDITION(shader3->GetName() == testShaderName, "Shader name")

  MITK_TEST_CONDITION_REQUIRED(shaderRepo->UnloadShader(id), "Unload shader")
  MITK_TEST_CONDITION(shaderRepo->GetShader(testShaderName).IsNull(), "Null shader")
  MITK_TEST_CONDITION(shaderRepo->GetShader(id).IsNull(), "Null shader")

  MITK_TEST_END()
}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import 'animate.css/animate.min.css';
import sleep from 'ringcentral-integration/lib/sleep';

import Message from '../Message';
import AlertDisplay from '../AlertDisplay';

const ANIMATION_DURATION = 500;
const ENTRANCE_ANIMATION = 'fadeInDown';
const EXIT_ANIMATION = 'fadeOutUp';

function AnimationMessage({ animation, duration, ...props }) {
  const second = duration / 1000;
  return (
    <div
      className={classnames([animation, 'animated'])}
      style={{
        animationDuration: `${second}s`
      }}>
      <Message {...props} />
    </div>
  );
}

AnimationMessage.propTypes = {
  ...Message.propTypes,
  animation: PropTypes.string,
  duration: PropTypes.number,
};
AnimationMessage.defaultProps = {
  animation: undefined,
  duration: ANIMATION_DURATION,
};

class AnimationAlert extends Component {
  constructor(props) {
    super(props);
    this.state = {
      messages: this.props.messages,
    };
  }
  componentDidMount() {
    this.mounted = true;
  }
  componentWillUnmount() {
    this.mounted = false;
  }
  componentWillReceiveProps(nextProps) {
    if (this.props.messages === nextProps.messages) return;
    (async () => {
      const {
        duration,
        entranceAnimation,
        exitAnimation,
      } = this.props;
      const currentMessagesIDs = this.props.messages.map(message => message.id);
      const nextMessagesIDs = nextProps.messages.map(message => message.id);
      const addedMessagesIDs = nextMessagesIDs.filter(id => !currentMessagesIDs.includes(id));
      const removedMessagesIDs = currentMessagesIDs.filter(id => !nextMessagesIDs.includes(id));
      const allMessagesIDs = [...new Set(currentMessagesIDs.concat(nextMessagesIDs))];
      const allMessages = {};
      this.props.messages.concat(nextProps.messages).map((message) => {
        allMessages[message.id] = message;
        return message;
      });
      const messages = allMessagesIDs
        .map((id) => {
          const message = allMessages[id];
          const isAddedMessage = addedMessagesIDs.includes(id);
          const isRemovedMessage = removedMessagesIDs.includes(id);
          let animation;
          if (isAddedMessage) {
            animation = entranceAnimation;
          } else if (isRemovedMessage) {
            animation = exitAnimation;
          }
          return {
            ...message,
            ...animation ? { animation } : {},
            duration,
          };
        });
      const stateWithAnimation = {
        messages,
      };
      if (messages.length > 0) {
        this.setState(stateWithAnimation);
      }
      await sleep(duration);
      if (!this.mounted) return;
      const isCurrentEmpty = currentMessagesIDs.length === 0;
      this.setState({
        messages: isCurrentEmpty ? messages : nextProps.messages,
      });
    })();
  }

  shouldComponentUpdate(nextProps, nextState) {
    return !(
      nextState.messages === this.state.messages || nextProps.messages === this.state.props
    );
  }

  render() {
    return (
      <AlertDisplay {...this.props} component={AnimationMessage} messages={this.state.messages} />
    );
  }
}

AnimationAlert.propTypes = {
  ...AlertDisplay.propTypes,
  entranceAnimation: PropTypes.string,
  exitAnimation: PropTypes.string,
  duration: PropTypes.number,
};

AnimationAlert.defaultProps = {
  ...AlertDisplay.defaultProps,
  entranceAnimation: ENTRANCE_ANIMATION,
  exitAnimation: EXIT_ANIMATION,
  duration: ANIMATION_DURATION,
};

export default AnimationAlert;


text:
/* :nodoc: */
#include "ruby_prof.h"
#if HAVE_GETTIMEOFDAY && !defined(_WIN32)
#include <sys/time.h>
#endif

static VALUE cMeasureWallTime;

static double
measure_wall_time()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec + (tv.tv_usec/1000000.0);
}

prof_measurer_t* prof_measurer_wall_time()
{
  prof_measurer_t* measure = ALLOC(prof_measurer_t);
  measure->measure = measure_wall_time;
  return measure;
}

/* Document-method: prof_measure_wall_time
   call-seq:
     measure_wall_time -> float

Returns the wall time.*/
static VALUE
prof_measure_wall_time(VALUE self)
{
    return rb_float_new(measure_wall_time());
}

void rp_init_measure_wall_time()
{
    rb_define_const(mProf, "WALL_TIME", INT2NUM(MEASURE_WALL_TIME));
    rb_define_const(mProf, "WALL_TIME_ENABLED", Qtrue);

    cMeasureWallTime = rb_define_class_under(mMeasure, "WallTime", rb_cObject);
    rb_define_singleton_method(cMeasureWallTime, "measure", prof_measure_wall_time, 0);
}


text:
var Guest = require('../models/guest')

module.exports.saveGuest = function(req, res, next) {
    console.log(req.ipGeo);
    Guest.findOne({'ip': req.ipGeo.ip}, function(err, guest){
        if(err)return err;
        if (guest) {
            //console.log("estaba");
        }else {
            console.log('new guest');
            var newGuest = new Guest();
            newGuest.geo=req.ipGeo.geo;
            newGuest.ip=req.ipGeo.ip;
            newGuest.save();
        }
    });
    next();
}

module.exports.alreadyLogged=function(req, res, next) {
    if (req.user) return res.redirect('/chat');
    next();
}

module.exports.noAlreadyLogged=function(req, res, next) {
    if (!req.user) return res.redirect('/login');
    next();
}

//middleware to get ip in request
var requestIp = require('request-ip');
var geoip = require('geoip-lite');
module.exports.ipMiddleware = function(req, res, next) {
    const clientIp = requestIp.getClientIp(req);
    var geo = geoip.lookup(clientIp);
    req.ipGeo={geo:geo,ip:clientIp};
    next();
};

/*
this middleware add  following information about geolocation in request
(example)
{
    geo:
        {
            range: [ 3200196608, 3200200703 ],
            country: 'AR',
            region: '05',
            city: 'Rio Cuarto',
            ll: [ -32.8417, -64.3 ],
            metro: 0,
            zip: 5800
        },
    ip: '190.191.45.133'
}

*/


text:
package org.metaborg.lang.pcf.interpreter.natives;

import org.metaborg.meta.lang.dynsem.interpreter.nodes.building.TermBuild;

import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.source.SourceSection;

@NodeChild(value = "print", type = TermBuild.class)
public abstract class printStringI_1 extends TermBuild {

      public printStringI_1(SourceSection source) {
              super(source);
      }

      @Specialization
      public Object doInt(Object s) {
        System.out.println(s);
        return s;
      }

      public static TermBuild create(SourceSection source, TermBuild print) {
              return printStringI_1NodeGen.create(source, print);
      }

}


text:
classdef LayerNoising < LayerBase
    % the non-linearity in a network y_i = f(x_i)
    properties
        actfunc
        gradfunc
        state
        droprate

        testing
        fixedmask
    end

    methods
        function L = LayerNoising(droprate)
            L.name = ['Noising'];
            L.droprate = droprate;
            L.params = [];
            L.testing = 0;
        end

        function output=forward(self, input)
            self.input = input;
            if ~self.testing
                if self.fixedmask
                    rng(1)
                end
                self.state = 1*(rand(size(input))>self.droprate);
                self.output = self.state.*input;
            else
                self.output = (1-self.droprate)*input;
            end
            output=self.output;
        end

        function dLdin = backward(self, dfdo)
            dLdin = dfdo .* self.state;
            self.grad = [];
        end
    end

end


text:
//
//  SCSession.h
//  SCAudioVideoRecorder
//
//  Created by Simon CORSIN on 27/03/14.
//  Copyright (c) 2014 rFlex. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#import "SCRecordSessionSegment.h"

#define kRecordSessionDefaultVideoCodec AVVideoCodecH264
#define kRecordSessionDefaultVideoScalingMode AVVideoScalingModeResizeAspectFill
#define kRecordSessionDefaultOutputBitPerPixel 12
#define kRecordSessionDefaultAudioBitrate 128000
#define kRecordSessionDefaultAudioFormat kAudioFormatMPEG4AAC

extern NSString * const SCRecordSessionSegmentFilenamesKey;
extern NSString * const SCRecordSessionDurationKey;
extern NSString * const SCRecordSessionIdentifierKey;
extern NSString * const SCRecordSessionDateKey;
extern NSString * const SCRecordSessionDirectoryKey;

extern NSString * const SCRecordSessionTemporaryDirectory;
extern NSString * const SCRecordSessionCacheDirectory;
extern NSString * const SCRecordSessionDocumentDirectory;

@class SCRecordSession;
@class SCRecorder;

@interface SCRecordSession : NSObject

//////////////////
// GENERAL SETTINGS
////

/**
 An unique identifier generated when creating this record session.
 */
@property (readonly, nonatomic) NSString *identifier;

/**
 The date when this record session was created.
 */
@property (readonly, nonatomic) NSDate *date;

/**
 The directory to which the record segments will be saved.
 Can be either SCRecordSessionTemporaryDirectory or an arbritary directory.
 Default is SCRecordSessionTemporaryDirectory.
 */
@property (copy, nonatomic) NSString *segmentsDirectory;

/**
 The output file type used for the AVAssetWriter.
 If null, AVFileTypeMPEG4 will be used for a video file, AVFileTypeAppleM4A for an audio file
 */
@property (copy, nonatomic) NSString *fileType;

/**
 The extension of every record segments.
 If null, the SCRecordSession will figure out one depending on the fileType.
 */
@property (copy, nonatomic) NSString *fileExtension;

/**
 The output url based on the identifier, the recordSegmentsDirectory and the fileExtension
 */
@property (readonly, nonatomic) NSURL *outputUrl;

/**
 Contains every record segment as SCRecordSessionSegment.
 */
@property (readonly, nonatomic) NSArray *segments;

/**
 The duration of the whole recordSession including the current recording segment
 and the previously added record segments.
 */
@property (readonly, nonatomic) CMTime duration;

/**
 The duration of the recorded record segments.
 */
@property (readonly, atomic) CMTime segmentsDuration;

/**
 The duration of the current recording segment.
 */
@property (readonly, atomic) CMTime currentSegmentDuration;

/**
 True if a recordSegment has began
 */
@property (readonly, nonatomic) BOOL recordSegmentBegan;

/**
 The recorder that is managing this SCRecordSession
 */
@property (readonly, nonatomic, weak) SCRecorder *recorder;

//////////////////
// PUBLIC METHODS
////

- (instancetype)init;

- (instancetype)initWithDictionaryRepresentation:(NSDictionary *)dictionaryRepresentation;

/**
 Create a SCRecordSession
 */
+ (instancetype)recordSession;

/**
 Create a SCRecordSession based on dictionary representation
 */
+ (instancetype)recordSession:(NSDictionary *)dictionaryRepresentation;

/**
 Calling any method of SCRecordSession is thread safe. However,
 if the record session is inside an SCRecorder instance, its state
 might change between 2 calls you are making. Making any modification
 within this block will ensure that you are the only one who has
 access to any modification on this SCRecordSession.
 */
- (void)dispatchSyncOnSessionQueue:(void(^)())block;

//////////////////////
/////// SEGMENTS
////

/**
 Remove the record segment. Does not delete the associated file.
 */
- (void)removeSegment:(SCRecordSessionSegment *)segment;

/**
 Remove the record segment at the given index.
 */
- (void)removeSegmentAtIndex:(NSInteger)segmentIndex deleteFile:(BOOL)deleteFile;

/**
 Add a recorded segment.
 */
- (void)addSegment:(SCRecordSessionSegment *)segment;

/**
 Insert a record segment.
 */
- (void)insertSegment:(SCRecordSessionSegment *)segment atIndex:(NSInteger)segmentIndex;

/**
 Remove all the record segments and their associated files.
 */
- (void)removeAllSegments;

/**
 Remove all the record segments and their associated files if deleteFiles is true.
 */
- (void)removeAllSegments:(BOOL)deleteFiles;

/**
 Remove the last segment safely. Does nothing if no segment were recorded.
 */
- (void)removeLastSegment;

/**
 Cancel the session.
 End the current recordSegment (if any) and call removeAllSegments
 If you don't want a segment to be automatically added when calling this method,
 you should remove the SCRecordSession from the SCRecorder
 */
- (void)cancelSession:(void(^)())completionHandler;

/**
 Merge the recorded record segments using the given AVAssetExportSessionPreset.
 */
- (void)mergeSegmentsUsingPreset:(NSString *)exportSessionPreset completionHandler:(void(^)(NSURL *outputUrl, NSError *error))completionHandler;

/**
 Returns an asset representing all the record segments
 from this record session. This can be called anytime.
 */
- (AVAsset *)assetRepresentingSegments;

/**
 Append all the record segments to a given AVMutableComposition.
 */
- (void)appendSegmentsToComposition:(AVMutableComposition *)composition;

/**
 Returns a dictionary that represents this SCRecordSession
 This will only contains strings and can be therefore safely serialized
 in any text format
 */
- (NSDictionary *)dictionaryRepresentation;

/**
 Returns a record segment URL for a filename and a directory.
 */
+ (NSURL *)segmentURLForFilename:(NSString *)filename andDirectory:(NSString *)directory;

/**
 Stop the current segment and deinitialize the video and the audio.
 This can be usefull if the input video or audio profile changed.
 */
- (void)deinitialize;

/**
 Start a new record segment.
 This method is automatically called by the SCRecorder.
 */
- (void)beginSegment:(NSError**)error;

/**
 End the current record segment.
 This method is automatically called by the SCRecorder
 when calling [SCRecorder pause] if necessary.
 segmentIndex contains the index of the segment recorded accessible
 in the recordSegments array. If error is not null, if will be -1
 If you don't remove the SCRecordSession from the SCRecorder while calling this method,
 The SCRecorder might create a new recordSegment right after automatically if it is not paused.
 */
- (BOOL)endSegmentWithInfo:(NSDictionary *)info completionHandler:(void(^)(SCRecordSessionSegment *segment, NSError *error))completionHandler;

@end


text:
@implementation ShoppingCart

+ (instancetype)initWithDictionary:(NSDictionary *)dictionary {

    ShoppingCart *cart = [[self alloc] init];
    cart.client = dictionary[@"client"];
    cart.count = [dictionary[@"count"] integerValue];
    NSArray *list = dictionary[@"list"];
    NSMutableArray *tempList = [NSMutableArray array];
    for (NSDictionary *dic in list) {
        ShoppingCartGoods *goods = [[ShoppingCartGoods alloc] init];
        [goods setValuesForKeysWithDictionary:dic];
        [tempList addObject:goods];
    }
    cart.list = [tempList copy];
    cart.type = [dictionary[@"type"] integerValue];
    NSArray *users = dictionary[@"users"];
    NSMutableArray *tempUsers = [NSMutableArray array];
    for (NSDictionary *dic in users) {
        ShoppingCartShop *shop = [[ShoppingCartShop alloc] init];
        [shop setValuesForKeysWithDictionary:dic];
        [tempUsers addObject:shop];
    }
    cart.users = [tempUsers copy];

    return cart;

}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    NSLog(@"%@", key);
}

@end


text:
package org.carlspring.commons.io.reloading;

import org.carlspring.commons.io.resource.ResourceCloser;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author mtodorov
 */
public class FSReloadableInputStreamHandler
    implements ReloadableInputStreamHandler
{

    private static final Logger logger = LoggerFactory.getLogger(FSReloadableInputStreamHandler.class);

    private Path filePath;

    private InputStream inputStream;

    public FSReloadableInputStreamHandler(Path filePath)
    {
        this.filePath = filePath;
    }

    @Override
    public InputStream getInputStream()
            throws IOException
    {
        if (inputStream == null)
        {
            loadInputStream();
            return inputStream;
        }
        else
        {
            return inputStream;
        }
    }

    @Override
    public void reload()
            throws IOException
    {
        ResourceCloser.close(inputStream, logger);
        loadInputStream();
    }

    private void loadInputStream()
            throws IOException
    {
        inputStream = Files.newInputStream(filePath);
    }

}


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

package com.google.enterprise.connector.spi;

import java.util.Set;

/**
 * Interface that represents a document. A document is a map of String
 * property names to {@link Property} objects. Map-like functionality is
 * provided through the {@link #findProperty(String)} method. In
 * addition, a method provides the caller with the {@code Set} of all property
 * names, which it can use to iterate over all properties.
 *

 * Important: a {@link Property} object obtained by calling
 * {@link #findProperty(String)} may be invalidated by the next
 * call to {@link #findProperty(String)}.  Typically, the caller will
 * store the current {@code Property} in a loop variable, so that it is
 * clear that this rule is observed; see the example code below.  The
 * caller may request a specific property multiple times with separate calls
 * to {@link #findProperty(String)}.  In such a case, the
 * implementation must return the same set of values associated with that
 * property name.  If the caller requests a property for which the
 * {@code Document} has no value, {@code null} should be returned.
 *

 * The typical pattern for consuming an object that implements this
 * interface is as follows (disregarding exception handling):
 *
 *

 * Document doc = ...
 * Property prop = null;
 * if ((prop = doc.findProperty(specialPropName1)) != null) {
 *   doSomethingSpecial(prop);
 * }
 * if ((prop = doc.findProperty(specialPropName2)) != null) {
 *   doSomethingElseSpecial(prop);
 * }
 * ... so on for other special properties as needed ...
 * for (String propName : doc.getPropertyNames()) {
 *   prop = doc.findProperty(propName);
 *   // assert(prop != null);
 *   doSomething(prop);
 * }
 *

 *
 * @since 1.0
 */
public interface Document {

  /**
   * Finds a {@link Property} by name. If the current document has a property
   * then that property is returned.
   *
   * @param name the name of the {@link Property} to find
   * @return the {@link Property}, if found; {@code null} otherwise
   * @throws RepositoryException if a repository access error occurs
   * @throws RepositoryDocumentException if a document has fatal
   *         processing errors
   */
  public Property findProperty(String name) throws RepositoryException;

  /**
   * Gets the set of names of all {@link Property Properties} in this
   * {@code Document}.
   *
   * @return the names, as a {@code Set} of Strings
   * @throws RepositoryException if a repository access error occurs
   * @throws RepositoryDocumentException if a document has fatal
   *         processing errors
   */
  public Set<String> getPropertyNames() throws RepositoryException;
}


text:
import React from "react";
import KnobbedThemeProvider from "@hig/storybook/storybook-support/decorators/KnobbedThemeProvider";
import DefaultExport from "../index";
import getKnobs from "./getKnobs";

export default function renderStory(props) {
  const { children, theme, ...otherProps } = getKnobs(props);

  return (
    <KnobbedThemeProvider>
      <DefaultExport {...otherProps}>{children}</DefaultExport>
    </KnobbedThemeProvider>
  );
}