text:
package org.grizzlytech.protoxml.xml;

import org.grizzlytech.protoxml.beans.Bean;
import org.grizzlytech.protoxml.beans.BeanTest;
import org.grizzlytech.protoxml.builder.BeanBuilder;
import org.grizzlytech.protoxml.builder.readers.NVPStringReader;
import org.grizzlytech.protoxml.main.ProtoAPI;
import org.grizzlytech.protoxml.util.AssertUtil;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.assertTrue;

public class XMLMarshallerTest {

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

    @Test
    public void employeeToXML() throws Exception {
        Bean bean = (new BeanTest()).createEmployeeBean();
        String[] assertions = new String[]{"city>new york", "<nse:localNumber>999"};
        toXML(bean, assertions);
    }

    @Test
    public void zooToXML() throws Exception {
        Bean bean = (new BeanTest()).createZooBean();
        String[] assertions = new String[]{"mascot xsi:type=\"nsz:penguin\"", "<nsz:length>20"};
        toXML(bean, assertions);
    }

    @Test
    public void companyToXML() throws Exception {
        Bean bean = (new BeanTest()).createCompanyBean();
        String[] assertions = new String[]{"http://www.grizzlytech.org/testdomain/company", "<nse:name>Fred"};
        toXML(bean, assertions);
    }

    private void toXML(Bean bean, String[] assertions) throws Exception {

        ProtoAPI api = new ProtoAPI();
        api.getConfig().usePrefixMapper(true);

        StringWriter xmlWriter = new StringWriter();
        api.createXML(bean, xmlWriter);
        String xmlText = xmlWriter.toString();

        LOG.info(xmlText);
        AssertUtil.assertContains(LOG, xmlText, assertions);

        // Validate
        Class elementClass = bean.unwrap().getClass();
        ElementList elementList = api.getElementList(elementClass);
        URL schemaURL = api.getSchemaURL(elementClass);
        assertTrue(elementList != null && schemaURL != null);
        StringReader xmlReader = new StringReader(xmlText);
        StringWriter valWriter = new StringWriter();
        api.validate(xmlReader, schemaURL, elementList.getResourceResolver(), valWriter);
        LOG.info("Validate: {}", valWriter.toString());
    }

    @Test
    public void toXMLWithComments() throws Exception {
        Bean bean = (new BeanTest()).createEmployeeBean();

        // Add a comment
        bean.setPathComment("address.city#", "home city");
        bean.setPathComment("phones[0]#", "mobile");

        // Generate XML
        ProtoAPI api = new ProtoAPI();
        api.getConfig().usePrefixMapper(true);

        StringWriter xmlWriter = new StringWriter();
        api.createXML(bean, xmlWriter);
        String xmlText = xmlWriter.toString();

        LOG.info("{}", xmlText);
        // Remove all whitespace to make assertion easier
        xmlText = AssertUtil.removeWhitespace(xmlText);

        AssertUtil.assertContains(LOG, xmlText,
                new String[]{"<!--homecity-->"}
        );
    }

    @Test
    public void toXMLWithCommentsComplexCases() throws Exception {
        NVPStringReader reader = new NVPStringReader();

        List<String> mappings = new ArrayList<>();
        mappings.add("doctype=testdomain.music.Library");
        mappings.add("name=top albums");
        mappings.add("format[0]&=testdomain.music.ObjectFactory#createCD");
        mappings.add("format[0]$=testdomain.music.Album");
        mappings.add("format[0].value.artist#=we like foo");
        mappings.add("format[0].value.artist=foo");
        mappings.add("format[0].value.albumTitle=bar");
        mappings.add("format[1]&=testdomain.music.ObjectFactory#createDigital");
        mappings.add("format[1]$=testdomain.music.DigitalAlbum");
        mappings.add("format[1].value.artist=c64");
        mappings.add("format[1].value.albumTitle=commando");
        mappings.add("format[1].value.bitRate=320");
        mappings.add("format[1].value.bitRate#=nice");
        mappings.add("format[2]&=testdomain.music.ObjectFactory#createCD");
        mappings.add("format[2]$=testdomain.music.Album");
        //TODO: currently the comment get mapped to the first CD, not the second
        mappings.add("format[2].value.artist#=excellent");
        mappings.add("format[2].value.artist=baz");
        mappings.add("format[2].value.albumTitle=the man");

        reader.setMappings(mappings);

        StringWriter traceWriter = new StringWriter();

        BeanBuilder builder = new BeanBuilder();
        Bean bean = builder.createBean(reader, traceWriter);
        String traceText = traceWriter.toString();

        LOG.info(traceText);

        // Generate XML
        ProtoAPI api = new ProtoAPI();
        api.getConfig().usePrefixMapper(false);

        StringWriter xmlWriter = new StringWriter();
        api.createXML(bean, xmlWriter);
        String xmlText = xmlWriter.toString();

        LOG.info("{}", xmlText);
    }
}


text:
package com.siyeh.ipp.switchtoif;

import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiUtil;
import com.siyeh.ipp.psiutils.EquivalenceChecker;
import com.siyeh.ipp.psiutils.SideEffectChecker;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NonNls;

import java.util.ArrayList;
import java.util.List;

class CaseUtil{

    private CaseUtil(){
        super();
    }

    private static boolean canBeCaseLabel(PsiExpression expression){
        if(expression == null){
            return false;
        }
        if(expression instanceof PsiReferenceExpression){
            final PsiElement referent = ((PsiReference) expression).resolve();
            if(referent instanceof PsiEnumConstant){
                return true;
            }
        }
        final PsiType type = expression.getType();
        if(type == null){
            return false;
        }
        if(!type.equals(PsiType.INT) &&
                !type.equals(PsiType.CHAR) &&
                !type.equals(PsiType.LONG) &&
                !type.equals(PsiType.SHORT)){
            return false;
        }
        return PsiUtil.isConstantExpression(expression);
    }

    public static boolean containsHiddenBreak(PsiStatement statement){
        return containsHiddenBreak(statement, true);
    }

    private static boolean containsHiddenBreak(PsiStatement statement,
                                               boolean isTopLevel){
        if(statement instanceof PsiBlockStatement){
            final PsiCodeBlock codeBlock =
                    ((PsiBlockStatement) statement).getCodeBlock();
            final PsiStatement[] statements = codeBlock.getStatements();
            for(final PsiStatement childStatement : statements){
                if(containsHiddenBreak(childStatement, false)){
                    return true;
                }
            }
        } else if(statement instanceof PsiIfStatement){
            final PsiIfStatement ifStatement = (PsiIfStatement) statement;
            final PsiStatement thenBranch = ifStatement.getThenBranch();
            final PsiStatement elseBranch = ifStatement.getElseBranch();
            return containsHiddenBreak(thenBranch, false) ||
                    containsHiddenBreak(elseBranch, false);
        } else if(statement instanceof PsiBreakStatement){
            if(isTopLevel){
                return false;
            }
            final PsiIdentifier identifier =
                    ((PsiBreakStatement) statement).getLabelIdentifier();
            if(identifier == null){
                return true;
            }
            final String text = identifier.getText();
            return "".equals(text);
        }
        return false;
    }

    public static boolean isUsedByStatementList(PsiLocalVariable variable,
                                                List<PsiElement> elements){
        for(PsiElement element : elements){
            if(isUsedByStatement(variable, element)){
                return true;
            }
        }
        return false;
    }

    private static boolean isUsedByStatement(PsiLocalVariable variable,
                                             PsiElement statement){
        final LocalVariableUsageVisitor visitor =
                new LocalVariableUsageVisitor(variable);
        statement.accept(visitor);
        return visitor.isUsed();
    }

    public static String findUniqueLabel(PsiStatement statement,
                                         @NonNls String baseName){
        PsiElement ancestor = statement;
        while(ancestor.getParent() != null){
            if(ancestor instanceof PsiMethod
                    || ancestor instanceof PsiClass
                    || ancestor instanceof PsiFile){
                break;
            }
            ancestor = ancestor.getParent();
        }
        if(!checkForLabel(baseName, ancestor)){
            return baseName;
        }
        int val = 1;
        while(true){
            final String name = baseName + val;
            if(!checkForLabel(name, ancestor)){
                return name;
            }
            val++;
        }
    }

    private static boolean checkForLabel(String name, PsiElement ancestor){
        final LabelSearchVisitor visitor = new LabelSearchVisitor(name);
        ancestor.accept(visitor);
        return visitor.isUsed();
    }

    @Nullable
    public static PsiExpression getCaseExpression(PsiIfStatement statement){
        final PsiExpression condition = statement.getCondition();
        final List<PsiExpression> possibleCaseExpressions =
                determinePossibleCaseExpressions(condition);
        if(possibleCaseExpressions == null){
            return null;
        }
        for(Object possibleCaseExpression : possibleCaseExpressions){
            final PsiExpression caseExpression =
                    (PsiExpression) possibleCaseExpression;
            if(!SideEffectChecker.mayHaveSideEffects(caseExpression)){
                PsiIfStatement statementToCheck = statement;
                while(true){
                    final PsiExpression caseCondition =
                            statementToCheck.getCondition();
                    if(canBeMadeIntoCase(caseCondition, caseExpression)){
                        final PsiStatement elseBranch =
                                statementToCheck.getElseBranch();
                        if(elseBranch == null ||
                                !(elseBranch instanceof PsiIfStatement)){
                            return caseExpression;
                        }
                        statementToCheck = (PsiIfStatement) elseBranch;
                    } else{
                        break;
                    }
                }
            }
        }
        return null;
    }

    private static List<PsiExpression> determinePossibleCaseExpressions(
            PsiExpression expression){
        PsiExpression expressionToCheck = expression;
        while(expressionToCheck instanceof PsiParenthesizedExpression){
            final PsiParenthesizedExpression parenthesizedExpression =
                    (PsiParenthesizedExpression)expressionToCheck;
            expressionToCheck = parenthesizedExpression.getExpression();
        }
        final List<PsiExpression> out=new ArrayList<PsiExpression>(10);
        if(!(expressionToCheck instanceof PsiBinaryExpression)){
            return out;
        }
        final PsiBinaryExpression binaryExpression =
                (PsiBinaryExpression) expressionToCheck;
        final PsiJavaToken sign = binaryExpression.getOperationSign();
        final IElementType operation = sign.getTokenType();
        final PsiExpression lhs = binaryExpression.getLOperand();
        final PsiExpression rhs = binaryExpression.getROperand();
        if(operation.equals(JavaTokenType.OROR)){
            return determinePossibleCaseExpressions(lhs);
        } else if(operation.equals(JavaTokenType.EQEQ)){
            if(canBeCaseLabel(lhs)){
                out.add(rhs);
            }
            if(canBeCaseLabel(rhs)){
                out.add(lhs);
            }
        }
        return out;
    }

    private static boolean canBeMadeIntoCase(PsiExpression expression,
                                             PsiExpression caseExpression){
        PsiExpression expressionToCheck = expression;
        while(expressionToCheck instanceof PsiParenthesizedExpression){
            final PsiParenthesizedExpression parenthesizedExpression =
                    (PsiParenthesizedExpression)expressionToCheck;
            expressionToCheck = parenthesizedExpression.getExpression();
        }
        if(!(expressionToCheck instanceof PsiBinaryExpression)){
            return false;
        }
        final PsiBinaryExpression binaryExpression =
                (PsiBinaryExpression) expressionToCheck;
        final PsiJavaToken sign = binaryExpression.getOperationSign();
        final IElementType operation = sign.getTokenType();
        final PsiExpression lOperand = binaryExpression.getLOperand();
        final PsiExpression rhs = binaryExpression.getROperand();
        if(operation.equals(JavaTokenType.OROR)){
            return canBeMadeIntoCase(lOperand, caseExpression) &&
                    canBeMadeIntoCase(rhs, caseExpression);
        } else if(operation.equals(JavaTokenType.EQEQ)){
            if(canBeCaseLabel(lOperand) &&
                    EquivalenceChecker.expressionsAreEquivalent(caseExpression,
                                                                rhs)){
                return true;
            } else if(canBeCaseLabel(rhs) &&
                    EquivalenceChecker.expressionsAreEquivalent(caseExpression,
                                                                lOperand)){
                return true;
            }
            return false;
        } else{
            return false;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace XeCore
{
    namespace Intuicio
    {
        using namespace XeCore::Common;
        using namespace XeCore::Common::Concurrent;

        class ThreadVM;
        class ProgramVM;

        class ParallelThreadVM
			: public virtual IRtti
			, public virtual MemoryManager::Manageable
			, public Thread
        {
            friend class ContextVM;

            RTTI_CLASS_DECLARE( ParallelThreadVM );

        public:
                                            ParallelThreadVM( ThreadVM* owner, ProgramVM* prog, ParallelThreadVM* parent = 0, unsigned int parallelIdx = 0, unsigned int parallelsCount = 1 );
            virtual                         ~ParallelThreadVM();

            void                            pushFragment( unsigned int begin, unsigned int end, unsigned int startAddress );
            void                            stop();
            virtual void                    run();
            bool                            runWithin( unsigned int startAddress );
            virtual void                    onComplete();
            void                            waitForChildren();
            FORCEINLINE bool                isWaiting() { SYNCHRONIZED_OBJECT( m_childrenSync ); return !m_children.empty(); };
            FORCEINLINE unsigned int        getParallelIdx() { return m_parallelIdx; };
            FORCEINLINE unsigned int        getParallelsCount() { return m_parallelsCount; };

        protected:
            void                            addChild( ParallelThreadVM* child );
            void                            removeChild( ParallelThreadVM* child );

        private:
            struct ProgramFragment
            {
                unsigned int                begin;
                unsigned int                end;
                unsigned int                start;
            };

            struct StackPosition
            {
                unsigned int                last;
                unsigned int                address;
            };

            ThreadVM*                       m_owner;
            unsigned int                    m_parallelIdx;
            unsigned int                    m_parallelsCount;
            ParallelThreadVM*               m_parent;
            ProgramVM*                      m_program;
            List< ProgramFragment >         m_fragments;
            int*                            m_regI;
            float*                          m_regF;
            unsigned int                    m_regIcount;
            unsigned int                    m_regFcount;
            byte*                           m_stack;
            unsigned int                    m_stackSize;
            unsigned int                    m_stackPos;
            List< StackPosition >           m_stackFrames;
            volatile bool                   m_running;
            Synchronized                    m_sync;
            Synchronized                    m_waitSync;
            Synchronized::Condition         m_waitCond;
            Synchronized                    m_childrenSync;
            Vector< ParallelThreadVM* >     m_children;
        };
    }
}

#endif


text:
#ifndef PHOENIX_STATEMENT_DETAIL_CATCH_COMPOSITE_HPP
#define PHOENIX_STATEMENT_DETAIL_CATCH_COMPOSITE_HPP

#include <boost/spirit/home/phoenix/core/actor.hpp>
#include <boost/spirit/home/phoenix/core/composite.hpp>
#include <boost/spirit/home/phoenix/core/compose.hpp>

namespace boost { namespace phoenix {
namespace detail
{
    struct catch_composite_eval
    {
        template<typename Env, typename Actor>
        struct result :
            eval_result<typename Actor::eval_type, Env> {};

        template<typename Rt, typename Env, typename Actor>
        static typename result<Env,Actor>::type
        eval(const Env& env, Actor& actor)
        {
            return actor.eval(env);
        }
    };

    template<typename Exception, typename Actor>
    struct catch_composite :
        composite<catch_composite_eval, fusion::vector<Actor> >
    {
        catch_composite(const Actor& actor)
            : composite<catch_composite_eval, fusion::vector<Actor> >(actor) { }

        typedef Exception exception_type;
    };

    template<typename Exception, typename Actor>
    struct as_catch_actor
    {
        typedef catch_composite<
            Exception,
            Actor> comp;

        typedef actor<comp> type;
    };

    template<typename Exception, typename Actor>
    inline typename as_catch_actor<Exception, Actor>::type
    catch_actor(const Actor& actor)
    {
        return catch_composite<Exception,Actor>(actor);
    }
}
}}

#endif


text:
@interface RootViewController ()

@property (nonatomic, copy) NSArray *dataSource;

@end

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];

    self.dataSource = @[@{@"title" : @"基础样式 + 多层嵌套", @"class" : @"MultilTabController"},
                        @{@"title" : @"可滚动,tabItem宽度适配标题,指示器宽度固定", @"class" : @"DynamicItemWidthTabController"},
                        @{@"title" : @"可滚动,tabItem固定宽度,指示器宽度适配title", @"class" : @"FixedItemWidthTabController"},
                        @{@"title" : @"不可滚动,指示器宽度适配title", @"class" : @"IndicatorFollowTitleTabController"},
                        @{@"title" : @"指示器样式自定义", @"class" : @"CustomIndicatorTabController"},
                        @{@"title" : @"仿系统segment", @"class" : @"SegmentTabController"},
                        @{@"title" : @"可伸缩的HeaderView", @"class" : @"HeaderViewTabController"},
                        @{@"title" : @"竖向tabBar", @"class" : @"VerticalTabController"}];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];

    cell.textLabel.text = self.dataSource[indexPath.row][@"title"];
    cell.textLabel.font = [UIFont systemFontOfSize:15];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *className = self.dataSource[indexPath.row][@"class"];
    if (className.length == 0) {
        return;
    }
    Class cls = NSClassFromString(className);
    [self.navigationController pushViewController:[[cls alloc] init] animated:YES];
}

@end


text:
import angular from 'angular';
import NodeActions from '_redux/actions/node-actions';
import nodeSelectorTpl from './nodeSelector.html';

const NodeSelectorComponent = {
    templateUrl: nodeSelectorTpl,
    controller: 'NodeSelectorController',
    bindings: {
        selected: '<',
        position: '<',
        onSelect: '&',
        onClose: '&'
    }
};

class NodeSelectorController {
    constructor(
        $rootScope, $log, $element, $scope, $timeout, $document, $ngRedux
    ) {
        'ngInject';
        $rootScope.autoInject(this, arguments);
    }

    mapStateToThis(state) {
        const nodes = state.lab.nodes;

        let nodeArray = nodes ?
            nodes.toArray().filter((node) => {
                return node.type !== 'const';
            }).map(({id, metadata}) => ({id, label: metadata.label})) :
            [];
        this.updateSelected(nodes, this.selected.id ? this.selected.id : this.selected);

        return {
            nodes,
            nodeArray
        };
    }

    $onInit() {
        let unsubscribe = this.$ngRedux.connect(
            this.mapStateToThis.bind(this),
            NodeActions
        )(this);
        this.$scope.$on('$destroy', unsubscribe);
    }

    $postLink() {
        this.$timeout(() => {
            if (this.position) {
                this.setPosition(this.position);
            }
        }, 0);
    }

    $onChanges(changes) {
        if (changes.position && changes.position.currentValue) {
            this.setPosition(changes.position.currentValue);
        }
        if (changes.selected && changes.selected.currentValue) {
            let selected = changes.selected.currentValue;
            this.updateSelected(this.nodes, selected.id ? selected.id : selected);
            this.$scope.$evalAsync();
            if (this.position) {
                this.$scope.$evalAsync(() => {
                    this.setPosition(this.position);
                });
            }
        }
    }

    updateSelected(nodes, selected) {
        if (nodes && selected) {
            const selectedNode = nodes.get(selected);
            this.selectedLabel = selectedNode.metadata.label;
            if (selectedNode.type) {
                this.selectedType = selectedNode.type;
            } else if (selectedNode.apply) {
                this.selectedType = 'function';
            }
        } else {
            delete this.selectedType;
            delete this.selectedLabel;
        }
    }

    setPosition(position) {
        let width = this.$element[0].offsetWidth;
        let percent = position.x * 100;
        let offset;
        if (position.side === 'left') {
            offset = width + position.offset;
        } else if (position.side === 'right' || position.side === 'none') {
            offset = position.offset;
        } else {
            throw new Error(`${position.side} is not a valid side to display a node selector on`);
        }
        let left = `calc(${percent}% ${position.side === 'left' ? '-' : '+'} ${offset}px)`;
        this.$element.css({
            left: left
        });
    }

    startSelecting() {
        let initialClick = true;
        const onClick = () => {
            if (!initialClick) {
                this.showSearch = false;
                this.$document.off('click', this.clickListener);
                this.setPosition(this.position);
                this.$scope.$evalAsync();
            } else {
                initialClick = false;
            }
        };

        if (!this.showSearch) {
            this.showSearch = true;
            this.clickListener = onClick;
            this.$document.on('click', onClick);
            this.$timeout(() => {
                this.setPosition(this.position);
                this.$element.find('.node-filter').focus();
            }, 100);
        } else {
            this.showSearch = false;
            this.setPosition(this.position);
            this.$document.off('click', this.clickListener);
            delete this.clickListener;
        }
    }

    onNodeSelect(node) {
        this.selected = node.id;
        this.onSelect({node: node.id});
        this.showSearch = false;
        this.selectFilter = '';
        this.$timeout(() => this.setPosition(this.position), 100);
    }
}
const NodeSelectorModule = angular.module('components.map.nodeSelector', []);

NodeSelectorModule.component('rfNodeSelector', NodeSelectorComponent);
NodeSelectorModule.controller('NodeSelectorController', NodeSelectorController);

export default NodeSelectorModule;


text:
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2015 the original author or authors.
//
// This library 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 2.1 of the License, or (at your option) any later version.
//
// This library 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 this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
////////////////////////////////////////////////////////////////////////////////

package com.puppycrawl.tools.checkstyle.api;

import com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocNodeImpl;

/**
 *
 * DetailNode is used to construct tree during parsing Javadoc comments.
 * Contains array of children, parent node and other useful fields.
 *
 * @author Baratali Izmailov
 * @see JavadocNodeImpl
 * @see com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck
 */
public interface DetailNode {
    /**
     * Node type.
     * @return node type.
     * @see JavadocTokenTypes
     */
    int getType();

    /**
     * Node text.
     * @return node text
     */
    String getText();

    /**
     * Node line number.
     * @return node line number
     */
    int getLineNumber();

    /**
     * Node column number.
     * @return node column number.
     */
    int getColumnNumber();

    /**
     * Array of children.
     * @return array of children
     */
    DetailNode[] getChildren();

    /**
     * Parent node.
     * @return parent node.
     */
    DetailNode getParent();

    /**
     * Node index among parent's children.
     * @return index
     */
    int getIndex();
}


text:
'use strict';

var Platform = require('Platform');
var crc32 = require('crc32');

export type Notification = {
  id: string;
  url: ?string;
  text: string;
  time: number;
};

export type SeenNotifications = {
  [id: string]: boolean;
};

type State = {
  enabled: ?boolean; // null = no answer
  registered: boolean;

  // Most notifications will be stored on Parse Core, so that
  // people who installed the app after the conference started can
  // get access. But some notifications will be delivered
  // via push and only to subset of attendees.
  server: Array<Notification>;
  push: Array<Notification>;

  seen: SeenNotifications;
};

const initialState = {
  server: [],
  push: [],
  enabled: Platform.OS === 'ios' ? null : true,
  registered: false,
  seen: {},
};

import type {Action} from '../actions/types';

function notifications(state: State = initialState, action: Action): State {
  switch (action.type) {
    case 'LOADED_NOTIFICATIONS':
      let list = action.list.map(fromParseObject);
      return {...state, server: list};

    case 'RECEIVED_PUSH_NOTIFICATION':
      return {...state, push: append(action.notification, state.push)};

    case 'LOGGED_OUT':
      return {...state, push: []};

    case 'TURNED_ON_PUSH_NOTIFICATIONS':
      return {...state, enabled: true};

    case 'SKIPPED_PUSH_NOTIFICATIONS':
      return {...state, enabled: false};

    case 'REGISTERED_PUSH_NOTIFICATIONS':
      return {...state, registered: true};

    case 'RESET_NUXES':
      return {...state, enabled: initialState.enabled};

    case 'SEEN_ALL_NOTIFICATIONS':
      return {...state, seen: fetchAllIds([...state.server, ...state.push])};

    default:
      return state;
  }
}

function append(notification, list) {
  const id = notification.id || crc32(notification.text + notification.url).toString(36);
  if (list.find((n) => n.id === id)) {
    return list;
  }
  return [{id, ...notification}, ...list];
}

function fetchAllIds(notifs: Array<Notification>): SeenNotifications {
  const seen = {};
  notifs.forEach((notification) => {
    seen[notification.id] = true;
  });
  return seen;
}

function fromParseObject(object: Object): Notification {
  return {
    id: object.id,
    text: object.get('text'),
    url: object.get('url'),
    time: object.createdAt.getTime(),
  };
}

module.exports = notifications;


text:
import logging

logger = logging.getLogger(__name__)

def outputUserMessage(errMsg, fixMsg=None):
    logger.info(f"\n\n****************************Usage Error************************\n" + errMsg)
    if fixMsg:
        logger.info(f"\n\n**************************How to fix***********************\n" + fixMsg)
    logger.info(f"\n\n****************************Call Stack*************************")

def invalidInputError(condition, errMsg, fixMsg=None):
    if not condition:
        outputUserMessage(errMsg, fixMsg)
        raise RuntimeError(errMsg)

def invalidOperationError(condition, errMsg, fixMsg=None, cause=None):
    if not condition:
        outputUserMessage(errMsg, fixMsg)
        if cause:
            raise cause
        else:
            raise RuntimeError(errMsg)


text:
NUcore is an old project and has passed through many hands. There are long controller methods, complex view logic, and odd routing. It began as a Rails 2.X project and pieces of that legacy remain. Many of the things that you may consider as bad may have even been considered best practices at the time. Give the past developers some credit. Future you may have similar things to say about what you're doing right now.

Times have changed, styles and best practices have evolved, and we want to keep the codebase healthy. That means cleaning things up and refactoring as needed. We can't fix everything at once, but we can make things better one little piece at a time.

If you see a nasty or incomprehensible method, see if you can refactor it to make it more understandable. If you're trying to make a change and it's hard, [refactor to make the change easy](https://twitter.com/kentbeck/status/250733358307500032).

But do consider the value vs effort. If it's a bug fix where you have `>` instead of `>=`, it might not be worth spending four hours refactoring. But if you're working within a nasty method and you know there's constant churn on that class, it's likely worth it.

The golden rule: **when working on a piece of code, _leave it nicer than when you found it_**.

Here are some general guidelines:

## Pull Requests

**Do not commit to master!**

All changes should go through a Pull Request and be reviewed prior to merging.

## Bug fixes

If you're tracking down a bug, write a test for it. Even if you fix the bug first, undo your change, write a failing test, and then re-do your change to make it pass.

## Use locales

Views should use locales/I18n whenever possible. This facilitates easy overriding
in downstream forks. We've begun moving locales into separate files, in general
one per controller/view set. This is still a work in progress, but see `config/locales` for examples.

Fork-specific overrides should be put in `config/locales/override/en.yml`. We've
made sure this is the last file to be loaded, so it always takes precedence. Nothing
should be in that file in nucore-open except the locales that we use to verify this
behavior in specs.

We use the [text-helpers](https://github.com/ahorner/text-helpers) gem for view
and controller locales. Use the standard [Rails I18n](http://guides.rubyonrails.org/i18n.html) for model names, attributes, and error messages.

* Prefer `Model.model_name.human` and `Model.human_attribute_name` over view-specific locales
* Prefer text-helper's `text` method over `I18n.t`
* When including references to "facility" and "facilities", within a longer string,
  use text-helper's interpolation features with `facility_downcase`/`facilities_downcase`
  e.g. `text("in this !facility_downcase!"). _We haven't found a better way to do this yet_

## Rubocop

We have rubocop set up with a set of style guidelines. When you're working in a file,
try to abide the guidelines (e.g. prefer double over single quotes, use 1.9-style
hash syntax, etc). Please run `rubocop` on the files you're touching, and preferably only
on the files you're touching.

It's difficult to see a salient change amidst a lot of stylistic updates, so if you
run rubocop or do another large stylistic update, give it a separate commit, or even
its own PR if the changes are significant enough.

Views are not Rubocopped, nor are Rails-specific cops inside of engines, so try to
follow the same style guidelines.

* Use Ruby 1.9 hash syntax

  ```ruby
  :key => value # Bad
  key: value # Good
  ```

* Prefer double-quotes to single-quotes
* Prefer `before_action` to `before_filter`
* Prefer `find_by(key: value)` over dynamic finders (`find_by_key(value)`)

## Fork-specific changes

Some features such as authentication or financial system integration may be specific to
a particular instance of NUcore. These kinds of features should be developed within their
respective downstream forks. When developing these kinds of features, it is important to
avoid making changes to application code (primarily `/app` and `/lib`) that also exists in
the open-source fork. Otherwise, there is a high likelyhood of merge conflict if anything
changes upstream.

The best method is to isolate your feature inside of an engine in `vendor/engines`. When
necessary, create a hook point where you need it within the open-source branch and hook
into that with your engine. Try to avoid overriding entire views (as happens in
the `c2po` engine). Then a change to the default view might need to happen in
multiple places. See the following section for more information.

* A factory configured in settings (e.g. `AccountValidator::ValidatorFactory`, `StatementPdfFactory`
* Adding a module onto an existing class in the engine initializer (see `vendor/engines/c2po/lib/c2po.rb`)
* Other things we haven't thought of

## Extending views within engines

When necessary, you can add to a view from your engine with minimal change to the
main application's view.

`render_view_hook("useful_identifier", local_variables)`

`"useful_identifier"` should be relevant to where it exists in the view. E.g.
`after_end_of_form`.

To insert a partial into this hook, within your engine's `to_prepare` block, add

```ruby
config.to_prepare do
  ViewHook.add_hook("partial_name", "useful_identifier", "your_engine/partial")
end
```

`partial_name` - The name of the partial where `render_view_hook` lives. It should use dots, and will be the same as the locale scope for the view. E.g. if you call `render_view_hook` in `reservations/_account_field.html.haml`, the `partial_name` will be `reservations.account_field`

`your_engine/partial` - The name of the partial you wish to include, located within your engine.

[`vendor/engines/projects/lib/projects/engine.rb`](vendor/engines/projects/lib/projects/engine.rb) has plenty of examples, as well
as examples of other ways to hook into the app from an engine.

## Gemfiles

There will necessarily be differences between the `Gemfile`s of different instances (the
included engines, database, etc.). Do your best to keep the common gems in Gemfiles are in
the same order. This will help prevent merge conflicts in `Gemfile`. Unfortunately, merge
conflicts within `Gemfile.lock` are likely inevitable.

Most gems are kept up to date by merging in changes from `nucore-open`, where dependabot is enabled. If your instance requires gem dependencies that are not included in `nucore-open`, you may want to enable dependabot for them by adding or modifying `.github/dependabot.yml`:

```
version: 2
updates:
- package-ecosystem: bundler
  directory: "/"
  schedule:
    interval: daily
    time: "23:00"
    timezone: America/Chicago
  open-pull-requests-limit: 99
  allow:
  - dependency-name: aws-sdk-rails
  - dependency-name: aws-sdk-s3

```

If you are building an engine that depends on an additional gem, add that dependency to the
engine's `gemspec`, not app's `Gemfile`.

_We should consider `optional` groups in Bundler 1.10 to see if this helps_

## Commits

Good commit messages vastly improve the history of the project. Tools like `git log`,
`git blame`, and `git bisect` are much easier to use when each commit is a discrete
piece of work. Each commit to master should result in a green build.

When merging Pull Requests, we prefer to use Github's "Squash and Merge" green button.
This allows the history of `master` to be one commit per feature or bug fix. It
also keeps commits from long-running PRs to be included in the history in chronological
order of when they were merged, not when they were written.

Use [Chris Beam's guidelines](https://chris.beams.io/posts/git-commit/) as a template
for your commits.

Prefix your pull requests with the ticket number. `[#12345] Fix critical issue`.
This is an open source project, so many people will not have access to the discussion
of the ticket, so include an explanation of the feature or bug fix in the pull
request body.

## Other

### Put application code where it belongs
There is quite a bit of code inside of `/lib` that is actually application code. Many of the
classes/modules are actually service objects or model concerns. Move them to the appropriate
place inside of `/app`.

We have an `app/support` directory that probably would be more at home in `app/services` or `app/models/concerns`. Move them to where they belong. This has led to an odd `spec` folder structure where `spec/support` is for testing support, and `spec/app_support` holds the tests for `app/support`.

Don't worry too much about moving code you're not actively working with. But when you do work on
something that seems to be in the wrong place, please fix it!

### Don't use DCI
There are a few places where we are using [DCI](http://www.sitepoint.com/dci-the-evolution-of-the-object-oriented-paradigm) such as `PriceDisplayment`. Do not use this technique going forward. Prefer decorators/presenters. Consider [`SimpleDelegator`](http://ruby-doc.org/stdlib/libdoc/delegate/rdoc/SimpleDelegator.html) or [`DelegateClass`](http://ruby-doc.org/stdlib/libdoc/delegate/rdoc/Object.html); we have chosen not to use something
more magical like Draper.

### Documentation
If a class is not immediately obvious what its purpose is, add comments to the top of the
class explaining its purpose and its use.

### Skinny Models, Controllers, and Views
You'll see lots of long controller methods or complex logic in the views. Don't contribute to the problem. If you need to touch one of these, start by refactoring out a service object or presenter. Additionally, try to avoid adding additional business logic onto the models. `OrderDetail` is already [large enough](https://en.wikipedia.org/wiki/God_object)!

### Roles
Prefer `Ability` checks (`can? :read, @order_detail)` over Role checks in views and controllers (e.g. `User#manager_of?(facility)`).

## Once again, leave things better than you found them.

And remember, break any of these rules sooner than do anything outright barbarous.


text:
<?php

if (!empty($_POST)) {
	// ensure post params are valid
	if(empty($_POST['chat_id']) || empty($_POST['timespan']))
		response_error("Error: Invalid post params!");

	$chat_id = $_POST['chat_id'];
	$timespan = $_POST['timespan'];

	$query = "	SELECT message, datetime, from_user_id, state
				FROM messages
				WHERE 	chat_id = :chat_id AND
						DATE_SUB(CURDATE(), INTERVAL :timespan DAY) <= datetime";

}

?>

<form action="index.php?view=get_messages" method="post">
	<input type="text" name="chat_id" placeholder="chat_id">
	<input type="text" name="timespan" placeholder="timespan (number of days)">
	<input type="submit" value="Get messages">
</form>


text:
package com.ebonheart.EbonArtsMod.common.items.resources;

import java.util.List;

import com.ebonheart.EbonArtsMod.EbonArtsMod;
import com.ebonheart.EbonArtsMod.common.items.ItemHelper;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class ItemVelious extends Item {

	public ItemVelious()
	{
		ItemHelper.setItemName(this, "gem/velious");
	}

	@SideOnly(Side.CLIENT)
    public void addInformation(ItemStack stack, EntityPlayer playerIn, List toolTip, boolean advanced)
	{
		toolTip.add(TextFormatting.GOLD + "A subtle chill emanates from");
		toolTip.add(TextFormatting.GOLD + "the core of this crystal.");
	}

	public EnumRarity getRarity(ItemStack stack)
    {
        return EnumRarity.UNCOMMON;
    }

}


text:
#pragma once

#include <inviwo/core/common/inviwocoredefine.h>
#include <inviwo/core/network/processornetwork.h>

namespace inviwo {

class Processor;

/**
 * \brief Utility class to calculate and apply auto linking
 */
class IVW_CORE_API AutoLinker {
public:
    /**
     * Construct an auto link helper
     * @param network the processor network in which to add autolinks
     * @param target the processor onto which auto links should be added
     * @param source source of links. If source is not null we consider all predecessors of source
     * as input for linking, if source is null we consider all processor in the network
     */
    AutoLinker(ProcessorNetwork* network, Processor* target, Processor* source = nullptr);
    virtual ~AutoLinker() = default;

    const std::unordered_map<Property*, std::vector<Property*>>& getAutoLinkCandidates() const;

    void sortAutoLinkCandidates();
    void sortAutoLinkCandidates(dvec2 pos);

    void addLinksToClosestCandidates(bool bidirectional);

    static void addLinks(ProcessorNetwork* network, Processor* target, Processor* source = nullptr);

private:
    ProcessorNetwork* network_;
    Processor* target_;
    std::unordered_map<Property*, std::vector<Property*>> autoLinkCandiates_;
};

}  // namespace inviwo


text:
package slamdata.engine.std

import slamdata.Predef._

import org.specs2.mutable._
import org.specs2.scalaz._
import org.specs2.ScalaCheck

import slamdata.engine._

class StructuralSpecs extends Specification with ScalaCheck with ValidationMatchers {
  import slamdata.engine.Type._

  import StructuralLib._

  import DataGen._
  import TypeGen._

  "ConcatOp" should {
    // NB: the func's domain is the type assigned to any argument if nothing
    // else is known about it.
    val unknown = AnyArray | Str

    "type combination of arbitrary strs as str" ! (arbStrType, arbStrType) { (st1: Type, st2: Type) =>
      ConcatOp(st1, st2).map(Str contains _) must beSuccessful(true)
      ConcatOp(st2, st1).map(Str contains _) must beSuccessful(true)
    }

    "type arbitrary str || unknown as Str" ! arbStrType { (st: Type) =>
      ConcatOp(st, unknown) must beSuccessful(Str)
      ConcatOp(unknown, st) must beSuccessful(Str)
    }

    "fold constant Strings" ! prop { (s1: String, s2: String) =>
      ConcatOp(Const(Data.Str(s1)), Const(Data.Str(s2))) must
        beSuccessful(Const(Data.Str(s1 + s2)))
    }

    "type combination of arbitrary arrays as array" ! (arbArrayType, arbArrayType) { (at1: Type, at2: Type) =>
      ConcatOp(at1, at2).map(_.arrayLike) must beSuccessful(true)
      ConcatOp(at2, at1).map(_.arrayLike) must beSuccessful(true)
    }

    "type arbitrary array || unknown as array" ! arbArrayType { (at: Type) =>
      ConcatOp(at, unknown).map(_.arrayLike) must beSuccessful(true)
      ConcatOp(unknown, at).map(_.arrayLike) must beSuccessful(true)
    }

    "fold constant arrays" ! prop { (ds1: List[Data], ds2: List[Data]) =>
      ConcatOp(Const(Data.Arr(ds1)), Const(Data.Arr(ds2))) must
        beSuccessful(Const(Data.Arr(ds1 ++ ds2)))
    }

    "fail with mixed Str and array args" ! (arbStrType, arbArrayType) { (st: Type, at: Type) =>
      ConcatOp(st, at) must beFailing
      ConcatOp(at, st) must beFailing
    }

    "propagate unknown types" in {
      ConcatOp(unknown, unknown) must beSuccessful(unknown)
    }

    import org.scalacheck.Gen, Gen._
    import org.scalacheck.Arbitrary, Arbitrary._
    lazy val arbStrType = Arbitrary(Gen.oneOf(
      const(Str),
      arbitrary[String].map(s => Const(Data.Str(s)))))

    lazy val arbArrayType = Arbitrary(simpleArrayGen)
    lazy val simpleArrayGen = Gen.oneOf(
      for {
        i <- arbitrary[Int]
        n <- arbitrary[Option[Int]]
        t <- arbitrary[Type]
      } yield FlexArr(i.abs, n.map(i.abs max _.abs), t),
      for {
        t <- arbitrary[List[Type]]
      } yield Arr(t),
      for {
        ds <- resize(5, arbitrary[List[Data]])
      } yield Const(Data.Arr(ds)))
  }
}


text:
title: "Contributing"
permalink: /docs/contributing/
excerpt: "How you can contribute to make this theme better."
last_modified_at: 2017-03-22T09:51:05-04:00
---

Having trouble working with the theme? Found a typo in the documentation? Interested in adding a feature or [fixing a bug](https://github.com/mmistakes/minimal-mistakes/issues)? Then by all means [submit an issue](https://github.com/mmistakes/minimal-mistakes/issues/new) or [pull request](https://help.github.com/articles/using-pull-requests/). If this is your first pull request, it may be helpful to read up on the [GitHub Flow](https://guides.github.com/introduction/flow/) first.

Minimal Mistakes has been designed as a base for you to customize and fit your site's unique needs. Please keep this in mind when requesting features and/or submitting pull requests. If it's not something that most people will use, I probably won't consider it. When in doubt ask.

This goes for author sidebar links and "share button" additions -- I have no intention of merging in every possibly option, the essentials are there to get you started :smile:.

## Pull requests

When submitting a pull request:

1. Clone the repo.
2. Create a branch off of `master` and give it a meaningful name (e.g. `my-awesome-new-feature`) and describe the feature or fix.
3. Open a pull request on GitHub.

Theme documentation and demo pages can be found in the [`/docs`](https://github.com/{{ site.repository }}/blob/master/docs) folder if you'd like to tackle any "low-hanging fruit" like fixing typos, bad grammar, etc.


text:
package ca.ualberta.cs.swapmyride;

import android.test.ActivityInstrumentationTestCase2;

import ca.ualberta.cs.swapmyride.Misc.VehicleCategory;
import ca.ualberta.cs.swapmyride.Misc.VehicleQuality;
import ca.ualberta.cs.swapmyride.Model.InventoryList;
import ca.ualberta.cs.swapmyride.Model.Vehicle;
import ca.ualberta.cs.swapmyride.View.MainMenu;

/**
 * Created by Garry on 2015-10-08.
 */
public class InventoryTest extends ActivityInstrumentationTestCase2 {
    public InventoryTest() {
        super(MainMenu.class);
    }

    // Use Case 1: Add Vehicle
    public void testAddItem() {
        InventoryList inventoryList = new InventoryList();
        Vehicle vehicle = new Vehicle();
        //list should be empty
        assertTrue(inventoryList.getList().isEmpty());
        inventoryList.add(vehicle);
        //make sure an vehicle was added
        assertTrue(inventoryList.size() == 1);
        //make sure it is the correct vehicle
        assertTrue(inventoryList.getList().get(0) == vehicle);
    }

    // Use Case 2: Browse Inventory
    public void testBrowseInventory() {
        InventoryList inventoryList = new InventoryList();
        Vehicle vehicle = new Vehicle();
        //list should be empty
        assertTrue(inventoryList.getList().size() == 0);
        inventoryList.add(vehicle);
        //check there is an vehicle in the list
        assertFalse(inventoryList.getList().size() == 0);
        //check the vehicle is the vehicle we put into the list
        assertTrue(inventoryList.getList().get(0) == vehicle);
    }

    // Use Case 3: View Vehicle
    public void testViewItem() {
        Vehicle vehicle = new Vehicle();
        //vehicle.setPhoto(picture);
        vehicle.setName("Cadillac");
        vehicle.setCategory(VehicleCategory.COUPE);
        vehicle.setQuality(VehicleQuality.GOOD);
        vehicle.setQuantity(1);
        vehicle.setComments("1995 Cadillac");

        //assertTrue(vehicle.getPhoto().equals(photo));
        assertTrue(vehicle.getName().equals("Cadillac"));
        assertTrue(vehicle.getCategory().equals(VehicleCategory.COUPE));
        assertTrue(vehicle.getQuality().equals(VehicleQuality.GOOD));
        assertTrue(vehicle.getQuantity().equals(1));
        assertTrue(vehicle.getComments().equals("1995 Cadillac"));
    }

    // Use Case 4: Set Public
    public void testSetPublic() {
        InventoryList inventoryList = new InventoryList();
        Vehicle vehicle = new Vehicle();
        vehicle.setPublic(false);
        inventoryList.add(vehicle);
        //check the vehicle does not appear in the public return
        assertTrue(inventoryList.getPublic().size() == 0);
        //check the vehicle does appear in the private list
        assertTrue(inventoryList.getPrivate().size() == 1);
    }

    // Use Case 5: Modify Items
    public void testModifyItems() {
        Vehicle vehicle = new Vehicle();
        vehicle.setName("Vehicle");
        assertTrue(vehicle.getName().equals("Vehicle"));
        vehicle.setName("Car");
        assertTrue(vehicle.getName().equals("Car"));
    }

    // Use Case 6: Delete Vehicle
    public void testDeleteItem() {
        InventoryList inventoryList = new InventoryList();
        Vehicle vehicle = new Vehicle();
        Vehicle newVehicle = new Vehicle();
        //list should be empty
        assertTrue(inventoryList.getList().size() == 0);
        inventoryList.add(vehicle);
        inventoryList.add(newVehicle);
        //check there is an vehicle in the list
        assertFalse(inventoryList.getList().size() == 0);
        inventoryList.delete(newVehicle);
        //check the size is correct
        assertTrue(inventoryList.getList().size() == 1);
        //check the vehicle left is the correct vehicle
        assertTrue(inventoryList.getList().contains(vehicle));
    }

    // Use Case 7: Minimum Navigation
    // No related test case as evaluation is not concrete

}


text:
from __future__ import print_function

from helpers import unittest

from luigi.mock import MockTarget, MockFileSystem

class MockFileTest(unittest.TestCase):

    def test_1(self):
        t = MockTarget('test')
        p = t.open('w')
        print('test', file=p)
        p.close()

        q = t.open('r')
        self.assertEqual(list(q), ['test\n'])
        q.close()

    def test_with(self):
        t = MockTarget("foo")
        with t.open('w') as b:
            b.write("bar")

        with t.open('r') as b:
            self.assertEqual(list(b), ['bar'])

    # That should work in python2 because of the autocast
    # That should work in python3 because the default format is Text
    def test_unicode(self):
        t = MockTarget("foo")
        with t.open('w') as b:
            b.write(u"bar")

        with t.open('r') as b:
            self.assertEqual(b.read(), u'bar')

class MockFileSystemTest(unittest.TestCase):
    fs = MockFileSystem()

    def _touch(self, path):
        t = MockTarget(path)
        with t.open('w'):
            pass

    def setUp(self):
        self.fs.clear()
        self.path = "/tmp/foo"
        self.path2 = "/tmp/bar"
        self._touch(self.path)
        self._touch(self.path2)

    def test_exists(self):
        self.assertTrue(self.fs.exists(self.path))

    def test_remove(self):
        self.fs.remove(self.path)
        self.assertFalse(self.fs.exists(self.path))

    def test_remove_recursive(self):
        self.fs.remove("/tmp", recursive=True)
        self.assertFalse(self.fs.exists(self.path))
        self.assertFalse(self.fs.exists(self.path2))

    def test_listdir(self):
        self.assertEqual(sorted([self.path, self.path2]), sorted(self.fs.listdir("/tmp")))

class TestImportMockFile(unittest.TestCase):

    def test_mockfile(self):
        from luigi.mock import MockFile
        self.assertTrue(isinstance(MockFile('foo'), MockTarget))


text:
#ifndef itkStandardDeviationProjectionImageFilter_h
#define itkStandardDeviationProjectionImageFilter_h

#include "itkProjectionImageFilter.h"
#include "itkConceptChecking.h"

namespace itk
{
/** \class StandardDeviationProjectionImageFilter
 * \brief Mean projection
 *
 * This class was contributed to the Insight Journal by Gaetan Lehmann.
 * The original paper can be found at
 *   http://hdl.handle.net/1926/164
 *
 * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction,
 * INRA de Jouy-en-Josas, France.
 *
 * \sa ProjectionImageFilter
 * \sa MedianProjectionImageFilter
 * \sa MeanProjectionImageFilter
 * \sa SumProjectionImageFilter
 * \sa MeanProjectionImageFilter
 * \sa MaximumProjectionImageFilter
 * \sa MinimumProjectionImageFilter
 * \sa BinaryProjectionImageFilter
 * \ingroup ITKImageStatistics
 */

namespace Functor
{
template< typename TInputPixel, typename TAccumulate >
class StandardDeviationAccumulator
{
public:
  typedef typename NumericTraits< TInputPixel >::RealType RealType;

  StandardDeviationAccumulator( SizeValueType size )
  {
    m_Size = size;
    m_Values.reserve(size);
  }

  ~StandardDeviationAccumulator(){}

  inline void Initialize()
  {
    m_Sum = NumericTraits< TAccumulate >::ZeroValue();
    m_Values.clear();
  }

  inline void operator()(const TInputPixel & input)
  {
    m_Sum = m_Sum + input;
    m_Values.push_back(input);
  }

  inline RealType GetValue()
  {
    // to avoid division by zero
    if ( m_Size <= 1 )
      {
      return NumericTraits< RealType >::ZeroValue();
      }

    typename NumericTraits< TInputPixel >::RealType mean =
      ( (RealType)m_Sum ) / m_Size;
    typename std::vector< TInputPixel >::iterator it;
    RealType squaredSum = NumericTraits< RealType >::ZeroValue();
    for ( it = m_Values.begin(); it != m_Values.end(); it++ )
      {
      squaredSum += vnl_math_sqr(*it - mean);
      }
    return std::sqrt( squaredSum / ( m_Size - 1 ) );
  }

  TAccumulate                m_Sum;
  SizeValueType              m_Size;
  std::vector< TInputPixel > m_Values;
};
} // end namespace Function

template< typename TInputImage,
          typename TOutputImage,
          typename TAccumulate = typename
                              NumericTraits< typename TOutputImage::PixelType >
                              ::AccumulateType >
class StandardDeviationProjectionImageFilter:
  public
  ProjectionImageFilter< TInputImage, TOutputImage,
                         Functor::StandardDeviationAccumulator< typename
                                                                TInputImage::PixelType, TAccumulate > >
{
public:
  typedef StandardDeviationProjectionImageFilter Self;

  typedef ProjectionImageFilter< TInputImage, TOutputImage,
                                 Functor::StandardDeviationAccumulator< typename
                                                                        TInputImage::PixelType,
                                                                        TAccumulate > > Superclass;

  typedef TInputImage                        InputImageType;
  typedef typename InputImageType::PixelType InputPixelType;

  typedef SmartPointer< Self >       Pointer;
  typedef SmartPointer< const Self > ConstPointer;

  /** Runtime information support. */
  itkTypeMacro(StandardDeviationProjectionImageFilter, ProjectionImageFilter);

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

#ifdef ITK_USE_CONCEPT_CHECKING
  // Begin concept checking
  itkConceptMacro( InputPixelToOutputPixelTypeGreaterAdditiveOperatorCheck,
                   ( Concept::AdditiveOperators< TAccumulate,
                                                 InputPixelType,
                                                 TAccumulate > ) );
  itkConceptMacro( InputHasNumericTraitsCheck,
                   ( Concept::HasNumericTraits< InputPixelType > ) );

  itkConceptMacro( AccumulateHasNumericTraitsCheck,
                   ( Concept::HasNumericTraits< TAccumulate > ) );

  // End concept checking
#endif

protected:
  StandardDeviationProjectionImageFilter() {}
  virtual ~StandardDeviationProjectionImageFilter() {}

private:
  //purposely not implemented
  StandardDeviationProjectionImageFilter(const Self &);

  void operator=(const Self &); //purposely not implemented
};                              // end StandardDeviationProjectionImageFilter
} //end namespace itk

#endif


text:
/*  ___ _  ___ _ _                                                            *\
** / __| |/ (_) | |       The SKilL Generator                                 **
** \__ \ ' <| | | |__     (c) 2013 University of Stuttgart                    **
** |___/_|\_\_|_|____|    see LICENSE                                         **
\*                                                                            */
package de.ust.skill.generator.scala

import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

/**
 * @author Timm Felden
 */
@RunWith(classOf[JUnitRunner])
class GeneratorTest extends FunSuite {

  def check(src : String, out : String) {
    Main.main(Array[String]("-u", "<<some developer>>", "-h2", "<<debug>>", "-p", out, "src/test/resources/scala/"+src, "testsuites/scala/src/main/scala/"))
  }

  test("number")(check("number.skill", "number"))
  test("fields")(check("fields.skill", "fields"))
  test("cycle")(check("cycle.skill", "cycle"))
  test("derivation")(check("derivation.skill", "derivation"))
  test("fixed size array")(check("fixedArray.skill", "containers.array.fixed"))
  test("variable size array")(check("variableArray.skill", "containers.array.variable"))
  test("list")(check("list.skill", "containers.list"))
  test("set")(check("set.skill", "containers.set"))
  test("map")(check("map.skill", "containers.map"))
  //test("benchmark: colored graph")(check("benchmarks.coloredGraph.skill", "benchmarks.coloredGraph"))
  //test("benchmark: graph")(check("benchmarks.graph.skill", "benchmarks.graph"))

  test("annotation")(check("annotation.skill", "annotation"))
  //test("blocks")(check("blocks.skill", "block"))
  test("container")(check("container.skill", "container"))
  test("date")(check("date.skill", "date"))
  test("graph")(check("graph.skill", "graph"))
  test("float")(check("float.skill", "floatTest"))
  test("unicode")(check("unicode.skill", "unicode"))

  test("restrictions: range")(check("restrictions.range.skill", "restrictions.range"))
  test("restrictions: singleton")(check("restrictions.singleton.skill", "restrictions.singleton"))

  test("hints: ignore")(check("hintIgnore.skill", "hints.ignore"))

  test("node")(check("node.skill", "node"))
  test("subtypes")(check("subtypesExample.skill", "subtypes"))
  //test("subtypesUnknown")(check("subtypesUnknown.skill", "unknown"))
  //test("datedMessage")(check("datedMessage.skill", "datedMessage"))

  /**
   * generate code for a more complex example that makes use of a set of tools to modify very simple nodes.
   * these tools enrich nodes with custom fields.
   * the related tests should also serve as a demonstration on the boundaries of format-change.
   */
  test("node tool chain example") {
    check("nodeExample.tool1.skill", "toolchains.node.tool1")
    check("nodeExample.tool2.skill", "toolchains.node.tool2")
    check("nodeExample.tool3.skill", "toolchains.node.tool3")
    check("nodeExample.viewer.skill", "toolchains.node.viewer")
  }

  //test("check _root_ bug")(
  //  assert(intercept[AssertionError] {
  //    Main.main(Array[String]("-u", "<<some developer>>", "-h2", "<<debug>>", "src/test/resources/scala/date.skill", "testsuites/scala/src/main/scala/"))
  //  }.getMessage === "assertion failed: You have to specify a non-empty package name!")
  //)
}


text:
from functools import wraps
import logging
from google.appengine.api import users
from flask import current_app
from flaskext.login import current_user

def staff_required(fn):
    @wraps(fn)
    def decorated_view(*args, **kwargs):
        u = current_user
        logging.debug("User: %s" % u)
        if u.is_authenticated() and u.is_active() and (u.is_staff or users.is_current_user_admin()):
            return fn(*args, **kwargs)
        return current_app.login_manager.unauthorized()
    return decorated_view

def sysop_required(fn):
    @wraps(fn)
    def decorated_view(*args, **kwargs):
        logging.debug("Sysop required: %s %s" % (users.get_current_user(), users.is_current_user_admin()))
        if users.is_current_user_admin():
            return fn(*args, **kwargs)
        return current_app.login_manager.unauthorized()
    return decorated_view


text:
<?php

declare(strict_types=1);

return $params['bar'];


text:
package com.khartec.waltz.common;

import org.junit.Test;

import static com.khartec.waltz.common.StringUtilities.firstChar;
import static com.khartec.waltz.common.StringUtilities.mkPath;
import static org.junit.Assert.assertEquals;

public class StringUtilities_mkPath {

    @Test
    public void mkPathWithNoSegmentsReturnsEmptyString() {
        assertEquals("", mkPath());
    }

    @Test
    public void mkPathWithSegmentsReturnsSlashDelimitedConcatenation() {
        assertEquals("hello/world", mkPath("hello", "world"));
    }

    @Test
    public void mkPathWithNonStringSegmentsReturnsToStringEquivalent() {
        assertEquals("hello/23/world", mkPath("hello", 23, "world"));
    }

    @Test
    public void mkPathWithOneSegmentsReturnsBasicString() {
        assertEquals("test", mkPath("test"));
    }

    @Test
    public void mkPathWithEmbeddedSegmentsPreservesSlashes() {
        assertEquals("test/one", mkPath("test/one"));
    }

    @Test
    public void mkPathWithEmbeddedSegmentsReducesSlashes() {
        assertEquals("test/one", mkPath("test///one"));
    }

    @Test(expected = IllegalArgumentException.class)
    public void mkPathWithNullSegmentsIsNotAllowed() {
        assertEquals("test", mkPath("test", null));
    }

    @Test(expected = IllegalArgumentException.class)
    public void mkPathWithEmptySegmentsIsNotAllowed() {
        assertEquals("test", mkPath("test", ""));
    }

}


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

import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.mongodb.Mongo;
import org.apache.camel.Endpoint;
import org.apache.camel.impl.UriEndpointComponent;
import org.apache.camel.util.CamelContextHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Represents the component that manages {@link MongoDbEndpoint}.
 */
public class MongoDbComponent extends UriEndpointComponent {

    public static final Set<MongoDbOperation> WRITE_OPERATIONS =
            new HashSet<MongoDbOperation>(Arrays.asList(MongoDbOperation.insert, MongoDbOperation.save,
                    MongoDbOperation.update, MongoDbOperation.remove));
    private static final Logger LOG = LoggerFactory.getLogger(MongoDbComponent.class);
    private volatile Mongo db;

    public MongoDbComponent() {
        super(MongoDbEndpoint.class);
    }

    /**
     * Should access a singleton of type Mongo
     */
    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
        // TODO: this only supports one mongodb
        if (db == null) {
            db = CamelContextHelper.mandatoryLookup(getCamelContext(), remaining, Mongo.class);
            LOG.debug("Resolved the connection with the name {} as {}", remaining, db);
        }

        MongoDbEndpoint endpoint = new MongoDbEndpoint(uri, this);
        endpoint.setConnectionBean(remaining);
        endpoint.setMongoConnection(db);
        setProperties(endpoint, parameters);

        return endpoint;
    }

    @Override
    protected void doShutdown() throws Exception {
        if (db != null) {
            // properly close the underlying physical connection to MongoDB
            LOG.debug("Closing the connection {} on {}", db, this);
            db.close();
        }

        super.doShutdown();
    }

    public static CamelMongoDbException wrapInCamelMongoDbException(Throwable t) {
        if (t instanceof CamelMongoDbException) {
            return (CamelMongoDbException) t;
        } else {
            return new CamelMongoDbException(t);
        }
    }

}


text:
namespace System.Collections.Generic
{
    using Fx;

    /// <summary>
    /// Factory methods for the <see cref="ReadOnlyDictionary{TKey, TValue}"/>
    /// </summary>
    /// <threadsafety static="true"/>
    public static class ReadOnlyDictionary
    {
        /// <summary>
        /// Creates a new instance of <see cref="ReadOnlyDictionary{TKey, TValue}"/> from <paramref name="source"/>
        /// </summary>
        /// <typeparam name="TKey">The type of the keys in <paramref name="source"/></typeparam>
        /// <typeparam name="TValue">The type of the values in <paramref name="source"/></typeparam>
        /// <param name="source">The <see cref="IDictionary{TKey, TValue}"/> to create a <see cref="ReadOnlyDictionary{TKey, TValue}"/> of</param>
        /// <returns>A new instance of <see cref="ReadOnlyDictionary{TKey, TValue}"/> based on <paramref name="source"/></returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="source"/> is null</exception>
        public static ReadOnlyDictionary<TKey, TValue> Create<TKey, TValue>(IDictionary<TKey, TValue> source)
        {
            Ensure.NotNull(source, nameof(source));

            return new ReadOnlyDictionary<TKey, TValue>(source);
        }
    }
}


text:
package typeutil

import (
	"strconv"

	gh "github.com/dustin/go-humanize"
	"github.com/juju/errors"
)

// ByteSize is a retype uint64 for TOML and JSON.
type ByteSize uint64

// MarshalJSON returns the size as a JSON string.
func (b ByteSize) MarshalJSON() ([]byte, error) {
	return []byte(`"` + gh.Bytes(uint64(b)) + `"`), nil
}

// UnmarshalJSON parses a JSON string into the bytesize.
func (b *ByteSize) UnmarshalJSON(text []byte) error {
	s, err := strconv.Unquote(string(text))
	if err != nil {
		return errors.Trace(err)
	}
	v, err := gh.ParseBytes(s)
	if err != nil {
		return errors.Trace(err)
	}
	*b = ByteSize(v)
	return nil
}

// UnmarshalText parses a Toml string into the bytesize.
func (b *ByteSize) UnmarshalText(text []byte) error {
	v, err := gh.ParseBytes(string(text))
	if err != nil {
		return errors.Trace(err)
	}
	*b = ByteSize(v)
	return nil
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    tools:context=".MainActivity" >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/user" />

    <TextView
        android:id="@+id/tv_list_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_horizontal"
        android:text="@string/hello_world" />

    <ImageView
        android:id="@+id/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/delete" />

</LinearLayout>


text:
var gulp = require('gulp'),
  sass = require('gulp-sass'),
  clean = require('gulp-clean'),
  concat = require('gulp-concat'),
  livereload = require('gulp-livereload'),
  embedlr = require('gulp-embedlr'),
  connect = require('connect');

gulp.task('clean', function(){
  return gulp.src(['build/*'], {read:false})
    .pipe(clean());
});

gulp.task('styles', function() {
  gulp.src('./src/scss/style.scss')
    .pipe(sass({
      outputStyle: 'compressed'
    }))
    .pipe(gulp.dest('./build/css'));
});

gulp.task('images', function() {
  gulp.src('./src/images/**/*.*')
    .pipe(gulp.dest('./build/images'));

  gulp.src('./src/favicon.ico')
    .pipe(gulp.dest('./build'));
});

gulp.task('fonts', function() {
  gulp.src('./src/fonts/**/*.*')
    .pipe(gulp.dest('./build/fonts'));
});

gulp.task('javascripts', function() {
  gulp.src(['./src/javascripts/jquery-1.11.0.min.js', './src/javascripts/bootstrap.min.js', './src/javascripts/app.js'])
    .pipe(concat('main.js'))
    .pipe(gulp.dest('./build/javascripts'));
});

gulp.task('templates', function() {
  gulp.src('./src/*.html')

    // Embed livereload snippet
    .pipe(embedlr())

    .pipe(gulp.dest('./build'));
});

gulp.task('default', ['clean'], function() {
  gulp.start('styles', 'javascripts', 'images', 'fonts', 'templates');
});

gulp.task('watch', ['default', 'server'], function() {
  gulp.watch('./src/scss/**/*.scss', ['styles']);
  gulp.watch('./src/javascripts/**/*.*', ['javascripts']);
  gulp.watch('./src/images/**/*.*', ['images']);
  gulp.watch('./src/fonts/**/*.*', ['fonts']);
  gulp.watch('./src/*.html', ['templates']);

  var server = livereload();
  gulp.watch('build/**').on('change', function(file) {
    server.changed(file.path);
  });
});

gulp.task('server', function(next) {
    var fs = require('fs'),
        path = require('path'),
        cons = require('consolidate'),
        Handlebars = require('handlebars'),
        express = require('express'),
        app = express(),
        port = process.env.PORT || 8000;

    // set app views
    app.engine('html', cons.handlebars);
    app.set('view engine', 'html');

    // set app public directory & views
    app.use(express.static(path.join(__dirname,'/build')));
    app.set('views', path.join(__dirname,'/src'));

    // Register partials
    var partials = path.join(__dirname,"/src/partials/");
    fs.readdirSync(partials).forEach(function (file) {
        var source = fs.readFileSync(path.join(partials, file), "utf8"),
            partial = /(.+)\.html/.exec(file).pop();
        Handlebars.registerPartial(partial, source);
    });

    // Register helpers
    var helpers = {
        "foreach": function(arr,options) {
            if(typeof arr==='string') {
                return options.fn(arr);
            }
            if(options.inverse && (!arr || !arr.length)) {
                return options.inverse(this);
            } else if(!arr) {
                return '';
            }
            return arr.map(function(item,index) {
                item.$index = index;
                item.$first = index === 0;
                item.$last  = index === arr.length-1;
                return options.fn(item);
            }).join('');
        },
        "propertyListClassFromStatus": function(status) {
            return status==="on the market" ? "onMarket" : (status==="under offer" ? "underOffer" : "propertyLet");
        },
        // from https://github.com/assemble/handlebars-helpers/blob/master/lib/helpers/helpers-strings.js
        "lowercase": function(str) {
            if(str && typeof str === "string") {
                return str.toLowerCase();
            }
        },
        // from https://github.com/assemble/handlebars-helpers/blob/master/lib/helpers/helpers-comparisons.js
        "is": function (value, test, options) {
            if (value === test) {
                return options.fn(this);
            } else {
                return options.inverse(this);
            }
        },
        // from https://github.com/assemble/handlebars-helpers/blob/master/lib/helpers/helpers-comparisons.js
        "or": function (a, b, options) {
            if (a || b) {
                return options.fn(this);
            } else {
                return options.inverse(this);
            }
        },
        // from https://github.com/assemble/handlebars-helpers/blob/master/lib/helpers/helpers-math.js
        "add": function (value, addition) {
            return value + addition;
        },
        "formatDate": function(datetime, formatString) {
            // mutate the date into London timezone and then format it
            return moment(datetime).tz('Europe/London').format(formatString);
        }
    };

    for (var helper in helpers) {
        if (helpers.hasOwnProperty(helper)) {
            Handlebars.registerHelper(helper, helpers[helper]);
        }
    }

    app.get('/pattern-book', function(req, res) {
        fs.readFile('./src/pattern-book-data.json', function(err, data) {
            try {
                data = JSON.parse(data);
                res.render('pattern-book', data);
            } catch(ex) {
                console.log(ex);
                res.send('uh-oh! error parsing the JSON file, check your console');
            }
        });
    });
    app.listen(process.env.PORT || 8000, next);
    console.log('listening on '+port+', why not visit /pattern-book');
});


text:
#ifndef _OWI_BB_H_
#define _OWI_BB_H_

/*!
 * \file dev/owibus_uartif.c
 * \brief Header for the One-Wire API bitbang Implementation
 *
 * \verbatim
 * $Id: owibus_bbif.h 4424 2012-08-17 12:12:06Z haraldkipp $
 * \endverbatim
 */

/*!
 * \brief Array of delay values for the different command phases.
 */
#include <stdint.h>
#include <sys/types.h>

/*!
 * \addtogroup xgOwibusBb
 */
/*@{*/

extern const uint16_t owi_timervalues_250ns[OWI_MODE_NONE][OWI_CMD_NONE][OWI_PHASE_NONE];

/*!
 * \brief OWI runtime controlblock container.
 *
 * This is installed in heap at initialization.
 */
struct _NUTOWIINFO_BB {
    int txrx_port;
    int txrx_pin;
    int pp_port;
    int pp_pin;
};

typedef struct _NUTOWIINFO_BB NUTOWIINFO_BB;

int NutRegisterOwiBus_BB(NUTOWIBUS *bus, int tx_port, uint_fast8_t tx_pin, int pullup_port, uint_fast8_t pullup_pin);

/*@}*/

#endif


text:
<?php

include_once '../../config.php';
include_once 'includes/header.php';

use LearnositySdk\Request\Init;
use LearnositySdk\Utils\Uuid;

$security = array(
    'consumer_key' => $consumer_key,
    'domain'       => $domain
);

$request = array(
    'activity_template_id' => 'demo-activity-1',
    'activity_id'          => 'my-demo-activity',
    'name'                 => 'Demo Activity',
    'session_id'           => Uuid::generate(),
    'user_id'              => $studentid,
    'assess_inline'        => true,
    'config'               => array(
        'administration' => array(
            'pwd' => '5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8' // `password`
        ),
        'questions_api_init_options' => [
            'beta_flags' => [
                'reactive_views' => true
            ]
        ]
    )
);

include_once 'utils/settings-override.php';

$Init = new Init('items', $security, $consumer_secret, $request);
$signedRequest = $Init->generate();

?>

Items API – Activities

Activities are a wrapper for multiple items authored in the Learnosity Author site. They can also
        include configuration used by the <a href="<?php echo $env['www'] ?>assessment/assess/index.php">Assess API to control the assessment user interface.

Preview the API Initialisation Object to see how simple it can be using the Items API to load activities
        authored in the Learnosity item bank.

Customise the activity you want to load.

Type ctrl+shift+m to open the Administration Panel. The default password is password.

<?php
    include_once 'views/modals/settings-items-activities.php';
    include_once 'views/modals/initialisation-preview.php';
    include_once 'includes/footer.php';


text:
module Language.Hakaru.RoundTrip
  ( ()(..), (,)(..), Either(..), Bool(..), Int, Num(..)
  , Fractional(..), Floating(..), ($), Any(Any), (^^)
  , module Language.Hakaru.Syntax
  , module Language.Hakaru.Embed
  ) where

import GHC.Tuple (()(..), (,)(..))
import Language.Hakaru.Syntax
import Language.Hakaru.Any (Any(Any))
import Language.Hakaru.Embed


text:
<?php

/**
 * @namespace
 */
namespace Zend\Tool\Framework\Manifest;
use Zend\Tool\Framework\Manifest;

/**
 * @uses       \Zend\Tool\Framework\Manifest
 * @category   Zend
 * @package    Zend_Tool
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface MetadataManifestable extends Manifest
{

    /**
     * getMetadata()
     *
     * Should either return a single metadata object or an array
     * of metadata objects
     *
     * @return array|Zend\Tool\Framework\Manifest\Metadata
     */
    public function getMetadata();

}


text:
package org.apache.tinkerpop.gremlin.process.computer.ranking.pagerank;

import org.apache.tinkerpop.gremlin.process.computer.KeyValue;
import org.apache.tinkerpop.gremlin.process.computer.util.StaticMapReduce;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import org.apache.commons.configuration.Configuration;

import java.util.Iterator;

/**
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
public class PageRankMapReduce extends StaticMapReduce<Object, Double, Object, Double, Iterator<KeyValue<Object, Double>>> {

    public static final String PAGE_RANK_MEMORY_KEY = "gremlin.pageRankMapReduce.memoryKey";
    public static final String DEFAULT_MEMORY_KEY = "pageRank";

    private String memoryKey = DEFAULT_MEMORY_KEY;

    private PageRankMapReduce() {

    }

    private PageRankMapReduce(final String memoryKey) {
        this.memoryKey = memoryKey;
    }

    @Override
    public void storeState(final Configuration configuration) {
        super.storeState(configuration);
        configuration.setProperty(PAGE_RANK_MEMORY_KEY, this.memoryKey);
    }

    @Override
    public void loadState(final Graph graph, final Configuration configuration) {
        this.memoryKey = configuration.getString(PAGE_RANK_MEMORY_KEY, DEFAULT_MEMORY_KEY);
    }

    @Override
    public boolean doStage(final Stage stage) {
        return stage.equals(Stage.MAP);
    }

    @Override
    public void map(final Vertex vertex, final MapEmitter<Object, Double> emitter) {
        final Property pageRank = vertex.property(PageRankVertexProgram.PAGE_RANK);
        if (pageRank.isPresent()) {
            emitter.emit(vertex.id(), (Double) pageRank.value());
        }
    }

    @Override
    public Iterator<KeyValue<Object, Double>> generateFinalResult(final Iterator<KeyValue<Object, Double>> keyValues) {
        return keyValues;
    }

    @Override
    public String getMemoryKey() {
        return this.memoryKey;
    }

    @Override
    public String toString() {
        return StringFactory.mapReduceString(this, this.memoryKey);
    }

    //////////////////////////////

    public static Builder build() {
        return new Builder();
    }

    public final static class Builder {

        private String memoryKey = DEFAULT_MEMORY_KEY;

        private Builder() {

        }

        public Builder memoryKey(final String memoryKey) {
            this.memoryKey = memoryKey;
            return this;
        }

        public PageRankMapReduce create() {
            return new PageRankMapReduce(this.memoryKey);
        }

    }
}


text:
/**
 * Imports
 */

import PixelGradient from 'components/PixelGradient'
import ShowcaseView from 'components/ShowcaseView'
import {component, element} from 'vdux'
import {Block, Icon} from 'vdux-ui'
import fire from 'vdux-fire'

/**
 * <Course Page/>
 */

export default fire((props) => ({
  courseVal: `/courses/${props.course}`
}))(component({
  render ({props, context}) {
  	const {courseVal} = props
  	const {value, loading} = courseVal

    if (loading) return <span />

    const {title, description, playlists} = value

    return (
    	<Block>
	    	<PixelGradient h={250}>
	        <Block tag='h1' m='24px 0' lighter fs={40} fontFamily='"Press Start 2P"'>
	          {title}
	        </Block>
	        <Block fs='l'>{description}</Block>
	        <Block align='center' mt='l' pointer onClick={context.setUrl('/courses')}>
	        	<Icon name='chevron_left'/>
	        	Back to Courses
        	</Block>
	      </PixelGradient>
	    	<ShowcaseView playlists={playlists} />
    	</Block>
    )
  }
}))


text:
The job-service API is used to create, retrieve, update, delete, suspend, cancel and check the status of jobs. HTTP requests are made to the job service which runs with a base Tomcat image. The job service then stores and retrieves data from the database.

Jobs can be suspended by setting the `CAF_JOB_SERVICE_SUSPENDED_PARTITIONS_REGEX` environment variable.
The variable can be set to a regular expression and can be used to control which partitions should be suspended.

For example to suspend only the "tenant-acme-corp" and "tenant-acme-com" partitions it can be set to `^tenant-acme-co(?rp|m)$`.
If a job is created for a suspended partition then rather than the job being kicked off immediately as it normally would be, the Job Service marks it as suspended and it is not eligible to run at this time.

Suspended jobs can be resumed by updating the `job_task_data` table.
```
UPDATE public.job_task_data
SET suspended=false
WHERE partition_id ~ '^tenant-acme-co(?rp|m)$';
```

## Job Service Links

[Overview](https://jobservice.github.io/job-service/pages/en-us/Overview)

[Getting Started](https://jobservice.github.io/job-service/pages/en-us/Getting-Started)

[API](https://jobservice.github.io/job-service/pages/en-us/API)

[Features](https://jobservice.github.io/job-service/pages/en-us/Features)

[Architecture](https://jobservice.github.io/job-service/pages/en-us/Architecture)


text:
package ee.tartu.jpg.minuposka.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import ee.tartu.jpg.minuposka.PoskaApplication;
import ee.tartu.jpg.minuposka.R;
import ee.tartu.jpg.minuposka.ui.base.DrawerBaseActivity;
import ee.tartu.jpg.minuposka.ui.util.DataUtils;
import ee.tartu.jpg.minuposka.ui.util.TextUtils;

/**
 * Created by gregor on 9/15/2015.
 */
public class LaunchActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        TextUtils.updateLanguage(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launch);
    }

    @Override
    protected void onStart() {
        TextUtils.updateLanguage(this);
        super.onStart();
        if (!DataUtils.isEulaAccepted(this)) {
            startActivity(new Intent(this, EulaActivity.class));
            finish();
        } else {
            DrawerBaseActivity.openActivity(this, DataUtils.getLastMenuNavigation(this));
            finish();
        }
    }
}


text:
namespace Cot
{
	template<typename Key, typename Value>
	class COT_API VectorMap
	{
		typedef std::pair<Key, Value> Element;
	private:
		std::vector<Element> _map;

	public:
		typedef typename std::vector<Element>::iterator iterator;
		typedef typename std::vector<Element>::const_iterator const_iterator;

		iterator begin() { return _map.begin(); }
		iterator begin() const { return _map.begin(); }

		iterator end() { return _map.end(); }
		iterator end() const { return _map.end(); }

		const_iterator cbegin() const { return _map.begin(); }
		const_iterator cend() const { return _map.end(); }

		VectorMap()
		{
			_map.clear();
			_map.reserve(150);
		}

		VectorMap(const VectorMap& other)
			: _map(other._map)
		{	}

		~VectorMap()
		{
			_map.clear();
		}

		void add(const Key& key, Value value) noexcept
		{
			_map.emplace_back(std::make_pair(key, component));
		}

		void remove(const Key& key) noexcept
		{
			if (_map.empty())
			{
				return;
			}
			Value value = find(key);
			Element element = std::make_pair(key, value);
			_map.erase(std::find(_map.cbegin(), _map.cend(), element));
		}

		void erase(const_iterator iter) noexcept
		{
			_map.erase(iter);
		}

		Value find(const Key& key) noexcept
		{
			if (_map.empty())
			{
				return NULL;
			}
			for (uint i = 0; i < _map.size(); ++i)
			{
				if (_map[i].first == key)
				{
					return _map[i].second;
				}
			}
			return NULL;
		}

		bool isHave(const Key& key) noexcept
		{
			if (_map.empty())
			{
				return false;
			}
			for (uint i = 0; i < _map.size(); ++i)
			{
				if (_map[i].first == key)
				{
					return true;
				}
			}

			return false;
		}

		VectorMap& operator=(const VectorMap& other) noexcept
		{
			_map = other._map;
		}

		Value operator[](const Key& key) noexcept
		{
			return find(key);
		}

		Element operator[](const int index) noexcept
		{
			return _map[index];
		}

		void clear() noexcept
		{
			_map.clear();
		}

		uint size() const noexcept { return _map.size(); }

	};

	template<typename Key, typename Value>
	class COT_API MultiVectorMap
	{
		typedef std::pair<Key, Value> Element;
	private:
		std::vector<Element> _map;

	public:
		typedef typename std::vector<Element>::iterator iterator;
		typedef typename std::vector<Element>::const_iterator const_iterator;

		iterator begin() { return _map.begin(); }
		iterator begin() const { return _map.begin(); }

		iterator end() { return _map.end(); }
		iterator end() const { return _map.end(); }

		const_iterator cbegin() const { return _map.cbegin(); }
		const_iterator cend() const { return _map.cend(); }

		MultiVectorMap()
		{
			_map.clear();
			_map.reserve(150);
		}

		MultiVectorMap(const MultiVectorMap& other)
			: _map(other._map)
		{	}

		~MultiVectorMap()
		{
			_map.clear();
		}

		void add(const Key& key, Value value) noexcept
		{
			_map.emplace_back(std::make_pair(key, value));
		}

		void remove(const Key& key) noexcept
		{
			if (_map.empty())
			{
				return;
			}
			Value value = find(key);
			Element element = std::make_pair(key, value);
			_map.erase(std::find(_map.cbegin(), _map.cend(), element));
		}

		void erase(const_iterator iter) noexcept
		{
			_map.erase(iter);
		}

		Value find(const Key& key) noexcept
		{
			if (_map.empty())
			{
				return NULL;
			}
			for (uint i = 0; i < _map.size(); ++i)
			{
				if (_map[i].first == key)
				{
					return _map[i].second;
				}
			}
			return NULL;
		}

		template<typename T>
		std::vector<T> finds(const Key& key) noexcept
		{
			std::vector<T> result;
			result.clear();
			if (_map.empty())
			{
				return result;
			}

			result.reserve(150);
			for (uint i = 0; i < _map.size(); ++i)
			{
				if (_map[i].first == key)
				{
					result.push_back(static_cast<T>(_map[i].second));
				}
			}
			return result;
		}

		bool isHave(const Key& key) noexcept
		{
			if (_map.empty())
			{
				return false;
			}
			for (uint i = 0; i < _map.size(); ++i)
			{
				if (_map[i].first == key)
				{
					return true;
				}
			}

			return false;
		}

		MultiVectorMap& operator=(const MultiVectorMap& other) noexcept
		{
			_map = other._map;
			return *this;
		}

		Value operator[](const Key& key) noexcept
		{
			return find(key);
		}

		Element operator[](const int index) noexcept
		{
			return _map[index];
		}

		void clear() noexcept
		{
			_map.clear();
		}

		uint size() const noexcept { return _map.size(); }

	};
}


text: A simple shell script that uses GCC's warning output to find likely pure functions.


text:
import { Table, Types } from 'ive-b';

export default class MessageTable {
	constructor (db) {
		this.db = db;

		this.table = new Table('message',
			{ name: 'user_id', 	type: new Types.Integer(11), ref: 'user' },
			{ name: 'file', 	type: new Types.Varchar(300) },
			{ name: 'text', 	type: new Types.Varchar(5000) },
			{ name: 'created', 	type: new Types.Date('CURRENT_TIMESTAMP')
		});
	}

	async install () {
		await this.db.execute(this.table.toSQL());

		await this.db.execute(`DROP PROCEDURE IF EXISTS createMessage;`);
		await this.db.execute(`DROP PROCEDURE IF EXISTS getMessageInterval;`);
		await this.db.execute(`DROP PROCEDURE IF EXISTS createImageMessage;`);
		await this.db.execute(`DROP PROCEDURE IF EXISTS getImage;`);

		await this.createMessage();
		await this.getMessageInterval();
		await this.createImage();
	}

	async clean () {
		await this.db.execute(`DROP TABLE IF EXISTS message;`);
	}

	createMessage () {
		return this.db.execute(`CREATE PROCEDURE createMessage (IN id INT, IN userText VARCHAR(2000))
		BEGIN
			INSERT INTO message (user_id, text) VALUES (id, userText);

			SELECT m.id, m.text, m.created, m.file, u.id as user_id, u.name as owner
			FROM message m JOIN user u ON m.user_id = u.id
			WHERE m.id=LAST_INSERT_ID();
		END`);
	}

	getMessageInterval () {
		return this.db.execute(`CREATE PROCEDURE getMessageInterval (IN messageId INT)
		BEGIN
			DECLARE safeId INT;

			IF messageId < 1 THEN SET safeId = (SELECT MAX(id) AS id FROM message);
			else SET safeId = 0;
			END IF;

			SELECT * FROM
				(SELECT m.id, m.text, m.created, m.file, u.id as user_id, u.name as owner
				 FROM message m JOIN user u ON m.user_id = u.id
				 WHERE m.id < messageId ORDER BY id DESC LIMIT 10) sub
			ORDER BY id ASC;
		END`);
	}

	createImage () {
		return this.db.execute(`CREATE PROCEDURE createImageMessage (IN userId INT, IN name VARCHAR(300))
		BEGIN
			INSERT INTO message (user_id, text, file) VALUES (userId, "", name);

			SELECT m.id, m.text, m.created, m.file, u.id as user_id, u.name as owner
			FROM message m JOIN user u ON m.user_id = u.id
			WHERE m.id=LAST_INSERT_ID();
		END`);
	}

}


text:
package org.jetbrains.kotlin.android.robowrapper;

import android.app.Activity;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import static org.junit.Assert.*;

@Config(manifest = Config.NONE)
@RunWith(RobolectricTestRunner.class)
public class ClassLoaderManagerTest {

    @Test
    public void testClassLoaderManager() throws Exception {
        Activity a = Robolectric.setupActivity(Activity.class);
        assertNotNull(a);

        ClassLoaderManager manager = new ClassLoaderManager();
        String className = "org.jetbrains.kotlin.android.robowrapper.test.SomeClass";

        ClassLoader cl1 = getContextClassLoader();
        Object o1 = cl1.loadClass(className);

        manager.replaceClassLoader("org.jetbrains.kotlin.android.robowrapper.test.");

        ClassLoader cl2 = getContextClassLoader();
        Object o2 = cl2.loadClass(className);

        manager.replaceClassLoader("org.jetbrains.kotlin.android.robowrapper.test.somethingNotExist");
        ClassLoader cl3 = getContextClassLoader();
        Object o3 = cl3.loadClass(className);

        assertNotSame(o1, o2);
        assertEquals(o2, o3);
    }

    private ClassLoader getContextClassLoader() {
        return Thread.currentThread().getContextClassLoader();
    }

}


text:
package edu.vu.isis.ammo.core.ui;

import android.content.res.Resources;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import edu.vu.isis.ammo.INetPrefKeys;
import edu.vu.isis.ammo.core.MyCheckBoxPreference;
import edu.vu.isis.ammo.core.MyEditIntegerPreference;
import edu.vu.isis.ammo.core.MyEditIntegerPreference.Type;
import edu.vu.isis.ammo.core.MyEditTextPreference;
import edu.vu.isis.ammo.core.R;

public class SerialPreferences extends AbstractAmmoPreference {

    private MyCheckBoxPreference serialOpEnablePref;

    private MyEditTextPreference serialDevicePref;

    private MyEditIntegerPreference serialSlotPref;
    private MyEditIntegerPreference serialRadiosInGroupPref;
    private MyEditIntegerPreference serialSlotDurationPref;
    private MyEditIntegerPreference serialTransmitDurationPref;
    private MyEditIntegerPreference serialBaudPref;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        logger.error("on create");
        super.onCreate(savedInstanceState);
        this.addPreferencesFromResource(R.xml.serial_preferences);

        final Resources res = this.getResources();

        this.serialOpEnablePref = (MyCheckBoxPreference) this
                .findPreference(INetPrefKeys.SERIAL_DISABLED);
        this.serialOpEnablePref.setTrueTitle("Serial " + TRUE_TITLE_SUFFIX);
        this.serialOpEnablePref.setFalseTitle("Serial " + FALSE_TITLE_SUFFIX);
        this.serialOpEnablePref.setSummary("Tap to toggle");
        this.serialOpEnablePref
                .setOnPreferenceClickListener(new OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(Preference preference) {
                        serialOpEnablePref.toggle();
                        return true;
                    }
                });

        this.serialDevicePref = (MyEditTextPreference) this
                .findPreference(INetPrefKeys.SERIAL_DEVICE);

        this.serialBaudPref =
                (MyEditIntegerPreference) this.findPreference(INetPrefKeys.SERIAL_BAUD_RATE);
        this.serialBaudPref.setType(Type.BAUDRATE);

        this.serialSlotPref = (MyEditIntegerPreference) this
                .findPreference(INetPrefKeys.SERIAL_SLOT_NUMBER);
        this.serialSlotPref.setType(Type.SLOT_NUMBER);
        this.serialSlotPref.setSummarySuffix(" (Set in Panthr Prefs)");
        this.serialSlotPref
                .setOnPreferenceClickListener(sendToPantherPrefsListener);

        this.serialRadiosInGroupPref = (MyEditIntegerPreference) this
                .findPreference(INetPrefKeys.SERIAL_RADIOS_IN_GROUP);
        this.serialRadiosInGroupPref.setType(Type.RADIOS_IN_GROUP);
        this.serialRadiosInGroupPref
                .setSummarySuffix(" (Set in Panthr Prefs)");
        this.serialRadiosInGroupPref
                .setOnPreferenceClickListener(sendToPantherPrefsListener);

        this.serialSlotDurationPref = (MyEditIntegerPreference) this
                .findPreference(INetPrefKeys.SERIAL_SLOT_DURATION);
        this.serialSlotDurationPref.setType(Type.SLOT_DURATION);

        this.serialTransmitDurationPref = (MyEditIntegerPreference) this
                .findPreference(INetPrefKeys.SERIAL_TRANSMIT_DURATION);
        this.serialTransmitDurationPref.setType(Type.TRANSMIT_DURATION);

        // These were removed from prefs
        // this.serialOpEnableSendingPref =
        // (MyCheckBoxPreference)this.findPreference(INetPrefKeys.SERIAL_SEND_ENABLED);
        // this.serialOpEnableReceivingPref =
        // (MyCheckBoxPreference)this.findPreference(INetPrefKeys.SERIAL_RECEIVE_ENABLED);
    }

    @Override
    protected void onResume() {
        logger.error("on resume");
        super.onResume();

        this.serialOpEnablePref.refresh();
        this.serialDevicePref.refresh();

        this.serialBaudPref.refresh();

        this.serialSlotPref.refresh();
        this.serialRadiosInGroupPref.refresh();
        this.serialSlotDurationPref.refresh();
        this.serialTransmitDurationPref.refresh();

        // These prefs were removed
        // this.serialOpEnableSendingPref.refresh();
        // this.serialOpEnableReceivingPref.refresh();
    }
}