text:
<?php

add_action('after_setup_theme', function () {
    $filters = [
    // wp-includes/default-filters.php line 94
    'comment_author', 'term_name', 'link_name', 'link_description', 'link_notes', 'bloginfo', 'wp_title', 'widget_title',
    // wp-includes/default-filters.php line 106
    'single_post_title', 'single_cat_title', 'single_tag_title', 'single_month_title', 'nav_menu_attr_title', 'nav_menu_description',
    // wp-includes/default-filters.php line 112
    'term_description',
    // wp-includes/default-filters.php line 127
    'the_title',
    // wp-includes/default-filters.php line 131
    'the_content',
    // wp-includes/default-filters.php line 138
    'the_excerpt',
    // wp-includes/default-filters.php line 145
    'comment_text',
    // wp-includes/default-filters.php line 154
    'list_cats',
  ];

    foreach ($filters as $filter) {
        remove_filter($filter, 'wptexturize');
    }
});


text:
layout: page
title: "About"
description: "Wake me up when September ends"
header-img: "img/about/about-bg.jpg"
---

My name is Michael. Aha, I am maybe a 'something' guy, Knowing something about Data Science, Knowing something about
  Front End, Knowing something about Back End, Knowing something about Machine Learning, Knowing something about Web Crawler...

Whatever, keep going and know more something.

 Hang on to your dreams

redpajama_set_name: RedPajamaGithub


text:
namespace gl
{
class Path;
}

namespace rx
{
class ContextImpl : public GLImplFactory
{
  public:
    ContextImpl(const gl::ContextState &state);
    virtual ~ContextImpl();

    virtual gl::Error initialize() = 0;

    // Flush and finish.
    virtual gl::Error flush() = 0;
    virtual gl::Error finish() = 0;

    // Drawing methods.
    virtual gl::Error drawArrays(GLenum mode, GLint first, GLsizei count) = 0;
    virtual gl::Error drawArraysInstanced(GLenum mode,
                                          GLint first,
                                          GLsizei count,
                                          GLsizei instanceCount) = 0;

    virtual gl::Error drawElements(GLenum mode,
                                   GLsizei count,
                                   GLenum type,
                                   const GLvoid *indices,
                                   const gl::IndexRange &indexRange) = 0;
    virtual gl::Error drawElementsInstanced(GLenum mode,
                                            GLsizei count,
                                            GLenum type,
                                            const GLvoid *indices,
                                            GLsizei instances,
                                            const gl::IndexRange &indexRange) = 0;
    virtual gl::Error drawRangeElements(GLenum mode,
                                        GLuint start,
                                        GLuint end,
                                        GLsizei count,
                                        GLenum type,
                                        const GLvoid *indices,
                                        const gl::IndexRange &indexRange) = 0;

    // CHROMIUM_path_rendering path drawing methods.
    virtual void stencilFillPath(const gl::Path *path, GLenum fillMode, GLuint mask);
    virtual void stencilStrokePath(const gl::Path *path, GLint reference, GLuint mask);
    virtual void coverFillPath(const gl::Path *path, GLenum coverMode);
    virtual void coverStrokePath(const gl::Path *path, GLenum coverMode);
    virtual void stencilThenCoverFillPath(const gl::Path *path,
                                          GLenum fillMode,
                                          GLuint mask,
                                          GLenum coverMode);

    virtual void stencilThenCoverStrokePath(const gl::Path *path,
                                            GLint reference,
                                            GLuint mask,
                                            GLenum coverMode);

    virtual void coverFillPathInstanced(const std::vector<gl::Path *> &paths,
                                        GLenum coverMode,
                                        GLenum transformType,
                                        const GLfloat *transformValues);
    virtual void coverStrokePathInstanced(const std::vector<gl::Path *> &paths,
                                          GLenum coverMode,
                                          GLenum transformType,
                                          const GLfloat *transformValues);
    virtual void stencilFillPathInstanced(const std::vector<gl::Path *> &paths,
                                          GLenum fillMode,
                                          GLuint mask,
                                          GLenum transformType,
                                          const GLfloat *transformValues);
    virtual void stencilStrokePathInstanced(const std::vector<gl::Path *> &paths,
                                            GLint reference,
                                            GLuint mask,
                                            GLenum transformType,
                                            const GLfloat *transformValues);
    virtual void stencilThenCoverFillPathInstanced(const std::vector<gl::Path *> &paths,
                                                   GLenum coverMode,
                                                   GLenum fillMode,
                                                   GLuint mask,
                                                   GLenum transformType,
                                                   const GLfloat *transformValues);
    virtual void stencilThenCoverStrokePathInstanced(const std::vector<gl::Path *> &paths,
                                                     GLenum coverMode,
                                                     GLint reference,
                                                     GLuint mask,
                                                     GLenum transformType,
                                                     const GLfloat *transformValues);

    // Device loss
    virtual GLenum getResetStatus() = 0;

    // Vendor and description strings.
    virtual std::string getVendorString() const = 0;
    virtual std::string getRendererDescription() const = 0;

    // Debug markers.
    virtual void insertEventMarker(GLsizei length, const char *marker) = 0;
    virtual void pushGroupMarker(GLsizei length, const char *marker) = 0;
    virtual void popGroupMarker() = 0;

    // State sync with dirty bits.
    virtual void syncState(const gl::State &state, const gl::State::DirtyBits &dirtyBits) = 0;

    // Disjoint timer queries
    virtual GLint getGPUDisjoint() = 0;
    virtual GLint64 getTimestamp() = 0;

    // Context switching
    virtual void onMakeCurrent(const gl::ContextState &data) = 0;

    // Native capabilities, unmodified by gl::Context.
    virtual const gl::Caps &getNativeCaps() const = 0;
    virtual const gl::TextureCapsMap &getNativeTextureCaps() const = 0;
    virtual const gl::Extensions &getNativeExtensions() const = 0;
    virtual const gl::Limitations &getNativeLimitations() const = 0;

    const gl::ContextState &getContextState() { return mState; }
    int getClientMajorVersion() const { return mState.getClientMajorVersion(); }
    int getClientMinorVersion() const { return mState.getClientMinorVersion(); }
    const gl::State &getGLState() const { return mState.getState(); }
    const gl::Caps &getCaps() const { return mState.getCaps(); }
    const gl::TextureCapsMap &getTextureCaps() const { return mState.getTextureCaps(); }
    const gl::Extensions &getExtensions() const { return mState.getExtensions(); }
    const gl::Limitations &getLimitations() const { return mState.getLimitations(); }

  protected:
    const gl::ContextState &mState;
};

}  // namespace rx

#endif  // LIBANGLE_RENDERER_CONTEXTIMPL_H_


text:
package org.mycontroller.standalone.db.dao;

import java.sql.SQLException;
import java.util.List;

import org.mycontroller.standalone.AppProperties.RESOURCE_TYPE;
import org.mycontroller.standalone.api.jaxrs.json.Query;
import org.mycontroller.standalone.api.jaxrs.json.QueryResponse;
import org.mycontroller.standalone.db.tables.ResourcesGroup;
import org.mycontroller.standalone.db.tables.ResourcesGroupMap;

import com.j256.ormlite.dao.Dao.CreateOrUpdateStatus;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.support.ConnectionSource;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Jeeva Kandasamy (jkandasa)
 * @since 0.0.2
 */
@Slf4j
public class ResourcesGroupMapDaoImpl extends BaseAbstractDaoImpl<ResourcesGroupMap, Integer> implements
        ResourcesGroupMapDao {

    public ResourcesGroupMapDaoImpl(ConnectionSource connectionSource) throws SQLException {
        super(connectionSource, ResourcesGroupMap.class);
    }

    @Override
    public void create(ResourcesGroupMap resourcesGroupMap) {
        try {
            Integer count = this.getDao().create(resourcesGroupMap);
            _logger.debug("Created ResourcesGroupMap:[{}], Create count:{}", resourcesGroupMap, count);
        } catch (SQLException ex) {
            _logger.error("unable to add ResourcesGroupMap:[{}]", resourcesGroupMap, ex);
        }
    }

    @Override
    public void createOrUpdate(ResourcesGroupMap resourcesGroupMap) {
        try {
            CreateOrUpdateStatus status = this.getDao().createOrUpdate(resourcesGroupMap);
            _logger.debug("CreateOrUpdate ResourcesGroupMap:[{}],Create:{},Update:{},Lines Changed:{}",
                    resourcesGroupMap,
                    status.isCreated(),
                    status.isUpdated(), status.getNumLinesChanged());
        } catch (SQLException ex) {
            _logger.error("unable to CreateOrUpdate ResourcesGroup:[{}]", resourcesGroupMap, ex);
        }
    }

    @Override
    public void update(ResourcesGroupMap resourcesGroupMap) {
        try {
            Integer count = this.getDao().update(resourcesGroupMap);
            _logger.debug("Updated ResourcesGroupMap:[{}], Create count:{}", resourcesGroupMap, count);
        } catch (SQLException ex) {
            _logger.error("unable to update ResourcesGroupMap:[{}]", resourcesGroupMap, ex);
        }
    }

    @Override
    public void delete(ResourcesGroupMap resourcesGroupMap) {
        delete(null, resourcesGroupMap.getId(), null, null);
    }

    @Override
    public void delete(Integer id) {
        delete(id, null, null, null);
    }

    @Override
    public void delete(RESOURCE_TYPE resourceType, Integer resourceId) {
        delete(null, null, resourceType, resourceId);
    }

    @Override
    public void delete(ResourcesGroup resourcesGroup) {
        delete(null, resourcesGroup.getId(), null, null);

    }

    private void delete(Integer id, Integer resourcesGroupId, RESOURCE_TYPE resourceType,
            Integer resourceId) {
        try {
            int deleteCount = 0;
            if (id != null) {
                deleteCount = this.getDao().deleteById(id);
            } else if (resourcesGroupId != null) {
                DeleteBuilder<ResourcesGroupMap, Integer> deleteBuilder = this.getDao().deleteBuilder();
                deleteBuilder.where().eq(ResourcesGroupMap.KEY_GROUP_ID, resourcesGroupId);
                deleteCount = deleteBuilder.delete();
            } else if (resourceType != null && resourceId != null) {
                DeleteBuilder<ResourcesGroupMap, Integer> deleteBuilder = this.getDao().deleteBuilder();
                deleteBuilder.where().eq(ResourcesGroupMap.KEY_RESOURCE_TYPE, resourceType).and()
                        .eq(ResourcesGroupMap.KEY_RESOURCE_ID, resourceId);
                deleteCount = deleteBuilder.delete();
            } else {
                _logger.warn("all values should not be null!");
            }
            _logger.debug("Deleted [id:{}, resourceGroupId:{}, resourceType:{}, resourceId:{}], delete count:{}",
                    id, resourcesGroupId, resourceType, resourceId, deleteCount);
        } catch (SQLException ex) {
            _logger.debug("unable to deleted [id:{}, resourceGroupId:{}, resourceType:{}, resourceId:{}]",
                    id, resourcesGroupId, resourceType, resourceId, ex);
        }
    }

    @Override
    public ResourcesGroupMap get(Integer id) {
        try {
            return this.getDao().queryForId(id);
        } catch (SQLException ex) {
            _logger.error("unable to get id:[{}]", id, ex);
        }
        return null;
    }

    @Override
    public List<ResourcesGroupMap> getAll(Integer resourceGroupId) {
        return getAllPrivate(resourceGroupId, null, null);
    }

    @Override
    public List<ResourcesGroupMap> getAll(RESOURCE_TYPE resourceType, Integer resourceId) {
        return getAllPrivate(null, resourceType, resourceId);
    }

    @Override
    public List<ResourcesGroupMap> getAll() {
        return getAllPrivate(null, null, null);
    }

    @Override
    public List<ResourcesGroupMap> getAll(ResourcesGroup resourcesGroup) {
        return getAllPrivate(resourcesGroup.getId(), null, null);
    }

    private List<ResourcesGroupMap> getAllPrivate(Integer resourceGroupId, RESOURCE_TYPE resourceType,
            Integer resourceId) {
        try {
            if (resourceGroupId == null && resourceType == null && resourceId == null) {
                return this.getDao().queryForAll();
            } else if (resourceGroupId != null) {
                QueryBuilder<ResourcesGroupMap, Integer> queryBuilder = this.getDao().queryBuilder();
                queryBuilder.where().eq(ResourcesGroupMap.KEY_GROUP_ID, resourceGroupId);
                return queryBuilder.query();
            } else if (resourceType != null && resourceId != null) {
                QueryBuilder<ResourcesGroupMap, Integer> queryBuilder = this.getDao().queryBuilder();
                queryBuilder.where().eq(ResourcesGroupMap.KEY_RESOURCE_TYPE, resourceType).and()
                        .eq(ResourcesGroupMap.KEY_RESOURCE_ID, resourceId);
                return queryBuilder.query();
            } else if (resourceType != null) {
                QueryBuilder<ResourcesGroupMap, Integer> queryBuilder = this.getDao().queryBuilder();
                queryBuilder.where().eq(ResourcesGroupMap.KEY_RESOURCE_TYPE, resourceType);
                return queryBuilder.query();
            }
            return null;
        } catch (SQLException ex) {
            _logger.error("unable to get all list", ex);
            return null;
        }
    }

    @Override
    public void delete(List<Integer> ids) {
        try {
            int deleteCount = this.getDao().deleteIds(ids);
            _logger.debug("Deleted [ids:{}], delete count:{}", ids, deleteCount);
        } catch (SQLException ex) {
            _logger.debug("unable to deleted [ids:{}]", ids, ex);
        }
    }

    @Override
    public long countOf(RESOURCE_TYPE resourceType, Integer resourceId) {
        try {
            QueryBuilder<ResourcesGroupMap, Integer> queryBuilder = this.getDao().queryBuilder();
            queryBuilder.where().eq(ResourcesGroupMap.KEY_RESOURCE_TYPE, resourceType).and()
                    .eq(ResourcesGroupMap.KEY_RESOURCE_ID, resourceId);
            return queryBuilder.countOf();
        } catch (SQLException ex) {
            _logger.error("unable to get items count for resource[Type:{}, Id:{}]", resourceType,
                    resourceId, ex);
        }
        return 0;
    }

    @Override
    public QueryResponse getAll(Query query) {
        try {
            return this.getQueryResponse(query, ResourcesGroupMap.KEY_ID, ResourcesGroupMap.KEY_GROUP_ID);
        } catch (SQLException ex) {
            _logger.error("unable to run query:[{}]", query, ex);
            return null;
        }
    }
}


text:
class MAX31725 {
    public:
        MAX31725(uint8_t _samples = TEMPERATURE_MAX_SAMPLES);
        MAX31725(uint8_t _i2cAddress, uint8_t _samples = TEMPERATURE_MAX_SAMPLES);
        ~MAX31725();

        int write_config_register(uint8_t _newConfig);
        int write_thyst_register(uint16_t _newThyst);
        int write_tos_register(uint16_t _newTos);

        uint8_t read_config_register();
        uint8_t read_thyst_register(uint16_t& _regValue);
        uint8_t read_tos_register(uint16_t& _regValue);

        uint8_t recieve_data();
        float convert_temp();

        // Setters
        void set_i2c_address(uint8_t _newAddr) { i2cAddress = _newAddr; }
        void set_num_samples(uint8_t _newSamples);

        // Getters
        uint8_t get_i2c_addr() { return i2cAddress; }
        uint8_t get_num_samples() { return numSamples; }
        uint16_t get_temperature() { return rawTemperature; }
        uint8_t get_current_config() { return currentConfig; }

    private:
        uint8_t i2cAddress;
        uint8_t numSamples;
        uint16_t rawTemperature;
        uint8_t currentConfig;

        int write_two_bytes(uint8_t _reg, uint16_t _value);
        int read_two_bytes(uint8_t _reg, uint16_t& _data);

};

#endif // TEMP_SENSE_H


text:
namespace _4.Distance_Between_Points
{
    using System;

    public class DistanceBetweenPoints
    {
        public static void Main()
        {
            string[] firstPair = Console.ReadLine().Split(' ');
            string[] secondPair = Console.ReadLine().Split(' ');

            Point p1 = new Point()
            {
                X = double.Parse(firstPair[0]),
                Y = double.Parse(firstPair[1])
            };

            Point p2 = new Point()
            {
                X = double.Parse(secondPair[0]),
                Y = double.Parse(secondPair[1])
            };

            Console.WriteLine("{0:f3}",CalculateDistance(p1, p2));
        }

        private static double CalculateDistance(Point p1, Point p2)
        {
            double sideA = p1.X - p2.X;
            double sideB = p1.Y - p2.Y;
            double distance = Math.Sqrt(Math.Pow(sideA, 2) + Math.Pow(sideB, 2));

            return distance;
        }
    }
}


text:
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Query.Expressions;

namespace Microsoft.EntityFrameworkCore.Query.ExpressionTranslators.Internal
{
    /// <summary>
    ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
    ///     directly from your code. This API may change or be removed in future releases.
    /// </summary>
    public class FbStringLengthTranslator : IMemberTranslator
    {
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public virtual Expression Translate(MemberExpression memberExpression)
            => memberExpression.Expression != null
               && memberExpression.Expression.Type == typeof(string)
               && memberExpression.Member.Name == nameof(string.Length)
                ? new SqlFunctionExpression("CHAR_LENGTH", memberExpression.Type, new[] { memberExpression.Expression })
                : null;
    }
}


text:
package com.yammer.tenacity.tests;

import com.google.common.collect.ImmutableList;
import com.yammer.tenacity.core.core.CircuitBreaker;
import com.yammer.tenacity.core.properties.TenacityPropertyKey;
import com.yammer.tenacity.core.properties.TenacityPropertyRegister;
import com.yammer.tenacity.core.resources.TenacityCircuitBreakersResource;
import com.yammer.tenacity.testing.TenacityTestRule;
import io.dropwizard.testing.junit.ResourceTestRule;
import org.glassfish.jersey.client.ClientResponse;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;

import javax.ws.rs.NotFoundException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import java.util.Collections;

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

public class TenacityCircuitBreakersResourceTest {
    @Rule
    public final TenacityTestRule tenacityTestRule = new TenacityTestRule();

    @SuppressWarnings("unchecked")
    private static final Iterable<TenacityPropertyKey> keysMock = mock(Iterable.class);

    @ClassRule
    public static final ResourceTestRule resources = ResourceTestRule.builder()
            .addResource(new TenacityCircuitBreakersResource(keysMock, new DependencyKeyFactory()))
            .build();

    @Before @SuppressWarnings("unchecked")
    public void setup() {
        reset(keysMock);
    }

    @Test
    public void healthyWithNoCircuitBreakers() {
        when(keysMock.iterator()).thenReturn(Collections.<TenacityPropertyKey>emptyIterator());

        assertThat(resources.client().target(TenacityCircuitBreakersResource.PATH).request()
                .get(CircuitBreaker[].class)).isEmpty();
    }

    @Test(expected = NotFoundException.class)
    public void notFoundWhenNoCircuitBreakers() {
        when(keysMock.iterator()).thenReturn(Collections.<TenacityPropertyKey>emptyIterator());

        assertThat(resources.client().target(TenacityCircuitBreakersResource.PATH)
                .path(DependencyKey.NON_EXISTENT_HEALTHCHECK.name())
                .request()
                .get(ClientResponse.class));
    }

    @Test
    public void healthyWithNonExistentCircuitBreakers() {
        when(keysMock.iterator()).thenReturn(ImmutableList.<TenacityPropertyKey>of(DependencyKey.NON_EXISTENT_HEALTHCHECK).iterator());

        assertThat(resources.client().target(TenacityCircuitBreakersResource.PATH).request()
                .get(CircuitBreaker[].class)).isEmpty();
    }

    @Test
    public void healthyWithClosedCircuitBreakers() {
        when(keysMock.iterator()).thenReturn(ImmutableList.<TenacityPropertyKey>of(DependencyKey.EXISTENT_HEALTHCHECK).iterator());

        new TenacitySuccessCommand(DependencyKey.EXISTENT_HEALTHCHECK).execute();

        assertThat(resources.client().target(TenacityCircuitBreakersResource.PATH).request()
                .get(CircuitBreaker[].class))
                .containsExactly(CircuitBreaker.closed(DependencyKey.EXISTENT_HEALTHCHECK));
    }

    @Test
    public void healthyExistentAgnostic() {
        when(keysMock.iterator()).thenReturn(ImmutableList.<TenacityPropertyKey>of(DependencyKey.NON_EXISTENT_HEALTHCHECK, DependencyKey.EXISTENT_HEALTHCHECK).iterator());

        new TenacitySuccessCommand(DependencyKey.EXISTENT_HEALTHCHECK).execute();

        assertThat(resources.client().target(TenacityCircuitBreakersResource.PATH).request()
                .get(CircuitBreaker[].class))
                .containsExactly(CircuitBreaker.closed(DependencyKey.EXISTENT_HEALTHCHECK));
    }

    private static void tryToOpenCircuitBreaker(TenacityPropertyKey key) {
        for (int i = 0; i < 100; i++) {
            new TenacityFailingCommand(key).execute();
        }
    }

    @Test
    public void unhealthyWithOpenCircuitBreaker() {
        when(keysMock.iterator()).thenReturn(ImmutableList.<TenacityPropertyKey>of(DependencyKey.EXISTENT_HEALTHCHECK).iterator());

        tryToOpenCircuitBreaker(DependencyKey.EXISTENT_HEALTHCHECK);

        assertThat(resources.client().target(TenacityCircuitBreakersResource.PATH).request()
                .get(CircuitBreaker[].class))
                .containsExactly(CircuitBreaker.open(DependencyKey.EXISTENT_HEALTHCHECK));
    }

    @Test
    public void mixedResults() {
        when(keysMock.iterator()).thenReturn(ImmutableList.<TenacityPropertyKey>of(DependencyKey.NON_EXISTENT_HEALTHCHECK, DependencyKey.EXISTENT_HEALTHCHECK).iterator());

        tryToOpenCircuitBreaker(DependencyKey.EXISTENT_HEALTHCHECK);

        assertThat(resources.client().target(TenacityCircuitBreakersResource.PATH).request()
                .get(CircuitBreaker[].class))
                .containsExactly(CircuitBreaker.open(DependencyKey.EXISTENT_HEALTHCHECK));
    }

    @Test
    public void multipleOpen() {
        when(keysMock.iterator()).thenReturn(ImmutableList.<TenacityPropertyKey>of(DependencyKey.ANOTHER_EXISTENT_HEALTHCHECK, DependencyKey.EXISTENT_HEALTHCHECK).iterator());

        tryToOpenCircuitBreaker(DependencyKey.EXISTENT_HEALTHCHECK);
        tryToOpenCircuitBreaker(DependencyKey.ANOTHER_EXISTENT_HEALTHCHECK);

        assertThat(resources.client().target(TenacityCircuitBreakersResource.PATH).request()
                .get(CircuitBreaker[].class))
                .contains(
                        CircuitBreaker.open(DependencyKey.EXISTENT_HEALTHCHECK),
                        CircuitBreaker.open(DependencyKey.ANOTHER_EXISTENT_HEALTHCHECK));
    }

    @Test
    public void canFindACircuitBreaker() {
        when(keysMock.iterator()).thenReturn(ImmutableList.<TenacityPropertyKey>of(DependencyKey.EXISTENT_HEALTHCHECK).iterator());

        new TenacitySuccessCommand(DependencyKey.EXISTENT_HEALTHCHECK).execute();

        assertThat(resources.client().target(TenacityCircuitBreakersResource.PATH)
                .path(DependencyKey.EXISTENT_HEALTHCHECK.name())
                .request()
                .get(CircuitBreaker.class))
                .isEqualTo(CircuitBreaker.closed(DependencyKey.EXISTENT_HEALTHCHECK));
    }

    @Test
    public void forcedCloseIsIdentifiedCorrectly() {
        TenacityPropertyRegister.registerCircuitForceClosed(DependencyKey.EXISTENT_HEALTHCHECK);

        when(keysMock.iterator()).thenReturn(ImmutableList.<TenacityPropertyKey>of(DependencyKey.EXISTENT_HEALTHCHECK).iterator());

        assertThat(new TenacitySuccessCommand(DependencyKey.EXISTENT_HEALTHCHECK).execute()).isEqualTo("value");

        assertThat(resources.client().target(TenacityCircuitBreakersResource.PATH)
                .path(DependencyKey.EXISTENT_HEALTHCHECK.name())
                .request()
                .get(CircuitBreaker.class))
                .isEqualTo(CircuitBreaker.forcedClosed(DependencyKey.EXISTENT_HEALTHCHECK))
                .isNotEqualTo(CircuitBreaker.closed(DependencyKey.EXISTENT_HEALTHCHECK));
    }

    @Test
    public void forcedOpenIsIdentifiedCorrectly() {
        TenacityPropertyRegister.registerCircuitForceOpen(DependencyKey.EXISTENT_HEALTHCHECK);

        when(keysMock.iterator()).thenReturn(ImmutableList.<TenacityPropertyKey>of(DependencyKey.EXISTENT_HEALTHCHECK).iterator());

        assertThat(new TenacitySuccessCommand(DependencyKey.EXISTENT_HEALTHCHECK).execute()).isEqualTo("fallback");

        assertThat(resources.client().target(TenacityCircuitBreakersResource.PATH)
                .path(DependencyKey.EXISTENT_HEALTHCHECK.name())
                .request()
                .get(CircuitBreaker.class))
                .isEqualTo(CircuitBreaker.forcedOpen(DependencyKey.EXISTENT_HEALTHCHECK))
                .isNotEqualTo(CircuitBreaker.open(DependencyKey.EXISTENT_HEALTHCHECK));
    }

    @Test
    public void forcedOpenCanBeReset() {
        when(keysMock.iterator()).thenReturn(ImmutableList.<TenacityPropertyKey>of(DependencyKey.EXISTENT_HEALTHCHECK).iterator());
        assertThat(new TenacitySuccessCommand(DependencyKey.EXISTENT_HEALTHCHECK).execute()).isEqualTo("value");
        assertThat(resources.client().target(TenacityCircuitBreakersResource.PATH)
                .path(DependencyKey.EXISTENT_HEALTHCHECK.name())
                .request()
                .get(CircuitBreaker.class))
                .isEqualTo(CircuitBreaker.closed(DependencyKey.EXISTENT_HEALTHCHECK));

        TenacityPropertyRegister.registerCircuitForceOpen(DependencyKey.EXISTENT_HEALTHCHECK);

        when(keysMock.iterator()).thenReturn(ImmutableList.<TenacityPropertyKey>of(DependencyKey.EXISTENT_HEALTHCHECK).iterator());
        assertThat(new TenacitySuccessCommand(DependencyKey.EXISTENT_HEALTHCHECK).execute()).isEqualTo("fallback");
        assertThat(resources.client().target(TenacityCircuitBreakersResource.PATH)
                .path(DependencyKey.EXISTENT_HEALTHCHECK.name())
                .request()
                .get(CircuitBreaker.class))
                .isEqualTo(CircuitBreaker.forcedOpen(DependencyKey.EXISTENT_HEALTHCHECK))
                .isNotEqualTo(CircuitBreaker.open(DependencyKey.EXISTENT_HEALTHCHECK));

        TenacityPropertyRegister.registerCircuitForceReset(DependencyKey.EXISTENT_HEALTHCHECK);

        when(keysMock.iterator()).thenReturn(ImmutableList.<TenacityPropertyKey>of(DependencyKey.EXISTENT_HEALTHCHECK).iterator());
        assertThat(new TenacitySuccessCommand(DependencyKey.EXISTENT_HEALTHCHECK).execute()).isEqualTo("value");
        assertThat(resources.client().target(TenacityCircuitBreakersResource.PATH)
                .path(DependencyKey.EXISTENT_HEALTHCHECK.name())
                .request()
                .get(CircuitBreaker.class))
                .isEqualTo(CircuitBreaker.closed(DependencyKey.EXISTENT_HEALTHCHECK));
    }

    @Test
    public void canModifyACircuitBreakerToBeForceClosed() {
        when(keysMock.iterator()).thenReturn(ImmutableList.<TenacityPropertyKey>of(DependencyKey.EXISTENT_HEALTHCHECK).iterator());

        assertThat(new TenacitySuccessCommand(DependencyKey.EXISTENT_HEALTHCHECK).execute()).isEqualTo("value");

        assertThat(resources.client().target(TenacityCircuitBreakersResource.PATH)
                .path(DependencyKey.EXISTENT_HEALTHCHECK.name())
                .request(MediaType.APPLICATION_JSON_TYPE)
                .put(Entity.entity(CircuitBreaker.State.FORCED_CLOSED.name(), MediaType.APPLICATION_OCTET_STREAM_TYPE), CircuitBreaker.class))
                .isEqualTo(CircuitBreaker.forcedClosed(DependencyKey.EXISTENT_HEALTHCHECK));
    }

    @Test
    public void canModifyACircuitBreakerToBeForceOpen() {
        when(keysMock.iterator()).thenReturn(ImmutableList.<TenacityPropertyKey>of(DependencyKey.EXISTENT_HEALTHCHECK).iterator());

        assertThat(new TenacitySuccessCommand(DependencyKey.EXISTENT_HEALTHCHECK).execute()).isEqualTo("value");

        assertThat(resources.client().target(TenacityCircuitBreakersResource.PATH)
                .path(DependencyKey.EXISTENT_HEALTHCHECK.name())
                .request(MediaType.APPLICATION_JSON_TYPE)
                .put(Entity.entity(CircuitBreaker.State.FORCED_OPEN.name(), MediaType.APPLICATION_OCTET_STREAM_TYPE), CircuitBreaker.class))
                .isEqualTo(CircuitBreaker.forcedOpen(DependencyKey.EXISTENT_HEALTHCHECK));
    }

    @Test
    public void canModifyACircuitBreakerToBeForceOpenBackToItsOriginalState() {
        when(keysMock.iterator()).thenReturn(ImmutableList.<TenacityPropertyKey>of(DependencyKey.EXISTENT_HEALTHCHECK).iterator());

        assertThat(new TenacitySuccessCommand(DependencyKey.EXISTENT_HEALTHCHECK).execute()).isEqualTo("value");

        assertThat(resources.client().target(TenacityCircuitBreakersResource.PATH)
                .path(DependencyKey.EXISTENT_HEALTHCHECK.name())
                .request(MediaType.APPLICATION_JSON_TYPE)
                .put(Entity.entity(CircuitBreaker.State.FORCED_OPEN.name(), MediaType.APPLICATION_OCTET_STREAM_TYPE), CircuitBreaker.class))
                .isEqualTo(CircuitBreaker.forcedOpen(DependencyKey.EXISTENT_HEALTHCHECK));

        when(keysMock.iterator()).thenReturn(ImmutableList.<TenacityPropertyKey>of(DependencyKey.EXISTENT_HEALTHCHECK).iterator());

        assertThat(resources.client().target(TenacityCircuitBreakersResource.PATH)
                .path(DependencyKey.EXISTENT_HEALTHCHECK.name())
                .request(MediaType.APPLICATION_JSON_TYPE)
                .put(Entity.entity(CircuitBreaker.State.FORCED_RESET.name(), MediaType.APPLICATION_OCTET_STREAM_TYPE), CircuitBreaker.class))
                .isEqualTo(CircuitBreaker.closed(DependencyKey.EXISTENT_HEALTHCHECK));
    }
}


text:
package dk.onlinecity.qrr.client;

import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.GameCanvas;

import dk.onlinecity.qrr.QrReader;
import dk.onlinecity.qrr.image.ImageUtil;
import dk.onlinecity.qrr.image.Thumbnail;

public class DecodeCanvas extends GameCanvas implements Runnable
{
	private QrReaderMidlet midlet;
	private Thread thread;
	private Thumbnail thumbnail;
	private int[] pixels;
	private int ih;
	private int iw;
	private int[] ul;
	private int[] ur;
	private int[] ll;
	private int[] lr;

	private int attempt = 1;
	private int attempts;

	private String message = "No QR Code found.";
	private boolean showMessage = false;
	private String result;

	public DecodeCanvas(QrReaderMidlet midlet, byte[] rawImage)
	{
		super(true);
		// #if !motorola
		setFullScreenMode(true);
		// #endif
		this.midlet = midlet;

		Image tmp = Image.createImage(rawImage, 0, rawImage.length);

		iw = tmp.getWidth();
		ih = tmp.getHeight();

		int tw = getWidth() - 60;
		int th = (int) ((double) tw * ((double) ih / (double) iw));
		pixels = new int[iw * ih];

		tmp.getRGB(pixels, 0, iw, 0, 0, iw, ih);
		thumbnail = ImageUtil.getThumbnail(pixels, iw, ih, tw, th);
		render(getGraphics());
		flushGraphics();
	}

	protected void showNotify()
	{
		if (thread == null) {
			thread = new Thread(this);
			thread.start();
		}

	}

	public void run()
	{
		decode();
	}

	private void decode()
	{
		QrReader qrReader = new QrReader(pixels, iw, ih, 8, 6);
		attempts = qrReader.getAttempts();
		render(getGraphics());
		flushGraphics();
		try {
			result = null;
			while (result == null) {
				result = qrReader.scan();
				ul = thumbnail.translateCoordinate(qrReader.getUl());
				ur = thumbnail.translateCoordinate(qrReader.getUr());
				ll = thumbnail.translateCoordinate(qrReader.getLl());
				lr = thumbnail.translateCoordinate(qrReader.getLr());
				render(getGraphics());
				flushGraphics();
				// System.out.println("attempt:" + attempt);
				attempt++;
			}

			System.out.println("result:" + result);
			render(getGraphics());
			flushGraphics();

		} catch (Exception e) {
			result = null;
			e.printStackTrace();
		}

		if (result == null) {
			long time = System.currentTimeMillis() + 2500;
			while (System.currentTimeMillis() < time) {
				showMessage = true;
				render(getGraphics());
				flushGraphics();
				Thread.yield();
			}
			midlet.showCamera();
			// midlet.showCamera();
		} else {
			midlet.showResult(result);
		}
		// processingImage = false;
	}

	private void render(Graphics g)
	{
		g.setColor(0x0);
		g.fillRect(0, 0, getWidth(), getHeight());
		g.drawImage(drawSquare(thumbnail.getImage()), getWidth() >> 1, getHeight() >> 1, Graphics.HCENTER | Graphics.VCENTER);
		g = getGraphics();
		if (showMessage) {
			g.setColor(0xffffff);
			g.setFont(Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_MEDIUM));
			g.drawString(message, getWidth() >> 1, getHeight() - 5, Graphics.BOTTOM | Graphics.HCENTER);
		} else {
			renderProgress(g, 20, getWidth() - 20, 10);
		}

	}

	private Image drawSquare(Image thumb)
	{
		if (ul != null || ur != null || lr != null || ll != null) {
			Image image = Image.createImage(thumb.getWidth(), thumb.getHeight());
			Graphics g = image.getGraphics();
			g.drawImage(thumb, 0, 0, Graphics.TOP | Graphics.LEFT);
			g.setColor(0x00ff00);
			if (ul != null && ur != null) g.drawLine(ul[0], ul[1], ur[0], ur[1]);
			if (ur != null && lr != null) g.drawLine(ur[0], ur[1], lr[0], lr[1]);
			if (lr != null && ll != null) g.drawLine(lr[0], lr[1], ll[0], ll[1]);
			if (ll != null && ul != null) g.drawLine(ll[0], ll[1], ul[0], ul[1]);
			return image;
		}
		return thumb;
	}

	private int getProcess(int x0, int x1)
	{
		int w = x1 - x0;
		double progress = (double) attempt / (double) attempts;

		return (int) (progress * ((double) w));
	}

	private void renderProgress(Graphics g, int x0, int x1, int height)
	{
		g.setColor(0xffffff);
		g.fillRect(x0, getHeight() - height - 10, x1 - x0, height);
		g.setColor(0);
		g.fillRect(x0 + 1, getHeight() - height - 10 + 1, x1 - x0 - 2, height - 2);
		g.setColor(0xffffff);
		g.fillRect(x0 + 2, getHeight() - height - 10 + 2, getProcess(x0, x1 - 2 - 2), height - 4);
	}
}


text:
package com.aspose.slides.examples.text;

import com.aspose.slides.AutoShape;
import com.aspose.slides.Presentation;
import com.aspose.slides.SaveFormat;
import com.aspose.slides.TextHighlightingOptions;
import com.aspose.slides.examples.RunExamples;

import java.awt.*;

public class HighlightTextusingRegex
{
    public static void main(String[] args)
    {

        //ExStart:HighlightTextUsingRegx
        // The path to the documents directory.
        String dataDir = RunExamples.getDataDir_Text();
        Presentation presentation = new Presentation(dataDir + "SomePresentation.pptx");
        TextHighlightingOptions options = new TextHighlightingOptions();
        ((AutoShape) presentation.getSlides().get_Item(0).getShapes().get_Item(0)).getTextFrame().highlightRegex("\\b[^\\s){5,}\\b", Color.BLUE, options); // highlighting all words with 10 symbols or longer
        presentation.save(dataDir + "SomePresentation-out.pptx", SaveFormat.Pptx);

        //ExEnd:HighlightTextUsingRegx
    }
}


text:
{% extends 'mapApp/base.html' %}

{% load static crispy_forms_tags i18n %}

{% block body %}

{% trans "Password reset successful" %}

{% trans "We've emailed you instructions for setting your password. You should be receiving them shortly." %}

{% trans "If you don't receive an email, please make sure you've entered the address you registered with, and check your spam folder." %}

{% endblock %}


text:
# pokenv [![Build status](https://ci.appveyor.com/api/projects/status/hrtwo6hrx10d7i88?svg=true)](https://ci.appveyor.com/project/tischda/pokenv)

Windows utility written in [Go](https://www.golang.org) to poke
environment variables into the registry.

### Install

There are no dependencies.

~~~
go get github.com/tischda/pokenv
~~~

### Usage

~~~
Usage: pokenv [-h] [-c] [-m] [-f infile]

OPTIONS:
  -c
  -checkpaths
        check if values are valid paths on this system
  -f string
        file containing the variables to load into the Windows environment (default "REQUIRED")
  -h
  -help
        displays this help message
  -m
  -machine
        specifies that the variables should be set system wide (HKEY_LOCAL_MACHINE)
  -v
  -version
        print version and exit
~~~

Examples:

~~~
# pokenv.exe -f data\setvar.txt
Setting `POKE_SECTION` to `valueline1`

# pokenv.exe
[MYVAR]
value1
value2
^Z
Setting `MYVAR` to `value1;value2`

# pokenv.exe
[MYVAR]
^Z
Deleting MYVAR
~~~

#### Input format

The input file has the following format:

~~~
# This is a comment
[Path]
C:\Windows\SYSTEM32
C:\Windows
C:\Windows\SYSTEM32\WBEM
C:\Windows\System32\WindowsPowerShell\v1.0

[TODELETE]
# nothing here means delete this variable
~~~

This is also the format generated by [peekenv](https://github.com/tischda/peekenv).

### Other setters

* http://sourceforge.net/projects/pathmanager/files/?source=navbar
* http://www.rapidee.com/en/about
* http://p-nand-q.com/download/gtools/pathed.html
* http://ss64.com/nt/setx.html


text:
<?php

namespace Core;

use \Exception;

/**
 * Static class to aid in debugging and error logging.
 */
class Log {

	/**
	 * @var array Contains associative array with "type" of log value and the actual output as the "value".
	 */
	private static $log = array();

	/**
	 * 0: The log goes into an empty void, never to be seen again.
	 * 1: Saves the log to "application.log".
	 * 2: Outputs the log to a javascript console.log command.
	 * 3: Saves the log to the log SQL database.
	 *
	 * @var int Defines the location that the log will be written to.
	 */
	private static $log_location = 2;

	/**
	 * @var float Time that the execution started.
	 */
	private static $start_time = 0;

	/**
	 * Internal variable that keeps the last memory usage since the last log call.
	 * @var number
	 */
	private static $last_memory_usage = 0;

	/**
	 * Sets the current log level.
	 * 0: No information was logged.
	 * 1: Debug
	 * 2: Information
	 * 3: Error
	 * @var int
	 */
	private static $log_current_level = 0;

	/**
	 * Contains benchmark points to measure.
	 * @var array
	 */
	private static $bench_points = array();

	/**
	 * Method to initialize starup variables required for time logging.

	 * @param number Time that the script started.
	 */
	public static function initialize() {
		self::$log_location = \Config::LOG_LOCATION;
		self::$start_time = microtime(true);
		self::debug("Loaded Core classes.  Initialized Log class.");
	}

	/**
	 * Sets the logging location for this request.

	 * 0: The log goes into an empty void, never to be seen again.

	 * 1: Saves the log to the configured error log.

	 * 2: Outputs the log to a javascript console.log command.

	 * 3: Saves the log to the log SQL database.
	 *
	 * @param int $location Integer defining the location to write the log.
	 */
	public static function setLogLocation($location) {
		self::$log_location = $location;
	}

	/**
	 *
Method to be called twice around an operation to get debugging information

	 * and execution times.

	 *
Usage: Call at the start of the code you want to benchmark with just an ID string.

	 * Call the second time to log the results.  String passed to the $text paramter will

	 * be passed to this benchmark log.

	 *
	 * @param string $id Reference to this benchmark.
	 * @param string $text Text to send to the debug log.
	 */
	public static function benchmark($id, $text = "") {
		if(isset(self::$bench_points[$id]) === false) {
			// Set the beginning bench mark point.
			self::$bench_points[$id] = array(memory_get_usage(false), microtime(true));
		} else {
			$mem_delta = memory_get_usage(false) - self::$bench_points[$id][0];

			$bench_line = "[Benchmark] (";

			if($mem_delta < 0) {
				$bench_line .= '-';
			} else {
				$bench_line .= '+';
			}

			$bench_line .= self::convertBytes(abs($mem_delta), 1);
			$bench_line .= ") (";
			$bench_line .= number_format((microtime(true) - self::$bench_points[$id][1]) * 1000, 2, '.', ',');
			$bench_line .= " ms) ";
			$bench_line .= $text;

			self::$log[] = self::buildLogLine("info", debug_backtrace(), $bench_line);
			unset(self::$bench_points[$id]);
		}
	}

	/**
	 * Logs a debugging item.
	 *
	 * @param string $log_text Text to send to the debug log.
	 */
	public static function debug($log_text) {
		if(\Config::LOG_DEBUG) {
			if(self::$log_current_level < 1) {
				self::$log_current_level = 1;
			}

			self::$log[] = self::buildLogLine("log", debug_backtrace(), $log_text);
		}
	}

	/**
	 * Logs a debugging item.
	 *
	 * @param string $log_text Text to send to the info log.
	 */
	public static function info($log_text) {
		if(\Config::LOG_DEBUG) {
			if(self::$log_current_level < 1) {
				self::$log_current_level = 1;
			}

			self::$log[] = self::buildLogLine("info", debug_backtrace(), $log_text);
		}
	}

	/**
	 * Adds a string of text to the log line without any additional preformatted text.
	 *
	 * @param string $log_text Raw text to output to the log.
	 */
	public static function line($log_text) {
		if(\Config::LOG_DEBUG) {
			self::$log[] = array("type" => "log", "value" => $log_text);
		}
	}

	/**
	 * Logs an error with an associated backtrace.
	 * @param string $log_text Text to send to the error log.
	 * @param bool $throw If ture, error call will kill the script execution. If false, error will not throw.
	 */
	public static function error($log_text, $throw = true) {
		if(self::$log_current_level < 3) {
			self::$log_current_level = 3;
		}
		if(DEBUG) {
			echo "
";
			echo $log_text;
			echo "
";
		}
		self::$log[] = self::buildLogLine("error", debug_backtrace(), $log_text);

		// If this is an unrecoverable error, we need to stop execution.
		if($throw) {
			throw new Exception("A fatal error occured.  A report has been filed with the administrator.");
		}
	}

	/**
	 * Saves or outputs a log to the user.  Output type depends on $log_location.
	 */
	public static function outputLog() {
		// If we do not have anything in the log, then there is nothing to output.
		if(count(self::$log) === 0) {
			return;
		}

		switch(self::$log_location) {
			case 0: break;
			// Empty void.
			case 1:
				// Check to see if we need to log anything to the server
				if(self::$log_current_level > 1) {
					$log_file_handle = fopen(BASEPATH . APP_DIR . "/" . \Config::LOG_FILE, 'a');
					// Log header.
					fprintf($log_file_handle, "[IP:%s TIME:%s USER_ID:%s] BEGIN LOG:\n", self::$main->User->Ipv4, time(), self::$main->User->Id);

					// Log body.  Just seperate each part of the log with a sepearate line.
					foreach(self::$log as $log_item) {
						fwrite($log_file_handle, $log_item['value']);
						fwrite($log_file_handle, "\n");
					}

					// Log footer.
					fwrite($log_file_handle, "END LOG;\n");

					fclose($log_file_handle);
				}

				break;

			case 2:
				// Output as a javascript object easily read by FireBug
				echo "";
				break;
			case 3:
				// TODO: Write logging code to write to database
				/* @var $model Core\LogModel */
				Main::app()->Loader->model('Core\LogModel');
				break;
		}
	}

	/**
	 * Builds a log line item with all the memory and time information.
	 *
	 * @param string $log_type Destribes what type of log item this is.

	 *	Used for the Javascript log outout.
	 * @param array $debug_trace backtrace from where the log was called.
	 * @param string $log_value Text to write about this log line.
	 *
	 * @return array Associative array with a log type and a value for the log.
	 */
	private static function buildLogLine($log_type, $debug_trace, $log_value) {
		$calling_info = $debug_trace[0];
		// Calling information
		$log_builder = "";
		$calling_file = explode("/", $calling_info["file"]);
		$log_builder .= sprintf("[%+15.15s:%3s] ", $calling_file[count($calling_file) - 1], $calling_info["line"]);

		// Time output.
		$log_builder .= "(";
		$log_builder .= number_format((microtime(true) - self::$start_time) * 1000, 2, '.', ',');
		$log_builder .= " ms) ";

		// Output the memory usage information if requested.
		if(\Config::LOG_MEMORY_USAGE === true) {
			$log_builder .= "(";
			$new_memory = $mem_delta = memory_get_usage(false);

			// Check to see if we want to log the delta or absolute value.
			if(\Config::LOG_MEMORY_USAGE_DELTA) {
				$mem_delta = $new_memory - self::$last_memory_usage;
				// Add the plus or minus depending on whether a memory cleanup event happened at some point.
				if($mem_delta < 0) {
					$log_builder .= '-';
				} else {
					$log_builder .= '+';
				}
				self::$last_memory_usage = $new_memory;
			}

			$log_builder .= self::convertBytes(abs($mem_delta), (\Config::LOG_MEMORY_USAGE_DELTA) ? 0 : 3 );
			$log_builder .= ') ';
		}

		$log_builder .= $log_value;

		if(\Config::LOG_IMMEDIATE_MODE) {
			echo $log_type . " " . $log_builder . "
\n";
		}

		return array("type" => $log_type, "value" => $log_builder);
	}

	public static function convertBytes($bytes, $round = 0) {
		$unit = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
		return @round($bytes / pow(1024, ($i = floor(log($bytes, 1024)))), $round) . ' ' . $unit[$i];
	}

}


text:
<?php

namespace MusicBrainz\Supplement\Field;

trait ReleasesTrait
{
    /**
     * True, if releases should be included, otherwise false
     *
     * @var bool
     */
    private bool $releases = false;

    /**
     * Returns true, if releases should be included, otherwise false.
     *
     * @return bool
     */
    public function getIncludeFlagForReleases(): bool
    {
        return $this->releases;
    }

    /**
     * Sets whether releases should be included.
     *
     * @param bool $releases True, if releases should be included, otherwise false
     *
     * @return self
     */
    public function includeReleases(bool $releases = true): self
    {
        $this->releases = $releases;

        return $this;
    }
}


text:
namespace Bog.Web.Api
{
    using System.Collections.Generic;
    using System.Web.Mvc;

    using AutoMapper;

    using Bog.Composition;

    /// <summary>
    ///     The register mapping definitions.
    /// </summary>
    public class EntityMapping : Profile
    {
        #region Public Properties

        /// <summary>
        ///     Gets the profile name.
        /// </summary>
        public override string ProfileName
        {
            get
            {
                return this.GetType().Name;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        ///     The configure.
        /// </summary>
        protected override void Configure()
        {
            var container = DependencyResolver.Current.GetService<BogCompositionContainer>();

            IEnumerable<IEntityMapping> externalMappings = container.GetExportedValues<IEntityMapping>();

            foreach (IEntityMapping externalBinding in externalMappings)
            {
                externalBinding.CreateMap(this);
            }
        }

        #endregion
    }
}


text:
`Crack the Net` is a completely new version of `Hack the Net`.

**Visit:** The [CrackTheNet website](https://www.crack-the-net.com)

**Be awesome:** [Support](#support) the future of CTN

Grab the source and join in the fun!

## Support me!
[![Support with Donation](https://pledgie.com/campaigns/33863.png?skin_name=chrome)](https://pledgie.com/campaigns/33863)

## Contents

- [Download](#download)
- [Installation](#install)
- [Support](#support)

---

![Download Phaser](https://www.crack-the-net.com/.github/header_download.png "Download CTN")

CTN is [hosted on Github][CTN]. There are a number of ways to download it:

* Clone the git repository via [https][clone-http], [ssh][clone-ssh] or with the Github [Windows][clone-ghwin] or [Mac][clone-ghmac] clients.
* Download as [zip][get-zip] or [tar.gz][get-tgz]
* Checkout with [svn][clone-svn]

### License

Phaser is released under the [MIT License](http://opensource.org/licenses/MIT).

![Install](https://www.crack-the-net.com/.github/header_install.png "Installation")

Download Crack the Net and upload it on your webspace.

**Requirements**

- PHP5
- MySQL
- less than 5 MB HDD space

![Support](https://www.crack-the-net.com/.github/header_support.png "Support US")

Developing takes a lot of time, effort, and money. There are monthly running costs; such as the server for developing and the website, which we maintain 100% ad-free. As well as countless hours of development time, community support, and assistance resolving issues.

If you like `Crack the Net` or have made income as a result of using it, and are in a position to support us financially, without causing any detriment to yourself, then please do. There are a number of ways:

* Send money over [PayPal](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=CLUKL96FQBRWJ).
* Ask us private for bank details

It all helps cover our running costs, and genuinely contributes towards future development.

If you would like to sponsor us, then please [get in touch](mailto:info@crack-the-net.com). We have sponsorship options available on our GitHub repo and web site. All of which receive tens of thousands of eyeballs per day.

[CTN]: https://github.com/CrackTheNet/
[clone-http]: https://github.com/CrackTheNet/Core.git
[clone-ssh]: git@github.com:CrackTheNet/Core.git
[clone-svn]: https://github.com/CrackTheNet/Core
[clone-ghwin]: github-windows://openRepo/https://github.com/CrackTheNet/Core
[clone-ghmac]: github-mac://openRepo/https://github.com/CrackTheNet/Core
[get-zip]: https://github.com/CrackTheNet/Core/archive/master.zip
[get-tgz]: https://github.com/CrackTheNet/Core/archive/master.tar.gz


text:
5 SHAPES

COMING SOON


text:
<?php

namespace frontend\assets;
use yii\web\AssetBundle;

/**
 * @author Mahesh Joshi <mahesh@bentraytech.com>
 * @since 2.0
 */

class AdminLteAsset extends AssetBundle
{
    public $sourcePath = '@vendor/bower/admin-lte/dist';
    public $css = [
        'css/AdminLTE.css',
        'css/skins/_all-skins.css',
    ];
    public $js = ['js/app.js'];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
        'yii\bootstrap\BootstrapPluginAsset',
        '\rmrevin\yii\fontawesome\AssetBundle'
    ];
}


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

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ui.DetailMovieActivity"
            android:parentActivityName=".ui.MainActivity"
            android:theme="@style/AppTheme">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".ui.MainActivity" />
        </activity>
        <service android:enabled="true" android:name=".services.AddingToDatabaseService"/>
        <provider
            android:name=".data.provider.MovieProvider"
            android:authorities="com.kacper.popularmovies"
            android:exported="false" />

    </application>

</manifest>


text:
DEBUG=

# SelectRootFileSystem() creates a dialog to select one of all available removable
# devices. The path to the selected device is stored in the variale DevicePath.
SelectRootFileSystem() {
	strSelection="0 ext4 1 ext3"
	dialog --title 'Select rootfs type'\
	--menu 'Move using [UP] [DOWN],[Enter] to select' 10 100 2\
	${strSelection}\
	2>/tmp/menuitem.$$

	# get OK/Cancel
	sel=$?
	# get selected menuitem
	menuitem=`cat /tmp/menuitem.$$`
	rm -f /tmp/menuitem.$$

	# Cancel Button or <ESC>
	if [ $sel -eq 1 -o $sel -eq 255 ] ; then
		echo 'Cancel selected SelectRootFileSystem()'
		return 1
	fi
	# Selection
	case $menuitem in
		0) RootfsType='ext4';;
		1) RootfsType='ext3';;
		*) echo "Unknown type"; exit 1;;
	esac
}

run_user() {
	if [ -z $DevicePath ]; then
		SelectCardDevice || exit 1
	fi
	if [ -z $RootfsType ]; then
		SelectRootFileSystem || exit 1
	fi
	if [ $# -gt 2 ]; then
		echo "Usage: $0 [Card device path] [Rootfs type]"
		exit 1;
	fi
	RootParams="$DevicePath $RootfsType"
}

run_root() {
	# device node valid?
	if [ ! -b $DevicePath ] ; then
		echo "$DevicePath is not a valid block device!"
		exit 1
	fi

	# file system valid?
	case $RootfsType in
		ext3) ;;
		ext4) ;;
		*) echo "Unknown rootfs type"; exit 1;;
	esac

	# check if the card is currently mounted
	MOUNTSTR=$(mount | grep $DevicePath)
	if [ -n "$MOUNTSTR" ] ; then
	    echo -e "\n$DevicePath is currenly mounted. Needs unmounting..."
	    $DEBUG umount -f ${DevicePath}?*
	fi

	# kill u-boot environment
	$DEBUG dd if=/dev/zero of=$DevicePath bs=1024 count=1024

	# Create the FAT partition of 64MB and make it bootable
	$DEBUG parted -s $DevicePath mklabel msdos
	$DEBUG parted -s $DevicePath mkpart primary fat32 63s 64MB
	$DEBUG parted -s $DevicePath toggle 1 boot

	# Create the rootfs partition until end of device
	$DEBUG parted -s $DevicePath -- mkpart primary $RootfsType 64MB -0

	# write partitions
	$DEBUG mkfs.vfat -F 32 -n "boot" -I ${DevicePath}1
	$DEBUG mke2fs -F -j -t $RootfsType -L "rootfs" ${DevicePath}2
}

. `dirname $0`/tools.inc
DevicePath=$1
RootfsType=$2
# On the 1st call: run user
# After the 2nd call: run root
chk_root && run_root


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <link rel="stylesheet" type="text/css" href="../../../framework/fss/css/fss-reset.css" />
        <link rel="stylesheet" type="text/css" href="../../../framework/fss/css/fss-layout.css" />
        <link rel="stylesheet" type="text/css" href="../../../framework/fss/css/fss-text.css" />
        <link rel="stylesheet" type="text/css" href="../../../framework/fss/css/fss-theme-hc.css" />
        <link rel="stylesheet" type="text/css" href="../../../framework/fss/css/fss-theme-hci.css" />
        <link rel="stylesheet" type="text/css" href="../../../framework/fss/css/fss-theme-slate.css" />
        <link rel="stylesheet" type="text/css" href="../../../framework/fss/css/fss-theme-coal.css" />
        <link rel="stylesheet" type="text/css" href="../../../framework/fss/css/fss-theme-mist.css" />
        <link rel="stylesheet" type="text/css" href="../../../framework/fss/css/fss-theme-rust.css" />
        <link rel="stylesheet" type="text/css" href="../../../lib/jquery/ui/css/fl-theme-coal/coal.css" />
        <link rel="stylesheet" type="text/css" href="../../../lib/jquery/ui/css/fl-theme-mist/mist.css" />
        <link rel="stylesheet" type="text/css" href="../../../lib/jquery/ui/css/fl-theme-slate/slate.css" />
        <link rel="stylesheet" type="text/css" href="../../../lib/jquery/ui/css/fl-theme-hc/hc.css" />
        <link rel="stylesheet" type="text/css" href="../../../lib/jquery/ui/css/fl-theme-hci/hci.css" />
        <link rel="stylesheet" type="text/css" href="../../../components/uiOptions/css/UIOptions.css" />
        <link rel="stylesheet" type="text/css" href="../../../components/uiOptions/css/Slider.css" />

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

        <title>UI Options</title>

Some Sample Title

Some content with a link and<button id="myButton">a button</button>.

        <button class="myButton">Edit Appearance</button>


text:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;

public partial class MasterPageError : BaseMaster
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //doesn't cache the page so users cannot back into sensitive information after logging off
        //Response.AddHeader("X-UA-Compatible", "IE=8");
        //Response.Cache.SetAllowResponseInBrowserHistory(false);
        //Response.Cache.SetCacheability(HttpCacheability.NoCache);
        //Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
        //Response.Cache.SetNoStore();
        //Response.AddHeader("Pragma", "no-cache");
    }
}


text:
<!DOCTYPE html>

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

      <router-view></router-view>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Søchting, Øvstedal & Sancho, Biblthca Lichenol. 88: 623 (2004)

#### Original name
Caloplaca insignis Søchting & Øvstedal

### Remarks
null


text:
<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width" />

        <title>Diverso | Just another YIW Themes Demo Sites site</title>

        <link rel="stylesheet" type="text/css" media="all" href="style.css" />
        <link rel="stylesheet" type="text/css" media="screen and (max-width: 960px)" href="css/lessthen800.css" />
        <link rel="stylesheet" type="text/css" media="screen and (max-width: 600px)" href="css/lessthen600.css" />
        <link rel="stylesheet" type="text/css" media="screen and (max-width: 480px)" href="css/lessthen480.css" />

        <link rel="stylesheet" type="text/css" media="all" href="css/custom-style.css" />

        <link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
        <link rel="icon" type="image/x-icon" href="favicon.ico" />

        <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz%3A400&subset=latin%2Ccyrillic%2Cgreek" type="text/css" media="all" />
        <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Droid+Sans" type="text/css" media="all" />
	    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Oswald" type="text/css" media="all" />
        <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz%3A200%2C400" type="text/css" media="all" />
        <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans+Condensed%3A300%7CPlayfair+Display%3A400italic" type="text/css" media="all" />

        <link rel="stylesheet" id="prettyPhoto-css" href="css/prettyPhoto.css" type="text/css" media="all" />
        <link rel="stylesheet" id="jquery-tipsy-css" href="css/tipsy.css" type="text/css" media="all" />

        <link rel="stylesheet" id="slider-elastic-css" href="css/slider-elastic.css" type="text/css" media="all" />

        <link rel="stylesheet" id="slider-cycle-css" href="css/slider-cycle.css" type="text/css" media="all" />

        <link rel="stylesheet" id="slider-thumbnails-css" href="css/slider-thumbnails.css" type="text/css" media="all" />

        <link rel="stylesheet" id="slider-elegant-css" href="css/slider-elegant.css" type="text/css" media="all" />

        <link rel="stylesheet" id="slider-nivo-css" href="css/slider-nivo.css" type="text/css" media="all" />

                                Login

 | Contact Us

                                HOME

HOME VERSION 2

HOME VERSION 3

HOME VERSION 4

HOME VERSION 5

HOME VERSION 6

                                Pages

Faq

Testimonials

Staff

Gallery

Archives

                                Portfolio

3 Columns

With Slider

Big Image

Full Description

Filterable

                                Shortcodes

Nivo Slider

Media & Widgets

Alert box & buttons

Icon Sections

Table & Box prices

Typography

Mix & Various

                                Blog

Small Image

Big image

Contact

This is a nice staff page

with the accordion slider for your team

Susanna

Web designer

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec placerat odio.  Vestibulum in orci nec turpis ultrices malesuada at et dolor. Praesent  dapibus augue ac mauris fringilla condimentum vestibulum!

Samuel

Art director

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec placerat odio.  Vestibulum in orci nec turpis ultrices malesuada at et dolor. Praesent  dapibus augue ac mauris fringilla condimentum vestibulum!

Thomas

Sales Account

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec placerat odio.  Vestibulum in orci nec turpis ultrices malesuada at et dolor. Praesent  dapibus augue ac mauris fringilla condimentum vestibulum!

Victor

Customer service

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec placerat odio.  Vestibulum in orci nec turpis ultrices malesuada at et dolor. Praesent  dapibus augue ac mauris fringilla condimentum vestibulum!

Jasmine

Copywriter

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec placerat odio.  Vestibulum in orci nec turpis ultrices malesuada at et dolor. Praesent  dapibus augue ac mauris fringilla condimentum vestibulum!

Welcome to our staff page

                            Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
                            Curabitur a quam in erat placerat tempor non ac orci. Class aptent taciti
                            sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.

                            Duis at tellus in ante fringilla lobortis. Sed tincidunt molestie justo molestie varius.
                            Nullam id pellentesque mauris. Quisque et sapien condimentum dui viverra
                            mollis ac et risus. Donec diam nibh, cursus in elementum eget, mollis sit amet tellus.

                            Phasellus in sapien ipsum. Vestibulum gravida odio sit amet magna tincidunt sit amet
                            sagittis mauris tempus.

                            Curabitur a quam in erat placerat tempor non ac orci. Class aptent taciti sociosqu ad
                            litora torquent per conubia nostra, per inceptos himenaeos.

Featured Projects

Prev

                                            Kassyopea Theme

web design

                                            Olìmpo

restyling, web design

                                            Coffee Break

logo design

                                            Tiramisu video

logo design, web design

                                            Kalysphèra

logo design, web design

                                            Impero Brand

logo design

                                            Brand: Food In Love

logo design

Next

COMPANY

                                Di'verso is a new WordPress all in one, clean & modern In in
                                odio ut lectus posuere consequat in nec ipsum. Proin pretium
                                ullamcorper lectus non feugiat.

PHOTOSTREAMING

RECENT POSTS

                                            A fresh and nice blog layout: do u like it?

December 13, 2011

                                            50% off on our products for the month of August

December 7, 2011

MENU

About Di’verso

Contact Di’verso

Shortcodes

Blog

Your Inspiration Web

Copyright Diverso 2010 - Powered by Your Inspiration Web

                            facebook
                            rss
                            flickr
                            youtube
                            twitter
                            linkedin
                            mail
                            skype


text:
using System;
using System.ComponentModel;
using DigitalRune.Windows.TextEditor.Insight;

namespace DigitalRune.Windows.TextEditor
{
  public partial class TextEditorControl
  {
    private InsightWindow _insightWindow;

    /// <summary>
    /// Gets a value indicating whether the insight window is shown at the moment.
    /// </summary>
    /// <value>
    /// 	<see langword="true"/> if the insight window is visible; otherwise, <see langword="false"/>.
    /// </value>
    [Browsable(false)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public bool InsightWindowVisible
    {
      get { return _insightWindow != null; }
    }

    /// <summary>
    /// Occurs when method insight is requested.
    /// </summary>
    [Category("Misc")]
    [Description("Occurs when method insight is requested.")]
    public event EventHandler<InsightEventArgs> InsightRequest;

    /// <summary>
    /// Shows the insight window.
    /// </summary>
    /// <remarks>
    /// The <see cref="TextEditorControl"/> does not know how to display the method
    /// insight window. This method does not create the method insight window
    /// itself, instead it raises the <see cref="InsightRequest"/> event.
    /// </remarks>
    public void RequestInsightWindow()
    {
      OnInsightRequest(InsightEventArgs.Empty);
    }

    /// <summary>
    /// Raises the <see cref="InsightRequest" /> event.
    /// </summary>
    /// <param name="e"><see cref="InsightEventArgs" /> object that provides the arguments for the event.</param>
    protected virtual void OnInsightRequest(InsightEventArgs e)
    {
      EventHandler<InsightEventArgs> handler = InsightRequest;

      if (handler != null)
        handler(this, e);
    }

    /// <summary>
    /// Shows the insight window.
    /// </summary>
    /// <param name="insightDataProvider">The insight data provider.</param>
    public void ShowInsightWindow(IInsightDataProvider insightDataProvider)
    {
      if (_insightWindow == null || _insightWindow.IsDisposed)
      {
        _insightWindow = new InsightWindow(ParentForm, this);
        _insightWindow.Closed += OnInsightWindowClosed;
      }
      _insightWindow.AddInsightDataProvider(insightDataProvider, FileName);
      _insightWindow.ShowInsightWindow();
    }

    void OnInsightWindowClosed(object sender, EventArgs e)
    {
      if (_insightWindow != null)
      {
        _insightWindow.Closed -= OnInsightWindowClosed;
        _insightWindow.Dispose();
        _insightWindow = null;
      }
    }
  }
}


text:
from __future__ import unicode_literals

from inlinestyler.utils import inline_css

def test_no_markup():
    inlined = inline_css("Hello World!")
    expected = '
Hello World!
\n'

    assert expected == inlined

def test_respects_encoding_argument():
    inlined = inline_css("Hello World!", encoding='utf-16')
    expected = '
Hello World!
\n'.encode('utf-16')

    assert expected == inlined

def test_inline_css_in_head():

    document = """

            Hello World!

    """

    expected = """

            Hello World!

"""
    inlined = inline_css(document)
    assert expected == inlined


text:
package com.thesimego.senacrs.sistemasdistribuidos.waserver.entity;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Table;

/**
 *
 * @author drafaelli
 */
@Table(name = "account")
public class AccountEN extends GenericEN implements Serializable {

    private static final long serialVersionUID = 1L;

    @Column(name = "id")
    private Integer id;

    @Column(name = "login")
    private String login;

    @Column(name = "password")
    private String password;

    public AccountEN() {
    }

    public AccountEN(Integer id) {
        this.id = id;
    }

    public AccountEN(Integer id, String login, String password) {
        this.id = id;
        this.login = login;
        this.password = password;
    }

    @Override
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "AccountEN{" + "id=" + id + ", login=" + login + ", password=" + password + '}';
    }

}


text:
gitbook-draft-plugin-math
=========================

See if it works. Don't use this.


text:
package org.springframework.security.oauth.consumer.client;

import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.security.oauth.consumer.OAuthConsumerSupport;
import org.springframework.security.oauth.consumer.ProtectedResourceDetails;
import org.springframework.web.client.RestTemplate;

/**
 * Rest template that is able to make OAuth-authenticated REST requests with the credentials of the provided resource.
 *
 * @author Ryan Heaton
 */
public class OAuthRestTemplate extends RestTemplate {

  private final ProtectedResourceDetails resource;
  private OAuthConsumerSupport support = new CoreOAuthConsumerSupport();

  public OAuthRestTemplate(ProtectedResourceDetails resource) {
    this(new SimpleClientHttpRequestFactory(), resource);
  }

  public OAuthRestTemplate(ClientHttpRequestFactory requestFactory, ProtectedResourceDetails resource) {
    super();
    if (resource == null) {
      throw new IllegalArgumentException("An OAuth resource must be supplied.");
    }
    if (support == null) {
      throw new IllegalArgumentException("OAuth support must be supplied.");
    }

    this.resource = resource;
    setRequestFactory(requestFactory);
  }

  @Override
  public void setRequestFactory(ClientHttpRequestFactory requestFactory) {
    if (!(requestFactory instanceof OAuthClientHttpRequestFactory)) {
      requestFactory = new OAuthClientHttpRequestFactory(requestFactory, getResource(), getSupport());
    }
    super.setRequestFactory(requestFactory);
  }

  public ProtectedResourceDetails getResource() {
    return resource;
  }

  /**
   * The support logic to use.
   *
   * @return The support logic to use.
   */
  public OAuthConsumerSupport getSupport() {
    return support;
  }

  /**
   * The support logic to use.
   *
   * @param support The support logic to use.
   */
  public void setSupport(OAuthConsumerSupport support) {
    this.support = support;
  }

}


text:
namespace arb {

template <template <class> class E>
struct dynamic_typed_map {
    // Retrieve value by reference associated with type T; create entry with
    // default value if no entry in map for T.
    template <typename T>
    E<T>& get() {
        std::any& store_entry = tmap_[std::type_index(typeid(T))];
        if (!store_entry.has_value()) {
            store_entry = std::any(E<T>{});
        }

        return std::any_cast<E<T>&>(store_entry);
    }

    // Retrieve value by const reference associated with type T;
    // throw if no entry in map for T.
    template <typename T>
    const E<T>& get() const {
        return std::any_cast<const E<T>&>(tmap_.at(std::type_index(typeid(T))));
    }

    // True if map has an entry for type T.
    template <typename T>
    bool has() const { return tmap_.count(std::type_index(typeid(T))); }

private:
    std::unordered_map<std::type_index, std::any> tmap_;
};

template <template <class> class E, typename... Keys>
struct static_typed_map {
    // Retrieve value by reference associated with type T.
    template <typename T>
    E<T>& get() {
        return std::get<index<T, Keys...>()>(tmap_);
    }

    // Retrieve value by const reference associated with type T.
    template <typename T>
    const E<T>& get() const {
        return std::get<index<T, Keys...>()>(tmap_);
    }

    // True if map has an entry for type T.
    template <typename T>
    constexpr bool has() const { return index<T, Keys...>()<sizeof...(Keys); }

private:
    std::tuple<E<Keys>...> tmap_;

    template <typename T>
    static constexpr std::size_t index() { return 1; }

    template <typename T, typename H, typename... A>
    static constexpr std::size_t index() {
        return std::is_same<H, T>::value? 0: 1+index<T, A...>();
    }
};

} // namespace arb


text:
from sklearn import svm, metrics
from sklearn.datasets import load_svmlight_file
import sys
from sklearn.multiclass import  OneVsRestClassifier
import codecs

# 返回precision, recall, f1, accuracy
def getScores(true_classes, pred_classes, average):
    precision = metrics.precision_score(true_classes, pred_classes, average=average)
    recall = metrics.recall_score(true_classes, pred_classes, average=average)
    f1 = metrics.f1_score(true_classes, pred_classes, average=average)
    accuracy = metrics.accuracy_score(true_classes, pred_classes)
    return precision, recall, f1, accuracy

# 加载training和test文件的特征
for i in xrange(3):
    train_file = "train.svm-lda-%d.txt" % i
    test_file = "test.svm-lda-%d.txt" % i
    train_features_sparse, true_train_classes = load_svmlight_file(train_file)
    test_features_sparse, true_test_classes = load_svmlight_file(test_file)

    # 缺省加载为稀疏矩阵。转化为普通numpy array
    train_features = train_features_sparse.toarray()
    test_features = test_features_sparse.toarray()

    print "Train: %dx%d" % (train_features.shape)

    # 线性SVM,L1正则
    model = svm.LinearSVC(penalty='l1', dual=False)

    # 在training文件上训练
    print "Training... Predicting ...",
    model.fit(train_features, true_train_classes)
    print "Done."

    # 在test文件上做预测
    pred_train_classes = model.predict(train_features)
    pred_test_classes = model.predict(test_features)

    with codecs.open('./data/output/%d_predict.csv' % i, 'w', 'utf-8') as fw:
        for idx in pred_test_classes:
            fw.write('%d\n' % int(idx) )
        fw.close()

    # 汇报结果
    print metrics.classification_report(true_train_classes, pred_train_classes, digits=3)
    print metrics.classification_report(true_test_classes, pred_test_classes, digits=3)

    for average in ['micro', 'macro']:
        train_precision, train_recall, train_f1, train_acc = getScores(true_train_classes, pred_train_classes, average)
        print "Train Prec (%s average): %.3f, recall: %.3f, F1: %.3f, Acc: %.3f" % (average, train_precision, train_recall, train_f1, train_acc)

        test_precision, test_recall, test_f1, test_acc = getScores(true_test_classes, pred_test_classes, average)
        print "Test Prec (%s average): %.3f, recall: %.3f, F1: %.3f, Acc: %.3f" % (average, test_precision, test_recall, test_f1, test_acc)


text:
package stooge.sort;

import static org.junit.Assert.*;

import org.junit.Test;

public class StoogeSort_test {

  @Test
  public void test() {

    int expected[] = {1,1,2,2,3,3,4,5,5,7,88 };
    int input[] = {2,4,1,5,3,88,5,3,7,2,1};

    StoogeSort ss = new StoogeSort();
    assertArrayEquals("Both arrays should match and give sorted results",expected, ss.sort(input));
    assertArrayEquals("Both arrays should match and give sorted results",expected, ss.sort(expected));

  }

}


text:
package org.talend.test.configuration;

import static java.util.Arrays.asList;
import static org.talend.sdk.component.api.component.Icon.IconType.AGGREGATE;

import java.io.Serializable;
import java.util.List;

import org.talend.sdk.component.api.component.Icon;
import org.talend.sdk.component.api.configuration.Option;
import org.talend.sdk.component.api.configuration.action.Suggestable;
import org.talend.sdk.component.api.configuration.condition.ActiveIf;
import org.talend.sdk.component.api.configuration.constraint.Required;
import org.talend.sdk.component.api.configuration.ui.DefaultValue;
import org.talend.sdk.component.api.configuration.ui.OptionsOrder;
import org.talend.sdk.component.api.meta.Documentation;

import lombok.Data;

@Data
@Icon(AGGREGATE)
@Documentation("Aggregate fields.")
@OptionsOrder({ "groupBy", "operations" })
public class AggregateConfiguration implements Serializable {

    @Option
    @Required
    @Documentation("The list of fields used for the aggregation.")
    private List<String> groupBy = asList("");

    @Option
    @Required
    @Documentation("The list of operation that will be executed.")
    private List<AggregateConfiguration.AggregateOperation> operations =
            asList(new AggregateConfiguration.AggregateOperation());

    @Data
    @OptionsOrder({ "fieldPath", "operation", "outputFieldPath" })
    @Documentation("Identifies a field.")
    public static class AggregateOperation implements Serializable {

        @Option
        @Required
        @Suggestable("datalist")
        @Documentation("The source field path.")
        private String fieldPath = "";

        @Option
        @Required
        @Documentation("The operation to apply.")
        private AggregateFieldOperationType operation = AggregateFieldOperationType.SUM;

        @Option
        @Required
        @ActiveIf(target = "fieldPath", value = { "a value", "anaother value" })
        @Documentation("The resulting field name.")
        private String outputFieldPath = "";

    }

    public enum AggregateFieldOperationType {
        SUM
    }
}


text:
Discourse.AdminApiView = Discourse.View.extend({
  templateName: 'admin/templates/api'
});


text:
package com.github.gavlyukovskiy.boot.jdbc.decorator.dsproxy;

import net.ttddyy.dsproxy.listener.MethodExecutionListener;
import net.ttddyy.dsproxy.listener.QueryCountStrategy;
import net.ttddyy.dsproxy.listener.QueryExecutionListener;
import net.ttddyy.dsproxy.listener.logging.CommonsLogLevel;
import net.ttddyy.dsproxy.listener.logging.SLF4JLogLevel;
import net.ttddyy.dsproxy.proxy.ResultSetProxyLogicFactory;
import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder;
import net.ttddyy.dsproxy.transform.ParameterTransformer;
import net.ttddyy.dsproxy.transform.QueryTransformer;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * Configurer for {@link ProxyDataSourceBuilder} based on the application context.
 *
 * @see ProxyDataSourceBuilder
 *
 * @author Arthur Gavlyukovskiy
 * @since 1.3.1
 */
public class ProxyDataSourceBuilderConfigurer {

    private static final Logger log = getLogger(ProxyDataSourceBuilderConfigurer.class);

    @Autowired(required = false)
    private QueryCountStrategy queryCountStrategy;

    @Autowired(required = false)
    private List<QueryExecutionListener> listeners;

    @Autowired(required = false)
    private List<MethodExecutionListener> methodExecutionListeners;

    @Autowired(required = false)
    private ParameterTransformer parameterTransformer;

    @Autowired(required = false)
    private QueryTransformer queryTransformer;

    @Autowired(required = false)
    private ResultSetProxyLogicFactory resultSetProxyLogicFactory;

    @Autowired(required = false)
    private ConnectionIdManagerProvider connectionIdManagerProvider;

    public void configure(ProxyDataSourceBuilder proxyDataSourceBuilder, DataSourceProxyProperties datasourceProxy) {
        switch (datasourceProxy.getLogging()) {
            case SLF4J: {
                if (datasourceProxy.getQuery().isEnableLogging()) {
                    proxyDataSourceBuilder.logQueryBySlf4j(toSlf4JLogLevel(datasourceProxy.getQuery().getLogLevel()), datasourceProxy.getQuery().getLoggerName());
                }
                if (datasourceProxy.getSlowQuery().isEnableLogging()) {
                    proxyDataSourceBuilder.logSlowQueryBySlf4j(datasourceProxy.getSlowQuery().getThreshold(), TimeUnit.SECONDS,
                            toSlf4JLogLevel(datasourceProxy.getSlowQuery().getLogLevel()), datasourceProxy.getSlowQuery().getLoggerName());
                }
                break;
            }
            case JUL: {
                if (datasourceProxy.getQuery().isEnableLogging()) {
                    proxyDataSourceBuilder.logQueryByJUL(toJULLogLevel(datasourceProxy.getQuery().getLogLevel()), datasourceProxy.getQuery().getLoggerName());
                }
                if (datasourceProxy.getSlowQuery().isEnableLogging()) {
                    proxyDataSourceBuilder.logSlowQueryByJUL(datasourceProxy.getSlowQuery().getThreshold(), TimeUnit.SECONDS,
                            toJULLogLevel(datasourceProxy.getSlowQuery().getLogLevel()), datasourceProxy.getSlowQuery().getLoggerName());
                }
                break;
            }
            case COMMONS: {
                if (datasourceProxy.getQuery().isEnableLogging()) {
                    proxyDataSourceBuilder.logQueryByCommons(toCommonsLogLevel(datasourceProxy.getQuery().getLogLevel()), datasourceProxy.getQuery().getLoggerName());
                }
                if (datasourceProxy.getSlowQuery().isEnableLogging()) {
                    proxyDataSourceBuilder.logSlowQueryByCommons(datasourceProxy.getSlowQuery().getThreshold(), TimeUnit.SECONDS,
                            toCommonsLogLevel(datasourceProxy.getSlowQuery().getLogLevel()), datasourceProxy.getSlowQuery().getLoggerName());
                }
                break;
            }
            case SYSOUT: {
                if (datasourceProxy.getQuery().isEnableLogging()) {
                    proxyDataSourceBuilder.logQueryToSysOut();
                }
                if (datasourceProxy.getSlowQuery().isEnableLogging()) {
                    proxyDataSourceBuilder.logSlowQueryToSysOut(datasourceProxy.getSlowQuery().getThreshold(), TimeUnit.SECONDS);
                }
                break;
            }
        }
        if (datasourceProxy.isMultiline() && datasourceProxy.isJsonFormat()) {
            log.warn("Found opposite multiline and json format, multiline will be used (may depend on library version)");
        }
        if (datasourceProxy.isMultiline()) {
            proxyDataSourceBuilder.multiline();
        }
        if (datasourceProxy.isJsonFormat()) {
            proxyDataSourceBuilder.asJson();
        }
        if (datasourceProxy.isCountQuery()) {
            proxyDataSourceBuilder.countQuery(queryCountStrategy);
        }
        if (listeners != null) {
            listeners.forEach(proxyDataSourceBuilder::listener);
        }
        if (methodExecutionListeners != null) {
            methodExecutionListeners.forEach(proxyDataSourceBuilder::methodListener);
        }
        if (parameterTransformer != null) {
            proxyDataSourceBuilder.parameterTransformer(parameterTransformer);
        }
        if (queryTransformer != null) {
            proxyDataSourceBuilder.queryTransformer(queryTransformer);
        }
        if (resultSetProxyLogicFactory != null) {
            proxyDataSourceBuilder.proxyResultSet(resultSetProxyLogicFactory);
        }
        if (connectionIdManagerProvider != null) {
            proxyDataSourceBuilder.connectionIdManager(connectionIdManagerProvider.get());
        }
    }

    private SLF4JLogLevel toSlf4JLogLevel(String logLevel) {
        if (logLevel == null) {
            return null;
        }
        for (SLF4JLogLevel slf4JLogLevel : SLF4JLogLevel.values()) {
            if (slf4JLogLevel.name().equalsIgnoreCase(logLevel)) {
                return slf4JLogLevel;
            }
        }
        throw new IllegalArgumentException("Unresolved log level " + logLevel + " for slf4j logger, " +
                "known levels: " + Arrays.toString(SLF4JLogLevel.values()));
    }

    private Level toJULLogLevel(String logLevel) {
        if (logLevel == null) {
            return null;
        }
        try {
            return Level.parse(logLevel);
        }
        catch (IllegalArgumentException e) {
            if (logLevel.equalsIgnoreCase("DEBUG")) {
                return Level.FINE;
            }
            if (logLevel.equalsIgnoreCase("WARN")) {
                return Level.WARNING;
            }
            throw new IllegalArgumentException("Unresolved log level " + logLevel + " for java.util.logging", e);
        }
    }

    private CommonsLogLevel toCommonsLogLevel(String logLevel) {
        if (logLevel == null) {
            return null;
        }
        for (CommonsLogLevel commonsLogLevel : CommonsLogLevel.values()) {
            if (commonsLogLevel.name().equalsIgnoreCase(logLevel)) {
                return commonsLogLevel;
            }
        }
        throw new IllegalArgumentException("Unresolved log level " + logLevel + " for apache commons logger, " +
                "known levels " + Arrays.toString(CommonsLogLevel.values()));
    }
}


text:
package io.skysail.server.ext.peers.app;

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

import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.event.EventAdmin;

import io.skysail.core.app.ApiVersion;
import io.skysail.core.app.ApplicationProvider;
import io.skysail.core.app.SkysailApplication;
import io.skysail.server.menus.MenuItem;
import io.skysail.server.menus.MenuItemProvider;
import io.skysail.server.restlet.RouteBuilder;
import io.skysail.server.security.config.SecurityConfigBuilder;

@Component(immediate = true)
public class PeersApplication extends SkysailApplication implements ApplicationProvider, MenuItemProvider {

	private static final String APP_NAME = "peers";
	@Reference(cardinality = ReferenceCardinality.OPTIONAL)
	private volatile EventAdmin eventAdmin;

	public PeersApplication() {
		super(APP_NAME, new ApiVersion(1));
		setDescription("The skysail peers application");
	}

	@Override
	protected void defineSecurityConfig(SecurityConfigBuilder securityConfigBuilder) {
		securityConfigBuilder.authorizeRequests().startsWithMatcher("").permitAll();
	}

	@Override
	protected void attach() {
		super.attach();

		router.attach(new RouteBuilder("", HeartbeatsResource.class));
		router.attach(new RouteBuilder("/heartbeats", HeartbeatsResource.class));
		router.attach(new RouteBuilder("/heartbeats/{id}/", PutHeartbeatResource.class));
	}

	@Override
	public List<MenuItem> getMenuEntries() {
		MenuItem appMenu = new MenuItem(APP_NAME, "/" + APP_NAME + getApiVersion().getVersionPath());
		appMenu.setCategory(MenuItem.Category.APPLICATION_MAIN_MENU);
		return Arrays.asList(appMenu);
	}
}


text:
namespace spvtools {
namespace val {

// Validates correctness of bitwise instructions.
spv_result_t BitwisePass(ValidationState_t& _, const Instruction* inst) {
  const SpvOp opcode = inst->opcode();
  const uint32_t result_type = inst->type_id();

  switch (opcode) {
    case SpvOpShiftRightLogical:
    case SpvOpShiftRightArithmetic:
    case SpvOpShiftLeftLogical: {
      if (!_.IsIntScalarType(result_type) && !_.IsIntVectorType(result_type))
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected int scalar or vector type as Result Type: "
               << spvOpcodeString(opcode);

      const uint32_t result_dimension = _.GetDimension(result_type);
      const uint32_t base_type = _.GetOperandTypeId(inst, 2);
      const uint32_t shift_type = _.GetOperandTypeId(inst, 3);

      if (!base_type ||
          (!_.IsIntScalarType(base_type) && !_.IsIntVectorType(base_type)))
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected Base to be int scalar or vector: "
               << spvOpcodeString(opcode);

      if (_.GetDimension(base_type) != result_dimension)
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected Base to have the same dimension "
               << "as Result Type: " << spvOpcodeString(opcode);

      if (_.GetBitWidth(base_type) != _.GetBitWidth(result_type))
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected Base to have the same bit width "
               << "as Result Type: " << spvOpcodeString(opcode);

      if (!shift_type ||
          (!_.IsIntScalarType(shift_type) && !_.IsIntVectorType(shift_type)))
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected Shift to be int scalar or vector: "
               << spvOpcodeString(opcode);

      if (_.GetDimension(shift_type) != result_dimension)
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected Shift to have the same dimension "
               << "as Result Type: " << spvOpcodeString(opcode);
      break;
    }

    case SpvOpBitwiseOr:
    case SpvOpBitwiseXor:
    case SpvOpBitwiseAnd:
    case SpvOpNot: {
      if (!_.IsIntScalarType(result_type) && !_.IsIntVectorType(result_type))
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected int scalar or vector type as Result Type: "
               << spvOpcodeString(opcode);

      const uint32_t result_dimension = _.GetDimension(result_type);
      const uint32_t result_bit_width = _.GetBitWidth(result_type);

      for (size_t operand_index = 2; operand_index < inst->operands().size();
           ++operand_index) {
        const uint32_t type_id = _.GetOperandTypeId(inst, operand_index);
        if (!type_id ||
            (!_.IsIntScalarType(type_id) && !_.IsIntVectorType(type_id)))
          return _.diag(SPV_ERROR_INVALID_DATA, inst)
                 << "Expected int scalar or vector as operand: "
                 << spvOpcodeString(opcode) << " operand index "
                 << operand_index;

        if (_.GetDimension(type_id) != result_dimension)
          return _.diag(SPV_ERROR_INVALID_DATA, inst)
                 << "Expected operands to have the same dimension "
                 << "as Result Type: " << spvOpcodeString(opcode)
                 << " operand index " << operand_index;

        if (_.GetBitWidth(type_id) != result_bit_width)
          return _.diag(SPV_ERROR_INVALID_DATA, inst)
                 << "Expected operands to have the same bit width "
                 << "as Result Type: " << spvOpcodeString(opcode)
                 << " operand index " << operand_index;
      }
      break;
    }

    case SpvOpBitFieldInsert: {
      if (!_.IsIntScalarType(result_type) && !_.IsIntVectorType(result_type))
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected int scalar or vector type as Result Type: "
               << spvOpcodeString(opcode);

      const uint32_t base_type = _.GetOperandTypeId(inst, 2);
      const uint32_t insert_type = _.GetOperandTypeId(inst, 3);
      const uint32_t offset_type = _.GetOperandTypeId(inst, 4);
      const uint32_t count_type = _.GetOperandTypeId(inst, 5);

      if (base_type != result_type)
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected Base Type to be equal to Result Type: "
               << spvOpcodeString(opcode);

      if (insert_type != result_type)
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected Insert Type to be equal to Result Type: "
               << spvOpcodeString(opcode);

      if (!offset_type || !_.IsIntScalarType(offset_type))
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected Offset Type to be int scalar: "
               << spvOpcodeString(opcode);

      if (!count_type || !_.IsIntScalarType(count_type))
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected Count Type to be int scalar: "
               << spvOpcodeString(opcode);
      break;
    }

    case SpvOpBitFieldSExtract:
    case SpvOpBitFieldUExtract: {
      if (!_.IsIntScalarType(result_type) && !_.IsIntVectorType(result_type))
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected int scalar or vector type as Result Type: "
               << spvOpcodeString(opcode);

      const uint32_t base_type = _.GetOperandTypeId(inst, 2);
      const uint32_t offset_type = _.GetOperandTypeId(inst, 3);
      const uint32_t count_type = _.GetOperandTypeId(inst, 4);

      if (base_type != result_type)
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected Base Type to be equal to Result Type: "
               << spvOpcodeString(opcode);

      if (!offset_type || !_.IsIntScalarType(offset_type))
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected Offset Type to be int scalar: "
               << spvOpcodeString(opcode);

      if (!count_type || !_.IsIntScalarType(count_type))
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected Count Type to be int scalar: "
               << spvOpcodeString(opcode);
      break;
    }

    case SpvOpBitReverse: {
      if (!_.IsIntScalarType(result_type) && !_.IsIntVectorType(result_type))
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected int scalar or vector type as Result Type: "
               << spvOpcodeString(opcode);

      const uint32_t base_type = _.GetOperandTypeId(inst, 2);

      if (base_type != result_type)
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected Base Type to be equal to Result Type: "
               << spvOpcodeString(opcode);
      break;
    }

    case SpvOpBitCount: {
      if (!_.IsIntScalarType(result_type) && !_.IsIntVectorType(result_type))
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected int scalar or vector type as Result Type: "
               << spvOpcodeString(opcode);

      const uint32_t base_type = _.GetOperandTypeId(inst, 2);
      if (!base_type ||
          (!_.IsIntScalarType(base_type) && !_.IsIntVectorType(base_type)))
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected Base Type to be int scalar or vector: "
               << spvOpcodeString(opcode);

      const uint32_t base_dimension = _.GetDimension(base_type);
      const uint32_t result_dimension = _.GetDimension(result_type);

      if (base_dimension != result_dimension)
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << "Expected Base dimension to be equal to Result Type "
                  "dimension: "
               << spvOpcodeString(opcode);
      break;
    }

    default:
      break;
  }

  return SPV_SUCCESS;
}

}  // namespace val
}  // namespace spvtools


text:
import Options from "./options";
import RuleSpec from "./ruleSpec";
import ChangeSet from "./changeset/changeset";
import * as raw from "./raw";
export default class Rule {
    expected: string;
    pattern: RegExp;
    regexpMustEmpty: string;
    options: Options;
    specs: RuleSpec[];
    raw: any;
    constructor(src: string | raw.Rule);
    reset(): void;
    check(): void;
    applyRule(content: string): ChangeSet;
    toJSON(): any;
}


text:
package org.aschyiel.rpg.activities.sandbox;

import org.aschyiel.rpg.activities.Terrain;
import org.aschyiel.rpg.level.Level;
import org.aschyiel.rpg.level.LevelDetail;
import org.aschyiel.rpg.level.Player;
import org.aschyiel.rpg.level.UnitType;

public class BasicMovement extends Terrain
{

  @Override
  protected Level getLevelInfo()
  {
    Level lvl = new Level();
    lvl.getUnits().add( new LevelDetail( UnitType.TANK, 0, 0, Player.ONE ) );
    lvl.getUnits().add( new LevelDetail( UnitType.TANK, 2, 3, Player.CPU ) );
    return lvl;
  }

}


text:
from django.db import models
from django.db.models import Sum

from thing.models.alliance import Alliance

class PosWatchCorporation(models.Model):
    corpId = models.BigIntegerField(primary_key=True)
    corpName = models.CharField(max_length=2000)
    key = models.CharField(max_length=2000)
    vCode = models.CharField(max_length=2000)
    discordHandle = models.CharField(max_length=2000)
    forumName = models.CharField(max_length=2000)

    class Meta:
        app_label = 'thing'
        db_table = 'thing_poswatch_corporation'


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

namespace ImageMagickSharp.InteropMarshaler
{
    public class UTF8Marshaler : ICustomMarshaler
    {
        static UTF8Marshaler static_instance;

        public IntPtr MarshalManagedToNative(object managedObj)
        {
            if (managedObj == null)
                return IntPtr.Zero;
            if (!(managedObj is string))
                throw new MarshalDirectiveException(
                       "UTF8Marshaler must be used on a string.");

            // not null terminated
            byte[] strbuf = Encoding.UTF8.GetBytes((string)managedObj);
            IntPtr buffer = Marshal.AllocHGlobal(strbuf.Length + 1);
            Marshal.Copy(strbuf, 0, buffer, strbuf.Length);

            // write the terminating null
            Marshal.WriteByte(buffer + strbuf.Length, 0);
            return buffer;
        }

        public object MarshalNativeToManaged(IntPtr pNativeData)
        {
            throw new NotImplementedException("MarshalNativeToManaged");
        }

        public void CleanUpNativeData(IntPtr pNativeData)
        {
            Marshal.FreeHGlobal(pNativeData);
        }

        public void CleanUpManagedData(object managedObj)
        {
        }

        public int GetNativeDataSize()
        {
            return -1;
        }

        public static ICustomMarshaler GetInstance(string cookie)
        {
            if (static_instance == null)
            {
                return static_instance = new UTF8Marshaler();
            }
            return static_instance;
        }
    }
}