text:
<?
class budget_Action
{
    private $_tables;
    private $_totalOut;
    private $_totanIn;

    private $_query;
    private $_row;
    private $_row2;
    private $_row3;
    private $_year;
    private $_value;
    private $_post;
    private $_post2;
    private $_ResultBudgetID;
    private $_LiquidityBudgetID;
    private $_budgetLinesResult;
    private $_budgetLinesLiquidity;
    private $_budgetRow;
    private $_BudgetLineId;

    ############################################

    public function __construct($args)
    {
    }

    ############################################

    public function action_budget_removeLine($args)
    {
        global $_lib;

        $this->_query = "update ".$args['db_table']." set Active=0 where BudgetLinesID=".$args['BudgetLinesID'];
        $this->_row   = $_lib['db']->db_update($this->_query);
    }

    ############################################

    #periodYear'=>$periodYear, 'budgetType'=>$budgetType, 'AccountPlanID'=>$value   'db_table'
    public function action_budget_addLine($args)
    {
        global $_lib;

        $this->_query = "select BudgetID from budget where PeriodYear='".$args['periodYear']."' and Type='".$args['budgetType']."'";
        $this->_row = $_lib['storage']->get_row(array('query' => $this->_query));

        $this->_post2['budgetline_BudgetID'] = $this->_row->BudgetID;
        $this->_post2['budgetline_AccountPlanID'] = $args['AccountPlanID'];
        $this->_BudgetLineId = $_lib['storage']->db_new_hash($this->_post2, $args['db_table']);
    }

    ############################################

    public function action_budget_setActive($args)
    {
        global $_lib;
        $this->_query = "update ".$args['db_table']." set Active=1 where BudgetLinesID=".$args['BudgetLinesID'];
        $this->_row = $_lib['db']->db_update($this->_query);
    }

    ############################################

    #$args['db_table', 'db_table2', '_POST']
    public function action_budget_update($args)
    {
        global $_lib;
        $this->_tables[$args['db_table']] = 'BudgetID';
        $this->_tables[$args['db_table2']] = 'BudgetLinesID';

        for($j=1; $j<=$_POST['numberofrows']; $j++)
        {
            $this->_totalOut = 0;
            $this->_totalIn = 0;

            for($i=1; $i<=12; $i++)
            {
                $tmphash = $_lib['convert']->Amount(array('value'=>$args['_POST']['budgetline_Period'.$i.'Out_'.$args['_POST'][$j]]));
                $this->_totalOut += $tmphash['value'];

                $tmphash = $_lib['convert']->Amount(array('value'=>$args['_POST']['budgetline_Period'.$i.'In_'.$args['_POST'][$j]]));
                $this->_totalIn += $tmphash['value'];
            }

            $args['_POST']['budgetline_SumOut_'.$args['_POST'][$j]] = $this->_totalOut;
            $args['_POST']['budgetline_SumIn_'.$args['_POST'][$j]] = $this->_totalIn;

            unset($args['_POST'][$j]);
        }

        unset($args['_POST']['numberofrows']);

        $_lib['storage']->db_update_multi_table($args['_POST'], $this->_tables);
    }

    ############################################

    #$args['db_table', 'db_table2']
    public function action_budget_new($args)
    {
        global $_lib;

        /*  Getting initial values  */
        if($args['year']) {
            $this->_year = $args['year'];
        } else {
            $this->_query = "select PeriodYear from budget order by PeriodYear desc";
            $this->_row = $_lib['storage']->get_row(array('query' => $this->_query));
            $this->_year = $this->_row->PeriodYear;

            if(!$this->_year)
                $this->_year = $_lib['date']->get_this_year($_lib['sess']->get_session('LoginFormDate'));
            else
                $this->_year++;
        }

        /*  Creating Reusult header  */
        $this->_post['budget_Type'] = 'result';
        $this->_post['budget_PeriodYear'] = $this->_year;
        $this->_ResultBudgetID = $_lib['storage']->db_new_hash($this->_post, $args['db_table']);

        /*  Creating liquidity header  */
        $this->_post['budget_Type'] = 'liquidity';
        $this->_LiquidityBudgetID = $_lib['storage']->db_new_hash($this->_post, $args['db_table']);

        $this->_query = "select AccountPlanID from accountplan where EnableBudgetResult=1";
        $this->_row = $_lib['storage']->get_hash(array('query'=>$this->_query, 'key'=>'AccountPlanID', 'value'=>'AccountPlanID'));

        $this->_query = "select AccountPlanID from accountplan where EnableBudgetLikviditet=1";
        $this->_row2 = $_lib['storage']->get_hash(array('query'=>$this->_query, 'key'=>'AccountPlanID', 'value'=>'AccountPlanID'));

        $this->_year--;

        foreach($this->_row as $this->_value)
        {
            $this->_post2['budgetline_BudgetID'] = $this->_ResultBudgetID;
            $this->_post2['budgetline_AccountPlanID'] = $this->_value;

            for($i=1; $i<=12; $i++)
            {
                $this->_query = "select V.AccountPlanID, sum(V.AmountOut) as sumout, sum(V.AmountIn) as sumin, V.VoucherPeriod from voucher V, accountplan A where A.accountplanID=V.AccountPlanID and A.AccountPlanID='$this->_value' and substring(V.VoucherPeriod,1,4)='$this->_year' and substring(V.VoucherPeriod,6,2)=$i group by V.VoucherPeriod order by V.VoucherPeriod";
                $this->_row3 = $_lib['storage']->get_row(array('query' => $this->_query));

                if(!isset($this->_row3->sumin))
                    $this->_row3->sumin = 0;
                if(!isset($this->_row3->sumout))
                    $this->_row3->sumout = 0;

                $this->_post2['budgetline_Period'.$i.'In'] = $this->_row3->sumin;
                $this->_post2['budgetline_Period'.$i.'Out'] = $this->_row3->sumout;
            }

            $this->_BudgetLineId = $_lib['storage']->db_new_hash($this->_post2, $args['db_table2']);
        }

        foreach($this->_row2 as $this->_value)
        {
            $this->_post2['budgetline_BudgetID'] = $this->_LiquidityBudgetID;
            $this->_post2['budgetline_AccountPlanID'] = $this->_value;

            for($i=1; $i<=12; $i++)
            {
                $this->_query = "select V.AccountPlanID, sum(V.AmountOut) as sumout, sum(V.AmountIn) as sumin, V.VoucherPeriod from voucher V, accountplan A where A.accountplanID=V.AccountPlanID and A.AccountPlanID='$this->_value' and substring(V.VoucherPeriod,1,4)='$this->_year' and substring(V.VoucherPeriod,6,2)=$i group by V.VoucherPeriod order by V.VoucherPeriod";
                $this->_row3 = $_lib['storage']->get_row(array('query' => $this->_query));

                if(!isset($this->_row3->sumin))
                    $this->_row3->sumin = 0;
                if(!isset($this->_row3->sumout))
                    $this->_row3->sumout = 0;

                $this->_post2['budgetline_Period'.$i.'In'] = $this->_row3->sumin;
                $this->_post2['budgetline_Period'.$i.'Out'] = $this->_row3->sumout;
            }

            $this->_BudgetLineId = $_lib['storage']->db_new_hash($this->_post2, $args['db_table2']);
        }
    }
}


text:
#pragma once

#include <inviwo/core/common/inviwocoredefine.h>
#include <inviwo/core/util/stdextensions.h>
#include <inviwo/core/util/logcentral.h>

#include <flags/flags.h>
#include <fmt/format.h>
#include <units/units.hpp>
#include <tcb/span.hpp>

#include <string_view>
#include <tuple>
#include <unordered_map>
#include <optional>
#include <iterator>
#include <vector>
#include <utility>

namespace inviwo {

using Unit = units::precise_unit;

struct IVW_CORE_API Axis {
    std::string name;
    Unit unit;
};

namespace util {

constexpr std::array<std::string_view, 4> defaultAxesNames = {"x", "y", "z", "t"};
constexpr std::array<Unit, 4> defaultAxesUnits = {Unit{}, Unit{}, Unit{}, Unit{}};

template <size_t N>
std::array<Axis, N> defaultAxes() {
    static_assert(N <= defaultAxesNames.size());
    return util::make_array<N>([](auto i) {
        return Axis{std::string{defaultAxesNames[i]}, defaultAxesUnits[i]};
    });
}

}  // namespace util

enum class UnitFlag {
    None = 0,
    UsesPrefix = 1 << 0,
    OnlyPositivePowers = 1 << 1,
    OnlyByItSelf = 1 << 2
};
ALLOW_FLAGS_FOR_ENUM(UnitFlag)
using UnitFlags = flags::flags<UnitFlag>;

struct UnitDesc {
    Unit unit;
    std::string_view name;
    std::string_view abbr;
    UnitFlags flags;
};

namespace unitgroups {

// clang-format off
constexpr std::array<UnitDesc, 10> si = {{
    {units::precise::meter,    "meter",    "m",   UnitFlag::UsesPrefix},
    {units::precise::kg,       "kilogram", "kg",  UnitFlag::None},
    {units::precise::second,   "second",   "s",   UnitFlag::UsesPrefix},
    {units::precise::Ampere,   "ampere",   "A",   UnitFlag::UsesPrefix},
    {units::precise::Kelvin,   "kelvin",   "K",   UnitFlag::UsesPrefix},
    {units::precise::mol,      "mole",     "mol", UnitFlag::UsesPrefix},
    {units::precise::candela,  "candela",  "Cd",  UnitFlag::UsesPrefix},
    {units::precise::currency, "currency", "$",   UnitFlag::UsesPrefix},
    {units::precise::count,    "count",    "#",   UnitFlag::None},
    {units::precise::radian,   "radian",   "rad", UnitFlag::None}
}};

constexpr std::array<UnitDesc, 17> derived = {{
    {units::precise::hertz,     "hertz",     "Hz",  UnitFlag::UsesPrefix |
                                                        UnitFlag::OnlyPositivePowers |
                                                        UnitFlag::OnlyByItSelf},
    {units::precise::volt,      "volt",      "V",   UnitFlag::UsesPrefix},
    {units::precise::newton,    "newton",    "N",   UnitFlag::UsesPrefix},
    {units::precise::Pa,        "pascal",    "Pa",  UnitFlag::UsesPrefix},
    {units::precise::joule,     "joule",     "J",   UnitFlag::UsesPrefix},
    {units::precise::watt,      "watt",      "W",   UnitFlag::UsesPrefix},
    {units::precise::farad,     "farad",     "F",   UnitFlag::UsesPrefix},
    {units::precise::siemens,   "siemens",   "S",   UnitFlag::UsesPrefix},
    {units::precise::weber,     "weber",     "Wb",  UnitFlag::UsesPrefix},
    {units::precise::tesla,     "tesla",     "T",   UnitFlag::UsesPrefix},
    {units::precise::henry,     "henry",     "H",   UnitFlag::UsesPrefix},
    {units::precise::lumen,     "lumen",     "lm",  UnitFlag::UsesPrefix},
    {units::precise::lux,       "lux",       "lx",  UnitFlag::UsesPrefix},
    {units::precise::becquerel, "becquerel", "Bq",  UnitFlag::UsesPrefix},
    {units::precise::gray,      "gray",      "Gy",  UnitFlag::UsesPrefix},
    {units::precise::sievert,   "sievert",   "Sv",  UnitFlag::UsesPrefix},
    {units::precise::katal,     "katal",     "kat", UnitFlag::UsesPrefix}
}};

constexpr std::array<UnitDesc, 3> extra = {{
    {units::precise::bar, "bar",   "bar", UnitFlag::UsesPrefix},
    {units::precise::L,   "liter", "L",   UnitFlag::UsesPrefix},
    {units::precise::g,   "gram",  "g",   UnitFlag::UsesPrefix}
}};

constexpr std::array<UnitDesc, 5> time = {{
    {units::precise::time::min,  "minute", "min",  UnitFlag::None},
    {units::precise::time::h,    "hour",   "h",    UnitFlag::None},
    {units::precise::time::day,  "day",    "day",  UnitFlag::None},
    {units::precise::time::week, "week",   "week", UnitFlag::None},
    {units::precise::time::yr,   "year",   "yr",   UnitFlag::None}
}};

constexpr std::array<UnitDesc, 1> temperature = {{
    {units::precise::temperature::celsius,  "celsius", "°C", UnitFlag::None},
}};

constexpr Unit elementary_charge{1.602176634e-19, units::precise::C};

constexpr std::array<UnitDesc, 4> atomic = {{
    {units::precise::distance::angstrom,  u8"\u00C5ngstr\u00F6m", u8"\u00C5", UnitFlag::None},
    {units::precise::energy::eV,          "electron volt",      "eV",     UnitFlag::UsesPrefix},
    {units::precise::energy::hartree,     "hartree",            "Ha",     UnitFlag::None},
    {elementary_charge,                   "elementary charge",  "e",      UnitFlag::None}
}};

constexpr std::array<UnitDesc, 3> astronomical = {{
    {units::precise::distance::parsec,  "parsec",            "pc", UnitFlag::None},
    {units::precise::distance::au,      "astronomical unit", "au", UnitFlag::None},
    {units::precise::distance::ly,      "light-year",        "ly", UnitFlag::None},
}};

constexpr std::array<UnitDesc, 17> prefixes = {{
    {units::precise::yocto, "yocto", "y", UnitFlag::None},
    {units::precise::zepto, "zepto", "z", UnitFlag::None},
    {units::precise::atto,  "atto",  "a", UnitFlag::None},
    {units::precise::femto, "femto", "f", UnitFlag::None},
    {units::precise::pico,  "pico",  "p", UnitFlag::None},
    {units::precise::nano,  "nano",  "n", UnitFlag::None},
    {units::precise::micro, "micro", u8"\u00B5", UnitFlag::None},
    {units::precise::milli, "milli", "m", UnitFlag::None},
    {units::precise::one,   "",      "",  UnitFlag::None},
    {units::precise::kilo,  "kilo",  "k", UnitFlag::None},
    {units::precise::mega,  "mega",  "M", UnitFlag::None},
    {units::precise::giga,  "giga",  "G", UnitFlag::None},
    {units::precise::tera,  "tera",  "T", UnitFlag::None},
    {units::precise::peta,  "peta",  "P", UnitFlag::None},
    {units::precise::exa,   "exa",   "E", UnitFlag::None},
    {units::precise::zetta, "zetta", "Z", UnitFlag::None},
    {units::precise::yotta, "yotta", "Y", UnitFlag::None},
}};

// clang-format on

struct Group {
    std::string_view name;
    util::span<const UnitDesc> units;
};

constexpr std::array<Group, 7> groups = {{{"SI", si},
                                          {"Derived", derived},
                                          {"Extra", extra},
                                          {"Time", time},
                                          {"Temperature", temperature},
                                          {"Atomic", atomic},
                                          {"Astronomical", astronomical}}};

using EnabledGroups = std::array<bool, groups.size()>;
constexpr EnabledGroups allGroups = {true, true, true, true, true, true, true};
constexpr EnabledGroups siGroups = {true, false, false, false, false, false, false};
constexpr EnabledGroups extGroups = {true, true, true, false, false, false, false};

}  // namespace unitgroups

namespace util {

enum class UseUnitPrefixes { Yes, No };

IVW_CORE_API unitgroups::EnabledGroups getSystemUnitGroups();

IVW_CORE_API std::unordered_map<units::detail::unit_data, std::vector<UnitDesc>> getUnitGroupsFor(
    Unit unit, const unitgroups::EnabledGroups& enabledGroups);

IVW_CORE_API std::pair<double, std::vector<std::tuple<std::string_view, std::string_view, int>>>
findBestSetOfNamedUnits(Unit unit, const unitgroups::EnabledGroups& enabledGroups,
                        UseUnitPrefixes usesPrefixes);

IVW_CORE_API std::back_insert_iterator<fmt::memory_buffer> formatUnitTo(
    std::back_insert_iterator<fmt::memory_buffer> it, Unit unit,
    const unitgroups::EnabledGroups& enabledGroups, UseUnitPrefixes usesPrefixes);

}  // namespace util

}  // namespace inviwo

/**
 * Formatting specialization for Units
 * The Units have a Format Specification Mini-Language
 *
 * spec         ::= [unit_spec][":" format_spec]
 *
 * format_spec ::= fmt standard format specifier
 *
 * unit_spec   ::= [space][braces][prefix][units]
 *
 * space       ::= " "
 * braces      ::= "(" | "["
 * prefix      ::= "p" | "P"
 * units       ::= "si" | "ext" | "sys" | "all"
 *
 * Space:
 *    " "     Add a leading space to the unit
 *
 * Braces:    By default no braces are added.
 *    "("     Surround the unit in (unit)
 *    "["     Surround the unit in [unit]
 *
 * Prefix:
 *    "p"     Use SI prefixes (yocto to Yotta) to reduce any multiplier (default)
 *    "P"     Don't use any prefixes
 *
 * Units:
 *    "si"    Only use the basic SI unit and combination of those.
 *    "ext"   Use unit from the SI, derived and extra groups.
 *    "sys"   Use the systems currently selected set of unit groups (default)
 *    "all"   Use all known unit groups.
 *
 */
template <>
struct fmt::formatter<::inviwo::Unit> {
    formatter<std::string_view> formatter_;

    enum class UnitSystem { SI, Ext, Sys, All };
    enum class Braces { None = 0, Paren, Square };

    ::inviwo::util::UseUnitPrefixes usePrefix = ::inviwo::util::UseUnitPrefixes::Yes;
    UnitSystem unitsystem = UnitSystem::Sys;
    Braces braces = Braces::None;
    bool leadingSpace = false;

    constexpr auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
        auto it = ctx.begin();
        auto end = ctx.end();

        const auto range = std::string_view(it, end - it);
        const auto endPos = range.find_first_of(":}");
        const auto endIt =
            endPos != std::string_view::npos ? it + endPos + (range[endPos] == ':' ? 1 : 0) : end;
        auto unitFormat = range.substr(0, endPos);

        if (unitFormat.size() > 0 && unitFormat[0] == ' ') {
            leadingSpace = true;
            unitFormat.remove_prefix(1);
        }

        if (unitFormat.size() > 0 && unitFormat[0] == '(') {
            braces = Braces::Paren;
            unitFormat.remove_prefix(1);
        } else if (unitFormat.size() > 0 && unitFormat[0] == '[') {
            braces = Braces::Square;
            unitFormat.remove_prefix(1);
        }

        if (unitFormat.size() > 0 && unitFormat[0] == 'p') {
            usePrefix = ::inviwo::util::UseUnitPrefixes::Yes;
            unitFormat.remove_prefix(1);
        } else if (unitFormat.size() > 0 && unitFormat[0] == 'P') {
            usePrefix = ::inviwo::util::UseUnitPrefixes::No;
            unitFormat.remove_prefix(1);
        }

        if (unitFormat.empty()) {
        } else if (unitFormat == "si") {
            unitsystem = UnitSystem::SI;
        } else if (unitFormat == "ext") {
            unitsystem = UnitSystem::Ext;
        } else if (unitFormat == "sys") {
            unitsystem = UnitSystem::Sys;
        } else if (unitFormat == "all") {
            unitsystem = UnitSystem::All;
        } else {
            throw format_error("Invalid unit format found");
        }

        ctx.advance_to(endIt);
        return formatter_.parse(ctx);
    }

    // Formats the point p using the parsed format specification (presentation)
    // stored in this formatter.
    template <typename FormatContext>
    auto format(const ::inviwo::Unit& unit, FormatContext& ctx) -> decltype(ctx.out()) {
        // ctx.out() is an output iterator to write to.

        if (unit == ::inviwo::Unit{}) return ctx.out();

        const ::inviwo::unitgroups::EnabledGroups enabledGroups = [&]() {
            if (unitsystem == UnitSystem::SI) {
                return ::inviwo::unitgroups::siGroups;
            } else if (unitsystem == UnitSystem::Ext) {
                return ::inviwo::unitgroups::extGroups;
            } else if (unitsystem == UnitSystem::All) {
                return ::inviwo::unitgroups::allGroups;
            } else {
                return ::inviwo::util::getSystemUnitGroups();
            }
        }();

        fmt::memory_buffer buff;
        auto it = std::back_inserter(buff);

        if (leadingSpace) *it++ = ' ';
        if (braces == Braces::Paren) *it++ = '(';
        if (braces == Braces::Square) *it++ = '[';
        if (!units::is_valid(unit)) {
            it = fmt::format_to(it, "Invalid");
        } else if (units::is_error(unit)) {
            it = fmt::format_to(it, "Error");
        } else {
            it = ::inviwo::util::formatUnitTo(it, unit, enabledGroups, usePrefix);
        }
        if (braces == Braces::Paren) *it++ = ')';
        if (braces == Braces::Square) *it++ = ']';

        return formatter_.format(std::string_view{buff.data(), buff.size()}, ctx);
    }
};

redpajama_set_name: RedPajamaGithub


text:
package org.jtransfo.internal;

import org.jtransfo.JTransfoException;
import org.jtransfo.object.ReadOnlyGetterDomain;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;

/**
 * Test for AccessorSyntheticField.
 */
public class AccessorSyntheticField2Test {

    @Mock
    private ReflectionHelper reflectionHelper;

    @Rule
    public ExpectedException exception = ExpectedException.none();

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        when(reflectionHelper.getMethod(ReadOnlyGetterDomain.class, null, "getId")).thenReturn(
                ReadOnlyGetterDomain.class.getMethod("getId"));
        when(reflectionHelper.getMethod(ReadOnlyGetterDomain.class, null, "setId", String.class)).thenReturn(
                ReadOnlyGetterDomain.class.getMethod("setId", String.class));
        when(reflectionHelper.getMethod(ReadOnlyGetterDomain.class, null, "getTwice")).thenReturn(
                ReadOnlyGetterDomain.class.getMethod("getTwice"));
    }

    @Test
    public void testConstructNoField() throws Exception {
        AccessorSyntheticField accessorSyntheticField =
                new AccessorSyntheticField(reflectionHelper, ReadOnlyGetterDomain.class, "id", false);

        assertThat(accessorSyntheticField.getName()).isEqualTo("id");
        assertThat(accessorSyntheticField.getType()).isEqualTo(String.class);

        ReadOnlyGetterDomain domain = new ReadOnlyGetterDomain();
        accessorSyntheticField.set(domain, "zzz");
        assertThat(accessorSyntheticField.get(domain)).isEqualTo("zzz");
    }

    @Test
    public void testConstructNoAccessors() throws Exception {
        exception.expect(JTransfoException.class);
        exception.expectMessage("Cannot find getter from [getAhum, ahum, isAhum, hasAhum] on class " +
                "org.jtransfo.object.ReadOnlyGetterDomain.");

        new AccessorSyntheticField(reflectionHelper, ReadOnlyGetterDomain.class, "ahum", false);
    }

    @Test
    public void testConstructNoSetter() throws Exception {
        exception.expect(JTransfoException.class);
        exception.expectMessage("Cannot find setter setTwice on class org.jtransfo.object.ReadOnlyGetterDomain.");

        new AccessorSyntheticField(reflectionHelper, ReadOnlyGetterDomain.class, "twice", false);
    }

    @Test
    public void testConstructNoFieldReadOnly() throws Exception {
        AccessorSyntheticField accessorSyntheticField =
                new AccessorSyntheticField(reflectionHelper, ReadOnlyGetterDomain.class, "twice", true);

        ReadOnlyGetterDomain domain = new ReadOnlyGetterDomain();
        domain.setId("ahum");
        assertThat(accessorSyntheticField.get(domain)).isEqualTo("ahumahum");
    }

}


text:
using System;
using System.Collections.Generic;
using Ch07.Common.Contracts;
using Ch07.Common.Services;
using Unity.Interception.InterceptionBehaviors;
using Unity.Interception.PolicyInjection.Pipeline;
using Unity.Interception.ContainerIntegration;
using Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception;
using Unity;

namespace Ex12.InterceptionDemo
{
    static class Program
    {
        static void Main(string[] args)
        {
            var container = new UnityContainer();

            // 為容器加入攔截功能。
            container.AddNewExtension<Interception>();

            // 註冊型別時,一併設定攔截器。
            container.RegisterType<IMessageService, EmailService>(
                new Interceptor(new InterfaceInterceptor()),
                new InterceptionBehavior(typeof(MyLoggerBehavior)),
                new InterceptionBehavior(typeof(MyLoggerBehavior2)));

            // 解析 IMessageService 物件。
            var msgService = container.Resolve<IMessageService>();

            // 呼叫方法。
            msgService.SendMessage("Michael", "Hello, 利用 Unity 攔截物件的方法!");

            // Prevent screen from closing
            Console.ReadLine();
        }
    }

    public class MyLoggerBehavior : IInterceptionBehavior
    {
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            // 呼叫方法之前
            Console.WriteLine("正要執行此方法:{0}", input.MethodBase.Name);

            // 呼叫目標方法(被攔截的方法)
            var result = getNext()(input, getNext);

            // 呼叫方法之後
            Console.WriteLine("正要離開此方法:{0},時間:{1}", input.MethodBase.Name, DateTime.Now.ToString());

            return result;
        }

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            // 傳回空的型別集合,表示欲攔截之物件可以是任何型別。
            return new Type[] { };
        }

        public bool WillExecute
        {
            get
            {
                return true;
            }
        }
    }

    public class MyLoggerBehavior2 : IInterceptionBehavior
    {
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            // 呼叫方法之前
            Console.WriteLine("2 before");

            // 呼叫目標方法(被攔截的方法)
            var result = getNext()(input, getNext);

            // 呼叫方法之後
            Console.WriteLine("2 after");

            return result;
        }

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            // 傳回空的型別集合,表示欲攔截之物件可以是任何型別。
            return new Type[] { };
        }

        public bool WillExecute
        {
            get
            {
                return true;
            }
        }
    }
}


text:
import gulp from 'gulp'
import babel from 'gulp-babel'
import browserSync from 'browser-sync'
import concat from 'gulp-concat'
import nunjucks from 'gulp-nunjucks-render'
import sass from 'gulp-sass'
import sourcemaps from 'gulp-sourcemaps'
import uglify from 'gulp-uglify'
const reload = browserSync.reload

function html() {
  return gulp.src('src/pages/*.njk')
    .pipe(nunjucks({
      path: 'src/'
    }))
    .pipe(gulp.dest('./dist'))
    .pipe(browserSync.stream())
}

const css = {
  project: () => {
    return css.compile('src/layouts/project/main.scss')
  },
  guide: () => {
    return css.compile('src/layouts/guide/guide.scss')
  },
  compile: (path) => {
    return gulp.src(path)
      .pipe(sourcemaps.init())
      .pipe(sass())
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('./dist/css'))
      .pipe(browserSync.stream())
  }
}

const js = {
  project: () => {
    return js.compile('src/layouts/project/**/*.js', 'core.js')
  },
  guide: () => {
    return js.compile('src/layouts/guide/**/*.js', 'guide.js')
  },
  compile: (path, output) => {
    return gulp.src(path)
      .pipe(sourcemaps.init())
      .pipe(babel())
      .pipe(uglify())
      .pipe(concat(output))
      .pipe(sourcemaps.write('.'))
      .pipe(gulp.dest('./dist/js'))
      .pipe(browserSync.stream())
  }
}

const img = {
  project: () => {
    return img.copy('src/layouts/project/img/*', 'dist/guide/img')
  },
  guide: () => {
    return img.copy('src/layouts/guide/img/*', 'dist/img')
  },
  copy: (path, destination) => {
    return gulp.src(path)
      .pipe(gulp.dest(destination))
  }
}

function dev() {
  browserSync.init({
    server: "./dist"
  })
  gulp.watch('src/**/*.njk', html).on('end', reload)
  gulp.watch('src/layouts/project/**/*.scss', css.project).on('end', reload)
  gulp.watch('src/layouts/guide/**/*.scss', css.guide).on('end', reload)
  gulp.watch('src/layouts/project/**/*.js', js.project).on('end', reload)
  gulp.watch('src/layouts/guide/**/*.js', js.guide).on('end', reload)
  gulp.watch('src/layouts/project/img/*', img.project).on('end', reload)
  gulp.watch('src/layouts/guide/img/*', img.guide).on('end', reload)
}

gulp.task(
  'default',
  gulp.series(
    gulp.parallel(html, css.project, css.guide, js.project, js.guide, img.project, img.guide),
    dev
  )
);


text:
<?php

namespace App\Classes;

use App\interfaces\UserInterface;
use App\traits\GetHeaderTrait;
use avtomon\{
    Acless, CustomException, DbResultItem, PQSkaTpl
};

/**
 * Класс ошибок
 *
 * Class ViewException
 * @package App\Classes
 */
class ViewException extends CustomException
{
}

/**
 * Представление
 *
 * Class View
 * @package App\Classes
 */
class View
{
    /**
     * Генератор шапок
     */
    use GetHeaderTrait;

    /**
     * Путь к файлу шаблона
     *
     * @var string
     */
    protected $filePath = '';

    /**
     * Добавлять ли шапку
     *
     * @var bool
     */
    protected $addHeader = true;

    /**
     * Настройки шаблона
     *
     * @var array
     */
    protected $settings = [];

    /**
     * Данные для добавления в шаблон
     *
     * @var array
     */
    protected $data = [];

    /**
     * Является ли представление письмом
     *
     * @var bool
     */
    protected $isMessage = false;

    /**
     * Конструктор
     *
     * @param string $filePath - путь к файлу шаблона
     * @param bool $addHeader - добавлять ли шапку
     * @param array $settings - настройки шаблонизатора
     *
     * @throws FileHelperException
     * @throws HelperException
     * @throws ResponseException
     */
    public function __construct(string $filePath, bool $addHeader = null, array $settings = [])
    {
        $this->filePath = $filePath;
        $this->addHeader = $addHeader ?? !App::getResponse()->getIsAjax();
        $this->settings = $settings;
    }

    /**
     * Установить является ли представление письмом
     *
     * @param bool $isMessage - новое значение
     */
    public function setIsMessage(bool $isMessage): void
    {
        $this->isMessage = $isMessage;
    }

    /**
     * Путь к файлу относительно директории с шаблонами представлений
     *
     * @return string
     */
    public function getFilePath(): string
    {
        return $this->filePath;
    }

    /**
     * Полный путь к файлу относительно директории с шаблонами представлений
     *
     * @return string
     */
    public function getFullFilePath(): string
    {
        return $_SERVER['DOCUMENT_ROOT'] . ($this->isMessage ? App::MESSAGES_PATH : App::VIEWS_PATH) . '/' . $this->filePath;
    }

    /**
     * Вернуть флаг добавления шабки
     *
     * @return bool
     */
    public function getAddHeader(): bool
    {
        return $this->addHeader;
    }

    /**
     * Добавить данные для добавления на страницу
     *
     * @param DbResultItem $data - данные
     * @param string $parentSelector - в элемент с каким селектором добавлять данные
     */
    public function addData(DbResultItem $data, string $parentSelector): void
    {
        $this->data[$parentSelector] = $data;
    }

    /**
     * Удалить данные для добавления на страницу
     *
     * @param string $parentSelector - в элемент с каким селектором больше не надо добавлять данные
     */
    public function deleteData(string $parentSelector): void
    {
        unset($this->data[$parentSelector]);
    }

    /**
     * Удалить со страницы данные недоступные текущему пользователю
     *
     * @param \avtomon\phpQueryObject|\avtomon\QueryTemplatesParse|\avtomon\QueryTemplatesSource|\avtomon\QueryTemplatesSourceQuery|string $template - страница
     *
     * @return mixed
     *
     * @throws ServiceException
     * @throws \ReflectionException
     */
    protected static function removeUnresolvedElements(&$template)
    {
        $elements = $template->find('*[data-acless-url-id]');
        $aclessUrls = Acless::create(App::getUser()->getId())->getAccessRights();

        foreach ($elements as $el) {
            if (empty($aclessRight = $aclessUrls[$el->attr('data-acless-url-id')])) {
                $el->remove();
                break;
            }

            if (
                !empty($value = $el->attr('data-acless-value'))
                &&
                !\in_array($value, json_decode($aclessRight['values'] ?? '', true) ?? [], true)
            ) {
                $el->remove();
                break;
            }
        }

        return $template;
    }

    /**
     * Отрендерить страницу
     *
     * @return \phpQueryObject
     *
     * @throws \avtomon\PQSkaTplException
     */
    public function render() : \phpQueryObject
    {
        $page = new PQSkaTpl($this->getFullFilePath(), $this->settings);
        $template = $page->getTemplate();
        self::removeUnresolvedElements($template);
        if ($this->addHeader) {
            $template->find('body')->prepend(self::getHeader());
        }

        foreach ($this->data as $selector => $data) {
            $page->setMultiData($data->getArrayResult(), $selector);
        }

        return $template;
    }
}


text:
<?php

declare (strict_types=1);

namespace Oxidmod\RestBundle\Transformer;

use Oxidmod\RestBundle\Transformer\Exception\UnsupportedObjectException;

/**
 * All transformers should implement this interface
 */
interface TransformerInterface
{
    /**
     * @param mixed $object
     *
     * @return array
     *
     * @throws UnsupportedObjectException
     */
    public function transform($object): array;

    /**
     * @param mixed $object
     *
     * @return bool
     */
    public function supports($object): bool;
}


text:
static int indent_step = 2;
static int indent;

void NInteger::print(std::stringstream &ss) {
    indent += indent_step;
    ss << std::string(indent, ' ') << "Integer " << value << std::endl;
    indent -= indent_step;
}

void NIdentifier::print(std::stringstream &ss) {
    indent += indent_step;
    ss << std::string(indent, ' ') << "Identifier " << name << std::endl;
    indent -= indent_step;
}

void NControl::print(std::stringstream &ss) {
    indent += indent_step;
    ss << std::string(indent, ' ') << "Control" << std::endl;
    l.print(ss);
    m.print(ss);
    r.print(ss);
    indent -= indent_step;
}

void NAssign::print(std::stringstream &ss) {
    indent += indent_step;
    ss << std::string(indent, ' ') << "Assign" << std::endl;
    l.print(ss);
    r.print(ss);
    indent -= indent_step;
}

void NLambda::print(std::stringstream &ss) {
    indent += indent_step;
    ss << std::string(indent, ' ') << "Lambda" << std::endl;
    l.print(ss);
    m.print(ss);
    r.print(ss);
    indent -= indent_step;
}

void NComparisonOperator::print(std::stringstream &ss) {
    indent += indent_step;
    ss << std::string(indent, ' ') << "Comparison " << op << " size: " << l.size() << std::endl;
    for (size_t i = 0; i < l.size(); ++i) {
        l[i]->print(ss);
    }
    indent -= indent_step;
}

void NBinaryOperator::print(std::stringstream &ss) {
    indent += indent_step;
    ss << std::string(indent, ' ') << "Binary " << op << std::endl;
    lhs.print(ss);
    rhs.print(ss);
    indent -= indent_step;
}

void NUnaryOperator::print(std::stringstream &ss) {
    indent += indent_step;
    ss << std::string(indent, ' ') << "Unary" << std::endl;
    u.print(ss);
    indent -= indent_step;
}

void NApply::print(std::stringstream &ss) {
    indent += indent_step;
    ss << std::string(indent, ' ') << "Apply" << std::endl;
    lhs.print(ss);
    rhs.print(ss);
    indent -= indent_step;
}

void NFuncType::print(std::stringstream &ss) {
    indent += indent_step;
    ss << std::string(indent, ' ') << "FuncType" << std::endl;
    lhs.print(ss);
    rhs.print(ss);
    indent -= indent_step;
}

void NTuple::print(std::stringstream &ss) {
    indent += indent_step;
    ss << std::string(indent, ' ') << "Tuple; size: " << l.size() << std::endl;
    for (size_t i = 0; i < l.size(); ++i) {
        l[i]->print(ss);
    }
    indent -= indent_step;
}

void NArray::print(std::stringstream &ss) {
    indent += indent_step;
    if (isString) {
        ss << std::string(indent, ' ') << "String " << name << std::endl;
    } else {
        ss << std::string(indent, ' ') << "Array; size: " << l.size() << std::endl;
        for (size_t i = 0; i < l.size(); ++i) {
            l[i]->print(ss);
        }
    }
    indent -= indent_step;
}


text:
/**
 * @author Max Fisher
 * @version 1.0
 */
package function;

import java.math.BigDecimal;

import core.MathToken;
import core.Expression;
import dict.Operator;
import exception.IllegalOperatorException;

public class SquareRoot extends Expression {

	public SquareRoot(MathToken operand) throws IllegalOperatorException {
		super(Operator.SQROOT, operand);
	}

	@Override
	public BigDecimal compute() {

		double operandD = operand[0].getValue().doubleValue();
		return (BigDecimal.valueOf(Math.sqrt(operandD)));
	}
}


text:
#ifndef itkGTest_h
#define itkGTest_h

#include "gtest/gtest.h"
#include "itkGTestPredicate.h"
#include "itkGTestTypedefsAndConstructors.h"

namespace itk
{

/** \namespace itk::GTest
 * \brief The GTest namespace contains GTest extensions for ITK, and
 * convenience type alias, and functions to aid in analytic testing of
 * results and values.
 *
 */
namespace GTest
{} // end namespace GTest

} // end namespace itk

#endif // itkGTest_h


text:
source /etc/nodepool/provider

NODEPOOL_PYPI_MIRROR=${NODEPOOL_PYPI_MIRROR:-http://pypi.$NODEPOOL_REGION.openstack.org/simple}

sudo sed -i -e "s,^index-url = .*,index-url = $NODEPOOL_PYPI_MIRROR," /etc/pip.conf

cat >/home/jenkins/.pydistutils.cfg <<EOF
[easy_install]
index_url = $NODEPOOL_PYPI_MIRROR
EOF

# Double check that when the node is made ready it is able
# to resolve names against DNS.
host git.openstack.org
host pypi.${NODEPOOL_REGION}.openstack.org


text:
package foo;

import org.jetbrains.annotations.Nullable;

public class A {
    public @Nullable String foo(String s) {
        return null;
    }
}


text:
package io.prometheus.client.exporter;

import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import static org.assertj.core.api.Java6Assertions.assertThat;

public class TestDaemonFlags {

    @Test
    public void testDefaultIsNotDaemon() throws IOException, ExecutionException, InterruptedException {
        assertThat(usesDaemonExecutor(new HTTPServer(0))).isFalse();
    }

    @Test
    public void testDaemon() throws IOException, ExecutionException, InterruptedException {
        assertThat(usesDaemonExecutor(new HTTPServer(0, true))).isTrue();
    }

    @Test
    public void testNonDaemon() throws IOException, ExecutionException, InterruptedException {
        assertThat(usesDaemonExecutor(new HTTPServer(0, false))).isFalse();
    }

    private boolean usesDaemonExecutor(HTTPServer httpServer) throws IOException, InterruptedException, ExecutionException {
        try {
            FutureTask<Boolean> task = new FutureTask<Boolean>(new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    return Thread.currentThread().isDaemon();
                }
            });
            httpServer.server.getExecutor().execute(task);
            return task.get();
        } finally {
            httpServer.stop();
        }
    }
}


text:
using BPMNET.Core;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System;
using BPMNET.Bpmn;
using BPMNET.Exception;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Text;

namespace BPMNET.Entity.Store
{
    public class ProcessTaskStore : IProcessTaskStore<int, ProcessTaskEntity>
    {
        protected DbContext Context { get; private set; }
        public bool DisposeContext { get; protected set; }

        protected string TenantId { get; set; }
        protected IUser User { get; set; }
        protected EntityStore<ProcessTaskEntity> TaskStore { get; private set; }
        protected DbSet<ProcessVariableEntity> ProcessVariableEntity { get; private set; }

        #region Constructor
        public ProcessTaskStore() : this(new BpmDbContext(), null, null)
        {
            DisposeContext = true;
        }
        public ProcessTaskStore(BpmDbContext context, IUser user, ITenant tenant)
        {
            Context = context;
            TenantId = tenant == null ? null : tenant.TenantId;
            User = user;
            TaskStore = new EntityStore<ProcessTaskEntity>(context);
            ProcessVariableEntity = context.Set<ProcessVariableEntity>();
        }

        #endregion

        #region Dispose
        private bool _disposed;
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (DisposeContext && disposing && !_disposed)
            {
                Context.Dispose();
            }
            _disposed = true;
        }
        #endregion

        #region Save Changes
        protected virtual async Task SaveChangesAsync()
        {
            bool saveFailed;
            do
            {
                saveFailed = false;
                try
                {
                    await Context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    saveFailed = true;
                    ex.Entries.Single().Reload();
                }
                catch (DbEntityValidationException vex)
                {
                    StringBuilder sb = new StringBuilder();
                    // Retrieve the error messages as a list of strings.
                    sb.AppendLine(vex.Message);
                    var errorMessages = vex.EntityValidationErrors
                            .SelectMany(x => x.ValidationErrors)
                            .Select(x => x.ErrorMessage);

                    // Join the list to a single string.
                    var fullErrorMessage = string.Join("; ", errorMessages);

                    sb.AppendLine("The validation errors are:");
                    foreach (var item in vex.EntityValidationErrors)
                    {
                        sb.AppendLine("entities : " + item.Entry.Entity.GetType().FullName);
                        foreach (var error in item.ValidationErrors)
                        {
                            sb.AppendLine(error.PropertyName + " : " + error.ErrorMessage);
                        }
                    }

                    // Combine the original exception message with the new one.
                    var exceptionMessage = string.Concat(sb.ToString());

                    // Throw a new DbEntityValidationException with the improved exception message.
                    throw new DbEntityValidationException(exceptionMessage, vex.EntityValidationErrors);
                }

            } while (saveFailed);
        }
        #endregion

        private string GetUserId() {
            if (User == null) return null;
            return User.UserId;
        }

        #region Implement Sub Routine
        public async Task<ProcessTaskEntity[]> GetProcessTaskByFlowNodeIdAsync(string name)
        {
            return await TaskStore.DbEntitySet.Where(t => t.TaskId.Equals(name)).ToArrayAsync();
        }

        public async Task<ProcessTaskEntity> CreateTaskAsync(int processInstanceId, int nodeId, string nodeName, ProcessItemType ItemType)
        {
            if (!ProcessItemCheck.IsTask(ItemType))
                throw new FlowNodeException(nodeName, "Task");
            ProcessTaskEntity task = new ProcessTaskEntity() {
                ProcessInstanceId = processInstanceId,
                FlowNodeId = nodeId,
                TaskId = nodeName,
                TaskType = ItemType,
                CreatedBy = GetUserId()
            };
            TaskStore.Create(task);
            await SaveChangesAsync();
            return task;

            //TODO Add to history
            //AddHistory(proc.Name, pi.ProcessInstanceName, t.ProcessTaskName, string.Format("User: {0} Created Task '{1}'", user, proc.Name), user);
        }

        #endregion

        //public async Task<ProcessTaskEntity> GetProcessTaskAsync(int processInstanceId, string taskName)
        //{
        //    return await Entities.FirstOrDefaultAsync(t => t.ProcessInstanceId.Equals(processInstanceId) && t.Name.Equals(taskName));
        //}

        //public ProcessTaskStore(BpmDbContext context) : base(context)
        //{
        //    _processInstanceSet = context.Set<ProcessInstanceEntity>();
        //}

        //public async Task<IEnumerable<ProcessTaskEntity>> GetActiveProcessTaskAsync(int processInstanceId)
        //{
        //    return await Store.EntitySet.Where(t => t.ProcessInstanceId.Equals(processInstanceId) && !t.IsDone).ToListAsync();
        //}

        //public async Task<ProcessTaskEntity> GetCurrentProcessTaskByName(int processInstanceId, string taskName)
        //{
        //    taskName.ThrowIfNull();
        //    return await Store.EntitySet.FirstOrDefaultAsync(t => t.ProcessInstanceId.Equals(processInstanceId) && t.Name.Equals(taskName));
        //}

        //public async Task<IEnumerable<ProcessTaskEntity>> GetAllProcessInstanceAsync(string taskName)
        //{
        //    taskName.ThrowIfNull();
        //    return await Entities.Where(t => t.Name.Equals(taskName)).ToListAsync();
        //}

        //public ProcessTaskEntity GetProcessTaskByFlowProcess(int flowNodeId, int processInstanceId)
        //{
        //    return Entities.FirstOrDefault(t => t.ProcessInstanceId.Equals(processInstanceId) && t.FlowNodeId.Equals(flowNodeId));
        //}

        //public async Task<bool> IsTaskDoneAsync(int flowNodeId, int processInstanceId)
        //{
        //    return await Entities.Where(t => t.ProcessInstanceId.Equals(processInstanceId) && t.FlowNodeId.Equals(flowNodeId)).Select(t => t.IsDone).SingleAsync();
        //}

    }
}


text:
package com.checkers.server.services;

import com.checkers.server.Consts;
import com.checkers.server.Context;
import com.checkers.server.beans.Game;
import com.checkers.server.beans.Step;
import com.checkers.server.beans.User;
import com.checkers.server.dao.GameDao;
import com.checkers.server.dao.StepDao;
import com.checkers.server.dao.UserDao;
import com.checkers.server.events.StepEvent;
import com.checkers.server.exceptions.ApplicationException;
import com.checkers.server.exceptions.CheckersException;
import com.checkers.server.listeners.MyListener;
import com.checkers.server.services.referee.*;
import com.checkers.server.services.referee.graph.FigureColor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 *
 *
 * @author Pavel Kuchin
 */
@Service("stepService")
public class StepServiceImpl implements StepService {
    @Autowired
    private StepDao stepDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private GameDao gameDao;

    @Autowired
    private MyListener myListener;

    @Autowired
    private Context context;

    private RefereeCollection russianReferees = new RussianRefereeCollectionImpl(this);
    private RefereeCollection worldwideReferees = new WorldwideRefereeCollectionImpl(this);

    @PostAuthorize("hasAnyRole('ROLE_ADMIN,ROLE_USER')")
    @Override
    public Step getStep(Long suid) throws ApplicationException {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        User user = userDao.getUserByLogin(name);

        Step step = null;

        Collection<SimpleGrantedAuthority> authorities =
                (Collection<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();

        if(authorities.contains(Consts.ROLE_ADMIN)){
            step = stepDao.getStep(suid);
        } else if(authorities.contains(Consts.ROLE_USER)){
            step = stepDao.getStep(suid);

            if(!(step.getGame().getBlackUuid() == user.getUuid() || step.getGame().getWhiteUuid() == user.getUuid())){
                throw new ApplicationException(1L, "You are not involved in game.");
            }
        }

        return step;
    }

    @PreAuthorize("hasAnyRole('ROLE_ADMIN,ROLE_USER')")
    @Override
    public Step newStep(Step step) throws ApplicationException, CheckersException {
        Object event;

        Game game = null;

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();

        User user = userDao.getUserByLogin(name);

        if(step.getGame() == null){
            game = gameDao.getGame(step.getGauid());
        } else{
            game = step.getGame();
        }

        // Do step Logic
        // Are you involved in game?
        if(!(game.getBlackUuid() == user.getUuid() || game.getWhiteUuid() == user.getUuid())){
            throw new ApplicationException(1L, "You are not involved in game.");
        }

        // Game should have status - 'game'
        if(!game.getState().equals("game")){
            throw new ApplicationException(2L, "You can't make step in 'close' or 'open' game. Game should be in 'game' state.");
        }

        // You can't make two steps, one by one. It is obviously.
        Step lastStep = stepDao.getGameLastStep(step.getGauid());

        if(lastStep != null){
            if(lastStep.getUuid().equals(user.getUuid())){
                throw new CheckersException(20L, "You made your move. Let the opponent to make a move.");
            }
        } else if(game.getBlackUuid() == user.getUuid()){
            throw new CheckersException(10L, "White should make step first");
        }

        Referee referee = null;

        if(game.getBoard().equals(Consts.GAME_BOARD_RUSSIAN)){
            referee = russianReferees.getRefereeByGuid(game.getGauid());
        } else if(game.getBoard().equals(Consts.GAME_BOARD_WORLDWIDE)){
            referee = worldwideReferees.getRefereeByGuid(game.getGauid());
        }

        if(game.getBlackUuid() == user.getUuid()){
            referee.checkStep(step.getStep(), FigureColor.BLACK);
        } else if(game.getWhiteUuid() == user.getUuid()){
            referee.checkStep(step.getStep(), FigureColor.WHITE);
        }

       //Bring a little Async
        step.setSuid(null);

        step.setUuid(null);

        step.setCreated(new Date());

        step.setUser(user);

        stepDao.newStep(step);

        GameResult gameResult= referee.checkGameStatus();

        if(!gameResult.equals(GameResult.CONTINUE)){
            game.setState(Consts.GAME_STATE_CLOSE);
            game.setResolution(gameResult.toString());

            gameDao.modGame(game);
        }

        context.getApplicationContext()
                .publishEvent(new StepEvent(context.getApplicationContext(), step));

        return step;
    }

    @PreAuthorize("hasAnyRole('ROLE_ADMIN,ROLE_USER')")
    @Override
    public List<Step> getGameSteps(Long gauid) throws ApplicationException {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        User user = userDao.getUserByLogin(name);

        List<Step> steps = null;

        Collection<SimpleGrantedAuthority> authorities =
                (Collection<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();

        if(authorities.contains(Consts.ROLE_ADMIN)){
            steps = stepDao.getGameSteps(gauid);
        } else if(authorities.contains(Consts.ROLE_USER)){
            Game game = gameDao.getGame(gauid);

            if((game.getBlackUuid() == user.getUuid() || game.getWhiteUuid() == user.getUuid())){
                steps = stepDao.getGameSteps(gauid);
            } else{
                throw new ApplicationException(1L, "You are not involved in game.");
            }
        }

        return steps;
    }

    @PreAuthorize("hasAnyRole('ROLE_ADMIN,ROLE_USER')")
    @Override
    public Step getGameLastStep(Long gauid) throws ApplicationException {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        User user = userDao.getUserByLogin(name);

        Step step = null;

        Collection<SimpleGrantedAuthority> authorities =
                (Collection<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();

        if(authorities.contains(Consts.ROLE_ADMIN)){
            step = stepDao.getGameLastStep(gauid);
        } else if(authorities.contains(Consts.ROLE_USER)){
            Game game = gameDao.getGame(gauid);

            if((game.getBlackUuid() == user.getUuid() || game.getWhiteUuid() == user.getUuid())){
                step = stepDao.getGameLastStep(gauid);
            } else{
                throw new ApplicationException(1L, "You are not involved in game.");
            }
        }

        return step;
    }

    @Override
    public Step getAsyncGameLastStep(Long gauid, String username) throws InterruptedException, ApplicationException {
        Step result = null;

        User user = userDao.getUserByLogin(username);

        Game game = gameDao.getGame(gauid);

        if(!(game.getBlackUuid() == user.getUuid() || game.getWhiteUuid() == user.getUuid())){
            throw new ApplicationException(1L, "You are not involved in game.");
        }

        while(result == null){
            Step lastStep = stepDao.getGameLastStep(gauid);
            if(lastStep != null && !lastStep.getUser().getLogin().equals(username)){
                result = lastStep;
            } else{
                //We are waiting for object creation
                Step eStep;
                do{
                    eStep = myListener.waitEvent(StepEvent.class).getStep();
                }while(eStep.getGauid() != gauid);
            }
        }
            return result;
    }
}


text:
| Name | Type | Description | Notes |
| ---- | ---- | ----------- | ----- |
| **client_order_id_format_exchange** | **String** | The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it. |  |
| **exchange_order_id** | **String** | Unique identifier of the order assigned by the exchange or executing system. | [optional] |
| **amount_open** | **Float** | Quantity open for further execution. `amount_open` = `amount_order` - `amount_filled` |  |
| **amount_filled** | **Float** | Total quantity filled. |  |
| **avg_px** | **Float** | Calculated average price of all fills on this order. | [optional] |
| **status** | [**OrdStatus**](OrdStatus.md) |  |  |
| **status_history** | **Array<Array<String>>** | Timestamped history of order status changes. | [optional] |
| **error_message** | **String** | Error message. | [optional] |
| **fills** | [**Array<Fills>**](Fills.md) | Relay fill information on working orders. | [optional] |

## Example

```ruby
require 'openapi_client'

instance = OpenapiClient::OrderExecutionReportAllOf.new(
  client_order_id_format_exchange: f81211e2-27c4-b86a-8143-01088ba9222c,
  exchange_order_id: 3456456754,
  amount_open: 0.22,
  amount_filled: 0.0,
  avg_px: 0.0783,
  status: null,
  status_history: null,
  error_message: {"result":"error","reason":"InsufficientFunds","message":"Failed to place buy order on symbol 'BTCUSD' for price $7,000.00 and quantity 0.22 BTC due to insufficient funds"},
  fills: null
)
```


text:
<?php

namespace Fd\BackendBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\Event\DataEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormError;
use Fd\OfertaEducativaBundle\Entity\Norma;
use Fd\TablaBundle\Repository\TipoNormaRepository;

class NormaBuscarType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('numero', 'integer', array(
            'required' => false,
            'label' => 'Número',
        ));
        $builder->add('anio', 'integer', array(
            'required' => false,
            'label' => 'Año',
        ));
        $builder->add('tipo', 'entity', array(
            'required' => false,
            'label' => 'Tipo',
            'class' => 'TablaBundle:TipoNorma',
            'empty_value' => 'Seleccione...',
            'query_builder' => function(TipoNormaRepository $er) {
                return $er->qbTodosOrdenado();
            },
        ));
        $builder->addEventListener(FormEvents::POST_BIND, function(DataEvent $event) {
                    $form = $event->getForm();
                    $datos = $form->getData();
                    $nombre = $form->getName();
                    if (empty($datos['numero']) and empty($datos['anio']) and empty($datos['tipo']) ) {
                        $form->addError(new FormError('No puede dejar todos los campos vacíos'));
                    };
                }
        );
    }

//    public function setDefaultOptions(OptionsResolverInterface $resolver) {
//        $resolver->setDefaults(array(
//            'data_class' => 'Fd\OfertaEducativaBundle\Entity\Carrera'
//        ));
//    }

    public function getName() {
        return 'norma_buscar_type';
    }

}


text:
import pytest
from EclecticIQ import maliciousness_to_dbotscore

test_data = [
    ('unknown', 'unknown', 3),
    ('unknown', 'safe', 0),
    ('unknown', 'low', 0),
    ('unknown', 'medium', 0),
    ('unknown', 'high', 0),
    ('safe', 'unknown', 3),
    ('safe', 'safe', 3),
    ('safe', 'low', 1),
    ('safe', 'medium', 1),
    ('safe', 'high', 1),
    ('low', 'unknown', 3),
    ('low', 'safe', 3),
    ('low', 'low', 3),
    ('low', 'medium', 3),
    ('low', 'high', 2),
    ('medium', 'unknown', 3),
    ('medium', 'safe', 3),
    ('medium', 'low', 3),
    ('medium', 'medium', 3),
    ('medium', 'high', 2),
    ('high', 'unknown', 3),
    ('high', 'safe', 3),
    ('high', 'low', 3),
    ('high', 'medium', 3),
    ('high', 'high', 3)
]

@pytest.mark.parametrize('maliciousness,threshold,expected_result', test_data)
def test_maliciousness_to_dbotscore(maliciousness, threshold, expected_result):
    assert maliciousness_to_dbotscore(maliciousness, threshold) == expected_result

def test_maliciousness_to_dbotscore_with_bad_args():
    with pytest.raises(ValueError, match=r'maliciousness=.*$'):
        maliciousness_to_dbotscore('tutuloo', 'unknown')

    with pytest.raises(ValueError, match=r'threshold=.*$'):
        maliciousness_to_dbotscore('safe', 'YUP')


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Inspire.Shared.Service
{
    /// <summary>
    /// A generic service container that provides collections and a base service
    /// </summary>
    public abstract class ServiceContainer
    {

        // Used to implement the GetService function
        private Dictionary<Type, Service> _serviceLookupTable;

        public ServiceContainer()
        {
            _serviceLookupTable = new Dictionary<Type, Service>();
        }

        /// <summary>
        /// Gets a specific type of service from the service container.
        /// This is useful for letting services talk to each other if required.
        /// </summary>
        /// <param name="serviceType"></param>
        /// <returns></returns>
        public T GetService<T>() where T : Service
        {
            return (T)_serviceLookupTable.Values.FirstOrDefault(c => c.GetType() == typeof(T));
        }

        /// <summary>
        /// Registers a service into the container.
        /// </summary>
        /// <param name="service"></param>
        public virtual void RegisterService(Service service)
        {
            service.ServiceContainer = this;
            _serviceLookupTable.Add(service.GetType(), service);

            // Setup now
            service.Setup();

        }

        /// <summary>
        /// Performs updates on all the services
        /// </summary>
        public void PerformUpdates()
        {
            foreach (var service in _serviceLookupTable.Values)
            {
                service.PeformUpdate();
            }
        }

    }
}


text:
package admin

type TemplateMap map[string]interface{}

func (t TemplateMap) AddTitle(title string) {
	t["title"] = title
}

func (t TemplateMap) AddErrors(errors ...string) {
	t["error"] = errors
}

func (t TemplateMap) AddSuccess(success ...string) {
	t["success"] = success
}


text:
package io.lacuna.bifurcan;

/**
 * @author ztellman
 */
public interface IEdge<V, E> {

  /**
   * @return the source vertex
   */
  V from();

  /**
   * @return the destination vertex
   */
  V to();

  /**
   * @return the value associated with the edge
   */
  E value();

  /**
   * @return true if the underlying graph is directed, otherwise false
   */
  boolean isDirected();
}


text:
<?php

	function modelLoader($class_name) {
		$root = $_SERVER['DOCUMENT_ROOT'];
		@include_once($root.'/models/'.strtolower($class_name).'.class.php'); // @ stands for silence warnings
	}
	function helperLoader($class_name) {
		$root = $_SERVER['DOCUMENT_ROOT'];
		@include_once($root.'/helpers/'.strtolower($class_name).'.class.php');
	}

	spl_autoload_register('modelLoader');
	spl_autoload_register('helperLoader');

?>


text:
namespace ray {

CoreWorkerMemoryStoreProvider::CoreWorkerMemoryStoreProvider(
    std::shared_ptr<CoreWorkerMemoryStore> store)
    : store_(store) {
  RAY_CHECK(store != nullptr);
}

Status CoreWorkerMemoryStoreProvider::SetClientOptions(std::string name,
                                                       int64_t limit_bytes) {
  return Status::NotImplemented(
      "SetClientOptions() not implemented for in-memory store.");
}

Status CoreWorkerMemoryStoreProvider::Put(const RayObject &object,
                                          const ObjectID &object_id) {
  Status status = store_->Put(object_id, object);
  if (status.IsObjectExists()) {
    // Object already exists in store, treat it as ok.
    return Status::OK();
  }
  return status;
}

Status CoreWorkerMemoryStoreProvider::Create(const std::shared_ptr<Buffer> &metadata,
                                             const size_t data_size,
                                             const ObjectID &object_id,
                                             std::shared_ptr<Buffer> *data) {
  return Status::NotImplemented(
      "Create/Seal interface not implemented for in-memory store.");
}

Status CoreWorkerMemoryStoreProvider::Seal(const ObjectID &object_id) {
  return Status::NotImplemented(
      "Create/Seal interface not implemented for in-memory store.");
}

Status CoreWorkerMemoryStoreProvider::Get(
    const std::unordered_set<ObjectID> &object_ids, int64_t timeout_ms,
    const TaskID &task_id,
    std::unordered_map<ObjectID, std::shared_ptr<RayObject>> *results,
    bool *got_exception) {
  const std::vector<ObjectID> id_vector(object_ids.begin(), object_ids.end());
  std::vector<std::shared_ptr<RayObject>> result_objects;
  RAY_RETURN_NOT_OK(
      store_->Get(id_vector, id_vector.size(), timeout_ms, true, &result_objects));

  for (size_t i = 0; i < id_vector.size(); i++) {
    if (result_objects[i] != nullptr) {
      (*results)[id_vector[i]] = result_objects[i];
      if (result_objects[i]->IsException()) {
        *got_exception = true;
      }
    }
  }
  return Status::OK();
}

Status CoreWorkerMemoryStoreProvider::Contains(const ObjectID &object_id,
                                               bool *has_object) {
  return Status::NotImplemented("Contains() not implemented for in-memory store.");
}

Status CoreWorkerMemoryStoreProvider::Wait(const std::unordered_set<ObjectID> &object_ids,
                                           int num_objects, int64_t timeout_ms,
                                           const TaskID &task_id,
                                           std::unordered_set<ObjectID> *ready) {
  std::vector<ObjectID> id_vector(object_ids.begin(), object_ids.end());
  std::vector<std::shared_ptr<RayObject>> result_objects;
  RAY_CHECK(object_ids.size() == id_vector.size());
  RAY_RETURN_NOT_OK(
      store_->Get(id_vector, num_objects, timeout_ms, false, &result_objects));

  for (size_t i = 0; i < id_vector.size(); i++) {
    if (result_objects[i] != nullptr) {
      ready->insert(id_vector[i]);
    }
  }

  return Status::OK();
}

Status CoreWorkerMemoryStoreProvider::Delete(const std::vector<ObjectID> &object_ids,
                                             bool local_only,
                                             bool delete_creating_tasks) {
  store_->Delete(object_ids);
  return Status::OK();
}

std::string CoreWorkerMemoryStoreProvider::MemoryUsageString() { return ""; }

}  // namespace ray


text:
@interface UASQSBatchResultErrorEntry : UASQSModel

@property (nonatomic, copy) NSString *identifier;
@property (nonatomic) BOOL senderFault;
@property (nonatomic, copy) NSString *code;
@property (nonatomic, copy) NSString *message;

@end


text:
#ifndef qdr_agent_config_link_route
#define qdr_agent_config_link_route 1

#include "router_core_private.h"

void qdra_config_link_route_get_first_CT(qdr_core_t *core, qdr_query_t *query, int offset);
void qdra_config_link_route_get_next_CT(qdr_core_t *core, qdr_query_t *query);
void qdra_config_link_route_create_CT(qdr_core_t *core, qd_iterator_t *name, qdr_query_t *query, qd_parsed_field_t *in_body);
void qdra_config_link_route_update_CT(qdr_core_t *core, qdr_query_t *query, qd_parsed_field_t *in_body);
void qdra_config_link_route_delete_CT(qdr_core_t *core, qdr_query_t *query, qd_iterator_t *name,
                                qd_iterator_t *identity);
void qdra_config_link_route_get_CT(qdr_core_t    *core,
                                   qd_iterator_t *name,
                                   qd_iterator_t *identity,
                                   qdr_query_t   *query,
                                   const char    *qdr_config_link_route_columns[]);

#define QDR_CONFIG_LINK_ROUTE_COLUMN_COUNT 10

const char *qdr_config_link_route_columns[QDR_CONFIG_LINK_ROUTE_COLUMN_COUNT + 1];

#endif


text:
title: Data Science Workflow with Clojure
date: 2016-11-07T13:07:09+00:00
author: admin
categories:
  - clojure
tags:
  - clojure
  - data science
  - funcitonal programming
  - atom
  - editors
---

Recently I've been coding in Clojure using at atom editor combined with the proto-repl and proto-repl-charts plugins. Blog post to come shortly =)


text:
/* Reset for angular bootstrap */
.nav, .pagination, .carousel, .panel-title a {
  cursor: pointer;
}

.navbar-default {
  background-color: white;
}

.list-group-item:hover {
  cursor: pointer;
}

/* Space out content a bit */
body {
  padding-top: 20px;
  padding-bottom: 20px;
}

.well.login {
  background-color: white;
}

#exemptions {
  list-style: none;
  padding-left: 0px;
}

#exemptions li {
  color: #ccc;
  padding: 7.5px;
  border-radius: 5px;
  border: solid #ccc 1px;
  width: 40%;
  margin-bottom: 10px;
  margin-right: 10px;
  text-align: center;
  float: left;
}

#exemptions li:hover {
  color: #428bca;
  border: solid #428bca 1px;
  cursor: pointer;
}

#exemptions li.selected {
  color: #5cb85c;
  border: solid #5cb85c 1px;
}

#main {
  margin-top: 50px;
}

#filter legend {
  margin-top: 15px;
}

#active-filters .filter {
  color: black;
}

#active-filters .filter:focus {
  outline: none;
}

#active-filters .filter:hover {
  color: black;
  text-decoration: none;
}

.no-background.jumbotron {
  background: none;
  padding-top: 20px;
  padding-bottom: 20px;
  padding-left: 15px;
}

.main.jumbotron {
  background: none;
  padding-top: 20px;
  padding-bottom: 0px;
  padding-left: 15px;
}

.animate-switch.ng-enter {
  -webkit-animation: bounceInRight 1.5s;
  animation: bounceInRight 1.5s;
}

div[ng-view].ng-enter {
  -webkit-animation: fadeInDown 0.5s;
  animation: fadeInDown 0.5s;
}

#planner {
  /*text-align: center;*/
}

.category {
  padding: 10px;
  width: 25%;
  float: left;
  text-align: center;
}

@media (max-width: 992px) {
  .category {
    width: 100%;
  }

  .category .course {
    width: 90%;
  }

  .category .status {
    width: 10%;
  }
}

.category .course {
  float: left;
  display: table;
  border-radius: 5px 0px 0px 5px;
  padding: 0px 10px;
  background-color: rgb(244,249,255);
  border: solid #ccc 1px;
  border-right: none;
  height: 50px;
  width: 75%;
  margin-bottom: 5px;
}

.category .course small {
  display: table-cell;
  vertical-align: middle;
}

.category .status {
  border-radius: 0px 5px 5px 0px;
  float: left;
  height: 50px;
  width: 25%;
  border: solid #ccc 1px;
}

.category .status.exemption:hover {
  cursor: not-allowed;
  background-color: white;
}

.category .status.preassigned:hover {
  background-color: rgb(250,250,250);
}

.category .course.selected {
  background-color: #D1E1E8;
}

.category .course.exemption {
  background-color: gainsboro;
}

.category .course.exemption:hover {
  background-color: gainsboro;
  cursor: not-allowed;
  animation: none;
}

.category .course.preassigned:hover {
  background-color: #dff0d8;
}

.category .course.scheduled {
  background-color: #dff0d8;
}

.category .course.scheduled:hover {
  background-color: #C6D7BF;
}

.category .status small {
  position: relative;
  top: 15px;
}

.category .status:hover {
  cursor: pointer;
  background-color: rgb(244,249,255);
}

/*.category .status:hover small {
  -webkit-animation: pulse 0.7s;
  animation: pulse 0.7s;
}*/

.category .course:hover{
  cursor: pointer;
  background-color: white;
  color: black;
}

/*.category .wrapper:hover {
  cursor: pointer;
  -webkit-animation: pulse 0.5s;
  animation: pulse 0.5s;
}*/

.category-title {
  font-size: 15.5px;
}

@media(max-width: 1280px){
  .category-title {
    font-size: 12.5px;
  }
}

.modal-content.browse {
  margin-top: 20%;
  width: 450px;
  margin-left: auto;
  margin-right: auto;
}

.course-modal {
  height: auto;
}

@media (max-width: 768px) {
  .modal-content {
    margin-top: 30px;
    width: 100%;
  }
  .course-modal {
    width: 100%;
  }
}

.modal.fade .modal-dialog, .modal.in .modal-dialog {
  -webkit-transform: translate(0, 0);
  -ms-transform: translate(0, 0);
  transform: translate(0, 0);
}

/*Toggle for bounce animation*/
.modal.fade {
  /*-webkit-animation: bounceIn 0.65s;
  animation: bounceIn 0.65s;*/
}

.modal-body h1 {
  padding-bottom: 20px;
  font-weight: 450;
  text-align: center;
}

.browse {
  height: 200px;
  border-radius: 5px;
  width: 100%;
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
  border: solid #ccc 1px;
}

.browse .course {
  box-sizing: border-box;
  width: 100%;
  height: 75px;
  padding: 15px;
  border-top: solid #ccc 1px;
}

.browse .course:hover {
  cursor: pointer;
}

.browse .course:first-child {
  border-top: none;
}

.browse .course .course-title {
  font-size: 11pt;
}

.browse .course small {
  color: grey;
}

.browse .course.selected {
  background-color: aliceblue;
}

.btn-delete {
  border-color: #FF5E3A;
  color: #FF5E3A;
}

#time-title {
  margin-bottom: 30px;
}

.selector:hover {
  cursor: move;
}

#categories-table {
  table-layout: fixed;
}

#categories-table tbody td:first-child{
  text-align: center;
  width: 10%;
}

#course-table {
  table-layout: fixed;
}

#course-table tbody td:first-child{
  text-align: center;
  width: 10%;
}

.drop-zone {
  border: dashed gainsboro 2px;
}

.drop-cell {
  padding: 20px !important
}

.panel-table-wrapper {
  height: 110px;
  overflow-y: scroll;
}

.preassigned-table {
  table-layout: fixed;
}

.preassigned-table tbody td:first-child {
  width: 7.5%;
}

.preassigned-table tbody td:last-child {
  width: 5%;
}

.preassigned-table tbody td:nth-child(2) {
  width: 15%;
}

.preassigned-table.drop-hover tbody tr td {
  background-color: aliceblue;
}

.subtype-table {
  margin-bottom: 0px;
}

.pointer:hover {
  cursor: pointer;
}

.scroll-y {
  height: 600px;
  overflow-y: scroll;
}

#new-category {
  height: 75px;
  width: 100%;
  border: dashed gainsboro 2px;
  margin-bottom: 15px;
  display: table;
}

#new-category p{
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

.new-category-hover {
  background-color: aliceblue;
}

#major-table {
  table-layout: fixed;
}

#major-table tbody td:first-child label {
  font-weight: normal;
}

#major-table tbody td:first-child {
  cursor: pointer;
}

#major-table tbody td:first-child label span {
  margin-right: 10px;
}

#major-table tbody td:last-child {
  text-align: center;
  width: 12.5%;
}

.subtype-heading{
  margin-top: 15px;
  box-sizing: border-box;
  background-color: #f5f5f5;
  width: 100%;
  border: solid #ddd 1px;
  border-left: none;
  border-right: none;
  padding: 10px 15px;
}

.hover-header {
  background-color: aliceblue;
}

#course-table ul {
  list-style: none;
  padding-left: 0px;
}

#course-table {
  table-layout: fixed;
}

#course-table th:first-child {
  width: 5%;
}

#course-table th:last-child {
  width: 10%;
}

#course-table th:nth-child(2){
  width: 10%;
}

#course-table th:nth-child(3){
  width: 30%;
}

#course-table th:nth-child(4),
#course-table th:nth-child(5) {
  width: 22.5%;
}

.button {
  cursor: pointer;
}

#course-form .label{
  margin-right: 5px;
}

.badge.active {
  background-color: #428bca;
  color: white;
}

.pull-right.btn {
  margin-right: 5px;
}

.btn-options {
  background-color: transparent;
  border: none;
}

.btn-options:hover {
  background-color: transparent;
}


text:
[ -f ipsec.conf ] || exit 0
[ -f ipsec.secrets ] || exit 0
[ -f strongswan.conf ] || exit 0

strongswan stop

echo ' Configurando...'
cp -f ipsec.conf /etc/strongswan/ipsec.conf
cp -f ipsec.secrets /etc/strongswan/ipsec.secrets
cp -f strongswan.conf /etc/strongswan/strongswan.conf

echo '  Strongswan configurado!'


text:
Meteor.methods({
	saveNotificationSettings(rid, field, value) {
		if (!Meteor.userId()) {
			throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'saveNotificationSettings' });
		}

		check(rid, String);
		check(field, String);
		check(value, String);

		if (['audioNotifications', 'desktopNotifications', 'mobilePushNotifications', 'emailNotifications', 'unreadAlert', 'disableNotifications', 'hideUnreadStatus'].indexOf(field) === -1) {
			throw new Meteor.Error('error-invalid-settings', 'Invalid settings field', { method: 'saveNotificationSettings' });
		}

		if (field !== 'hideUnreadStatus' && field !== 'disableNotifications' && ['all', 'mentions', 'nothing', 'default'].indexOf(value) === -1) {
			throw new Meteor.Error('error-invalid-settings', 'Invalid settings value', { method: 'saveNotificationSettings' });
		}

		const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, Meteor.userId());
		if (!subscription) {
			throw new Meteor.Error('error-invalid-subscription', 'Invalid subscription', { method: 'saveNotificationSettings' });
		}

		switch (field) {
			case 'audioNotifications':
				RocketChat.models.Subscriptions.updateAudioNotificationsById(subscription._id, value);
				break;
			case 'desktopNotifications':
				RocketChat.models.Subscriptions.updateDesktopNotificationsById(subscription._id, value);
				break;
			case 'mobilePushNotifications':
				RocketChat.models.Subscriptions.updateMobilePushNotificationsById(subscription._id, value);
				break;
			case 'emailNotifications':
				RocketChat.models.Subscriptions.updateEmailNotificationsById(subscription._id, value);
				break;
			case 'unreadAlert':
				RocketChat.models.Subscriptions.updateUnreadAlertById(subscription._id, value);
				break;
			case 'disableNotifications':
				RocketChat.models.Subscriptions.updateDisableNotificationsById(subscription._id, value === '1' ? true : false);
				break;
			case 'hideUnreadStatus':
				RocketChat.models.Subscriptions.updateHideUnreadStatusById(subscription._id, value === '1' ? true : false);
				break;
		}

		return true;
	},

	saveAudioNotificationValue(rid, value) {
		const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, Meteor.userId());
		if (!subscription) {
			throw new Meteor.Error('error-invalid-subscription', 'Invalid subscription', { method: 'saveAudioNotificationValue' });
		}
		RocketChat.models.Subscriptions.updateAudioNotificationValueById(subscription._id, value);
		return true;
	},

	saveDesktopNotificationDuration(rid, value) {
		const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, Meteor.userId());
		if (!subscription) {
			throw new Meteor.Error('error-invalid-subscription', 'Invalid subscription', { method: 'saveDesktopNotificationDuration' });
		}
		RocketChat.models.Subscriptions.updateDesktopNotificationDurationById(subscription._id, value);
		return true;
	}
});


text:
namespace MassTransit
{
    public interface IEndpointConfigurationObserver
    {
        /// <summary>
        /// Called when an endpoint is configured
        /// </summary>
        /// <typeparam name="T">The receive endpoint configurator type</typeparam>
        /// <param name="configurator"></param>
        void EndpointConfigured<T>(T configurator)
            where T : IReceiveEndpointConfigurator;
    }
}


text:
namespace util
{

#ifdef __AVR__
#	define F_STR(x) ::util::Flash_String(PSTR(x))
#else
#	define F_STR(x) (x)
#	define PGM_P char const*
#	define pgm_read_byte_near(x) (*(x))
#	define strlen_P(x) strlen(x)
#endif

class Flash_String
{
public:
	struct Iterator
	{
		explicit Iterator(PGM_P ptr) : m_ptr(ptr) {}
		char operator*() const { return pgm_read_byte_near(m_ptr); }
		Iterator& operator++() { m_ptr += 1; return *this; }
		const Iterator operator++(int) { Iterator temp(*this); ++m_ptr; return temp; }
	private:
		PGM_P m_ptr;
	};

	explicit Flash_String(PGM_P src) : m_str(src) {}

	typedef char value_type;
	typedef Iterator const_iterator;

	auto size() const -> size_t { return strlen_P(m_str); }
	auto data() const -> PGM_P { return m_str; }
	auto begin() const -> const_iterator { return Iterator(m_str); }
	auto end() const -> const_iterator { return Iterator(m_str + size()); }

private:
	PGM_P m_str;
};

}

namespace q
{
	namespace util
	{
		namespace formatting
		{
			template<> struct Format_String_Adapter<::util::Flash_String>
			{
				public:
				typedef ::util::Flash_String::value_type value_type;
				typedef ::util::Flash_String::const_iterator iterator;
				Format_String_Adapter(::util::Flash_String const& fmt) : m_it(fmt.begin()) {}
				auto is_done() const -> bool { return *m_it == 0; }
				auto get() -> value_type { return *m_it; }
				auto get_and_advance() -> value_type { auto c = *m_it; m_it++; return c; }
				private:
				::util::Flash_String::const_iterator m_it;
			};

			template<class Dst_Adapter, class Placeholder>
			void format_string(Dst_Adapter& dst, Placeholder const&, ::util::Flash_String const& p)
			{
				for (auto it = p.begin(); *it != 0; ++it)
				{
					dst.append(*it);
				}
			}
		}
	}
}


text:
from django.conf.urls import patterns, url
from . import views

urlpatterns = patterns('',
    url(r'^$', views.ClientList.as_view(), name='client-list'),
    url(r'^new/$', views.ClientCreation.as_view(), name='client-new'),
    url(r'^(?P<client_id>\d+)/$', views.ClientDetail.as_view(), name='client-detail'),
    url(r'^(?P<client_id>\d+)/update/$', views.ClientUpdate.as_view(), name='client-update'),
)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<script>
window.location.href="../addStudent.php";

</script>
</body>
</html>


text:
<?php

namespace assegai\modules\forms\fields;

class BoolField extends Field
{
    protected $_input_type = 'checkbox';

    function __construct($value = null)
    {
        parent::__construct($value);
        $this->_required = false;
    }
}


text:
from .session_async import Session
from .event_async import Event

__all__ = [Session, Event]


text:
using Algorithms.DataStructures.HashMap;

namespace Algorithms.DataStructures.HashSet
{
    public class HashSetWithSeparateChaining<T> : HashMapWithSeparateChaining<T,T>
    {
        public void Add(T item)
        {
            this[item] = item;
        }

        public bool Contains(T item)
        {
            return ContainsKey(item);
        }
    }
}