text:
package com.evolveum.midpoint.web.component.search;

import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.marshaller.QueryConvertor;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.polystring.PolyStringNormalizer;
import com.evolveum.midpoint.prism.query.*;
import com.evolveum.midpoint.prism.query.builder.QueryBuilder;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.DebugDumpable;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.DisplayableValue;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SearchBoxModeType;
import com.evolveum.prism.xml.ns._public.query_3.SearchFilterType;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author Viliam Repan (lazyman)
 */
public class Search implements Serializable, DebugDumpable {

    public static final String F_AVAILABLE_DEFINITIONS = "availableDefinitions";
    public static final String F_ITEMS = "items";
    public static final String F_ADVANCED_QUERY = "advancedQuery";
    public static final String F_ADVANCED_ERROR = "advancedError";
    public static final String F_FULL_TEXT = "fullText";

    private static final Trace LOGGER = TraceManager.getTrace(Search.class);

    private SearchBoxModeType searchType;

    private boolean showAdvanced = false;
    private boolean isFullTextSearchEnabled = false;

    private String advancedQuery;
    private String advancedError;
    private String fullText;

    private Class<? extends ObjectType> type;
    private Map<ItemPath, ItemDefinition> allDefinitions;

    private List<ItemDefinition> availableDefinitions = new ArrayList<>();
    private List<SearchItem> items = new ArrayList<>();

    public Search(Class<? extends ObjectType> type, Map<ItemPath, ItemDefinition> allDefinitions) {
        this(type, allDefinitions, false, null);
    }

    public Search(Class<? extends ObjectType> type, Map<ItemPath, ItemDefinition> allDefinitions,
                  boolean isFullTextSearchEnabled, SearchBoxModeType searchBoxModeType) {
        this.type = type;
        this.allDefinitions = allDefinitions;

        this.isFullTextSearchEnabled = isFullTextSearchEnabled;

        if (searchBoxModeType != null){
            searchType = searchBoxModeType;
        } else if (isFullTextSearchEnabled ){
            searchType = SearchBoxModeType.FULLTEXT;
        } else {
            searchType = SearchBoxModeType.BASIC;
        }
        availableDefinitions.addAll(allDefinitions.values());
    }

    public List<SearchItem> getItems() {
        return Collections.unmodifiableList(items);
    }

    public List<ItemDefinition> getAvailableDefinitions() {
        return Collections.unmodifiableList(availableDefinitions);
    }

    public List<ItemDefinition> getAllDefinitions() {
        return new ArrayList<>(allDefinitions.values());
    }

    public SearchItem addItem(ItemDefinition def) {
        boolean isPresent = false;
        for (ItemDefinition itemDefinition : availableDefinitions){
            if (itemDefinition.getName() != null &&
                    itemDefinition.getName().equals(def.getName())){
                isPresent = true;
                break;
            }
        }
        if (!isPresent){
            return null;
        }

        ItemPath path = null;
        ItemDefinition itemToRemove = null;
        for (Map.Entry<ItemPath, ItemDefinition> entry : allDefinitions.entrySet()) {
            if (entry.getValue().getName().equals(def.getName())) {
                path = entry.getKey();
                itemToRemove = entry.getValue();
                break;
            }
        }

        if (path == null) {
            return null;
        }

        SearchItem item = new SearchItem(this, path, def);
        item.getValues().add(new SearchValue<>());

        items.add(item);
        if (itemToRemove != null) {
            availableDefinitions.remove(itemToRemove);
        }

        return item;
    }

    public void delete(SearchItem item) {
        if (items.remove(item)) {
            availableDefinitions.add(item.getDefinition());
        }
    }

    public Class<? extends ObjectType> getType() {
        return type;
    }

    public ObjectQuery createObjectQuery(PrismContext ctx) {
        LOGGER.debug("Creating query from {}", this);
        if (SearchBoxModeType.ADVANCED.equals(searchType)){
            return createObjectQueryAdvanced(ctx);
        } else if (SearchBoxModeType.FULLTEXT.equals(searchType)){
            return createObjectQueryFullText(ctx);
        } else {
            return createObjectQuerySimple(ctx);
        }
    }

    public ObjectQuery createObjectQuerySimple(PrismContext ctx) {
        List<SearchItem> searchItems = getItems();
        if (searchItems.isEmpty()) {
            return null;
        }

        List<ObjectFilter> conditions = new ArrayList<>();
        for (SearchItem item : searchItems) {
            ObjectFilter filter = createFilterForSearchItem(item, ctx);
            if (filter != null) {
                conditions.add(filter);
            }
        }

        switch (conditions.size()) {
            case 0:
                return null;
            case 1:
                return ObjectQuery.createObjectQuery(conditions.get(0));
            default:
                AndFilter and = AndFilter.createAnd(conditions);
                return ObjectQuery.createObjectQuery(and);
        }
    }

    private ObjectFilter createFilterForSearchItem(SearchItem item, PrismContext ctx) {
        if (item.getValues().isEmpty()) {
            return null;
        }

        List<ObjectFilter> conditions = new ArrayList<>();
        for (DisplayableValue value : (List<DisplayableValue>) item.getValues()) {
            if (value.getValue() == null) {
                continue;
            }

            ObjectFilter filter = createFilterForSearchValue(item, value, ctx);
            if (filter != null) {
                conditions.add(filter);
            }
        }

        switch (conditions.size()) {
            case 0:
                return null;
            case 1:
                return conditions.get(0);
            default:
                return OrFilter.createOr(conditions);
        }
    }

    private ObjectFilter createFilterForSearchValue(SearchItem item, DisplayableValue searchValue,
                                                    PrismContext ctx) {

        ItemDefinition definition = item.getDefinition();
        ItemPath path = item.getPath();

        if (definition instanceof PrismReferenceDefinition) {
            return QueryBuilder.queryFor(ObjectType.class, ctx)
                    .item(path, definition).ref((PrismReferenceValue) searchValue.getValue())
                    .buildFilter();
        }

        PrismPropertyDefinition propDef = (PrismPropertyDefinition) definition;
        if ((propDef.getAllowedValues() != null && !propDef.getAllowedValues().isEmpty())
                || DOMUtil.XSD_BOOLEAN.equals(propDef.getTypeName())) {
            //we're looking for enum value, therefore equals filter is ok
            //or if it's boolean value
            DisplayableValue displayableValue = (DisplayableValue) searchValue.getValue();
            Object value = displayableValue.getValue();
            return QueryBuilder.queryFor(ObjectType.class, ctx)
                    .item(path, propDef).eq(value).buildFilter();
        } else if (DOMUtil.XSD_INT.equals(propDef.getTypeName())
                || DOMUtil.XSD_INTEGER.equals(propDef.getTypeName())
                || DOMUtil.XSD_LONG.equals(propDef.getTypeName())
                || DOMUtil.XSD_SHORT.equals(propDef.getTypeName())) {

            String text = (String) searchValue.getValue();
            if (!StringUtils.isNumeric(text) && (searchValue instanceof SearchValue)) {
                ((SearchValue) searchValue).clear();
                return null;
            }
            Object value = Long.parseLong((String) searchValue.getValue());
            return QueryBuilder.queryFor(ObjectType.class, ctx)
                    .item(path, propDef).eq(value).buildFilter();
        } else if (DOMUtil.XSD_STRING.equals(propDef.getTypeName())) {
            String text = (String) searchValue.getValue();
            return QueryBuilder.queryFor(ObjectType.class, ctx)
                    .item(path, propDef).contains(text).matchingCaseIgnore().buildFilter();
        } else if (SchemaConstants.T_POLY_STRING_TYPE.equals(propDef.getTypeName())) {
            //we're looking for string value, therefore substring filter should be used
            String text = (String) searchValue.getValue();
            PolyStringNormalizer normalizer = ctx.getDefaultPolyStringNormalizer();
            String value = normalizer.normalize(text);
            return QueryBuilder.queryFor(ObjectType.class, ctx)
                    .item(path, propDef).contains(text).matchingNorm().buildFilter();
        }

        //we don't know how to create filter from search item, should not happen, ha ha ha :)
        //at least we try to cleanup field

        if (searchValue instanceof SearchValue) {
            ((SearchValue) searchValue).clear();
        }

        return null;
    }

    public boolean isShowAdvanced() {
        return showAdvanced;
    }

    public void setShowAdvanced(boolean showAdvanced) {
        this.showAdvanced = showAdvanced;
    }

    public String getAdvancedQuery() {
        return advancedQuery;
    }

    public void setAdvancedQuery(String advancedQuery) {
        this.advancedQuery = advancedQuery;
    }

    public String getFullText() {
        return fullText;
    }

    public void setFullText(String fullText) {
        this.fullText = fullText;
    }

    public ObjectQuery createObjectQueryAdvanced(PrismContext ctx) {
        try {
            advancedError = null;

            ObjectFilter filter = createAdvancedObjectFilter(ctx);
            if (filter == null) {
                return null;
            }

            return ObjectQuery.createObjectQuery(filter);
        } catch (Exception ex) {
            advancedError = createErrorMessage(ex);
        }

        return null;
    }

    public ObjectQuery createObjectQueryFullText(PrismContext ctx) {
        if (StringUtils.isEmpty(fullText)){
            return null;
        }
        ObjectQuery query = QueryBuilder.queryFor(type, ctx)
                .fullText(fullText)
                .build();
        return query;
    }

    private ObjectFilter createAdvancedObjectFilter(PrismContext ctx) throws SchemaException {
        if (StringUtils.isEmpty(advancedQuery)) {
            return null;
        }

        SearchFilterType search = ctx.parserFor(advancedQuery).type(SearchFilterType.COMPLEX_TYPE).parseRealValue();
        return QueryConvertor.parseFilter(search, type, ctx);
    }

    public boolean isAdvancedQueryValid(PrismContext ctx) {
        try {
            advancedError = null;

            createAdvancedObjectFilter(ctx);
            return true;
        } catch (Exception ex) {
            advancedError = createErrorMessage(ex);
        }

        return false;
    }

    public SearchBoxModeType getSearchType() {
        return searchType;
    }

    public void setSearchType(SearchBoxModeType searchType) {
        this.searchType = searchType;
    }

    public boolean isFullTextSearchEnabled() {
        return isFullTextSearchEnabled;
    }

    public void setFullTextSearchEnabled(boolean fullTextSearchEnabled) {
        isFullTextSearchEnabled = fullTextSearchEnabled;
    }

    private String createErrorMessage(Exception ex) {
        StringBuilder sb = new StringBuilder();

        Throwable t = ex;
        while (t != null) {
            sb.append(t.getMessage()).append('\n');
            t = t.getCause();
        }

        return sb.toString();
    }

    public String getAdvancedError() {
        return advancedError;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append("items", items)
                .toString();
    }

	@Override
	public String debugDump() {
		return debugDump(0);
	}

	@Override
	public String debugDump(int indent) {
		StringBuilder sb = new StringBuilder();
		DebugUtil.indentDebugDump(sb, indent);
		sb.append("Search\n");
		DebugUtil.debugDumpWithLabelLn(sb, "showAdvanced", showAdvanced, indent+1);
		DebugUtil.debugDumpWithLabelLn(sb, "advancedQuery", advancedQuery, indent+1);
		DebugUtil.debugDumpWithLabelLn(sb, "advancedError", advancedError, indent+1);
		DebugUtil.debugDumpWithLabelLn(sb, "type", type, indent+1);
		DebugUtil.debugDumpWithLabelLn(sb, "allDefinitions", allDefinitions, indent+1);
		DebugUtil.debugDumpWithLabelLn(sb, "availableDefinitions", availableDefinitions, indent+1);
		DebugUtil.debugDumpWithLabel(sb, "items", items, indent+1);
		return sb.toString();
	}
}


text:
<!doctype html>

    <title>Code coverage report for web3/lib/web3/subscriptions.js</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../../../prettify.css">
    <link rel="stylesheet" href="../../../base.css">

Code coverage report for web3/lib/web3/subscriptions.js

        Statements: 92% (23 / 25)
        Branches: 33.33% (2 / 6)
        Functions: 100% (5 / 5)
        Lines: 92% (23 / 25)
        Ignored: none

All files » web3/lib/web3/ » subscriptions.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

1
1
1

1
308
308
308
308
308

1
308

1
308
308
308
308

308

1
308

308
7

7

1

/*
    This file is part of web3.js.

    web3.js is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    web3.js is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with web3.js.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file subscriptions.js
 *
 * @authors:
 *   Fabian Vogelsteller <fabian@ethdev.com>
 * @date 2015
 */

var utils = require('../utils/utils');
var errors = require('./errors');
var Subscription = require('./subscription.js');

Subscriptions = function (options) {
    this.name = options.name;
    this.subscribe = options.subscribe;
    this.unsubscribe = options.unsubscribe;
    this.subscriptions = options.subscriptions || {};
    this.requestManager = null;
};

Subscriptions.prototype.setRequestManager = function (rm) {
    this.requestManager = rm;
};

Subscriptions.prototype.attachToObject = function (obj) {
    var func = this.buildCall();
    func.call = this.call; // TODO!!! that's ugly. filter.js uses it
    var name = this.name.split('.');
    Iif (name.length > 1) {
        obj[name[0]] = obj[name[0]] || {};
        obj[name[0]][name[1]] = func;
    } else {
        obj[name[0]] = func;
    }
};

Subscriptions.prototype.buildCall = function() {
    var _this = this;

    return function(){
        var subscription = new Subscription({
            subscription: _this.subscriptions[arguments[0]],
            subscribeMethod: _this.subscribe,
            unsubscribeMethod: _this.unsubscribe,
            requestManager: _this.requestManager
        });

        return subscription.subscribe.apply(subscription, arguments);
    };
};

module.exports = Subscriptions;

Generated by istanbul at Fri Jan 22 2016 12:10:16 GMT+0100 (CET)

redpajama_set_name: RedPajamaGithub


text:
package app.config;

import com.mpalourdio.springboottemplate.properties.CredentialsProperties;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
@EnableConfigurationProperties(CredentialsProperties.class)
public class WebSecurityConfig {

    private static final String BASIC_AUTH_ENDPOINT = "/basicauth";
    private static final String ADMIN_ROLE = "ADMIN";
    private static final String ACTUATOR_ROLE = "ACTUATOR";

    private final CredentialsProperties credentialsProperties;

    public WebSecurityConfig(CredentialsProperties credentialsProperties) {
        this.credentialsProperties = credentialsProperties;
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(csrf -> csrf.ignoringRequestMatchers(EndpointRequest.toAnyEndpoint()))
                .logout(logout -> logout
                        .logoutSuccessUrl("/")
                        .invalidateHttpSession(true)
                        .clearAuthentication(true)
                        .logoutSuccessHandler(logoutHandler())
                        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                )
                .authorizeRequests(authorizeRequests -> authorizeRequests
                        .antMatchers(BASIC_AUTH_ENDPOINT)
                        .hasRole(ADMIN_ROLE)
                        .requestMatchers(EndpointRequest.toAnyEndpoint())
                        .hasRole(ACTUATOR_ROLE)
                )
                .httpBasic();

        return http.build();
    }

    @Bean
    public InMemoryUserDetailsManager inMemoryUserDetailsManager() {
        return new InMemoryUserDetailsManager(
                User.withDefaultPasswordEncoder()
                        .username(credentialsProperties.getUsername())
                        .password(credentialsProperties.getPassword())
                        .roles(ADMIN_ROLE, ACTUATOR_ROLE)
                        .build()
        );
    }

    private LogoutSuccessHandler logoutHandler() {
        var logoutSuccessHandler = new SimpleUrlLogoutSuccessHandler();
        var redirectStrategy = new DefaultRedirectStrategy();

        redirectStrategy.setContextRelative(false);
        logoutSuccessHandler.setRedirectStrategy(redirectStrategy);

        return logoutSuccessHandler;
    }
}


text:
package com.sepoysoftware;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class AnalyzerTest {

    private Analyzer analyzer, analyzer2, analyzer3, analyzer4, analyzer5;
    private double averageDelta = 0.009D;

    @Before
    public void setUp() throws Exception {
        analyzer = new Analyzer("The quick brown fox jumped over the lazy dog");
        analyzer2 = new Analyzer("I must be dreaming. Pinch me");
        analyzer3 = new Analyzer("Is this the place? No sir! This is not the place.");
        analyzer4 = new Analyzer("Grus is a constellation in the southern sky. Its name is Latin for the crane, a type of bird. "
                + "It is one of twelve constellations conceived by Petrus Plancius from the observations of Pieter Dirkszoon Keyser "
                + "and Frederick de Houtman.");
        analyzer5 = new Analyzer("Adam opened his eyes and pulled the covers up to " +
                "his chin. He stared around his room, searching the darkness " +
                "for the thing that was making those scary sounds. ");
    }

    @Test
    public void testWordCount() throws Exception {
        assertEquals(9, analyzer.getWords().size());
        assertEquals(6, analyzer2.getWords().size());
        assertEquals(11, analyzer3.getWords().size());
        assertEquals(40, analyzer4.getWords().size());
        assertEquals(29, analyzer5.getWords().size());
    }

    @Test
    public void testAverageWordLength() throws Exception {
        assertEquals(4.0D, analyzer.getAverageWordLength(), averageDelta);
        assertEquals(3.83D, analyzer2.getAverageWordLength(), averageDelta);
        assertEquals(2.78D, analyzer3.getAverageWordLength(), averageDelta);
    }

    @Test
    public void testSentences() throws Exception {
        assertEquals(1, analyzer.getSentences().length);
        assertEquals(2, analyzer2.getSentences().length);
        assertEquals(3, analyzer3.getSentences().length);
    }

    @Test
    public void testFleschReadingEase() throws Exception {
      assertEquals(new Double(113.10000000000002D), analyzer.getFleschReadingEase());
      assertEquals(new Double(64.3), analyzer4.getFleschReadingEase());
      assertEquals(new Double(84.2), analyzer5.getFleschReadingEase());
    }

    @Test
    public void testFleschKincaidGradeLevel() throws Exception {
        assertEquals(new Double(4.220000000000002D), analyzer.getFleschKincaidGradeLevel());
        assertEquals(new Double(7.600D), analyzer4.getFleschKincaidGradeLevel());
        assertEquals(new Double(5.100), analyzer5.getFleschKincaidGradeLevel());
    }
}


text:
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>

#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "driverlib/sysctl.h"
#include "driverlib/gpio.h"
#include "driverlib/ssi.h"
#include "driverlib/pin_map.h"
#include "driverlib/udma.h"
#include "inc/hw_ssi.h"

#include "lpd8806_ledstrip.h"

/**
 * @addtogroup lpd8806_ledstrip_driver Driver for LPD8806 RGB LED Strips
 *
 * This is a Stellaris/Tiva driver intended to be used with RGB LED lighting
 * strip based on the LPD8806 controller.  These lighting strips can be found on
 * adafruit and other places.  They are typically 32 LEDs in a strip but can
 * be longer and can be joined in series.
 *
 * This has been tested using an Stellaris EK-LM3S6965, but should work
 * with any Stellaris or Tiva part with little or no modifications.
 *
 * The LED strip must be powered appropriately and connected to the data and
 * clock lines of one of the Stellaris SSI/SPI ports.  This driver is attached
 * to a SPI peripheral when it is initialized.
 *
 * This driver maintains a pixel "frame buffer".  The provided functions allow
 * to set and get the RGB value of any pixel in the buffer and to update the
 * entire string at once.
 *
 * Each pixel is 7-bit * 3 channels (total of 21 bits) RGB.  You can manipulate
 * the pixel values by individual color channel or as a single value.
 *
 * @todo make driver interrupt driven (presently is polled or DMA)
 *
 * EXAMPLE:
 *  Here is code showing how you might use this driver in an example:
 *
 * ~~~~~~~~.c
 *    // Allocate a frame buffer for a 32 pixel strip
 *    #define NUM_PIXELS 32
 *    uint8_t frameBuffer[LPD8806_LEDSTRIP_FRAMEBUF_SIZE(NUM_PIXELS)];
 *
 *    // init the driver for SPI 0, and 500 kHz clock rate
 *    LPD8806_LedStrip_Handle_t hLed = LPD8806_LedStrip_Init(SysCtlClockGet(), 0, 500000);
 *    if(!hLed)
 *    {
 *        // handle error
 *        ...
 *    }
 *
 *    // Assign the frame buffer
 *    LPD8806_LedStrip_SetFrameBuffer(hLed, frameBuffer, NUM_PIXELS);
 *
 *    // Clear out the pixel data
 *    LPD8806_LedStrip_Clear(hLed);
 *
 *    // Update the strip so everything will be turned off
 *    LPD8806_LedStrip_Update(hLed);
 *
 *    // set pixel 0 to full red, half green, quarter blue
 *    LPD8806_LedStrip_SetPixelRgb(hLed, 0, 0x7f, 0x40, 0x20);
 *
 *    // update the light string
 *    LPD8806_LedStrip_Update(hLed);
 * ~~~~~~~~
 *
 * @{
 */

/******************************************************************************
 *
 * Macros
 *
 *****************************************************************************/

// set internal macro to indicate if DMA support is compiled in
#ifdef LPD8806_LEDSTRIP_ALLOW_DMA
#define LPD8806_DMA_SUPPORT 1
#else
#define LPD8806_DMA_SUPPORT 0
#endif

/******************************************************************************
 *
 * Locals
 *
 *****************************************************************************/

// data type to represent a single rgb led (pixel) in the string
typedef union __attribute__((__packed__))
{
    uint8_t bytes[3];
    struct __attribute__((__packed__))
    {
        uint8_t g;
        uint8_t r;
        uint8_t b;
    } rgb;
} pixel_t;

// Structure that holds a single instance of an "LedStrip".  It contains
// all variable information about the LedStrip configuration so that
// the driver can support multiple instances.
typedef struct
{
    uint32_t spiPeriph;     // SPI peripheral for PeriphEnable
    uint32_t spiBase;       // SPI peripheral base address
    uint32_t spiRate;       // SPI data rate
    pixel_t *pFrameBuffer;  // Pointer to buffer for pixel data
    uint32_t numPixels;     // number of pixels in the frame buffer
    uint32_t latchBytes;    // number of latch bytes needed for strip
    uint32_t dmaChannel;    // DMA channel to use, if any
    bool useDma;            // flag to indicate if DMA is used
} Instance_t;

// Storage for multiple LED instances.  When _Init() is called, an
// instance is allocated from here.  It uses a simple scheme to mark
// allocations - non-zero if spiPeriph
static Instance_t instances[LPD8806_LEDSTRIP_NUM_INSTANCES];

// A structure holding hardware information for a SPI peripheral
typedef struct
{
    uint32_t periph;
    uint32_t base;
} Spi_t;

// A table to map SPI index numbers to underlying peripherals
static const Spi_t spiPeriphTable[] =
{
    { SYSCTL_PERIPH_SSI0, SSI0_BASE },
    { SYSCTL_PERIPH_SSI1, SSI1_BASE },
};
#define NUM_SPI_PERIPHS (sizeof(spiPeriphTable) / sizeof(Spi_t))

/******************************************************************************
 *
 * Private API
 *
 *****************************************************************************/

/*
 * Validate an instance pointer.
 *
 * @param pInst is the instance pointer to check
 *
 * This function will perform basic validity checks on the instance
 * pointer.
 *
 * @returns Returns **true** if the instance data is valid, or **false**
 *          if not.
 */
static bool
InstanceIsValid(Instance_t *pInst)
{
    if(!pInst)
    {
        return false;
    }
    if(!pInst->pFrameBuffer || (pInst->numPixels == 0))
    {
        return false;
    }
    if(pInst->spiPeriph == 0)
    {
        return false;
    }

    return true;
}

/******************************************************************************
 *
 * Public API
 *
 *****************************************************************************/

/**
 *
 * Set the RGB value of a pixel directly
 *
 * @param h is the LedStrip instance handle from _Init()
 * @param pixelNum is the pixel number to modify
 * @param rgb is the 24-bit RGB value ([23:16]red, [15:8]green, [7:0]blue)
 *
 * This function is used to set the color value of a pixel using a
 * combined RGB value in a uint32_t.  The RGB color channel values are
 * 7 bits each and arranged as follows:
 *
 *  Bits | Color Channel
 * ------|--------------
 * 31:24 | Not used
 *    23 | Reserved (set to 0)
 * 22:16 | Red
 *    15 | Reserved (set to 0)
 * 14:8  | Green
 *    7  | Reserved (set to 0)
 *  6:0  | Blue
 *
 */
void
LPD8806_LedStrip_SetPixelValue(LPD8806_LedStrip_Handle_t h,
                               uint32_t pixelNum, uint32_t rgb)
{
    // Get instance pointer
    Instance_t *pInst = (Instance_t *)h;

    // Validate the instance
    if(!InstanceIsValid(pInst))
    {
        return;
    }

    // check that pixel is within bounds
    if(pixelNum >= pInst->numPixels)
    {
        return;
    }

    // Get frame buffer from instance
    pixel_t *pfb = pInst->pFrameBuffer;

    // set the individual channels based on the input value
    // the upper bit of each color channel must be set for the controller
    pfb[pixelNum].bytes[0] = ((rgb >> 8) & 0xff) | 0x80;
    pfb[pixelNum].bytes[1] = ((rgb >> 16) & 0xff) | 0x80;
    pfb[pixelNum].bytes[2] = ((rgb >> 0) & 0xff) | 0x80;
}

/**
 *
 * Get the pixel color as a single RGB value
 *
 * @param h is the LedStrip instance handle from _Init()
 * @param pixelNum is the pixel number to read
 *
 * The value is returned as a 24-bit RGB value with color channels
 * arranged as: ([23:16]red, [15:8]green, [7:0]blue)
 *
 * @returns Returns the RGB color value of the pixel.  If there is any
 *          error then 0 is returned.
 */
uint32_t
LPD8806_LedStrip_GetPixelValue(LPD8806_LedStrip_Handle_t h, uint32_t pixelNum)
{
    // Get instance pointer
    Instance_t *pInst = (Instance_t *)h;

    // Validate the instance
    if(!InstanceIsValid(pInst))
    {
        return 0x80000000;
    }

    // check that pixel is within bounds
    if(pixelNum >= pInst->numPixels)
    {
        return 0x80000000;
    }

    // Get a pointer to the specific pixel
    pixel_t *px = &pInst->pFrameBuffer[pixelNum];

    // read each color channel and combine into a 24-bit value.  Mask off
    // the upper bit of each byte since it is used by the controller and
    // is not part of the color value
    uint32_t val = ((uint32_t)px->rgb.r << 16)
                 | ((uint32_t)px->rgb.g << 8)
                 | (uint32_t)px->rgb.b;
    val &= 0x7f7f7f;

    return val;
}

/**
 *
 * Set the pixel color using color channels
 *
 * @param h is the LedStrip instance handle from _Init()
 * @param pixelNum is the pixel number to modify
 * @param r is the 7-bit value of the *red* color channel
 * @param g is the 7-bit value of the *green* color channel
 * @param b is the 7-bit value of the *blue* color channel
 *
 * This function is used to set the color of a specific pixel by specifying
 * the individual color channel values.  Each color channel is 7 bits.
 */
void
LPD8806_LedStrip_SetPixelRgb(LPD8806_LedStrip_Handle_t h, uint32_t pixelNum,
                             uint8_t r, uint8_t g, uint8_t b)
{
    // Get instance pointer
    Instance_t *pInst = (Instance_t *)h;

    // Validate the instance
    if(!InstanceIsValid(pInst))
    {
        return;
    }

    // Get frame buffer
    pixel_t *pfb = pInst->pFrameBuffer;

    // check that pixel is within bounds
    if(pixelNum >= pInst->numPixels)
    {
        return;
    }

    // set each color in the pixel
    // the upper bit of each color channel must be set for the controller
    pfb[pixelNum].rgb.r = r | 0x80;
    pfb[pixelNum].rgb.g = g | 0x80;
    pfb[pixelNum].rgb.b = b | 0x80;
}

/**
 *
 * Get the pixel color as separate color channels
 *
 * @param h is the LedStrip instance handle from _Init()
 * @param pixelNum is the pixel number to read
 * @param[out] pr is a pointer for the returned value of the *red* color channel
 * @param[out] pg is a pointer for the returned value of the *green* color channel
 * @param[out] pb is a pointer for the returned value of the *blue* color channel
 *
 * The color channel values are returned via 3 caller supplied pointers,
 * each as a 7-bit value.  The values will all be set to 0 if there is
 * any error.
 */
void
LPD8806_LedStrip_GetPixelRgb(LPD8806_LedStrip_Handle_t h, uint32_t pixelNum,
                             uint8_t *pr, uint8_t *pg, uint8_t *pb)
{
    // Validate the return value pointers
    if(!pr || !pg || !pb)
    {
        return;
    }

    // Get instance pointer
    Instance_t *pInst = (Instance_t *)h;

    // Validate the instance
    if(!InstanceIsValid(pInst))
    {
        *pr = 0x80;
        *pg = 0x80;
        *pb = 0x80;
        return;
    }

    // check that pixel is within bounds
    if(pixelNum >= pInst->numPixels)
    {
        *pr = 0x80;
        *pg = 0x80;
        *pb = 0x80;
        return;
    }

    // Get the frame buffer
    pixel_t *pfb = pInst->pFrameBuffer;

    // read each color channel and store in the caller suppied storage
    // upper bit of each byte is masked off since it is not part
    // of the color value
    *pr = pfb[pixelNum].rgb.r & 0x7f;
    *pg = pfb[pixelNum].rgb.g & 0x7f;
    *pb = pfb[pixelNum].rgb.b & 0x7f;
}

/**
 *
 * Set an individual color channel for a pixel
 *
 * @param h is the LedStrip instance handle from _Init()
 * @param pixelNum is the pixel number to modify
 * @param channel is the color channel to modify: CHAN_RED, CHAN_GREEN, CHAN_BLUE
 * @param channelValue is the 7-bit value for the color channel
 *
 * This function can be used to set just a single color channel of a pixel.
 */
void
LPD8806_LedStrip_SetPixelChannel(LPD8806_LedStrip_Handle_t h, uint32_t pixelNum,
                                 LPD8806_LedStrip_Channel_t channel,
                                 uint8_t channelValue)
{
    // Get instance pointer
    Instance_t *pInst = (Instance_t *)h;

    // Validate the instance
    if(!InstanceIsValid(pInst))
    {
        return;
    }

    // Get the frame buffer
    pixel_t *pfb = pInst->pFrameBuffer;

    // check that pixel is within bounds
    if(pixelNum >= pInst->numPixels)
    {
        return;
    }

    // process the specified color channel
    // set the appropriate part (r, g, or b) of the LED
    // upper bit must be set to satisfy the controller
    switch(channel)
    {
        case CHAN_RED:
        {
            pfb[pixelNum].rgb.r = channelValue | 0x80;
            break;
        }
        case CHAN_GREEN:
        {
            pfb[pixelNum].rgb.g = channelValue | 0x80;
            break;
        }
        case CHAN_BLUE:
        {
            pfb[pixelNum].rgb.b = channelValue | 0x80;
            break;
        }
        default:
        {
            break;
        }
    }
}

/**
 *
 * Get a pixel individual color channel
 *
 * @param h is the LedStrip instance handle from _Init()
 * @param pixelNum is the pixel number to read
 * @param channel is the color channel to read: CHAN_RED, CHAN_GREEN, CHAN_BLUE
 *
 * @returns Returns the value of the specified color channel as 7-bits, or
 *          0 if there is an error.
 */
uint8_t
LPD8806_LedStrip_GetPixelChannel(LPD8806_LedStrip_Handle_t h, uint32_t pixelNum,
                                 LPD8806_LedStrip_Channel_t channel)
{
    // Get instance pointer
    Instance_t *pInst = (Instance_t *)h;

    // Validate the instance
    if(!InstanceIsValid(pInst))
    {
        return 0x80;
    }

    // Get the frame buffer
    pixel_t *pfb = pInst->pFrameBuffer;

    // check that pixel is within bounds
    if(pixelNum >= pInst->numPixels)
    {
        return 0x80;
    }

    // read the specified color channel value
    uint8_t ret;
    switch(channel)
    {
        case CHAN_RED:
        {
            ret = pfb[pixelNum].rgb.r;
            break;
        }
        case CHAN_GREEN:
        {
            ret = pfb[pixelNum].rgb.g;
            break;
        }
        case CHAN_BLUE:
        {
            ret = pfb[pixelNum].rgb.b;
            break;
        }
        default:
        {
            return 0x80;
            break;
        }
    }

    // mask off the upper bit because that is not part of the color value
    return ret & 0x7f;
}

/**
 * Update the LED string with the buffered values
 *
 * @param h is the LedStrip instance handle from _Init()
 *
 * The pixel values that were written to the LED "frame buffer" with the
 * above functions are copied to the physical LED string via the SSI/SPI
 * port.
 *
 * If DMA support is enabled, then this function will return right away while
 * the DMA runs in the background.  If DMA is not enabled, then this function
 * uses polled IO to copy the data to the SPI port until the entire buffer
 * has been copied to the output FIFO.
 */
void
LPD8806_LedStrip_Update(LPD8806_LedStrip_Handle_t h)
{
    // Get instance pointer
    Instance_t *pInst = (Instance_t *)h;

    // Validate the instance
    if(!InstanceIsValid(pInst))
    {
        return;
    }

    // Get the frame buffer
    pixel_t *pfb = pInst->pFrameBuffer;

    // Get count and pointer to start of data
    int count = pInst->numPixels * 3;
    uint8_t *pbytes = &pfb[0].bytes[0];

    // determine if DMA is enabled.  If LPD8806_DMA_SUPPORT is 0, then the
    // compiler will recognize that this code can not be executed and compile
    // it out.
    if(LPD8806_DMA_SUPPORT && pInst->useDma)
    {
        // wait until any prior DMA transfer is complete
        while(uDMAChannelModeGet(pInst->dmaChannel | UDMA_PRI_SELECT) != UDMA_MODE_STOP)
        {}

        // set the required trailing 0
        pfb[pInst->numPixels].bytes[0] = 0;

        // set up the DMA channel transfer and enable it.  Once this happens
        // the DMA should begin running
        uDMAChannelTransferSet(pInst->dmaChannel | UDMA_PRI_SELECT, UDMA_MODE_BASIC,
                               pbytes, (void *)(pInst->spiBase + SSI_O_DR),
                               count + 1);
        uDMAChannelEnable(pInst->dmaChannel);
    }

    // otherwise, handle by IO polling
    else
    {
        // Wait for any prior transaction to complete
        while(SSIBusy(pInst->spiBase))
        {}

        // loop until all bytes are written
        while(count--)
        {
            SSIDataPut(pInst->spiBase, *pbytes++);
        }

        // write the restart byte(s)
        for (uint32_t extra = 0; extra < pInst->latchBytes; extra++)
        {
            SSIDataPut(pInst->spiBase, 0);
        }
    }
}

/**
 * Get the number of pixels in the instance.
 *
 * @param h is the LedStrip instance handle from _Init()
 *
 * @returns Returns the number of pixels supported for the specified
 *          LedStrip instance.
 */
uint32_t
LPD8806_LedStrip_NumPixels(LPD8806_LedStrip_Handle_t h)
{
    // Get instance pointer
    Instance_t *pInst = (Instance_t *)h;

    // Validate the instance
    if(!InstanceIsValid(pInst))
    {
        return 0;
    }

    return pInst->numPixels;
}

/**
 * Initialize the LED strip driver hardware
 *
 * @param sysClock is the value of the system clock
 * @param spiIdx is the index of the SPI peripheral to use (0-origin)
 * @param spiRate is the data rate to use for SPI
 *
 * The application must call this function before using any other functions
 * in this driver.  It is used to set up a hardware instance for use by
 * the driver.  The parameter *sysClock* is the value of the MCU system
 * clock frequency.  It is needed for initializing the SPI peripheral.
 * The parameter *spiIdx* is the SPI peripheral number to use (0, 1, etc).
 * It is limited to the number of SPI peripherals in the system.
 * The *spiRate* is the desired clock frequency of the SPI peripheral.  There
 * is no validation of this parameter.  The driver will attempt to set
 * the specified value of the SPI clock rate but if it is not valid then
 * the init will probably fail silently.
 *
 * @note The application must also call LPD8806_LedStrip_SetFrameBuffer()
 *       before this driver can be used.
 *
 * @returns Returns a handle that is used for the other LedStrip function.
 *          The returned value will be NULL if there is any error with
 *          the initialization.
 */
LPD8806_LedStrip_Handle_t
LPD8806_LedStrip_Init(uint32_t sysClock, uint32_t spiIdx, uint32_t spiRate)
{
    // Check for valid parameters
    if (spiIdx >= NUM_SPI_PERIPHS)
    {
        return NULL;
    }

    // Attempt to allocate an instance for this new LedStrip
    Instance_t *pInst = NULL;
    for(uint32_t idx = 0; idx < LPD8806_LEDSTRIP_NUM_INSTANCES; idx++)
    {
        if(instances[idx].spiPeriph == 0)
        {
            pInst = &instances[idx];
            break;
        }
    }

    // Check to see if one was allocated
    if(!pInst)
    {
        return NULL;
    }

    // Save the SPI periph and enable it
    pInst->spiPeriph = spiPeriphTable[spiIdx].periph;
    SysCtlPeripheralEnable(pInst->spiPeriph);

    // Save the reset of the SPI config
    // Things are done in this order so there is some time gap from
    // PeripheralEnable() until peripheral is used
    pInst->spiBase = spiPeriphTable[spiIdx].base;
    pInst->spiRate = spiRate;

    // Configure the SSI(SPI) port used to control the display
    SSIDisable(pInst->spiBase);
    SSIConfigSetExpClk(pInst->spiBase, sysClock, SSI_FRF_MOTO_MODE_0,
                       SSI_MODE_MASTER, pInst->spiRate, 8);
    SSIEnable(pInst->spiBase);

    // Return the new handle to the caller
    return (void *)pInst;
}

/**
 * Set the frame buffer for an LedStrip instance
 *
 * @param h is the LedStrip instance handle from _Init()
 * @param pFrameBuffer is a pointer to storage for the frame buffer
 * @param numPixels is the number of pixels for the frame buffer
 *
 * This function assigns a frame buffer to the LedStrip instance.  This
 * must be called at least once following LPD8806_LedStrip_Init().  It can
 * be called other times if needed to change the frame buffer for an LedStrip.
 * For example if there is a pre-rendered frame buffer it could be used to
 * switch between computed and pre-rendered frame buffer.
 *
 * The caller must allocate the space for the frame buffer, *pFrameBuffer*.
 * The macro LPD8806_FRAMEBUF_SIZE can be used to get the number of bytes
 * that are needed for a frame buffer given the number of pixels to store.
 */
void
LPD8806_LedStrip_SetFrameBuffer(LPD8806_LedStrip_Handle_t h, void *pFrameBuffer,
                                uint32_t numPixels)
{
    // Get instance pointer
    Instance_t *pInst = (Instance_t *)h;

    // Check for basic instance validity
    if(!pInst || (pInst->spiPeriph == 0))
    {
        return;
    }

    // Check for valid frame buffer
    if(!pFrameBuffer || (numPixels == 0))
    {
        return;
    }

    // Assign the frame buffer to the instance
    pInst->numPixels = numPixels;
    pInst->pFrameBuffer = pFrameBuffer;

    // Compute the number of "latch" bytes that are needed.
    // These are extra bytes inserting into the data stream and are
    // required by the lpd8806
    pInst->latchBytes = (numPixels + 31) / 32;
}

/**
 * Clear the frame buffer
 *
 * @param h is the LedStrip instance handle from _Init()
 *
 * This is a convenience function the clear the contents of the frame
 * buffer back to "zero", meaning all pixels are off.  This function does
 * not update the hardware.
 */
void
LPD8806_LedStrip_Clear(LPD8806_LedStrip_Handle_t h)
{
    // Get instance pointer
    Instance_t *pInst = (Instance_t *)h;

    // Validate the instance
    if(!InstanceIsValid(pInst))
    {
        return;
    }

    // Get the frame buffer
    pixel_t *pfb = pInst->pFrameBuffer;

    // clear out all the pixel values and set the upper bits, which is
    // needed by the controler
    for(int i = 0; i < pInst->numPixels; i++)
    {
        pfb[i].bytes[0] = 0x80;
        pfb[i].bytes[1] = 0x80;
        pfb[i].bytes[2] = 0x80;
    }
}

/**
 * Enable the use of DMA by the driver
 *
 * @param h is the LedStrip instance handle from _Init()
 * @param dmaChannel is the DMA channel number that should be used for the SSI/SPI
 *
 * This function assigns the DMA channel to the LedStrip instance and enables
 * use of DMA when writing pixel data using the SPI peripheral.  The caller
 * must provide a valid DMA channel and configuration - nothing is done
 * to validate the DMA channel.
 *
 * The application must first set up the DMA controller and configure the
 * correct DMA channel for this peripheral before calling this function.
 */
#ifdef LPD8806_LEDSTRIP_ALLOW_DMA
void
LPD8806_LedStrip_EnableDma(LPD8806_LedStrip_Handle_t h, uint32_t dmaChannel)
{
    // Get instance pointer
    Instance_t *pInst = (Instance_t *)h;

    // Validate the instance
    if(!InstanceIsValid(pInst))
    {
        return;
    }

    // save DMA flag and channel number
    pInst->useDma = true;
    pInst->dmaChannel = dmaChannel;

    // set up the DMA channel
    uDMAChannelControlSet(dmaChannel | UDMA_PRI_SELECT,
                          UDMA_SIZE_8 | UDMA_SRC_INC_8 |
                          UDMA_DST_INC_NONE | UDMA_ARB_4);

    // configure the SSI/SPI peripheral to generate DMA request
    SSIDMAEnable(pInst->spiBase, SSI_DMA_TX);
}
#endif

/**
 * @}
 */

#ifdef LPD8806_LEDSTRIP_COMPILER_TEST
/******************************************************************************
 *
 * TEST CODE
 *
 * The following is test code just for the purpose of a compiler test.
 * It is not functional.
 *
 *****************************************************************************/

#define NUM_TEST_PIXELS 40
static uint8_t frameBuffer[LPD8806_FRAMEBUF_SIZE(NUM_TEST_PIXELS)];

void
LPD8806_LedStrip_Test(void)
{
    LPD8806_LedStrip_Handle_t h;

    h = LPD8806_LedStrip_Init(SysCtlClockGet(), 0, 500000);
    LPD8806_LedStrip_SetFrameBuffer(h, frameBuffer, NUM_TEST_PIXELS);
    LPD8806_LedStrip_Clear(h);
    LPD8806_LedStrip_Update(h);
    LPD8806_LedStrip_SetPixelChannel(h, 0, CHAN_BLUE, 0x40);
    uint8_t blue = LPD8806_LedStrip_GetPixelChannel(h, 0, CHAN_BLUE);
    LPD8806_LedStrip_SetPixelValue(h, 0, 0x123456);
    uint32_t value = LPD8806_LedStrip_GetPixelValue(h, 0);
    LPD8806_LedStrip_SetPixelRgb(h, 0, 1, 2, 3);
    uint8_t r, g, b;
    LPD8806_LedStrip_GetPixelRgb(h, 0, &r, &g, &b);
    uint32_t numPixels = LPD8806_LedStrip_NumPixels(h);
    numPixels = numPixels;
    value = value;
    blue = blue;
}
#endif


text:
title: Vert.x 3.2.0 is released !
date: 2015-12-15
template: post.html
author: cescoffier
---

We are pleased to announce the release of Vert.x 3.2.0!

Some of the highlights of this release include:

* [vertx-lang-ceylon](http://vertx.io/docs/vertx-core/ceylon): the support of the [Ceylon language](http://ceylon-lang.org/)!

*	[vertx-tcp-bridge](http://vertx.io/docs/vertx-tcp-eventbus-bridge/java/): an event bus bridge that lets any TCP-capable application to interact with vert.x applications using the event bus.

*	[vertx-hawkular-metric](http://vertx.io/docs/vertx-hawkular-metrics/java/): an implementation of the vert.x metrics for [Hawkular](http://www.hawkular.org/). In addition, it lets you report your own metrics to hawkular.

* A new [stack manager](http://vertx.io/docs/vertx-stack-manager/stack-manager/) to configure the vert.x distribution with the content you want.

* [vertx-shell](http://vertx.io/docs/vertx-shell/java/) is now an official component.

* [vertx-jgroups](http://vertx.io/docs/vertx-jgroups/java/): an alternative implementation of the vert.x cluster manager using [JGroups](http://jgroups.org/). This component is a technical preview.

The release also contains many bug fixes and a ton of improvements. Full release notes can be found here:

https://github.com/vert-x3/wiki/wiki/3.2.0---Release-Notes

Breaking changes are here:

https://github.com/vert-x3/wiki/wiki/3.2.0-Breaking-changes

The event bus client using the SockJS bridge are available from NPM, Bower and as a WebJar:

* https://www.npmjs.com/package/vertx3-eventbus-client
* https://github.com/vert-x3/vertx-bus-bower
* http://www.webjars.org/

Dockers images are also available on the [Docker Hub](https://hub.docker.com/u/vertx/)
The vert.x distribution is also available from [SDKMan](http://sdkman.io/index.html).

Many thanks to all the committers and community whose contributions made this possible.

Next stop is Vert.x 3.3.0 which we hope to have out in March 2016.

The artifacts have been deployed to [Maven Central](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22io.vertx%22%20AND%20v%3A%223.2.0%22)
 and you can get the distribution on [Bintray](https://bintray.com/vertx/downloads/distribution/3.2.0/view).


text:
package general;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class RainWaterTest {

	@Test
	public void findAccumulatedWater_NoWaterAccumulated() {
		assertEquals(0L, RainWater.findAccumulatedWater(new int[] { 2, 1 }));
	}

	@Test
	public void findAccumulatedWater_SomeWaterAccumulated() {
		assertEquals(
				25L,
				RainWater.findAccumulatedWater(new int[] { 2, 0, 2, 1, 3, 2, 6,
						0, 5, 2, 10, 5, 5, 0, 0, 2, 4 }));
	}
}


text:
namespace Prism.Logging
{
    /// <summary>
    /// Defines a simple logger façade to be used by the Prism Library.
    /// </summary>
    public interface ILoggerFacade
    {
        /// <summary>
        /// Write a new log entry with the specified category and priority.
        /// </summary>
        /// <param name="message">Message body to log.</param>
        /// <param name="category">Category of the entry.</param>
        /// <param name="priority">The priority of the entry.</param>
        void Log(string message, Category category, Priority priority);
    }
}


text:
package org.jboss.hal.ballroom.editor;

import jsinterop.annotations.JsFunction;
import jsinterop.annotations.JsType;

@JsType(isNative = true)
public class Session {

    public native void setValue(String value);

    public native void setMode(String mode);

    public native String getValue();

    public native int getLength();

    public native void on(String event, OnChange onChange);

    @JsFunction
    @FunctionalInterface
    public interface OnChange {

        void onChange(Object delta);
    }
}


text:
import os

def get_settings_module():
    if os.environ['USER'] == 'ubuntu':
        import botaniser.settings.prod as settings
        return settings
    else:
        import botaniser.settings.dev as settings
        return settings


text:
var test = require('tap').test
var feedGenerator = require('../lib/feed-generator')

var path = require('path')

var f = require('util').format

test('generate the rss feed!', function (t) {
  var site = {
    url: 'http://example.org',
    title: 'My Site',
    description: 'A site for stuff, ya know?',
    imageUrl: 'http://example.org/image.png',
    author: 'brianloveswords',
  }

  var expect = {
    preamble: '<?xml version="1.0" encoding="UTF-8"?>\n<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">',
    title: f('<title><![CDATA[%s]]></title>', site.title),
    desc: f('<description><![CDATA[%s]]></description>', site.description),
    image: f('<image><url>%s</url><title>%s</title><link>%s</link></image>',
            site.imageUrl, site.title, site.url),
    author: f('<author><![CDATA[%s]]></author>', site.author),
    items: [
      '<item><title><![CDATA[Today]]></title><description><![CDATA[Today]]></description><link>http://example.org/blog/today.html</link><guid isPermaLink="true">http://example.org/blog/today.html</guid><dc:creator><![CDATA[brianloveswords]]></dc:creator><pubDate>Invalid Date</pubDate></item>',
      '<item><title><![CDATA[Tomorrow]]></title><description><![CDATA[Tomorrow]]></description><link>http://example.org/blog/tomorrow.html</link><guid isPermaLink="true">http://example.org/blog/tomorrow.html</guid><dc:creator><![CDATA[brianloveswords]]></dc:creator><pubDate>Invalid Date</pubDate></item>',
      '<item><title><![CDATA[Yesterday]]></title><description><![CDATA[Yesterday]]></description><link>http://example.org/blog/yesterday.html</link><guid isPermaLink="true">http://example.org/blog/yesterday.html</guid><dc:creator><![CDATA[brianloveswords]]></dc:creator><pubDate>Invalid Date</pubDate></item>'
    ]
  }

  feedGenerator({
    postsDir: path.join(__dirname, 'test-feedgen'),
    urlPrefix: 'blog',
    site: site
  }, function (err, feed) {

    t.ok(~feed.indexOf(expect.preamble), 'should have preamble')
    t.ok(~feed.indexOf(expect.title), 'should have title')
    t.ok(~feed.indexOf(expect.desc), 'should have desc')
    t.ok(~feed.indexOf(expect.image), 'should have image')
    t.ok(~feed.indexOf(expect.author), 'should have author')

    expect.items.forEach(function (item, i) {
      t.ok(~feed.indexOf(item), 'should have item ' + i)
    })

    t.end()
  })
})


text:
<link rel="import" href="filter-test-filter.html">
<link rel="import" href="filter-test-response.html">

<dom-module id="filter-test-page">

    <template>
        <iron-ajax
            id="listAjax"
            url="[[listAjaxUrl]]"
            body="[[bodyPost]]"
            headers="[[header]]"
            method="GET"
            last-response="{{response}}"></iron-ajax>
        <iron-ajax
            id="listAjaxPost"
            url="[[listAjaxUrlPost]]"
            body="[[bodyPost]]"
            headers="[[header]]"
            method="POST"
            content-type="application/json"
            last-response="{{responsePost}}"></iron-ajax>

        <iron-ajax
            id="listAjaxPut"
            url="[[listAjaxUrlPut]]"
            body="[[bodyPut]]"
            headers="[[header]]"
            method="PUT"
            content-type="application/json"
            last-response="{{responsePut}}"></iron-ajax>
        <iron-ajax
            id="listAjaxDelete"
            url="[[listAjaxUrlDelete]]"
            body="[[bodyDelete]]"
            headers="[[header]]"
            method="DELETE"
            content-type="application/json"
            last-response="{{responseDelete}}"></iron-ajax>

        <my-app-title page="[[page]]" is-current="[[isCurrentPage]]">Összetett szűrés</my-app-title>
        <fab-element id="refreshFab" icon="refresh" signal-name="refresh-filter-test" page="[[home]]"></fab-element>
        <iron-signals on-iron-signal-refresh-filter-test="refresh"></iron-signals>

GET

            <paper-material elevation="1" class="card flex-1">
                <filter-test-filter filter="{{filter}}" valid="{{valid}}"></filter-test-filter>
            </paper-material>

            <paper-material elevation="1" class="card flex-2">
                <filter-test-response response="[[response]]"></filter-test-response>
            </paper-material>

POST

            <paper-material elevation="1" class="card flex-1">
                <filter-test-filter filter="{{filterPost}}" valid="{{validPost}}"></filter-test-filter>
            </paper-material>

            <paper-material elevation="1" class="card flex-2">
                <filter-test-response response="[[responsePost]]"></filter-test-response>
            </paper-material>

PUT

            <paper-material elevation="1" class="card flex-1">
                <filter-test-filter filter="{{filterPut}}" valid="{{validPut}}"></filter-test-filter>
            </paper-material>

            <paper-material elevation="1" class="card flex-2">
                <filter-test-response response="[[responsePut]]"></filter-test-response>
            </paper-material>

DELETE

            <paper-material elevation="1" class="card flex-1">
                <filter-test-filter filter="{{filterDelete}}" valid="{{validDelete}}"></filter-test-filter>
            </paper-material>

            <paper-material elevation="1" class="card flex-2">
                <filter-test-response response="[[responseDelete]]"></filter-test-response>
            </paper-material>

    </template>
</dom-module>


text:
function isScrolledIntoView(elem, offsetFromTop)
{
    offsetFromTop = typeof offsetFromTop !== 'undefined' ? offsetFromTop : 0;
    var $elem = $(elem);
    var $window = $(window);

    var docViewTop = $window.scrollTop() + offsetFromTop;
    var docViewBottom = docViewTop + $window.height();

    var elemTop = $elem.offset().top;
    var elemBottom = elemTop + $elem.height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

$(document).ready(function() {

    $('#edit-on-github').click(function(e) {
        var path = location.pathname;
        var repo = "https://github.com/Gigaspaces/xap-docs";
        //handling directories

        if (path.indexOf("/", path.length - 1) !== -1) path = path.slice(0,-1);
        if (path.indexOf(".html") == -1) path += "/index.html";
        markdownFile = path.replace(".html", ".markdown");
        location.href=repo + "/edit/master/site/content/" + markdownFile + "#";

 //       if (path.indexOf("/sbp/") != -1) {
 //           repo = "https://github.com/Gigaspaces/xap-docs";
 //           markdownFile = markdownFile.replace("/sbp/", "/")
 //           location.href=repo + "/edit/master" + markdownFile + "#";
 //       }
    });

    var githubPopupTitle = 'Help Us Improve!';
    var githubPopupText = 'Found a mistake in this page? Click here to edit it in Github and propose your change!';

    var mq = window.matchMedia( "(min-width: 1024px)" );
    if (mq.matches) {
        $("#edit-on-github").popover({
            placement: 'left',
            html: 'true',
            title : ''+githubPopupTitle+'' +
            '<button type="button" id="close" class="close" onclick="$("#edit-on-github").popover("hide");">×</button>',
            content : githubPopupText
        });

        function enablePopoverOnMouseover() {
            $('#edit-on-github').on('mouseover',
            function () {
                $('#edit-on-github').popover('show');
            });

            $('#edit-on-github').on('mouseleave',
            function () {
                $('#edit-on-github').popover('hide');
            });
        }

        var githubPopupPresented = sessionStorage.getItem('githubPopupPresented');
        enablePopoverOnMouseover();
    }
});


text:
package service

import ()

// TokenService is the abstract representation of this service.
type TokenService interface {
	Ping() string
	// Parameters:
	//  - Key
	//  - Ttype
	CreateToken(key string, ttype int64) string
	// Parameters:
	//  - Key
	//  - Ttype
	DeleteToken(key string, ttype int64) bool
}


text:
module Metova
  module Oauth
    class GenericProvider
      attr_accessor :access_token, :token_secret, :uid, :provider, :info

      def initialize(access_token, token_secret = nil)
        @access_token = access_token
        @token_secret = token_secret
      end

      def self.authenticate(provider, access_token, token_secret = nil)
        find_provider(provider).new(access_token, token_secret).authenticate
      end

      def name
        'OAuth'
      end

      protected
        def me(&block)
          yield
          # rescue errors
        end

        def setup_with_devise?
          devise_configuration.present?
        end

        def devise_configuration
          ::Devise.omniauth_configs[provider]
        end

        def devise_strategy
          devise_configuration.strategy
        end

        def consumer_key
          devise_strategy.consumer_key
        end

        def consumer_secret
          devise_strategy.consumer_secret
        end

      private
        def self.find_provider(provider)
          map = {
            twitter: Metova::Oauth::TwitterProvider,
            facebook: Metova::Oauth::FacebookProvider,
            google_oauth2: Metova::Oauth::GoogleProvider,
            flux: Metova::Oauth::FluxProvider
          }

          map.fetch provider.to_sym
        end
    end
  end
end


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activities.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/list_recycle_parent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:scrollbars="vertical" />

</RelativeLayout>


text:
var sensor = {

  publish: function(data) {
    var params = config.load();
    var deviceId = sensor.deviceInfo().uuid;
    var client = mqtt.connect(
      "tcp://" + params.org + ".messaging.internetofthings.ibmcloud.com:1883",
      {
        clientId: 'd:' + params.org + ':' + params.deviceType + ':' + deviceId,
        username: 'use-token-auth',
        password: params.token
      }
    );
    geolocation.get(function(geolocation) {
      accelerometer.get(function(accelerometer) {
        console.log("publihed");
        client.publish(
          "iot-2/evt/itemsvc/fmt/json",
          JSON.stringify({
            "d": {
              device: sensor.deviceInfo(),
              geolocation: geolocation,
              accelerometer: accelerometer
            },
            "ts": sensor.timestamp()
          }),
          function() {
            console.log("disconnected")
            client.end();
          }
        );
      });
    });
  },

  deviceInfo: function() {
    try {
      return device;
    } catch (e) {
      return null;
    }
  },

  timestamp: function() {
    var now = new Date();
    var date = now.getFullYear() + '/';
    date = date + (now.getMonth() + 1) + '/';
    date = date + now.getDate() + 'T';
    date = date + now.getHours() + ':';
    date = date + now.getMinutes() + ':';
    date = date + now.getSeconds() + '.';
    date = date + now.getMilliseconds() + 'Z';
    return date;
  }

};


text:
{% extends "base.html" %}

{% block title %}Impressum - BundesTagger{% endblock %}

{% block description %}Impressum von BundesTagger und Kontaktinformationen zu Stefan Wehrmeyer{% endblock %}

{% block currentnav %}startseite{% endblock %}

{% block body %}

Impressum

Diese Seite ist parteiunabhängig, nicht kommerziell und wird betrieben von:

    Stefan
    Wehrmeyer

        Roonstr. 22

        12203 Berlin,
        Deutschland

E-Mail: mail@bundestagger.de

Twitter: bundestagger bei Twitter

Bildquellen

Das Original des Hintergrundbilds ist von pablokdc und steht unter einer Creative Commons Lizenz (by-nc-sa-2.0/en). Der Remix auf dieser Seite steht unter der gleichen Lizenz zur Verfügung.

Bitte beachte auch die Nutzungsbedinungen/Datenschutzerklärung und die wichtigen Hinweise.

{% endblock %}


text:
require 'spec_helper'

describe SemanticIconHelper do
  it "render icon with name" do
    expect(semantic_icon('add')).to eq ''
  end

  it "render icon with names with string" do
    expect(semantic_icon('add sign')).to eq ''
  end

  it "render icon with names with params" do
    expect(semantic_icon('add', 'sign')).to eq ''
  end

  it "render icon with names with sym params" do
    expect(semantic_icon(:add, :sign)).to eq ''
  end

  it "render icon with name and id" do
    expect(semantic_icon('add', id: 'id')).to eq ''
  end

  it "render icon with names with string and id" do
    expect(semantic_icon('add sign', id: 'id')).to eq ''
  end

  it "render icon with names with params and id" do
    expect(semantic_icon('add', 'sign', id: 'id')).to eq ''
  end

  it "render icon with names with sym params and id" do
    expect(semantic_icon(:add, :sign, id: 'id')).to eq ''
  end

end


text:
@interface TestViewController : BaseViewController

@end


text:
__author__ = 'heddevanderheide'

import six

# Django specific
from django_extensions.db.fields import AutoSlugField

def __init__(self, *args, **kwargs):
    kwargs.setdefault('blank', True)
    kwargs.setdefault('editable', False)

    populate_from = kwargs.pop('populate_from', None)
    # if populate_from is None:
        # raise ValueError("missing 'populate_from' argument")
    # else:
    self._populate_from = populate_from
    self.separator = kwargs.pop('separator', six.u('-'))
    self.overwrite = kwargs.pop('overwrite', False)
    self.allow_duplicates = kwargs.pop('allow_duplicates', False)
    super(AutoSlugField, self).__init__(*args, **kwargs)

AutoSlugField.__init__ = __init__
"""
Unfortunately django-extensions is not entirely compatible
with Django's migrations, so we need some patching code

n.b. this file is imported explicitly from the init file.
"""


text:
package org.apache.bookkeeper.metastore;

/**
 * A metastore watched event.
 */
public class MSWatchedEvent {
    /**
     * The metastore event type.
     */
    public enum EventType {CHANGED, REMOVED}

    String key;
    EventType type;

    public MSWatchedEvent(String key, EventType type) {
        this.key = key;
        this.type = type;
    }

    public EventType getType() {
        return type;
    }

    public String getKey(){
        return key;
    }
}


text:
<head>
  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <!-- Enable responsiveness on mobile devices-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>
    {{ if eq .Url "/" }}
      {{ .Site.Params.Title }} · {{ .Site.Params.Tagline }}
    {{ else }}
      {{ .Title }} · {{ .Site.Params.Title }}
    {{ end }}
  </title>

  <!-- CSS -->
  <link rel="stylesheet" href="/blog/css/poole.css">
  <link rel="stylesheet" href="/blog/css/syntax.css">
  <link rel="stylesheet" href="/blog/css/lanyon.css">
  <link rel="stylesheet" href="/blog/css/custom.css">
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Serif:400,400italic,700|PT+Sans:400">

  <!-- Icons -->
  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/blog/assets/apple-touch-icon-144-precomposed.png">
  <link rel="shortcut icon" href="/blog/assets/favicon.ico">

  <!-- RSS -->
  <link rel="alternate" type="application/rss+xml" title="RSS" href="/blog/index.xml">
</head>


text:
package com.qlfg.miningcircle.entity;

public class LoanEntity {
	String id ;
	String name;
	Object icon;
	Object icon_act;
	String act;
	String type ;

	public Object getIcon_act() {
		return icon_act;
	}
	public void setIcon_act(Object icon_act) {
		this.icon_act = icon_act;
	}
	public String getAct() {
		return act;
	}
	public void setAct(String act) {
		this.act = act;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Object getIcon() {
		return icon;
	}
	public void setIcon(Object icon) {
		this.icon = icon;
	}

}


text:
<!DOCTYPE html>

<meta charset="utf-8"/>
<title data-ng-bind="'Dr. Referral Tracker | ' + $state.current.data.pageInfo.title"></title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1" name="viewport"/>
<meta content="" name="description"/>
<meta content="" name="author"/>

<link href="./assets/global/plugins/googleapifonts/OpenSans.css" rel="stylesheet" type="text/css"/>
<link href="./assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
<link href="./assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css"/>
<link href="./assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="./assets/global/plugins/angular-ui-select/select.min.css" rel="stylesheet" type="text/css"/>
<link href="./assets/global/plugins/ui-grid/ui-grid.min.css" rel="stylesheet" type="text/css"/>

<link href="./assets/global/css/components.css" id="style_components" rel="stylesheet" type="text/css"/>
<link href="./assets/global/css/plugins.css" rel="stylesheet" type="text/css"/>
<link href="./assets/admin/layout2/css/layout.css" rel="stylesheet" type="text/css"/>
<link href="./assets/admin/layout2/css/themes/default.css" rel="stylesheet" type="text/css" id="style_color"/>
<link href="./assets/admin/layout2/css/custom.css" rel="stylesheet" type="text/css"/>

<link rel="shortcut icon" href="favicon.ico"/>

                         Old site

                        {{currentUser.username}}

                                 My Profile

                                 Log Out

                    {{ $state.get('dashboard').data.pageInfo.title }}

                    {{ $state.get('organization-list').data.pageInfo.title }}

                    {{ $state.get('referring_entity-list').data.pageInfo.title }}

                    {{ $state.get('treating_provider-list').data.pageInfo.title }}

                    {{ $state.get('patient_visit-list').data.pageInfo.title }}

                        Reports

                                 {{ $state.get('report-patient_visits').data.pageInfo.title }}

                                 {{ $state.get('report-weekly_providers_visits').data.pageInfo.title }}

                                 {{ $state.get('report-monthly_providers_visits').data.pageInfo.title }}

                        Email Reports Setting

                                 {{ $state.get('reportsetting-clinic').data.pageInfo.title }}

                                 {{ $state.get('reportsetting-referring').data.pageInfo.title }}

             2016 © Heteroskedastic.


text:
package org.milvus.core;

public interface Annotation {

  String getType();

  int getStart();

  int getEnd();

}


text:
@interface PodsDummy_Pods_SwiftySensorsExample : NSObject
@end
@implementation PodsDummy_Pods_SwiftySensorsExample
@end


text:
namespace google_calendar_api {
using namespace googleapis;

// Object factory method (static).
Calendar* Calendar::New() {
  return new client::JsonCppCapsule<Calendar>;
}

// Standard immutable constructor.
Calendar::Calendar(const Json::Value& storage)
  : client::JsonCppData(storage) {
}

// Standard mutable constructor.
Calendar::Calendar(Json::Value* storage)
  : client::JsonCppData(storage) {
}

// Standard destructor.
Calendar::~Calendar() {
}
}  // namespace google_calendar_api


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Web.Mvc;
using Glimpse.Core.Extensibility;
using Glimpse.Core.Extensions;
using Glimpse.Core.Message;
using Glimpse.Mvc.Message;

namespace Glimpse.Mvc.AlternateType
{
    public class View : AlternateType<IView>
    {
        private List<IAlternateMethod> allMethods;

        public View(IProxyFactory proxyFactory) : base(proxyFactory)
        {
        }

        public override IEnumerable<IAlternateMethod> AllMethods
        {
            get
            {
                return allMethods ?? (allMethods = new List<IAlternateMethod>
                    {
                        new Render()
                    });
            }
        }

        public class Render : AlternateMethod
        {
            public Render() : base(typeof(IView), "Render")
            {
            }

            public override void PostImplementation(IAlternateMethodContext context, TimerResult timing)
            {
                var mixin = context.Proxy as IViewCorrelationMixin;
                var args = new Arguments(context.Arguments);
                var message = new Message(args.ViewContext.ViewData.Model.GetTypeOrNull(), args.ViewContext.ViewData.ModelState.IsValid, args.ViewContext.TempData, args.ViewContext.ViewData, args.ViewContext.ViewData.ModelMetadata, context.TargetType, mixin)
                    .AsActionMessage(args.ViewContext.Controller)
                    .AsTimedMessage(timing)
                    .AsMvcTimelineMessage(MvcTimelineCategory.View);

                context.MessageBroker.Publish(message);
            }

            public class Arguments
            {
                public Arguments(params object[] arguments)
                {
                    ViewContext = (ViewContext)arguments[0];
                    Writer = (TextWriter)arguments[1];
                }

                public ViewContext ViewContext { get; set; }

                public TextWriter Writer { get; set; }
            }

            public class Message : MessageBase, IActionMessage, ITimelineMessage
            {
                public Message(Type viewDataModelType, bool modelStateIsValid, IDictionary<string, object> tempData, IDictionary<string, object> viewData, ModelMetadata modelMetadata, Type baseType, IViewCorrelationMixin viewCorrelation)
                {
                    ViewDataModelType = viewDataModelType;
                    ModelStateIsValid = modelStateIsValid;
                    TempData = tempData;
                    ViewData = viewData;
                    ModelMetadata = modelMetadata;
                    BaseType = baseType;
                    ViewCorrelation = viewCorrelation;
                }

                public string ControllerName { get; set; }

                public string ActionName { get; set; }

                public TimeSpan Offset { get; set; }

                public TimeSpan Duration { get; set; }

                public DateTime StartTime { get; set; }

                public string EventName { get; set; }

                public TimelineCategoryItem EventCategory { get; set; }

                public string EventSubText { get; set; }

                public Type ViewDataModelType { get; private set; }

                public bool ModelStateIsValid { get; private set; }

                public IDictionary<string, object> TempData { get; private set; }

                public IDictionary<string, object> ViewData { get; private set; }

                public ModelMetadata ModelMetadata { get; private set; }

                public Type BaseType { get; private set; }

                public IViewCorrelationMixin ViewCorrelation { get; private set; }
            }
        }
    }
}


text:
void *memset(void *s, int c, size_t n) {
    return mp_fun_table.memset_(s, c, n);
}
#endif

mp_obj_full_type_t decompio_type;
mp_stream_p_t decompio_stream_p;

#include "extmod/moduzlib.c"

mp_map_elem_t decompio_locals_dict_table[3];
STATIC MP_DEFINE_CONST_DICT(decompio_locals_dict, decompio_locals_dict_table);

mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) {
    MP_DYNRUNTIME_INIT_ENTRY

    decompio_stream_p.name = MP_QSTR_protocol_stream;
    decompio_stream_p.read = decompio_read;

    decompio_type.base.type = mp_fun_table.type_type;
    decompio_type.flags = MP_TYPE_FLAG_EXTENDED;
    decompio_type.name = MP_QSTR_DecompIO;
    decompio_type.make_new = decompio_make_new;
    decompio_type.ext[0].protocol = &decompio_stream_p;
    decompio_locals_dict_table[0] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_read), MP_OBJ_FROM_PTR(&mp_stream_read_obj) };
    decompio_locals_dict_table[1] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_readinto), MP_OBJ_FROM_PTR(&mp_stream_readinto_obj) };
    decompio_locals_dict_table[2] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_readline), MP_OBJ_FROM_PTR(&mp_stream_unbuffered_readline_obj) };
    decompio_type.locals_dict = (void*)&decompio_locals_dict;

    mp_store_global(MP_QSTR___name__, MP_OBJ_NEW_QSTR(MP_QSTR_uzlib));
    mp_store_global(MP_QSTR_decompress, MP_OBJ_FROM_PTR(&mod_uzlib_decompress_obj));
    mp_store_global(MP_QSTR_DecompIO, MP_OBJ_FROM_PTR(&decompio_type));

    MP_DYNRUNTIME_INIT_EXIT
}


text:
package com.dianping.cat.status.model.transform;

import com.dianping.cat.status.model.Constants;
import com.dianping.cat.status.model.IEntity;
import com.dianping.cat.status.model.entity.*;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.Stack;

public class DefaultSaxParser extends DefaultHandler {
    private DefaultLinker linker = new DefaultLinker(true);
    private DefaultSaxMaker maker = new DefaultSaxMaker();
    private Stack<String> tags = new Stack<String>();
    private Stack<Object> objects = new Stack<Object>();
    private IEntity<?> entity;
    private StringBuilder text = new StringBuilder();

    public static StatusInfo parse(InputSource is) throws SAXException, IOException {
        return parseEntity(StatusInfo.class, is);
    }

    public static StatusInfo parse(InputStream in) throws SAXException, IOException {
        return parse(new InputSource(in));
    }

    public static StatusInfo parse(Reader reader) throws SAXException, IOException {
        return parse(new InputSource(reader));
    }

    public static StatusInfo parse(String xml) throws SAXException, IOException {
        return parse(new InputSource(new StringReader(xml)));
    }

    public static <T extends IEntity<?>> T parseEntity(Class<T> type, String xml) throws SAXException, IOException {
        return parseEntity(type, new InputSource(new StringReader(xml)));
    }

    @SuppressWarnings("unchecked")
    public static <T extends IEntity<?>> T parseEntity(Class<T> type, InputSource is) throws SAXException, IOException {
        try {
            DefaultSaxParser handler = new DefaultSaxParser();
            SAXParserFactory factory = SAXParserFactory.newInstance();

            factory.setValidating(false);
            factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            factory.setFeature("http://xml.org/sax/features/validation", false);

            factory.newSAXParser().parse(is, handler);
            return (T) handler.getEntity();
        } catch (ParserConfigurationException e) {
            throw new IllegalStateException("Unable to get SAX parser instance!", e);
        }
    }

    @SuppressWarnings("unchecked")
    protected <T> T convert(Class<T> type, String value, T defaultValue) {
        if (value == null || value.length() == 0) {
            return defaultValue;
        }

        if (type == Boolean.class) {
            return (T) Boolean.valueOf(value);
        } else if (type == Integer.class) {
            return (T) Integer.valueOf(value);
        } else if (type == Long.class) {
            return (T) Long.valueOf(value);
        } else if (type == Short.class) {
            return (T) Short.valueOf(value);
        } else if (type == Float.class) {
            return (T) Float.valueOf(value);
        } else if (type == Double.class) {
            return (T) Double.valueOf(value);
        } else if (type == Byte.class) {
            return (T) Byte.valueOf(value);
        } else if (type == Character.class) {
            return (T) (Character) value.charAt(0);
        } else {
            return (T) value;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        text.append(ch, start, length);
    }

    @Override
    public void endDocument() throws SAXException {
        linker.finish();
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (uri == null || uri.length() == 0) {
            Object currentObj = objects.pop();
            String currentTag = tags.pop();

            if (currentObj instanceof RuntimeInfo) {
                RuntimeInfo runtime = (RuntimeInfo) currentObj;

                if (Constants.ELEMENT_USER_DIR.equals(currentTag)) {
                    runtime.setUserDir(getText());
                } else if (Constants.ELEMENT_JAVA_CLASSPATH.equals(currentTag)) {
                    runtime.setJavaClasspath(getText());
                }
            } else if (currentObj instanceof ThreadsInfo) {
                ThreadsInfo thread = (ThreadsInfo) currentObj;

                if (Constants.ELEMENT_DUMP.equals(currentTag)) {
                    thread.setDump(getText());
                }
            } else if (currentObj instanceof Extension) {
                Extension extension = (Extension) currentObj;

                if (Constants.ELEMENT_DESCRIPTION.equals(currentTag)) {
                    extension.setDescription(getText());
                }
            }
        }

        text.setLength(0);
    }

    private IEntity<?> getEntity() {
        return entity;
    }

    protected String getText() {
        return text.toString();
    }

    private void parseForCustomInfo(CustomInfo parentObj, String parentTag, String qName, Attributes attributes) throws SAXException {
        objects.push(parentObj);
        tags.push(qName);
    }

    private void parseForDisk(DiskInfo parentObj, String parentTag, String qName, Attributes attributes) throws SAXException {
        if (Constants.ENTITY_DISK_VOLUME.equals(qName)) {
            DiskVolumeInfo diskVolume = maker.buildDiskVolume(attributes);

            linker.onDiskVolume(parentObj, diskVolume);
            objects.push(diskVolume);
        } else {
            throw new SAXException(String.format("Element(%s) is not expected under disk!", qName));
        }

        tags.push(qName);
    }

    private void parseForDiskVolume(DiskVolumeInfo parentObj, String parentTag, String qName, Attributes attributes) throws SAXException {
        objects.push(parentObj);
        tags.push(qName);
    }

    private void parseForExtension(Extension parentObj, String parentTag, String qName, Attributes attributes) throws SAXException {
        if (Constants.ELEMENT_DESCRIPTION.equals(qName)) {
            objects.push(parentObj);
        } else if (Constants.ENTITY_EXTENSIONDETAIL.equals(qName)) {
            ExtensionDetail extensionDetail = maker.buildExtensionDetail(attributes);

            linker.onExtensionDetail(parentObj, extensionDetail);
            objects.push(extensionDetail);
        } else {
            throw new SAXException(String.format("Element(%s) is not expected under extension!", qName));
        }

        tags.push(qName);
    }

    private void parseForExtensionDetail(ExtensionDetail parentObj, String parentTag, String qName, Attributes attributes) throws SAXException {
        objects.push(parentObj);
        tags.push(qName);
    }

    private void parseForGc(GcInfo parentObj, String parentTag, String qName, Attributes attributes) throws SAXException {
        objects.push(parentObj);
        tags.push(qName);
    }

    private void parseForMemory(MemoryInfo parentObj, String parentTag, String qName, Attributes attributes) throws SAXException {
        if (Constants.ENTITY_GC.equals(qName)) {
            GcInfo gc = maker.buildGc(attributes);

            linker.onGc(parentObj, gc);
            objects.push(gc);
        } else {
            throw new SAXException(String.format("Element(%s) is not expected under memory!", qName));
        }

        tags.push(qName);
    }

    private void parseForMessage(MessageInfo parentObj, String parentTag, String qName, Attributes attributes) throws SAXException {
        objects.push(parentObj);
        tags.push(qName);
    }

    private void parseForOs(OsInfo parentObj, String parentTag, String qName, Attributes attributes) throws SAXException {
        objects.push(parentObj);
        tags.push(qName);
    }

    private void parseForRuntime(RuntimeInfo parentObj, String parentTag, String qName, Attributes attributes) throws SAXException {
        if (Constants.ELEMENT_USER_DIR.equals(qName) || Constants.ELEMENT_JAVA_CLASSPATH.equals(qName)) {
            objects.push(parentObj);
        } else {
            throw new SAXException(String.format("Element(%s) is not expected under runtime!", qName));
        }

        tags.push(qName);
    }

    private void parseForStatus(StatusInfo parentObj, String parentTag, String qName, Attributes attributes) throws SAXException {
        if (Constants.ENTITY_RUNTIME.equals(qName)) {
            RuntimeInfo runtime = maker.buildRuntime(attributes);

            linker.onRuntime(parentObj, runtime);
            objects.push(runtime);
        } else if (Constants.ENTITY_OS.equals(qName)) {
            OsInfo os = maker.buildOs(attributes);

            linker.onOs(parentObj, os);
            objects.push(os);
        } else if (Constants.ENTITY_DISK.equals(qName)) {
            DiskInfo disk = maker.buildDisk(attributes);

            linker.onDisk(parentObj, disk);
            objects.push(disk);
        } else if (Constants.ENTITY_MEMORY.equals(qName)) {
            MemoryInfo memory = maker.buildMemory(attributes);

            linker.onMemory(parentObj, memory);
            objects.push(memory);
        } else if (Constants.ENTITY_THREAD.equals(qName)) {
            ThreadsInfo thread = maker.buildThread(attributes);

            linker.onThread(parentObj, thread);
            objects.push(thread);
        } else if (Constants.ENTITY_MESSAGE.equals(qName)) {
            MessageInfo message = maker.buildMessage(attributes);

            linker.onMessage(parentObj, message);
            objects.push(message);
        } else if (Constants.ENTITY_EXTENSION.equals(qName)) {
            Extension extension = maker.buildExtension(attributes);

            linker.onExtension(parentObj, extension);
            objects.push(extension);
        } else if (Constants.ENTITY_CUSTOMINFO.equals(qName)) {
            CustomInfo customInfo = maker.buildCustomInfo(attributes);

            linker.onCustomInfo(parentObj, customInfo);
            objects.push(customInfo);
        } else {
            throw new SAXException(String.format("Element(%s) is not expected under status!", qName));
        }

        tags.push(qName);
    }

    private void parseForThread(ThreadsInfo parentObj, String parentTag, String qName, Attributes attributes) throws SAXException {
        if (Constants.ELEMENT_DUMP.equals(qName)) {
            objects.push(parentObj);
        } else {
            throw new SAXException(String.format("Element(%s) is not expected under thread!", qName));
        }

        tags.push(qName);
    }

    private void parseRoot(String qName, Attributes attributes) throws SAXException {
        if (Constants.ENTITY_STATUS.equals(qName)) {
            StatusInfo status = maker.buildStatus(attributes);

            entity = status;
            objects.push(status);
            tags.push(qName);
        } else if (Constants.ENTITY_RUNTIME.equals(qName)) {
            RuntimeInfo runtime = maker.buildRuntime(attributes);

            entity = runtime;
            objects.push(runtime);
            tags.push(qName);
        } else if (Constants.ENTITY_OS.equals(qName)) {
            OsInfo os = maker.buildOs(attributes);

            entity = os;
            objects.push(os);
            tags.push(qName);
        } else if (Constants.ENTITY_MEMORY.equals(qName)) {
            MemoryInfo memory = maker.buildMemory(attributes);

            entity = memory;
            objects.push(memory);
            tags.push(qName);
        } else if (Constants.ENTITY_THREAD.equals(qName)) {
            ThreadsInfo thread = maker.buildThread(attributes);

            entity = thread;
            objects.push(thread);
            tags.push(qName);
        } else if (Constants.ENTITY_DISK.equals(qName)) {
            DiskInfo disk = maker.buildDisk(attributes);

            entity = disk;
            objects.push(disk);
            tags.push(qName);
        } else if (Constants.ENTITY_DISK_VOLUME.equals(qName)) {
            DiskVolumeInfo diskVolume = maker.buildDiskVolume(attributes);

            entity = diskVolume;
            objects.push(diskVolume);
            tags.push(qName);
        } else if (Constants.ENTITY_MESSAGE.equals(qName)) {
            MessageInfo message = maker.buildMessage(attributes);

            entity = message;
            objects.push(message);
            tags.push(qName);
        } else if (Constants.ENTITY_GC.equals(qName)) {
            GcInfo gc = maker.buildGc(attributes);

            entity = gc;
            objects.push(gc);
            tags.push(qName);
        } else if (Constants.ENTITY_EXTENSION.equals(qName)) {
            Extension extension = maker.buildExtension(attributes);

            entity = extension;
            objects.push(extension);
            tags.push(qName);
        } else if (Constants.ENTITY_EXTENSIONDETAIL.equals(qName)) {
            ExtensionDetail extensionDetail = maker.buildExtensionDetail(attributes);

            entity = extensionDetail;
            objects.push(extensionDetail);
            tags.push(qName);
        } else if (Constants.ENTITY_CUSTOMINFO.equals(qName)) {
            CustomInfo customInfo = maker.buildCustomInfo(attributes);

            entity = customInfo;
            objects.push(customInfo);
            tags.push(qName);
        } else {
            throw new SAXException("Unknown root element(" + qName + ") found!");
        }
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (uri == null || uri.length() == 0) {
            if (objects.isEmpty()) { // root
                parseRoot(qName, attributes);
            } else {
                Object parent = objects.peek();
                String tag = tags.peek();

                if (parent instanceof StatusInfo) {
                    parseForStatus((StatusInfo) parent, tag, qName, attributes);
                } else if (parent instanceof RuntimeInfo) {
                    parseForRuntime((RuntimeInfo) parent, tag, qName, attributes);
                } else if (parent instanceof OsInfo) {
                    parseForOs((OsInfo) parent, tag, qName, attributes);
                } else if (parent instanceof MemoryInfo) {
                    parseForMemory((MemoryInfo) parent, tag, qName, attributes);
                } else if (parent instanceof ThreadsInfo) {
                    parseForThread((ThreadsInfo) parent, tag, qName, attributes);
                } else if (parent instanceof DiskInfo) {
                    parseForDisk((DiskInfo) parent, tag, qName, attributes);
                } else if (parent instanceof DiskVolumeInfo) {
                    parseForDiskVolume((DiskVolumeInfo) parent, tag, qName, attributes);
                } else if (parent instanceof MessageInfo) {
                    parseForMessage((MessageInfo) parent, tag, qName, attributes);
                } else if (parent instanceof GcInfo) {
                    parseForGc((GcInfo) parent, tag, qName, attributes);
                } else if (parent instanceof Extension) {
                    parseForExtension((Extension) parent, tag, qName, attributes);
                } else if (parent instanceof ExtensionDetail) {
                    parseForExtensionDetail((ExtensionDetail) parent, tag, qName, attributes);
                } else if (parent instanceof CustomInfo) {
                    parseForCustomInfo((CustomInfo) parent, tag, qName, attributes);
                } else {
                    throw new RuntimeException(String.format("Unknown entity(%s) under %s!", qName, parent.getClass().getName()));
                }
            }

            text.setLength(0);
        } else {
            throw new SAXException(String.format("Namespace(%s) is not supported by %s.", uri, this.getClass().getName()));
        }
    }

    protected java.util.Date toDate(String str, String format) {
        try {
            return new java.text.SimpleDateFormat(format).parse(str);
        } catch (java.text.ParseException e) {
            throw new RuntimeException(String.format("Unable to parse date(%s) in format(%s)!", str, format), e);
        }
    }
}


text:
namespace GafferSceneUIBindings
{

/// This doesn't actually bind SceneHierarchy, because that is implemented
/// in Python at present. Instead, it binds C++ support classes and functions
/// that the SceneHierarchy uses internally.
void bindSceneHierarchy();

} // namespace GafferUIBindings

#endif // GAFFERSCENEUIBINDINGS_SCENEHIERARCHYBINDING_H


text:
package io.apiman.test.integration.ui.support.selenide;

import com.paulhammant.ngwebdriver.NgWebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.events.WebDriverEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author jkaspar
 */
public class ApimanEventListener implements WebDriverEventListener {

    private static final Logger LOG = LoggerFactory.getLogger(ApimanEventListener.class);

    @Override
    public void beforeNavigateTo(String url, WebDriver driver) {

    }

    @Override
    public void afterNavigateTo(String url, WebDriver driver) {

    }

    @Override
    public void beforeNavigateBack(WebDriver driver) {

    }

    @Override
    public void afterNavigateBack(WebDriver driver) {

    }

    @Override
    public void beforeNavigateForward(WebDriver driver) {

    }

    @Override
    public void afterNavigateForward(WebDriver driver) {

    }

    @Override
    public void beforeFindBy(By by, WebElement element, WebDriver driver) {

    }

    @Override
    public void afterFindBy(By by, WebElement element, WebDriver driver) {

    }

    @Override
    public void beforeClickOn(WebElement element, WebDriver driver) {
        LOG.debug("Wait before clicking on element '" + element.getTagName() + "' with text '" + element.getText()
            + "' on page: " + driver.getCurrentUrl());
        try {
            new NgWebDriver((JavascriptExecutor) driver).waitForAngularRequestsToFinish();
        } catch (TimeoutException exception) {
            LOG.debug("WaitForAngular timed out: " + exception.getMessage());
        }
    }

    @Override
    public void afterClickOn(WebElement element, WebDriver driver) {

    }

    @Override
    public void beforeChangeValueOf(WebElement element, WebDriver driver) {

    }

    @Override
    public void afterChangeValueOf(WebElement element, WebDriver driver) {

    }

    @Override
    public void beforeScript(String script, WebDriver driver) {

    }

    @Override
    public void afterScript(String script, WebDriver driver) {

    }

    @Override
    public void onException(Throwable throwable, WebDriver driver) {

    }
}


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

import {Component, OnInit} from '@angular/core';
import * as moment from 'moment';

import {LoaderView} from '../../../../../shared/components/loader';
import {ConfigService} from '../../../../../shared/config';
import {Device} from '../../../../../shared/models/device';
import {FailAction, FailType, Failure} from '../../shared/failure';
import {Loan} from '../../shared/loan';
import {ReturnDateService} from '../../shared/return_date_service';

@Component({
  host: {'class': 'mat-typography'},
  selector: 'return',
  styleUrls: ['./return.scss'],
  templateUrl: './return.ng.html',
})
export class ReturnComponent extends LoaderView implements OnInit {
  device = new Device();
  newReturnDate?: Date;
  toBeSubmitted = true;
  validDate = true;
  webAppUrl: string;

  constructor(
      private readonly config: ConfigService, private failure: Failure,
      private loan: Loan, private returnService: ReturnDateService) {
    super(true);
    this.webAppUrl = this.config.webAppUrl;
  }

  ngOnInit() {
    this.loan.getDevice().subscribe(
        device => {
          this.device = device;
          this.newReturnDate = this.getMinimumReturnDate();
          this.initializeDateServiceVariables(device);
          this.ready();
        },
        error => {
          this.ready();
          const message = `We had some trouble getting your loan information.`;
          this.failure.register(
              message, FailType.Network, FailAction.Quit, error);
        });

    this.returnService.validDate.subscribe(validDate => {
      this.validDate = validDate;
    });
  }

  private initializeDateServiceVariables(device: Device) {
    this.returnService.updateDueDate(device.dueDate);
    this.returnService.updateNewReturnDate(device.dueDate)
        .subscribe(newReturnDate => {
          if (this.newReturnDate instanceof Date) {
            this.newReturnDate = newReturnDate!;
          }
        });
    this.returnService.updateMaxReturnDate(device.maxExtendDate);

    // Do validation checks on changes.
    this.returnService.validationChecks().subscribe(val => {
      this.validDate = val;
      this.returnService.updateValidDate(val);
    });
  }

  /** Gets the minimum return date. */
  getMinimumReturnDate(): Date {
    const today = moment().set({
      hour: 0,
      minute: 0,
      second: 0,
    });

    return moment(today).add(1, 'd').toDate();
  }

  /**
   * Prevents non 0-9 and / characters from being used in the date field.
   * @param event The DOM event to be tracked on key presses.
   */
  validateField(event: KeyboardEvent): boolean {
    const pattern = /[0-9\/]/;
    const inputCharacters = String.fromCharCode(event.charCode);

    return pattern.test(inputCharacters);
  }
}


text:
__all__ = [
    'model',
    'controller',
    'rest',
    'Client'
]

from yubiauth.client.controller import Client


text:
module Elastics
  # never instantiate this class directly: it is automatically done by the scoped method
  class Scope < Vars

    class Error < StandardError; end

    include FilterMethods
    include VarsMethods
    include QueryMethods

    SCOPED_METHODS = FilterMethods.instance_methods + VarsMethods.instance_methods + QueryMethods.instance_methods

    def inspect
      "#<#{self.class.name} #{self}>"
    end

    def respond_to?(meth, private=false)
      super || is_template?(meth) || is_context_scope?(meth) || is_self_scope?(meth)
    end

    def method_missing(meth, *args, &block)
      super unless respond_to?(meth)
      case
      when is_context_scope?(meth)
        deep_merge self[:context].send(meth, *args, &block)
      when is_self_scope?(meth)
        deep_merge self[:self_context].send(meth, *args, &block)
      when is_template?(meth)
        self[:context].send(meth, deep_merge(*args), &block)
      end
    end

    private

    def is_template?(name)
      self[:context].respond_to?(:template_methods) && self[:context].template_methods.include?(name.to_sym)
    end

    def is_context_scope?(name)
      self[:context].respond_to?(:scope_methods) && self[:context].scope_methods.include?(name.to_sym)
    end

    # only used for AR scopes, when you namespace the scope module
    def is_self_scope?(name)
      self[:self_context].respond_to?(:scope_methods) && self[:self_context].scope_methods.include?(name.to_sym)
    end

  end
end