text:
import * as ACTIONS from 'constants/action_types';
import { Lbryio } from 'lbryinc';
import { SETTINGS, Lbry, doWalletEncrypt, doWalletDecrypt } from 'lbry-redux';
import { selectGetSyncIsPending, selectSetSyncIsPending, selectSyncIsLocked } from 'redux/selectors/sync';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import { getSavedPassword } from 'util/saved-passwords';
import { doAnalyticsTagSync, doHandleSyncComplete } from 'redux/actions/app';
import { selectUserVerifiedEmail } from 'redux/selectors/user';

let syncTimer = null;
const SYNC_INTERVAL = 1000 * 60 * 5; // 5 minutes
const NO_WALLET_ERROR = 'no wallet found for this user';
const BAD_PASSWORD_ERROR_NAME = 'InvalidPasswordError';

export function doSetDefaultAccount(success, failure) {
  return (dispatch) => {
    dispatch({
      type: ACTIONS.SET_DEFAULT_ACCOUNT,
    });

    Lbry.account_list()
      .then((accountList) => {
        const { lbc_mainnet: accounts } = accountList;
        let defaultId;
        for (let i = 0; i < accounts.length; ++i) {
          if (accounts[i].satoshis > 0) {
            defaultId = accounts[i].id;
            break;
          }
        }

        // In a case where there's no balance on either account
        // assume the second (which is created after sync) as default
        if (!defaultId && accounts.length > 1) {
          defaultId = accounts[1].id;
        }

        // Set the default account
        if (defaultId) {
          Lbry.account_set({ account_id: defaultId, default: true })
            .then(() => {
              if (success) {
                success();
              }
            })
            .catch((err) => {
              if (failure) {
                failure(err);
              }
            });
        } else if (failure) {
          // no default account to set
          failure('Could not set a default account'); // fail
        }
      })
      .catch((err) => {
        if (failure) {
          failure(err);
        }
      });
  };
}

export function doSetSync(oldHash, newHash, data) {
  return (dispatch) => {
    dispatch({
      type: ACTIONS.SET_SYNC_STARTED,
    });

    return Lbryio.call('sync', 'set', { old_hash: oldHash, new_hash: newHash, data }, 'post')
      .then((response) => {
        if (!response.hash) {
          throw Error('No hash returned for sync/set.');
        }

        return dispatch({
          type: ACTIONS.SET_SYNC_COMPLETED,
          data: { syncHash: response.hash },
        });
      })
      .catch((error) => {
        dispatch({
          type: ACTIONS.SET_SYNC_FAILED,
          data: { error },
        });
      });
  };
}

export const doGetSyncDesktop = (cb?, password) => (dispatch, getState) => {
  const state = getState();
  const syncEnabled = makeSelectClientSetting(SETTINGS.ENABLE_SYNC)(state);
  const getSyncPending = selectGetSyncIsPending(state);
  const setSyncPending = selectSetSyncIsPending(state);
  const syncLocked = selectSyncIsLocked(state);

  return getSavedPassword().then((savedPassword) => {
    const passwordArgument = password || password === '' ? password : savedPassword === null ? '' : savedPassword;

    if (syncEnabled && !getSyncPending && !setSyncPending && !syncLocked) {
      return dispatch(doGetSync(passwordArgument, cb));
    }
  });
};

export function doSyncLoop(noInterval) {
  return (dispatch, getState) => {
    if (!noInterval && syncTimer) clearInterval(syncTimer);
    const state = getState();
    const hasVerifiedEmail = selectUserVerifiedEmail(state);
    const syncEnabled = makeSelectClientSetting(SETTINGS.ENABLE_SYNC)(state);
    const syncLocked = selectSyncIsLocked(state);
    if (hasVerifiedEmail && syncEnabled && !syncLocked) {
      dispatch(doGetSyncDesktop((error, hasNewData) => dispatch(doHandleSyncComplete(error, hasNewData))));
      dispatch(doAnalyticsTagSync());
      if (!noInterval) {
        syncTimer = setInterval(() => {
          const state = getState();
          const syncEnabled = makeSelectClientSetting(SETTINGS.ENABLE_SYNC)(state);
          if (syncEnabled) {
            dispatch(doGetSyncDesktop((error, hasNewData) => dispatch(doHandleSyncComplete(error, hasNewData))));
            dispatch(doAnalyticsTagSync());
          }
        }, SYNC_INTERVAL);
      }
    }
  };
}

export function doSyncUnsubscribe() {
  return (dispatch) => {
    if (syncTimer) {
      clearInterval(syncTimer);
    }
  };
}

export function doGetSync(passedPassword, callback) {
  const password = passedPassword === null || passedPassword === undefined ? '' : passedPassword;

  function handleCallback(error, hasNewData) {
    if (callback) {
      if (typeof callback !== 'function') {
        throw new Error('Second argument passed to "doGetSync" must be a function');
      }

      callback(error, hasNewData);
    }
  }

  return (dispatch) => {
    dispatch({
      type: ACTIONS.GET_SYNC_STARTED,
    });

    const data = {};

    Lbry.wallet_status()
      .then((status) => {
        if (status.is_locked) {
          return Lbry.wallet_unlock({ password });
        }

        // Wallet is already unlocked
        return true;
      })
      .then((isUnlocked) => {
        if (isUnlocked) {
          return Lbry.sync_hash();
        }
        data.unlockFailed = true;
        throw new Error();
      })
      .then((hash) => Lbryio.call('sync', 'get', { hash }, 'post'))
      .then((response) => {
        const syncHash = response.hash;
        data.syncHash = syncHash;
        data.syncData = response.data;
        data.changed = response.changed;
        data.hasSyncedWallet = true;

        if (response.changed) {
          return Lbry.sync_apply({ password, data: response.data, blocking: true });
        }
      })
      .then((response) => {
        if (!response) {
          dispatch({ type: ACTIONS.GET_SYNC_COMPLETED, data });
          handleCallback(null, data.changed);
          return;
        }

        const { hash: walletHash, data: walletData } = response;

        if (walletHash !== data.syncHash) {
          // different local hash, need to synchronise
          dispatch(doSetSync(data.syncHash, walletHash, walletData));
        }

        dispatch({ type: ACTIONS.GET_SYNC_COMPLETED, data });
        handleCallback(null, data.changed);
      })
      .catch((syncAttemptError) => {
        const badPasswordError =
          syncAttemptError && syncAttemptError.data && syncAttemptError.data.name === BAD_PASSWORD_ERROR_NAME;

        if (data.unlockFailed) {
          dispatch({ type: ACTIONS.GET_SYNC_FAILED, data: { error: syncAttemptError } });

          if (badPasswordError) {
            dispatch({ type: ACTIONS.SYNC_APPLY_BAD_PASSWORD });
          }

          handleCallback(syncAttemptError);
        } else if (data.hasSyncedWallet) {
          const error = (syncAttemptError && syncAttemptError.message) || 'Error getting synced wallet';
          dispatch({
            type: ACTIONS.GET_SYNC_FAILED,
            data: {
              error,
            },
          });

          if (badPasswordError) {
            dispatch({ type: ACTIONS.SYNC_APPLY_BAD_PASSWORD });
          }

          handleCallback(error);
        } else {
          const noWalletError = syncAttemptError && syncAttemptError.message === NO_WALLET_ERROR;

          dispatch({
            type: ACTIONS.GET_SYNC_COMPLETED,
            data: {
              hasSyncedWallet: false,
              syncHash: null,
              // If there was some unknown error, bail
              fatalError: !noWalletError,
            },
          });

          // user doesn't have a synced wallet
          //   call sync_apply to get data to sync
          //   first time sync. use any string for old hash
          if (noWalletError) {
            Lbry.sync_apply({ password })
              .then(({ hash: walletHash, data: syncApplyData }) => {
                dispatch(doSetSync('', walletHash, syncApplyData, password));
                handleCallback();
              })
              .catch((syncApplyError) => {
                handleCallback(syncApplyError);
              });
          }
        }
      });
  };
}

export function doSyncApply(syncHash, syncData, password) {
  return (dispatch) => {
    dispatch({
      type: ACTIONS.SYNC_APPLY_STARTED,
    });

    Lbry.sync_apply({ password, data: syncData })
      .then(({ hash: walletHash, data: walletData }) => {
        dispatch({
          type: ACTIONS.SYNC_APPLY_COMPLETED,
        });

        if (walletHash !== syncHash) {
          // different local hash, need to synchronise
          dispatch(doSetSync(syncHash, walletHash, walletData));
        }
      })
      .catch(() => {
        dispatch({
          type: ACTIONS.SYNC_APPLY_FAILED,
          data: {
            error: 'Invalid password specified. Please enter the password for your previously synchronised wallet.',
          },
        });
      });
  };
}

export function doCheckSync() {
  return (dispatch) => {
    dispatch({
      type: ACTIONS.GET_SYNC_STARTED,
    });

    Lbry.sync_hash().then((hash) => {
      Lbryio.call('sync', 'get', { hash }, 'post')
        .then((response) => {
          const data = {
            hasSyncedWallet: true,
            syncHash: response.hash,
            syncData: response.data,
            hashChanged: response.changed,
          };
          dispatch({ type: ACTIONS.GET_SYNC_COMPLETED, data });
        })
        .catch(() => {
          // user doesn't have a synced wallet
          dispatch({
            type: ACTIONS.GET_SYNC_COMPLETED,
            data: { hasSyncedWallet: false, syncHash: null },
          });
        });
    });
  };
}

export function doResetSync() {
  return (dispatch) =>
    new Promise((resolve) => {
      dispatch({ type: ACTIONS.SYNC_RESET });
      resolve();
    });
}

export function doSyncEncryptAndDecrypt(oldPassword, newPassword, encrypt) {
  return (dispatch) => {
    const data = {};
    return Lbry.sync_hash()
      .then((hash) => Lbryio.call('sync', 'get', { hash }, 'post'))
      .then((syncGetResponse) => {
        data.oldHash = syncGetResponse.hash;

        return Lbry.sync_apply({ password: oldPassword, data: syncGetResponse.data });
      })
      .then(() => {
        if (encrypt) {
          dispatch(doWalletEncrypt(newPassword));
        } else {
          dispatch(doWalletDecrypt());
        }
      })
      .then(() => Lbry.sync_apply({ password: newPassword }))
      .then((syncApplyResponse) => {
        if (syncApplyResponse.hash !== data.oldHash) {
          return dispatch(doSetSync(data.oldHash, syncApplyResponse.hash, syncApplyResponse.data));
        }
      })
      .catch(console.error); // eslint-disable-line
  };
}

export function doSetSyncLock(lock) {
  return {
    type: ACTIONS.SET_SYNC_LOCK,
    data: lock,
  };
}

export function doSetPrefsReady() {
  return {
    type: ACTIONS.SET_PREFS_READY,
    data: true,
  };
}


text:
'use strict';

// Homes controller
angular.module('homes').controller('HomesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Homes',
	function($scope, $stateParams, $location, Authentication, Homes ) {
		$scope.authentication = Authentication;

		// Create new Home
		$scope.create = function() {
			// Create new Home object
			var home = new Homes ({
				name: this.name
			});

			// Redirect after save
			home.$save(function(response) {
				$location.path('homes/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Home
		$scope.remove = function( home ) {
			if ( home ) { home.$remove();

				for (var i in $scope.homes ) {
					if ($scope.homes [i] === home ) {
						$scope.homes.splice(i, 1);
					}
				}
			} else {
				$scope.home.$remove(function() {
					$location.path('homes');
				});
			}
		};

		// Update existing Home
		$scope.update = function() {
			var home = $scope.home ;

			home.$update(function() {
				$location.path('homes/' + home._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Homes
		$scope.find = function() {
			$scope.homes = Homes.query();
		};

		// Find existing Home
		$scope.findOne = function() {
			$scope.home = Homes.get({
				homeId: $stateParams.homeId
			});
		};
	}
]);

redpajama_set_name: RedPajamaGithub


text:
function [shistograms_train,label_vector_train,shistograms_test,label_vector_test,lengthlabelstrain,names] = extractimagefeatures(imagepath,commonpath,groups,cache_poshistograms, slice_ml,vocabulary)

% add required search paths
setup;

fprintf('Loading Training data..\n');

% Compute positive histograms from training images
testtrain = {'/train/','/test/'};

for j=1:length(testtrain)
    names = [];
    label_vector = [];
    lengthlabels = [];
    % Iterate around subfolders
    for i=1:length(groups)

     trainpath =[imagepath,groups{i},testtrain{j}];
     tmpnames = getImageSet(trainpath, slice_ml);

     label_vector = [label_vector,ones(1,length(tmpnames))*i];

     names = [names,tmpnames];
     lengthlabels = [lengthlabels,length(tmpnames)];
    end

    histograms = computeHistogramsFromImageList(vocabulary, names, cache_poshistograms);

    % Hellinger's kernel (histograms are l1 normalized)
    histograms = sqrt(histograms) ;
    histograms = double(histograms);

    shistograms = sparse(histograms);

    if j==1
        label_vector_train = label_vector';
        shistograms_train = shistograms;
        lengthlabelstrain = lengthlabels;
        namestrain = names;
    else
        label_vector_test = label_vector';
        shistograms_test = shistograms;
        lengthlabelstest = lengthlabels;
        namestest = names;
    end

end
names = {namestrain,namestest};
end


text:
<?php
namespace Gabrieljmj\TranslatorBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class TranslatorBundle extends Bundle
{
}


text:
import * as cd from 'cd-interfaces';
import { matButtonConfig } from './button-audit.config';
import { matSelectConfig } from './select-audit.config';
import { matInputConfig } from './input-audit.config';
import { matDatepickerConfig } from './datepicker-audit.config';
import { matCheckboxConfig } from './checkbox-audit.config';
import { matSwitchConfig } from './switch-audit.config';
import { matRadiobuttonsConfig } from './radiobuttons-audit.config';
import { matSliderConfig } from './slider-audit.config';
import { matSpinnerConfig } from './spinner-audit.config';
import { matProgressBarConfig } from './progressbar-audit.config';
import { matChipsListConfig } from './chipslist-audit.config';
import { matTabsConfig } from './tabs-audit.config';
import { matStepperConfig } from './stepper-audit.config';
import { matExpansionPanelConfig } from './expansionpanel-audit.config';

export interface IAuditView {
  title: string;
  elementType: cd.ComponentIdentity;
  variants: IAuditVariant[];
  columnWidth?: string;
}

export interface IAuditVariant {
  title: string;
  subVariants: IAuditSubVariant[];
  hidden?: boolean;
}

export interface IAuditSubVariant {
  title: string;
  inputs: any;
  hidden?: boolean;
}

export const CUSTOM_AUDIT_VIEWS: IAuditView[] = [
  matButtonConfig,
  matSelectConfig,
  matInputConfig,
  matDatepickerConfig,
  matCheckboxConfig,
  matSwitchConfig,
  matRadiobuttonsConfig,
  matSliderConfig,
  matSpinnerConfig,
  matProgressBarConfig,
  matChipsListConfig,
  matTabsConfig,
  matStepperConfig,
  matExpansionPanelConfig,
];


text:
var app = app || {};
(function () {
  'use strict';
  app.NextPlayableTiles = Backbone.Collection.extend({
    model: app.Tile
  });
})();


text:
object ApiLevelHelper {

    /**
     * Checks if the current api level is at least the provided value.
     * @param apiLevel One of the values within [Build.VERSION_CODES].
     *
     * @return `true` if the calling version is at least `apiLevel`.
     *  Else `false` is returned.
     */
    fun isAtLeast(apiLevel: Int) = Build.VERSION.SDK_INT >= apiLevel

    /**
     * Checks if the current api level is at lower than the provided value.
     * @param apiLevel One of the values within [Build.VERSION_CODES].
     *
     * @return `true` if the calling version is lower than `apiLevel`.
     * Else `false` is returned.
     */
    fun isLowerThan(apiLevel: Int) = Build.VERSION.SDK_INT < apiLevel
}


text:
var Partial = $CL.namespace('Ginger.Jobs.View.Index.Partial');

$CL.require('Cl.Backbone.View');

Partial.EditSidebar = function() {};

Partial.EditSidebar = $CL.extendClass(Partial.EditSidebar, Cl.Backbone.View, {
    events : {
        'click #job-starter' : 'onStartJobClick'
    },
    onStartJobClick : function(e) {
        e.preventDefault();
        $CL.app().router.forward('jobs_jobrun_start', {jobname: this.data.name});
    }
});


text:
"""
This module contains the tool of birdhousebuilder.recipe.adagucserver
"""
from setuptools import find_packages
from setuptools import setup

version = '0.3.4'
description = 'A Buildout recipe to install and configure Adaguc Web Map Service with Anaconda.'
long_description = (
    open('README.rst').read() + '\n' +
    open('AUTHORS.rst').read() + '\n' +
    open('CHANGES.rst').read()
)

entry_point = 'birdhousebuilder.recipe.adagucserver'
entry_points = {"zc.buildout": [
                            "default = %s:Recipe" % entry_point,
                          ],
                "zc.buildout.uninstall": [
                            "default = %s:uninstall" % entry_point,
                          ],
                       }

tests_require = ['zope.testing', 'zc.buildout', 'manuel']

setup(name='birdhousebuilder.recipe.adagucserver',
      version=version,
      description=description,
      long_description=long_description,
      # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers
      classifiers=[
          'Framework :: Buildout',
          'Intended Audience :: Developers',
          'Topic :: Software Development :: Build Tools',
          'Topic :: Software Development :: Libraries :: Python Modules',
          'License :: OSI Approved :: BSD License',
      ],
      keywords='buildout recipe pywps wms birdhouse conda anaconda',
      author='Birdhouse',
      author_email='',
      url='https://github.com/bird-house/birdhousebuilder.recipe.adagucserver',
      license='BSD',
      packages=find_packages(exclude=['ez_setup']),
      namespace_packages=['birdhousebuilder', 'birdhousebuilder.recipe'],
      include_package_data=True,
      zip_safe=False,
      install_requires=['setuptools',
                        'zc.buildout',
                        # -*- Extra requirements: -*-
            'Mako',
            'birdhousebuilder.recipe.conda',
            'birdhousebuilder.recipe.supervisor',
            'birdhousebuilder.recipe.nginx',
                        ],
      tests_require=tests_require,
      extras_require=dict(tests=tests_require),
      test_suite='birdhousebuilder.recipe.adagucserver.tests.test_docs.test_suite',
      entry_points=entry_points,
      )


text:
using System;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Metadata;
using Pomelo.EntityFrameworkCore.MySql.Storage.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
using Microsoft.EntityFrameworkCore.ValueGeneration;

namespace Pomelo.EntityFrameworkCore.MySql.ValueGeneration.Internal
{
    /// <summary>
    ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
    ///     directly from your code. This API may change or be removed in future releases.
    /// </summary>
    public class MySqlValueGeneratorSelector : RelationalValueGeneratorSelector
    {
        private readonly IMySqlSequenceValueGeneratorFactory _sequenceFactory;

        private readonly IMySqlConnection _connection;

        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public MySqlValueGeneratorSelector(
            [NotNull] ValueGeneratorSelectorDependencies dependencies,
            [NotNull] IMySqlSequenceValueGeneratorFactory sequenceFactory,
            [NotNull] IMySqlConnection connection)
            : base(dependencies)
        {
            Check.NotNull(sequenceFactory, nameof(sequenceFactory));
            Check.NotNull(connection, nameof(connection));

            _sequenceFactory = sequenceFactory;
            _connection = connection;
        }

        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public new virtual IMySqlValueGeneratorCache Cache => (IMySqlValueGeneratorCache)base.Cache;

        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public override ValueGenerator Select(IProperty property, IEntityType entityType)
        {
            Check.NotNull(property, nameof(property));
            Check.NotNull(entityType, nameof(entityType));

            return property.GetValueGeneratorFactory() == null
                   && property.MySql().ValueGenerationStrategy == MySqlValueGenerationStrategy.SequenceHiLo
                ? _sequenceFactory.Create(property, Cache.GetOrAddSequenceState(property), _connection)
                : base.Select(property, entityType);
        }

        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public override ValueGenerator Create(IProperty property, IEntityType entityType)
        {
            Check.NotNull(property, nameof(property));
            Check.NotNull(entityType, nameof(entityType));

            return property.ClrType.UnwrapNullableType() == typeof(Guid)
                ? property.ValueGenerated == ValueGenerated.Never
                  || property.MySql().DefaultValueSql != null
                    ? (ValueGenerator)new TemporaryGuidValueGenerator()
                    : new SequentialGuidValueGenerator()
                : base.Create(property, entityType);
        }
    }
}


text:
namespace System.ComponentModel {
    using System;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Security.Permissions;

    /// <devdoc>
    ///    <para>Represents the method that will handle the event raised when canceling an
    ///       event.</para>
    /// </devdoc>
    [HostProtection(SharedState = true)]
    public delegate void CancelEventHandler(object sender, CancelEventArgs e);
}


text:
package com.woniuxy.easyBuy.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.woniuxy.easyBuy.user.OrderDetail;
import com.woniuxy.easyBuy.utils.DbUtils;

public class OrderDetailDao {
	/**
	 * 通过订单ID,获得订单详情列表
	 * @param eo_id
	 * @return List<OrderDetail>
	 */
	public List<OrderDetail> getOrderDetailByOrderId(int eo_id){
		Connection connection = DbUtils.getConnection();
		if(connection!=null){
			PreparedStatement statement = null;
			ResultSet resultSet = null;
			try {
				String sql="SELECT * FROM easybuy_order_detail WHERE eo_id=?";
				statement = connection.prepareStatement(sql);
				//绑定数据
				statement.setInt(1, eo_id);
				resultSet = statement.executeQuery();
				//处理结果集
				List<OrderDetail> OrderDetails = new ArrayList<OrderDetail>();
				OrderDetail OrderDetail = null;
				ProductDao productDao = new ProductDao();
				if(resultSet.first()){
					OrderDetail = new OrderDetail();
					OrderDetail.setEo_id(eo_id);
					OrderDetail.setEod_id(resultSet.getInt("eod_id"));
					OrderDetail.setEp_id(resultSet.getInt("ep_id"));
					String ep_name = productDao.getProductById(resultSet.getInt("ep_id")).getEp_name();
					OrderDetail.setEp_name(ep_name);
					OrderDetail.setEod_quantity(resultSet.getInt("eod_quantity"));
					OrderDetail.setEod_cost(resultSet.getFloat("eod_cost"));

					OrderDetails.add(OrderDetail);
					OrderDetail = null;
				}
				return OrderDetails==null?null:OrderDetails;
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				DbUtils.closeResource(connection,statement,resultSet);
			}
		}

		return null;
	}
}


text:
/**
 * Create view with text label in user coordinate
 *
 * @param container
 * @param width
 * @param height
 */
function createUserTextLabel(container, width, height) {

	var view = new JenScript.View({
		name : container,
		width : width,
		height : height,
		west : 80,
		south:60
	});

	var bg1 = new JenScript.GradientViewBackground();
	view.addViewBackground(bg1);
	var textureBackground = new JenScript.TexturedViewBackground({
		opacity : 0.3,
		texture : JenScript.Texture.getTriangleCarbonFiber(),
		strokeColor : 'cyan',
		strokeWidth : 2,
		cornerRadius : 0
	});
	view.addViewBackground(textureBackground);

	var gloss = new JenScript.GlossViewForeground();
	view.addViewForeground(gloss);

	var proj = new JenScript.LinearProjection({
		name : "proj",
		minX : -1000,
		maxX : 1000,
		minY : -1000,
		maxY : 1000
	});
	view.registerProjection(proj);

	var outline = new JenScript.DeviceOutlinePlugin({
		color : 'pink'
	});

	proj.registerPlugin(outline);

	minor = {
		tickMarkerSize : 2,
		tickMarkerColor : JenScript.RosePalette.AEGEANBLUE,
		tickMarkerStroke : 1
	};
	median = {
		tickMarkerSize : 4,
		tickMarkerColor : JenScript.RosePalette.EMERALD,
		tickMarkerStroke : 1.2,
		tickTextColor : JenScript.RosePalette.EMERALD,
		tickTextFontSize : 10
	};
	major = {
		tickMarkerSize : 8,
		tickMarkerColor : JenScript.RosePalette.TURQUOISE,
		tickMarkerStroke : 3,
		tickTextColor : JenScript.RosePalette.TURQUOISE,
		tickTextFontSize : 12
	};

	var southMetrics = new JenScript.AxisMetricsModeled({
		axis : JenScript.Axis.AxisSouth,
		minor:minor,
		median:median,
		major:major
	});
	proj.registerPlugin(southMetrics);

	var westMetrics = new JenScript.AxisMetricsModeled({
		axis : JenScript.Axis.AxisWest,
		minor:minor,
		median:median,
		major:major
	});
	proj.registerPlugin(westMetrics);

	//TOOL
	var tx1 = new JenScript.TranslatePlugin();
	proj.registerPlugin(tx1);
	tx1.registerWidget(new JenScript.TranslateCompassWidget({
		ringFillColor : 'pink'
	}));
	tx1.select();

	var zoomwheel = new JenScript.ZoomWheelPlugin();
	proj.registerPlugin(zoomwheel);

	var labelPlugin = new JenScript.TextLabelPlugin();
	proj.registerPlugin(labelPlugin);

	var label = new JenScript.TextLabel({
		fillColor : 'white',
		outlineColor : 'darkgray',
		outlineWidth : 2,
		textColor : JenScript.RosePalette.COALBLACK,
		nature : 'User',
		location : {x : 500, y:500}
	});
	labelPlugin.addLabel(label);

}


text:
.. _bokeh.resources:

``bokeh.resources``
===================

.. automodule:: bokeh.resources
  :members:


text:
from optparse import make_option

from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.core.management.base import BaseCommand

from mkt.developers.providers import Provider
from mkt.developers.utils import uri_to_pk
from mkt.site.utils import chunked
from mkt.webapps.models import Webapp
from mkt.webpay.utils import make_external_id

def get_generic_product(app):
    if app.app_payment_accounts.exists():
        for account in app.app_payment_accounts.all():
            print (
                'Looking up public_id for app '
                '{app} using account {account}'
            ).format(
                app=app,
                account=account.payment_account.seller_uri)
            try:
                generic_product = Provider.generic.product.get_object(
                    seller=uri_to_pk(account.payment_account.seller_uri),
                    external_id=make_external_id(app))
                print (
                    'Found generic product {product} for '
                    'app {app} using account {account}'
                ).format(
                    product=generic_product['public_id'],
                    app=app,
                    account=account)
                return generic_product
            except ObjectDoesNotExist:
                pass
            except MultipleObjectsReturned:
                print 'Found multiple generic products for app {app}'.format(
                    app=app)
        print 'Unable to find a generic product for app {app}'.format(app=app)

class Command(BaseCommand):
    help = ('Look up and store the Generic Product public_ids'
            ' for existing webapps with configured payment accounts.')
    option_list = BaseCommand.option_list + (
        make_option(
            '--dry-run',
            default=False,
            action='store_true',
            dest='dry_run',
            help='Look up the public_ids in Solitude without saving'),)

    def handle(self, *args, **options):
        webapps = (Webapp.objects.filter(app_payment_accounts__isnull=False)
                                 .no_transforms()
                                 .select_related('app_payment_accounts'))
        for chunk in chunked(webapps, 50):
            for app in chunk:
                generic_product = get_generic_product(app)
                if not generic_product:
                    continue
                print 'Found public_id', generic_product['public_id']

                if not options['dry_run']:
                    print 'Saving app', app
                    app.solitude_public_id = generic_product['public_id']
                    app.save()


text:
package cn.remex.wechat.beans.paymch;

/**
 * 微信业务接口返回参数
 * Created by guoqi on 2016/3/23.
 */
public class WeChatPayResult {
    private String code;
    private String msg;
    private String prepay_id ;
    private String url;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getPrepay_id() {
        return prepay_id;
    }

    public void setPrepay_id(String prepay_id) {
        this.prepay_id = prepay_id;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Facade
{
    public static class FacadeForCreatingMarine
    {
        public static Marine GetMarine()
        {
            // creating motor
            var random = new Random();

            var wheels = random.Next(2, 4);
            var wheelsArr = new Wheel[wheels];
            for (int i = 0; i < wheels; i++)
			{
                wheelsArr[i] = new Wheel();
			}

            var frame = new Frame();

            var hp = random.Next(40, 101);
            var engine = new Engine(hp);

            var motor = new Motor(wheelsArr, frame, engine);

            // creating marine
            var gun = new Gun();

            var ammo = new Ammo();

            var marine = new Marine(gun, ammo, motor);

            return marine;
        }
    }
}


text:
<!doctype html>
<meta charset="utf-8">
<title>Check that sandboxed iframe can not navigate other frame's popup</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<body>
<script>

// This HTML file is loaded 3 times.
//   (1) As the initial test file (mode = '').
//   (2) In the popup window (mode = 'popup').
//   (3) In the sandboxed iframe (mode = 'iframe').
// Note: The sandboxed iframe (3) tries to navigate the popup window (2) to
// a new mode=iframenavigated URL. But this must be blocked because (3) is not
// the 'one permitted sandboxed navigator'.
// https://html.spec.whatwg.org/multipage/origin.html#one-permitted-sandboxed-navigator
(() => {
  const mode = '{{GET[mode]}}';
  if (mode == 'popup') {
    // (2): Loaded in the popup window.
    return;
  }
  if (mode == 'iframe') {
    // (3): Loaded in the sandboxed iframe.
    try {
      // Attempts to navigate the popup window (2).
      parent.document.popupWin.location = location.href + 'navigated';
    } catch (e) {
      parent.postMessage('cannot navigate');
    }
    return;
  }
  if (mode == 'iframenavigated') {
    // This URL page must not be loaded.
    opener.postMessage('can navigate');
    return;
  }

  // (1): Loaded as the initial test file.
  promise_test(async t => {
    // Opens a popup window to load the page (2).
    document.popupWin = window.open(location.href + '?mode=popup', '_blank');
    t.add_cleanup(() => document.popupWin.close());
    await new Promise(resolve => {
      document.popupWin.addEventListener('load', resolve);
    });

    // Adds an iframe to load the page (3).
    const iframe = document.createElement('iframe');
    t.add_cleanup(() => iframe.remove());
    iframe.sandbox = 'allow-popups allow-same-origin allow-scripts';
    iframe.src = location.href + '?mode=iframe';
    const message_promise = new Promise(resolve => {
      window.addEventListener('message', (e) => { resolve(e.data); });
    });
    document.body.appendChild(iframe);

    const result = await message_promise;
    assert_equals(result, 'cannot navigate');
  }, "Sandboxed iframe can not navigate other frame's popup");

})();
</script>
</body>


text:
package net.codetojoy;

import java.util.*;

import org.junit.*;
import static org.junit.Assert.*;

import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import static org.hamcrest.CoreMatchers.is;

@RunWith(value = Parameterized.class)
public class StringUtilsTestCase {
    private String s;
    private String expected;
    private String note;
    private static final String Y = "Y";
    private static final String N = "N";

    public StringUtilsTestCase(String s, String expected, String note) {
        this.s = s;
        this.expected = expected;
        this.note = note;
    }

    @Parameters(name = "#{index}  __  str: {0}  __  uuid? {1}  __  note: {2}")
    public static Collection<Object[]> data() {
        // { str, expected, note }
        //
        // * if (`expected` is Y) then assert `str` is UUID else assert not
        //
        // * `note` is only used as a comment for the test report
        //     * this is just my notation, but I use "!" in notes to capture
        //       why a given `str` is not a UUID

        return Arrays.asList(new Object[][]{
            {"d8bebfbc-aea2-4c13-9122-264217042fa3", Y, "basic",},
            {"d8bebfbc-aea2-4c13-9122-264217042fa3", Y, "group3[0] is 4",},
            {"d8bebfbc-aea2-6c13-9122-264217042fa3", N, "group3[0] is 4 !",},
            {"d8bebfbc-aea2-4c13-8122-264217042fa3", Y, "group4[0] in {8,9,A,B}",},
            {"d8bebfbc-aea2-4c13-2122-264217042fa3", N, "group4[0] in {8,9,A,B} !",},
        });
    }

    @Test
    public void testIsUUID() {
        boolean expectedResult = (expected.equals(Y));

        // test
        boolean result = StringUtils.isUUID(s);

        assertThat(result, is(expectedResult));
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.eas.designer.application.report;

import org.openide.filesystems.FileObject;
import org.openide.filesystems.MIMEResolver;
import org.openide.loaders.MultiFileLoader;

public class PlatypusReportDataObjectXLS extends PlatypusReportDataObject {

    @MIMEResolver.ExtensionRegistration(displayName="#LBL_PlatypusReport_layout_file", extension="xls", mimeType="application/ms-excel")
    public PlatypusReportDataObjectXLS(FileObject aJsFile, MultiFileLoader aLoader) throws Exception {
        super(aJsFile, aLoader);
    }

}


text:
using System;

namespace System.Messaging
{
	[Flags]
	[Serializable]
	public enum AcknowledgeTypes
	{
		FullReachQueue = 5,
		FullReceive = 14,
		NegativeReceive = 8,
		None = 0,
		NotAcknowledgeReachQueue = 4,
		NotAcknowledgeReceive = 12,
		PositiveArrival = 1,
		PositiveReceive = 2
	}
}


text:
package com.ibatis.sqlmap.engine.builder.xml;

import com.ibatis.common.resources.*;

import java.io.*;
import java.util.*;

import org.xml.sax.*;

/**
 * Offline entity resolver for the iBATIS DTDs.
 */
public class SqlMapClasspathEntityResolver implements EntityResolver {

  /** The Constant SQL_MAP_CONFIG_DTD. */
  private static final String SQL_MAP_CONFIG_DTD = "com/ibatis/sqlmap/engine/builder/xml/sql-map-config-2.dtd";

  /** The Constant SQL_MAP_DTD. */
  private static final String SQL_MAP_DTD = "com/ibatis/sqlmap/engine/builder/xml/sql-map-2.dtd";

  /** The Constant doctypeMap. */
  private static final Map doctypeMap = new HashMap();

  static {
    doctypeMap.put("http://www.ibatis.com/dtd/sql-map-config-2.dtd".toUpperCase(Locale.ROOT), SQL_MAP_CONFIG_DTD);
    doctypeMap.put("http://ibatis.apache.org/dtd/sql-map-config-2.dtd".toUpperCase(Locale.ROOT), SQL_MAP_CONFIG_DTD);
    doctypeMap.put("-//iBATIS.com//DTD SQL Map Config 2.0//EN".toUpperCase(Locale.ROOT), SQL_MAP_CONFIG_DTD);
    doctypeMap.put("-//ibatis.apache.org//DTD SQL Map Config 2.0//EN".toUpperCase(Locale.ROOT), SQL_MAP_CONFIG_DTD);

    doctypeMap.put("http://www.ibatis.com/dtd/sql-map-2.dtd".toUpperCase(Locale.ROOT), SQL_MAP_DTD);
    doctypeMap.put("http://ibatis.apache.org/dtd/sql-map-2.dtd".toUpperCase(Locale.ROOT), SQL_MAP_DTD);
    doctypeMap.put("-//iBATIS.com//DTD SQL Map 2.0//EN".toUpperCase(Locale.ROOT), SQL_MAP_DTD);
    doctypeMap.put("-//ibatis.apache.org//DTD SQL Map 2.0//EN".toUpperCase(Locale.ROOT), SQL_MAP_DTD);
  }

  /**
   * Converts a public DTD into a local one
   *
   * @param publicId
   *          Unused but required by EntityResolver interface
   * @param systemId
   *          The DTD that is being requested
   * @return The InputSource for the DTD
   * @throws SAXException
   *           If anything goes wrong
   */
  public InputSource resolveEntity(String publicId, String systemId) throws SAXException {

    if (publicId != null)
      publicId = publicId.toUpperCase(Locale.ROOT);
    if (systemId != null)
      systemId = systemId.toUpperCase(Locale.ROOT);

    InputSource source = null;
    try {
      String path = (String) doctypeMap.get(publicId);
      source = getInputSource(path, source);
      if (source == null) {
        path = (String) doctypeMap.get(systemId);
        source = getInputSource(path, source);
      }
    } catch (Exception e) {
      throw new SAXException(e.toString());
    }
    return source;
  }

  /**
   * Gets the input source.
   *
   * @param path
   *          the path
   * @param source
   *          the source
   * @return the input source
   */
  private InputSource getInputSource(String path, InputSource source) {
    if (path != null) {
      InputStream in = null;
      try {
        in = Resources.getResourceAsStream(path);
        source = new InputSource(in);
      } catch (IOException e) {
        // ignore, null is ok
      }
    }
    return source;
  }

}


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

namespace LAP.Logic
{
    public partial class BenutzerRolle
    {
        public const int ADMINISTRATOR = 1;
        public const int BENUTZER = 2;
        public const int MITARBEITER = 3;

    }
}


text:
#ifndef QFUF_TACTIC_H_
#define QFUF_TACTIC_H_

#include"params.h"
class ast_manager;
class tactic;

tactic * mk_qfuf_tactic(ast_manager & m, params_ref const & p);

/*
  ADD_TACTIC("qfuf", "builtin strategy for solving QF_UF problems.", "mk_qfuf_tactic(m, p)")
*/

#endif


text:
package es.upm.fi.oeg.rider.domain;

import java.util.LinkedList;

import es.upm.fi.oeg.rider.dataservice.DataService;
import es.upm.fi.oeg.rider.domain.ontology.ToolCategory;
import es.upm.fi.oeg.rider.domain.ontology.ToolVersion;
import es.upm.fi.oeg.rider.domain.recommendation.Alternative;
import es.upm.fi.oeg.rider.domain.recommendation.Requirement;

public class AlternativesFactory {

	public static LinkedList<Alternative> createAlternativesList(LinkedList<Requirement> requirements, DataService service){
		LinkedList<ToolCategory> toolCategories = new LinkedList<ToolCategory>();
		LinkedList<Alternative> alternatives = new LinkedList<Alternative>();

		for (Requirement requirement : requirements) {
			ToolCategory toolCategory = requirement.getMeasure().getToolCategory();
			if(!toolCategories.contains(toolCategory))
				toolCategories.add(toolCategory);
		}

		if(toolCategories.size() == 1){
			for (ToolVersion toolVersion : service.getToolVersions(toolCategories.get(0).getUri().toString())) {
				toolVersion.setQualityValues(service.getQualityValuesForRequirements(toolVersion.getUri().toString(),
						requirements));
				Alternative alternative = new Alternative();
				alternative.addTool(toolVersion);
				alternatives.add(alternative);
			}
		}

		if(toolCategories.size() == 2){
			for (ToolVersion toolVersion1 : service.getToolVersions(toolCategories.get(0).getUri().toString())) {
				toolVersion1.setQualityValues(service.getQualityValuesForRequirements(toolVersion1.getUri().toString(),
						requirements));
				for (ToolVersion toolVersion2 : service.getToolVersions(toolCategories.get(1).getUri().toString())) {
					toolVersion2.setQualityValues(service.getQualityValuesForRequirements(toolVersion2.getUri().toString(),
							requirements));
					Alternative alternative = new Alternative();
					alternative.addTool(toolVersion1);
					alternative.addTool(toolVersion2);
					alternatives.add(alternative);
				}
			}
		}

		if(toolCategories.size() == 3){
			for (ToolVersion toolVersion1 : service.getToolVersions(toolCategories.get(0).getUri().toString())) {
				toolVersion1.setQualityValues(service.getQualityValuesForRequirements(toolVersion1.getUri().toString(),
						requirements));
				for (ToolVersion toolVersion2 : service.getToolVersions(toolCategories.get(1).getUri().toString())) {
					toolVersion2.setQualityValues(service.getQualityValuesForRequirements(toolVersion2.getUri().toString(),
							requirements));
					for (ToolVersion toolVersion3 : service.getToolVersions(toolCategories.get(2).getUri().toString())) {
						toolVersion3.setQualityValues(service.getQualityValuesForRequirements(toolVersion3.getUri().toString(),
								requirements));
						Alternative alternative = new Alternative();
						alternative.addTool(toolVersion1);
						alternative.addTool(toolVersion2);
						alternative.addTool(toolVersion3);
						alternatives.add(alternative);
					}
				}
			}
		}
		return alternatives;
	}

	// this method is called in the case when the comparison according to all criteria is needed
	// (not only w.r.t. requirements), because alternatives and measures are initially formed based on
	// user requirements only
	/**
	 * Adds quality values for a given quality measure to all alternatives in a given list.
	 * @param alternatives
	 * @param measureUri
	 */
	public static void addMeasureToAlternatives(
			LinkedList<Alternative> alternatives, String measureUri, DataService service) {

		for (Alternative alternative : alternatives) {
			for (ToolVersion toolVersion : alternative.getTools()) {
				if(service.coversQualityMeasure(toolVersion.getUri().toString(), measureUri))
					toolVersion.addQualityValue(service.getQualityValue(toolVersion.getUri().toString(),
							measureUri));
			}
		}

	}
}


text:
name: Armenia
permalink: "/categories/armenia/"
layout: category
---


text:
export default {
  'basic-interval': {
    name: 'Basic interval',
    code: `const { interval } = Rx;
const { take } = RxOperators;

interval(1000).pipe(
  take(4)
)
`,
    timeWindow: 5000
  },
  'random-error': {
    name: 'Random error',
    code: `const { Observable } = Rx;

Observable.create(observer => {
  let n = 1;

  const intervalId = setInterval(() => {
    if (Math.random() < 0.8 && n < 9) {
      observer.next(n * n);
      n += 1;
    } else {
      observer.error('Oh no...');
    }
  }, 1000);

  return () => clearInterval(intervalId);
})
`,
    timeWindow: 10000
  },
  'chess-game': {
    name: 'Chess game',
    code: `const { of, interval } = Rx;
const { zip, map } = RxOperators;

const timer$ = interval(1000);
const pieces$ = of('', '♞', '', '♞', '♘', '♞');
const columns$ = of('e', 'c', 'g', 'd', 'e', 'f');
const rows$ = of('4', '6', '4', '4', '2', '3');

timer$.pipe(
  zip(
    pieces$,
    columns$,
    rows$
  ),
  map(([_, piece, column, row]) => \`\${piece}\${column}\${row}\`)
)
`,
    timeWindow: 7000
  },
  'higher-order-observable': {
    name: 'Higher order Observable',
    code: `const { interval } = Rx;
const { groupBy } = RxOperators;

interval(1000).pipe(
  groupBy(n => n % 2)
)
`,
    timeWindow: 10000
  },
  'grouped-fibonacci': {
    name: 'Grouped Fibonacci',
    code: `const { interval } = Rx;
const { scan, pluck, groupBy } = RxOperators;

interval(1000).pipe(
  scan(
    ({ secondLast, last }) => ({
      secondLast: last,
      last: last + secondLast
    }),
    { secondLast: 0, last: 1 }
  ),
  pluck("secondLast"),
  groupBy(n => Math.floor(Math.log10(n)))
)

`,
    timeWindow: 15000
  },
  'today-is': {
    name: 'Today is...',
    code: `const { of, interval, range, EMPTY } = Rx;
const { delay, take, map, concatMap } = RxOperators;

const sentence = new Date().toString().toUpperCase();
const words = sentence.split(' ');
const delayMS = 1000;

const wordDelay = i =>
  i === 0
    ? delayMS
    : (words[i - 1].length + 1) * delayMS;

const wordStart = i =>
  i < words.length
    ? of(i).pipe(delay(wordDelay(i)))
    : EMPTY.pipe(delay(wordDelay(i)))

const wordObservable = word => {
  const letters = word.split('');

  return interval(delayMS).pipe(
    take(letters.length),
    map(i => letters[i])
  );
};

range(0, words.length + 1).pipe(
  concatMap(wordStart),
  map(i => wordObservable(words[i]))
)
`,
    timeWindow: 17000
  },
  'custom-operator': {
    name: 'Custom operator',
    code: `const { Observable, interval } = Rx;

const sqrt = source$ => Observable.create(observer =>
  source$.subscribe(
    value => {
      const result = Math.sqrt(value);

      if (typeof value !== 'number' || isNaN(result)) {
        observer.error(\`Square root of \${value} doesn't exist\`);
      } else {
        observer.next(result);
      }
    },
    err => observer.error(err),
    () => observer.complete()
  )
);

interval(1000).pipe(sqrt)

`,
    timeWindow: 12000
  },
  'mouse-move': {
    name: 'Mouse move',
    code: `const { fromEvent } = Rx;
const { map, throttleTime } = RxOperators;

fromEvent(document, 'mousemove').pipe(
  map(event => event.clientX),
  throttleTime(300)
)

// Move your mouse over the right hand pane
// after clicking Visualize.
`,
    timeWindow: 10000
  },
  'input-element': {
    name: 'Input element',
    code: `const { fromEvent } = Rx;
const { map, filter } = RxOperators;

const input = document.createElement('input');

input.setAttribute('placeholder', 'Type something');

// \`output\` represents the right hand pane.
// You can prepend/append elements to it.
output.prepend(input);

input.focus();

fromEvent(input, 'keydown').pipe(
  map(e => e.key),
  filter(key => key !== ' ')
)
`,
    timeWindow: 20000
  },
  'pause-and-resume': {
    name: 'Pause and resume',
    code: `const { fromEvent, timer, EMPTY } = Rx;
const { scan, startWith, map, filter, switchMap } = RxOperators;

const pauseResume$ = fromEvent(document, 'click').pipe(
  scan(acc => !acc, true),
  startWith(true)
);
const counter$ = timer(0, 1000);

pauseResume$.pipe(
  switchMap(resume => resume ? counter$ : EMPTY)
)

// Click to pause and resume over the right hand pane
// after clicking Visualize.
`,
    timeWindow: 20000
  },
  custom: {
    name: 'Custom',
    code: `// Write any JavaScript you want, just make sure that
// the last expression is an Rx.Observable

const {  } = Rx;
const {  } = RxOperators;
 `,
    timeWindow: 10000
  }
};


text:
package com.dkarv.jdcallgraph.util.log;

import com.dkarv.jdcallgraph.helper.Console;
import com.dkarv.jdcallgraph.util.config.ConfigUtils;
import org.hamcrest.text.MatchesPattern;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.Mockito;

import java.io.IOException;
import java.util.regex.Pattern;

import static org.junit.Assert.*;

public class LoggerTest {
  @Rule
  public TemporaryFolder tmp = new TemporaryFolder();

  private Logger init(int logLevel, boolean stdOut) {
    try {
      ConfigUtils.replace( true, "logLevel: " + logLevel, "logConsole: " + stdOut);
    } catch (IOException e) {
      fail("Error initializing config");
    }
    Logger.init();
    return new Logger(LoggerTest.class);
  }

  @Test
  public void testInit() {
    init(0, false);
    assertTrue(Logger.TARGETS.isEmpty());

    init(1, false);
    assertEquals(1, Logger.TARGETS.size());
    assertTrue(Logger.TARGETS.get(0) instanceof FileTarget);

    init(1, true);
    assertEquals(2, Logger.TARGETS.size());
    assertTrue(Logger.TARGETS.get(0) instanceof FileTarget);
    assertTrue(Logger.TARGETS.get(1) instanceof ConsoleTarget);

    Logger logger = init(1, false);
    assertEquals("[LoggerTest]", logger.prefix);
  }

  @Test
  public void testTrace() {
    Logger logger = Mockito.spy(init(6, false));
    logger.trace("test");
    Mockito.verify(logger).trace("test");
    Mockito.verify(logger).log(6, "test");
    Mockito.verifyNoMoreInteractions(logger);

    logger = Mockito.spy(init(5, false));
    logger.trace("test");
    Mockito.verify(logger).trace("test");
    Mockito.verifyNoMoreInteractions(logger);
  }

  @Test
  public void testDebug() {
    Logger logger = Mockito.spy(init(5, false));
    logger.debug("test");
    Mockito.verify(logger).debug("test");
    Mockito.verify(logger).log(5, "test");
    Mockito.verifyNoMoreInteractions(logger);

    logger = Mockito.spy(init(4, false));
    logger.debug("test");
    Mockito.verify(logger).debug("test");
    Mockito.verifyNoMoreInteractions(logger);
  }

  @Test
  public void testInfo() {
    Logger logger = Mockito.spy(init(4, false));
    logger.info("test");
    Mockito.verify(logger).info("test");
    Mockito.verify(logger).log(4, "test");
    Mockito.verifyNoMoreInteractions(logger);

    logger = Mockito.spy(init(3, false));
    logger.info("test");
    Mockito.verify(logger).info("test");
    Mockito.verifyNoMoreInteractions(logger);
  }

  @Test
  public void testWarn() {
    Logger logger = Mockito.spy(init(3, false));
    logger.warn("test");
    Mockito.verify(logger).warn("test");
    Mockito.verify(logger).log(3, "test");
    Mockito.verifyNoMoreInteractions(logger);

    logger = Mockito.spy(init(2, false));
    logger.warn("test");
    Mockito.verify(logger).warn("test");
    Mockito.verifyNoMoreInteractions(logger);
  }

  @Test
  public void testError() {
    Logger logger = Mockito.spy(init(2, false));
    logger.error("test");
    Mockito.verify(logger).error("test");
    Mockito.verify(logger).logE(2, "test");
    Mockito.verify(logger).log(2, "test");
    Mockito.verifyNoMoreInteractions(logger);

    logger = Mockito.spy(init(1, false));
    logger.error("test");
    Mockito.verify(logger).error("test");
    Mockito.verifyNoMoreInteractions(logger);
  }

  @Test
  public void testFatal() {
    Logger logger = Mockito.spy(init(1, false));
    logger.fatal("test");
    Mockito.verify(logger).fatal("test");
    Mockito.verify(logger).logE(1, "test");
    Mockito.verify(logger).log(1, "test");
    Mockito.verifyNoMoreInteractions(logger);

    logger = Mockito.spy(init(0, false));
    logger.fatal("test");
    Mockito.verify(logger).fatal("test");
    Mockito.verifyNoMoreInteractions(logger);
  }

  @Test
  public void testException() throws IOException {
    Logger logger = init(6, false);
    Logger.TARGETS.clear();
    LogTarget target = Mockito.mock(LogTarget.class);
    Logger.TARGETS.add(target);

    Exception e = new RuntimeException();
    logger.error("test", e);

    Mockito.verify(target).printTrace(e, 2);
    Mockito.verify(target, Mockito.times(2)).print(Mockito.anyString(), Mockito.eq(2));
    Mockito.verify(target, Mockito.times(2)).flush();
    Mockito.verifyNoMoreInteractions(target);
  }

  @Test
  public void testReplacement() throws IOException {
    Logger logger = init(6, false);
    Logger.TARGETS.clear();
    LogTarget target = Mockito.mock(LogTarget.class);
    Logger.TARGETS.add(target);

    String arg = "123";
    logger.debug("test {}", arg);
    Mockito.verify(target).print(Mockito.matches("\\[.*] \\[DEBUG] \\[LoggerTest] test 123\n"),
        Mockito.eq(5));

    arg = null;
    logger.debug("test {}", arg);
    Mockito.verify(target).print(Mockito.matches("\\[.*] \\[DEBUG] \\[LoggerTest] test null\n"),
        Mockito.eq(5));
  }

  @Test
  public void testWrongArgumentCount() {
    Logger logger = init(6, false);
    try {
      logger.debug("test {}", "123", "456");
      fail("Should notice too less {}");
    } catch (IllegalArgumentException e) {
    }

    try {
      logger.debug("test {} {}");
      fail("Should notice missing arguments");
    } catch (IllegalArgumentException e) {
    }
  }

  @Test
  public void testTargetError() throws IOException {
    Logger logger = init(6, false);
    Logger.TARGETS.clear();
    LogTarget target = Mockito.mock(LogTarget.class);
    Mockito.doThrow(new IOException("error")).when(target).print(Mockito.anyString(), Mockito.anyInt());
    Logger.TARGETS.add(target);

    Console console = new Console();
    console.startCapture();
    logger.debug("test");
    logger.error("test", new RuntimeException());
    assertEquals("", console.getOut());
    String pattern = "Error in logger: error\njava.io.IOException: error\n.*";
    pattern = pattern + pattern + pattern;
    assertThat(console.getErr(), MatchesPattern.matchesPattern(Pattern.compile(pattern, Pattern.DOTALL)));
    console.reset();
  }
}


text:
package org.apache.maven.plugin.jar;

import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.handler.ArtifactHandler;
import org.apache.maven.artifact.metadata.ArtifactMetadata;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.artifact.versioning.OverConstrainedVersionException;
import org.apache.maven.artifact.versioning.VersionRange;

import java.io.File;
import java.util.Collection;
import java.util.List;

/**
 * @todo move to maven-artifact-test
 */
class MockArtifact
    implements Artifact
{
    private String groupId;

    private String artifactId;

    private String version;

    private File file;

    private String scope;

    private String type;

    private String classifier;

    private String baseVersion;

    public String getGroupId()
    {
        return groupId;
    }

    public String getArtifactId()
    {
        return artifactId;
    }

    public String getVersion()
    {
        return version;
    }

    public void setVersion( String string )
    {
        this.version = string;
    }

    public String getScope()
    {
        return scope;
    }

    public String getType()
    {
        return type;
    }

    public String getClassifier()
    {
        return classifier;
    }

    public boolean hasClassifier()
    {
        return classifier != null;
    }

    public File getFile()
    {
        return file;
    }

    public void setFile( File file )
    {
        this.file = file;
    }

    public String getBaseVersion()
    {
        return baseVersion;
    }

    public void setBaseVersion( String string )
    {
        this.baseVersion = string;
    }

    public String getId()
    {
        // TODO
        return null;
    }

    public String getDependencyConflictId()
    {
        // TODO
        return null;
    }

    public void addMetadata( ArtifactMetadata artifactMetadata )
    {
        // TODO
    }

    public Collection getMetadataList()
    {
        // TODO
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public void setRepository( ArtifactRepository artifactRepository )
    {
        //To change body of implemented methods use File | Settings | File Templates.
        // TODO
    }

    public ArtifactRepository getRepository()
    {
        // TODO
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public void updateVersion( String string, ArtifactRepository artifactRepository )
    {
        //To change body of implemented methods use File | Settings | File Templates.
        // TODO
    }

    public String getDownloadUrl()
    {
        // TODO
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public void setDownloadUrl( String string )
    {
        //To change body of implemented methods use File | Settings | File Templates.
        // TODO
    }

    public ArtifactFilter getDependencyFilter()
    {
        // TODO
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public void setDependencyFilter( ArtifactFilter artifactFilter )
    {
        // TODO
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public ArtifactHandler getArtifactHandler()
    {
        // TODO
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public List getDependencyTrail()
    {
        // TODO
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public void setDependencyTrail( List list )
    {
        //To change body of implemented methods use File | Settings | File Templates.
        // TODO
    }

    public void setScope( String string )
    {
        //To change body of implemented methods use File | Settings | File Templates.
        // TODO
    }

    public VersionRange getVersionRange()
    {
        // TODO
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public void setVersionRange( VersionRange versionRange )
    {
        // TODO
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void selectVersion( String string )
    {
        // TODO
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public boolean isSnapshot()
    {
        // TODO
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public void setResolved( boolean b )
    {
        // TODO
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public boolean isResolved()
    {
        // TODO
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public void setResolvedVersion( String string )
    {
        // TODO
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void setArtifactHandler( ArtifactHandler artifactHandler )
    {
        // TODO
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public boolean isRelease()
    {
        // TODO
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public void setRelease( boolean b )
    {
        // TODO
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public List getAvailableVersions()
    {
        // TODO
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public void setAvailableVersions( List list )
    {
        // TODO
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public boolean isOptional()
    {
        return false;  //To change body of implemented methods use File | Settings | File Templates.
        // TODO
    }

    public void setOptional( boolean b )
    {
        // TODO
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public ArtifactVersion getSelectedVersion()
        throws OverConstrainedVersionException
    {
        // TODO
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public boolean isSelectedVersionKnown()
        throws OverConstrainedVersionException
    {
        return false;  //To change body of implemented methods use File | Settings | File Templates.
        // TODO
    }

    public void setGroupId( String groupId )
    {
        this.groupId = groupId;
    }

    public void setArtifactId( String artifactId )
    {
        this.artifactId = artifactId;
    }

    public void setType( String type )
    {
        this.type = type;
    }

    public void setClassifier( String classifier )
    {
        this.classifier = classifier;
    }

    public int compareTo( Object o )
    {
        // TODO
        return 0;  //To change body of implemented methods use File | Settings | File Templates.
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Venturia clintonii Peck

### Remarks
null