text:
package com.vangent.hieos.xwebtools.servlets.xviewer;

import com.vangent.hieos.xclient.xds.repository.RetrieveB;
import com.vangent.hieos.xclient.xds.repository.RetContext;
import com.vangent.hieos.xclient.xds.repository.RetInfo;
import com.vangent.hieos.xutil.exception.MetadataException;
import com.vangent.hieos.xutil.exception.SOAPFaultException;
import com.vangent.hieos.xutil.exception.XdsException;
import com.vangent.hieos.xutil.metadata.structure.Metadata;
import com.vangent.hieos.xutil.metadata.structure.MetadataSupport;
import com.vangent.hieos.xutil.response.RegistryResponseParser;

import java.util.ArrayList;
import java.util.HashMap;

import org.apache.axiom.om.OMElement;

/**
 *
 * @author NIST (adapted)
 */
public class RetrieveBEngine {

    boolean isXca = false;

    /**
     *
     * @param isit
     */
    public void setIsXca(boolean isit) {
        isXca = isit;
    }

    /**
     *
     * @param id
     * @param qc
     * @param m
     * @param repositories
     * @param home
     */
    public void retrieve(String id, RetrieveBQueryContents qc, Metadata m, HashMap<String, ArrayList<String>> repositories, String home) {
        OMElement doc = null;
        try {
            doc = m.getObjectById(id);
        } catch (MetadataException e) {
            qc.addException(e);
        }
        if (doc == null) {
            qc.addFatalError("No Document with id of <" + id + "> present in this metadata");
            return;
        }
        String rep_uid = m.getSlotValue(doc, "repositoryUniqueId", 0);
        if (rep_uid == null) {
            qc.addFatalError("No repositoryUniqueId found in document <" + id + ">");
            return;
        }
        if (isXca) {
            rep_uid = home;
        }
        ArrayList<String> endpoints = repositories.get(rep_uid);
        if (endpoints == null) {
            qc.addFatalError("The repositoryUniqueId found in document <" + id + ">, is not configured in xwebtools");
            return;
        }
        for (String endpoint : endpoints) {
            try {
                qc.endpoint = endpoint;
                retrieve(id, qc, m, home);
                // seems to have worked
                return;
            } catch (SOAPFaultException e) {
                qc.addError(e.getMessage());
                // endpoint failed - try next one in list
            }
        }
        // none worked
        qc.addFatalError("Connection to all known endpoints for <" + rep_uid + "> " + endpoints + " failed");
    }

    /**
     *
     * @param id
     * @param qc
     * @param m
     * @param home
     * @throws XdsWSException
     */
    public void retrieve(String id, RetrieveBQueryContents qc, Metadata m, String home) throws SOAPFaultException {
        RetContext r_ctx = new RetContext();
        try {
            OMElement doc = m.getObjectById(id);
            if (doc == null) {
                qc.addFatalError("No Document with id of <" + id + "> present in this metadata");
                return;
            }
            RetInfo req_info = new RetInfo();
            req_info.setContent_type(doc.getAttributeValue(MetadataSupport.mime_type_qname));
            String uid = m.getUniqueIdValue(id);
            req_info.setDoc_uid(uid);
            req_info.setRep_uid(m.getSlotValue(doc, "repositoryUniqueId", 0));
            req_info.setHash(m.getSlotValue(doc, "hash", 0));
            req_info.setHome(home);

            String size = m.getSlotValue(doc, "size", 0);
            if (size != null) {
                req_info.setSize(Integer.parseInt(size));
            }

            r_ctx.addRequestInfo(uid, req_info);

            RetrieveB ret_b = new RetrieveB(r_ctx, qc.endpoint);
            ret_b.setIsXca(isXca);
            ret_b.run();

            ret_b.validate(false /* validateRequest */);

            qc.setRequestXML(r_ctx.getRequest());
            qc.setResultXML(r_ctx.getResult());
            qc.set_id(id);
            RegistryResponseParser rrp = r_ctx.getRrp();
            if (rrp == null) {
                qc.addFatalError("RetrieveBEngine.retrieve: RegistryResponseParser is null");
                return;
            }
            String status = rrp.get_registry_response_status();
            RetInfo ri = r_ctx.getResponseInfo().get(uid);
            qc.set_contents(ri.getContents(), ri.getContent_type());
            String errors = r_ctx.getResponseInfo().get(uid).getErrors();
            if (errors != null && !errors.equals("")) {
                qc.addError(errors);
            }
        } catch (MetadataException e) {
            qc.setResultXML(r_ctx.getResult());
            qc.addException(e);
        } catch (SOAPFaultException e) {
            qc.setResultXML(r_ctx.getResult());
            qc.addException(e);
        } catch (XdsException e) {
            qc.setResultXML(r_ctx.getResult());
            qc.addException(e);
        }
    }
}


text:
import os
from .configuration import Config
from . import handlers as cmd

VERSION = '0.0.3'
APPNAME = 'archie'

def main(args):
    configfile = args['--config'] or os.path.join(args['PACKAGE'], 'a.rc')
    cfg = Config(configfile, args)

    if args['install']:
        result = cmd.Install(cfg)
    elif args['restore']:
        result = cmd.Restore(cfg)

    for item in result:
        print(item)

redpajama_set_name: RedPajamaGithub


text:
import java.io.*;
import java.util.*;
public class stapler {
	public static int MAX_STACK = 30;
	public static void main(String[] Args) throws IOException {
		Scanner input = new Scanner(new File("stapler.in"));

		//read in the total number of cases
		int num_cases = input.nextInt();

		//loop through all cases
		for(int count = 1; count <= num_cases; count++) {

			//read in the amount of stacks
			int num_amounts = input.nextInt();

			//initialize the stack size
			int stack_size = 0;

			//count up all the stack sizes
			for(int amount_index = 0; amount_index < num_amounts; amount_index++) {

				//read in stack size and add it
				int current_amount = input.nextInt();
				stack_size = stack_size+ current_amount;
			}

			//output result
			if(stack_size > MAX_STACK){

				//case where there are too many pages
				System.out.printf("Battle #%d:%n", count);
				System.out.printf("The Stapler must face %d pages%n", stack_size);
				System.out.printf("Foiled again!%n");
			}
			else {

				//case where the stapler was successful
				System.out.printf("Battle #%d:%n", count);
				System.out.printf("The Stapler must face %d pages%n", stack_size);
				System.out.printf("The Stapler saves the day!%n");
			}

			//output new line if we are not on the last case
			if(count != num_cases) {

				System.out.printf("%n");
			}
		}
	}
}


text:
package net.irext.webapi.utils;

import java.security.MessageDigest;

/**
 * Filename:       MD5Digest.java
 * Revised:        Date: 2017-04-03
 * Revision:       Revision: 1.0
 *

 * Description:    MD5 digest algorithm
 *

 * Revision log:
 * 2017-04-03: created by strawmanbobi
 */
public class MD5Digest {

    public static String MD5(String content) {
        String result = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(content.getBytes());
            byte b[] = md.digest();

            int i;

            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) i += 256;
                if (i < 16) buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return content;
        }
        return result;
    }
}


text:
<?php

namespace Amadeus\Client\Struct\Fare\MasterPricer;

/**
 * MultiCity
 *
 * @package Amadeus\Client\Struct\Fare\MasterPricer
 * @author Dieter Devlieghere <dermikagh@gmail.com>
 */
class MultiCity
{
    /**
     * @var string
     */
    public $locationId;
    /**
     * @var string
     */
    public $airportCityQualifier;

    /**
     * @param string $locationId
     * @param string|null $qualifier
     */
    public function __construct($locationId, $qualifier = null)
    {
        $this->locationId = $locationId;
        $this->airportCityQualifier = $qualifier;
    }
}


text:
angular.module('starter.controllers', [])

.controller('AppCtrl', function($scope, $ionicModal, $timeout, $ionicHistory, $state) {

  // With the new view caching in Ionic, Controllers are only called
  // when they are recreated or on app start, instead of every page change.
  // To listen for when this page is active (for example, to refresh data),
  // listen for the $ionicView.enter event:
  //$scope.$on('$ionicView.enter', function(e) {
  //});

  var menu = this;

  menu.tempTitle = "";
  menu.tempValue = "";
  menu.editMode = false;

  menu.refreshMenu = function () {
    menu.savedNotes = JSON.parse(localStorage.getItem("savedNotes"));
  };
  menu.refreshMenu();

  menu.loadNote = function (key, value)  {
    menu.editMode = false;
    menu.loadedKey = key;
    menu.loadedValue = value;
    console.log("menu.loadedValue", menu.loadedValue);
  }

  menu.deleteNote = function (key) {
    menu.loadedKey = "";
    menu.loadedValue = "";
    console.log("key", key);
    console.log("pre delete menu.savedNotes", menu.savedNotes);
    delete menu.savedNotes[key];
    console.log("post delete menu.savedNotes", menu.savedNotes);
    localStorage.setItem('savedNotes', JSON.stringify(menu.savedNotes));
    menu.refreshMenu();

    $ionicHistory.nextViewOptions({
      disableBack: true
    });
    $state.go('app.playlists');
  };

  menu.editNote = function () {
    menu.tempValue = menu.loadedValue;
    menu.tempTitle = menu.loadedKey;
    menu.editMode = true;
  };

  menu.clear = function () {
      menu.loadedKey = "";
      menu.loadedValue = "";
  };

  menu.addNote = function () {
    // var savedNotes = JSON.parse(localStorage.getItem("savedNotes")) || {};
    // var titleToDelete = menu.tempTitle;
    delete menu.savedNotes[menu.tempTitle];
    localStorage.setItem('savedNotes', JSON.stringify(menu.savedNotes));
    menu.savedNotes = JSON.parse(localStorage.getItem("savedNotes"));
    var title = menu.loadedKey;
    var content = menu.loadedValue;
      if (menu.savedNotes.hasOwnProperty(title) === false) {
        menu.savedNotes[title] = content;
        localStorage.setItem('savedNotes', JSON.stringify(menu.savedNotes));
        menu.editMode = false;
        menu.clear();
        menu.refreshMenu();
        $ionicHistory.nextViewOptions({
          disableBack: true
        });
        $state.go('app.playlists');
        // menu.savedNotes = JSON.parse(localStorage.getItem("savedNotes"));
      } else {
        console.log("you already have a note by this title");
          // menu.tempValue = menu.loadedValue;
          // menu.tempTitle = menu.loadedKey;
          // menu.loadedValue = menu.tempValue;
          menu.loadedKey = menu.tempTitle;
          menu.savedNotes[menu.tempTitle] = menu.tempValue;
          localStorage.setItem('savedNotes', JSON.stringify(menu.savedNotes));
          menu.refreshMenu();

      }
  };

})

.controller('PlaylistsCtrl', function($scope) {
    var notes = this;

    notes.clear = function () {
      notes.titleInput = "";
      notes.contentInput = "";
    };

    notes.addNote = function () {
      var savedNotes = JSON.parse(localStorage.getItem("savedNotes")) || {};
      var title = notes.titleInput;
      var content = notes.contentInput;
        if (savedNotes.hasOwnProperty(title) === false) {
          savedNotes[title] = content;
          localStorage.setItem('savedNotes', JSON.stringify(savedNotes));
          notes.clear();
          $scope.$parent.menu.refreshMenu();
          // menu.savedNotes = JSON.parse(localStorage.getItem("savedNotes"));
        } else {
          console.log("you already have a note by this title");
        }
    };
})

.controller('PlaylistCtrl', function($scope, $stateParams) {
});


text:
<?php

namespace Thruster\Component\HttpModifier;

use Psr\Http\Message\RequestInterface;

/**
 * Interface RequestModifierInterface
 *
 * @package Thruster\Component\HttpModifier
 * @author  Aurimas Niekis <aurimas@niekis.lt>
 */
interface RequestModifierInterface extends ModifierInterface
{
    public function modify(RequestInterface $request) : RequestInterface;
}


text:
layout: master
include: person
name: John White
home: CERN
country: "CH"
photo: assets/images/people/john-white.jpg
email: john.white@cern.ch
phone:
on_contract: yes
has_been_on_contract: yes
orcid: ORCID ID
groups:
  dellingr:
    role: Project leader
  dellingr-sg:
    role: Observer, Project leader
  dellingr-po:
    role: Project leader
  e3ds:
    role: Project leader
  e3ds-sg:
    role: Observer, Project leader
  e3ds-po:
    role: Project leader
  glenna2-rg:
---


text:
                <form class="container-fluid" name="form" role="form">

                            <input type="text" class="form-control" name="username" ng-model="username" placeholder="用户名" required />

                            <input type="text" class="form-control" name="machineno" ng-model="machineno" placeholder="机器号" required />

                            <input type="text" class="form-control" name="regnumber" ng-model="regnumber" placeholder="注册号码" required />

                            <input type="checkbox" /> 我同意注册协议

                        <button class="btn btn-primary col-md-12" ng-disabled="form.$invalid" ng-click="me.regist()">注册</button>

                                点击查看注册协议 >

                                返回

                </form>


text:
import gulp from "gulp";
import pkg from "./package.json";
import cssNano from "gulp-cssnano";
import uglify from "gulp-uglify";
import replace from "gulp-replace";
import rimraf from "gulp-rimraf";
import scss from "gulp-sass";
import rename from "gulp-rename";
import preprocess from "gulp-preprocess";
import browserify from "browserify";
import babelify from "babelify";
import sourceStream from "vinyl-source-stream";
import buffer from "vinyl-buffer";
import fs from "fs";
import preprocessify from "preprocessify";
//import sourcemaps from "gulp-sourcemaps";
import { getAutomaton, getRuleMappings } from "./src/client/js/parser/_build";

let INSTALLER_CLASS_NAME = `${ pkg["packageName"] }.Installer`;

let dir = __dirname,
    dest = `${dir}/build`,
    source = `${dir}/src`,
    context = {
        context: {
            package: pkg,
            compileAfter: "", // is set during "pre-cls" task.
            themes: "", // is set after css move task
            autocompleteAutomaton: [],
            ruleMappings: {}
        }
    },
    themes = []; // reassigned

function themesReady () { // triggered when build is done
    themes = fs.readdirSync(`${ dest }/client/css/themes`);
    context.context.themes = themes.map(function (n) {
        return ', "' + n.replace(/\..*$/, "") + '": "css/themes/' + n + '"';
    }).join("");
}

gulp.task("prepare", function (cb) {
    let aut = [];
    console.log(`Compiling autocomplete and highlight rules...`);
    try {
        aut = getAutomaton();
        context.context.autocompleteAutomaton = JSON.stringify(aut.automaton);
        context.context.ruleMappings = JSON.stringify(aut.ruleMappings);
    } catch (e) {
        console.error.apply(console, e);
        cb(e);
    }
    console.log(`Automaton ready and has ${ aut.automaton.length } states with ${
        aut.automaton.reduce((a, b) =>
             (typeof a === "number" ? a : a.length) + (typeof b === "number" ? b : b.length))
    } rules.`);
    cb();
});

gulp.task("clean", ["prepare"], function () {
    return gulp.src(dest, { read: false })
        .pipe(rimraf());
});

gulp.task("html", ["clean"], function () {
    return gulp.src(`${ source }/client/index.html`)
        .pipe(preprocess(context))
        .pipe(gulp.dest(`${ dest }/client`));
});

gulp.task("scss", ["clean"], () => {
    return gulp.src([`${source}/client/scss/index.scss`])
        .pipe(preprocess(context))
        .pipe(scss())
        .pipe(cssNano({
            zindex: false
        }))
        .pipe(gulp.dest(`${dest}/client/css`));
});

gulp.task("js", ["clean", "css"], function () {
    let bundler = browserify({
        entries: `${source}/client/js/index.js`,
        debug: true
    }).transform(preprocessify, {
        includeExtensions: ['.js'],
        context: context.context
    });
    bundler.transform("babelify", { presets: ["es2015"] });
    return bundler.bundle()
        .on("error", function (err) { console.error("An error occurred during bundling:", err); })
        .pipe(sourceStream("index.js"))
        .pipe(buffer())
        //.pipe(sourcemaps.init({ loadMaps: true }))
        .pipe(uglify({
            output: {
                ascii_only: true,
                width: 25000,
                max_line_len: 15000
            },
            preserveComments: "some"
        }))
        .pipe(replace(/\x0b|\x1b/g, e => `\\x${ e === "\x0b" ? 0 : 1 }b`))
        .pipe(replace(/[\x00-\x08]/g, e =>  `\\x0${ e.charCodeAt(0) }`))
        //.pipe(sourcemaps.write())
        .pipe(gulp.dest(`${ dest }/client/js`));
});

gulp.task("copy-css-themes", ["clean"], function () {
    return gulp.src(`${ source }/client/scss/themes/*.*`)
        .pipe(preprocess(context))
        .pipe(scss())
        .pipe(cssNano())
        .pipe(gulp.dest(`${ dest }/client/css/themes/`));
});

// Need css themes directory copied to collect themes names.
gulp.task("css", ["scss", "copy-css-themes"], function (cb) {
    themesReady();
    cb();
});

gulp.task("pre-cls", ["js", "js", "html", "css", "readme"], () => {
    return gulp.src([`${ source }/cls/**/*.cls`])
        .pipe(rename((f) => {
            f.basename = `${ f.dirname === "." ? "" : f.dirname + "." }${
                f.basename
            }`;
            f.dirname = ".";
            if (f.basename !== INSTALLER_CLASS_NAME)
                context.context.compileAfter +=
                    (context.context.compileAfter ? "," : "") + f.basename;
        }))
        .pipe(gulp.dest(`${dest}/cls`));
});

gulp.task("cls", ["pre-cls"], () => {
    return gulp.src([`${dest}/cls/**/*.cls`])
        .pipe(preprocess(context))
        .pipe(gulp.dest(`${dest}/cls`));
});

gulp.task("readme", ["clean"], function () {
    return gulp.src(`${ dir }/readme.md`)
        .pipe(gulp.dest(`${ dest }`));
});

gulp.task("default", ["cls"]);


text:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { propType } from 'v2/util/inlinedGraphqlAnywhere'
import styled from 'styled-components'

import currentUserService from 'v2/util/currentUserService'

import MemberAvatar from 'v2/components/MemberAvatar'
import GenericButton from 'v2/components/UI/GenericButton'
import Badge from 'v2/components/UI/Badge'

import managedMemberFragment from 'v2/components/ManagedMembers/components/ManagedMember/fragments/managedMember'

const Container = styled.div`
  display: flex;
  padding: 0.5em;
  border-top: 1px solid ${x => x.theme.colors.gray.light};
`

const Representation = styled.div`
  display: flex;
  flex: 1;
`

const Information = styled.div`
  display: flex;
  flex: 1;
  flex-direction: column;
  justify-content: space-around;
  padding-left: 1em;
  font-size: ${x => x.theme.fontSizesIndexed.xs};
  line-height: ${x => x.theme.lineHeightsIndexed.base};
  color: ${x => x.theme.colors.gray.base};

  &:first-child {
    padding-left: 0;
  }
`

const Name = styled.a`
  display: block;
  font-weight: bold;
  color: ${x => x.theme.colors.gray.base};
`

const Warning = styled.div`
  color: ${x => x.theme.colors.state.alert};
`

const Amount = styled.div`
  color: ${x => x.theme.colors.gray.medium};
`

const Button = styled(GenericButton).attrs({
  f: 1,
})`
  align-self: flex-start;
`

export default class ManagedMembers extends Component {
  static propTypes = {
    isOwner: PropTypes.bool,
    isRemovable: PropTypes.bool,
    confirmationWarning: PropTypes.string,
    confirmationSelfWarning: PropTypes.string,
    onRemove: PropTypes.func.isRequired,
    member: propType(managedMemberFragment).isRequired,
  }

  static defaultProps = {
    isOwner: false,
    isRemovable: true,
    confirmationWarning: 'Are you sure?',
    confirmationSelfWarning: null,
  }

  state = {
    mode: 'resting',
  }

  remove = () => {
    const { mode } = this.state

    if (mode === 'clicked') {
      return this.setState({ mode: 'resting' })
    }

    return this.setState({ mode: 'clicked' })
  }

  confirm = () => {
    const { onRemove, member } = this.props

    this.setState({ mode: 'removing' })

    return onRemove({
      member_id: member.id,
      member_type: member.__typename.toUpperCase(),
    }).catch(() => this.setState({ mode: 'error' }))
  }

  render() {
    const { mode } = this.state

    const {
      member,
      isOwner,
      isRemovable,
      confirmationWarning,
      confirmationSelfWarning,
    } = this.props

    return (
      <Container>
        <Representation>
          {member.__typename === 'User' && <MemberAvatar member={member} />}

          <Information>
            <Name href={member.href}>
              {member.name}
              {member.__typename === 'Group' && (
                <Badge
                  ml={2}
                  f={0}
                  color="gray.medium"
                  icon={{ private: 'Lock' }[member.visibility]}
                >
                  Group
                </Badge>
              )}
            </Name>

            {member.__typename === 'Group' && mode !== 'clicked' && (
              <Amount>Group started by {member.user.name}</Amount>
            )}

            {mode === 'clicked' && (
              <Warning>
                {currentUserService().id === member.id &&
                  `${confirmationSelfWarning} `}

                {`${confirmationWarning} `}

                  Confirm

              </Warning>
            )}
          </Information>
        </Representation>

        {isOwner && <Button disabled>Owner</Button>}

        {!isOwner && isRemovable && (
          <Button
            onClick={this.remove}
            color={mode === 'clicked' ? 'state.alert' : undefined}
          >
            {
              {
                resting: 'Remove',
                clicked: 'Cancel',
                removing: 'Removing...',
                error: 'Error',
              }[mode]
            }
          </Button>
        )}
      </Container>
    )
  }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.costmanagement.models;

import com.azure.resourcemanager.costmanagement.fluent.models.ExportExecutionListResultInner;
import java.util.List;

/** An immutable client-side representation of ExportExecutionListResult. */
public interface ExportExecutionListResult {
    /**
     * Gets the value property: The list of export executions.
     *
     * @return the value value.
     */
    List<ExportExecution> value();

    /**
     * Gets the inner com.azure.resourcemanager.costmanagement.fluent.models.ExportExecutionListResultInner object.
     *
     * @return the inner object.
     */
    ExportExecutionListResultInner innerModel();
}


text:
package com.thoughtworks.go.server.newsecurity.models;

public interface Credentials {
}


text:
import cv2
import utils
from skimage.feature import hog
import cPickle
import numpy
from sklearn.externals import joblib
from sklearn import svm

def get_set(metadataFile, classType):
    set = []

    with open(metadataFile, "r") as f:
        entries = f.readlines()

    for entry in entries:
        entry = entry.split()
        filePath = entry[0]
        x, y, scale = int(entry[1]), int(entry[2]), float(entry[3])

        img = cv2.imread(filePath)
        img = cv2.resize(img, (0, 0), fx=scale, fy=scale)
        img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        img_gray_crop = img_gray[y:y+128, x:x+64]

        hog_gray = hog(img_gray_crop, orientations=9, pixels_per_cell=(8, 8),
                         cells_per_block=(2, 2), visualise=False)

        prevFilePath = utils.get_prev_img(filePath)

        prev_img = cv2.imread(prevFilePath)
        prev_img = cv2.resize(prev_img, (0, 0), fx=scale, fy=scale)
        prev_img_gray = cv2.cvtColor(prev_img, cv2.COLOR_BGR2GRAY)

        flow = cv2.calcOpticalFlowFarneback(prev_img_gray, img_gray, 0.5, 3, 15, 3, 5, 1.2, 0)

        # flowx, flowy = flow[..., 0], flow[..., 1]
        # flowx_crop, flowy_crop = flowx[y:y+128, x:x+64], flowy[y:y+128, x:x+64]
        #
        # hog_flow_x = hog(flowx_crop, orientations=9, pixels_per_cell=(8, 8),
        #                  cells_per_block=(2, 2), visualise=False)
        # hog_flow_y = hog(flowy_crop, orientations=9, pixels_per_cell=(8, 8),
        #                  cells_per_block=(2, 2), visualise=False)

        hsv = numpy.zeros_like(img)
        hsv[..., 1] = 255

        mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])
        hsv[..., 0] = ang * 180/ numpy.pi / 2
        hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)
        flowRGB = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
        flow_gray = cv2.cvtColor(flowRGB, cv2.COLOR_BGR2GRAY)

        flow_gray_crop = flow_gray[y:y+128, x:x+64]

        hog_flow = hog(flow_gray_crop, orientations=9, pixels_per_cell=(8, 8),
                         cells_per_block=(2, 2), visualise=False)

        desc = hog_gray + hog_flow

        set.append(desc)
    return set, [classType] * len(entries)

def get_hog_train_set(pos_filepath, neg_filepath, featureFile):
    p_features, p_classes = get_set(pos_filepath, 1)
    n_features, n_classes = get_set(neg_filepath, -1)
    print "positive samples", len(p_features)
    print "negative samples", len(n_features)

    features = p_features + n_features
    classes = p_classes + n_classes

    cPickle.dump((features, classes), open(featureFile, "wb"), protocol=2)

def trainSvmClassifier(feature_file, classifierFile):
    get_hog_train_set("hog_corpus_pos.txt", "hog_corpus_neg.txt", feature_file)

    obj = cPickle.load(open(feature_file, "rb"))

    features, classes = obj

    svc = svm.SVC(C=1.0, kernel='linear', probability=True).fit(features, classes)

    joblib.dump(svc, classifierFile)

trainSvmClassifier("hog_train_test_sum.dump", "hog_sum.dump")


text:
<?php
$this->addScript("config.js");
$this->addStyle("config.css");
?>

Configure Election

To know how to do the configuration, read this.

  <?php
  $type = Request::postParam("type");
  $strength = Request::postParam("strength");
  $votes = Request::postParam("votes");

  if($type !== null && $strength !== null && $votes !== null && CSRF::check()){
    $classes = Request::postParam("classes");
    $divs = Request::postParam("divs");
    $ableToChoose = Request::postParam("votes");

    $defaultClass = Request::postParam("default-class");
    $defaultDiv = Request::postParam("default-division");

    if(($type === "single" || $type === "multiple" || $type === "class") && !empty($classes)){
      $submitConfig = array(
        "type" => $type,
        "classes" => $classes,
        "divisions" => $divs,
        "max-strength" => $strength,
        "able-to-choose" => $ableToChoose,
        "password" => isset($_POST["password"]) ? "1" : "0",
        "default-class" => $defaultClass,
        "default-division" => $defaultDiv,
        "disable-class-div-change" => isset($_POST["disable-class-div-change"]) ? "1" : "0"
      );
      $newConfig = $submitConfig + $this->config;
      $newConfig = array_replace($newConfig, $submitConfig);

      $this->removeData("config");
      $this->saveJSONData("config", $newConfig);

      echo sss("Saved", "The configuration has been saved.");
      $this->config = $newConfig;
    }
  }
  ?>
  <form action="<?php echo Lobby::u();?>" method="POST">

      Election Type
      <select name="type">
        <option value="single">Normal Election</option>
        <option value="class" <?php if($this->config["type"] === "class"){echo "selected='selected'";}?>>Class Wise</option>
        <option value="multiple" <?php if($this->config["type"] === "multiple"){echo "selected='selected'";}?>>Boys & Girls</option>
      </select>

      Number of Votes
      <input type="number" name="votes" placeholder="How may votes can the student make ?"  value="<?php echo $this->config["able-to-choose"];?>" />

      Maximum Strength
      <input type="number" name="strength" value="<?php echo $this->config["max-strength"];?>" />

      Password For Voters<cl/>

        <input type="checkbox" name="password" <?php if($this->config["password"] === "1"){echo "checked='checked'";}?> />
        Enable password for each roll numbers

      Classes
      <?php
      foreach($this->config["classes"] as $class){
      ?>

          <input type="number" name="classes[]" value="<?php echo $class;?>" class="valign" />

      <?php
      }
      ?>

      Divisions
      <?php
      foreach($this->config["divisions"] as $div){
      ?>

          <input type="text" name="divs[]" value="<?php echo $div;?>" class="valign" />

      <?php
      }
      ?>

    <?php
    if(!empty($this->config["classes"])){
    ?>

        Default Class
        <select name="default-class">
          <?php
          foreach($this->config["classes"] as $class){
            echo "<option value='$class' ". ($this->config["default-class"] === $class ? "selected='selected'" : "") .">$class</option>";
          }
          ?>
        </select>

    <?php
    }
    if(!empty($this->config["divisions"])){
    ?>

        Default Division
        <select name="default-division">
          <?php
          foreach($this->config["divisions"] as $div){
            echo "<option value='$div'". ($this->config["default-division"] === $div ? "selected='selected'" : "") .">$div</option>";
          }
          ?>
        </select>

    <?php
    }
    ?>

      Disable choice of class and division<cl/>

        <input type="checkbox" name="disable-class-div-change" <?php if($this->config["disable-class-div-change"] === "1"){echo "checked='checked'";}?> />
        Prevent student from choosing class & division

    <?php echo CSRF::getInput();?>
    <button class="btn green">Save Settings</button>
  </form>


text:
package br.usp.each.saeg.code.forest.metaphor;

import javax.media.j3d.*;
import javax.vecmath.*;
import org.apache.commons.lang3.*;
import br.usp.each.saeg.code.forest.domain.*;
import br.usp.each.saeg.code.forest.metaphor.assembler.*;
import br.usp.each.saeg.code.forest.metaphor.building.blocks.*;
import br.usp.each.saeg.code.forest.metaphor.util.*;
import com.sun.j3d.utils.geometry.*;

/**
 * @author Danilo Mutti (dmutti@gmail.com)
 */
public class Leaf extends CodeGeometry {

    private LeafData data;
    private CodeCone shape;
    private final ForestRestrictions restrictions;
    private Branch parent;

    public Leaf(Branch parent, float radius, LeafData data, ForestRestrictions restr, Transform3D tr) {
        this.parent = parent;
        this.data = data;
        appearance = ImageUtils.getLeafAppearance(new Color3f(createColor(data.getScore())));
        this.restrictions = restr;

        shape = new CodeCone(radius/4, radius, Primitive.GENERATE_NORMALS + Primitive.GENERATE_TEXTURE_COORDS, appearance);
        shape.setGeometry(this);

        GroupDataItem item = new GroupDataItem(tr, shape);
        groupData.add(item);
        getTrunk().add(item.getTransformGroup());
    }

    public LeafData getData() {
        return data;
    }

    public CodeCone getShape() {
        return shape;
    }

    @Override
    public void changeStatus() {
        if (isEnabled()) {
            disable();
        } else {
            refresh();
        }
    }

    @Override
    public void refresh() {
        if (restrictions.isLeaves() && !restrictions.isBranches()) {
            if (!containsTerm() || !containsScore()) {
                disable();
                return;
            }
        }
        if (restrictions.isLeaves() && restrictions.isBranches()) {

            if (StringUtils.isBlank(restrictions.getTerm())) {
                if(!containsScore()) {
                    disable();
                    return;
                }
            } else {
                if (StringUtils.containsIgnoreCase(parent.getData().getValue(), StringUtils.trim(restrictions.getTerm()))) {
                    if (!containsScore()) {
                        disable();
                        return;
                    }
                }
                else {
                    if (!containsTerm() || !containsScore()) {
                        disable();
                        return;
                    }
                }
            }
        }
        enable();
    }

    private boolean containsTerm() {
        if (StringUtils.isBlank(restrictions.getTerm())) {
            return true;
        }
        if (restrictions.isLeaves()) {
            if (restrictions.containsTerm(data.getValue())) {
                return true;
            }
        }
        return false;
    }

    private boolean containsScore() {
        if (restrictions.isLeaves()) {
            if (data.isScoreBetween(restrictions.getMinScore(), restrictions.getMaxScore())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Trunk getTrunk() {
        return parent.getTrunk();
    }

}


text:
Portfolio
=========

Portfolio of interesting work


text:
namespace content {

class ShellPluginServiceFilter : public PluginServiceFilter {
 public:
  ShellPluginServiceFilter();

  ShellPluginServiceFilter(const ShellPluginServiceFilter&) = delete;
  ShellPluginServiceFilter& operator=(const ShellPluginServiceFilter&) = delete;

  ~ShellPluginServiceFilter() override;

  // PluginServiceFilter implementation.
  bool IsPluginAvailable(int render_process_id,
                         const WebPluginInfo& plugin) override;

  bool CanLoadPlugin(int render_process_id,
                     const base::FilePath& path) override;
};

}  // namespace content

#endif  // CONTENT_SHELL_BROWSER_SHELL_PLUGIN_SERVICE_FILTER_H_


text:
//=====================================================================//
/*! @file
    @brief  ハードウェアー・ベクター関係
    @author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <stdlib.h>
#include "vect.h"

void (*interrupt_vectors[256])(void);

// null interrupt TASK
INTERRUPT_FUNC void null_task_(void)
{
}

//-----------------------------------------------------------------//
/*!
	@brief	割り込み関数の設定
	@param[in]	task	割り込み関数
	@param[in]	idx		割り込みベクター番号
 */
//-----------------------------------------------------------------//
void set_interrupt_task(void (*task)(void), uint32_t idx)
{
	if(idx < 256) {
		if(task == NULL) {
			task = null_task_;
		}
		interrupt_vectors[idx] = task;
	}
}

// Exception(Supervisor Instruction)
INTERRUPT_FUNC void super_visor_inst_(void)
{
}

// Exception(Undefined Instruction)
INTERRUPT_FUNC void undefined_inst_(void)
{
}

// Exception(Floating Point)
INTERRUPT_FUNC void floating_point_(void)
{
}

// NMI
INTERRUPT_FUNC void non_maskable_interrupt_(void)
{
}

INTERRUPT_FUNC void power_on_reset(void);

#define FIXEDVECT_SECTION __attribute__ ((section (".fvectors")))

void * const Fixed_Vectors[] FIXEDVECT_SECTION = {
//;0xffffffd0  Exception(Supervisor Instruction)
    super_visor_inst_,
//;0xffffffd4  Reserved
    null_task_,
//;0xffffffd8  Reserved
    null_task_,
//;0xffffffdc  Exception(Undefined Instruction)
    undefined_inst_,
//;0xffffffe0  Reserved
    null_task_,
//;0xffffffe4  Exception(Floating Point)
    floating_point_,
//;0xffffffe8  Reserved
    null_task_,
//;0xffffffec  Reserved
    null_task_,
//;0xfffffff0  Reserved
    null_task_,
//;0xfffffff4  Reserved
    null_task_,
//;0xfffffff8  NMI
    non_maskable_interrupt_,
//;0xfffffffc  RESET
	power_on_reset
};


text:
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ASP
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Web;
    using System.Web.Helpers;
    using System.Web.Mvc;
    using System.Web.Mvc.Ajax;
    using System.Web.Mvc.Html;
    using System.Web.Routing;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.WebPages;
    using Advertise.Web;

    [System.CodeDom.Compiler.GeneratedCodeAttribute("RazorGenerator", "2.0.0.0")]
    [System.Web.WebPages.PageVirtualPathAttribute("~/Views/Category/List.cshtml")]
    public partial class _Views_Category_List_cshtml : System.Web.Mvc.WebViewPage<IEnumerable<Advertise.ViewModel.Models.Categories.CategoryListViewModel>>
    {
        public _Views_Category_List_cshtml()
        {
        }
        public override void Execute()
        {
WriteLiteral("\r\n");

WriteLiteral("\r\n");

            #line 5 "..\..\Views\Category\List.cshtml"

    ViewBag.Title = "لیست";

            #line default
            #line hidden
WriteLiteral("\r\n\r\n
\r\n\r\n
\r\n
لیست دسته ها
\r\n
\r\n\r\n
\r\n\r\n
\r\n
\r\n\r\n\r\n\r\n\r\n                \r\n");

WriteLiteral("                    ");

            #line 25 "..\..\Views\Category\List.cshtml"
               Write(Html.DisplayNameFor(model => model.Title));

            #line default
            #line hidden
WriteLiteral("\r\n                	\r\n\r\n\r\n                \r\n");

WriteLiteral("                    ");

            #line 30 "..\..\Views\Category\List.cshtml"
               Write(Html.DisplayNameFor(model => model.Description));

            #line default
            #line hidden
WriteLiteral("\r\n                	\r\n\r\n                \r\n");

WriteLiteral("                    ");

            #line 34 "..\..\Views\Category\List.cshtml"
               Write(Html.DisplayNameFor(model => model.IsActive));

            #line default
            #line hidden
WriteLiteral("\r\n                	\r\n\r\n                	\r\n
\r\n\r\n");

            #line 40 "..\..\Views\Category\List.cshtml"

            #line default
            #line hidden

            #line 40 "..\..\Views\Category\List.cshtml"
             foreach (var item in Model)
            {

            #line default
            #line hidden
WriteLiteral("
\r\n\r\n\r\n                    \r\n");

WriteLiteral("                        ");

            #line 46 "..\..\Views\Category\List.cshtml"
                   Write(Html.DisplayFor(modelItem => item.Title));

            #line default
            #line hidden
WriteLiteral("\r\n                    	\r\n\r\n\r\n                    \r\n");

WriteLiteral("                        ");

            #line 51 "..\..\Views\Category\List.cshtml"
                   Write(Html.DisplayFor(modelItem => item.Description));

            #line default
            #line hidden
WriteLiteral("\r\n                    	\r\n\r\n                    \r\n");

WriteLiteral("                        ");

            #line 55 "..\..\Views\Category\List.cshtml"
                   Write(Html.DisplayFor(modelItem => item.IsActive));

            #line default
            #line hidden
WriteLiteral("\r\n                    	\r\n\r\n                    \r\n                        " +
"\r\n                        <a");

WriteLiteral(" class=\"btn-sm btn btn-default\"");

WriteAttribute("href", Tuple.Create(" href=\"", 1312), Tuple.Create("\"", 1358)

            #line 60 "..\..\Views\Category\List.cshtml"
, Tuple.Create(Tuple.Create("", 1319), Tuple.Create<System.Object, System.Int32>(Url.Action(MVC.Category.Edit(item.Id))

            #line default
            #line hidden
, 1319), false)
);

WriteLiteral("\r\n                           type=\"button\"");

WriteLiteral(">\r\n                            \r\n                            ویرایش\r\n                        \r\n        " +
"                |\r\n                        <a");

WriteLiteral(" class=\"btn-sm btn btn-default\"");

WriteAttribute("href", Tuple.Create(" href=\"", 1610), Tuple.Create("\"", 1659)

            #line 66 "..\..\Views\Category\List.cshtml"
, Tuple.Create(Tuple.Create("", 1617), Tuple.Create<System.Object, System.Int32>(Url.Action(MVC.Category.Details(item.Id))

            #line default
            #line hidden
, 1617), false)
);

WriteLiteral("\r\n                           type=\"button\"");

WriteLiteral(">\r\n                            \r\n                            جزییات\r\n                        \r\n        " +
"                |\r\n                        <a");

WriteLiteral(" class=\"btn-sm btn btn-danger\"");

WriteAttribute("href", Tuple.Create(" href=\"", 1917), Tuple.Create("\"", 1965)

            #line 72 "..\..\Views\Category\List.cshtml"
, Tuple.Create(Tuple.Create("", 1924), Tuple.Create<System.Object, System.Int32>(Url.Action(MVC.Category.Delete(item.Id))

            #line default
            #line hidden
, 1924), false)
);

WriteLiteral("\r\n                           type=\"button\"");

WriteLiteral(">\r\n                            \r\n                            حذف\r\n                        \r\n\r\n         " +
"           	\r\n\r\n
\r\n");

            #line 81 "..\..\Views\Category\List.cshtml"
            }

            #line default
            #line hidden
WriteLiteral("\r\n
\r\n\r\n\r\n\r\n
\r\n\r\n\r\n
\r\n
\r\n
\r\n");

WriteLiteral("                ");

            #line 93 "..\..\Views\Category\List.cshtml"
           Write(Html.ActionLink("ایجاد جدید", "Create", new { Controller = "Category" }, new { @class = "btn btn-primary" }));

            #line default
            #line hidden
WriteLiteral("\r\n
\r\n
\r\n");

WriteLiteral("                ");

            #line 96 "..\..\Views\Category\List.cshtml"
           Write(Html.ActionLink("مشاهده دسته ها", "Item", new {Controller = "Category"}, new {@class = "btn btn-default"}));

            #line default
            #line hidden
WriteLiteral("\r\n
\r\n\r\n
\r\n
\r\n
\r\n");

        }
    }
}
#pragma warning restore 1591


text:
\hypertarget{group___r_c_c_ex___a_h_b1___low_power___enable___disable}{}\section{A\+H\+B1 Peripheral Low Power Enable Disable}
\label{group___r_c_c_ex___a_h_b1___low_power___enable___disable}\index{A\+H\+B1 Peripheral Low Power Enable Disable@{A\+H\+B1 Peripheral Low Power Enable Disable}}

Enable or disable the A\+H\+B1 peripheral clock during Low Power (Sleep) mode.

Enable or disable the A\+H\+B1 peripheral clock during Low Power (Sleep) mode.

\begin{DoxyNote}{Note}
Peripheral clock gating in S\+L\+E\+EP mode can be used to further reduce power consumption.

After wakeup from S\+L\+E\+EP mode, the peripheral clock is enabled again.

By default, all peripheral clocks are enabled during S\+L\+E\+EP mode.
\end{DoxyNote}


text:
#ifndef QABSTRACTSCROLLAREA_H
#define QABSTRACTSCROLLAREA_H

#include <QtWidgets/qframe.h>

QT_BEGIN_NAMESPACE

#ifndef QT_NO_SCROLLAREA

class QMargins;
class QScrollBar;
class QAbstractScrollAreaPrivate;

class Q_WIDGETS_EXPORT QAbstractScrollArea : public QFrame
{
    Q_OBJECT

    Q_PROPERTY(Qt::ScrollBarPolicy verticalScrollBarPolicy READ verticalScrollBarPolicy WRITE setVerticalScrollBarPolicy)
    Q_PROPERTY(Qt::ScrollBarPolicy horizontalScrollBarPolicy READ horizontalScrollBarPolicy WRITE setHorizontalScrollBarPolicy)
    Q_PROPERTY(SizeAdjustPolicy sizeAdjustPolicy READ sizeAdjustPolicy WRITE setSizeAdjustPolicy)

public:
    explicit QAbstractScrollArea(QWidget* parent=0);
    ~QAbstractScrollArea();

    enum SizeAdjustPolicy {
        AdjustIgnored,
        AdjustToContentsOnFirstShow,
        AdjustToContents
    };
    Q_ENUM(SizeAdjustPolicy)

    Qt::ScrollBarPolicy verticalScrollBarPolicy() const;
    void setVerticalScrollBarPolicy(Qt::ScrollBarPolicy);
    QScrollBar *verticalScrollBar() const;
    void setVerticalScrollBar(QScrollBar *scrollbar);

    Qt::ScrollBarPolicy horizontalScrollBarPolicy() const;
    void setHorizontalScrollBarPolicy(Qt::ScrollBarPolicy);
    QScrollBar *horizontalScrollBar() const;
    void setHorizontalScrollBar(QScrollBar *scrollbar);

    QWidget *cornerWidget() const;
    void setCornerWidget(QWidget *widget);

    void addScrollBarWidget(QWidget *widget, Qt::Alignment alignment);
    QWidgetList scrollBarWidgets(Qt::Alignment alignment);

    QWidget *viewport() const;
    void setViewport(QWidget *widget);
    QSize maximumViewportSize() const;

    QSize minimumSizeHint() const Q_DECL_OVERRIDE;

    QSize sizeHint() const Q_DECL_OVERRIDE;

    virtual void setupViewport(QWidget *viewport);

    SizeAdjustPolicy sizeAdjustPolicy() const;
    void setSizeAdjustPolicy(SizeAdjustPolicy policy);

protected:
    QAbstractScrollArea(QAbstractScrollAreaPrivate &dd, QWidget *parent = 0);
    void setViewportMargins(int left, int top, int right, int bottom);
    void setViewportMargins(const QMargins &margins);
    QMargins viewportMargins() const;

    bool eventFilter(QObject *, QEvent *) Q_DECL_OVERRIDE;
    bool event(QEvent *) Q_DECL_OVERRIDE;
    virtual bool viewportEvent(QEvent *);

    void resizeEvent(QResizeEvent *) Q_DECL_OVERRIDE;
    void paintEvent(QPaintEvent *) Q_DECL_OVERRIDE;
    void mousePressEvent(QMouseEvent *) Q_DECL_OVERRIDE;
    void mouseReleaseEvent(QMouseEvent *) Q_DECL_OVERRIDE;
    void mouseDoubleClickEvent(QMouseEvent *) Q_DECL_OVERRIDE;
    void mouseMoveEvent(QMouseEvent *) Q_DECL_OVERRIDE;
#ifndef QT_NO_WHEELEVENT
    void wheelEvent(QWheelEvent *) Q_DECL_OVERRIDE;
#endif
#ifndef QT_NO_CONTEXTMENU
    void contextMenuEvent(QContextMenuEvent *) Q_DECL_OVERRIDE;
#endif
#ifndef QT_NO_DRAGANDDROP
    void dragEnterEvent(QDragEnterEvent *) Q_DECL_OVERRIDE;
    void dragMoveEvent(QDragMoveEvent *) Q_DECL_OVERRIDE;
    void dragLeaveEvent(QDragLeaveEvent *) Q_DECL_OVERRIDE;
    void dropEvent(QDropEvent *) Q_DECL_OVERRIDE;
#endif

    void keyPressEvent(QKeyEvent *) Q_DECL_OVERRIDE;

    virtual void scrollContentsBy(int dx, int dy);

    virtual QSize viewportSizeHint() const;

private:
    Q_DECLARE_PRIVATE(QAbstractScrollArea)
    Q_DISABLE_COPY(QAbstractScrollArea)
    Q_PRIVATE_SLOT(d_func(), void _q_hslide(int))
    Q_PRIVATE_SLOT(d_func(), void _q_vslide(int))
    Q_PRIVATE_SLOT(d_func(), void _q_showOrHideScrollBars())

    friend class QStyleSheetStyle;
    friend class QWidgetPrivate;
};

#endif // QT_NO_SCROLLAREA

QT_END_NAMESPACE

#endif // QABSTRACTSCROLLAREA_H


text:
package org.yeshen.video.librtmp.unstable.net.sender.local;

import android.os.Environment;

import org.yeshen.video.librtmp.unstable.net.sender.Sender;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @Title: LocalSender
 * @Package org.yeshen.video.librtmp.afix.net.sender.local
 * @Description:
 * @Author Jim
 * @Date 16/9/18
 * @Time 下午5:10
 * @Version
 */
public class LocalSender implements Sender{
    private File mTestFile;
    private FileOutputStream mOutStream;
    private static BufferedOutputStream mBuffer;

    @Override
    public void start() {
        String sdcardPath = Environment.getExternalStorageDirectory().toString();
        mTestFile = new File(sdcardPath+"/SopCast.flv");

        if(mTestFile.exists()){
            mTestFile.delete();
        }

        try {
            mTestFile.createNewFile();
            mOutStream = new FileOutputStream(mTestFile);
            mBuffer = new BufferedOutputStream(mOutStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onData(byte[] data, int type) {
        if (mBuffer != null){
            try {
                mBuffer.write(data);
                mBuffer.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void stop() {
        if(mBuffer != null) {
            try {
                mBuffer.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            mBuffer = null;
        }
        if(mOutStream != null) {
            try {
                mOutStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            mBuffer = null;
            mOutStream = null;
        }
    }
}


text:
package org.apache.phoenix.client;

import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.KeyValue.Type;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;

import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData;

/**
 * A {@link KeyValueBuilder} that builds {@link ClientKeyValue}, eliminating the extra byte copies
 * inherent in the standard {@link KeyValue} implementation.
 * <p>
 * This {@link KeyValueBuilder} is only supported in HBase 0.94.14+ (
 * {@link PhoenixDatabaseMetaData#CLIENT_KEY_VALUE_BUILDER_THRESHOLD}), with the addition of
 * HBASE-9834.
 */
public class ClientKeyValueBuilder extends KeyValueBuilder {

    public static final KeyValueBuilder INSTANCE = new ClientKeyValueBuilder();

  private ClientKeyValueBuilder() {
    // private ctor for singleton
  }

  @Override
  public KeyValue buildPut(ImmutableBytesWritable row, ImmutableBytesWritable family,
      ImmutableBytesWritable qualifier, long ts, ImmutableBytesWritable value) {
    return new ClientKeyValue(row, family, qualifier, ts, Type.Put, value);
  }

  @Override
  public KeyValue buildDeleteFamily(ImmutableBytesWritable row, ImmutableBytesWritable family,
            ImmutableBytesWritable qualifier, long ts) {
        return new ClientKeyValue(row, family, qualifier, ts, Type.DeleteFamily, null);
  }

  @Override
  public KeyValue buildDeleteColumns(ImmutableBytesWritable row, ImmutableBytesWritable family,
            ImmutableBytesWritable qualifier, long ts) {
        return new ClientKeyValue(row, family, qualifier, ts, Type.DeleteColumn, null);
  }

  @Override
  public KeyValue buildDeleteColumn(ImmutableBytesWritable row, ImmutableBytesWritable family,
            ImmutableBytesWritable qualifier, long ts) {
        return new ClientKeyValue(row, family, qualifier, ts, Type.Delete, null);
  }
}


text:
/**
 * A drawable single tile in the expanding brain meme.
 */

/*
 * AetheBot - A Discord Chatbot
 *
 * Created by Tyrone Trevorrow on 08/06/18.
 * Copyright (c) 2018 Tyrone Trevorrow. All rights reserved.
 *
 * This source code is licensed under the permissive MIT license.
 */

import { Image, CanvasRenderingContext2D } from "canvas"
import { Rect } from "../../util/rect"
import { Drawable } from "./drawable"

interface WrapTextResult {
    lines: string[]
    adjustedFontSize: number
}

function renderTextInRect(ctx: CanvasRenderingContext2D,
                          text: string, font: string, rect: Rect, maxFontSize?: number): void {
    // start with a large font size
    let fontSize = maxFontSize || rect.height
    let res = wrappedTextAtSize(ctx, text, font, rect.width, fontSize)
    if (!res) {
        return
    }
    let { lines, adjustedFontSize } = res
    let textHeight = 0
    fontSize = adjustedFontSize + 1

    // lower the font size until the text fits the canvas
    do {
        fontSize = fontSize - 1
        res = wrappedTextAtSize(ctx, text, font, rect.width, fontSize) as WrapTextResult
        lines = res.lines
        adjustedFontSize = res.adjustedFontSize
        if (adjustedFontSize < fontSize) {
            fontSize = adjustedFontSize
        }
        ctx.font = fontSize + " " + font
        textHeight = lines.length * fontSize
    } while (textHeight > rect.height && fontSize > 8)

    // draw the text
    const textBoxHeight = fontSize * lines.length
    const topMargin = (rect.height - textBoxHeight) / 2
    let y = topMargin + rect.y
    ctx.textBaseline = "top"
    ctx.textAlign = "center"
    for (const line of lines) {
        ctx.fillText(line, rect.x + (rect.width / 2), y)
        y = y + fontSize
    }
}

function wrappedTextAtSize(ctx: CanvasRenderingContext2D,
                           text: string, fontFace: string, maxWidth: number, fontSize: number): WrapTextResult | null {
    const words = text.split(" ")
    const lines = []
    let line = ""

    if (words.length < 1) {
        return null
    }

    // Handle if even the first word doesn't fit
    let fontDiff = 0
    let wordWidth = 0
    do {
        ctx.font = (fontSize - fontDiff) + "px " + fontFace
        wordWidth = ctx.measureText(words[0]).width
        fontDiff = fontDiff + 1
    } while (wordWidth > maxWidth && (fontSize - fontDiff) > 8)
    fontSize = fontSize - fontDiff - 1

    for (const word of words) {
        const testLine = line + word + " "
        const metrics = ctx.measureText(testLine)
        const testWidth = metrics.width
        if (testWidth > maxWidth) {
            if (line !== "") {
                lines.push(line)
            }
            line = word + " "
        } else {
            line = testLine
        }
    }
    lines.push(line)
    return {
        adjustedFontSize: fontSize,
        lines,
    }
}

export class MemeTile implements Drawable {
    public text: string
    public image: Image
    public width: number

    public get height(): number {
        const ratio = this.image.height / this.image.width
        return (this.width / 2) * ratio
    }

    public constructor(text: string, image: Image, width: number) {
        this.text = text
        this.image = image
        this.width = width
    }

    public drawInContext(ctx: CanvasRenderingContext2D, offset?: {x: number; y: number}): void {
        offset = offset || {x: 0, y: 0}
        const textRect = new Rect(offset.x, offset.y, this.width / 2, this.height)
        ctx.fillStyle = "#000"
        renderTextInRect(ctx, this.text, "Arial", textRect, 36)
        ctx.drawImage(this.image, this.width / 2, offset.y, this.width / 2, this.height)
    }
}


text:
package xxx.web.comments.clustering.tfidf;

import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
import de.tudarmstadt.ukp.dkpro.core.frequency.tfidf.TfidfAnnotator;
import de.tudarmstadt.ukp.dkpro.core.frequency.tfidf.TfidfConsumer;
import de.tudarmstadt.ukp.dkpro.core.io.xmi.XmiReader;
import org.apache.uima.fit.factory.AnalysisEngineFactory;
import org.apache.uima.fit.factory.CollectionReaderFactory;
import org.apache.uima.fit.pipeline.SimplePipeline;

/**
 * Collects tfidf
 * (c) 2015 XXX
 */
public class TfIdfAnnotatorMain
{
    private String sourceDataDir;
    private String tfidfModel;

    public void collectIdf()
            throws Exception
    {
        SimplePipeline.runPipeline(CollectionReaderFactory
                .createReaderDescription(XmiReader.class, XmiReader.PARAM_SOURCE_LOCATION,
                        sourceDataDir, XmiReader.PARAM_PATTERNS,
                        XmiReader.INCLUDE_PREFIX + "*.xmi"), AnalysisEngineFactory
                .createEngineDescription(TfidfConsumer.class, TfidfConsumer.PARAM_FEATURE_PATH,
                        Token.class.getName(), TfidfConsumer.PARAM_TARGET_LOCATION, tfidfModel));
    }

    public void annotateIdf()
            throws Exception
    {
        SimplePipeline.runPipeline(CollectionReaderFactory
                        .createReaderDescription(XmiReader.class, XmiReader.PARAM_SOURCE_LOCATION,
                                sourceDataDir, XmiReader.PARAM_PATTERNS,
                                XmiReader.INCLUDE_PREFIX + "*.xmi"), AnalysisEngineFactory
                        .createEngineDescription(TfidfAnnotator.class,
                                TfidfAnnotator.PARAM_FEATURE_PATH, Token.class.getName(),
                                TfidfAnnotator.PARAM_TF_MODE,
                                TfidfAnnotator.WeightingModeTf.LOG_PLUS_ONE,
                                TfidfAnnotator.PARAM_IDF_MODE, TfidfAnnotator.WeightingModeIdf.LOG,
                                TfidfAnnotator.PARAM_TFDF_PATH, tfidfModel));
    }

    public static void main(String[] args)
            throws Exception
    {
        TfIdfAnnotatorMain annotator = new TfIdfAnnotatorMain();
        annotator.sourceDataDir = args[0];
        annotator.tfidfModel = args[1];

        annotator.collectIdf();
        annotator.annotateIdf();
    }
}


text:
RSpec.describe ProgressMonitor::Task::PercentageCalculation::FilePosition do
  let(:calculator) { described_class.new task }
  let(:task) { instance_double ProgressMonitor::Task, file: file }
  let(:file) { instance_double File, size: file_size, pos: file_pos }
  let(:file_size) { 1000 }
  let(:file_pos) { 200 }

  describe '#perform' do
    subject(:perform) { calculator.perform }

    context 'when file is nil' do
      let(:file) { nil }

      it 'returns nil' do
        expect(perform).to eq nil
      end
    end

    context 'when file size is 0' do
      let(:file_size) { 0 }

      it 'returns nil' do
        expect(perform).to eq nil
      end
    end

    context 'when file size is nonzero' do
      let(:file_size) { 1000 }
      let(:file_pos) { 200 }

      it 'calculates percentage based on file pos' do
        expect(perform).to eq 20
      end
    end

    context 'when an error occurs' do
      before do
        allow(file).to receive(:size).and_raise
      end

      it 'returns :unknown' do
        expect(perform).to eq :unknown
      end
    end
  end
end


text:
package config

import (
	"testing"

	"github.com/ransoni/uchiwa/uchiwa/authentication"
	"github.com/stretchr/testify/assert"
)

func TestLoad(t *testing.T) {
	// Only default & config file
	conf := Load("../../fixtures/config_test.json", "")
	assert.Equal(t, 4567, conf.Sensu[0].Port)
	assert.Equal(t, 10, conf.Sensu[0].Timeout)
	assert.Equal(t, 10, conf.Uchiwa.Refresh)
	assert.Equal(t, 389, conf.Uchiwa.Ldap.Port)
	assert.Equal(t, "person", conf.Uchiwa.Ldap.UserObjectClass)
	assert.Equal(t, "default", conf.Uchiwa.Audit.Level)

	conf = Load("../../fixtures/config_test.json", "../../fixtures/conf.d")
	assert.Equal(t, 5, len(conf.Sensu))
	assert.Equal(t, 4567, conf.Sensu[0].Port)
	assert.Equal(t, 10, conf.Sensu[0].Timeout)
	assert.Equal(t, 4569, conf.Sensu[3].Port)
	assert.Equal(t, 5, conf.Sensu[3].Timeout)
	assert.Equal(t, 4567, conf.Sensu[4].Port)
	assert.Equal(t, 10, conf.Sensu[4].Timeout)

	assert.Equal(t, "192.168.0.1", conf.Uchiwa.Host)
	assert.Equal(t, 8000, conf.Uchiwa.Port)
	assert.Equal(t, 2, len(conf.Uchiwa.Users))

	// Test the removal of the Role object in configuration files
	assert.Equal(t, false, conf.Uchiwa.Users[0].Role.Readonly)
	assert.Equal(t, "foobar", conf.Uchiwa.Users[0].Role.AccessToken)
	assert.Equal(t, true, conf.Uchiwa.Users[1].Role.Readonly)

	// We should also support the dashboard attribute instead of uchiwa
	conf = Load("../../fixtures/config_dashboard.json", "")
	assert.Equal(t, "127.0.0.1", conf.Uchiwa.Host)
	assert.Equal(t, 8080, conf.Uchiwa.Port)
	assert.Equal(t, 1, len(conf.Uchiwa.Users))
	assert.Equal(t, 389, conf.Uchiwa.Ldap.Port)
	assert.Equal(t, "person", conf.Uchiwa.Ldap.UserObjectClass)
}

func TestLoadDirectories(t *testing.T) {
	conf := loadDirectories("foobar,../../fixtures/conf.d")

	assert.Equal(t, 3, len(conf.Sensu))
	assert.Equal(t, "us-east-2", conf.Sensu[0].Name)
	assert.Equal(t, "us-west-2", conf.Sensu[1].Name)
	assert.Equal(t, "us-east-3", conf.Sensu[2].Name)

	assert.Equal(t, 2, len(conf.Uchiwa.Users))
	assert.Equal(t, "admin", conf.Uchiwa.Users[0].Username)
	assert.Equal(t, "readonly", conf.Uchiwa.Users[1].Username)
	assert.Equal(t, "192.168.0.1", conf.Uchiwa.Host)
	assert.Equal(t, 8000, conf.Uchiwa.Port)
}

func TestLoadFile(t *testing.T) {
	_, err := loadFile("foo.bar")
	assert.NotNil(t, err, "foo.bar does not exist")

	_, err = loadFile("config.go")
	assert.NotNil(t, err, "config.go is not a JSON file")

	conf, err := loadFile("../../fixtures/config_test.json")
	assert.Nil(t, err, "got unexpected error: %s", err)

	// Sensu APIs
	assert.Equal(t, 2, len(conf.Sensu))
	assert.Equal(t, "us-east-1", conf.Sensu[0].Name)
	assert.Equal(t, "us-west-1", conf.Sensu[1].Name)
	assert.Equal(t, 4570, conf.Sensu[1].Port)
	assert.Equal(t, 5, conf.Sensu[1].Timeout)

	// Uchiwa
	assert.Equal(t, "0.0.0.0", conf.Uchiwa.Host)
	assert.Equal(t, 8080, conf.Uchiwa.Port)
	assert.Equal(t, "foo", conf.Uchiwa.User)
	assert.Equal(t, "bar", conf.Uchiwa.Pass)
}

func TestInitSensu(t *testing.T) {
	apis := []SensuConfig{
		SensuConfig{Host: "10.0.0.1", Port: 4567},
		SensuConfig{Name: "test/1", Host: "10.0.10.1", Port: 4567, Ssl: true},
	}

	sensu := initSensu(apis)
	assert.NotEqual(t, "", sensu[0].Name)
	assert.Equal(t, "http://10.0.0.1:4567", sensu[0].URL)
	assert.Equal(t, "test1", sensu[1].Name)
	assert.Equal(t, "https://10.0.10.1:4567", sensu[1].URL)
}

func TestInitUchiwa(t *testing.T) {
	conf := GlobalConfig{Github: Github{Server: "127.0.0.1"}}
	uchiwa := initUchiwa(conf)
	assert.Equal(t, "github", uchiwa.Auth.Driver)

	conf = GlobalConfig{Gitlab: Gitlab{Server: "127.0.0.1"}}
	uchiwa = initUchiwa(conf)
	assert.Equal(t, "gitlab", uchiwa.Auth.Driver)

	conf = GlobalConfig{Ldap: Ldap{BaseDN: "cn=foo", Server: "127.0.0.1"}}
	uchiwa = initUchiwa(conf)
	assert.Equal(t, "ldap", uchiwa.Auth.Driver)
	assert.Equal(t, Ldap{BaseDN: "cn=foo", GroupBaseDN: "cn=foo", UserBaseDN: "cn=foo", Server: "127.0.0.1"}, uchiwa.Ldap)

	conf = GlobalConfig{Db: Db{Driver: "mysql", Scheme: "foo"}}
	uchiwa = initUchiwa(conf)
	assert.Equal(t, "sql", uchiwa.Auth.Driver)

	conf = GlobalConfig{Users: []authentication.User{authentication.User{ID: 1}}}
	uchiwa = initUchiwa(conf)
	assert.Equal(t, "simple", uchiwa.Auth.Driver)

	conf = GlobalConfig{User: "foo", Pass: "secret"}
	uchiwa = initUchiwa(conf)
	assert.Equal(t, "simple", uchiwa.Auth.Driver)
	assert.Equal(t, []authentication.User{authentication.User{ID: 0, FullName: "foo", Password: "secret", Username: "foo"}}, uchiwa.Users)
}

func TestGetPublic(t *testing.T) {
	conf := Config{
		Sensu: []SensuConfig{
			SensuConfig{
				User: "foo",
				Pass: "secret",
			},
		},
		Uchiwa: GlobalConfig{
			User:   "foo",
			Pass:   "secret",
			Users:  []authentication.User{authentication.User{ID: 1}},
			Db:     Db{Scheme: "foo"},
			Github: Github{ClientID: "foo", ClientSecret: "secret"},
			Ldap:   Ldap{BindPass: "secret"},
		},
	}

	pubConf := conf.GetPublic()

	assert.NotEqual(t, conf, pubConf)

	assert.Equal(t, "foo", conf.Sensu[0].User)
	assert.Equal(t, "secret", conf.Sensu[0].Pass)
	assert.Equal(t, "foo", conf.Uchiwa.User)
	assert.Equal(t, "secret", conf.Uchiwa.Pass)

	assert.Equal(t, "*****", pubConf.Sensu[0].User)
	assert.Equal(t, "*****", pubConf.Sensu[0].Pass)
	assert.Equal(t, "*****", pubConf.Uchiwa.User)
	assert.Equal(t, "*****", pubConf.Uchiwa.Pass)
	assert.Equal(t, []authentication.User{}, pubConf.Uchiwa.Users)
	assert.Equal(t, "*****", pubConf.Uchiwa.Db.Scheme)
	assert.Equal(t, "*****", pubConf.Uchiwa.Github.ClientID)
	assert.Equal(t, "*****", pubConf.Uchiwa.Github.ClientSecret)
	assert.Equal(t, "*****", pubConf.Uchiwa.Ldap.BindPass)
}


text:
package org.apache.hadoop.hbase.regionserver;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.ByteBufferKeyValue;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.exceptions.UnexpectedStateException;
import org.apache.hadoop.hbase.io.util.MemorySizeUtil;
import org.apache.hadoop.hbase.regionserver.ChunkCreator.ChunkType;
import org.apache.hadoop.hbase.testclassification.RegionServerTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;

/**
 * Test the {@link org.apache.hadoop.hbase.regionserver.ChunkCreator.MemStoreChunkPool} class
 */
@Category({ RegionServerTests.class, SmallTests.class })
public class TestMemStoreChunkPool {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
    HBaseClassTestRule.forClass(TestMemStoreChunkPool.class);

  private final static Configuration conf = new Configuration();
  private static ChunkCreator chunkCreator;
  private static boolean chunkPoolDisabledBeforeTest;

  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    conf.setBoolean(MemStoreLAB.USEMSLAB_KEY, true);
    conf.setFloat(MemStoreLAB.CHUNK_POOL_MAXSIZE_KEY, 0.2f);
    chunkPoolDisabledBeforeTest = ChunkCreator.chunkPoolDisabled;
    ChunkCreator.chunkPoolDisabled = false;
    long globalMemStoreLimit =
      (long) (ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax()
        * MemorySizeUtil.getGlobalMemStoreHeapPercent(conf, false));
    chunkCreator = ChunkCreator.initialize(MemStoreLAB.CHUNK_SIZE_DEFAULT, false,
      globalMemStoreLimit, 0.2f, MemStoreLAB.POOL_INITIAL_SIZE_DEFAULT, null,
      MemStoreLAB.INDEX_CHUNK_SIZE_PERCENTAGE_DEFAULT);
    assertNotNull(chunkCreator);
  }

  @AfterClass
  public static void tearDownAfterClass() throws Exception {
    ChunkCreator.chunkPoolDisabled = chunkPoolDisabledBeforeTest;
  }

  @After
  public void tearDown() throws Exception {
    chunkCreator.clearChunksInPool();
  }

  @Test
  public void testReusingChunks() {
    MemStoreLAB mslab = new MemStoreLABImpl(conf);
    int expectedOff = 0;
    ByteBuffer lastBuffer = null;
    final byte[] rk = Bytes.toBytes("r1");
    final byte[] cf = Bytes.toBytes("f");
    final byte[] q = Bytes.toBytes("q");
    // Randomly allocate some bytes
    final Random rand = ThreadLocalRandom.current();
    for (int i = 0; i < 100; i++) {
      int valSize = rand.nextInt(1000);
      KeyValue kv = new KeyValue(rk, cf, q, new byte[valSize]);
      int size = kv.getSerializedSize();
      ByteBufferKeyValue newKv = (ByteBufferKeyValue) mslab.copyCellInto(kv);
      if (newKv.getBuffer() != lastBuffer) {
        expectedOff = 4;
        lastBuffer = newKv.getBuffer();
      }
      assertEquals(expectedOff, newKv.getOffset());
      assertTrue("Allocation overruns buffer",
        newKv.getOffset() + size <= newKv.getBuffer().capacity());
      expectedOff += size;
    }
    // chunks will be put back to pool after close
    mslab.close();
    int chunkCount = chunkCreator.getPoolSize();
    assertTrue(chunkCount > 0);
    // reconstruct mslab
    mslab = new MemStoreLABImpl(conf);
    // chunk should be got from the pool, so we can reuse it.
    KeyValue kv = new KeyValue(rk, cf, q, new byte[10]);
    mslab.copyCellInto(kv);
    assertEquals(chunkCount - 1, chunkCreator.getPoolSize());
  }

  @Test
  public void testPuttingBackChunksAfterFlushing() throws UnexpectedStateException {
    byte[] row = Bytes.toBytes("testrow");
    byte[] fam = Bytes.toBytes("testfamily");
    byte[] qf1 = Bytes.toBytes("testqualifier1");
    byte[] qf2 = Bytes.toBytes("testqualifier2");
    byte[] qf3 = Bytes.toBytes("testqualifier3");
    byte[] qf4 = Bytes.toBytes("testqualifier4");
    byte[] qf5 = Bytes.toBytes("testqualifier5");
    byte[] val = Bytes.toBytes("testval");

    DefaultMemStore memstore = new DefaultMemStore();

    // Setting up memstore
    memstore.add(new KeyValue(row, fam, qf1, val), null);
    memstore.add(new KeyValue(row, fam, qf2, val), null);
    memstore.add(new KeyValue(row, fam, qf3, val), null);

    // Creating a snapshot
    MemStoreSnapshot snapshot = memstore.snapshot();
    assertEquals(3, memstore.getSnapshot().getCellsCount());

    // Adding value to "new" memstore
    assertEquals(0, memstore.getActive().getCellsCount());
    memstore.add(new KeyValue(row, fam, qf4, val), null);
    memstore.add(new KeyValue(row, fam, qf5, val), null);
    assertEquals(2, memstore.getActive().getCellsCount());
    // close the scanner - this is how the snapshot will be used
    for (KeyValueScanner scanner : snapshot.getScanners()) {
      scanner.close();
    }
    memstore.clearSnapshot(snapshot.getId());

    int chunkCount = chunkCreator.getPoolSize();
    assertTrue(chunkCount > 0);

  }

  @Test
  public void testPuttingBackChunksWithOpeningScanner() throws IOException {
    byte[] row = Bytes.toBytes("testrow");
    byte[] fam = Bytes.toBytes("testfamily");
    byte[] qf1 = Bytes.toBytes("testqualifier1");
    byte[] qf2 = Bytes.toBytes("testqualifier2");
    byte[] qf3 = Bytes.toBytes("testqualifier3");
    byte[] qf4 = Bytes.toBytes("testqualifier4");
    byte[] qf5 = Bytes.toBytes("testqualifier5");
    byte[] qf6 = Bytes.toBytes("testqualifier6");
    byte[] qf7 = Bytes.toBytes("testqualifier7");
    byte[] val = Bytes.toBytes("testval");

    DefaultMemStore memstore = new DefaultMemStore();

    // Setting up memstore
    memstore.add(new KeyValue(row, fam, qf1, val), null);
    memstore.add(new KeyValue(row, fam, qf2, val), null);
    memstore.add(new KeyValue(row, fam, qf3, val), null);

    // Creating a snapshot
    MemStoreSnapshot snapshot = memstore.snapshot();
    assertEquals(3, memstore.getSnapshot().getCellsCount());

    // Adding value to "new" memstore
    assertEquals(0, memstore.getActive().getCellsCount());
    memstore.add(new KeyValue(row, fam, qf4, val), null);
    memstore.add(new KeyValue(row, fam, qf5, val), null);
    assertEquals(2, memstore.getActive().getCellsCount());

    // opening scanner before clear the snapshot
    List<KeyValueScanner> scanners = memstore.getScanners(0);
    // Shouldn't putting back the chunks to pool,since some scanners are opening
    // based on their data
    // close the snapshot scanner
    for (KeyValueScanner scanner : snapshot.getScanners()) {
      scanner.close();
    }
    memstore.clearSnapshot(snapshot.getId());

    assertTrue(chunkCreator.getPoolSize() == 0);

    // Chunks will be put back to pool after close scanners;
    for (KeyValueScanner scanner : scanners) {
      scanner.close();
    }
    assertTrue(chunkCreator.getPoolSize() > 0);

    // clear chunks
    chunkCreator.clearChunksInPool();

    // Creating another snapshot
    snapshot = memstore.snapshot();
    // Adding more value
    memstore.add(new KeyValue(row, fam, qf6, val), null);
    memstore.add(new KeyValue(row, fam, qf7, val), null);
    // opening scanners
    scanners = memstore.getScanners(0);
    // close scanners before clear the snapshot
    for (KeyValueScanner scanner : scanners) {
      scanner.close();
    }
    // Since no opening scanner, the chunks of snapshot should be put back to
    // pool
    // close the snapshot scanners
    for (KeyValueScanner scanner : snapshot.getScanners()) {
      scanner.close();
    }
    memstore.clearSnapshot(snapshot.getId());
    assertTrue(chunkCreator.getPoolSize() > 0);
  }

  @Test
  public void testPutbackChunksMultiThreaded() throws Exception {
    final int maxCount = 10;
    final int initialCount = 5;
    final int chunkSize = 40;
    final int valSize = 7;
    ChunkCreator oldCreator = ChunkCreator.getInstance();
    ChunkCreator newCreator = new ChunkCreator(chunkSize, false, 400, 1, 0.5f, null, 0);
    assertEquals(initialCount, newCreator.getPoolSize());
    assertEquals(maxCount, newCreator.getMaxCount());
    // Replace the global ref with the new one we created.
    // Used it for the testing. Later in finally we put
    // back the original
    ChunkCreator.instance = newCreator;

    final KeyValue kv =
      new KeyValue(Bytes.toBytes("r"), Bytes.toBytes("f"), Bytes.toBytes("q"), new byte[valSize]);
    final AtomicReference<Throwable> exceptionRef = new AtomicReference<Throwable>();
    try {
      Runnable r = new Runnable() {
        @Override
        public void run() {
          try {
            MemStoreLAB memStoreLAB = new MemStoreLABImpl(conf);
            for (int i = 0; i < maxCount; i++) {
              // Try allocate size = chunkSize. Means every
              // allocate call will result in a new chunk
              memStoreLAB.copyCellInto(kv);
            }
            // Close MemStoreLAB so that all chunks will be tried to be put back to pool
            memStoreLAB.close();
          } catch (Throwable execption) {
            exceptionRef.set(execption);
          }
        }
      };
      Thread t1 = new Thread(r);
      Thread t2 = new Thread(r);
      Thread t3 = new Thread(r);
      t1.start();
      t2.start();
      t3.start();
      t1.join();
      t2.join();
      t3.join();
      assertTrue(exceptionRef.get() == null);
      assertTrue(newCreator.getPoolSize() <= maxCount && newCreator.getPoolSize() > 0);
    } finally {
      ChunkCreator.instance = oldCreator;
    }
  }

  // This test is for HBASE-26142, which throws NPE when indexChunksPool is null.
  @Test
  public void testNoIndexChunksPoolOrNoDataChunksPool() throws Exception {
    final int maxCount = 10;
    final int initialCount = 5;
    final int newChunkSize = 40;
    final int valSize = 7;

    ChunkCreator oldCreator = ChunkCreator.getInstance();
    try {
      // Test dataChunksPool is not null and indexChunksPool is null
      ChunkCreator newCreator = new ChunkCreator(newChunkSize, false, 400, 1, 0.5f, null, 0);
      assertEquals(initialCount, newCreator.getPoolSize());
      assertEquals(0, newCreator.getPoolSize(ChunkType.INDEX_CHUNK));
      assertEquals(maxCount, newCreator.getMaxCount());
      assertEquals(0, newCreator.getMaxCount(ChunkType.INDEX_CHUNK));
      assertTrue(newCreator.getDataChunksPool() != null);
      assertTrue(newCreator.getIndexChunksPool() == null);
      ChunkCreator.instance = newCreator;
      final KeyValue kv =
        new KeyValue(Bytes.toBytes("r"), Bytes.toBytes("f"), Bytes.toBytes("q"), new byte[valSize]);

      MemStoreLAB memStoreLAB = new MemStoreLABImpl(conf);
      memStoreLAB.copyCellInto(kv);
      memStoreLAB.close();
      assertEquals(initialCount, newCreator.getPoolSize());
      assertEquals(0, newCreator.getPoolSize(ChunkType.INDEX_CHUNK));

      Chunk dataChunk = newCreator.getChunk();
      assertTrue(dataChunk.isDataChunk());
      assertTrue(dataChunk.isFromPool());
      assertEquals(initialCount - 1, newCreator.getPoolSize());
      assertEquals(0, newCreator.getPoolSize(ChunkType.INDEX_CHUNK));
      newCreator.putbackChunks(Collections.singleton(dataChunk.getId()));
      assertEquals(initialCount, newCreator.getPoolSize());
      assertEquals(0, newCreator.getPoolSize(ChunkType.INDEX_CHUNK));

      // We set ChunkCreator.indexChunkSize to 0, but we want to get a IndexChunk
      try {
        newCreator.getChunk(ChunkType.INDEX_CHUNK);
        fail();
      } catch (IllegalArgumentException e) {
      }

      Chunk jumboChunk = newCreator.getJumboChunk(newChunkSize + 10);
      assertTrue(jumboChunk.isJumbo());
      assertTrue(!jumboChunk.isFromPool());
      assertEquals(initialCount, newCreator.getPoolSize());
      assertEquals(0, newCreator.getPoolSize(ChunkType.INDEX_CHUNK));

      // Test both dataChunksPool and indexChunksPool are null
      newCreator = new ChunkCreator(newChunkSize, false, 400, 0, 0.5f, null, 0);
      assertEquals(0, newCreator.getPoolSize());
      assertEquals(0, newCreator.getPoolSize(ChunkType.INDEX_CHUNK));
      assertEquals(0, newCreator.getMaxCount());
      assertEquals(0, newCreator.getMaxCount(ChunkType.INDEX_CHUNK));
      assertTrue(newCreator.getDataChunksPool() == null);
      assertTrue(newCreator.getIndexChunksPool() == null);
      ChunkCreator.instance = newCreator;

      memStoreLAB = new MemStoreLABImpl(conf);
      memStoreLAB.copyCellInto(kv);
      memStoreLAB.close();
      assertEquals(0, newCreator.getPoolSize());
      assertEquals(0, newCreator.getPoolSize(ChunkType.INDEX_CHUNK));

      dataChunk = newCreator.getChunk();
      assertTrue(dataChunk.isDataChunk());
      assertTrue(!dataChunk.isFromPool());
      assertEquals(0, newCreator.getPoolSize());
      assertEquals(0, newCreator.getPoolSize(ChunkType.INDEX_CHUNK));

      try {
        // We set ChunkCreator.indexChunkSize to 0, but we want to get a IndexChunk
        newCreator.getChunk(ChunkType.INDEX_CHUNK);
        fail();
      } catch (IllegalArgumentException e) {
      }

      jumboChunk = newCreator.getJumboChunk(newChunkSize + 10);
      assertTrue(jumboChunk.isJumbo());
      assertTrue(!jumboChunk.isFromPool());
      assertEquals(0, newCreator.getPoolSize());
      assertEquals(0, newCreator.getPoolSize(ChunkType.INDEX_CHUNK));

      // Test dataChunksPool is null and indexChunksPool is not null
      newCreator = new ChunkCreator(newChunkSize, false, 400, 1, 0.5f, null, 1);
      assertEquals(0, newCreator.getPoolSize());
      assertEquals(initialCount, newCreator.getPoolSize(ChunkType.INDEX_CHUNK));
      assertEquals(0, newCreator.getMaxCount());
      assertEquals(maxCount, newCreator.getMaxCount(ChunkType.INDEX_CHUNK));
      assertTrue(newCreator.getDataChunksPool() == null);
      assertTrue(newCreator.getIndexChunksPool() != null);
      assertEquals(newCreator.getChunkSize(ChunkType.DATA_CHUNK),
        newCreator.getChunkSize(ChunkType.INDEX_CHUNK));
      ChunkCreator.instance = newCreator;

      memStoreLAB = new MemStoreLABImpl(conf);
      memStoreLAB.copyCellInto(kv);
      memStoreLAB.close();
      assertEquals(0, newCreator.getPoolSize());
      assertEquals(initialCount, newCreator.getPoolSize(ChunkType.INDEX_CHUNK));

      dataChunk = newCreator.getChunk();
      assertTrue(dataChunk.isDataChunk());
      assertTrue(!dataChunk.isFromPool());
      assertEquals(0, newCreator.getPoolSize());
      assertEquals(initialCount, newCreator.getPoolSize(ChunkType.INDEX_CHUNK));

      Chunk indexChunk = newCreator.getChunk(ChunkType.INDEX_CHUNK);
      assertEquals(0, newCreator.getPoolSize());
      assertEquals(initialCount - 1, newCreator.getPoolSize(ChunkType.INDEX_CHUNK));
      assertTrue(indexChunk.isIndexChunk());
      assertTrue(indexChunk.isFromPool());
      newCreator.putbackChunks(Collections.singleton(indexChunk.getId()));
      assertEquals(0, newCreator.getPoolSize());
      assertEquals(initialCount, newCreator.getPoolSize(ChunkType.INDEX_CHUNK));

      jumboChunk = newCreator.getJumboChunk(newChunkSize + 10);
      assertTrue(jumboChunk.isJumbo());
      assertTrue(!jumboChunk.isFromPool());
      assertEquals(0, newCreator.getPoolSize());
      assertEquals(initialCount, newCreator.getPoolSize(ChunkType.INDEX_CHUNK));
    } finally {
      ChunkCreator.instance = oldCreator;
    }

    // Test both dataChunksPool and indexChunksPool are not null
    assertTrue(ChunkCreator.getInstance().getDataChunksPool() != null);
    assertTrue(ChunkCreator.getInstance().getIndexChunksPool() != null);
    Chunk dataChunk = ChunkCreator.getInstance().getChunk();
    assertTrue(dataChunk.isDataChunk());
    assertTrue(dataChunk.isFromPool());
    Chunk indexChunk = ChunkCreator.getInstance().getChunk(ChunkType.INDEX_CHUNK);
    assertTrue(indexChunk.isIndexChunk());
    assertTrue(indexChunk.isFromPool());
    Chunk jumboChunk =
      ChunkCreator.getInstance().getJumboChunk(ChunkCreator.getInstance().getChunkSize() + 10);
    assertTrue(jumboChunk.isJumbo());
    assertTrue(!jumboChunk.isFromPool());
  }
}


text:
<?php

namespace Oro\Bundle\CalendarBundle\Model\Recurrence;

use Oro\Bundle\CalendarBundle\Entity;
use Oro\Bundle\CalendarBundle\Model\Recurrence;

class DailyStrategy extends AbstractStrategy
{
    /**
     * {@inheritdoc}
     */
    public function getOccurrences(Entity\Recurrence $recurrence, \DateTime $start, \DateTime $end)
    {
        $result = [];
        $occurrenceDate = $recurrence->getStartTime();
        $fromStartInterval = 1;
        if ($start > $occurrenceDate) {
            $dateInterval = $start->diff($occurrenceDate);
            $fromStartInterval = floor($dateInterval->format('%a') / $recurrence->getInterval());
            $occurrenceDate = $this->getNextOccurrence(
                $fromStartInterval++ * $recurrence->getInterval(),
                $occurrenceDate
            );
        }

        $occurrences = $recurrence->getOccurrences();
        while ($occurrenceDate <= $recurrence->getCalculatedEndTime()
            && $occurrenceDate <= $end
            && ($occurrences === null || $fromStartInterval <= $occurrences)
        ) {
            if ($occurrenceDate >= $start) {
                $result[] = $occurrenceDate;
            }
            $fromStartInterval++;
            $occurrenceDate = $this->getNextOccurrence($recurrence->getInterval(), $occurrenceDate);
        }

        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function supports(Entity\Recurrence $recurrence)
    {
        return $recurrence->getRecurrenceType() === Recurrence::TYPE_DAILY;
    }

    /**
     * {@inheritdoc}
     */
    public function getTextValue(Entity\Recurrence $recurrence)
    {
        $interval = $recurrence->getInterval();

        return $this->getFullRecurrencePattern(
            $recurrence,
            'oro.calendar.recurrence.patterns.daily',
            $interval,
            ['%count%' => $interval]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'recurrence_daily';
    }

    /**
     * Returns occurrence date according to last occurrence date and recurrence interval.
     *
     * @param integer $interval A number of days.
     * @param \DateTime $date
     *
     * @return \DateTime
     */
    protected function getNextOccurrence($interval, \DateTime $date)
    {
        return new \DateTime("+{$interval} day {$date->format('c')}");
    }

    /**
     * {@inheritdoc}
     */
    public function getLastOccurrence(Entity\Recurrence $recurrence)
    {
        return $this->getNextOccurrence(
            $recurrence->getInterval() * ($recurrence->getOccurrences() - 1),
            $recurrence->getStartTime()
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getValidationErrorMessage(Entity\Recurrence $recurrence)
    {
        if ($recurrence->getInterval() > 99) {
            return "Parameter 'interval' can't be more than 99 for Daily recurrence pattern";
        }

        return null;
    }
}


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Organization;

class OrganizationController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $organizations = Organization::all();

        return view('organization.index', compact('organizations'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('organization.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $organization = Organization::create($request->all());

        return redirect()->route('organization.index')
                         ->with('success', sprintf('Successfully created "%s".', $organization->name));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return view('organization.show')->withOrganization(Organization::findOrFail($id));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        return view('organization.edit')->withOrganization(Organization::findOrFail($id));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $organization = Organization::findOrFail($id);

        $organization->update($request->all());

        return redirect()->route('organization.index')
                         ->with('success', sprintf('Successfully updated "%s".', $organization->name));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}


text:
import pygame
from OpenGL.GL import *
from OpenGL.GLU import *
import DevIL

pygame.init()
screen = pygame.display.set_mode((800, 600), pygame.OPENGL | pygame.DOUBLEBUF)
pygame.display.set_caption('Devil Test')

glDisable(GL_DEPTH_TEST)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluOrtho2D(0, 800, 0, 600)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glEnable(GL_TEXTURE_2D)

DevIL.ilInit()
DevIL.ilutRenderer(DevIL.ILUT_OPENGL)
texture = DevIL.ilutGLLoadImage('devil.gif')
glEnable(GL_TEXTURE_2D)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glBindTexture(GL_TEXTURE_2D, texture)

while 1:
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        break

    glClear(GL_COLOR_BUFFER_BIT)

    glBegin(GL_QUADS)
    glTexCoord2f(0, 0); glVertex2f(-400, -400);
    glTexCoord2f(5, 0); glVertex2f(1200, -400)
    glTexCoord2f(5, 5); glVertex2f(1200, 1000)
    glTexCoord2f(0, 5); glVertex2f(-400, 1000)
    glEnd()

    glTranslatef(400, 300, 0)
    glRotatef(0.5, 0, 0, 1)
    glTranslatef(-400, -300, 0)

    pygame.display.flip()


text:
#import "Private/FIRComponentType.h"

#import "Private/FIRComponentContainerInternal.h"

@implementation FIRComponentType

+ (id)instanceForProtocol:(Protocol *)protocol inContainer:(FIRComponentContainer *)container {
  // Forward the call to the container.
  return [container instanceForProtocol:protocol];
}

@end


text:
@implementation DGActivityIndicatorTripleRingsAnimation

#pragma mark -
#pragma mark DGActivityIndicatorAnimation Protocol

- (void)setupAnimationInLayer:(CALayer *)layer withSize:(CGSize)size tintColor:(UIColor *)tintColor {
    NSTimeInterval beginTime = CACurrentMediaTime();

    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0.0f, 0.0f, size.width, size.width)];
    CGFloat oX = (layer.bounds.size.width - size.width) / 2.0f;
    CGFloat oY = (layer.bounds.size.height - size.height) / 2.0f;
    for (int i = 0; i < 3; i++) {
        CAShapeLayer *circle = [CAShapeLayer layer];
        circle.path = path.CGPath;
        circle.fillColor = [UIColor clearColor].CGColor;
        circle.strokeColor = tintColor.CGColor;
        circle.frame = CGRectMake(oX, oY, size.width, size.height);
        circle.anchorPoint = CGPointMake(0.5f, 0.5f);
        circle.opacity = 1.0f;
        circle.transform = CATransform3DMakeScale(0.0f, 0.0f, 0.0f);

        CABasicAnimation *transformAnimation = [self createBasicAnimationWithKeyPath:@"transform"];
        transformAnimation.duration = 2.0f - i * 0.4f;
        transformAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1f, 0.1f, 0.0f)];
        transformAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0f, 1.0f, 0.0f)];
        transformAnimation.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseOut];

        CABasicAnimation *opacityAnimation = [self createBasicAnimationWithKeyPath:@"opacity"];
        opacityAnimation.duration = transformAnimation.duration;
        opacityAnimation.fromValue = @(1.0f);
        opacityAnimation.toValue = @(0.8f);
        opacityAnimation.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseOut];

        CAAnimationGroup *animationGroup = [self createAnimationGroup];;
        animationGroup.beginTime = beginTime + i * 0.4f;
        animationGroup.repeatCount = HUGE_VALF;
        animationGroup.duration = 2.0f;
        animationGroup.animations = @[transformAnimation, opacityAnimation];

        [layer addSublayer:circle];
        [circle addAnimation:animationGroup forKey:@"animation"];
    }
}
@end


text:
<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>A group » A subgroup module | My Project</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,600,600i%7CSource+Code+Pro:400,400i,600" />
  <link rel="stylesheet" href="m-dark+documentation.compiled.css" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

      My Project

Modules

          A group »
          A subgroup module

Subgroup brief description.

Contents

Description

Description

Subgroup description. There are no members, so there should be also no Reference section in the TOC.


text:
package org.vaadin.hackathonofthings.data;

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

public class AbstractDataSource {
	private List<DataSink> sinks = new ArrayList<DataSink>();

	public synchronized void addSink(DataSink sink) {
		sinks.add(sink);
	}

	public synchronized void removeSink(DataSink sink) {
		sinks.remove(sink);
	}

	protected synchronized List<DataSink> getSinks() {
		return new ArrayList<DataSink>(sinks);
	}

	protected void sendEvent(DataEvent event) {
		for (DataSink sink : getSinks()) {
			sink.consumeData(event);
		}
	}
}