text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<type language="gradle" name="org.gradle.api.plugins.quality.PmdExtension" version="3.0" superType="org.gradle.api.plugins.quality.CodeQualityExtension" documented="true">
    <description> Configuration options for the PMD plugin.

 (see PmdPlugin)

</description>
    <method name="getRulePriority" returnType="int">
        <description> The rule priority threshold; violations for rules with a lower priority will not be reported. Default value is 5, which means that all violations will be reported.

 This is equivalent to PMD's Ant task minimumPriority property.

 See the official documentation for the list of priorities.

 Example: rulePriority = 3

</description>
    </method>
    <method name="getRuleSetConfig" returnType="org.gradle.api.resources.TextResource">
        <description> The custom rule set to be used (if any). Replaces ruleSetFiles, except that it does not currently support multiple rule sets.

 See the official documentation for how to author a rule set.

 Example: ruleSetConfig = resources.text.fromFile("config/pmd/myRuleSet.xml")

(since 2.2)

</description>
    </method>
    <method name="getRuleSetFiles" returnType="org.gradle.api.file.FileCollection">
        <description> The custom rule set files to be used. See the official documentation for how to author a rule set file.

 Example: ruleSetFiles = files("config/pmd/myRuleSet.xml")

</description>
    </method>
    <method name="getRuleSets" returnType="java.util.List">
        <description> The built-in rule sets to be used. See the official list of built-in rule sets.

 Example: ruleSets = ["basic", "braces"]

</description>
    </method>
    <method name="getTargetJdk" returnType="org.gradle.api.plugins.quality.TargetJdk">
        <description> The target jdk to use with pmd, 1.3, 1.4, 1.5, 1.6, 1.7 or jsp

</description>
    </method>
    <method name="isConsoleOutput" returnType="boolean">
        <description> Whether or not to write PMD results to System.out.

</description>
    </method>
    <method name="ruleSetFiles" returnType="void" documented="true">
        <description> Convenience method for adding rule set files.

 Example: ruleSetFiles "config/pmd/myRuleSet.xml"

param:ruleSetFiles the rule set files to be added

</description>
        <parameter type="java.lang.Object" name="ruleSetFiles"/>
    </method>
    <method name="ruleSets" returnType="void" documented="true">
        <description> Convenience method for adding rule sets.

 Example: ruleSets "basic", "braces"

param:ruleSets the rule sets to be added

</description>
        <parameter type="java.lang.String" name="ruleSets"/>
    </method>
    <method name="setConsoleOutput" returnType="void">
        <parameter type="boolean" name="consoleOutput"/>
    </method>
    <method name="setRulePriority" returnType="void">
        <description> Sets the rule priority threshold.

</description>
        <parameter type="int" name="intValue"/>
    </method>
    <method name="setRuleSetConfig" returnType="void">
        <parameter type="org.gradle.api.resources.TextResource" name="ruleSetConfig"/>
    </method>
    <method name="setRuleSetFiles" returnType="void">
        <parameter type="org.gradle.api.file.FileCollection" name="ruleSetFiles"/>
    </method>
    <method name="setRuleSets" returnType="void">
        <parameter type="java.util.List" name="ruleSets"/>
    </method>
    <method name="setTargetJdk" returnType="void">
        <description> Sets the target jdk used with pmd.

 @value The value for the target jdk as defined by TargetJdk#toVersion(Object)

</description>
        <parameter type="java.lang.Object" name="value"/>
    </method>
    <property name="consoleOutput" type="boolean" documented="true">
        <description> Whether or not to write PMD results to System.out.

</description>
    </property>
    <property name="rulePriority" type="int" documented="true">
        <description> The rule priority threshold; violations for rules with a lower priority will not be reported. Default value is 5, which means that all violations will be reported.

 This is equivalent to PMD's Ant task minimumPriority property.

 See the official documentation for the list of priorities.

 Example: rulePriority = 3

</description>
    </property>
    <property name="ruleSetConfig" type="org.gradle.api.resources.TextResource" documented="true">
        <description> The custom rule set to be used (if any). Replaces ruleSetFiles, except that it does not currently support multiple rule sets.

 See the official documentation for how to author a rule set.

 Example: ruleSetConfig = resources.text.fromFile("config/pmd/myRuleSet.xml")

(since 2.2)

</description>
    </property>
    <property name="ruleSetFiles" type="org.gradle.api.file.FileCollection" documented="true">
        <description> The custom rule set files to be used. See the official documentation for how to author a rule set file.

 Example: ruleSetFiles = files("config/pmd/myRuleSet.xml")

</description>
    </property>
    <property name="ruleSets" type="java.util.List" documented="true">
        <description> The built-in rule sets to be used. See the official list of built-in rule sets.

 Example: ruleSets = ["basic", "braces"]

</description>
    </property>
    <property name="targetJdk" type="org.gradle.api.plugins.quality.TargetJdk" documented="true">
        <description> The target jdk to use with pmd, 1.3, 1.4, 1.5, 1.6, 1.7 or jsp

</description>
    </property>
</type>


text:
<?php

namespace LasVenturas\BlackjackBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class UserControllerTest extends WebTestCase
{
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
N. Amer. Fl. (New York) 9(4): 242 (1915)

#### Original name
Agaricus striatulus J.F. Gmel., 1792

### Remarks
null


text:
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  rescue_from CanCan::AccessDenied do |exception|
    redirect_to main_app.root_url, :alert => exception.message
  end

  def after_sign_in_path_for(resource)
  	if current_user.role? :admin
  		stored_location_for(resource) || admin_path
  	else
  		stored_location_for(resource) || root_path
  	end
  end
end


text:
import { default as React, Component } from 'react';
import { render } from 'react-dom';
import { urlShare } from '../service/UrlShare';

export class MirageLink extends Component {
  constructor(props) {
    super(props);
  }
  redirect() {
    urlShare.redirectUrl('mirage').then((url) => {
      window.open(url, '_self');
    }).catch((error) => console.log(error));
  }
  render() {
    return (
      <a title="Mirage - Query Explorer"
        className="link action-btn"
        onClick = {() => this.redirect()}>
        M
      </a>
    );
  }
}


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

"""
printer.py

Meta class for test printer.
"""

class Printer(object):
    """Meta class for test printer."""

    def __init__(self, ctx, lang):
        self.ctx = ctx
        self.lang = lang

    def _write_end(self, line):
        """Write with language specific ending."""
        if self.lang == 'py':
            self._writeln(line)
        elif self.lang == 'cpp':
            self._writeln('{};'.format(line))

    def _writeln(self, line):
        """Write line with new line character."""
        self.ctx.writeln(line)

    def _writelns(self, lines):
        """Write lines."""
        self.ctx.writelns(lines)

    def _bline(self, num=1):
        """Write blank lines."""
        while num > 0:
            self.ctx.bline()
            num -= 1

    def _write_comment(self, line):
        """Write langauge specific line comment."""
        if self.lang == 'py':
            self.ctx.writeln('# {}'.format(line))
        elif self.lang == 'cpp':
            self.ctx.writeln('// {}'.format(line))

    def _write_comments(self, line):
        """Write langauge specific block comments."""
        if self.lang == 'py':
            self.ctx.writeln('"""')
            self.ctx.writeln(line)
            self.ctx.writeln('"""')
        elif self.lang == 'cpp':
            self.ctx.writeln('/*')
            self.ctx.writeln(line)
            self.ctx.writeln('*/')

    def _lvl_inc(self):
        """Indent."""
        self.ctx.lvl_inc()

    def _lvl_dec(self):
        """Unindent."""
        self.ctx.lvl_dec()


text:
package net.opengis.gml.impl;
/**
 * A document containing one GridCoverage(@http://www.opengis.net/gml) element.
 *
 * This is a complex type.
 */
public class GridCoverageDocumentImpl extends net.opengis.gml.impl.DiscreteCoverageDocumentImpl implements net.opengis.gml.GridCoverageDocument
{
    private static final long serialVersionUID = 1L;

    public GridCoverageDocumentImpl(org.apache.xmlbeans.SchemaType sType)
    {
        super(sType);
    }

    private static final javax.xml.namespace.QName GRIDCOVERAGE$0 =
        new javax.xml.namespace.QName("http://www.opengis.net/gml", "GridCoverage");

    /**
     * Gets the "GridCoverage" element
     */
    public net.opengis.gml.GridCoverageType getGridCoverage()
    {
        synchronized (monitor())
        {
            check_orphaned();
            net.opengis.gml.GridCoverageType target = null;
            target = (net.opengis.gml.GridCoverageType)get_store().find_element_user(GRIDCOVERAGE$0, 0);
            if (target == null)
            {
                return null;
            }
            return target;
        }
    }

    /**
     * Sets the "GridCoverage" element
     */
     public void setGridCoverage(net.opengis.gml.GridCoverageType gridCoverage)
    {
        generatedSetterHelperImpl(gridCoverage, GRIDCOVERAGE$0, 0, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON);
    }

    /**
     * Appends and returns a new empty "GridCoverage" element
     */
    public net.opengis.gml.GridCoverageType addNewGridCoverage()
    {
        synchronized (monitor())
        {
            check_orphaned();
            net.opengis.gml.GridCoverageType target = null;
            target = (net.opengis.gml.GridCoverageType)get_store().add_element_user(GRIDCOVERAGE$0);
            return target;
        }
    }
}


text:
require 'spaceship'

require 'base64'

require_relative 'manager'
require_relative 'module'

module Sigh
  class DownloadAll
    # Download all valid provisioning profiles
    def download_all(download_xcode_profiles: false)
      if (api_token = Spaceship::ConnectAPI::Token.from(hash: Sigh.config[:api_key], filepath: Sigh.config[:api_key_path]))
        UI.message("Creating authorization token for App Store Connect API")
        Spaceship::ConnectAPI.token = api_token
      elsif !Spaceship::ConnectAPI.token.nil?
        UI.message("Using existing authorization token for App Store Connect API")
      else
        # Team selection passed though FASTLANE_ITC_TEAM_ID and FASTLANE_ITC_TEAM_NAME environment variables
        # Prompts select team if multiple teams and none specified
        UI.message("Starting login with user '#{Sigh.config[:username]}'")
        Spaceship::ConnectAPI.login(Sigh.config[:username], nil, use_portal: true, use_tunes: false)
        UI.message("Successfully logged in")
      end

      if download_xcode_profiles
        UI.deprecated("The App Store Connect API does not support querying for Xcode managed profiles: --download_code_profiles is deprecated")
      end

      case Sigh.config[:platform].to_s
      when 'ios'
        profile_types = [
          Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_STORE,
          Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_INHOUSE,
          Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_ADHOC,
          Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_DEVELOPMENT
        ]
      when 'macos'
        profile_types = [
          Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_STORE,
          Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_DEVELOPMENT,
          Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_DIRECT
        ]

        # As of 2022-06-25, only available with Apple ID auth
        if Spaceship::ConnectAPI.token
          UI.important("Skipping #{Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_INHOUSE}... only available with Apple ID auth")
        else
          profile_types << Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_INHOUSE
        end
      when 'catalyst'
        profile_types = [
          Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_STORE,
          Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_DEVELOPMENT,
          Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_DIRECT
        ]

        # As of 2022-06-25, only available with Apple ID auth
        if Spaceship::ConnectAPI.token
          UI.important("Skipping #{Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_INHOUSE}... only available with Apple ID auth")
        else
          profile_types << Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_INHOUSE
        end
      when 'tvos'
        profile_types = [
          Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_STORE,
          Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_INHOUSE,
          Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_ADHOC,
          Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_DEVELOPMENT
        ]
      end

      profiles = Spaceship::ConnectAPI::Profile.all(filter: { profileType: profile_types.join(",") }, includes: "bundleId")
      download_profiles(profiles)
    end

    # @param profiles [Array] Array of all the provisioning profiles we want to download
    def download_profiles(profiles)
      UI.important("No profiles available for download") if profiles.empty?

      profiles.each do |profile|
        if profile.valid?
          UI.message("Downloading profile '#{profile.name}'...")
          download_profile(profile)
        else
          UI.important("Skipping invalid/expired profile '#{profile.name}'")
        end
      end
    end

    def pretty_type(profile_type)
      return Sigh.profile_pretty_type(profile_type)
    end

    # @param profile [ProvisioningProfile] A profile we plan to download and store
    def download_profile(profile)
      FileUtils.mkdir_p(Sigh.config[:output_path])

      type_name = pretty_type(profile.profile_type)
      profile_name = "#{type_name}_#{profile.uuid}_#{profile.bundle_id.identifier}"

      if Sigh.config[:platform].to_s == 'tvos'
        profile_name += "_tvos"
      end

      if ['macos', 'catalyst'].include?(Sigh.config[:platform].to_s)
        profile_name += '.provisionprofile'
      else
        profile_name += '.mobileprovision'
      end

      output_path = File.join(Sigh.config[:output_path], profile_name)
      File.open(output_path, "wb") do |f|
        content = Base64.decode64(profile.profile_content)
        f.write(content)
      end

      Manager.install_profile(output_path) unless Sigh.config[:skip_install]
    end
  end
end


text:
<?php

namespace Phpactor\ClassFileConverter;

use Phpactor\ClassFileConverter\Adapter\Composer\ComposerFileToClass;
use Phpactor\ClassFileConverter\Adapter\Composer\ComposerClassToFile;
use Phpactor\ClassFileConverter\Domain\ClassToFileFileToClass;
use Composer\Autoload\ClassLoader;
use Phpactor\ClassFileConverter\Domain\ChainClassToFile;
use Phpactor\ClassFileConverter\Domain\ChainFileToClass;

/**
 * Facade for the library.
 */
final class ClassToFileConverter
{
    private $converter;

    private function __construct(ClassToFileFileToClass $converter)
    {
        $this->converter = $converter;
    }

    public static function fromComposerAutoloader(ClassLoader $classLoader): ClassToFileFileToClass
    {
        return  new ClassToFileFileToClass(
            new ComposerClassToFile($classLoader),
            new ComposerFileToClass($classLoader)
        );
    }

    public static function fromComposerAutoloaders(array $classLoaders): ClassToFileFileToClass
    {
        $classToFiles = $fileToClasses = [];
        foreach ($classLoaders as $classLoader) {
            $classToFiles[] = new ComposerClassToFile($classLoader);
        }
        foreach ($classLoaders as $classLoader) {
            $fileToClasses[] = new ComposerFileToClass($classLoader);
        }

        return new ClassToFileFileToClass(
            new ChainClassToFile($classToFiles),
            new ChainFileToClass($fileToClasses)
        );
    }
}


text:
var adminApp = angular.module('adminApp', ['textAngular', 'angularFileUpload', 'config', 'infinite-scroll', 'app', 'ui.tinymce', 'ngBootbox']);

adminApp.factory('adminFactory', function($http, $q, ENV) {

	return {
		getAdminData: function(){
			var deferred = $q.defer();

			$http.get(ENV.apiEndpoint+'admin/data')
				.success(function(data) {
					return deferred.resolve(data);
				})
				.error(function(data) {
					return deferred.resolve(data);
				});

			return deferred.promise;
		},
		getApprovalQueue: function(offset, num){
			var deferred = $q.defer();

			$http.get(ENV.apiEndpoint+'admin/approval-queue/'+offset+'/'+num)
				.success(function(data) {
					return deferred.resolve(data);
				})
				.error(function(data) {
					return deferred.resolve(data);
				});

			return deferred.promise;
		},
		approvePost: function(id){
			return $http.post(ENV.apiEndpoint+'posts/approve', {'id':id});
		},
		rejectPost: function(id){
			return $http.post(ENV.apiEndpoint+'posts/reject', {'id':id});
		},
		approveModerator: function(id){
			return $http.post(ENV.apiEndpoint+'admin/approve-moderator', {'id':id});
		},
		rejectModerator: function(id){
			return $http.post(ENV.apiEndpoint+'admin/reject-moderator', {'id':id});
		},
		saveCollection: function(collection){
			return $http.post(ENV.apiEndpoint+'admin/save-collection', {'collection':collection});
		},
		deleteCollection: function(id){
			return $http.post(ENV.apiEndpoint+'admin/delete-collection', {'id':id});
		},
		deletePostFromCollection: function(post_id, collection_id){
			return $http.post(ENV.apiEndpoint+'admin/remove-post-from-collection', {'post_id':post_id,'collection_id':collection_id});
		},
		getUserList: function(offset, num) {
			return $http.get(ENV.apiEndpoint+'admin/user-list/'+offset+'/'+num);
		},
		saveStaticContent: function(page, content) {
			return $http.post(ENV.apiEndpoint+'admin/save-static-content', {'page':page, 'content':content});
		},
		deleteUser: function(user_id) {
			return $http.post(ENV.apiEndpoint+'admin/delete-user', {'id':user_id});
		},
		makeModerator: function(user_id) {
			return $http.post(ENV.apiEndpoint+'admin/make-moderator', {'id':user_id});
		},
		removeModerator: function(user_id) {
			return $http.post(ENV.apiEndpoint+'admin/remove-moderator', {'id':user_id});
		},
		resendUserCode: function(user_id) {
			return $http.post(ENV.apiEndpoint+'admin/resend-user-code', {'id':user_id});
		},
		deleteTag: function(id) {
			return $http.post(ENV.apiEndpoint+'admin/delete-tag', {'id': id});
		},
		moveTag: function(tag_id, cat_id) {
			return $http.post(ENV.apiEndpoint+'admin/move-tag', {'tag_id' : tag_id, 'category_id' : cat_id});
		},
		renameCategory: function(id, newName) {
			return $http.post(ENV.apiEndpoint+'admin/rename-category', {'id': id, 'new': newName});
		},
		renameTag: function(id, category_id, newName) {
			return $http.post(ENV.apiEndpoint+'admin/rename-tag', {'id' : id, 'category_id' : category_id, 'newName': newName});
		},
		approveTag: function(id) {
			return $http.post(ENV.apiEndpoint+'admin/approve-tag', {'id' : id});
		},
		addNewTag: function(id, tag_name) {
			return $http.post(ENV.apiEndpoint+'admin/add-new-tag', {'id': id, 'name': tag_name});
		}
	}
});

adminApp.controller('AdminController', function($scope, postFactory, adminFactory, ENV, $upload, $timeout, $ngBootbox, $compile) {

	$scope.ENV = ENV;

	$scope.actions = new Array();
	$scope.actions.showCollectionPosts = false;

	$scope.current_user = window.networked.user;

	$scope.tinymceOptions = {
		height: 500,
		content_css: ENV.baseUrl+'assets/css/all.min.css',
		plugins: 'code paste table link colorpicker hr image',
		menubar: false,
		toolbar: [
			'undo redo | cut copy paste pastetext | bold italic underline | alignleft aligncenter alignright alignjustify | styleselect | bullist numlist',
			'table | link | hr | code'
		]
	};

	adminFactory.getAdminData().then(function(data){

		$scope.admin_data = data;

		$scope.admin_data.about_page = data.about_content;
		$scope.admin_data.fellows_page = data.fellows_content;

		if (data.hasOwnProperty('approval_queue'))
		{
			$scope.numApprovalQueueLoaded = data.approval_queue.length;
		}

		if (data.hasOwnProperty('collections'))
		{
			angular.forEach($scope.admin_data.collections, function(collection) {
				if (parseInt(collection.active)) collection.active = 'true';
				else collection.active = 'false';
				collection.old_name = collection.name;
			});
		}

		$scope.numUserListToLoad = 15;
		$scope.numUserListPage = 0;
		$scope.numUserListTotalPages;
		if (data.hasOwnProperty('user_list'))
		{
			$scope.numUserListTotalPages = Math.ceil($scope.admin_data.total_num_users / $scope.numUserListToLoad);

			angular.forEach($scope.admin_data.user_list, function(a_user) {
				a_user.user_role_names = '';
				if (typeof a_user.role_title === 'string')
				{
					a_user.user_role_names = a_user.role_title;
					//convert to array
					a_user.role_title = [ a_user.role_title ];
				}
				else if (a_user.role_title && a_user.role_title.length > 0)
				{
					a_user.user_role_names = a_user.role_title.join(', ');
				}

				//check if 'Other' role is selected
				var other_idx;
				if (a_user.role_title)
				{
					other_idx = a_user.role_title.indexOf('Other');
					if (other_idx >= 0 && a_user.role_title_other)
					{
						a_user.user_role_names += ' (' + a_user.role_title_other + ')';
					}
				}
			});
		}

		if (data.hasOwnProperty('moderator_queue'))
		{
			angular.forEach($scope.admin_data.moderator_queue, function(moderator) {
				moderator.user_role_names = '';
				if (typeof moderator.role_title === 'string')
				{
					moderator.user_role_names = moderator.role_title;
					//convert to array
					moderator.role_title = [ moderator.role_title ];
				}
				else if (moderator.role_title && moderator.role_title.length > 0)
				{
					moderator.user_role_names = moderator.role_title.join(', ');
				}

				//check if 'Other' role is selected
				var other_idx;
				if (moderator.role_title)
				{
					other_idx = moderator.role_title.indexOf('Other');
					if (other_idx >= 0 && moderator.role_title_other)
					{
						moderator.user_role_names += ' (' + moderator.role_title_other + ')';
					}
				}
			});
		}

		if (window.networked.tab)
		{
			$scope.actions.showAdmin = window.networked.tab;
		}
		else
		{
			$scope.actions.showAdmin = '';
		}

	});

	$scope.loadingApprovalQueue = false;
	$scope.loadedAllApprovalQueue = false;
	$scope.loadMoreApprovalQueue = function()
	{
		if ($scope.loadingApprovalQueue) return;
		$scope.loadingApprovalQueue = true;

		adminFactory.getApprovalQueue($scope.numApprovalQueueLoaded, 15).then(function(data){

			if (data.length == 0)
			{
				$scope.loadedAllApprovalQueue = true;
			}
			else
			{
				angular.forEach(data, function(item) {
					$scope.admin_data.approval_queue.push(item);
				});

				$scope.numApprovalQueueLoaded += data.length;
			}

			$scope.loadingApprovalQueue = false;

		});
	}

	$scope.approvePost = function(post)
	{
		adminFactory.approvePost(post.id).then(function(data){

			//remove post from the queue
			if (data.data == 200)
			{
				angular.forEach($scope.admin_data.approval_queue, function(item, index) {

					if (item.id == post.id)
					{
						$scope.admin_data.approval_queue.splice(index, 1);
						$scope.admin_data.approval_queue_count--;
					}
				});
			}
		});
	}

	$scope.rejectPost = function(post)
	{
		$ngBootbox.confirm('Are you sure you want to reject this post?')
		    .then(function() {
		        //confirmed
		        adminFactory.rejectPost(post.id).then(function(data){

					//remove post from the queue
					if (data.data == 200)
					{
						angular.forEach($scope.admin_data.approval_queue, function(item, index) {

							if (item.id == post.id)
							{
								$scope.admin_data.approval_queue.splice(index, 1);
								$scope.admin_data.approval_queue_count--;
							}
						});
					}
				});
		    }, function() {
		        //dismissed
		    });
	}

	$scope.approveModerator = function(user)
	{
		adminFactory.approveModerator(user.id).then(function() {
			window.location.replace(ENV.baseUrl+'admin/moderator_requests');
		});
	}

	$scope.rejectModerator = function(user)
	{
		adminFactory.rejectModerator(user.id).then(function() {
			window.location.replace(ENV.baseUrl+'admin/moderator_requests');
		});
	}

	$scope.addCollection = function()
	{
		$ngBootbox.prompt('New collection name:')
			.then(function(result) {
				//prompt returned
				adminFactory.saveCollection({
					thumbnail: '',
					name: result,
					active: 'false',
					activeVal: 0
				}).then(function(resp) {
					if (resp && resp.data)
					{
						if (resp.data == '409')
						{
							$ngBootbox.alert('A collection already exists with this name');
						}
						else if (resp.data.id)
						{
							$scope.admin_data.collections.push({
								id: resp.data.id,
								slug: resp.data.slug,
								thumbnail: '',
								name: result,
								active: 'false',
								old_name: result
							});
						}
					}
				});
			}, function() {
				//dismissed
			});
	}

	$scope.deleteCollection = function(collection)
	{
		$ngBootbox.confirm('Are you sure you want to delete the Collection ' + collection.name + '?')
		    .then(function() {
		        //confirmed
		        if (collection.id)
				{
					adminFactory.deleteCollection(collection.id).then(function() {

					});
				}

				var index = $scope.admin_data.collections.indexOf(collection);
				$scope.admin_data.collections.splice(index, 1);
		    }, function() {
		        //dismissed
		    });
	}

	$scope.pendingSave;
	$scope.saveCollection = function(collection)
	{
		if (collection.name)
		{
			if ($scope.pendingSave)
			{
				$timeout.cancel($scope.pendingSave);
			}

			$scope.pendingSave = $timeout(function() {
				//post thumbnail, name, and active
				if (collection.active == 'true') collection.activeVal = 1;
				else collection.activeVal = 0;
				adminFactory.saveCollection(collection).then(function(resp) {
					if (resp && resp.data)
					{
						if (resp.data == '409')
						{
							$ngBootbox.alert('A collection already exists with this name');
							collection.name = collection.old_name;
						}
						else if (resp.data.id)
						{
							collection.slug = resp.data.slug;
							collection.old_name = resp.data.name;
						}
					}
				});
			}, 1000);
		}
	}

	$scope.uploadCollectionImage = function($files, $event, updateObject)
	{
		// https://github.com/danialfarid/angular-file-upload
		var file = $files[0];

		$scope.upload = $upload.upload({
			url: ENV.apiEndpoint+'admin/upload-collection-image',
			file: file,
		}).success(function(data, status, headers, config) {
			// file is uploaded successfully
			updateObject.thumbnail = data.thumbnail;

			$scope.saveCollection(updateObject);
		});
	}

	$scope.activeCollection;
	$scope.manageCollection = function(collection)
	{
		$scope.activeCollection = collection;

		postFactory.getCollection(collection.slug).then(function(data) {
			collection.posts = data.posts;

			$scope.actions.showCollectionPosts = true;
		});
	}

	$scope.deletePostFromCollection = function(collection, post)
	{
		adminFactory.deletePostFromCollection(post.id, collection.id).then(function(data) {
			var index = collection.posts.indexOf(post);
			collection.posts.splice(index, 1);
		});
	}

	$scope.loadUserListPage = function(page)
	{
		adminFactory.getUserList(page*$scope.numUserListToLoad, $scope.numUserListToLoad).then(function(data) {
			$scope.admin_data.user_list = data['data'];
			$scope.numUserListPage = page;
		});
	}

	$scope.saveStaticContent = function(page, content)
	{
		adminFactory.saveStaticContent(page, content).then(function(data) {
			$ngBootbox.alert('Saved!');
		});
	}

	$scope.onStaticContentFileSelect = function($files, $event, contentPage)
	{
		// https://github.com/danialfarid/angular-file-upload
		var file = $files[0];

		$scope.upload = $upload.upload({
			url:ENV.apiEndpoint+'admin/upload-static-content-media',
			file: file,
		}).success(function(data, status, headers, config) {
			if (data != 500)
			{
				var img = '';

				if (contentPage == 'about')
				{
					$scope.admin_data.about_page = img + $scope.admin_data.about_page;
				}
				else if (contentPage == 'fellows')
				{
					$scope.admin_data.fellows_page += img + $scope.admin_data.fellows_page;
				}
			}
		});
	}

	$scope.deleteUser = function(user)
	{
		if (!user.is_admin){
			$ngBootbox.confirm('Are you sure you want to permanently delete the user ' + user.first_name + ' ' + user.last_name + ' from the system? This will reassign all of their posts to you.')
			    .then(function() {
			        //confirmed
			        adminFactory.deleteUser(user.id).then(function(data) {
						if (data['data'] != 500)
						{
							$ngBootbox.alert('User deleted and posts reassigned to your user.').then(function( ){
								window.location.replace(ENV.baseUrl+'admin/user_list');
							});
						}
						else
						{
							$ngBootbox.alert('Could not delete user.');
						}
					});
			    }, function() {
			        //dismissed
			    });
		}
	}

	$scope.makeModerator = function(user)
	{
		if (!user.is_moderator){
			$ngBootbox.confirm('Are you sure you want to make ' + user.first_name + ' ' + user.last_name + ' a moderator?')
			    .then(function() {
			        //confirmed
			        adminFactory.makeModerator(user.id).then(function(data) {
						if (data['data'] != 500)
						{
							user.is_moderator = true;
							user.role_id = 2;

							$ngBootbox.alert(user.first_name + ' ' + user.last_name + ' is now a moderator.').then(function() {
								window.location.replace(ENV.baseUrl+'admin/user_list');
							});

						}
						else
						{
							$ngBootbox.alert('Could not make user a moderator.');
						}
					});
			    }, function() {
			        //dismissed
			    });
		}
	}

	$scope.removeModerator = function(user)
	{
		$ngBootbox.confirm('Are you sure you want to revoke moderator privileges from ' + user.first_name + ' ' + user.last_name + '?')
		    .then(function() {
		        //confirmed
		        adminFactory.removeModerator(user.id).then(function(data) {
					$ngBootbox.alert('User is no longer a moderator.').then(function() {
						window.location.replace(ENV.baseUrl+'admin/moderator_list');
					});
				});
		    }, function() {
		        //dismissed
		    });
	}

	$scope.resendUserConfirmationCode = function(user)
	{
		adminFactory.resendUserCode(user.id).then(function(data) {
			$ngBootbox.alert('User confirmation code resent. The email should be delivered to the user shortly.');
		});
	}

	$scope.renameCategory = function(id)
	{
		$ngBootbox.prompt('Enter new name for category:').then(function(result) {
			adminFactory.renameCategory(id, result).then(function(data) {
				if (data['data'] == 500)
				{
					$ngBootbox.alert('A category already exists with this name.');
				}
				else
				{
					window.location.replace(ENV.baseUrl+'admin/'+$scope.actions.showAdmin);
				}
			});
		});
	}

	$scope.deleteTag = function(tag)
	{
		$ngBootbox.confirm('Are you sure you want to delete the tag ' + tag.name + '?')
		    .then(function() {
		        //confirmed
		        adminFactory.deleteTag(tag.id).then(function(data) {
					window.location.replace(ENV.baseUrl+'admin/'+$scope.actions.showAdmin);
				});
		    }, function() {
		        //dismissed
		    });
	}

	//move tag to a different category
	$scope.moveTagCategoryId;
	$scope.moveTag = function(tag, currentCatName)
	{
		var tplCrop = '<select ng-model="moveTagCategoryId" class="form-control"><option value="{{obj.category.id}}" ng-repeat="obj in admin_data.tags">{{obj.category.name}}</option></select>';
		var template = angular.element(tplCrop);
		var linkFn = $compile(template);
		var html = linkFn($scope);

		var options = {
			title: 'Move '+tag.name+' to a new category.
Current category is '+currentCatName+'.',
			message: html,
			buttons: {
				warning: {
					label: 'Cancel',
					className: 'btn-gray',
					callback: function() {

					}
				},
				success: {
					label: 'Move',
					className: 'btn-red',
					callback: function() {
						adminFactory.moveTag(tag.id, $scope.moveTagCategoryId).then(function() {
							window.location.replace(ENV.baseUrl+'admin/'+$scope.actions.showAdmin);
						});
					}
				}
			}
		}

		$ngBootbox.customDialog(options);
	}

	$scope.startRenameTag = function(tag)
	{
		tag.old_name = tag.name;
		tag.edit = true;
	}

	$scope.renameTag = function(tag)
	{
		adminFactory.renameTag(tag.id, tag.category_id, tag.name).then(function(data) {
			if (data.data.response == 500)
			{
				$ngBootbox.alert('A tag already exists with this name in the category '+data.data.tag.tag_category.name+'.');
				tag.name = tag.old_name;
				tag.old_name = null;
			}
			else
			{
				window.location.replace(ENV.baseUrl+'admin/'+$scope.actions.showAdmin);
			}
		});
	}

	$scope.cancelTagUpdate = function(tag)
	{
		if (tag.old_name){
			tag.name = tag.old_name;
			tag.old_name = null;
		}
		tag.edit = false;
	}

	$scope.approveTag = function(tag)
	{
		adminFactory.approveTag(tag.id).then(function(data) {
			window.location.replace(ENV.baseUrl+'admin/'+$scope.actions.showAdmin);
		});
	}

	$scope.addNewTag = function(id)
	{
		$ngBootbox.prompt('Enter name for new tag:').then(function(result) {
			adminFactory.addNewTag(id, result).then(function(data) {
				if (data.data.response == 500)
				{
					$ngBootbox.alert('A tag already exists with this name in the category '+data.data.tag.tag_category.name+'.');
				}
				else
				{
					window.location.replace(ENV.baseUrl+'admin/'+$scope.actions.showAdmin);
				}
			});
		});
	}

});


text:
import chai from 'chai';
import EventPublisher from '../../src/services/event-publisher.js';
import { Observable } from 'rx';

chai.expect();

const expect = chai.expect;
const assert = chai.assert;

var reader, publisher, evt, topic;

describe("Given an EventPublisher",function(){
  before(() => {
    reader = EventPublisher();
  });

  it("should be a Reader", () => { assert(reader.run, "MessagePublisher() does not return a reader")});

  describe("when run against an environment",function(){
    beforeEach(() => {
      const api = {
        publish: (e, t) => { evt = e; topic = t; return Observable.just(evt)},
      };
      const env = { eventBus: api };
      publisher = reader.run(env);
      evt = undefined; topic = undefined;
    });
    it("should return an instantiated api",() => {
      expect(publisher).to.respondTo('publish');
      expect(publisher).to.respondTo('broadcast');
    });
    describe("EventPublisher ~> broadcast", function() {
      it("should return an Observable", () => {
        expect(publisher.broadcast({})).to.respondTo('subscribe');
      });
      it("should broadcast an event", function(done){
        publisher.broadcast({an:'event'}).subscribe(
          function(result) {
            expect(evt).to.eql({an:'event'});
            expect(topic).to.be.undefined;
            done();
          }, err => done(err)
        );
      });
    });
    describe("EventPublisher ~> publish", function() {
      it("should return an Observable", () => {
        expect(publisher.publish('t',{})).to.respondTo('subscribe');
      })
      it("should publish an event to a topic", (done) => {
        publisher.publish('mytopic', {another:'event'}).subscribe(
          function(result) {
            expect(evt).to.eql({another:'event'});
            expect(topic).to.eql('mytopic');
            done();
          }, err => done(err)
        );
      });
    });

  });
});


text:
@class GroupData;

@protocol GroupNearDelegate <NSObject>

- (void)selectNearGroup:(GroupData *)groupData;

- (void)moreNearGrop;

@end

@interface GroupNear : GroupBaseView
{
    UIScrollView *_contentScrollV;
}

@property (nonatomic, assign) id <GroupNearDelegate>groupDelegate;

@property (nonatomic, retain) NSArray *dataAry;

- (void)updateNearGroupWithAry:(NSArray *)ary;

@end


text:
package org.apache.servicecomb.core.provider.consumer;

public class TestConsumerProviderManager {
//  @Before
//  public void setUp() throws Exception {
//    ArchaiusUtils.resetConfig();
//  }
//
//  @After
//  public void tearDown() throws Exception {
//    ArchaiusUtils.resetConfig();
//  }
//
//  @Test
//  public void allowedNoProvider(@Mocked ConsumerSchemaFactory consumerSchemaFactory) {
//    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
//    context.getBeanFactory().registerSingleton(consumerSchemaFactory.getClass().getName(), consumerSchemaFactory);
//    context.register(ConsumerProviderManager.class);
//    // must not throw exception
//    context.refresh();
//
//    context.close();
//  }
//
//  private ReferenceConfig mockCreateReferenceConfig() {
//    EventBus eventBus = new EventBus();
//    AppManager appManager = new AppManager(eventBus);
//
//    ConsumerProviderManager consumerProviderManager = new ConsumerProviderManager();
//    consumerProviderManager.setAppManager(appManager);
//
//    new Expectations(RegistryUtils.class) {
//      {
//        RegistryUtils.findServiceInstances(anyString, anyString, DefinitionConst.VERSION_RULE_ALL, null);
//        result = Collections.emptyList();
//      }
//    };
//
//    new MockUp<MicroserviceVersionRule>() {
//      @Mock
//      MicroserviceVersion getLatestMicroserviceVersion() {
//        return Mockito.mock(MicroserviceVersion.class);
//      }
//    };
//    return consumerProviderManager.createReferenceConfig("app:ms");
//  }
//
//  @Test
//  public void createReferenceConfig_default() {
//    ReferenceConfig referenceConfig = mockCreateReferenceConfig();
//
//    Assert.assertEquals("app", referenceConfig.getMicroserviceVersionRule().getAppId());
//    Assert.assertEquals("app:ms", referenceConfig.getMicroserviceVersionRule().getMicroserviceName());
//    Assert.assertEquals("0.0.0.0+", referenceConfig.getMicroserviceVersionRule().getVersionRule().getVersionRule());
//    Assert.assertEquals(Const.ANY_TRANSPORT, referenceConfig.getTransport());
//  }
//
//  @Test
//  public void createReferenceConfig_config() {
//    ArchaiusUtils.setProperty("servicecomb.references.app:ms.version-rule", "1.0.0+");
//    ArchaiusUtils.setProperty("servicecomb.references.app:ms.transport", Const.RESTFUL);
//
//    ReferenceConfig referenceConfig = mockCreateReferenceConfig();
//
//    Assert.assertEquals("app", referenceConfig.getMicroserviceVersionRule().getAppId());
//    Assert.assertEquals("app:ms", referenceConfig.getMicroserviceVersionRule().getMicroserviceName());
//    Assert.assertEquals("1.0.0.0+", referenceConfig.getMicroserviceVersionRule().getVersionRule().getVersionRule());
//    Assert.assertEquals(Const.RESTFUL, referenceConfig.getTransport());
//  }
//
//  @Test
//  public void createReferenceConfig_ProviderNotFound() {
//    EventBus eventBus = new EventBus();
//    AppManager appManager = new AppManager(eventBus);
//
//    ConsumerProviderManager consumerProviderManager = new ConsumerProviderManager();
//    consumerProviderManager.setAppManager(appManager);
//
//    new Expectations(RegistryUtils.class) {
//      {
//        RegistryUtils.findServiceInstances(anyString, anyString, DefinitionConst.VERSION_RULE_ALL, null);
//        result = Collections.emptyList();
//      }
//    };
//
//    new MockUp<MicroserviceVersionRule>() {
//      @Mock
//      String getAppId() {
//        return "aId";
//      }
//
//      @Mock
//      String getMicroserviceName() {
//        return "ms";
//      }
//    };
//
//    try {
//      consumerProviderManager.createReferenceConfig("app:ms");
//      fail("an IllegalStateException is expected!");
//    } catch (Exception e) {
//      Assert.assertEquals(IllegalStateException.class, e.getClass());
//      Assert.assertEquals(
//          "Probably invoke a service before it is registered, or no instance found for it, appId=aId, name=ms",
//          e.getMessage());
//      e.printStackTrace();
//    }
//  }
}


text:
const test = require('tape')
const ProviderEngine = require('../index.js')
const FilterProvider = require('../subproviders/filters.js')
const TestBlockProvider = require('./util/block.js')
const createPayload = require('../util/create-payload.js')
const injectMetrics = require('./util/inject-metrics')

filterTest('basic block filter', { method: 'eth_newBlockFilter' },
  function afterInstall(t, testMeta, response, cb){
    var block = testMeta.block = testMeta.blockProvider.nextBlock()
    cb()
  },
  function filterChangesOne(t, testMeta, response, cb){
    var results = response.result
    var returnedBlockHash = response.result[0]
    t.equal(results.length, 1, 'correct number of results')
    t.equal(returnedBlockHash, testMeta.block.hash, 'correct result')
    cb()
  },
  function filterChangesTwo(t, testMeta, response, cb){
    var results = response.result
    t.equal(results.length, 0, 'correct number of results')
    cb()
  }
)

filterTest('log filter - basic', {
    method: 'eth_newFilter',
    params: [{
      topics: ['0x00000000000000000000000000000000000000000000000000deadbeefcafe01']
    }],
  },
  function afterInstall(t, testMeta, response, cb){
    testMeta.tx = testMeta.blockProvider.addTx({
      topics: ['0x00000000000000000000000000000000000000000000000000deadbeefcafe01']
    })
    testMeta.badTx = testMeta.blockProvider.addTx({
      topics: ['0x00000000000000000000000000000000000000000000000000deadbeefcafe02']
    })
    var block = testMeta.block = testMeta.blockProvider.nextBlock()
    cb()
  },
  function filterChangesOne(t, testMeta, response, cb){
    var results = response.result
    var matchedTx = response.result[0]
    t.equal(results.length, 1, 'correct number of results')
    t.equal(matchedTx, testMeta.tx, 'correct result')
    cb()
  },
  function filterChangesTwo(t, testMeta, response, cb){
    var results = response.result
    t.equal(results.length, 0, 'correct number of results')
    cb()
  }
)

filterTest('log filter - and logic', {
    method: 'eth_newFilter',
    params: [{
      topics: [
      '0x00000000000000000000000000000000000000000000000000deadbeefcafe01',
      '0x00000000000000000000000000000000000000000000000000deadbeefcafe02',
      ],
    }],
  },
  function afterInstall(t, testMeta, response, cb){
    testMeta.tx = testMeta.blockProvider.addTx({
      topics: [
        '0x00000000000000000000000000000000000000000000000000deadbeefcafe01',
        '0x00000000000000000000000000000000000000000000000000deadbeefcafe02',
      ],
    })
    testMeta.badTx = testMeta.blockProvider.addTx({
      topics: [
        '0x00000000000000000000000000000000000000000000000000deadbeefcafe02',
        '0x00000000000000000000000000000000000000000000000000deadbeefcafe01',
      ],
    })
    var block = testMeta.block = testMeta.blockProvider.nextBlock()
    cb()
  },
  function filterChangesOne(t, testMeta, response, cb){
    var results = response.result
    var matchedTx = response.result[0]
    t.equal(results.length, 1, 'correct number of results')
    t.equal(matchedTx, testMeta.tx, 'correct result')
    cb()
  },
  function filterChangesTwo(t, testMeta, response, cb){
    var results = response.result
    t.equal(results.length, 0, 'correct number of results')
    cb()
  }
)

filterTest('log filter - or logic', {
    method: 'eth_newFilter',
    params: [{
      topics: [
        [
          '0x00000000000000000000000000000000000000000000000000deadbeefcafe01',
          '0x00000000000000000000000000000000000000000000000000deadbeefcafe02',
        ],
      ],
    }],
  },
  function afterInstall(t, testMeta, response, cb){
    testMeta.tx1 = testMeta.blockProvider.addTx({
      topics: [
        '0x00000000000000000000000000000000000000000000000000deadbeefcafe01',
      ],
    })
    testMeta.tx2 = testMeta.blockProvider.addTx({
      topics: [
        '0x00000000000000000000000000000000000000000000000000deadbeefcafe02',
      ],
    })
    testMeta.badTx = testMeta.blockProvider.addTx({
      topics: [
        '0x00000000000000000000000000000000000000000000000000deadbeefcafe03',
      ],
    })
    var block = testMeta.block = testMeta.blockProvider.nextBlock()
    cb()
  },
  function filterChangesOne(t, testMeta, response, cb){
    var results = response.result
    var matchedTx1 = response.result[0]
    var matchedTx2 = response.result[1]
    t.equal(results.length, 2, 'correct number of results')
    t.equal(matchedTx1, testMeta.tx1, 'correct result')
    t.equal(matchedTx2, testMeta.tx2, 'correct result')
    cb()
  },
  function filterChangesTwo(t, testMeta, response, cb){
    var results = response.result
    t.equal(results.length, 0, 'correct number of results')
    cb()
  }
)

filterTest('log filter - wildcard logic', {
    method: 'eth_newFilter',
    params: [{
      topics: [
        null,
        '0x00000000000000000000000000000000000000000000000000deadbeefcafe02',
      ],
    }],
  },
  function afterInstall(t, testMeta, response, cb){
    testMeta.tx1 = testMeta.blockProvider.addTx({
      topics: [
        '0x00000000000000000000000000000000000000000000000000deadbeefcafe01',
        '0x00000000000000000000000000000000000000000000000000deadbeefcafe02',
      ],
    })
    testMeta.tx2 = testMeta.blockProvider.addTx({
      topics: [
        '0x00000000000000000000000000000000000000000000000000deadbeefcafe02',
        '0x00000000000000000000000000000000000000000000000000deadbeefcafe02',
      ],
    })
    testMeta.badTx = testMeta.blockProvider.addTx({
      topics: [
        '0x00000000000000000000000000000000000000000000000000deadbeefcafe01',
        '0x00000000000000000000000000000000000000000000000000deadbeefcafe01',
      ],
    })
    var block = testMeta.block = testMeta.blockProvider.nextBlock()
    cb()
  },
  function filterChangesOne(t, testMeta, response, cb){
    var results = response.result
    var matchedTx1 = response.result[0]
    var matchedTx2 = response.result[1]
    t.equal(results.length, 2, 'correct number of results')
    t.equal(matchedTx1, testMeta.tx1, 'correct result')
    t.equal(matchedTx2, testMeta.tx2, 'correct result')
    cb()
  },
  function filterChangesTwo(t, testMeta, response, cb){
    var results = response.result
    t.equal(results.length, 0, 'correct number of results')
    cb()
  }
)

// util

function filterTest(label, filterPayload, afterInstall, filterChangesOne, filterChangesTwo){
  test('filters - '+label, function(t){
    // t.plan(8)

    // install filter
    // new block
    // check filter

    var testMeta = {}

    // handle "test_rpc"
    var filterProvider = testMeta.filterProvider = injectMetrics(new FilterProvider())
    // handle block requests
    var blockProvider = testMeta.blockProvider = injectMetrics(new TestBlockProvider())

    var engine = testMeta.engine = new ProviderEngine({
      pollingInterval: 20,
      pollingShouldUnref: false,
    })
    engine.addProvider(filterProvider)
    engine.addProvider(blockProvider)
    engine.once('block', startTest)
    engine.start()

    function startTest(){
      // install block filter
      engine.sendAsync(createPayload(filterPayload), function(err, response){
        t.ifError(err, 'did not error')
        t.ok(response, 'has response')

        var method = filterPayload.method

        t.equal(filterProvider.getWitnessed(method).length, 1, 'filterProvider did see "'+method+'"')
        t.equal(filterProvider.getHandled(method).length, 1, 'filterProvider did handle "'+method+'"')

        var filterId = testMeta.filterId = response.result

        afterInstall(t, testMeta, response, function(err){
          t.ifError(err, 'did not error')

          engine.once('block', continueTest)
        })
      })
    }

    function continueTest(filterId){
      var filterId = testMeta.filterId
      // after filter check one
      engine.sendAsync(createPayload({ method: 'eth_getFilterChanges', params: [filterId] }), function(err, response){
        t.ifError(err, 'did not error')
        t.ok(response, 'has response')

        t.equal(filterProvider.getWitnessed('eth_getFilterChanges').length, 1, 'filterProvider did see "eth_getFilterChanges"')
        t.equal(filterProvider.getHandled('eth_getFilterChanges').length, 1, 'filterProvider did handle "eth_getFilterChanges"')

        filterChangesOne(t, testMeta, response, function(err){
          t.ifError(err, 'did not error')

          // after filter check two
          engine.sendAsync(createPayload({ method: 'eth_getFilterChanges', params: [filterId] }), function(err, response){
            t.ifError(err, 'did not error')
            t.ok(response, 'has response')

            t.equal(filterProvider.getWitnessed('eth_getFilterChanges').length, 2, 'filterProvider did see "eth_getFilterChanges"')
            t.equal(filterProvider.getHandled('eth_getFilterChanges').length, 2, 'filterProvider did handle "eth_getFilterChanges"')

            filterChangesTwo(t, testMeta, response, function(err){
              t.ifError(err, 'did not error')
              engine.stop()
              t.end()
            })
          })
        })
      })
    }

  })
}


text:
package v2ch10.table;

import java.awt.*;
import java.awt.print.*;

import javax.swing.*;

/**
 * This program demonstrates how to show a simple table.
 * @version 1.13 2016-05-10
 * @author Cay Horstmann
 */
public class TableTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() ->
         {
            JFrame frame = new PlanetTableFrame();
            frame.setTitle("TableTest");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
         });
   }
}

/**
 * This frame contains a table of planet data.
 */
class PlanetTableFrame extends JFrame
{
   private String[] columnNames = { "Planet", "Radius", "Moons", "Gaseous", "Color" };
   private Object[][] cells = { { "Mercury", 2440.0, 0, false, Color.YELLOW },
         { "Venus", 6052.0, 0, false, Color.YELLOW }, { "Earth", 6378.0, 1, false, Color.BLUE },
         { "Mars", 3397.0, 2, false, Color.RED }, { "Jupiter", 71492.0, 16, true, Color.ORANGE },
         { "Saturn", 60268.0, 18, true, Color.ORANGE },
         { "Uranus", 25559.0, 17, true, Color.BLUE }, { "Neptune", 24766.0, 8, true, Color.BLUE },
         { "Pluto", 1137.0, 1, false, Color.BLACK } };

   public PlanetTableFrame()
   {
      final JTable table = new JTable(cells, columnNames);
      table.setAutoCreateRowSorter(true);
      add(new JScrollPane(table), BorderLayout.CENTER);
      JButton printButton = new JButton("Print");
      printButton.addActionListener(event ->
         {
            try { table.print(); }
            catch (SecurityException | PrinterException ex) { ex.printStackTrace(); }
         });
      JPanel buttonPanel = new JPanel();
      buttonPanel.add(printButton);
      add(buttonPanel, BorderLayout.SOUTH);
      pack();
   }
}


text:
layout: page
title: Shimika
---

* Coming soon...


text: Testing & deployment server for student projects.


text:
package org.apache.hadoop.record;

public class RecBuffer extends org.apache.hadoop.record.Record {
	private static final org.apache.hadoop.record.meta.RecordTypeInfo _rio_recTypeInfo;
	private static org.apache.hadoop.record.meta.RecordTypeInfo _rio_rtiFilter;
	private static int[] _rio_rtiFilterFields;
	static {
		_rio_recTypeInfo = new org.apache.hadoop.record.meta.RecordTypeInfo(
				"RecBuffer");
		_rio_recTypeInfo.addField("data",
				org.apache.hadoop.record.meta.TypeID.BufferTypeID);
	}

	private org.apache.hadoop.record.Buffer data;

	public RecBuffer() {
	}

	public RecBuffer(final org.apache.hadoop.record.Buffer data) {
		this.data = data;
	}

	public static org.apache.hadoop.record.meta.RecordTypeInfo getTypeInfo() {
		return _rio_recTypeInfo;
	}

	public static void setTypeFilter(
			org.apache.hadoop.record.meta.RecordTypeInfo rti) {
		if (null == rti)
			return;
		_rio_rtiFilter = rti;
		_rio_rtiFilterFields = null;
	}

	private static void setupRtiFields() {
		if (null == _rio_rtiFilter)
			return;
		// we may already have done this
		if (null != _rio_rtiFilterFields)
			return;
		int _rio_i, _rio_j;
		_rio_rtiFilterFields = new int[_rio_rtiFilter.getFieldTypeInfos()
				.size()];
		for (_rio_i = 0; _rio_i < _rio_rtiFilterFields.length; _rio_i++) {
			_rio_rtiFilterFields[_rio_i] = 0;
		}
		java.util.Iterator<org.apache.hadoop.record.meta.FieldTypeInfo> _rio_itFilter = _rio_rtiFilter
				.getFieldTypeInfos().iterator();
		_rio_i = 0;
		while (_rio_itFilter.hasNext()) {
			org.apache.hadoop.record.meta.FieldTypeInfo _rio_tInfoFilter = _rio_itFilter
					.next();
			java.util.Iterator<org.apache.hadoop.record.meta.FieldTypeInfo> _rio_it = _rio_recTypeInfo
					.getFieldTypeInfos().iterator();
			_rio_j = 1;
			while (_rio_it.hasNext()) {
				org.apache.hadoop.record.meta.FieldTypeInfo _rio_tInfo = _rio_it
						.next();
				if (_rio_tInfo.equals(_rio_tInfoFilter)) {
					_rio_rtiFilterFields[_rio_i] = _rio_j;
					break;
				}
				_rio_j++;
			}
			_rio_i++;
		}
	}

	public org.apache.hadoop.record.Buffer getData() {
		return data;
	}

	public void setData(final org.apache.hadoop.record.Buffer data) {
		this.data = data;
	}

	public void serialize(final org.apache.hadoop.record.RecordOutput _rio_a,
			final String _rio_tag) throws java.io.IOException {
		_rio_a.startRecord(this, _rio_tag);
		_rio_a.writeBuffer(data, "data");
		_rio_a.endRecord(this, _rio_tag);
	}

	private void deserializeWithoutFilter(
			final org.apache.hadoop.record.RecordInput _rio_a,
			final String _rio_tag) throws java.io.IOException {
		_rio_a.startRecord(_rio_tag);
		data = _rio_a.readBuffer("data");
		_rio_a.endRecord(_rio_tag);
	}

	public void deserialize(final org.apache.hadoop.record.RecordInput _rio_a,
			final String _rio_tag) throws java.io.IOException {
		if (null == _rio_rtiFilter) {
			deserializeWithoutFilter(_rio_a, _rio_tag);
			return;
		}
		// if we're here, we need to read based on version info
		_rio_a.startRecord(_rio_tag);
		setupRtiFields();
		for (int _rio_i = 0; _rio_i < _rio_rtiFilter.getFieldTypeInfos().size(); _rio_i++) {
			if (1 == _rio_rtiFilterFields[_rio_i]) {
				data = _rio_a.readBuffer("data");
			} else {
				java.util.ArrayList<org.apache.hadoop.record.meta.FieldTypeInfo> typeInfos = (java.util.ArrayList<org.apache.hadoop.record.meta.FieldTypeInfo>) (_rio_rtiFilter
						.getFieldTypeInfos());
				org.apache.hadoop.record.meta.Utils
						.skip(_rio_a, typeInfos.get(_rio_i).getFieldID(),
								typeInfos.get(_rio_i).getTypeID());
			}
		}
		_rio_a.endRecord(_rio_tag);
	}

	public int compareTo(final Object _rio_peer_) throws ClassCastException {
		if (!(_rio_peer_ instanceof RecBuffer)) {
			throw new ClassCastException(
					"Comparing different types of records.");
		}
		RecBuffer _rio_peer = (RecBuffer) _rio_peer_;
		int _rio_ret = 0;
		_rio_ret = data.compareTo(_rio_peer.data);
		if (_rio_ret != 0)
			return _rio_ret;
		return _rio_ret;
	}

	public boolean equals(final Object _rio_peer_) {
		if (!(_rio_peer_ instanceof RecBuffer)) {
			return false;
		}
		if (_rio_peer_ == this) {
			return true;
		}
		RecBuffer _rio_peer = (RecBuffer) _rio_peer_;
		boolean _rio_ret = false;
		_rio_ret = data.equals(_rio_peer.data);
		if (!_rio_ret)
			return _rio_ret;
		return _rio_ret;
	}

	public Object clone() throws CloneNotSupportedException {
		RecBuffer _rio_other = new RecBuffer();
		_rio_other.data = (org.apache.hadoop.record.Buffer) this.data.clone();
		return _rio_other;
	}

	public int hashCode() {
		int _rio_result = 17;
		int _rio_ret;
		_rio_ret = data.hashCode();
		_rio_result = 37 * _rio_result + _rio_ret;
		return _rio_result;
	}

	public static String signature() {
		return "LRecBuffer(B)";
	}

	public static class Comparator extends
			org.apache.hadoop.record.RecordComparator {
		public Comparator() {
			super(RecBuffer.class);
		}

		static public int slurpRaw(byte[] b, int s, int l) {
			try {
				int os = s;
				{
					int i = org.apache.hadoop.record.Utils.readVInt(b, s);
					int z = org.apache.hadoop.record.Utils.getVIntSize(i);
					s += z + i;
					l -= (z + i);
				}
				return (os - s);
			} catch (java.io.IOException e) {
				throw new RuntimeException(e);
			}
		}

		static public int compareRaw(byte[] b1, int s1, int l1, byte[] b2,
				int s2, int l2) {
			try {
				int os1 = s1;
				{
					int i1 = org.apache.hadoop.record.Utils.readVInt(b1, s1);
					int i2 = org.apache.hadoop.record.Utils.readVInt(b2, s2);
					int z1 = org.apache.hadoop.record.Utils.getVIntSize(i1);
					int z2 = org.apache.hadoop.record.Utils.getVIntSize(i2);
					s1 += z1;
					s2 += z2;
					l1 -= z1;
					l2 -= z2;
					int r1 = org.apache.hadoop.record.Utils.compareBytes(b1,
							s1, i1, b2, s2, i2);
					if (r1 != 0) {
						return (r1 < 0) ? -1 : 0;
					}
					s1 += i1;
					s2 += i2;
					l1 -= i1;
					l1 -= i2;
				}
				return (os1 - s1);
			} catch (java.io.IOException e) {
				throw new RuntimeException(e);
			}
		}

		public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
			int ret = compareRaw(b1, s1, l1, b2, s2, l2);
			return (ret == -1) ? -1 : ((ret == 0) ? 1 : 0);
		}
	}

	static {
		org.apache.hadoop.record.RecordComparator.define(RecBuffer.class,
				new Comparator());
	}
}


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

{% block body_id %}homepage{% endblock %}

{% block content %}

Not Found

We tried really hard, but couldn't find a regex that matches that path.
            Maybe you came here for the view, but there isn't one at this URL.

{% endblock %}


text:
autocommit off;
create class employees ( ssn  int);
create class employees_v under employees;
alter class employees_v drop attribute ssn;
rollback;


text:
    When using Code Completion, you can accept the currently highlighted selection in the popup list
      with the &shortcut:EditorChooseLookupItemReplace; key.

      Unlike accepting with the &shortcut:EditorChooseLookupItem; key, the selected name will overwrite
      the rest of the name to the right of the caret. This can be especially useful for replacing one method
      or variable name with another.


text:
const _ = require('lodash');
const limitService = require('../../services/limits');
const {events} = require('../../lib/common');
const logging = require('../../../shared/logging');
const trigger = require('./trigger');

const WEBHOOKS = [
    'site.changed',

    'post.added',
    'post.deleted',
    'post.edited',
    'post.published',
    'post.published.edited',
    'post.unpublished',
    'post.scheduled',
    'post.unscheduled',
    'post.rescheduled',

    'page.added',
    'page.deleted',
    'page.edited',
    'page.published',
    'page.published.edited',
    'page.unpublished',
    'page.scheduled',
    'page.unscheduled',
    'page.rescheduled',

    'tag.added',
    'tag.edited',
    'tag.deleted',

    'member.added',
    'member.deleted',
    'member.edited',

    'post.tag.attached',
    'post.tag.detached',
    'page.tag.attached',
    'page.tag.detached'
];

const listen = async () => {
    if (limitService.isLimited('customIntegrations')) {
        // NOTE: using "checkWouldGoOverLimit" instead of "checkIsOverLimit" here because flag limits don't have
        //       a concept of measuring if the limit has been surpassed
        const overLimit = await limitService.checkWouldGoOverLimit('customIntegrations');

        if (overLimit) {
            logging.info(`Skipped subscribing webhooks to events. The "customIntegrations" plan limit is enabled."`);
            return;
        }
    }

    _.each(WEBHOOKS, (event) => {
        events.on(event, (model, options) => {
            // CASE: avoid triggering webhooks when importing
            if (options && options.importing) {
                return;
            }

            trigger(event, model);
        });
    });
};

module.exports = listen;


text:
using namespace std;

int main(int argc, char* argv[]) {
  using namespace yafic;
  QtYaficDb yaficDb;
  return 0;
}


text:
package com.smallchill.common.pay.util;

import org.json.JSONObject;

public class JsonUtil {

	public static String getJsonValue(String rescontent, String key) {
		JSONObject jsonObject;
		String v = null;
		try {
			jsonObject = new JSONObject(rescontent);
			v = jsonObject.getString(key);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return v;
	}
}


text:
.. Copyright 2012 splinter authors. All rights reserved.
   Use of this source code is governed by a BSD-style
   license that can be found in the LICENSE file.

.. meta::
    :description: New splinter features on version 0.0.2.
    :keywords: splinter 0.0.2, python, news, documentation, tutorial, web application

[0.0.2]
=======

Features
--------

- fill instead of fill_in to fill inputs
- support to google chrome selenium 2 driver
- form interactions now support select
- issue #11: improve find's methods to return all/first/last elements

now finder methods (find_by_name, find_by_css_selector, find_by_tag, find_by_id, find_by_xpath) returns a ElementList object that contains a list of all found elements:

::

	browser.find_by_name('name')

.first - to find first element

::

	browser.find_by_name('name').first

.last - to find last element

::

	browser.find_by_name('name').last

And additionally, using index

::

	browser.find_by_name('name')[1]

An id should be unique in a web page, so find_by_id() method always returns a list with a single element.

Backward incompatible changes
-----------------------------

- issue #24 remove save_and_open_page method from splinter api. This feature is out of splinter's scope, hence should be implemented as an external package.
- now finder methods (find_by_name, find_by_css_selector, find_by_tag, find_by_id, find_by_xpath) returns a list with elements, to get the first element founded use `first` attribute

::

	browser.find_by_name('name').first


text:
include_recipe "bcpc::keystone"
include_recipe "bcpc::nova-head"

bash "nova-default-secgroup" do
    user "root"
    code <<-EOH
        . /root/adminrc
        nova secgroup-add-rule default icmp -1 -1 0.0.0.0/0
        nova secgroup-add-rule default tcp 22 22 0.0.0.0/0
    EOH
    not_if ". /root/adminrc; nova secgroup-list-rules default | grep icmp"
end

bash "nova-floating-add" do
    user "root"
    code <<-EOH
        . /root/adminrc
        nova-manage floating create --ip_range=#{node['bcpc']['floating']['available_subnet']} --pool #{node['bcpc']['region_name']}
    EOH
    only_if ". /root/adminrc; nova-manage floating list | grep \"No floating IP addresses have been defined\""
end

bash "nova-fixed-add" do
    user "root"
    code <<-EOH
        . /root/adminrc
        nova-manage network create --label fixed --fixed_range_v4=#{node['bcpc']['fixed']['cidr']} --num_networks=#{node['bcpc']['fixed']['num_networks']} --multi_host=T --network_size=#{node['bcpc']['fixed']['network_size']} --vlan_start=#{node['bcpc']['fixed']['vlan_start']}
    EOH
    only_if ". /root/adminrc; nova-manage network list | grep \"No networks found\""
end


text:
package com.example.alexis.navitia_android;

import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;

/**
 * @author Alexis Robin
 * @version 0.6
 * Licensed under the Apache2 license
 */
public class Address implements Parcelable {

    protected double lat, lon;
    protected String name;
    protected int icon, nameId;

    public Address(){

    }

    public Address(String name, int icon){
        this.name = name;
        this.icon = icon;
    }

    public Address(int name, int icon){
        this.nameId = name;
        this.icon = icon;
    }

    public Address(String name, int icon, double lat, double lon){
        this.name = name;
        this.icon = icon;
        this.lat = lat;
        this.lon = lon;
    }

    public Address(int name, int icon, double lat, double lon){
        this.nameId = name;
        this.icon = icon;
        this.lat = lat;
        this.lon = lon;
    }

    public Address(Parcel in){
        name = in.readString();
        icon = in.readInt();
        nameId = in.readInt();
        lat = in.readDouble();
        lon = in.readDouble();
    }

    public String getName(Context c){
        return (name != null) ? name : c.getString(nameId);
    }

    public int getIcon(){
        return icon;
    }

    public double getLongitude(){
        return lat;
    }
    public double getLatitude(){
        return lon;
    }

    public void setLatitude(double lat){
        this.lat = lat;
    }

    public void setLongitude(double lon){
        this.lon = lon;
    }

    @Override
    public String toString(){
        return this.name;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(icon);
        dest.writeInt(nameId);
        dest.writeDouble(lat);
        dest.writeDouble(lon);
    }

    public static final Creator CREATOR =
            new Creator() {

                @Override
                public Object createFromParcel(Parcel in) {
                    return new Address(in);
                }

                public Address[] newArray(int size) {
                    return new Address[size];
                }
            };

}


text:
using UnityEngine;
using System.Collections;

public class XftVolumeFogObject : MonoBehaviour {
    protected MeshRenderer FogObject;
    protected float Radius = 10f;
    public Material VolumFogMaterial;
    public Color FogColor = Color.white;

    void Awake()
    {
        FogObject = gameObject.GetComponent<MeshRenderer>();
        if (FogObject == null)
        {
            Debug.LogError("Volume Fog Object must have a MeshRenderer Component!");
        }
    }

    void OnEnable()
    {
        //Note: In forward lightning path, the depth texture is not automatically generated.
        if (Camera.main.depthTextureMode == DepthTextureMode.None)
            Camera.main.depthTextureMode = DepthTextureMode.Depth;
    }

    void Start()
    {
        FogObject.material = VolumFogMaterial;
        FogObject.material.SetColor("_FogColor", FogColor);
        Radius = (transform.localScale.x + transform.localScale.y + transform.localScale.z) / 6;
        FogObject.material.SetVector("FogParam", new Vector4(transform.position.x, transform.position.y, transform.position.z, Radius));
    }

	void Update ()
    {

	}
}


text:
<!DOCTYPE html>

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

  <title>Introducing JASP: A free and intuitive statistics software that might finally replace SPSS</title>

  <meta name="author" content="JEPS Bulletin" />

  <link rel="alternate" type="application/rss+xml" title="Our Journal - A virtual proof that name is awesome!" href="/feed.xml" />

      <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" />

      <link rel="stylesheet" href="/css/bootstrap.min.css" />

      <link rel="stylesheet" href="/css/main.css" />

	  <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" />

	  <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" />

  <meta property="og:title" content="Introducing JASP: A free and intuitive statistics software that might finally replace SPSS" />
  <meta property="og:type" content="website" />

  <meta property="og:url" content="http://jeps.efpsa.org/2015-09-01-introducing-jasp-a-free-and-intuitive-statistics-software-that-might-finally-replace-spss/" />

  <meta property="og:image" content="" />

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-navbar">
        Toggle navigation

      </button>
      Our Journal

	      Home

	      About

	      Search

	      Contribute

Introducing JASP: A free and intuitive statistics software that might finally replace SPSS

        Posted on September 1, 2015

Are you tired of SPSS's confusing menus and of the ugly tables it generates? Are you annoyed by having statistical software only at university computers? Would you like to use advanced techniques such as Bayesian statistics, but you lack the time to learn a programming language (like R or Python) because you prefer to focus on your research?

While there was no real solution to this problem for a long time, there is now good news for you! A group of researchers at the University of Amsterdam are developing JASP, a free open-source statistics package that includes both standard and more advanced techniques and puts major emphasis on providing an intuitive user interface.

The current version already supports a large array of analyses, including the ones typically used by researchers in the field of psychology (e.g. ANOVA, t-tests, multiple regression).

In addition to being open source, freely available for all platforms, and providing a considerable number of analyses, JASP also comes with several neat, distinctive features, such as real-time computation and display of all results. For example, if you decide that you want not only the mean but also the median in the table, you can tick "Median" to have the medians appear immediately in the results table. For comparison, think how this works in SPSS: First, you must navigate a forest of menus (or edit the syntax), then, you execute the new syntax. A new window appears and you get a new (ugly) table.

In JASP, you get better-looking tables in no time. Click here to see a short demonstration of this feature. But it gets even better—the tables are already in APA format and you can copy and paste them into Word. Sounds too good to be true, doesn't it? It does, but it works!

Interview with lead developer Jonathon Love

Where is this software project coming from? Who pays for all of this? And what plans are there for the future? There is nobody who could answer these questions better than the lead developer of JASP, Jonathon Love, who was so kind as to answer a few questions about JASP.

How did development on JASP start? How did you get involved in the project?

All through my undergraduate program, we used SPSS, and it struck me just how suboptimal it was. As a software designer, I find poorly designed software somewhat distressing to use, and so SPSS was something of a thorn in my mind for four years. I was always thinking things like, "Oh, what? I have to completely re-run the analysis, because I forgot X?," "Why can't I just click on the output to see what options were used?," "Why do I have to read this awful syntax?," or "Why have they done this like this? Surely they should do this like that!"

At the same time, I was working for Andrew Heathcote, writing software for analyzing response time data. We were using the R programming language and so I was exposed to this vast trove of statistical packages that R provides. On one hand, as a programmer, I was excited to gain access to all these statistical techniques. On the other hand, as someone who wants to empower as many people as possible, I was disappointed by the difficulty of using R and by the very limited options to provide a good user interface with it.

So I saw that there was a real need for both of these things—software providing an attractive, free, and open statistics package to replace SPSS, and a platform for methodologists to publish their analyses with rich, accessible user interfaces. However, the project was far too ambitious to consider without funding, and so I couldn't see any way to do it.

Then I met E.J. Wagenmakers, who had just received a European Research Council grant to develop an SPSS-like software package to provide Bayesian methods, and he offered me the position to develop it. I didn't know a lot about Bayesian methods at the time, but I did see that our goals had a lot of overlap.

So I said, "Of course, we would have to implement classical statistics as well," and E.J.'s immediate response was, "Nooooooooooo!" But he quickly saw how significant this would be. If we can liberate the underlying platform that scientists use, then scientists (including ourselves) can provide whatever analyses we like.

And so that was how the JASP project was born, and how the three goals came together:

to provide a liberated (free and open) alternative to SPSS

to provide Bayesian analyses in an accessible way

to provide a universal platform for publishing analyses with accessible user interfaces

What are the biggest challenges for you as a lead developer of JASP?

Remaining focused. There are hundreds of goals, and hundreds of features that we want to implement, but we must prioritize ruthlessly. When will we implement factor analysis? When will we finish the SEM module? When will data entry, editing, and restructuring arrive? Outlier exclusion? Computing of variables? These are all such excellent, necessary features; it can be really hard to decide what should come next. Sometimes it can feel a bit overwhelming too. There's so much to do! I have to keep reminding myself how much progress we're making.

Maintaining a consistent user experience is a big deal too. The JASP team is really large, to give you an idea, in addition to myself there's:

Ravi Selker, developing the frequentist analyses

Maarten Marsman, developing the Bayesian ANOVAs and  Bayesian linear regression

Tahira Jamil, developing the classical and Bayesian contingency tables

Damian Dropmann, developing the file save, load functionality, and the annotation system

Alexander Ly, developing the Bayesian correlation

Quentin Gronau, developing the Bayesian plots and the classical linear regression

Dora Matzke, developing the help system

Patrick Knight, developing the SPSS importer

Eric-Jan Wagenmakers, coming up with new Bayesian techniques and visualizations

With such a large team, developing the software and all the analyses in a consistent and coherent way can be really challenging. It's so easy for analyses to end up a mess of features, and for every subsequent analysis we add to look nothing like the last. Of course, providing as elegant and consistent a user-experience is one of our highest priorities, so we put a lot of effort into this.

How do you imagine JASP five years from now?

JASP will provide the same, silky, sexy user experience that it does now. However, by then it will have full data entering, editing, cleaning, and restructuring facilities. It will provide all the common analyses used through undergraduate and postgraduate psychology programs. It will provide comprehensive help documentation, an abundance of examples, and a number of online courses. There will be textbooks available. It will have a growing community of methodologists publishing the analyses they are developing as additional JASP modules, and applied researchers will have access to the latest cutting-edge analyses in a way that they can understand and master. More students will like statistics than ever before.

How can JASP stay up to date with state-of-the-art statistical methods? Even when borrowing implementations written in R and the like, these always have to be implemented by you in JASP. Is there a solution to this problem?

Well, if SPSS has taught us anything, you really don't need to stay up to date to be a successful statistical product, ha-ha! The plan is to provide tools for methodologists to write add-on modules for JASP—tools for creating user interfaces and tools to connect these user interfaces to their underlying analyses. Once an add-on module is developed, it can appear in a directory, or a sort of "App Store," and people will be able to rate the software for different things: stability, user-friendliness, attractiveness of output, and so forth. In this way, we hope to incentivize a good user experience as much as possible.

Some people think this will never work—that methodologists will never put in all that effort to create nice, useable software (because it does take substantial effort). But I think that once methodologists grasp the importance of making their work accessible to as wide an audience as possible, it will become a priority for them. For example, consider the following scenario: Alice provides a certain analysis with a nice user interface. Bob develops an analysis that is much better than Alice's analysis, but everyone uses Alice's, because hers is so easy and convenient to use. Bob is upset because everyone uses Alice's instead of his. Bob then realizes that he has to provide a nice, accessible user experience for people to use his analysis.

I hope that we can create an arms race in which methodologists will strive to provide as good a user experience as possible. If you develop a new method and nobody can use it, have you really developed a new method? Of course, this sort of add-on facility isn't ready yet, but I don't think it will be too far away.

You mention on your website that many more methods will be included, such as structural equation modeling (SEM) or tools for data manipulation. How can you both offer a large amount of features without cluttering the user interface in the future?

Currently, JASP uses a ribbon arrangement; we have a "File" tab for file operations, and we have a "Common" tab that provides common analyses. As we add more analyses (and as other people begin providing additional modules), these will be provided as additional tabs. The user will be able to toggle on or off which tabs they are interested in. You can see this in the current version of JASP: we have a proof-of-concept SEM module that you can toggle on or off on the options page. JASP thus provides you only with what you actually need, and the user interface can be kept as simple as you like.

Students who are considering switching to JASP might want to know whether the future of JASP development is secured or dependent on getting new grants. What can you tell us about this?

JASP is currently funded by a European Research Council (ERC) grant, and we've also received some support from the Centre for Open Science. Additionally, the University of Amsterdam has committed to providing us a software developer on an ongoing basis, and we've just run our first annual Bayesian Statistics in JASP workshop. The money we charge for these workshops is plowed straight back into JASP's development.

We're also developing a number of additional strategies to increase the funding that the JASP project receives. Firstly, we're planning to provide technical support to universities and businesses that make use of JASP, for a fee. Additionally, we're thinking of simply asking universities to contribute the cost of a single SPSS license to the JASP project. It would represent an excellent investment; it would allow us to accelerate development, achieve feature parity with SPSS sooner, and allow universities to abandon SPSS and its costs sooner. So I don't worry about securing JASP's future, I'm thinking about how we can expand JASP's future.

Of course, all of this depends on people actually using JASP, and that will come down to the extent that the scientific community decides to use and get behind the JASP project. Indeed, the easiest way that people can support the JASP project is by simply using and citing it. The more users and the more citations we have, the easier it is for us to obtain funding.

Having said all that, I'm less worried about JASP's future development than I'm worried about SPSS's! There's almost no evidence that any development work is being done on it at all! Perhaps we should pass the hat around for IBM.

What is the best way to get started with JASP? Are there tutorials and reproducible examples?

For classical statistics, if you've used SPSS, or if you have a book on statistics in SPSS, I don't think you'll have any difficulty using JASP. It's designed to be familiar to users of SPSS, and our experience is that most people have no difficulty moving from SPSS to JASP. We also have a video on our website that demonstrates some basic analyses, and we're planning to create a whole series of these.

As for the Bayesian statistics, that's a little more challenging. Most of our effort has been going in to getting the software ready, so we don't have as many resources for learning Bayesian statistics ready as we would like. This is something we'll be looking at addressing in the next six to twelve months. E.J. has at least one (maybe three) books planned.

That said, there are a number of resources available now, such as:

Alexander Etz's blog

E.J.'s website provides a number of papers on Bayesian statistics (his website also serves as a reminder of what the internet looked like in the '80s)

Zoltan Dienes book is a great for Bayesian statistics as well

However, the best way to learn Bayesian statistics is to come to one of our Bayesian Statistics with JASP workshops. We've run two so far and they've been very well received. Some people have been reluctant to attend—because JASP is so easy to use, they didn't see the point of coming and learning it. Of course, that's the whole point! JASP is so easy to use, you don't need to learn the software, and you can completely concentrate on learning the Bayesian concepts. So keep an eye out on the JASP website for the next workshop. Bayes is only going to get more important in the future. Don't be left behind!

        ← Previous Post

        Next Post →

	Please enable JavaScript to view the comments powered by Disqus.

		  JEPS Bulletin
		   •
		  2015

		   •
		  jeps.efpsa.org

		  Theme by
		  beautiful-jekyll


text:
var fs = require('fs');
if (! fs) process.exit(1);

if (process.argv.length < 4) {
	console.log("Syntax: fileName string");
	process.exit(2);
}

var fileName = process.argv[2];
var textToFind = process.argv[3];
var readStream = fs.createReadStream(fileName);;
var oldBlob = "";
var index = -1;

readStream.on("data", function(blob) {
			console.log("Read " + blob.length +  " bytes");
			var newBlob = oldBlob + blob;
			index = newBlob.indexOf(textToFind);
			if (index >= 0) readStream.emit("end");
			oldBlob = blob;
		} );

readStream.on("end", function() {
		if (index>=0)
			console.log("Found string " + textToFind);
		else
			console.log("Did not find string " + textToFind);
	} );

readStream.on("error", function() {
		console.log("Error occurred when reading from file " + fileName);
	} );

console.log("End of program");


text:
using System;
using System.Linq;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PhysX.Test.Controller
{
	[TestClass]
	public class ControllerTest : Test
	{
		[TestMethod]
		public void ControllerStateIsValid()
		{
			using (var core = CreatePhysicsAndScene())
			{
				var controllerManager = core.Scene.CreateControllerManager();

				var material = core.Physics.CreateMaterial(0.1f, 0.1f, 0.1f);

				var desc = new CapsuleControllerDesc()
				{
					Height = 12,
					Radius = 7,
					Material = material,
					Position = new Vector3(0, 25, 0)
				};

				// Create a capsule controller
				var capsuleController = controllerManager.CreateController<CapsuleController>(desc);

				// A box for it to fall on to
				var box = CreateBoxActor(core.Scene, new Vector3(10, 1, 10), new Vector3(0, 0.5f, 0));

				// Make it fall
				for (int i = 0; i < 200; i++)
				{
					capsuleController.Move(new Vector3(0, -0.3f, 0), TimeSpan.FromMilliseconds(0.1));

					core.Scene.Simulate(0.1f);
					core.Scene.FetchResults(block: true);
				}

				//

				var controllerState = capsuleController.GetState();

				Assert.IsNotNull(controllerState);
				Assert.AreEqual(box.Shapes.First(), controllerState.TouchedShape);
				Assert.AreEqual(box, controllerState.TouchedActor);
				Assert.AreEqual(ControllerCollisionFlag.Down, controllerState.CollisionFlags);
			}
		}
	}
}


text:
<?php

final class PhabricatorMemeEngine extends Phobject {

  private $viewer;
  private $template;
  private $aboveText;
  private $belowText;

  private $templateFile;
  private $metrics;

  public function setViewer(PhabricatorUser $viewer) {
    $this->viewer = $viewer;
    return $this;
  }

  public function getViewer() {
    return $this->viewer;
  }

  public function setTemplate($template) {
    $this->template = $template;
    return $this;
  }

  public function getTemplate() {
    return $this->template;
  }

  public function setAboveText($above_text) {
    $this->aboveText = $above_text;
    return $this;
  }

  public function getAboveText() {
    return $this->aboveText;
  }

  public function setBelowText($below_text) {
    $this->belowText = $below_text;
    return $this;
  }

  public function getBelowText() {
    return $this->belowText;
  }

  public function getGenerateURI() {
    $params = array(
      'macro' => $this->getTemplate(),
      'above' => $this->getAboveText(),
      'below' => $this->getBelowText(),
    );

    return new PhutilURI('/macro/meme/', $params);
  }

  public function newAsset() {
    $cache = $this->loadCachedFile();
    if ($cache) {
      return $cache;
    }

    $template = $this->loadTemplateFile();
    if (!$template) {
      throw new Exception(
        pht(
          'Template "%s" is not a valid template.',
          $template));
    }

    $hash = $this->newTransformHash();

    $asset = $this->newAssetFile($template);

    $xfile = id(new PhabricatorTransformedFile())
      ->setOriginalPHID($template->getPHID())
      ->setTransformedPHID($asset->getPHID())
      ->setTransform($hash);

    try {
      $caught = null;

      $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
      try {
        $xfile->save();
      } catch (Exception $ex) {
        $caught = $ex;
      }
      unset($unguarded);

      if ($caught) {
        throw $caught;
      }

      return $asset;
    } catch (AphrontDuplicateKeyQueryException $ex) {
      $xfile = $this->loadCachedFile();
      if (!$xfile) {
        throw $ex;
      }
      return $xfile;
    }
  }

  private function newTransformHash() {
    $properties = array(
      'kind' => 'meme',
      'above' => $this->getAboveText(),
      'below' => $this->getBelowText(),
    );

    $properties = phutil_json_encode($properties);

    return PhabricatorHash::digestForIndex($properties);
  }

  public function loadCachedFile() {
    $viewer = $this->getViewer();

    $template_file = $this->loadTemplateFile();
    if (!$template_file) {
      return null;
    }

    $hash = $this->newTransformHash();

    $xform = id(new PhabricatorTransformedFile())->loadOneWhere(
      'originalPHID = %s AND transform = %s',
      $template_file->getPHID(),
      $hash);
    if (!$xform) {
      return null;
    }

    return id(new PhabricatorFileQuery())
      ->setViewer($viewer)
      ->withPHIDs(array($xform->getTransformedPHID()))
      ->executeOne();
  }

  private function loadTemplateFile() {
    if ($this->templateFile === null) {
      $viewer = $this->getViewer();
      $template = $this->getTemplate();

      $macro = id(new PhabricatorMacroQuery())
        ->setViewer($viewer)
        ->withNames(array($template))
        ->needFiles(true)
        ->executeOne();
      if (!$macro) {
        return null;
      }

      $this->templateFile = $macro->getFile();
    }

    return $this->templateFile;
  }

  private function newAssetFile(PhabricatorFile $template) {
    $data = $this->newAssetData($template);
    return PhabricatorFile::newFromFileData(
      $data,
      array(
        'name' => 'meme-'.$template->getName(),
        'canCDN' => true,

        // In modern code these can end up linked directly in email, so let
        // them stick around for a while.
        'ttl.relative' => phutil_units('30 days in seconds'),
      ));
  }

  private function newAssetData(PhabricatorFile $template) {
    $template_data = $template->loadFileData();

    // When we aren't adding text, just return the data unmodified. This saves
    // us from doing expensive stitching when we aren't actually making any
    // changes to the image.
    $above_text = $this->getAboveText();
    $below_text = $this->getBelowText();
    if (!strlen(trim($above_text)) && !strlen(trim($below_text))) {
      return $template_data;
    }

    $result = $this->newImagemagickAsset($template, $template_data);
    if ($result) {
      return $result;
    }

    return $this->newGDAsset($template, $template_data);
  }

  private function newImagemagickAsset(
    PhabricatorFile $template,
    $template_data) {

    // We're only going to use Imagemagick on GIFs.
    $mime_type = $template->getMimeType();
    if ($mime_type != 'image/gif') {
      return null;
    }

    // We're only going to use Imagemagick if it is actually available.
    $available = PhabricatorEnv::getEnvConfig('files.enable-imagemagick');
    if (!$available) {
      return null;
    }

    // Test of the GIF is an animated GIF. If it's a flat GIF, we'll fall
    // back to GD.
    $input = new TempFile();
    Filesystem::writeFile($input, $template_data);
    list($err, $out) = exec_manual('convert %s info:', $input);
    if ($err) {
      return null;
    }

    $split = phutil_split_lines($out);
    $frames = count($split);
    if ($frames <= 1) {
      return null;
    }

    // Split the frames apart, transform each frame, then merge them back
    // together.
    $output = new TempFile();

    $future = new ExecFuture(
      'convert %s -coalesce +adjoin %s_%s',
      $input,
      $input,
      '%09d');
    $future->setTimeout(10)->resolvex();

    $output_files = array();
    for ($ii = 0; $ii < $frames; $ii++) {
      $frame_name = sprintf('%s_%09d', $input, $ii);
      $output_name = sprintf('%s_%09d', $output, $ii);

      $output_files[] = $output_name;

      $frame_data = Filesystem::readFile($frame_name);
      $memed_frame_data = $this->newGDAsset($template, $frame_data);
      Filesystem::writeFile($output_name, $memed_frame_data);
    }

    $future = new ExecFuture(
      'convert -dispose background -loop 0 %Ls %s',
      $output_files,
      $output);
    $future->setTimeout(10)->resolvex();

    return Filesystem::readFile($output);
  }

  private function newGDAsset(PhabricatorFile $template, $data) {
    $img = imagecreatefromstring($data);
    if (!$img) {
      throw new Exception(
        pht('Failed to imagecreatefromstring() image template data.'));
    }

    $dx = imagesx($img);
    $dy = imagesy($img);

    $metrics = $this->getMetrics($dx, $dy);
    $font = $this->getFont();
    $size = $metrics['size'];

    $above = $this->getAboveText();
    if (strlen($above)) {
      $x = (int)floor(($dx - $metrics['text']['above']['width']) / 2);
      $y = $metrics['text']['above']['height'] + 12;

      $this->drawText($img, $font, $metrics['size'], $x, $y, $above);
    }

    $below = $this->getBelowText();
    if (strlen($below)) {
      $x = (int)floor(($dx - $metrics['text']['below']['width']) / 2);
      $y = $dy - 12 - $metrics['text']['below']['descend'];

      $this->drawText($img, $font, $metrics['size'], $x, $y, $below);
    }

    return PhabricatorImageTransformer::saveImageDataInAnyFormat(
      $img,
      $template->getMimeType());
  }

  private function getFont() {
    $phabricator_root = dirname(phutil_get_library_root('phabricator'));

    $font_root = $phabricator_root.'/resources/font/';
    if (Filesystem::pathExists($font_root.'impact.ttf')) {
      $font_path = $font_root.'impact.ttf';
    } else {
      $font_path = $font_root.'tuffy.ttf';
    }

    return $font_path;
  }

  private function getMetrics($dim_x, $dim_y) {
    if ($this->metrics === null) {
      $font = $this->getFont();

      $font_max = 72;
      $font_min = 5;

      $margin_x = 16;
      $margin_y = 16;

      $last = null;
      $cursor = floor(($font_max + $font_min) / 2);
      $min = $font_min;
      $max = $font_max;

      $texts = array(
        'above' => $this->getAboveText(),
        'below' => $this->getBelowText(),
      );

      $metrics = null;
      $best = null;
      while (true) {
        $all_fit = true;
        $text_metrics = array();
        foreach ($texts as $key => $text) {
          $box = imagettfbbox($cursor, 0, $font, $text);
          $height = abs($box[3] - $box[5]);
          $width = abs($box[0] - $box[2]);

          // This is the number of pixels below the baseline that the
          // text extends, for example if it has a "y".
          $descend = $box[3];

          if (($height + $margin_y) > $dim_y) {
            $all_fit = false;
            break;
          }

          if (($width + $margin_x) > $dim_x) {
            $all_fit = false;
            break;
          }

          $text_metrics[$key]['width'] = $width;
          $text_metrics[$key]['height'] = $height;
          $text_metrics[$key]['descend'] = $descend;
        }

        if ($all_fit || $best === null) {
          $best = $cursor;
          $metrics = $text_metrics;
        }

        if ($all_fit) {
          $min = $cursor;
        } else {
          $max = $cursor;
        }

        $last = $cursor;
        $cursor = floor(($max + $min) / 2);
        if ($cursor === $last) {
          break;
        }
      }

      $this->metrics = array(
        'size' => $best,
        'text' => $metrics,
      );
    }

    return $this->metrics;
  }

  private function drawText($img, $font, $size, $x, $y, $text) {
    $text_color = imagecolorallocate($img, 255, 255, 255);
    $border_color = imagecolorallocate($img, 0, 0, 0);

    $border = 2;
    for ($xx = ($x - $border); $xx <= ($x + $border); $xx += $border) {
      for ($yy = ($y - $border); $yy <= ($y + $border); $yy += $border) {
        if (($xx === $x) && ($yy === $y)) {
          continue;
        }
        imagettftext($img, $size, 0, $xx, $yy, $border_color, $font, $text);
      }
    }

    imagettftext($img, $size, 0, $x, $y, $text_color, $font, $text);
  }

}


text:
/*global angular */
/*jshint unused:false */
'use strict';

/**
 * @type {angular.Module}
 */
var gyroscroll = angular.module('gyroscroll', ['adaptive.scroll']);