text:
__all__ = []

# The following pattern is used below for importing sub-modules:
#
# 1. "from foo import *".  This imports all the names from foo.__all__ into
#    this module. But, this does not put those names into the __all__ of
#    this module. This enables "from sympy.physics.quantum import State" to
#    work.
# 2. "import foo; __all__.extend(foo.__all__)". This adds all the names in
#    foo.__all__ to the __all__ of this module. The names in __all__
#    determine which names are imported when
#    "from sympy.physics.quantum import *" is done.

import anticommutator
from anticommutator import *
__all__.extend(anticommutator.__all__)

import applyops
from applyops import *
__all__.extend(applyops.__all__)

import commutator
from commutator import *
__all__.extend(commutator.__all__)

import dagger
from dagger import *
__all__.extend(dagger.__all__)

import hilbert
from hilbert import *
__all__.extend(hilbert.__all__)

import innerproduct
from innerproduct import *
__all__.extend(innerproduct.__all__)

import kronecker
from kronecker import *
__all__.extend(kronecker.__all__)

import operator
from operator import *
__all__.extend(operator.__all__)

import represent as repmod
from represent import *
__all__.extend(repmod.__all__)

import state
from state import *
__all__.extend(state.__all__)

import tensorproduct
from tensorproduct import *
__all__.extend(tensorproduct.__all__)

import constants
from constants import *
__all__.extend(constants.__all__)


text:
    {% include search_form.html %}

Getting Started

            Prerequisites for Installing TabMon

            Installing TabMon

            Upgrading from a Previous Version of TabMon

            Configuring TabMon

Using TabMon

            Using TabMon

            FAQ/Troubleshooting

Reference

            Appendix A: Additional Installation Instructions

redpajama_set_name: RedPajamaGithub


text:
package com.linkedin.bowser.core.exceptions;

/**
 * Represents the 'base' exception for all runtime eval errors (i.e., type error,
 * subscript error). This exception contains no information about the Expn which invoked
 * the eval in question
 *
 * @author sdawson
 */
public abstract class EvalError extends RuntimeException
{
  private static final long serialVersionUID = 1L;

  public EvalError()
  {
    super();
  }

  public EvalError(String message, Throwable cause)
  {
    super(message, cause);
  }

  public EvalError(String message)
  {
    super(message);
  }

  public EvalError(Throwable cause)
  {
    super(cause);
  }
}


text:
package moe.akagi.chibaproject.card;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import de.hdodenhof.circleimageview.CircleImageView;
import it.gmariotti.cardslib.library.internal.Card;
import moe.akagi.chibaproject.R;

/**
 * Created by yunze on 12/10/15.
 */
public class FriendCardListItem extends Card{
    private Context mContext;

    protected CircleImageView personImage;
    protected TextView nicknameTextView;
    protected int imageResId;
    protected String nickname;

    public FriendCardListItem(Context context) {
        this(context, R.layout.friend_list_item_content);
        mContext = context;
        imageResId = 0;
        nickname = "Nickname";
    }

    public FriendCardListItem(Context context, int innerLayout) {
        super(context, innerLayout);
    }

    @Override
    public void setupInnerViewElements(ViewGroup parent, View view) {
        personImage = (CircleImageView) parent.findViewById(R.id.friend_activity_card_item_image);
        nicknameTextView = (TextView) parent.findViewById(R.id.friend_activity_card_item_nickname);

        if (personImage != null) {
            if (imageResId != 0) {
                personImage.setImageResource(imageResId);
            }
        }

        if (nicknameTextView != null) {
            nicknameTextView.setText(nickname);
        }
    }

    public void setImageResId(int imageResId) {
        this.imageResId = imageResId;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
}


text:
import sqlite3

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print(cur.fetchone()["a"])


text:
IRC::Plugins.register(:eightball) do
  ANSWERS = ["yes", "no", "outlook not so good", "all signs point to yes", "all signs point to no", "why the hell are you asking me?", "the answer is unclear"]

  def respond(options)
    return IRC::chat_action(recipient, "shakes the magic 8-ball... #{ANSWERS.sample()}")
  end
end


text:
#ifndef unwind_i_h
#define unwind_i_h

#include <stdint.h>

#include <libunwind-hppa.h>

#include "libunwind_i.h"

#define hppa_lock			UNW_OBJ(lock)
#define hppa_local_resume		UNW_OBJ(local_resume)
#define hppa_local_addr_space_init	UNW_OBJ(local_addr_space_init)
#define hppa_scratch_loc		UNW_OBJ(scratch_loc)
#define setcontext			UNW_ARCH_OBJ (setcontext)

extern void hppa_local_addr_space_init (void);
extern int hppa_local_resume (unw_addr_space_t as, unw_cursor_t *cursor,
			      void *arg);
extern dwarf_loc_t hppa_scratch_loc (struct cursor *c, unw_regnum_t reg);
extern int setcontext (const ucontext_t *ucp);

#endif /* unwind_i_h */


text:
package com.jxd.android.bookinventtory.utils;

import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

/**
 * 打开或关闭软键盘
 * Created by Administrator on 2017/10/11.
 */

public class KeyWordUtil {
    /**
     * 打卡软键盘
     *
     * @param mEditText
     *            输入框
     * @param mContext
     *            上下文
     */
    public static void openKeybord(EditText mEditText, Context mContext){
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    /**
     * 关闭软键盘
     *
     * @param mEditText
     *            输入框
     * @param mContext
     *            上下文
     */
    public static void closeKeybord(EditText mEditText, Context mContext) {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }
}


text:
package io.prometheus.client.spring.boot;

import io.prometheus.client.Collector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.PublicMetrics;
import org.springframework.boot.actuate.metrics.Metric;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 *
Spring boot metrics integration for Prometheus exporter.

 *
 *
{@literal @}Bean
 * public SpringBootMetricsCollector springBootMetricsCollector(Collection{@literal <}PublicMetrics{@literal >} publicMetrics) {
 *   SpringBootMetricsCollector springBootMetricsCollector = new SpringBootMetricsCollector(publicMetrics);
 *   springBootMetricsCollector.register();
 *   return springBootMetricsCollector;
 * }
 *

 */
@Component
public class SpringBootMetricsCollector extends Collector {
  private final Collection<PublicMetrics> publicMetrics;

  @Autowired
  public SpringBootMetricsCollector(Collection<PublicMetrics> publicMetrics) {
    this.publicMetrics = publicMetrics;
  }

  @Override
  public List<MetricFamilySamples> collect() {
    ArrayList<MetricFamilySamples> samples = new ArrayList<MetricFamilySamples>();
    for (PublicMetrics publicMetrics : this.publicMetrics) {
      for (Metric<?> metric : publicMetrics.metrics()) {
        String name = Collector.sanitizeMetricName(metric.getName());
        double value = metric.getValue().doubleValue();
        MetricFamilySamples metricFamilySamples = new MetricFamilySamples(
                name, Type.GAUGE, name, Collections.singletonList(
                new MetricFamilySamples.Sample(name, new ArrayList<String>(), new ArrayList<String>(), value)));
        samples.add(metricFamilySamples);
      }
    }
    return samples;
  }
}


text:
server "alpha.forset.ge", :web, :app, :db, primary: true # server where app is located
set :application, "Hours" # unique name of application
set :user, "deploy"# name of user on server
set :ngnix_conf_file_loc, "production/nginx.conf" # location of nginx conf file
set :unicorn_init_file_loc, "production/unicorn_init.sh" # location of unicor init shell file
set :github_account_name, "ForSetGeorgia" # name of accout on git hub
set :github_repo_name, "Hours" # name of git hub repo
set :git_branch_name, "master" # name of branch to deploy
set :rails_env, "production" # name of environment: production, staging, ...
##################################


text:
001
017
018    package org.apache.commons.configuration.web;
019
020    import java.util.Iterator;
021    import javax.servlet.Servlet;
022    import javax.servlet.ServletContext;
023
024    import org.apache.commons.collections.iterators.EnumerationIterator;
025
026    /**
027     * A configuration wrapper to read the initialization parameters of a servlet
028     * context. This configuration is read only, adding or removing a property will
029     * throw an UnsupportedOperationException.
030     *
031     * @author <a href="mailto:ebourg@apache.org">Emmanuel Bourg</a>
032     * @version $Revision: 515306 $, $Date: 2007-03-06 22:15:00 +0100 (Di, 06. Mrz 2007) $
033     * @since 1.1
034     */
035    public class ServletContextConfiguration extends BaseWebConfiguration
036    {
037        /** Stores the wrapped servlet context.*/
038        protected ServletContext context;
039
040        /**
041         * Create a ServletContextConfiguration using the context of
042         * the specified servlet.
043         *
044         * @param servlet the servlet
045         */
046        public ServletContextConfiguration(Servlet servlet)
047        {
048            this.context = servlet.getServletConfig().getServletContext();
049        }
050
051        /**
052         * Create a ServletContextConfiguration using the servlet context
053         * initialization parameters.
054         *
055         * @param context the servlet context
056         */
057        public ServletContextConfiguration(ServletContext context)
058        {
059            this.context = context;
060        }
061
062        public Object getProperty(String key)
063        {
064            return handleDelimiters(context.getInitParameter(key));
065        }
066
067        public Iterator getKeys()
068        {
069            return new EnumerationIterator(context.getInitParameterNames());
070        }
071    }


text:
using System;
using System.Linq;
using Microsoft.Azure.Management.DataFactories.Models;

namespace Microsoft.Azure.Management.DataFactories.Models
{
    /// <summary>
    /// Linked Service for Teradata data source.
    /// </summary>
    public partial class OnPremisesHdfsLinkedService : LinkedServiceProperties
    {
        private string _authenticationType;

        /// <summary>
        /// Required. Gets or sets authenticationType to be used for connection.
        /// </summary>
        public string AuthenticationType
        {
            get { return this._authenticationType; }
            set { this._authenticationType = value; }
        }

        private string _contentType;

        /// <summary>
        /// Optional. Gets or sets hint to content type
        /// </summary>
        public string ContentType
        {
            get { return this._contentType; }
            set { this._contentType = value; }
        }

        private string _encryptedCredential;

        /// <summary>
        /// Optional. Gets or sets the encryptedCredential for authentication.
        /// </summary>
        public string EncryptedCredential
        {
            get { return this._encryptedCredential; }
            set { this._encryptedCredential = value; }
        }

        private string _gatewayName;

        /// <summary>
        /// Required. Gets or sets the on-premises gateway name.
        /// </summary>
        public string GatewayName
        {
            get { return this._gatewayName; }
            set { this._gatewayName = value; }
        }

        private string _password;

        /// <summary>
        /// Optional. Gets or sets password for authentication.
        /// </summary>
        public string Password
        {
            get { return this._password; }
            set { this._password = value; }
        }

        private string _url;

        /// <summary>
        /// Required. Gets or sets HDFS url.
        /// </summary>
        public string Url
        {
            get { return this._url; }
            set { this._url = value; }
        }

        private string _username;

        /// <summary>
        /// Optional. Gets or sets username for authentication.
        /// </summary>
        public string Username
        {
            get { return this._username; }
            set { this._username = value; }
        }

        /// <summary>
        /// Initializes a new instance of the OnPremisesHdfsLinkedService class.
        /// </summary>
        public OnPremisesHdfsLinkedService()
        {
        }

        /// <summary>
        /// Initializes a new instance of the OnPremisesHdfsLinkedService class
        /// with required arguments.
        /// </summary>
        public OnPremisesHdfsLinkedService(string url, string authenticationType, string gatewayName)
            : this()
        {
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }
            if (authenticationType == null)
            {
                throw new ArgumentNullException("authenticationType");
            }
            if (gatewayName == null)
            {
                throw new ArgumentNullException("gatewayName");
            }
            this.Url = url;
            this.AuthenticationType = authenticationType;
            this.GatewayName = gatewayName;
        }
    }
}


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

import com.facebook.presto.connector.ConnectorId;
import com.facebook.presto.connector.informationSchema.InformationSchemaConnector;
import com.facebook.presto.connector.system.SystemConnector;
import com.facebook.presto.metadata.Catalog;
import com.facebook.presto.metadata.CatalogManager;
import com.facebook.presto.metadata.InMemoryNodeManager;
import com.facebook.presto.metadata.MetadataManager;
import com.facebook.presto.metadata.QualifiedObjectName;
import com.facebook.presto.spi.CatalogSchemaTableName;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.SchemaTableName;
import com.facebook.presto.spi.connector.Connector;
import com.facebook.presto.spi.connector.ConnectorAccessControl;
import com.facebook.presto.spi.connector.ConnectorTransactionHandle;
import com.facebook.presto.spi.security.Identity;
import com.facebook.presto.spi.security.Privilege;
import com.facebook.presto.spi.security.SystemAccessControl;
import com.facebook.presto.spi.security.SystemAccessControlFactory;
import com.facebook.presto.testing.TestingConnectorContext;
import com.facebook.presto.tpch.TpchConnectorFactory;
import com.facebook.presto.transaction.TransactionManager;
import com.google.common.collect.ImmutableMap;
import org.testng.annotations.Test;

import java.security.Principal;
import java.util.Map;
import java.util.Optional;

import static com.facebook.presto.connector.ConnectorId.createInformationSchemaConnectorId;
import static com.facebook.presto.connector.ConnectorId.createSystemTablesConnectorId;
import static com.facebook.presto.security.AccessControlManager.ALLOW_ALL_ACCESS_CONTROL;
import static com.facebook.presto.spi.security.AccessDeniedException.denySelectTable;
import static com.facebook.presto.transaction.TransactionBuilder.transaction;
import static com.facebook.presto.transaction.TransactionManager.createTestTransactionManager;
import static java.util.Objects.requireNonNull;
import static org.testng.Assert.assertEquals;

public class TestAccessControlManager
{
    private static final Principal PRINCIPAL = new TestingPrincipal("principal");
    private static final String USER_NAME = "user_name";

    @Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = "Presto server is still initializing")
    public void testInitializing()
            throws Exception
    {
        AccessControlManager accessControlManager = new AccessControlManager(createTestTransactionManager());
        accessControlManager.checkCanSetUser(null, "foo");
    }

    @Test
    public void testNoneSystemAccessControl()
            throws Exception
    {
        AccessControlManager accessControlManager = new AccessControlManager(createTestTransactionManager());
        accessControlManager.setSystemAccessControl(ALLOW_ALL_ACCESS_CONTROL, ImmutableMap.<String, String>of());
        accessControlManager.checkCanSetUser(null, USER_NAME);
    }

    @Test
    public void testSetAccessControl()
            throws Exception
    {
        AccessControlManager accessControlManager = new AccessControlManager(createTestTransactionManager());

        TestSystemAccessControlFactory accessControlFactory = new TestSystemAccessControlFactory("test");
        accessControlManager.addSystemAccessControlFactory(accessControlFactory);
        accessControlManager.setSystemAccessControl("test", ImmutableMap.of());

        accessControlManager.checkCanSetUser(PRINCIPAL, USER_NAME);
        assertEquals(accessControlFactory.getCheckedUserName(), USER_NAME);
        assertEquals(accessControlFactory.getCheckedPrincipal(), PRINCIPAL);
    }

    @Test
    public void testNoCatalogAccessControl()
            throws Exception
    {
        TransactionManager transactionManager = createTestTransactionManager();
        AccessControlManager accessControlManager = new AccessControlManager(transactionManager);

        TestSystemAccessControlFactory accessControlFactory = new TestSystemAccessControlFactory("test");
        accessControlManager.addSystemAccessControlFactory(accessControlFactory);
        accessControlManager.setSystemAccessControl("test", ImmutableMap.of());

        transaction(transactionManager, accessControlManager)
                .execute(transactionId -> {
                    accessControlManager.checkCanSelectFromTable(transactionId, new Identity(USER_NAME, Optional.of(PRINCIPAL)), new QualifiedObjectName("catalog", "schema", "table"));
                });
    }

    @Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = "Access Denied: Cannot select from table schema.table")
    public void testDenyCatalogAccessControl()
            throws Exception
    {
        CatalogManager catalogManager = new CatalogManager();
        TransactionManager transactionManager = createTestTransactionManager(catalogManager);
        AccessControlManager accessControlManager = new AccessControlManager(transactionManager);

        TestSystemAccessControlFactory accessControlFactory = new TestSystemAccessControlFactory("test");
        accessControlManager.addSystemAccessControlFactory(accessControlFactory);
        accessControlManager.setSystemAccessControl("test", ImmutableMap.of());

        ConnectorId connectorId = registerBogusConnector(catalogManager, transactionManager, "catalog");
        accessControlManager.addCatalogAccessControl(connectorId, new DenyConnectorAccessControl());

        transaction(transactionManager, accessControlManager)
                .execute(transactionId -> {
                    accessControlManager.checkCanSelectFromTable(transactionId, new Identity(USER_NAME, Optional.of(PRINCIPAL)), new QualifiedObjectName("catalog", "schema", "table"));
                });
    }

    @Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = "Access Denied: Cannot select from table secured_catalog.schema.table")
    public void testDenySystemAccessControl()
            throws Exception
    {
        CatalogManager catalogManager = new CatalogManager();
        TransactionManager transactionManager = createTestTransactionManager(catalogManager);
        AccessControlManager accessControlManager = new AccessControlManager(transactionManager);

        TestSystemAccessControlFactory accessControlFactory = new TestSystemAccessControlFactory("test");
        accessControlManager.addSystemAccessControlFactory(accessControlFactory);
        accessControlManager.setSystemAccessControl("test", ImmutableMap.of());

        registerBogusConnector(catalogManager, transactionManager, "connector");
        accessControlManager.addCatalogAccessControl(new ConnectorId("connector"), new DenyConnectorAccessControl());

        transaction(transactionManager, accessControlManager)
                .execute(transactionId -> {
                    accessControlManager.checkCanSelectFromTable(transactionId, new Identity(USER_NAME, Optional.of(PRINCIPAL)), new QualifiedObjectName("secured_catalog", "schema", "table"));
                });
    }

    private static ConnectorId registerBogusConnector(CatalogManager catalogManager, TransactionManager transactionManager, String catalogName)
    {
        ConnectorId connectorId = new ConnectorId(catalogName);
        Connector connector = new TpchConnectorFactory().create(catalogName, ImmutableMap.of(), new TestingConnectorContext());

        InMemoryNodeManager nodeManager = new InMemoryNodeManager();
        MetadataManager metadata = MetadataManager.createTestMetadataManager(catalogManager);
        ConnectorId systemId = createSystemTablesConnectorId(connectorId);
        catalogManager.registerCatalog(new Catalog(
                catalogName,
                connectorId,
                connector,
                createInformationSchemaConnectorId(connectorId),
                new InformationSchemaConnector(catalogName, nodeManager, metadata),
                systemId,
                new SystemConnector(
                        systemId,
                        nodeManager,
                        connector.getSystemTables(),
                        transactionId -> transactionManager.getConnectorTransaction(transactionId, connectorId))));

        return connectorId;
    }

    private static class TestSystemAccessControlFactory
            implements SystemAccessControlFactory
    {
        private final String name;
        private Map<String, String> config;

        private Principal checkedPrincipal;
        private String checkedUserName;

        public TestSystemAccessControlFactory(String name)
        {
            this.name = requireNonNull(name, "name is null");
        }

        public Map<String, String> getConfig()
        {
            return config;
        }

        public Principal getCheckedPrincipal()
        {
            return checkedPrincipal;
        }

        public String getCheckedUserName()
        {
            return checkedUserName;
        }

        @Override
        public String getName()
        {
            return name;
        }

        @Override
        public SystemAccessControl create(Map<String, String> config)
        {
            this.config = config;
            return new SystemAccessControl()
            {
                @Override
                public void checkCanSetUser(Principal principal, String userName)
                {
                    checkedPrincipal = principal;
                    checkedUserName = userName;
                }

                @Override
                public void checkCanSetSystemSessionProperty(Identity identity, String propertyName)
                {
                    throw new UnsupportedOperationException();
                }

                @Override
                public void checkCanSelectFromTable(Identity identity, CatalogSchemaTableName table)
                {
                    if (table.getCatalogName().equals("secured_catalog")) {
                        denySelectTable(table.toString());
                    }
                }
            };
        }
    }

    private static class DenyConnectorAccessControl
            implements ConnectorAccessControl
    {
        @Override
        public void checkCanSelectFromTable(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName tableName)
        {
            denySelectTable(tableName.toString());
        }

        @Override
        public void checkCanCreateSchema(ConnectorTransactionHandle transactionHandle, Identity identity, String schemaName)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void checkCanDropSchema(ConnectorTransactionHandle transactionHandle, Identity identity, String schemaName)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void checkCanRenameSchema(ConnectorTransactionHandle transactionHandle, Identity identity, String schemaName, String newSchemaName)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void checkCanCreateTable(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName tableName)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void checkCanDropTable(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName tableName)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void checkCanRenameTable(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName tableName, SchemaTableName newTableName)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void checkCanAddColumn(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName tableName)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void checkCanRenameColumn(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName tableName)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void checkCanInsertIntoTable(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName tableName)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void checkCanDeleteFromTable(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName tableName)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void checkCanCreateView(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName viewName)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void checkCanDropView(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName viewName)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void checkCanSelectFromView(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName viewName)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void checkCanCreateViewWithSelectFromTable(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName tableName)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void checkCanCreateViewWithSelectFromView(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName viewName)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void checkCanSetCatalogSessionProperty(Identity identity, String propertyName)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void checkCanGrantTablePrivilege(ConnectorTransactionHandle transactionHandle, Identity identity, Privilege privilege, SchemaTableName tableName)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void checkCanRevokeTablePrivilege(ConnectorTransactionHandle transactionHandle, Identity identity, Privilege privilege, SchemaTableName tableName)
        {
            throw new UnsupportedOperationException();
        }
    }
}


text:
var decorate = require('../lib/functions').decorate;

function dec1(func, arg1, arg2) {
  return (arg1 || 'a') + func(arg1, arg2) + (arg2 || 'f');
}

function dec2(func, arg1, arg2) {
  return (arg1 || 'b') + func(arg1, arg2) + (arg2 || 'e');
}

function foo(arg1, arg2) {
  return (arg1 || 'c') + (arg2 || 'd');
}

// Actual tests
describe('functions.decorate', function() {

  var decorated1 = decorate(foo, dec1);
  var decorated2 = decorate(foo, dec1, dec2);

  it('should work correctly without arguments', function() {
    decorated1().should.equal('acdf')
    decorated2().should.equal('bacdfe')
  });

  it('should work correctly with arguments', function() {
    decorated1('x', 'y').should.equal('xxyy')
    decorated2('y', 'x').should.equal('yyyxxx')
  });

});


text:
Database: Dropping collections (memory test)
--SKIPIF--
<?php require_once dirname(__FILE__) ."/skipif.inc"; ?>
--FILE--
<?php
require_once dirname(__FILE__) . "/../utils.inc";
$a = mongo();
$d = $a->selectDb("phpunit");
$ns = $d->selectCollection('system.namespaces');

// drop the collection 100 times
$u = memory_get_usage(true);
for ($i = 0; $i < 100; $i++) {
	$d->dropCollection($d->dropcoltest);
}
var_dump($u - memory_get_usage(true));

// drop the collection 100 times
$u = memory_get_usage(true);
for ($i = 0; $i < 100; $i++) {
	$d->dropCollection('dropcoltest');
}
var_dump($u - memory_get_usage(true));

?>
--EXPECT--
int(0)
int(0)


text:
namespace Google.Cloud.ApigeeRegistry.V1.Snippets
{
    // [START apigeeregistry_v1_generated_Registry_ListArtifacts_async_flattened_resourceNames5]
    using Google.Api.Gax;
    using Google.Cloud.ApigeeRegistry.V1;
    using System;
    using System.Linq;
    using System.Threading.Tasks;

    public sealed partial class GeneratedRegistryClientSnippets
    {
        /// <summary>Snippet for ListArtifactsAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task ListArtifactsResourceNames5Async()
        {
            // Create client
            RegistryClient registryClient = await RegistryClient.CreateAsync();
            // Initialize request argument(s)
            ApiDeploymentName parent = ApiDeploymentName.FromProjectLocationApiDeployment("[PROJECT]", "[LOCATION]", "[API]", "[DEPLOYMENT]");
            // Make the request
            PagedAsyncEnumerable<ListArtifactsResponse, Artifact> response = registryClient.ListArtifactsAsync(parent);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((Artifact item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((ListArtifactsResponse page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Artifact item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<Artifact> singlePage = await response.ReadPageAsync(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (Artifact item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }
    // [END apigeeregistry_v1_generated_Registry_ListArtifacts_async_flattened_resourceNames5]
}


text:
package consulo.container.impl;

import consulo.container.classloader.PluginClassLoader;
import consulo.container.plugin.PluginDescriptor;
import consulo.container.plugin.PluginId;
import consulo.container.plugin.PluginManager;
import consulo.container.plugin.internal.PluginManagerInternal;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.File;
import java.util.List;

/**
 * @author VISTALL
 * @since 2019-07-25
 */
public class PluginManagerInternalImpl implements PluginManagerInternal {

  @Nonnull
  @Override
  public List<PluginDescriptor> getPlugins() {
    return PluginHolderModificator.getPlugins();
  }

  @Override
  public boolean isInitialized() {
    return PluginHolderModificator.isInitialized();
  }

  @Nullable
  @Override
  public File getPluginPath(@Nonnull Class<?> pluginClass) {
    ClassLoader temp = pluginClass.getClassLoader();
    assert temp instanceof PluginClassLoader : "classloader is not plugin";
    PluginClassLoader classLoader = (PluginClassLoader)temp;
    PluginId pluginId = classLoader.getPluginId();
    PluginDescriptor plugin = PluginManager.findPlugin(pluginId);
    assert plugin != null : "plugin is not found";
    return plugin.getPath();
  }

  @Nullable
  @Override
  public PluginDescriptor getPlugin(@Nonnull Class<?> pluginClass) {
    ClassLoader temp = pluginClass.getClassLoader();
    if (!(temp instanceof PluginClassLoader)) {
      return null;
    }
    return ((PluginClassLoader)temp).getPluginDescriptor();
  }

  @Nonnull
  @Override
  public List<String> getDisabledPlugins() {
    return PluginValidator.getDisabledPlugins();
  }

  @Override
  public boolean shouldSkipPlugin(@Nonnull PluginDescriptor descriptor) {
    return PluginValidator.shouldSkipPlugin(descriptor);
  }

  @Override
  public PluginManager.PluginSkipReason calcPluginSkipReason(PluginDescriptor descriptor) {
    return PluginValidator.calcPluginSkipReason(descriptor);
  }

  @Override
  public boolean disablePlugin(String id) {
    return PluginValidator.disablePlugin(id);
  }

  @Override
  public boolean enablePlugin(String id) {
    return PluginValidator.enablePlugin(id);
  }

  @Override
  public void replaceDisabledPlugins(List<String> ids) {
    PluginValidator.replaceDisabledPlugins(ids);
  }
}


text:
<!DOCTYPE html>

		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Tracking Chrome App</title>
		<meta name="description" content="Chrome Tracking App by Descartes" />
		<meta name="keywords" content="Descartes, Tracking, Chrome App, Web Tracking" />
		<meta name="author" content="Haralambos Yokos" />
		<link rel="shortcut icon" href="assets/icons/favicon.ico">
		<link rel="stylesheet" type="text/css" href="assets/expandingsearch/css/default.css" />
		<link rel="stylesheet" type="text/css" href="assets/expandingsearch/css/component.css" />
		<link rel="stylesheet" type="text/css" href="assets/youtubemenu/css/component.css" />

Descartes Chrome ApplicationQuick Search for Shipment Tracking

Use the search to the right to start immedietly. Or click the icon below for more options.

						<form>
							<input class="sb-search-input" placeholder="Enter your search term..." type="text" value="" name="search" id="search">
							<input class="sb-search-submit" type="submit" value="">

						</form>

Options

Log In

Barcode Search

Favorites

Contact Support

Downloads

Settings

Logout


text:
package org.apache.camel.component.kafka;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.camel.AsyncCallback;
import org.apache.camel.CamelException;
import org.apache.camel.CamelExchangeException;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.impl.DefaultAsyncProducer;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.utils.Bytes;

public class KafkaProducer extends DefaultAsyncProducer {

    private org.apache.kafka.clients.producer.KafkaProducer kafkaProducer;
    private final KafkaEndpoint endpoint;
    private ExecutorService workerPool;
    private boolean shutdownWorkerPool;

    public KafkaProducer(KafkaEndpoint endpoint) {
        super(endpoint);
        this.endpoint = endpoint;
    }

    Properties getProps() {
        Properties props = endpoint.getConfiguration().createProducerProperties();
        endpoint.updateClassProperties(props);

        // brokers can be configured on endpoint or component level
        String brokers = endpoint.getConfiguration().getBrokers();
        if (brokers == null) {
            brokers = endpoint.getComponent().getBrokers();
        }
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers);

        return props;
    }

    public org.apache.kafka.clients.producer.KafkaProducer getKafkaProducer() {
        return kafkaProducer;
    }

    /**
     * To use a custom {@link org.apache.kafka.clients.producer.KafkaProducer} instance.
     */
    public void setKafkaProducer(org.apache.kafka.clients.producer.KafkaProducer kafkaProducer) {
        this.kafkaProducer = kafkaProducer;
    }

    public ExecutorService getWorkerPool() {
        return workerPool;
    }

    public void setWorkerPool(ExecutorService workerPool) {
        this.workerPool = workerPool;
    }

    @Override
    protected void doStart() throws Exception {
        Properties props = getProps();
        if (kafkaProducer == null) {
            ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader();
            try {
                // Kafka uses reflection for loading authentication settings, use its classloader
                Thread.currentThread().setContextClassLoader(org.apache.kafka.clients.producer.KafkaProducer.class.getClassLoader());
                kafkaProducer = new org.apache.kafka.clients.producer.KafkaProducer(props);
            } finally {
                Thread.currentThread().setContextClassLoader(threadClassLoader);
            }
        }

        // if we are in asynchronous mode we need a worker pool
        if (!endpoint.isSynchronous() && workerPool == null) {
            workerPool = endpoint.createProducerExecutor();
            // we create a thread pool so we should also shut it down
            shutdownWorkerPool = true;
        }
    }

    @Override
    protected void doStop() throws Exception {
        if (kafkaProducer != null) {
            kafkaProducer.close();
        }

        if (shutdownWorkerPool && workerPool != null) {
            endpoint.getCamelContext().getExecutorServiceManager().shutdown(workerPool);
            workerPool = null;
        }
    }

    @SuppressWarnings("unchecked")
    protected Iterator<ProducerRecord> createRecorder(Exchange exchange) throws CamelException {
        String topic = endpoint.getConfiguration().getTopic();

        if (!endpoint.getConfiguration().isBridgeEndpoint()) {
            String headerTopic = exchange.getIn().getHeader(KafkaConstants.TOPIC, String.class);
            boolean allowHeader = true;

            // when we do not bridge then detect if we try to send back to ourselves
            // which we most likely do not want to do
            if (headerTopic != null && endpoint.getConfiguration().isCircularTopicDetection()) {
                Endpoint from = exchange.getFromEndpoint();
                if (from instanceof KafkaEndpoint) {
                    String fromTopic = ((KafkaEndpoint) from).getConfiguration().getTopic();
                    allowHeader = !headerTopic.equals(fromTopic);
                    if (!allowHeader) {
                        log.debug("Circular topic detected from message header."
                            + " Cannot send to same topic as the message comes from: {}"
                            + ". Will use endpoint configured topic: {}", from, topic);
                    }
                }
            }
            if (allowHeader && headerTopic != null) {
                topic = headerTopic;
            }
        }

        if (topic == null) {
            throw new CamelExchangeException("No topic key set", exchange);
        }

        // endpoint take precedence over header configuration
        final Integer partitionKey = endpoint.getConfiguration().getPartitionKey() != null
            ? endpoint.getConfiguration().getPartitionKey() : exchange.getIn().getHeader(KafkaConstants.PARTITION_KEY, Integer.class);
        final boolean hasPartitionKey = partitionKey != null;

        // endpoint take precedence over header configuration
        Object key = endpoint.getConfiguration().getKey() != null
            ? endpoint.getConfiguration().getKey() : exchange.getIn().getHeader(KafkaConstants.KEY);
        final Object messageKey = key != null
            ? tryConvertToSerializedType(exchange, key, endpoint.getConfiguration().getKeySerializerClass()) : null;
        final boolean hasMessageKey = messageKey != null;

        Object msg = exchange.getIn().getBody();

        // is the message body a list or something that contains multiple values
        Iterator<Object> iterator = null;
        if (msg instanceof Iterable) {
            iterator = ((Iterable<Object>)msg).iterator();
        } else if (msg instanceof Iterator) {
            iterator = (Iterator<Object>)msg;
        }
        if (iterator != null) {
            final Iterator<Object> msgList = iterator;
            final String msgTopic = topic;
            return new Iterator<ProducerRecord>() {
                @Override
                public boolean hasNext() {
                    return msgList.hasNext();
                }

                @Override
                public ProducerRecord next() {
                    // must convert each entry of the iterator into the value according to the serializer
                    Object next = msgList.next();
                    Object value = tryConvertToSerializedType(exchange, next, endpoint.getConfiguration().getSerializerClass());

                    if (hasPartitionKey && hasMessageKey) {
                        return new ProducerRecord(msgTopic, partitionKey, key, value);
                    } else if (hasMessageKey) {
                        return new ProducerRecord(msgTopic, key, value);
                    } else {
                        return new ProducerRecord(msgTopic, value);
                    }
                }

                @Override
                public void remove() {
                    msgList.remove();
                }
            };
        }

        // must convert each entry of the iterator into the value according to the serializer
        Object value = tryConvertToSerializedType(exchange, msg, endpoint.getConfiguration().getSerializerClass());

        ProducerRecord record;
        if (hasPartitionKey && hasMessageKey) {
            record = new ProducerRecord(topic, partitionKey, key, value);
        } else if (hasMessageKey) {
            record = new ProducerRecord(topic, key, value);
        } else {
            record = new ProducerRecord(topic, value);
        }
        return Collections.singletonList(record).iterator();
    }

    @Override
    @SuppressWarnings("unchecked")
    // Camel calls this method if the endpoint isSynchronous(), as the KafkaEndpoint creates a SynchronousDelegateProducer for it
    public void process(Exchange exchange) throws Exception {
        Iterator<ProducerRecord> c = createRecorder(exchange);
        List<Future<RecordMetadata>> futures = new LinkedList<Future<RecordMetadata>>();
        List<RecordMetadata> recordMetadatas = new ArrayList<RecordMetadata>();

        if (endpoint.getConfiguration().isRecordMetadata()) {
            if (exchange.hasOut()) {
                exchange.getOut().setHeader(KafkaConstants.KAFKA_RECORDMETA, recordMetadatas);
            } else {
                exchange.getIn().setHeader(KafkaConstants.KAFKA_RECORDMETA, recordMetadatas);
            }
        }

        while (c.hasNext()) {
            ProducerRecord rec = c.next();
            if (log.isDebugEnabled()) {
                log.debug("Sending message to topic: {}, partition: {}, key: {}", rec.topic(), rec.partition(), rec.key());
            }
            futures.add(kafkaProducer.send(rec));
        }
        for (Future<RecordMetadata> f : futures) {
            //wait for them all to be sent
            recordMetadatas.add(f.get());
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public boolean process(Exchange exchange, AsyncCallback callback) {
        try {
            Iterator<ProducerRecord> c = createRecorder(exchange);
            KafkaProducerCallBack cb = new KafkaProducerCallBack(exchange, callback);
            while (c.hasNext()) {
                cb.increment();
                ProducerRecord rec = c.next();
                if (log.isDebugEnabled()) {
                    log.debug("Sending message to topic: {}, partition: {}, key: {}", rec.topic(), rec.partition(), rec.key());
                }
                kafkaProducer.send(rec, cb);
            }
            return cb.allSent();
        } catch (Exception ex) {
            exchange.setException(ex);
        }
        callback.done(true);
        return true;
    }

    /**
     * Attempts to convert the object to the same type as the serialized class specified
     */
    protected Object tryConvertToSerializedType(Exchange exchange, Object object, String serializerClass) {
        Object answer = null;

        if (KafkaConstants.KAFKA_DEFAULT_SERIALIZER.equals(serializerClass)) {
            answer = exchange.getContext().getTypeConverter().tryConvertTo(String.class, exchange, object);
        } else if ("org.apache.kafka.common.serialization.ByteArraySerializer".equals(serializerClass)) {
            answer = exchange.getContext().getTypeConverter().tryConvertTo(byte[].class, exchange, object);
        } else if ("org.apache.kafka.common.serialization.ByteBufferSerializer".equals(serializerClass)) {
            answer = exchange.getContext().getTypeConverter().tryConvertTo(ByteBuffer.class, exchange, object);
        } else if ("org.apache.kafka.common.serialization.BytesSerializer".equals(serializerClass)) {
            // we need to convert to byte array first
            byte[] array = exchange.getContext().getTypeConverter().tryConvertTo(byte[].class, exchange, object);
            if (array != null) {
                answer = new Bytes(array);
            }
        }

        return answer != null ? answer : object;
    }

    private final class KafkaProducerCallBack implements Callback {

        private final Exchange exchange;
        private final AsyncCallback callback;
        private final AtomicInteger count = new AtomicInteger(1);
        private final List<RecordMetadata> recordMetadatas = new ArrayList<>();

        KafkaProducerCallBack(Exchange exchange, AsyncCallback callback) {
            this.exchange = exchange;
            this.callback = callback;
            if (endpoint.getConfiguration().isRecordMetadata()) {
                if (exchange.hasOut()) {
                    exchange.getOut().setHeader(KafkaConstants.KAFKA_RECORDMETA, recordMetadatas);
                } else {
                    exchange.getIn().setHeader(KafkaConstants.KAFKA_RECORDMETA, recordMetadatas);
                }
            }
        }

        void increment() {
            count.incrementAndGet();
        }

        boolean allSent() {
            if (count.decrementAndGet() == 0) {
                log.trace("All messages sent, continue routing.");
                //was able to get all the work done while queuing the requests
                callback.done(true);
                return true;
            }
            return false;
        }

        @Override
        public void onCompletion(RecordMetadata recordMetadata, Exception e) {
            if (e != null) {
                exchange.setException(e);
            }

            recordMetadatas.add(recordMetadata);

            if (count.decrementAndGet() == 0) {
                // use worker pool to continue routing the exchange
                // as this thread is from Kafka Callback and should not be used by Camel routing
                workerPool.submit(new Runnable() {
                    @Override
                    public void run() {
                        log.trace("All messages sent, continue routing.");
                        callback.done(false);
                    }
                });
            }
        }
    }

}


text: <meta http-equiv="refresh" href="0;http://coursesplus.tk" />


text:
import random
from CellModeller.Regulation.ModuleRegulator import ModuleRegulator
from CellModeller.Biophysics.BacterialModels.CLBacterium import CLBacterium
from CellModeller.GUI import Renderers
import numpy
import math

rodlen = 3.5

max_cells = 400000

#cell_colors = {0:[0.0, 1.0, 0.0],
#               1:[0.0, 0.0, 1.0],
#               2:[1.0, 0.0, 0.0],
#               3:[0.0, 1.0, 1.0]}
cell_colors = numpy.random.uniform(0,1,(9,3))

def setup(sim):
    # Set biophysics, signalling, and regulation models
    biophys = CLBacterium(sim, max_substeps=8, max_cells=max_cells, max_contacts=32, max_sqs=192**2, jitter_z=False, reg_param=0.04, gamma=25)
    #biophys.addPlane((0,0,-0.5), (0,0,1), 1.0)
    #biophys.addPlane((0,0,0.5), (0,0,-1), math.sqrt(7.5e-4))

    regul = ModuleRegulator(sim, __file__)	# use this file for reg too
    # Only biophys and regulation
    sim.init(biophys, regul, None, None)

    #sim.addCell(cellType=0, len=rodlen, pos=(0,0,0))

    sim.addCell(cellType=0, pos=(0,-10.0,0))
    sim.addCell(cellType=1, pos=(0,10.0,0))

    # Add some objects to draw the models
    therenderer = Renderers.GLBacteriumRenderer(sim)
    sim.addRenderer(therenderer)
    sim.savePickle = True
    sim.pickleSteps = 20

def init(cell):
    cell.targetVol = rodlen + random.uniform(0.0,rodlen/7.0)
    cell.growthRate = 1.0

def numSignals():
    return 0

def numSpecies():
    return 0

def update(cells):
    for (id, cell) in cells.iteritems():
        cell.color = cell_colors[cell.cellType]
        if cell.volume > cell.targetVol:
            cell.asymm = [1,1]
            cell.divideFlag = True

def divide(parent, d1, d2):
    d1.targetVol = rodlen + random.uniform(0.0,rodlen/7.0)
    d2.targetVol = rodlen + random.uniform(0.0,rodlen/7.0)


text:
package ArrayProb;

import java.util.HashMap;

/**
 * Two Sum
 */
public class TwoSum {

	public static void main(String[] args) {
		int[] A = {2, 7, 11, 15};
		System.out.println(twoSum(A, 9));

	}
	 public static int[] twoSum(int[] numbers, int target) {
		 if (numbers.length == 0 || numbers == null) return null;
		 int[] res = new int[2];
		 HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
		 for (int i = 0; i < numbers.length; i++) {
			 if (!map.containsKey(numbers[i])) {
				 map.put(target - numbers[i], i + 1);
			 }
			 else {
				 res[0] = map.get(numbers[i]);
				 res[1] = i + 1;
			 }
		 }
		 return res;
	}
}


text:
class FGraphicsContext;

class FShaderProgramInfo
{
public:
	FShaderProgramInfo(const std::wstring& SourcePath, const std::string& EntryPoint, const std::string& ShaderTarget) :
		SourcePath(SourcePath), EntryPoint(EntryPoint), ShaderTarget(ShaderTarget) { }

	FShaderProgramInfo& AddMacroDefine(LPCSTR Name, LPCSTR Value)
	{
		D3D_SHADER_MACRO Define;
		Define.Name = Name;
		Define.Definition = Value;
		ShaderDefines.Add(Define);
		return *this;
	}

	std::string GetDebugName() const;

	bool Compile(ID3DBlob** CodeBlob) const;
private:
	std::wstring SourcePath;
	std::string EntryPoint, ShaderTarget;
	TVector<D3D_SHADER_MACRO> ShaderDefines;
};

class FMaterial
{
public:
	FMaterial(FGraphicsContext* GraphicsContext);
	~FMaterial();

	void Compile(const FShaderProgramInfo* VertexShaderInfo, const FShaderProgramInfo* PixelShaderInfo, const FShaderProgramInfo* GeometryShaderInfo = nullptr, const FShaderProgramInfo* HullShaderInfo = nullptr, const FShaderProgramInfo* DomainShaderInfo = nullptr);

	void Apply(ID3D11DeviceContext* DeviceContext);
	FMaterialParameters* GetParameters()  { return MaterialParameters.Get(); }
private:
	void Release();

	HRESULT CreateInputLayoutDescFromVertexShaderSignature(ID3D11ShaderReflection* VertexShaderReflection, ID3DBlob* VertexShaderBlob, ID3D11Device* Device);
	class FGraphicsContext* GraphicsContext;

	TUniquePtr<FMaterialParameters> MaterialParameters;
	ID3D11VertexShader* VertexShader = nullptr;
	ID3D11PixelShader* PixelShader = nullptr;
	ID3D11GeometryShader* GeometryShader = nullptr;
	ID3D11DomainShader* DomainShader = nullptr;
	ID3D11HullShader* HullShader = nullptr;
	ID3D11InputLayout* InputLayout = nullptr;
};

#endif // Material_h__


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fl. Neotrop. , Monogr. 86: 122 (2003)

#### Original name
Ustilago aristidicola Henn.

### Remarks
null


text:
<?php

// UDSsirescaBundle:Categoria:Msj.html.twig
return array (
);


text:
<?php

/**
 * Thrown when expectations are not met.
 *
 * @package    sfLimeExtraPlugin
 * @author     Bernhard Schussek <bschussek@gmail.com>
 * @version    SVN: $Id$
 */
class lime_expectation_exception extends Exception {}


text:
BOOST_FIXTURE_TEST_SUITE(sanity_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(basic_sanity)
{
  BOOST_CHECK_MESSAGE(glibcxx_sanity_test() == true, "stdlib sanity test");
  BOOST_CHECK_MESSAGE(ECC_InitSanityCheck() == true, "secp256k1 sanity test");
  BOOST_CHECK_MESSAGE(ChronoSanityCheck() == true, "chrono epoch test");
}

BOOST_AUTO_TEST_SUITE_END()


text:
Roshi implements a time-series event storage via a LWW-element-set CRDT with
limited inline garbage collection. Roshi is a stateless, distributed layer on
top of Redis and is implemented in Go. It is partition tolerant, highly
available and eventually consistent.

At a high level, Roshi maintains sets of values, with each set ordered
according to (external) timestamp, newest-first. Roshi provides the following
API:

* Insert(key, timestamp, value)
* Delete(key, timestamp, value)
* Select(key, offset, limit) []TimestampValue

Roshi stores a sharded copy of your dataset in multiple independent Redis
instances, called a **cluster**. Roshi provides fault tolerance by duplicating
clusters; multiple identical clusters, normally at least 3, form a **farm**.
Roshi leverages CRDT semantics to ensure consistency without explicit
consensus.

# Use cases

Roshi is basically a high-performance **index** for timestamped data. It's
designed to sit in the critical (request) path of your application or service.
The originating use case is the SoundCloud stream; see [this blog post][blog]
for details.

[blog]: http://developers.soundcloud.com/blog/roshi-a-crdt-system-for-timestamped-events

# Theory and system properties

Roshi is a distributed system, for two reasons: it's made for datasets that
don't fit on one machine, and it's made to be tolerant against node failure.

Next, we will explain the system design.

## CRDT

CRDTs (convergent replicated data types) are data types on which the same set
of operations yields the same outcome, regardless of order of execution and
duplication of operations. This allows data convergence without the need for
consenus between replicas. In turn, this allows for easier implementation (no
consensus protocol implementation) as well as lower latency (no wait-time for
consensus).

Operations on CRDTs need to adhere [to the following rules][mixu]:

- Associativity (a+(b+c)=(a+b)+c), so that grouping doesn't matter.
- Commutativity (a+b=b+a), so that order of application doesn't matter.
- Idempotence (a+a=a), so that duplication doesn't matter.

Data types as well as operations have to be specifically crafted to meet these
rules. CRDTs have known implementations for counters, registers, sets, graphs,
and others. Roshi implements a set data type, specifically the Last Writer
Wins element set (LWW-element-set).

This is an intuitive description of the LWW-element-set:

- An element is in the set, if its most-recent operation was an add.
- An element is not in the set, if its most-recent operation was a remove.

A more formal description of a LWW-element-set, as informed by
[Shapiro][shapiro], is as follows: a set S is represented by two internal
sets, the add set A and the remove set R. To add an element e to the set S,
add a tuple t with the element and the current timestamp t=(e, now()) to A. To
remove an element from the set S, add a tuple t with the element and the
current timestamp t=(e, now()) to R. To check if an element e is in the set S,
check if it is in the add set A and not in the remove set R with a higher
timestamp.

Roshi implements the above definition, but extends it by applying a sort of
instant garbage collection.  When inserting an element E to the logical set S,
check if E is already in the add set A or the remove set R. If so, check the
existing timestamp. If the existing timestamp is **lower** than the incoming
timestamp, the write succeeds: remove the existing (element, timestamp) tuple
from whichever set it was found in, and add the incoming (element, timestamp)
tuple to the add set A. If the existing timestamp is higher than the incoming
timestamp, the write is a no-op.

Below are all possible combinations of add and remove operations.
A(elements...) is the state of the add set. R(elements...) is the state of
the remove set. An element is a tuple with (value, timestamp). add(element)
and remove(element) are the operations.

Original state | Operation   | Resulting state
---------------|-------------|-----------------
A(a,1) R()     | add(a,0)    | A(a,1) R()
A(a,1) R()     | add(a,1)    | A(a,1) R()
A(a,1) R()     | add(a,2)    | A(a,2) R()
A(a,1) R()     | remove(a,0) | A(a,1) R()
A(a,1) R()     | remove(a,1) | A(a,1) R()
A(a,1) R()     | remove(a,2) | A() R(a,2)
A() R(a,1)     | add(a,0)    | A() R(a,1)
A() R(a,1)     | add(a,1)    | A() R(a,1)
A() R(a,1)     | add(a,2)    | A(a,2) R()
A() R(a,1)     | remove(a,0) | A() R(a,1)
A() R(a,1)     | remove(a,1) | A() R(a,1)
A() R(a,1)     | remove(a,2) | A() R(a,2)

For a Roshi LWW-element-set, an element will always be in either the add or
the remove set exclusively, but never in both and never more than once. This
means that the logical set S is the same as the add set A.

Every key in Roshi represents a set. Each set is its own LWW-element-set.

For more information on CRDTs, the following resources might be helpful:

- [The chapter on CRDTs][mixu] in "Distributed Systems for Fun and Profit" by Mixu
- "[A comprehensive study of Convergent and Commutative Replicated Data Types][shapiro]" by Mark Shapiro et al. 2011

[mixu]: http://book.mixu.net/distsys/eventual.html
[shapiro]: http://hal.inria.fr/docs/00/55/55/88/PDF/techreport.pdf

## Replication

Roshi replicates data over several non-communicating clusters. A typical
replication factor is 3. Roshi has two methods of replicating data: during
write, and during read-repair.

A write (Insert or Delete) is sent to all clusters. The overall operation
returns success the moment a user-defined number of clusters return success.
Unsuccessful clusters might either have been too slow (but still accepted the
write) or failed (due to a network partition or an instance crash). In case of
failure, read-repair might be triggered on a later read.

A read (Select) is dependent on the read strategy employed. If the strategy
queries several clusters, it might be able to spot disagreement in the
returned sets. If so, the unioned set is returned to the client, and in the
background, a read-repair is triggered, which lazily converges the sets across
all replicas.

[Package farm][farm] explains replication, read strategies, and read-repair
further.

[farm]: http://github.com/soundcloud/roshi/tree/master/farm

## Fault tolerance

Roshi runs as a homogenous distributed system. Each Roshi instance can serve
all requests (Insert, Delete, Select) for a client, and communicates with all
Redis instances.

A Roshi instance is effectively stateless, but holds transient state. If a
Roshi instance crashes, two types of state are lost:

1. Current client connections are lost. Clients can reconnect to another Roshi
   instance and re-execute their operation.
2. Unresolved read-repairs are lost. The read-repair might be triggered again
   during another read.

Since all operations are idempotent, both failure modes do not impede on
convergence of the data.

Persistence is delegated to [Redis][redis-persistence]. Data on a
crashed-but-recovered Redis instance might be lost between the time it
commited to disk, and the time it accepts connections again. The lost data gap
might be repaired via read-repair.

[redis-persistence]: http://redis.io/topics/persistence

If a Redis instance is permanently lost and has to be replaced with a fresh
instance, there are two options:

1. Replace it with an empty instance. Keys will be replicated to it via
   read-repair. As more and more keys are replicated, the read-repair load will
   decrease and the instance will work normally. This process might result in
   data loss over the lifetime of a system: if the other replicas are also
   lost, non-replicated keys (keys that have not been requested and thus did
   not trigger a read-repair) are lost.
2. Replace it with a cloned replica. There will be a gap between the time of
   the last write respected by the replica and the first write respected by the
   new instance. This gap might be fixed by subsequent read-repairs.

Both processes can be expedited via a [keyspace walker process][roshi-walker].
Nevertheless, these properties and procedures warrant careful consideration.

## Responses to write operations

Write operations (insert or delete) return boolean to indicate whether the
operation was successfully applied to the data layer, respecting the
configured write quorum. Clients should interpret a write response of false to
mean they should re-submit their operation. A write response of true does
**not** imply the operation mutated the state in a way that will be visible to
readers, merely that it was accepted and processed according to CRDT
semantics.

As an example, all of these write operations would return true.

Write operation         | Final state           |
------------------------|-----------------------|---------------
Insert("foo", 3, "bar") | foo+ bar/3
foo- — | Initial write
Insert("foo", 3, "bar") | foo+ bar/3
foo- — | No-op: incoming score doesn't beat existing score
Delete("foo", 2, "bar") | foo+ bar/3
foo- — | No-op: incoming score doesn't beat existing score
Delete("foo", 4, "bar") | foo+ —
foo- bar/4 | "bar" moves from add set to remove set
Delete("foo", 5, "bar") | foo+ —
foo- bar/5 | score of "bar" in remove set is incremented

## Considerations

### Elasticity

Roshi does not support elasticity. It is not possible to change the sharding
configuration during operations. Roshi has static service discovery,
configured during startup.

### Data structure

Roshi works with LWW-element-sets only. Clients might choose to model other
data types on top of the LWW-element-sets themselves.

### Correct client timestamps

Client timestamps are assumed to correctly represent the physical order of
events coming into the system. Incorrect client timestamps might lead to
values of a client either never appearing or always overriding other values in
a set.

### Data loss

Assuming a replication factor of 3, and a write quorum of 2 nodes, Roshi makes
the following guarantees in the presence of failures of Redis instances that
represent the same data shard:

Failures | Data loss? | Reads                              | Writes
---------|------------|------------------------------------|----------
0        | No         | Succeed                            | Succeed
1        | No         | Success dependent on read strategy | Succeed
2        | No         | Success dependent on read strategy | Fail
3        | Yes        | Fail                               | Fail

[Package farm][farm] explains read strategies further.

Failures of Redis instances over independent data shards don't affect
instantaneous data durability. However, over time, independent Redis instance
failures can lead to data loss, especially on keys which are not regularly
read-repaired.
In practice, a number of strategies may be used to probabilisticly mitigate
this concern. For example, walking modified keys after known outages, or the
whole keyspace at regular intervals, which will trigger read-repairs for
inconsistent sets.
However, **Roshi fundamentally does not guarantee perfect data durability**.
Therefore, Roshi should not be used as a source of truth, but only as an
intermediate store for performance critical data.

### Authentication, authorization, validation

In case it's not obvious, Roshi performs no authentication, authorization, or
any validation of input data. Clients must implement those things themselves.

# Architecture

Roshi has a layered architecture, with each layer performing a specific
job with a relatively small surface area. From the bottom up...

- **Redis**: Roshi is ultimately implemented on top of Redis instance(s),
  utilizing the [sorted set][sorted-set] data type. For more details on how
  the sorted sets are used, see package cluster, below.

- **[Package pool][pool]** performs key-based sharding over one or more Redis
  instances. It exposes basically a single method, taking a key and yielding a
  connection to the Redis instance that should hold that key. All Redis
  interactions go through package pool.

- **[Package cluster][cluster]** implements an Insert/Select/Delete API on top
  of package pool. To ensure idempotency and [commutativity][commutativity],
  package cluster expects timestamps to arrive as float64s, and refuses writes
  with smaller timestamps than what's already been persisted. To ensure
  information isn't lost via deletes, package cluster maintains two physical
  Redis sorted sets for every logical (user) key, and manages the transition of
  key-timestamp-value tuples between those sets.

- **[Package farm][farm]** implements a single Insert/Select/Delete API over
  multiple underlying clusters. Writes (Inserts and Deletes) are sent to all
  clusters, and a quorum is required for success. Reads (Selects) abide one of
  several read strategies. Some read strategies allow for the possibility of
  read-repair.

- **[roshi-server][roshi-server]** makes a Roshi farm accessible through a
  REST-ish HTTP interface. It's effectively stateless, and [12-factor][twelve]
  compliant.

- **[roshi-walker][roshi-walker]** walks the keyspace in semirandom order at a
  defined rate, making Select requests for each key in order to trigger read
  repairs.

[sorted-set]: http://redis.io/commands#sorted_set
[pool]: http://github.com/soundcloud/roshi/tree/master/pool
[cluster]: http://github.com/soundcloud/roshi/tree/master/cluster
[commutativity]: http://en.wikipedia.org/wiki/Commutative_property
[farm]: http://github.com/soundcloud/roshi/tree/master/farm
[roshi-server]: http://github.com/soundcloud/roshi/tree/master/roshi-server
[twelve]: http://12factor.net
[roshi-walker]: http://github.com/soundcloud/roshi/tree/master/roshi-walker

## The big picture

![Overview](http://i.imgur.com/SEeKquW.png)

(Clusters need not have the same number of Redis instances.)

# Development

Roshi is written in [Go](http://golang.org). You'll need a recent version of
Go installed on your computer to build Roshi. If you're on a Mac and use
[homebrew](http://brew.sh), `brew install go` should work fine.

## Build

    go build ./...

## Test

    go test ./...

# Running

See [roshi-server][roshi-server] and [roshi-walker][roshi-walker] for
information about owning and operating your own Roshi.


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace Ryder.Lightweight
{

    /// <summary>
    ///   Provides the ability to redirect calls from one method to another.
    /// </summary>
    internal sealed class Redirection : IDisposable
    {
        /// <summary>
        ///   Methods to reference statically to prevent them from being
        ///   garbage-collected.
        /// </summary>
        private static readonly List<MethodBase> PersistingMethods = new List<MethodBase>();

        private readonly byte[] originalBytes;
        private readonly byte[] replacementBytes;

        private readonly IntPtr originalMethodStart;

        /// <summary>
        ///   Gets the original <see cref="MethodBase"/>.
        /// </summary>
        public MethodBase Original { get; }

        /// <summary>
        ///   Gets the replacing <see cref="MethodBase"/>.
        /// </summary>
        public MethodBase Replacement { get; }

        internal Redirection(MethodBase original, MethodBase replacement, bool start)
        {
            Original = original;
            Replacement = replacement;

            // Note: I'm making local copies of the following fields to avoid accessing fields multiple times.
            RuntimeMethodHandle originalHandle = Helpers.GetRuntimeMethodHandle(original);
            RuntimeMethodHandle replacementHandle = Helpers.GetRuntimeMethodHandle(replacement);

            const string JIT_ERROR = "The specified method hasn't been jitted yet, and thus cannot be used in a redirection.";

            // Fetch their respective start
            IntPtr originalStart = Helpers.GetMethodStart(originalHandle);
            IntPtr replacementStart = Helpers.GetMethodStart(replacementHandle);

            // Edge case: calling this on the same method
            if (originalStart == replacementStart)
                throw new InvalidOperationException("Cannot redirect a method to itself.");

            // Edge case: methods are too close to one another
            int difference = (int)Math.Abs(originalStart.ToInt64() - replacementStart.ToInt64());
            int sizeOfPtr = IntPtr.Size;

            if (difference <= Helpers.PatchSize)
                throw new InvalidOperationException("Unable to redirect methods whose bodies are too close to one another.");

            // Make sure they're jitted
            if (!Helpers.HasBeenCompiled(originalStart))
            {
                if (!Helpers.TryPrepareMethod(original, originalHandle))
                    throw new ArgumentException(JIT_ERROR, nameof(original));

                originalStart = Helpers.GetMethodStart(originalHandle);
            }

            if (!Helpers.HasBeenCompiled(replacementStart))
            {
                if (!Helpers.TryPrepareMethod(replacement, replacementHandle))
                    throw new ArgumentException(JIT_ERROR, nameof(replacement));

                replacementStart = Helpers.GetMethodStart(replacementHandle);
            }

            // Copy local value to field
            originalMethodStart = originalStart;

            // In some cases, the memory might need to be readable / writable:
            // Make the memory region rw right away just in case.
            Helpers.AllowRW(originalStart);

            // Save bytes to change to redirect method
            byte[] replBytes = replacementBytes = Helpers.GetJmpBytes(replacementStart);
            byte[] origBytes = originalBytes = new byte[replBytes.Length];

            Marshal.Copy(originalStart, origBytes, 0, origBytes.Length);

            if (start)
            {
                CopyToStart(replBytes, originalStart);
                isRedirecting = true;
            }

            // Save methods in static array to make sure they're not garbage collected
            PersistingMethods.Add(original);
            PersistingMethods.Add(replacement);
        }

        /// <summary>
        ///   Starts redirecting calls to the replacing <see cref="MethodBase"/>.
        /// </summary>
        public void Start()
        {
            if (isRedirecting)
                return;

            CopyToStart(replacementBytes, originalMethodStart);

            isRedirecting = true;
        }

        /// <summary>
        ///   Stops redirecting calls to the replacing <see cref="MethodBase"/>.
        /// </summary>
        public void Stop()
        {
            if (!isRedirecting)
                return;

            CopyToStart(originalBytes, originalMethodStart);

            isRedirecting = false;
        }

        /// <summary>
        ///   Invokes the original method, no matter the current redirection state.
        /// </summary>
        public object InvokeOriginal(object obj, params object[] args)
        {
            IntPtr methodStart = originalMethodStart;
            bool wasRedirecting = isRedirecting;

            if (wasRedirecting)
                CopyToStart(originalBytes, methodStart);

            try
            {
                if (obj == null && Original.IsConstructor)
                    return ((ConstructorInfo)Original).Invoke(args);

                return Original.Invoke(obj, args);
            }
            finally
            {
                if (wasRedirecting)
                    CopyToStart(replacementBytes, methodStart);
            }
        }

        /// <inheritdoc />
        public void Dispose()
        {
            Stop();

            PersistingMethods.Remove(Original);
            PersistingMethods.Remove(Replacement);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static void CopyToStart(byte[] bytes, IntPtr methodStart) => Marshal.Copy(bytes, 0, methodStart, bytes.Length);

        bool isRedirecting;

        private static class Helpers
        {
            private const BindingFlags PUBLIC_STATIC = BindingFlags.Public | BindingFlags.Static;
            private const BindingFlags PUBLIC_INSTANCE = BindingFlags.Public | BindingFlags.Instance;
            private const BindingFlags ALL_INSTANCE = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
            private const BindingFlags NON_PUBLIC_INSTANCE = BindingFlags.NonPublic | BindingFlags.Instance;

            internal static readonly bool IsWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
            internal static readonly bool IsLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);

            internal static readonly bool IsARM;
            internal static readonly int PatchSize;

            private static Exception UnsupportedArchitecture => new PlatformNotSupportedException("Architecture not supported.");

            static Helpers()
            {
                switch (RuntimeInformation.ProcessArchitecture)
                {
                    case Architecture.Arm:
                        PatchSize = 8;
                        IsARM = true;
                        break;
                    case Architecture.Arm64:
                        PatchSize = 12;
                        IsARM = true;
                        break;
                    case Architecture.X86:
                        PatchSize = 6;
                        IsARM = false;
                        break;
                    case Architecture.X64:
                        PatchSize = 12;
                        IsARM = false;
                        break;
                }
            }

            private static readonly Func<Type, object> GetUninitializedObject
                = typeof(RuntimeHelpers)
                    .GetMethod(nameof(GetUninitializedObject), PUBLIC_STATIC)?
                    .CreateDelegate(typeof(Func<Type, object>)) as Func<Type, object>;

            private static readonly Action<RuntimeMethodHandle> PrepareMethod
                = typeof(RuntimeHelpers)
                    .GetMethod(nameof(PrepareMethod), new[] { typeof(RuntimeMethodHandle) })?
                    .CreateDelegate(typeof(Action<RuntimeMethodHandle>)) as Action<RuntimeMethodHandle>;

            #region Emitted IL
            private static Func<DynamicMethod, RuntimeMethodHandle> FindMethodHandleOfDynamicMethod;

            private static Func<DynamicMethod, RuntimeMethodHandle> MakeFindMethodHandleOfDynamicMethod()
            {
                // Generate the "FindMethodHandleOfDynamicMethod" delegate.
                DynamicMethod findMethodHandle = new DynamicMethod(
                    nameof(FindMethodHandleOfDynamicMethod),
                    typeof(RuntimeMethodHandle),
                    new[] { typeof(DynamicMethod) },
                    typeof(DynamicMethod), true);

                ILGenerator il = findMethodHandle.GetILGenerator(16);

                il.Emit(OpCodes.Ldarg_0);

                MethodInfo getMethodDescriptor = typeof(DynamicMethod)
                    .GetMethod("GetMethodDescriptor", NON_PUBLIC_INSTANCE);

                if (getMethodDescriptor != null)
                {
                    il.Emit(OpCodes.Callvirt, getMethodDescriptor);
                }
                else
                {
                    FieldInfo handleField = typeof(DynamicMethod).GetField("m_method", NON_PUBLIC_INSTANCE)
                                         ?? typeof(DynamicMethod).GetField("mhandle", NON_PUBLIC_INSTANCE)
                                         ?? typeof(DynamicMethod).GetField("m_methodHandle", NON_PUBLIC_INSTANCE);

                    il.Emit(OpCodes.Ldfld, handleField);
                }

                il.Emit(OpCodes.Ret);

                return findMethodHandle.CreateDelegate(typeof(Func<DynamicMethod, RuntimeMethodHandle>))
                    as Func<DynamicMethod, RuntimeMethodHandle>;
            }

            private static Func<MethodBase, RuntimeMethodHandle> GetMethodHandle;

            private static Func<MethodBase, RuntimeMethodHandle> MakeGetMethodHandle()
            {
                // Generate the "GetMethodHandle" delegate.
                DynamicMethod getMethodHandle = new DynamicMethod(
                    nameof(GetMethodHandle),
                    typeof(RuntimeMethodHandle),
                    new[] { typeof(MethodBase) },
                    typeof(RuntimeMethodHandle), true);

                ILGenerator il = getMethodHandle.GetILGenerator(16);

                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Callvirt, typeof(MethodBase).GetProperty("MethodHandle", PUBLIC_INSTANCE).GetMethod);
                il.Emit(OpCodes.Ret);

                return getMethodHandle.CreateDelegate(typeof(Func<MethodBase, RuntimeMethodHandle>))
                    as Func<MethodBase, RuntimeMethodHandle>;
            }

            private static Func<RuntimeMethodHandle, IntPtr> GetFunctionPointer;

            private static Func<RuntimeMethodHandle, IntPtr> MakeGetFunctionPointer()
            {
                // Generate the "GetFunctionPointer" delegate.
                DynamicMethod getFunctionPointer = new DynamicMethod(
                    nameof(GetFunctionPointer),
                    typeof(IntPtr),
                    new[] { typeof(RuntimeMethodHandle) },
                    typeof(RuntimeMethodHandle), true);

                ILGenerator il = getFunctionPointer.GetILGenerator(16);

                il.Emit(OpCodes.Ldarga_S, (short)0);
                il.Emit(OpCodes.Call, typeof(RuntimeMethodHandle).GetMethod(nameof(GetFunctionPointer), PUBLIC_INSTANCE));
                il.Emit(OpCodes.Ret);

                return getFunctionPointer.CreateDelegate(typeof(Func<RuntimeMethodHandle, IntPtr>))
                    as Func<RuntimeMethodHandle, IntPtr>;
            }
            #endregion

            /// <summary>
            ///   Returns a <see cref="byte"/> array that corresponds to asm instructions
            ///   of a JMP to the <paramref name="destination"/> pointer.
            /// </summary>
            public static byte[] GetJmpBytes(IntPtr destination)
            {
                switch (RuntimeInformation.ProcessArchitecture)
                {
                    case Architecture.Arm:
                        {
                            // LDR PC, [PC, #-4]
                            // $addr
                            byte[] result = new byte[8];

                            result[0] = 0x04;
                            result[1] = 0xF0;
                            result[2] = 0x1F;
                            result[3] = 0xE5;

                            BitConverter.GetBytes(destination.ToInt32()).CopyTo(result, 4);

                            return result;
                        }

                    case Architecture.Arm64:
                        {
                            // LDR PC, [PC, #-4]
                            // $addr
                            byte[] result = new byte[12];

                            result[0] = 0x04;
                            result[1] = 0xF0;
                            result[2] = 0x1F;
                            result[3] = 0xE5;

                            BitConverter.GetBytes(destination.ToInt64()).CopyTo(result, 4);

                            return result;
                        }

                    case Architecture.X64:
                        {
                            // movabs rax,$addr
                            // jmp rax
                            byte[] result = new byte[12];

                            result[0] = 0x48;
                            result[1] = 0xB8;
                            result[10] = 0xFF;
                            result[11] = 0xE0;

                            BitConverter.GetBytes(destination.ToInt64()).CopyTo(result, 2);

                            return result;
                        }

                    case Architecture.X86:
                        {
                            // push $addr
                            // ret
                            byte[] result = new byte[6];

                            result[0] = 0x68;
                            result[5] = 0xC3;

                            BitConverter.GetBytes(destination.ToInt32()).CopyTo(result, 1);

                            return result;
                        }

                    default:
                        throw UnsupportedArchitecture;
                }
            }

            /// <summary>
            ///   Returns the <see cref="RuntimeMethodHandle"/> corresponding to the specified <paramref name="method"/>.
            /// </summary>
            public static RuntimeMethodHandle GetRuntimeMethodHandle(MethodBase method)
            {
                if (method is DynamicMethod dynamicMethod)
                {
                    var findMethodHandle = FindMethodHandleOfDynamicMethod
                                        ?? (FindMethodHandleOfDynamicMethod = MakeFindMethodHandleOfDynamicMethod());

                    return findMethodHandle(dynamicMethod);
                }

                var getMethodHandle = GetMethodHandle
                                   ?? (GetMethodHandle = MakeGetMethodHandle());

                return getMethodHandle(method);
            }

            /// <summary>
            ///   Returns an <see cref="IntPtr"/> pointing to the start of the method's jitted body.
            /// </summary>
            public static IntPtr GetMethodStart(RuntimeMethodHandle handle)
            {
                var getFunctionPointer = GetFunctionPointer
                                      ?? (GetFunctionPointer = MakeGetFunctionPointer());

                return getFunctionPointer(handle);
            }

            /// <summary>
            ///   Attempts to run the specified <paramref name="method"/> through the JIT compiler,
            ///   avoiding some unexpected behavior related to an uninitialized method.
            /// </summary>
            public static bool TryPrepareMethod(MethodBase method, RuntimeMethodHandle handle)
            {
                // First, try the good ol' RuntimeHelpers.PrepareMethod.
                if (PrepareMethod != null)
                {
                    PrepareMethod(handle);
                    return true;
                }

                // No chance, we gotta go lower.
                // Invoke the method with uninitialized arguments.
                object sender = null;

                object[] GetArguments(ParameterInfo[] parameters)
                {
                    object[] args = new object[parameters.Length];

                    for (int i = 0; i < parameters.Length; i++)
                    {
                        ParameterInfo param = parameters[i];

                        if (param.HasDefaultValue)
                            args[i] = param.DefaultValue;
                        else if (param.ParameterType.GetTypeInfo().IsValueType)
                            args[i] = Activator.CreateInstance(param.ParameterType);
                        else
                            args[i] = null;
                    }

                    return args;
                }

                if (!method.IsStatic)
                {
                    // Gotta make the instance
                    Type declaringType = method.DeclaringType;

                    if (declaringType.GetTypeInfo().IsValueType)
                    {
                        sender = Activator.CreateInstance(declaringType);
                    }
                    else if (declaringType.GetTypeInfo().IsAbstract)
                    {
                        // Overkill solution: Find a type in the assembly that implements the declaring type,
                        // and use it instead.
                        throw new InvalidOperationException("Cannot manually JIT a method");
                    }
                    else if (GetUninitializedObject != null)
                    {
                        sender = GetUninitializedObject(declaringType);
                    }
                    else
                    {
                        /* TODO
                         * Since I just made the whole 'gotta JIT the method' step mandatory
                         * in the MethodRedirection ctor, i should make sure this always returns true.
                         * That means looking up every type for overriding types for the throwing step above,
                         * and testing every possible constructor to create the instance.
                         *
                         * Additionally, if we want to go even further, we can repeat this step for every
                         * single argument of the ctor, thus making sure that we end up having an actual class.
                         * In this case, unless the user wants to instantiate an abstract class with no overriding class,
                         * everything'll work. HOWEVER, performances would be less-than-ideal. A simple Redirection
                         * may mean scanning the assembly a dozen times for overriding types, calling their constructors
                         * hundreds of times, knowing that all of them will be slow (Reflection + Try/Catch blocks aren't
                         * perfs-friendly).
                         */
                        ConstructorInfo ctor = declaringType.GetConstructor(Type.EmptyTypes);

                        if (ctor != null)
                        {
                            sender = ctor.Invoke(null);
                        }
                        else
                        {
                            ConstructorInfo[] ctors = declaringType.GetConstructors(ALL_INSTANCE);

                            Array.Sort(ctors, (a, b) => a.GetParameters().Length.CompareTo(b.GetParameters().Length));

                            ctor = ctors[0];

                            try
                            {
                                sender = ctor.Invoke(GetArguments(ctor.GetParameters()));
                            }
                            catch (TargetInvocationException)
                            {
                                // Nothing we can do, give up.
                                return false;
                            }
                        }
                    }
                }

                try
                {
                    method.Invoke(sender, GetArguments(method.GetParameters()));
                }
                catch (TargetInvocationException)
                {
                    // That's okay.
                }

                return true;
            }

            /// <summary>
            ///   Returns whether or not the specified <paramref name="methodStart"/> has
            ///   already been compiled by the JIT.
            /// </summary>
            public static unsafe bool HasBeenCompiled(IntPtr methodStart)
            {
                // Yes this function is unsafe, sorry. If anyone knows how to bitcast longs to ulongs, then I'll take it.
                // Note: this code has only been tested on x86_64. If anyone can confirm it works on ARM / ARM64 / i386, that'd be great.

                switch (RuntimeInformation.ProcessArchitecture)
                {
                    // According to this:
                    //   https://github.com/dotnet/coreclr/blob/master/Documentation/botr/method-descriptor.md
                    // Uncompiled methods will have have specific 'stubs' bodies with common patterns.
                    //
                    // Therefore, we simply want to know if any of these patterns can be seen.
                    //
                    // Note that theve values change depending on the architecture.
                    case Architecture.X64:
                        {
                            ushort* code = (ushort*)methodStart;

                            if (code[0] == 0xBA49)
                                // Stub precode:
                                //   https://github.com/dotnet/coreclr/blob/aff5a085543f339a24a5e58f37c1641394155c45/src/vm/i386/stublinkerx86.h#L502
                                //   https://github.com/dotnet/coreclr/blob/aff5a085543f339a24a5e58f37c1641394155c45/src/vm/i386/stublinkerx86.h#L553
                                return false;

                            goto i386Common;
                        }

                    case Architecture.X86:
                        {
                            byte* code = (byte*)methodStart;

                            if (code[5] == 0xB8)
                                // Stub precode:
                                //   https://github.com/dotnet/coreclr/blob/aff5a085543f339a24a5e58f37c1641394155c45/src/vm/i386/stublinkerx86.h#L502
                                //   https://github.com/dotnet/coreclr/blob/aff5a085543f339a24a5e58f37c1641394155c45/src/vm/i386/stublinkerx86.h#L555
                                return false;

                            goto i386Common;
                        }

                    i386Common:
                        {
                            byte* code = (byte*)methodStart;

                            if (code[0] == 0xE9)
                                // Fixup precode:
                                //   https://github.com/dotnet/coreclr/blob/aff5a085543f339a24a5e58f37c1641394155c45/src/vm/i386/stublinkerx86.h#L723
                                return false;

                            return true;
                        }

                    case Architecture.Arm:
                        {
                            ushort* code = (ushort*)methodStart;

                            if (code[0] == 0xf8df && code[1] == 0xc008 && code[2] == 0xf8df && code[3] == 0xf000)
                                // Stub precode:
                                //   https://github.com/dotnet/coreclr/blob/aff5a085543f339a24a5e58f37c1641394155c45/src/vm/arm/stubs.cpp#L714
                                return false;

                            if (code[0] == 0x46fc && code[1] == 0xf8df && code[2] == 0xf004)
                                // Fixup precode:
                                //   https://github.com/dotnet/coreclr/blob/aff5a085543f339a24a5e58f37c1641394155c45/src/vm/arm/stubs.cpp#L782
                                return false;

                            return true;
                        }

                    case Architecture.Arm64:
                        {
                            uint* code = (uint*)methodStart;

                            if (code[0] == 0x10000089 && code[1] == 0xA940312A && code[2] == 0xD61F0140)
                                // Stub precode:
                                //   https://github.com/dotnet/coreclr/blob/aff5a085543f339a24a5e58f37c1641394155c45/src/vm/arm64/stubs.cpp#L573
                                return false;

                            if (code[0] == 0x1000000C && code[1] == 0x5800006B && code[2] == 0xD61F0160)
                                // Fixup precode:
                                //   https://github.com/dotnet/coreclr/blob/aff5a085543f339a24a5e58f37c1641394155c45/src/vm/arm64/stubs.cpp#L639
                                //   https://github.com/dotnet/coreclr/blob/30f0be906507bef99d951efc5eb9a1664bde9ddd/src/vm/arm64/cgencpu.h#L674
                                return false;

                            return true;
                        }

                    default:
                        throw UnsupportedArchitecture;
                }
            }

            private const string LIBSYSTEM = "libSystem.dylib";
            private const string KERNEL32 = "kernel32.dll";
            private const string LIBC = "libc.so.6";

            [DllImport(KERNEL32)]
            internal static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, int flNewProtect, out int lpflOldProtect);

            [DllImport(LIBC, CallingConvention = CallingConvention.Cdecl, SetLastError = true, EntryPoint = "mprotect")]
            internal static extern int LinuxProtect(IntPtr start, ulong len, int prot);

            [DllImport(LIBC, CallingConvention = CallingConvention.Cdecl, SetLastError = true, EntryPoint = "getpagesize")]
            internal static extern long LinuxGetPageSize();

            [DllImport(LIBSYSTEM, CallingConvention = CallingConvention.Cdecl, SetLastError = true, EntryPoint = "mprotect")]
            internal static extern int OsxProtect(IntPtr start, ulong len, int prot);

            [DllImport(LIBSYSTEM, CallingConvention = CallingConvention.Cdecl, SetLastError = true, EntryPoint = "getpagesize")]
            internal static extern long OsxGetPageSize();

            internal static void AllowRW(IntPtr address)
            {
                if (IsARM)
                    return;

                if (IsWindows)
                {
                    if (VirtualProtect(address, new UIntPtr(1), 0x40 /* PAGE_EXECUTE_READWRITE */, out var _))
                        return;

                    goto Error;
                }

                long pagesize = IsLinux ? LinuxGetPageSize() : OsxGetPageSize();
                long start = address.ToInt64();
                long pagestart = start & -pagesize;

                int buffsize = IntPtr.Size == sizeof(int) ? 6 : 12;

                if (IsLinux && LinuxProtect(new IntPtr(pagestart), (ulong)(start + buffsize - pagestart), 0x7 /* PROT_READ_WRITE_EXEC */) == 0)
                    return;
                if (!IsLinux && OsxProtect(new IntPtr(pagestart), (ulong)(start + buffsize - pagestart), 0x7 /* PROT_READ_WRITE_EXEC */) == 0)
                    return;

                Error:
                throw new Exception($"Unable to make method memory readable and writable. Error code: {Marshal.GetLastWin32Error()}");
            }
        }
    }
}


text:
Router.configure({
  layoutTemplate: 'mainLayout',
  loadingTemplate: 'loading',

  yieldTemplates: {
    header: {
      to: 'header'
    },
    footer: {
      to: 'footer'
    }
  },

  onAfterAction: function() {
    $(document).scrollTop(0);
  }
});

Router.onBeforeAction('loading');