text:
package org.apereo.cas.authentication.handler;

import org.apereo.cas.authentication.AuthenticationHandler;
import org.apereo.cas.authentication.AuthenticationHandlerResolver;
import org.apereo.cas.authentication.AuthenticationServiceSelectionPlan;
import org.apereo.cas.authentication.AuthenticationTransaction;
import org.apereo.cas.authentication.MultifactorAuthenticationHandler;
import org.apereo.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler;
import org.apereo.cas.authentication.principal.Service;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.services.UnauthorizedSsoServiceException;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * This is {@link RegisteredServiceAuthenticationHandlerResolver}
 * that acts on the criteria presented by a registered service to
 * detect which handler(s) should be resolved for authentication.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
@Slf4j
@RequiredArgsConstructor
@Getter
@Setter
public class RegisteredServiceAuthenticationHandlerResolver implements AuthenticationHandlerResolver {

    /**
     * The Services manager.
     */
    protected final ServicesManager servicesManager;

    /**
     * The service selection plan.
     */
    protected final AuthenticationServiceSelectionPlan authenticationServiceSelectionPlan;

    private int order;

    private static Set<AuthenticationHandler> filterExcludedAuthenticationHandlers(
        final Set<AuthenticationHandler> candidateHandlers,
        final Service service,
        final RegisteredService registeredService) {

        val authenticationPolicy = registeredService.getAuthenticationPolicy();
        val excludedHandlers = authenticationPolicy.getExcludedAuthenticationHandlers();
        LOGGER.debug("Authentication transaction excludes [{}] for service [{}]", excludedHandlers, service);

        val handlerSet = new LinkedHashSet<>(candidateHandlers);
        LOGGER.debug("Candidate authentication handlers examined for this transaction are [{}]", handlerSet);

        if (!excludedHandlers.isEmpty()) {
            val it = handlerSet.iterator();
            while (it.hasNext()) {
                val handler = it.next();
                val handlerName = handler.getName();
                if (excludedHandlers.contains(handlerName)) {
                    LOGGER.debug("Authentication handler [{}] is excluded for this transaction and is removed", handlerName);
                    it.remove();
                }
            }
        }
        LOGGER.info("Final authentication handlers after exclusion rules are [{}]", handlerSet);
        return handlerSet;
    }

    private static Set<AuthenticationHandler> filterRequiredAuthenticationHandlers(
        final Set<AuthenticationHandler> candidateHandlers,
        final Service service, final RegisteredService registeredService) {

        val authenticationPolicy = registeredService.getAuthenticationPolicy();
        val requiredHandlers = authenticationPolicy.getRequiredAuthenticationHandlers();
        LOGGER.debug("Authentication transaction requires [{}] for service [{}]", requiredHandlers, service);
        val handlerSet = new LinkedHashSet<>(candidateHandlers);
        LOGGER.debug("Candidate authentication handlers examined for this transaction are [{}]", handlerSet);

        if (!requiredHandlers.isEmpty()) {
            val it = handlerSet.iterator();
            while (it.hasNext()) {
                val handler = it.next();
                val handlerName = handler.getName();
                val removeHandler = !(handler instanceof MultifactorAuthenticationHandler)
                    && !(handler instanceof HttpBasedServiceCredentialsAuthenticationHandler)
                    && !requiredHandlers.contains(handlerName);
                if (removeHandler) {
                    it.remove();
                    LOGGER.debug("Authentication handler [{}] is removed", handlerName);
                }
            }
        }
        LOGGER.info("Final authentication handlers after inclusion rules are [{}]", handlerSet);
        return handlerSet;
    }

    @Override
    public Set<AuthenticationHandler> resolve(final Set<AuthenticationHandler> candidateHandlers,
                                              final AuthenticationTransaction transaction) {
        val service = authenticationServiceSelectionPlan.resolveService(transaction.getService());
        val registeredService = this.servicesManager.findServiceBy(service);

        val requiredHandlers = filterRequiredAuthenticationHandlers(candidateHandlers, service, registeredService);
        return filterExcludedAuthenticationHandlers(requiredHandlers, service, registeredService);
    }

    @Override
    public boolean supports(final Set<AuthenticationHandler> handlers, final AuthenticationTransaction transaction) {
        val service = authenticationServiceSelectionPlan.resolveService(transaction.getService());
        if (service != null) {
            val registeredService = this.servicesManager.findServiceBy(service);
            LOGGER.trace("Located registered service definition [{}] for this authentication transaction", registeredService);
            if (registeredService == null || !registeredService.getAccessStrategy().isServiceAccessAllowed()) {
                LOGGER.warn("Service [{}] is not allowed to use SSO.", service);
                throw new UnauthorizedSsoServiceException();
            }
            val authenticationPolicy = registeredService.getAuthenticationPolicy();
            return !authenticationPolicy.getRequiredAuthenticationHandlers().isEmpty()
                || !authenticationPolicy.getExcludedAuthenticationHandlers().isEmpty();
        }
        return false;
    }
}


text:
hei = 10;
wid = 10;
set(gcf, 'Units','centimeters', 'Position',[0 0 wid hei]);
set(gcf, 'PaperPositionMode','auto');
printpdf(filename);

redpajama_set_name: RedPajamaGithub


text:
package copsandrobbers.test;

import java.security.SecureRandom;
import java.util.HashMap;

import copsandrobbers.Generator;
import copsandrobbers.generator.*;

public class TestDrive {

	public static void main(String[] args) {
		SecureRandom sr = new SecureRandom();
		long seed = sr.nextLong();
		HashMap<String, Generator> generators = new HashMap<>();
		generators.put("Java", new JavaRandomGenerator(seed));
		generators.put("Exponent", new ExponentRandomGenerator(seed));
		generators.put("Linear", new LinearRandomGenerator(seed));
		generators.put("Middle Squarish", new MiddleSquareishRandomGenerator(seed));
		generators.put("One", new OneRandomGenerator());
		generators.put("Time", new TimeRandomGenerator());

		for(String key : generators.keySet()){
			System.out.println(key + ": " + new EntropyCalculator(generators.get(key)).getEntropy());
			System.out.println(key + ": " + new EntropyCalculator(generators.get(key)).getIndexEntropy());
		}

//		Corey's mean test for the random generators
//		System.out.println("the closer to 1 the number, the better the random generator is at spreading through the numbers. \n");
//		RandomGeneratorMeanTester rgmt = new RandomGeneratorMeanTester(1000, 1000, new TimeRandomGenerator());
//		System.out.println("TimeRandomGenerator randomness is: " + rgmt.getMeanCloseness());
//
//		rgmt = new RandomGeneratorMeanTester(1000, 1000, new JavaRandomGenerator(6566));
//		System.out.println("Java's randomness is: " + rgmt.getMeanCloseness());
//
//		rgmt = new RandomGeneratorMeanTester(1000, 1000, new LinearRandomGenerator(6566));
//		System.out.println("LinearRandomGenerator randomness is: " + rgmt.getMeanCloseness());
//
//		rgmt = new RandomGeneratorMeanTester(1000, 1000, new MiddleSquareishRandomGenerator());
//		System.out.println("MiddleSquarishRandomGenerator randomness is: " + rgmt.getMeanCloseness());
//
//		rgmt = new RandomGeneratorMeanTester(1000, 1000, new OneRandomGenerator());
//		System.out.println("OneRandomGenerator randomness is: " + rgmt.getMeanCloseness());
//
//		rgmt = new RandomGeneratorMeanTester(1000, 1000, new ExponentRandomGenerator(6566));
//		System.out.println("ExponenetRandomGenerator randomness is: " + rgmt.getMeanCloseness());
	}

}


text:
package cmd

import (
	"fmt"
	"net/url"
	"os"

	"github.com/spf13/cobra"
)

// ShippingAddressesListCmdOperatorId holds value of 'operator_id' option
var ShippingAddressesListCmdOperatorId string

func init() {
	ShippingAddressesListCmd.Flags().StringVar(&ShippingAddressesListCmdOperatorId, "operator-id", "", TRAPI("operator_id"))
	ShippingAddressesCmd.AddCommand(ShippingAddressesListCmd)
}

// ShippingAddressesListCmd defines 'list' subcommand
var ShippingAddressesListCmd = &cobra.Command{
	Use:   "list",
	Short: TRAPI("/operators/{operator_id}/shipping_addresses:get:summary"),
	Long:  TRAPI(`/operators/{operator_id}/shipping_addresses:get:description`) + "\n\n" + createLinkToAPIReference("ShippingAddress", "listShippingAddresses"),
	RunE: func(cmd *cobra.Command, args []string) error {

		if len(args) > 0 {
			return fmt.Errorf("unexpected arguments passed => %v", args)
		}

		opt := &apiClientOptions{
			BasePath: "/v1",
			Language: getSelectedLanguage(),
		}

		ac := newAPIClient(opt)
		if v := os.Getenv("SORACOM_VERBOSE"); v != "" {
			ac.SetVerbose(true)
		}
		err := authHelper(ac, cmd, args)
		if err != nil {
			cmd.SilenceUsage = true
			return err
		}

		param, err := collectShippingAddressesListCmdParams(ac)
		if err != nil {
			return err
		}

		body, err := ac.callAPI(param)
		if err != nil {
			cmd.SilenceUsage = true
			return err
		}

		if body == "" {
			return nil
		}

		if rawOutput {
			_, err = os.Stdout.Write([]byte(body))
		} else {
			return prettyPrintStringAsJSON(body)
		}
		return err
	},
}

func collectShippingAddressesListCmdParams(ac *apiClient) (*apiParams, error) {
	if ShippingAddressesListCmdOperatorId == "" {
		ShippingAddressesListCmdOperatorId = ac.OperatorID
	}

	return &apiParams{
		method: "GET",
		path:   buildPathForShippingAddressesListCmd("/operators/{operator_id}/shipping_addresses"),
		query:  buildQueryForShippingAddressesListCmd(),

		noRetryOnError: noRetryOnError,
	}, nil
}

func buildPathForShippingAddressesListCmd(path string) string {

	escapedOperatorId := url.PathEscape(ShippingAddressesListCmdOperatorId)

	path = strReplace(path, "{"+"operator_id"+"}", escapedOperatorId, -1)

	return path
}

func buildQueryForShippingAddressesListCmd() url.Values {
	result := url.Values{}

	return result
}


text:
/**
 * Auto-configuration classes for RSocket integration with GraphQL.
 */
package org.springframework.boot.autoconfigure.graphql.rsocket;


text:
package controllers

import play.api.mvc.{Controller, Action}

import library.Util
import models.Member
import models.Post
import models.CustomData
import views.html

object PageController extends Controller {
  def index(pageNum: String) = Action {
    implicit request => {
      val memberId = Member.selectByUname(Util.getUnameFromSubdomain(request.domain)).get.id
      val posts = Post.postsByMemberId(memberId, Some(pageNum.toInt * Post.articlesPerPage))
      val css = CustomData.loadCss(memberId, "list")
      val js = CustomData.loadJs(memberId, "list")

      Ok(html.myindex(
        request.session.get("uname"),
        css,
        js,
        Util.getUnameFromSubdomain(request.domain),
        Post.postsByMemberId(memberId, Some((pageNum.toInt - 1) * Post.articlesPerPage)),
        pageNum.toInt,
        Map(
         "prev" -> (1 < pageNum.toInt),
         "next" -> Post.hasNextPage(memberId, pageNum.toInt)))
      )
    }
  }
}


text:
import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';

import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';

import { Data } from '../../model/data.model';

import { PositionsHttpService } from '../../positions/positions-http.service';

@Injectable()
export class ResultsHttpPositionsService extends PositionsHttpService {

    constructor(protected http: HttpClient) {
        super(http);
    }

  public getPositionsData(): Observable<Data> {
    return this.getData(this.endPoint);
   }
}


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

#if UNITY_EDITOR
using UnityEditor;
#endif

using UnityEngine;

namespace UnityEngine.Tilemaps
{
	[Serializable]
	public class TerrainTile : TileBase
	{
		[SerializeField]
		public Sprite[] m_Sprites;

		public override void RefreshTile(Vector3Int location, ITilemap tileMap)
		{
			for (int yd = -1; yd <= 1; yd++)
				for (int xd = -1; xd <= 1; xd++)
				{
					Vector3Int position = new Vector3Int(location.x + xd, location.y + yd, location.z);
					if (TileValue(tileMap, position))
						tileMap.RefreshTile(position);
				}
		}

		public override void GetTileData(Vector3Int location, ITilemap tileMap, ref TileData tileData)
		{
			UpdateTile(location, tileMap, ref tileData);
		}

		private void UpdateTile(Vector3Int location, ITilemap tileMap, ref TileData tileData)
		{
			tileData.transform = Matrix4x4.identity;
			tileData.color = Color.white;

			int mask = TileValue(tileMap, location + new Vector3Int(0, 1, 0)) ? 1 : 0;
			mask += TileValue(tileMap, location + new Vector3Int(1, 1, 0)) ? 2 : 0;
			mask += TileValue(tileMap, location + new Vector3Int(1, 0, 0)) ? 4 : 0;
			mask += TileValue(tileMap, location + new Vector3Int(1, -1, 0)) ? 8 : 0;
			mask += TileValue(tileMap, location + new Vector3Int(0, -1, 0)) ? 16 : 0;
			mask += TileValue(tileMap, location + new Vector3Int(-1, -1, 0)) ? 32 : 0;
			mask += TileValue(tileMap, location + new Vector3Int(-1, 0, 0)) ? 64 : 0;
			mask += TileValue(tileMap, location + new Vector3Int(-1, 1, 0)) ? 128 : 0;

			byte original = (byte)mask;
			if ((original | 254) < 255) { mask = mask & 125; }
			if ((original | 251) < 255) { mask = mask & 245; }
			if ((original | 239) < 255) { mask = mask & 215; }
			if ((original | 191) < 255) { mask = mask & 95; }

			int index = GetIndex((byte)mask);
			if (index >= 0 && index < m_Sprites.Length && TileValue(tileMap, location))
			{
				tileData.sprite = m_Sprites[index];
				tileData.transform = GetTransform((byte)mask);
				tileData.color = Color.white;
				tileData.flags = TileFlags.LockTransform | TileFlags.LockColor;
				tileData.colliderType = Tile.ColliderType.Sprite;
			}
		}

		private bool TileValue(ITilemap tileMap, Vector3Int position)
		{
			TileBase tile = tileMap.GetTile(position);
			return (tile != null && tile == this);
		}

		private int GetIndex(byte mask)
		{
			switch (mask)
			{
				case 0: return 0;
				case 1:
				case 4:
				case 16:
				case 64: return 1;
				case 5:
				case 20:
				case 80:
				case 65: return 2;
				case 7:
				case 28:
				case 112:
				case 193: return 3;
				case 17:
				case 68: return 4;
				case 21:
				case 84:
				case 81:
				case 69: return 5;
				case 23:
				case 92:
				case 113:
				case 197: return 6;
				case 29:
				case 116:
				case 209:
				case 71: return 7;
				case 31:
				case 124:
				case 241:
				case 199: return 8;
				case 85: return 9;
				case 87:
				case 93:
				case 117:
				case 213: return 10;
				case 95:
				case 125:
				case 245:
				case 215: return 11;
				case 119:
				case 221: return 12;
				case 127:
				case 253:
				case 247:
				case 223: return 13;
				case 255: return 14;
			}
			return -1;
		}

		private Matrix4x4 GetTransform(byte mask)
		{
			switch (mask)
			{
				case 4:
				case 20:
				case 28:
				case 68:
				case 84:
				case 92:
				case 116:
				case 124:
				case 93:
				case 125:
				case 221:
				case 253:
					return Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0f, 0f, -90f), Vector3.one);
				case 16:
				case 80:
				case 112:
				case 81:
				case 113:
				case 209:
				case 241:
				case 117:
				case 245:
				case 247:
					return Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0f, 0f, -180f), Vector3.one);
				case 64:
				case 65:
				case 193:
				case 69:
				case 197:
				case 71:
				case 199:
				case 213:
				case 215:
				case 223:
					return Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0f, 0f, -270f), Vector3.one);
			}
			return Matrix4x4.identity;
		}

#if UNITY_EDITOR
		[MenuItem("Assets/Create/Terrain Tile")]
		public static void CreateTerrainTile()
		{
			string path = EditorUtility.SaveFilePanelInProject("Save Terrain Tile", "New Terrain Tile", "asset", "Save Terrain Tile", "Assets");

			if (path == "")
				return;

			AssetDatabase.CreateAsset(ScriptableObject.CreateInstance<TerrainTile>(), path);
		}
#endif
	}

#if UNITY_EDITOR
	[CustomEditor(typeof(TerrainTile))]
	public class TerrainTileEditor : Editor
	{
		private TerrainTile tile { get { return (target as TerrainTile); } }

		public void OnEnable()
		{
			if (tile.m_Sprites == null || tile.m_Sprites.Length != 15)
			{
				tile.m_Sprites = new Sprite[15];
				EditorUtility.SetDirty(tile);
			}
		}

		public override void OnInspectorGUI()
		{
			EditorGUILayout.LabelField("Place sprites shown based on the contents of the sprite.");
			EditorGUILayout.Space();

			float oldLabelWidth = EditorGUIUtility.labelWidth;
			EditorGUIUtility.labelWidth = 210;

			EditorGUI.BeginChangeCheck();
			tile.m_Sprites[0] = (Sprite) EditorGUILayout.ObjectField("Filled", tile.m_Sprites[0], typeof(Sprite), false, null);
			tile.m_Sprites[1] = (Sprite) EditorGUILayout.ObjectField("Three Sides", tile.m_Sprites[1], typeof(Sprite), false, null);
			tile.m_Sprites[2] = (Sprite) EditorGUILayout.ObjectField("Two Sides and One Corner", tile.m_Sprites[2], typeof(Sprite), false, null);
			tile.m_Sprites[3] = (Sprite) EditorGUILayout.ObjectField("Two Adjacent Sides", tile.m_Sprites[3], typeof(Sprite), false, null);
			tile.m_Sprites[4] = (Sprite) EditorGUILayout.ObjectField("Two Opposite Sides", tile.m_Sprites[4], typeof(Sprite), false, null);
			tile.m_Sprites[5] = (Sprite) EditorGUILayout.ObjectField("One Side and Two Corners", tile.m_Sprites[5], typeof(Sprite), false, null);
			tile.m_Sprites[6] = (Sprite) EditorGUILayout.ObjectField("One Side and One Lower Corner", tile.m_Sprites[6], typeof(Sprite), false, null);
			tile.m_Sprites[7] = (Sprite) EditorGUILayout.ObjectField("One Side and One Upper Corner", tile.m_Sprites[7], typeof(Sprite), false, null);
			tile.m_Sprites[8] = (Sprite) EditorGUILayout.ObjectField("One Side", tile.m_Sprites[8], typeof(Sprite), false, null);
			tile.m_Sprites[9] = (Sprite) EditorGUILayout.ObjectField("Four Corners", tile.m_Sprites[9], typeof(Sprite), false, null);
			tile.m_Sprites[10] = (Sprite) EditorGUILayout.ObjectField("Three Corners", tile.m_Sprites[10], typeof(Sprite), false, null);
			tile.m_Sprites[11] = (Sprite) EditorGUILayout.ObjectField("Two Adjacent Corners", tile.m_Sprites[11], typeof(Sprite), false, null);
			tile.m_Sprites[12] = (Sprite) EditorGUILayout.ObjectField("Two Opposite Corners", tile.m_Sprites[12], typeof(Sprite), false, null);
			tile.m_Sprites[13] = (Sprite) EditorGUILayout.ObjectField("One Corner", tile.m_Sprites[13], typeof(Sprite), false, null);
			tile.m_Sprites[14] = (Sprite) EditorGUILayout.ObjectField("Empty", tile.m_Sprites[14], typeof(Sprite), false, null);
			if (EditorGUI.EndChangeCheck())
				EditorUtility.SetDirty(tile);

			EditorGUIUtility.labelWidth = oldLabelWidth;
		}
	}
#endif
}


text:
package org.elasticsearch.index.analysis;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.CustomAnalyzerWrapper;
import org.apache.lucene.util.Version;
import org.elasticsearch.common.lucene.Lucene;

/**
 * Named analyzer is an analyzer wrapper around an actual analyzer ({@link #analyzer} that is associated
 * with a name ({@link #name()}.
 */
public class NamedAnalyzer extends CustomAnalyzerWrapper {

    private final String name;
    private final AnalyzerScope scope;
    private final Analyzer analyzer;
    private final int positionOffsetGap;

    public NamedAnalyzer(NamedAnalyzer analyzer, int positionOffsetGap) {
        this(analyzer.name(), analyzer.scope(), analyzer.analyzer(), positionOffsetGap);
    }

    public NamedAnalyzer(String name, Analyzer analyzer) {
        this(name, AnalyzerScope.INDEX, analyzer);
    }

    public NamedAnalyzer(String name, AnalyzerScope scope, Analyzer analyzer) {
        this(name, scope, analyzer, Integer.MIN_VALUE);
    }

    static {
        // LUCENE MONITOR: this should be in Lucene 4.5.
        assert Lucene.VERSION == Version.LUCENE_44 : "when upgrading to 4.5, we should use call analyzer#getReuseStrategy(), see https://issues.apache.org/jira/browse/LUCENE-5170";
    }

    public NamedAnalyzer(String name, AnalyzerScope scope, Analyzer analyzer, int positionOffsetGap) {
        // our named analyzer always wrap a non per field analyzer, so no need to have per field analyzer
        super(new GlobalReuseStrategy());
        this.name = name;
        this.scope = scope;
        this.analyzer = analyzer;
        this.positionOffsetGap = positionOffsetGap;
    }

    /**
     * The name of the analyzer.
     */
    public String name() {
        return this.name;
    }

    /**
     * The scope of the analyzer.
     */
    public AnalyzerScope scope() {
        return this.scope;
    }

    /**
     * The actual analyzer.
     */
    public Analyzer analyzer() {
        return this.analyzer;
    }

    @Override
    protected Analyzer getWrappedAnalyzer(String fieldName) {
        return this.analyzer;
    }

    @Override
    protected TokenStreamComponents wrapComponents(String fieldName, TokenStreamComponents components) {
        return components;
    }

    @Override
    public int getPositionIncrementGap(String fieldName) {
        if (positionOffsetGap != Integer.MIN_VALUE) {
            return positionOffsetGap;
        }
        return super.getPositionIncrementGap(fieldName);
    }

    @Override
    public String toString() {
        return "analyzer name[" + name + "], analyzer [" + analyzer + "]";
    }
}


text:
module Dubious
  module CLI
    class Generator < Thor
      include Thor::Actions
      source_root File.dirname(__FILE__)+"/../templates/generator"
      argument :name
      add_runtime_options!

      desc "model NAME", "creates model file"
      def model#(name)
        template "model.mirah.tt", "app/models/#{name.underscore}.mirah"
      end

      desc "controller NAME", "creates controller file"
      def controller#(name)
        template "controller.mirah.tt", "app/controllers/#{name.underscore}_controller.mirah"
        empty_directory "app/views/#{name.underscore}"
        inject_into_file "WEB-INF/app.yaml", "  - url: /#{name.underscore}/*\n    servlet: controllers.#{name.classify}Controller\n    name: #{name.underscore}\n",:after => "handlers:\n"
      end

    end
  end
end


text:
import { webFrame, ipcRenderer as ipc } from "electron";

import NotificationSystem from "react-notification-system";

import chai, { expect } from "chai";
import sinon from "sinon";
import sinonChai from "sinon-chai";

import { dummyStore } from "../utils";
import * as menu from "../../src/notebook/menu";
import * as constants from "../../src/notebook/constants";

chai.use(sinonChai);

describe("menu", () => {
  describe("dispatchCreateCellAfter", () => {
    it("dispatches a CREATE_CELL_AFTER action", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchCreateCellAfter(store);

      expect(store.dispatch.firstCall).to.be.calledWith({
        type: constants.NEW_CELL_AFTER,
        cellType: "code",
        source: "",
        id: null
      });
    });
  });

  describe("dispatchCreateTextCellAfter", () => {
    it("dispatches a CREATE_TEXT_CELL_AFTER action", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchCreateTextCellAfter(store);

      expect(store.dispatch.firstCall).to.be.calledWith({
        type: constants.NEW_CELL_AFTER,
        cellType: "markdown",
        source: "",
        id: null
      });
    });
  });

  describe("dispatchPasteCell", () => {
    it("dispatches a PASTE_CELL action", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchPasteCell(store);

      expect(store.dispatch.firstCall).to.be.calledWith({
        type: constants.PASTE_CELL
      });
    });
  });

  describe("dispatchCutCell", () => {
    it("dispatches a CUT_CELL action", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchCutCell(store);

      expect(store.dispatch.firstCall).to.be.calledWith({
        type: constants.CUT_CELL,
        id: null
      });
    });
  });

  describe("dispatchCopyCell", () => {
    it("dispatches a COPY_CELL action", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchCopyCell(store);

      expect(store.dispatch.firstCall).to.be.calledWith({
        type: constants.COPY_CELL,
        id: null
      });
    });
  });

  describe("dispatchSetTheme", () => {
    it("dispatches a SET_CONFIG_KEY action", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchSetTheme(store, {}, "test_theme");

      expect(store.dispatch.firstCall).to.be.calledWith({
        type: constants.SET_CONFIG_KEY,
        key: "theme",
        value: "test_theme"
      });
    });
  });
  describe("dispatchSetCursorBlink", () => {
    it("dispatches a SET_CONFIG_KEY action", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchSetCursorBlink(store, {}, 42);

      expect(store.dispatch.firstCall).to.be.calledWith({
        type: constants.SET_CONFIG_KEY,
        key: "cursorBlinkRate",
        value: 42
      });
    });
  });

  describe("dispatchLoadConfig", () => {
    it("dispatches a LOAD_CONFIG action", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchLoadConfig(store);

      expect(store.dispatch.firstCall).to.be.calledWith({
        type: "LOAD_CONFIG"
      });
    });
  });

  describe("dispatchZoomOut", () => {
    it("executes zoom out", () => {
      const setZoomLevel = sinon.spy(webFrame, "setZoomLevel");
      menu.dispatchZoomOut();
      setZoomLevel.restore();
      expect(setZoomLevel).to.be.called;
    });
  });

  describe("dispatchZoomIn", () => {
    it("executes zoom in", () => {
      const setZoomLevel = sinon.spy(webFrame, "setZoomLevel");
      menu.dispatchZoomIn();
      setZoomLevel.restore();
      expect(setZoomLevel).to.be.called;
    });
  });

  describe("dispatchZoomReset", () => {
    it("executes zoom reset", () => {
      const setZoomLevel = sinon.spy(webFrame, "setZoomLevel");
      menu.dispatchZoomReset();
      setZoomLevel.restore();
      expect(setZoomLevel).to.be.calledWith(0);
    });
  });

  describe("dispatchRestartClearAll", () => {
    it("dispatches KILL_KERNEL and CLEAR_OUTPUTS actions", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchRestartClearAll(store);

      expect(store.dispatch.firstCall).to.be.calledWith({
        type: constants.KILL_KERNEL
      });
    });
  });

  describe("dispatchRestartKernel", () => {
    it("dispatches KILL_KERNEL and NEW_KERNEL actions", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchRestartKernel(store);

      expect(store.dispatch.firstCall).to.be.calledWith({
        type: constants.KILL_KERNEL
      });
    });
  });

  describe("dispatchInterruptKernel", () => {
    it("dispatches INTERRUPT_KERNEL actions", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchInterruptKernel(store);

      if (process.platform !== "win32") {
        expect(store.dispatch.firstCall).to.be.calledWith({
          type: constants.INTERRUPT_KERNEL
        });
      }
    });
  });

  describe("dispatchKillKernel", () => {
    it("dispatches KILL_KERNEL actions", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchKillKernel(store);

      expect(store.dispatch.firstCall).to.be.calledWith({
        type: constants.KILL_KERNEL
      });
    });
  });

  describe("dispatchClearAll", () => {
    it("dispatches CLEAR_OUTPUTS actions", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchClearAll(store);

      expect(store.dispatch.firstCall).to.be.calledWith({
        type: constants.CLEAR_OUTPUTS,
        id: store.getState().document.getIn(["notebook", "cellOrder"]).first()
      });
    });
  });

  describe("dispatchRunAllBelow", () => {
    it("runs all code cells below the focused cell", () => {
      const store = dummyStore({ codeCellCount: 4, markdownCellCount: 4 });
      const markdownCells = store
        .getState()
        .document.getIn(["notebook", "cellMap"])
        .filter(cell => cell.get("cell_type") === "markdown");
      store.dispatch = sinon.spy();

      menu.dispatchRunAllBelow(store);

      expect(store.dispatch.calledThrice).to.equal(true);
      markdownCells.forEach(cellId => {
        expect(
          store.dispatch.neverCalledWith({
            type: "EXECUTE_CELL",
            id: cellId,
            source: ""
          })
        ).to.equal(true);
      });
    });
  });

  describe("dispatchRunAll", () => {
    it("dispatches EXECUTE_CELL for all cells action", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchRunAll(store);

      const first = store
        .getState()
        .document.getIn(["notebook", "cellOrder"])
        .first();
      expect(store.dispatch.firstCall).to.be.calledWith({
        type: "EXECUTE_CELL",
        id: first,
        source: store
          .getState()
          .document.getIn(["notebook", "cellMap", first, "source"])
      });
    });
  });

  describe("dispatchUnhideAll", () => {
    it("dispatches changeInputVisibility for hidden code cells", () => {
      const store = dummyStore({ hideAll: true });
      store.dispatch = sinon.spy();

      menu.dispatchUnhideAll(store);

      const first = store
        .getState()
        .document.getIn(["notebook", "cellOrder"])
        .first();
      const expectedAction = { type: "CHANGE_INPUT_VISIBILITY", id: first };
      expect(store.dispatch.firstCall).to.be.calledWith(expectedAction);
    });
  });

  describe("dispatchPublishAnonGist", () => {
    it("dispatches PUBLISH_ANONYMOUS_GIST action", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();
      menu.dispatchPublishAnonGist(store);
      expect(store.dispatch.firstCall).to.be.calledWith({
        type: "PUBLISH_ANONYMOUS_GIST"
      });
    });
  });

  describe("dispatchPublishUserGist", () => {
    it("sets github token if token provided", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();
      menu.dispatchPublishUserGist(store, {}, "TOKEN");
      const expectedAction = { type: "SET_GITHUB_TOKEN", githubToken: "TOKEN" };
      expect(store.dispatch).to.have.been.calledWith(expectedAction);
    });
    it("dispatches setUserGithub and publishes gist", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();
      menu.dispatchPublishUserGist(store, {});
      const expectedSecondAction = { type: "PUBLISH_USER_GIST" };
      expect(store.dispatch).to.have.been.calledWith(expectedSecondAction);
    });
  });

  describe("dispatchNewKernel", () => {
    it("dispatches LAUNCH_KERNEL action", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchNewKernel(store, {}, { spec: "hokey" });

      expect(store.dispatch.firstCall).to.be.calledWith({
        type: constants.LAUNCH_KERNEL,
        kernelSpec: { spec: "hokey" },
        cwd: process.cwd()
      });
    });
  });

  describe("dispatchSave", () => {
    it("sends as SAVE request if given a filename", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchSave(store);

      expect(store.dispatch.firstCall).to.be.calledWith({
        type: "SAVE",
        filename: store.getState().metadata.get("filename"),
        notebook: store.getState().document.get("notebook")
      });
    });
  });

  describe("dispatchSaveAs", () => {
    it("dispatches SAVE_AS action", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchSaveAs(store, {}, "test-ipynb.ipynb");
      expect(store.dispatch.firstCall).to.be.calledWith({
        type: "SAVE_AS",
        filename: "test-ipynb.ipynb",
        notebook: store.getState().document.get("notebook")
      });
    });
  });

  describe("dispatchLoad", () => {
    it("dispatches LOAD action", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchLoad(store, {}, "test-ipynb.ipynb");
      expect(store.dispatch.firstCall).to.be.calledWith({
        type: "LOAD",
        filename: "test-ipynb.ipynb"
      });
    });
  });

  describe("dispatchNewNotebook", () => {
    it("dispatches a NEW_NOTEBOOK action", () => {
      const store = dummyStore();
      store.dispatch = sinon.spy();

      menu.dispatchNewNotebook(store, {}, { spec: "hokey" });
      expect(store.dispatch.firstCall).to.be.calledWith({
        type: "NEW_NOTEBOOK",
        kernelSpec: { spec: "hokey" },
        cwd: process.cwd()
      });
    });
  });

  describe("initMenuHandlers", () => {
    it("registers the menu events", () => {
      const store = dummyStore();
      const ipcOn = sinon.spy(ipc, "on");
      menu.initMenuHandlers(store);
      [
        "menu:new-kernel",
        "menu:run-all",
        "menu:clear-all",
        "menu:unhide-all",
        "menu:save",
        "menu:save-as",
        "menu:new-code-cell",
        "menu:copy-cell",
        "menu:cut-cell",
        "menu:paste-cell",
        "menu:kill-kernel",
        "menu:interrupt-kernel",
        "menu:restart-kernel",
        "menu:restart-and-clear-all",
        "menu:publish:gist",
        "menu:github:auth",
        "menu:zoom-in",
        "menu:zoom-out",
        "menu:theme",
        "menu:set-blink-rate",
        "main:load",
        "main:new"
      ].forEach(name => {
        expect(ipcOn).to.have.been.calledWith(name);
      });
    });
  });

  describe("showSaveAsDialog", () => {
    it("returns a promise", () => {
      const dialog = menu.showSaveAsDialog();
      expect(dialog).to.be.a("promise");
    });
  });

  describe("triggerWindowRefresh", () => {
    it("does nothing if no filename is given", () => {
      const store = dummyStore();

      expect(menu.triggerWindowRefresh(store, null)).to.be.undefined;
    });
    it("sends a SAVE_AS action if given filename", () => {
      const store = dummyStore();
      const filename = "dummy-nb.ipynb";
      store.dispatch = sinon.spy();

      menu.triggerWindowRefresh(store, filename);

      expect(store.dispatch.firstCall).to.be.calledWith({
        type: "SAVE_AS",
        notebook: store.getState().document.get("notebook"),
        filename
      });
    });
  });

  describe("exportPDF", () => {
    it("it notifies a user upon successful write", () => {
      const store = dummyStore();
      const notificationSystem = NotificationSystem();
      const addNotification = sinon.spy(notificationSystem, "addNotification");
      const filename = "thisisafilename.ipynb";
      menu.exportPDF(store, filename, notificationSystem);
      expect(addNotification).to.have.been.calledWithMatch({
        title: "PDF exported",
        message: `Notebook ${filename} has been exported as a pdf.`,
        dismissible: true,
        position: "tr",
        level: "success"
      });
    });
  });
  describe("triggerSaveAsPDF", () => {
    it("does something", () => {});
  });

  describe("storeToPDF", () => {
    it("triggers notification when not saved", () => {
      const config = { noFilename: true };
      const store = dummyStore(config);
      const addNotification = store.getState().app.get("notificationSystem")
        .addNotification;
      menu.storeToPDF(store);
      expect(addNotification).to.have.been.calledWithMatch({
        title: "File has not been saved!",
        message: [
          "Click the button below to save the notebook such that it can be ",
          "exported as a PDF."
        ],
        dismissible: true,
        position: "tr",
        level: "warning"
      });
    });
    it("calls export PDF when filename exists", () => {
      // const exportStub = sinon.spy(menu.exportPDF);
      const store = dummyStore();
      const addNotification = store.getState().app.get("notificationSystem")
        .addNotification;
      menu.storeToPDF(store);
      expect(addNotification).to.have.been.calledWithMatch({
        title: "PDF exported",
        message: "Notebook dummy-store-nb has been exported as a pdf.",
        dismissible: true,
        position: "tr",
        level: "success"
      });
    });
  });
});


text:
"""
testing case_class.signature

Copyright (c) 2016 Tom Wiesing -- licensed under MIT, see LICENSE
"""

from unittest import TestCase

from case_class import signature, exceptions

class TestSignature(TestCase):
    """ Tests the SignatureClass. """

    def test___init__(self):
        """ Tests that the signature extraction works properly. """

        def f(a, b="b", *c, **d):
            pass

        s = signature.Signature(f)

        self.assertEqual(s.args, ["a", "b"], "Extracting arguments from " +
                         "a function")
        self.assertEqual(s.defaults, ["b"], "Extracting default arguments " +
                         "from a function. ")
        self.assertEqual(s.vararg, "c", "Extracting vararg from function. ")
        self.assertEqual(s.varkw, "d", "Extracting keyword vararg from "
                                       "function. ")

    def test_get_argument_type(self):
        """ Tests that the get_argument_type works properly. """

        def f(a, b="b", *c, **d):
            pass

        s = signature.Signature(f)

        self.assertEqual(s.get_argument_type("a"),
                         signature.Signature.ARGUMENT,
                         "getting normal argument type")

        self.assertEqual(s.get_argument_type("b"),
                         signature.Signature.ARGUMENT_WITH_DEFAULT,
                         "getting argument with default type")

        self.assertEqual(s.get_argument_type("c"),
                         signature.Signature.VARARG,
                         "getting vararg type")
        self.assertEqual(s.get_argument_type("d"),
                         signature.Signature.KEYWORD_VARARG,
                         "getting keyword vararg")

        self.assertRaises(exceptions.NoSuchArgument,
                          lambda: s.get_argument_type("e"))

    def test_get_default(self):
        """ Tests that the test_get_default works properly. """

        def f(a, b="b", *c, **d):
            pass

        s = signature.Signature(f)

        # check that normal values do not have a default
        self.assertRaises(exceptions.NoDefaultValue,
                          lambda: s.get_default("a"))

        self.assertEqual(s.get_default("b"), "b", "Getting default value of " +
                         "a normal argument. ")

        # check that VARARG has no default
        self.assertRaises(exceptions.NoDefaultValue,
                          lambda: s.get_default("c"))

        # check that the KWVARARG as no default
        self.assertRaises(exceptions.NoDefaultValue,
                          lambda: s.get_default("d"))

        # check that we raise NoSuchArgument for non-existing values
        self.assertRaises(exceptions.NoSuchArgument,
                          lambda: s.get_default("e"))

    def test___eq__(self):
        """ Tests that equality between signatures works properly. """

        def f(a, b=1, *c, **d):
            pass

        sF = signature.Signature(f)

        def g(a, b=1, *c, **d):
            pass

        sG = signature.Signature(g)

        def h(a, b=1):
            pass

        sH = signature.Signature(h)

        self.assertEqual(sF, sF, "Equality of a signature to itself")
        self.assertEqual(sF, sG, "Equality of two signatures")
        self.assertNotEqual(sF, sH, "Inequality of two signatures")

        self.assertEqual(sG, sF, "Equality of two signatures")
        self.assertEqual(sG, sG, "Equality of a signature to itself")
        self.assertNotEqual(sG, sH, "Inequality of two signatures")

        self.assertNotEqual(sH, sF, "Inequality of two signatures")
        self.assertNotEqual(sH, sG, "Inequality of two signatures")
        self.assertEqual(sH, sH, "Equality of a signature to itself")

    def test___iter__(self):
        """ Tests that the iterator works properly. """

        def f(a, b="b", *c, **d):
            pass

        s = signature.Signature(f)

        self.assertEqual(list(s), [
            ("a", signature.Signature.ARGUMENT, None),
            ("b", signature.Signature.ARGUMENT_WITH_DEFAULT, "b"),
            ("c", signature.Signature.VARARG, None),
            ("d", signature.Signature.KEYWORD_VARARG, None)
        ], "iterate over a function signature")

    def test___str__(self):
        """ Tests that the stringifying signatures works properly. """

        def f(a, b="b", *c, **d):
            pass

        s = signature.Signature(f)
        self.assertEqual(str(s), "a, b='b', *c, **d",
                         "turning Signature into a string")

class TestAppliedSignature(TestCase):
    """ Tests the AppliedSignatureClass. """

    def test_passnormal(self):
        """ Tests that normal passing of arguments works. """

        def f(a, b="b", *c, **d):
            pass

        s = signature.Signature(f)

        a = s(1, 2, 3, e=4)

        self.assertEqual(a["a"], 1, "pass normal argument")
        self.assertEqual(a["b"], 2, "pass default argument")
        self.assertEqual(a["c"], (3,), "pass vararg")
        self.assertEqual(a["d"], {"e": 4}, "pass kwvararg")

    def test_passmin(self):
        """ Tests that passing of non-needed arguments works. """

        def f(a, b="b", *c, **d):
            pass

        s = signature.Signature(f)

        a = s(1)

        self.assertEqual(a["a"], 1, "pass normal argument")
        self.assertEqual(a["b"], "b", "using default value")
        self.assertEqual(a["c"], tuple(), "pass vararg")
        self.assertEqual(a["d"], {}, "pass kwvararg")

    def test_passweird(self):
        """ Tests that weird passing of arguments works. """

        def f(a, b="b", *c, **d):
            pass

        s = signature.Signature(f)

        a = s(b=2, a=1)

        self.assertEqual(a["a"], 1, "pass normal argument")
        self.assertEqual(a["b"], 2, "using default value")
        self.assertEqual(a["c"], tuple(), "pass vararg")
        self.assertEqual(a["d"], {}, "pass kwvararg")

    def test_MissingArgument(self):
        """ Tests that you must supply all missing arguments. """

        def f(a):
            pass

        s = signature.Signature(f)

        self.assertRaises(exceptions.MissingArgument, lambda: s())

    def test_DoubleArgumentValue(self):
        """ Tests that arguments can only be passed once. """

        def f(a):
            pass

        s = signature.Signature(f)

        self.assertRaises(exceptions.DoubleArgumentValue, lambda: s(1, a=1))

    def test_TooManyArguments(self):
        """ Tests that we can not pass to many arguments. """

        def f(a):
            pass

        s = signature.Signature(f)

        self.assertRaises(exceptions.TooManyArguments, lambda: s(1, 2))

    def test_TooManyKeyWordArguments(self):
        """ Tests that we can not pass to many keyword arguments. """

        def f(a):
            pass

        s = signature.Signature(f)

        self.assertRaises(exceptions.TooManyKeyWordArguments,
                          lambda: s(a=1, b=2))

    def test___eq__(self):
        """ Tests that equality between applied Signatures works properly. """

        def f(a, b=1, *c, **d):
            pass

        s = signature.Signature(f)
        aF = s(1, 2, k=4)
        aG = s(b=2, a=1, k=4)
        aH = s(1, 2, 3)

        self.assertEqual(aF, aF, "Equality of an applied signature to itself")
        self.assertEqual(aF, aG, "Equality of two applied signatures")
        self.assertNotEqual(aF, aH, "Inequality of two applied signatures")

        self.assertEqual(aG, aF, "Equality of two applied signatures")
        self.assertEqual(aG, aG, "Equality of an applied signature to itself")
        self.assertNotEqual(aG, aH, "Inequality of two applied signatures")

        self.assertNotEqual(aH, aF, "Inequality of two applied signatures")
        self.assertNotEqual(aH, aG, "Inequality of two applied signatures")
        self.assertEqual(aH, aH, "Equality of an applied signature to itself")

    def test___call__(self):
        """ Tests that partially overwriting values in Applied Signatures works
        properly.
        """

        def f(a, b=None, *c, **d):
            pass

        s = signature.Signature(f)
        a1 = s(1, 2, 3, f=4)
        a2 = s('o', 't', 3, f=4)
        a3 = s(1, 't', 3, f=4)
        a4 = s(1, 2, 4, 5, 6, f=4)
        a5 = s(1, 2, 3, f=4, g=5)
        a6 = s(1, 2, 3, f=5, g=6)

        self.assertEqual(a1, a1(), 'applying a signature overwriting nothing')
        self.assertEqual(a1('o', 't'), a2, 'overwriting normal arguments')
        self.assertEqual(a1(b='t'), a3, 'overwriting defaulted arguments')
        self.assertEqual(a1(1, 2, 4, 5, 6), a4, 'overwriting VARARG')
        self.assertEqual(a1(g=5), a5, 'adding KEYWORDVARARG')
        self.assertEqual(a1(f=5, g=6), a6, 'overwriting KEYWORDVARARG')

    def test___str__(self):
        """ Tests that the stringifying applied works properly. """

        def f(a, b="b", *c, **d):
            pass

        s = signature.Signature(f)
        a = s("1", "2", "3", f="4")
        self.assertEqual(str(a), "'1', b='2', *c=('3',), **d={'f': '4'}",
                         "turning Applied Signature into a string")

    def call(self):
        """ Tests that one can call applied signatures. """

        def f(a, b="b", *c, **d):
            return {
                'a': a,
                'b': b,
                'c': c,
                'd': d
            }

        s = signature.Signature(f)

        aF = s(1, 2, k=4)
        bF = f(1, 2, k=4)

        self.assertEqual(aF.call(), bF, 'calling applied signature')

        aG = s(b=2, a=1, k=4)
        bG = f(b=2, a=1, k=4)

        self.assertEqual(aG.call(), bG, 'calling applied signature')

        aH = s(1, 2, 3)
        bH = f(1, 2, 3)

        self.assertEqual(aG.call(), bG, 'calling applied signature')


text:
package com.nokia.springboot.training.d02.s02;

/**
 * The used run profiles
 *
 * @author bogdan.solga
 */
public final class Profiles {

    public static final String DEV = "dev";

    public static final String PROD = "prod";
}


text:
/* 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.
 */
package org.flowable.rest.api.jpa;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.test.Deployment;
import org.flowable.rest.api.jpa.model.Message;
import org.flowable.rest.service.api.RestUrls;
import org.flowable.task.api.Task;

import com.fasterxml.jackson.databind.JsonNode;

public class JpaRestTest extends BaseJPARestTestCase {

    @Deployment(resources = { "org/flowable/rest/api/jpa/jpa-process.bpmn20.xml" })
    public void testGetJpaVariableViaTaskVariablesCollections() throws Exception {

        // Get JPA managed entity through the repository
        Message message = messageRepository.findOne(1L);
        assertNotNull(message);
        assertEquals("Hello World", message.getText());

        // add the entity to the process variables and start the process
        Map<String, Object> processVariables = new HashMap<>();
        processVariables.put("message", message);

        ProcessInstance processInstance = processEngine.getRuntimeService().startProcessInstanceByKey("jpa-process", processVariables);
        assertNotNull(processInstance);

        Task task = processEngine.getTaskService().createTaskQuery().singleResult();
        assertEquals("Activiti is awesome!", task.getName());

        // Request all variables (no scope provides) which include global and
        // local
        HttpResponse response = executeHttpRequest(new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId())), HttpStatus.SC_OK);

        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent()).get(0);

        // check for message variable of type serializable
        assertNotNull(responseNode);
        assertEquals("message", responseNode.get("name").asText());
        assertEquals("global", responseNode.get("scope").asText());
        assertEquals("serializable", responseNode.get("type").asText());
        assertNotNull(responseNode.get("valueUrl"));
    }

    @Deployment(resources = { "org/flowable/rest/api/jpa/jpa-process.bpmn20.xml" })
    public void testGetJpaVariableViaTaskCollection() throws Exception {

        // Get JPA managed entity through the repository
        Message message = messageRepository.findOne(1L);
        assertNotNull(message);
        assertEquals("Hello World", message.getText());

        // add the entity to the process variables and start the process
        Map<String, Object> processVariables = new HashMap<>();
        processVariables.put("message", message);

        ProcessInstance processInstance = processEngine.getRuntimeService().startProcessInstanceByKey("jpa-process", processVariables);
        assertNotNull(processInstance);

        Task task = processEngine.getTaskService().createTaskQuery().singleResult();
        assertEquals("Activiti is awesome!", task.getName());

        // Request all variables (no scope provides) which include global and
        // local
        HttpResponse response = executeHttpRequest(new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_COLLECTION) + "?includeProcessVariables=true"), HttpStatus.SC_OK);

        JsonNode dataNode = objectMapper.readTree(response.getEntity().getContent()).get("data").get(0);
        assertNotNull(dataNode);

        JsonNode variableNode = dataNode.get("variables").get(0);
        assertNotNull(variableNode);

        // check for message variable of type serializable
        assertEquals("message", variableNode.get("name").asText());
        assertEquals("global", variableNode.get("scope").asText());

        assertEquals("serializable", variableNode.get("type").asText());
        assertNotNull(variableNode.get("valueUrl"));
    }

    @Deployment(resources = { "org/flowable/rest/api/jpa/jpa-process.bpmn20.xml" })
    public void testGetJpaVariableViaHistoricProcessCollection() throws Exception {

        // Get JPA managed entity through the repository
        Message message = messageRepository.findOne(1L);
        assertNotNull(message);
        assertEquals("Hello World", message.getText());

        // add the entity to the process variables and start the process
        Map<String, Object> processVariables = new HashMap<>();
        processVariables.put("message", message);

        ProcessInstance processInstance = processEngine.getRuntimeService().startProcessInstanceByKey("jpa-process", processVariables);
        assertNotNull(processInstance);

        Task task = processEngine.getTaskService().createTaskQuery().singleResult();
        assertEquals("Activiti is awesome!", task.getName());

        // Request all variables (no scope provides) which include global and
        // local
        HttpResponse response = executeHttpRequest(
                new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_HISTORIC_PROCESS_INSTANCES) + "?processInstanceId=" + processInstance.getId() + "&includeProcessVariables=true"),
                HttpStatus.SC_OK);

        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());

        // check for message variable of type serializable
        assertNotNull(responseNode);
        JsonNode variablesArrayNode = responseNode.get("data").get(0).get("variables");
        assertEquals(1, variablesArrayNode.size());
        JsonNode variableNode = variablesArrayNode.get(0);
        assertEquals("message", variableNode.get("name").asText());
        assertEquals("serializable", variableNode.get("type").asText());
        assertNotNull(variableNode.get("valueUrl"));
    }

    @Deployment(resources = { "org/flowable/rest/api/jpa/jpa-process.bpmn20.xml" })
    public void testGetJpaVariableViaHistoricVariablesCollections() throws Exception {

        // Get JPA managed entity through the repository
        Message message = messageRepository.findOne(1L);
        assertNotNull(message);
        assertEquals("Hello World", message.getText());

        // add the entity to the process variables and start the process
        Map<String, Object> processVariables = new HashMap<>();
        processVariables.put("message", message);

        ProcessInstance processInstance = processEngine.getRuntimeService().startProcessInstanceByKey("jpa-process", processVariables);
        assertNotNull(processInstance);

        Task task = processEngine.getTaskService().createTaskQuery().singleResult();
        assertEquals("Activiti is awesome!", task.getName());

        // Request all variables (no scope provides) which include global and
        // local
        HttpResponse response = executeHttpRequest(
                new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_HISTORIC_VARIABLE_INSTANCES) + "?processInstanceId=" + processInstance.getId()), HttpStatus.SC_OK);

        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());

        // check for message variable of type serializable
        assertNotNull(responseNode);
        JsonNode variableNode = responseNode.get("data").get(0).get("variable");
        assertEquals("message", variableNode.get("name").asText());
        assertEquals("serializable", variableNode.get("type").asText());
        assertNotNull(variableNode.get("valueUrl"));
    }
}


text:
using UnityEngine;

public class PingPong : MonoBehaviour
{
    public float lerpTime = 5f;

    public Vector3 posMin = Vector3.zero;
    public Vector3 posMax = Vector3.zero;

    private Transform thisTransform = null;

    void OnEnable()
    {
        thisTransform = transform;
    }

    void Update()
    {
        thisTransform.localPosition = Vector3.Lerp(posMin, posMax, Mathf.PingPong(Time.time * (1f / lerpTime), 1f));
    }
}


text:
// Copyright 2014 Shanghai Jiao Tong University
//
// 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.
//
// Authors - Trusted Cloud Group (http://tcloud.sjtu.edu.cn)

#ifndef EXPR_H_
#define EXPR_H_

#ifdef USE_SOLVER
#include "../stp/c_interface/c_interface.h"
#endif
#include <string>

using namespace std;

namespace esp{

class Expression{
public:
  string name;      /* name of the expression */
  unsigned width;   /* width of the expression.*/

#ifdef USE_SOLVER
  Expr expr;    //STP-style Expression

  Expression(string _name, unsigned _width, Expr _expr)
            :name(_name), width(_width), expr(_expr){};
#else
  bool value;       /* */

  /*
   * Constructor
   * @Param
   * _name: name of the boolean expression
   * _width:width of the boolean expression
   * _value:value of the boolean expression
   */
  Expression(string _name, unsigned _width, bool _value)
            :name(_name), width(_width), value(_value){};
#endif

};

}

#endif /* EXPR_H_ */


text:
class CreateNotifications < ActiveRecord::Migration[4.2]
  def change
    create_table :notifications do |t|
      t.integer :user_id
      t.boolean :read, null: false, default: false
      t.integer :broadcast_id
      t.integer :broadcast_comment_id
      t.timestamps null: false
    end
    add_index :notifications, :user_id
    add_index :notifications, :read
    add_index :notifications, :broadcast_id
    add_index :notifications, :broadcast_comment_id
  end
end


text:
/* eslint-disable no-underscore-dangle */
import callable from '../callable.next.js';
import streamDuplex from './stream.duplex.next.js';

/**
 *
 * @function
 * @memberof is
 * @param {any} value
 * @returns {Boolean}
 */
export default function isStreamTransform(value) {
	return streamDuplex(value) &&
	value._transformState != null &&
	callable(value._transform);
}


text:
class CreateContacts < ActiveRecord::Migration
  def self.up
    create_table :contacts, :force => true do |t|
      t.string      :uuid,   :limit => 36
      t.references  :user
      t.references  :lead
      t.integer     :assigned_to
      t.integer     :reports_to
      t.string      :first_name,  :limit => 64, :null => false, :default => ""
      t.string      :last_name,   :limit => 64, :null => false, :default => ""
      t.string      :access,      :limit => 8, :default => "Public"
      t.string      :title,       :limit => 64
      t.string      :department,  :limit => 64
      t.string      :source,      :limit => 32
      t.string      :email,       :limit => 64
      t.string      :alt_email,   :limit => 64
      t.string      :phone,       :limit => 32
      t.string      :mobile,      :limit => 32
      t.string      :fax,         :limit => 32
      t.string      :blog,        :limit => 128
      t.string      :linkedin,    :limit => 128
      t.string      :facebook,    :limit => 128
      t.string      :twitter,     :limit => 128
      t.string      :address
      t.date        :born_on
      t.boolean     :do_not_call, :null => false, :default => false
      t.datetime    :deleted_at
      t.timestamps
    end

    add_index :contacts, [ :user_id, :last_name, :deleted_at ], :unique => true, :name => 'id_last_name_deleted'
    add_index :contacts, :assigned_to
  end

  def self.down
    drop_table :contacts
  end
end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="generator" content="Source Themes Academic 4.8.0">

  <meta name="author" content="Rajeev Sharma">

  <meta name="description" content="Problem We have listing of all Users and other data list at our admin panels per application. A basic Search functionality was required with less efforts and adjustable quickly.
Solution In your Gemfile, for the last officially released gem: gem 'ransack'">

  <link rel="alternate" hreflang="en-us" href="/post/2016-05-14-object-based-search-rails-ransack-/">

  <meta name="theme-color" content="hsl(339, 90%, 68%)">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.6/css/academicons.min.css" integrity="sha256-uFVgMKfistnJAfoCUQigIl+JfUaP47GrRKjf6CTPVmw=" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-1/css/all.min.css" integrity="sha256-4w9DunooKSr3MFXHXWyFER38WmPdm361bQS/2KUWZbU=" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css" integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin="anonymous">

          <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/github.min.css" crossorigin="anonymous" title="hl-light">
          <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/dracula.min.css" crossorigin="anonymous" title="hl-dark" disabled>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.css" integrity="sha256-SHMGCYmST46SoyGgo4YR/9AlK1vf3ff84Aq9yK4hdqM=" crossorigin="anonymous">

  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:400,700%7CRoboto:400,400italic,700%7CRoboto+Mono&display=swap">

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

  <link rel="manifest" href="/index.webmanifest">
  <link rel="icon" type="image/png" href="/images/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_32x32_fill_lanczos_center_2.png">
  <link rel="apple-touch-icon" type="image/png" href="/images/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_192x192_fill_lanczos_center_2.png">

  <link rel="canonical" href="/post/2016-05-14-object-based-search-rails-ransack-/">

  <meta property="twitter:card" content="summary_large_image">

  <meta property="twitter:site" content="@rajeevkannav">
  <meta property="twitter:creator" content="@rajeevkannav">

  <meta property="og:site_name" content="Rajeev Sharma">
  <meta property="og:url" content="/post/2016-05-14-object-based-search-rails-ransack-/">
  <meta property="og:title" content="Object-based searching rails Active-Record | Rajeev Sharma">
  <meta property="og:description" content="Problem We have listing of all Users and other data list at our admin panels per application. A basic Search functionality was required with less efforts and adjustable quickly.
Solution In your Gemfile, for the last officially released gem: gem 'ransack'"><meta property="og:image" content="/img/rajeevkannav.jpeg">
  <meta property="twitter:image" content="/img/rajeevkannav.jpeg"><meta property="og:locale" content="en-us">

      <meta property="article:published_time" content="2016-05-14T00:00:00+00:00">

    <meta property="article:modified_time" content="2016-05-14T00:00:00+00:00">

  <title>Object-based searching rails Active-Record | Rajeev Sharma</title>

Search

        <input name="q" id="search-query" placeholder="Search..." autocapitalize="off"
        autocomplete="off" autocorrect="off" spellcheck="false" type="search">

      Rajeev Sharma

    <button type="button" class="navbar-toggler" data-toggle="collapse"
            data-target="#navbar-content" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation">

    </button>

      Rajeev Sharma

          Home

          Posts

          Experience

          Contact

Object-based searching rails Active-Record

    May 14, 2016

    1 min read

Problem

We have listing of all Users and other data list at our admin panels per application.
A basic Search functionality was required with less efforts and adjustable quickly.

Solution

In your Gemfile, for the last officially released gem:
gem 'ransack'

In your controller

{% highlight ruby %}
def index
@q = Person.ransack(params[:q])
@people = @q.result(distinct: true)
end
{% endhighlight %}

In your view

{% highlight ruby %}
<%= search_form_for @q do |f| %>

Search if the name field contains…

<%= f.label :name_cont %>
<%= f.search_field :name_cont %>

Search if an associated articles.title starts with…

<%= f.label :articles_title_start %>
<%= f.search_field :articles_title_start %>

Attributes may be chained. Search multiple attributes for one value…

<%= f.label :name_or_description_or_email_or_articles_title_cont %>
<%= f.search_field :name_or_description_or_email_or_articles_title_cont %>

<%= f.submit %>
<% end %>
{% endhighlight %}

cont (contains) and start (starts with) are just two of the
available search predicates. See
Constants for a full list
and the
wiki for more information.

Ransack’s sort_link helper creates table headers that are sortable links

<%= sort_link(@q, :name) %>

And if you get stuck…
Ask Here

 email me
rajeevsharma86@gmail.com

  rails

  search

  activerecord

Rajeev Sharma

Technical Lead

software entrepreneur and father of a fairy tale!!!.

Related

Rack::Utils Basic information

passenger 5.0.26 with nginx deployment fix

using twitter-bootstrap via rails engine.

Bad to worse rails practice

Gemfile audits in rails

    © 2020 Rajeev Sharma ·

    Powered by the
    Academic theme for
    Hugo.

Cite

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

           Copy

           Download


text:
package stackcommands

import (
	"github.com/rackspace/rack/commandoptions"
	"github.com/rackspace/rack/handler"
	"github.com/rackspace/rack/internal/github.com/codegangsta/cli"
	"github.com/rackspace/rack/internal/github.com/rackspace/gophercloud/rackspace/orchestration/v1/stacktemplates"
	"github.com/rackspace/rack/util"
)

var getTemplate = cli.Command{
	Name:        "get-template",
	Usage:       util.Usage(commandPrefix, "get-template", "[--name <stackName> | --id <stackID> | --stdin name]"),
	Description: "Get template for specified stack",
	Action:      actionGetTemplate,
	Flags:       commandoptions.CommandFlags(flagsGetTemplate, keysGetTemplate),
	BashComplete: func(c *cli.Context) {
		commandoptions.CompleteFlags(commandoptions.CommandFlags(flagsGetTemplate, keysGetTemplate))
	},
}

func flagsGetTemplate() []cli.Flag {
	return []cli.Flag{
		cli.StringFlag{
			Name:  "name",
			Usage: "[optional; required if neither `id` nor `stdin` is provided] The stack name.",
		},
		cli.StringFlag{
			Name:  "id",
			Usage: "[optional; required if neither `name` nor `stdin` is provided] The stack id.",
		},
		cli.StringFlag{
			Name:  "stdin",
			Usage: "[optional; required if neither `name` nor `id` is provided] The field being piped into STDIN. Valid values are: name.",
		},
	}
}

type paramsGetTemplate struct {
	stackName string
	stackID   string
}

var keysGetTemplate = []string{"Description", "HeatTemplateVersion", "Parameters", "Resources", "Outputs"}

type commandGetTemplate handler.Command

func actionGetTemplate(c *cli.Context) {
	command := &commandGetTemplate{
		Ctx: &handler.Context{
			CLIContext: c,
		},
	}
	handler.Handle(command)
}

func (command *commandGetTemplate) Context() *handler.Context {
	return command.Ctx
}

func (command *commandGetTemplate) Keys() []string {
	return keysGetTemplate
}

func (command *commandGetTemplate) ServiceClientType() string {
	return serviceClientType
}

func (command *commandGetTemplate) HandlePipe(resource *handler.Resource, item string) error {
	name, id, err := IDAndName(command.Ctx.ServiceClient, item, "")
	if err != nil {
		return err
	}
	resource.Params = &paramsGetTemplate{
		stackName: name,
		stackID:   id,
	}
	return nil
}

func (command *commandGetTemplate) HandleSingle(resource *handler.Resource) error {
	c := command.Ctx.CLIContext
	name := c.String("name")
	id := c.String("id")
	name, id, err := IDAndName(command.Ctx.ServiceClient, name, id)
	if err != nil {
		return err
	}

	resource.Params = &paramsGetTemplate{
		stackName: name,
		stackID:   id,
	}
	return nil
}

func (command *commandGetTemplate) HandleFlags(resource *handler.Resource) error {
	return nil
}

func (command *commandGetTemplate) Execute(resource *handler.Resource) {
	params := resource.Params.(*paramsGetTemplate)
	stackName := params.stackName
	stackID := params.stackID
	template, err := stacktemplates.Get(command.Ctx.ServiceClient, stackName, stackID).Extract()
	if err != nil {
		resource.Err = err
		return
	}
	resource.Result = string(template)
}

func (command *commandGetTemplate) StdinField() string {
	return "name"
}


text:
use strict;
use warnings;
use HPEOneView::Clients::Security::LoginSessions;
use HPEOneView::Clients::Servers::ServerHardware;
use HPEOneView::Behaviors::Activity::Tasks;
use HPEOneView::Behaviors::Servers::ServerProfiles;

my $hostname = '';
my $username = '';
my $password = '';
# Set this to directory server name if use directory authorization
#my $login_domain = '';

my $server_hardware_type_uri = '';
my $enclosure_group_uri = '';

my $login = HPEOneView::Clients::Security::LoginSessions->new(hostname=>$hostname,userName=>$username,password=>$password);
my $sh = HPEOneView::Clients::Servers::ServerHardware->new(session=>$login->session);
my $sp = HPEOneView::Behaviors::Servers::ServerProfiles->new(session=>$login->session);

open(my $fh, '>', 'server_hardware_uris');
foreach my $start (0..3) {
    my $resp = $sh->get_server_hardware(start=>$start, count=>1);
    my $json = parse_json($resp->content);
    my $sh= $json->{members}->[0];
    my $id = $start + 1;
    my $name = "sp-nospt-nospp-$id";
    print $fh $sh->{uri};

    my $body = qq({"type":"ServerProfileV6","serverHardwareUri":"$sh->{uri}","serverHardwareTypeUri":"$server_hardware_type_uri","enclosureGroupUri":"$enclosure_group_uri","serialNumberType":"Virtual","iscsiInitiatorNameType":"AutoGenerated","macType":"Virtual","wwnType":"Virtual","name":"$name","description":"","affinity":"Bay","connections":[],"boot":{"manageBoot":false},"bootMode":null,"firmware":{"manageFirmware":false,"firmwareBaselineUri":"","forceInstallFirmware":false,"firmwareInstallType":null},"bios":{"manageBios":false,"overriddenSettings":[]},"hideUnusedFlexNics":true,"iscsiInitiatorName":"","osDeploymentSettings":null,"localStorage":{"sasLogicalJBODs":[],"controllers":[]},"sanStorage":null});
    if (! $sp->create_sp($body)) {
        print $fh " failed\n";
    }
    print $fh "\n";
}

close $fh;


text:
<?php

namespace App\Http\Middleware;

use App\Enseignant;
use Closure;
use Illuminate\Support\Facades\Session;

class HeaderManager
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Session::get('connected_user') !== null){
            $id = Enseignant::getIdFromLogin(Session::get('connected_user'));
            if($id === null){
                Session::forget('jwt');
                Session::forget('connected_user');
                Session::forget('user_id');
            }
        }

        if(Session::get('jwt') !== null) {
            $request->headers->set('Authorization', 'bearer ' . Session::get('jwt'));
        }
        return $next($request);
    }
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Module: SoftwareHeretics::ActiveRecord::SimplyVersioned::VersionsProxyMethods</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href="../../../.././rdoc-style.css" type="text/css" media="screen" />

          Module
          SoftwareHeretics::ActiveRecord::SimplyVersioned::VersionsProxyMethods

            In:

                lib/simply_versioned.rb

Methods

      clean
      current
      first
      get
      next
      prev

Public Instance methods

          clean( versions_to_keep )

If the model instance has more versions than the limit specified, delete
all excess older versions.

[Source]

    # File lib/simply_versioned.rb, line 79
79:         def clean( versions_to_keep )
80:           find( :all, :conditions => [ 'number <= ?', self.maximum( :number ) - versions_to_keep ] ).each do |version|
81:             version.destroy
82:           end
83:         end

          current()

Get the current Version
corresponding to this model.

[Source]

    # File lib/simply_versioned.rb, line 74
74:         def current
75:           find( :first, :order => 'number DESC' )
76:         end

          first()

Get the first Version
corresponding to this model.

[Source]

    # File lib/simply_versioned.rb, line 69
69:         def first
70:           find( :first, :order => 'number ASC' )
71:         end

          get( number )

Get the Version instance corresponding to this models for the specified
version number.

[Source]

    # File lib/simply_versioned.rb, line 64
64:         def get( number )
65:           find_by_number( number )
66:         end

          next( number )

Return the Version for this model with the next higher version

[Source]

    # File lib/simply_versioned.rb, line 86
86:         def next( number )
87:           find( :first, :order => 'number ASC', :conditions => [ "number > ?", number ] )
88:         end

          prev( number )

Return the Version for this model with the next lower version

[Source]

    # File lib/simply_versioned.rb, line 91
91:         def prev( number )
92:           find( :first, :order => 'number DESC', :conditions => [ "number < ?", number ] )
93:         end

[Validate]


text:
<?php

declare(strict_types=1);

namespace Xparse\Parser\Helper;

use DOMElement;
use DOMNodeList;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\Psr7\UriResolver;
use Xparse\ElementFinder\DomNodeListAction\DomNodeListActionInterface;

/**
 * @internal
 * @author Ivan Shcherbak <alotofall@gmail.com>
 */
class ConvertUrlElementFinderModifier implements DomNodeListActionInterface
{

    /**
     * @var string
     */
    private $affectedUrl;

    /**
     * @var string
     */
    private $baseUrl;

    public function __construct(string $affectedUrl, string $baseUrl)
    {
        $this->affectedUrl = $affectedUrl;
        $this->baseUrl = $baseUrl;
    }

    final public function execute(DOMNodeList $nodeList): void
    {
        $affected = new Uri($this->affectedUrl);
        foreach ($nodeList as $element) {
            assert($element instanceof DOMElement);
            $attribute = $this->attributeName($element);
            $relative = $element->getAttribute($attribute);
            $isValid = parse_url($relative) !== false;
            if (
                $isValid
                &&
                !preg_match('!^\s*javascript\s*:\s*!', $relative)
            ) {
                if ($this->baseUrl !== '' && !preg_match('!^(/|http)!i', $relative)) {
                    $relative = UriResolver::resolve(new Uri($this->baseUrl), new Uri($relative));
                }
                $url = UriResolver::resolve($affected, new Uri($relative));
                $element->setAttribute($attribute, (string)$url);
            }
        }
    }

    private function attributeName(DOMElement $element): string
    {
        $name = 'href';
        if ($element->tagName === 'form' && $element->hasAttribute('action') === true) {
            $name = 'action';
        } else if ($element->hasAttribute('src') === true) {
            $name = 'src';
        }
        return $name;
    }

}


text:
require('normalize.css')
require('@/main.css')

const logoSrc = require('@/assets/images/yeoman-logo.png')

const logo = document.createElement('img')
logo.setAttribute('src', logoSrc)
document.getElementById('app').appendChild(logo)

// function append() {
//   require.ensure(['jquery'], require => {
//     const $ = require('jquery')
//     $('#app').append(logo)
//   })
// }

// setTimeout(append, 0)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Öst. bot. Z. 112: 189 (1965)

#### Original name
Lentaria mucida var. hexaspora Geitler

### Remarks
null


text:
@protocol AcromineHTTPClientDelegate;

@interface AcromineHTTPClient : AFHTTPSessionManager

@property (nonatomic, weak) id<AcromineHTTPClientDelegate>delegate;

- (instancetype)initWithBaseURL:(NSURL *)url;

- (void)fetchLongFormsForAcronym:(NSString *)acronym;

@end

@protocol AcromineHTTPClientDelegate <NSObject>

@optional

- (void)acromineHTTPClient:(AcromineHTTPClient *)client didFetchLongForms:(id)longForms;
- (void)acromineHTTPClient:(AcromineHTTPClient *)client didFailFetchingLongFormsWithError:(NSError *)error;

@end


text:
#pragma once
#include <aws/events/CloudWatchEvents_EXPORTS.h>
#include <aws/events/CloudWatchEventsRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace CloudWatchEvents
{
namespace Model
{

  /**
   */
  class AWS_CLOUDWATCHEVENTS_API RemovePermissionRequest : public CloudWatchEventsRequest
  {
  public:
    RemovePermissionRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "RemovePermission"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The statement ID corresponding to the account that is no longer allowed to
     * put events to the default event bus.

     */
    inline const Aws::String& GetStatementId() const{ return m_statementId; }

    /**
     *
The statement ID corresponding to the account that is no longer allowed to
     * put events to the default event bus.

     */
    inline bool StatementIdHasBeenSet() const { return m_statementIdHasBeenSet; }

    /**
     *
The statement ID corresponding to the account that is no longer allowed to
     * put events to the default event bus.

     */
    inline void SetStatementId(const Aws::String& value) { m_statementIdHasBeenSet = true; m_statementId = value; }

    /**
     *
The statement ID corresponding to the account that is no longer allowed to
     * put events to the default event bus.

     */
    inline void SetStatementId(Aws::String&& value) { m_statementIdHasBeenSet = true; m_statementId = std::move(value); }

    /**
     *
The statement ID corresponding to the account that is no longer allowed to
     * put events to the default event bus.

     */
    inline void SetStatementId(const char* value) { m_statementIdHasBeenSet = true; m_statementId.assign(value); }

    /**
     *
The statement ID corresponding to the account that is no longer allowed to
     * put events to the default event bus.

     */
    inline RemovePermissionRequest& WithStatementId(const Aws::String& value) { SetStatementId(value); return *this;}

    /**
     *
The statement ID corresponding to the account that is no longer allowed to
     * put events to the default event bus.

     */
    inline RemovePermissionRequest& WithStatementId(Aws::String&& value) { SetStatementId(std::move(value)); return *this;}

    /**
     *
The statement ID corresponding to the account that is no longer allowed to
     * put events to the default event bus.

     */
    inline RemovePermissionRequest& WithStatementId(const char* value) { SetStatementId(value); return *this;}

    /**
     *
Specifies whether to remove all permissions.

     */
    inline bool GetRemoveAllPermissions() const{ return m_removeAllPermissions; }

    /**
     *
Specifies whether to remove all permissions.

     */
    inline bool RemoveAllPermissionsHasBeenSet() const { return m_removeAllPermissionsHasBeenSet; }

    /**
     *
Specifies whether to remove all permissions.

     */
    inline void SetRemoveAllPermissions(bool value) { m_removeAllPermissionsHasBeenSet = true; m_removeAllPermissions = value; }

    /**
     *
Specifies whether to remove all permissions.

     */
    inline RemovePermissionRequest& WithRemoveAllPermissions(bool value) { SetRemoveAllPermissions(value); return *this;}

    /**
     *
The name of the event bus to revoke permissions for. If you omit this, the
     * default event bus is used.

     */
    inline const Aws::String& GetEventBusName() const{ return m_eventBusName; }

    /**
     *
The name of the event bus to revoke permissions for. If you omit this, the
     * default event bus is used.

     */
    inline bool EventBusNameHasBeenSet() const { return m_eventBusNameHasBeenSet; }

    /**
     *
The name of the event bus to revoke permissions for. If you omit this, the
     * default event bus is used.

     */
    inline void SetEventBusName(const Aws::String& value) { m_eventBusNameHasBeenSet = true; m_eventBusName = value; }

    /**
     *
The name of the event bus to revoke permissions for. If you omit this, the
     * default event bus is used.

     */
    inline void SetEventBusName(Aws::String&& value) { m_eventBusNameHasBeenSet = true; m_eventBusName = std::move(value); }

    /**
     *
The name of the event bus to revoke permissions for. If you omit this, the
     * default event bus is used.

     */
    inline void SetEventBusName(const char* value) { m_eventBusNameHasBeenSet = true; m_eventBusName.assign(value); }

    /**
     *
The name of the event bus to revoke permissions for. If you omit this, the
     * default event bus is used.

     */
    inline RemovePermissionRequest& WithEventBusName(const Aws::String& value) { SetEventBusName(value); return *this;}

    /**
     *
The name of the event bus to revoke permissions for. If you omit this, the
     * default event bus is used.

     */
    inline RemovePermissionRequest& WithEventBusName(Aws::String&& value) { SetEventBusName(std::move(value)); return *this;}

    /**
     *
The name of the event bus to revoke permissions for. If you omit this, the
     * default event bus is used.

     */
    inline RemovePermissionRequest& WithEventBusName(const char* value) { SetEventBusName(value); return *this;}

  private:

    Aws::String m_statementId;
    bool m_statementIdHasBeenSet = false;

    bool m_removeAllPermissions;
    bool m_removeAllPermissionsHasBeenSet = false;

    Aws::String m_eventBusName;
    bool m_eventBusNameHasBeenSet = false;
  };

} // namespace Model
} // namespace CloudWatchEvents
} // namespace Aws


text:
A jQuery plugin to easily add functionality to fix elements to the top of the page on scroll.

### Installation

Include script after the jQuery library:

```html
<script type="text/javascript" src="/path/to/jquery-sticky.js"></script>
```

### Usage

```js
$('.menu').sticky( options )
```

### Options

#### stickyClass (string)

An optional class to be added to the element.

```js
stickyClass: 'sticky'
```

#### anchorClass (string)

An optional class to be added to the generated anchor.

```js
anchorClass: 'sticky-anchor'
```

#### activeClass (string)

Set the class that will be added to the element when it is fixed to the top of the page.

```js
activeClass: 'active'
```

#### buffer (number)

Option to add a buffer to the top of the sticky element in the form of a number representing the size of the buffer in pixels.

```js
buffer: 20
```

### TODO

* If the height of the sticky element is changed (for example when active) the anchor retains the original height

## License

MIT License
(c) [Bruno Tarmann](http://tarmann.com.br) & [Gareth Nolan](http://ie.linkedin.com/in/garethnolan/)


text:
<service name="PingPort">
	<parameter locked="false" name="ServiceClass">org.apache.axis2.oasis.ping.PingPortSkeleton</parameter>
	<!--Mounting the method Ping-->
	<operation name="Ping">
		<messageReceiver class="org.apache.axis2.oasis.ping.PingPortMessageReceiverInOut"/>
	</operation>

    <parameter name="InflowSecurity">
      <action>
        <items>Signature Encrypt Timestamp</items>
        <passwordCallbackClass>org.apache.axis2.security.PWCallback</passwordCallbackClass>
        <signaturePropFile>interop.properties</signaturePropFile>
      </action>
    </parameter>

    <parameter name="OutflowSecurity">
      <action>
        <items>Signature Encrypt Timestamp</items>
        <user>bob</user>
        <passwordCallbackClass>org.apache.axis2.security.PWCallback</passwordCallbackClass>
        <signaturePropFile>interop.properties</signaturePropFile>
        <signatureKeyIdentifier>DirectReference</signatureKeyIdentifier>
        <encryptionKeyIdentifier>SKIKeyIdentifier</encryptionKeyIdentifier>
        <encryptionUser>alice</encryptionUser>

        <optimizeParts>//xenc:EncryptedData/xenc:CipherData/xenc:CipherValue</optimizeParts>
      </action>
    </parameter>

</service>


text:
#region License

#endregion

#region Contact

/*
 * Leslie Sanford
 * Email: jabberdabber@hotmail.com
 */

#endregion

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Sanford.Multimedia;

namespace Sanford.Multimedia.Midi.UI
{
    public partial class PianoControl
    {
        private class PianoKey : Control
        {
            private PianoControl owner;

            private bool on = false;

            private SolidBrush onBrush = new SolidBrush(Color.SkyBlue);

            private SolidBrush offBrush = new SolidBrush(Color.White);

            private int noteID = 60;

            public PianoKey(PianoControl owner)
            {
                this.owner = owner;
                this.TabStop = false;
            }

            public void PressPianoKey()
            {
                #region Guard

                if(on)
                {
                    return;
                }

                #endregion

                on = true;

                Invalidate();

                owner.OnPianoKeyDown(new PianoKeyEventArgs(noteID));
            }

            public void ReleasePianoKey()
            {
                #region Guard

                if(!on)
                {
                    return;
                }

                #endregion

                on = false;

                Invalidate();

                owner.OnPianoKeyUp(new PianoKeyEventArgs(noteID));
            }

            protected override void Dispose(bool disposing)
            {
                if(disposing)
                {
                    onBrush.Dispose();
                    offBrush.Dispose();
                }

                base.Dispose(disposing);
            }

            protected override void OnMouseEnter(EventArgs e)
            {
                if(Control.MouseButtons == MouseButtons.Left)
                {
                    PressPianoKey();
                }

                base.OnMouseEnter(e);
            }

            protected override void OnMouseLeave(EventArgs e)
            {
                if(on)
                {
                    ReleasePianoKey();
                }

                base.OnMouseLeave(e);
            }

            protected override void OnMouseDown(MouseEventArgs e)
            {
                PressPianoKey();

                if(!owner.Focused)
                {
                    owner.Focus();
                }

                base.OnMouseDown(e);
            }

            protected override void OnMouseUp(MouseEventArgs e)
            {
                ReleasePianoKey();

                base.OnMouseUp(e);
            }

            protected override void OnMouseMove(MouseEventArgs e)
            {
                if(e.X < 0 || e.X > Width || e.Y < 0 || e.Y > Height)
                {
                    Capture = false;
                }

                base.OnMouseMove(e);
            }

            protected override void OnPaint(PaintEventArgs e)
            {
                if(on)
                {
                    e.Graphics.FillRectangle(onBrush, 0, 0, Size.Width, Size.Height);
                }
                else
                {
                    e.Graphics.FillRectangle(offBrush, 0, 0, Size.Width, Size.Height);
                }

                e.Graphics.DrawRectangle(Pens.Black, 0, 0, Size.Width - 1, Size.Height - 1);

                base.OnPaint(e);
            }

            public Color NoteOnColor
            {
                get
                {
                    return onBrush.Color;
                }
                set
                {
                    onBrush.Color = value;

                    if(on)
                    {
                        Invalidate();
                    }
                }
            }

            public Color NoteOffColor
            {
                get
                {
                    return offBrush.Color;
                }
                set
                {
                    offBrush.Color = value;

                    if(!on)
                    {
                        Invalidate();
                    }
                }
            }

            public int NoteID
            {
                get
                {
                    return noteID;
                }
                set
                {
                    #region Require

                    if(value < 0 || value > ShortMessage.DataMaxValue)
                    {
                        throw new ArgumentOutOfRangeException("NoteID", noteID,
                            "Note ID out of range.");
                    }

                    #endregion

                    noteID = value;
                }
            }

            public bool IsPianoKeyPressed
            {
                get
                {
                    return on;
                }
            }
        }
    }
}


text:
import {Create} from './templates/Create.js';
import {TargetBindUnbindBoundGetter} from './templates/TargetBindUnbindBoundGetter.js';
import {ParameterAccess} from './prototypeExtensions/ParameterAccess.js';
import {ExtendedMath} from '../../ExtendedMath.js';

const TYPE_NAME = 'Texture',
	RESOURCE_REFERENCE_NAME = `_gl${TYPE_NAME}`,
	TARGET_REFERENCE_NAME = 'glTarget',
	GET_PARAMETER_METHOD_NAME = 'getTexParameter',
	/*Install float getters/setters*/
	SUPER_CLASS = ParameterAccess(
		/*Install int getters/setters*/
		ParameterAccess(
			TargetBindUnbindBoundGetter(
				Create(
					TYPE_NAME,
					RESOURCE_REFERENCE_NAME
				),
				TARGET_REFERENCE_NAME
			),
			TARGET_REFERENCE_NAME,
			GET_PARAMETER_METHOD_NAME,
			'texParameteri',
			{
				pMinFilter: 0x2801,
				pMagFilter: 0x2800,
				pWrapS: 0x2802,
				pWrapT: 0x2803,
				pWrapR: 0x8072,
				pBaseLevel: 0x813C,
				pMaxLevel: 0x813D,
				pCompareMode: 0x884C,
				pCompareFunc: 0x884D
			}
		),
		TARGET_REFERENCE_NAME,
		GET_PARAMETER_METHOD_NAME,
		'texParameterf',
		{
			pMinLod: 0x813A,
			pMaxLod: 0x813B
		}
	),
	ALLOCATION_INFO_DEFAULTS = {
		width: 0,
		height: 0,
		levels: 0,
		glInternalFormat: 0
	};

class Texture extends SUPER_CLASS {
	constructor(gl = null, glTarget = 0) {
		super(gl, glTarget);
		this._allocated = false;
		this._allocationInfo = {
			width: 0,
			height: 0,
			levels: 0,
			glInternalFormat: 0
		};
		this._manualLevels = [];
	}

	hasLevel(level) {
		return this._allocated ? ExtendedMath.between(level, 0, this._allocationInfo.levels) : this._manualLevels.indexOf(level) !== -1;
	}

	getManualLevels(destinationArray = []) {
		const MANUAL_LEVELS = this._manualLevels;
		let i = 0, len = MANUAL_LEVELS.length;
		for(; i < len; ++i) {
			destinationArray[i] = MANUAL_LEVELS[i];
		}
		return destinationArray;
	}

	get allocated() {
		return this._allocated;
	}

	get width() {
		return this._allocationInfo.width;
	}

	get height() {
		return this._allocationInfo.height;
	}

	get levels() {
		return this._allocationInfo.levels;
	}

	get glInternalFormat() {
		return this._allocationInfo.glInternalFormat;
	}

	destroy() {
		super.destroy();
		Object.assign(this._allocationInfo, ALLOCATION_INFO_DEFAULTS);
		this._manualLevels.length = 0;
		this._allocated = false;
	}

	allocate(width, height, levels, glInternalFormat) {
		const ALLOCATION_INFO = this._allocationInfo;
		if(this._allocated) throw new Error(`${this.TYPE_NAME} must be destroyed before allocated again !`);

		this.gl.texStorage2D(
			this[this.TARGET_REFERENCE_NAME],
			ALLOCATION_INFO.levels = levels,
			ALLOCATION_INFO.glInternalFormat = glInternalFormat,
			ALLOCATION_INFO.width = width,
			ALLOCATION_INFO.height = height
		);

		this._allocated = true;

		return this;
	}

	generateMipmap() {
		this.gl.generateMipmap(this[this.TARGET_REFERENCE_NAME]);
		return this;
	}

	modifyLevel(level, xOffset, yOffset, width, height, glFormat, glType, dataOrOffset) {
		this.gl.texSubImage2D(
			this[this.TARGET_REFERENCE_NAME],
			level,
			xOffset,
			yOffset,
			width,
			height,
			glFormat,
			glType,
			dataOrOffset
		);

		return this;
	}

	uploadLevel(level, width, height, glInternalFormat, glFormat, glType, dataOrOffset) {
		const MANUAL_LEVELS = this._manualLevels;
		this.gl.texImage2D(
			this[this.TARGET_REFERENCE_NAME],
			level,
			glInternalFormat,
			width,
			height,
			0,
			glFormat,
			glType,
			dataOrOffset
		);

		if(MANUAL_LEVELS.indexOf(level) === -1) {
			MANUAL_LEVELS.push(level);
		}

		return this;
	}
}

export {Texture};


text:
package io.crate.operation.collect.sources;

import io.crate.operation.collect.CrateCollector;
import io.crate.operation.collect.JobCollectContext;
import io.crate.operation.projectors.RowReceiver;
import io.crate.planner.node.dql.CollectPhase;

import java.util.Collection;

public interface CollectSource {

    Collection<CrateCollector> getCollectors(CollectPhase collectPhase, RowReceiver downstream, JobCollectContext jobCollectContext);
}


text:
<Alloy>
	<Window id="home" class="container">
		<View id="welcome">
			<Label>Welcome to Emoticaptcha!</Label>
			<Button id="startSearch" onClick="startClick" />
		</View>
		<ImageView image="/images/emoticaptcha_logo.png" bottom="20dp">
		</ImageView>
	</Window>
</Alloy>


text:
<?php

namespace AcmePhp\Cli\Monolog;

use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;
use Symfony\Component\Console\Output\Output;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Writes logs to the console output depending on its verbosity setting.
 *
 * Extracted from Symfony Monolog bridge.
 *
 * @link https://github.com/symfony/monolog-bridge/edit/master/Handler/ConsoleHandler.php
 *
 * @author Tobias Schultze <http://tobion.de>
 */
class ConsoleHandler extends AbstractProcessingHandler
{
    /**
     * @var OutputInterface|null
     */
    private $output;

    /**
     * @var array
     */
    private $verbosityLevelMap = [
        OutputInterface::VERBOSITY_QUIET        => Logger::ERROR,
        OutputInterface::VERBOSITY_NORMAL       => Logger::INFO,
        OutputInterface::VERBOSITY_VERBOSE      => Logger::INFO,
        OutputInterface::VERBOSITY_VERY_VERBOSE => Logger::INFO,
        OutputInterface::VERBOSITY_DEBUG        => Logger::DEBUG,
    ];

    /**
     * Constructor.
     *
     * @param OutputInterface|null $output            The console output to use (the handler remains disabled when passing null
     *                                                until the output is set, e.g. by using console events)
     * @param bool                 $bubble            Whether the messages that are handled can bubble up the stack
     * @param array                $verbosityLevelMap Array that maps the OutputInterface verbosity to a minimum logging
     *                                                level (leave empty to use the default mapping)
     */
    public function __construct(OutputInterface $output = null, $bubble = true, array $verbosityLevelMap = [])
    {
        parent::__construct(Logger::DEBUG, $bubble);
        $this->output = $output;

        if ($verbosityLevelMap) {
            $this->verbosityLevelMap = $verbosityLevelMap;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function isHandling(array $record)
    {
        return $this->updateLevel() && parent::isHandling($record);
    }

    /**
     * {@inheritdoc}
     */
    public function handle(array $record)
    {
        // we have to update the logging level each time because the verbosity of the
        // console output might have changed in the meantime (it is not immutable)
        return $this->updateLevel() && parent::handle($record);
    }

    /**
     * Sets the console output to use for printing logs.
     *
     * @param OutputInterface $output The console output to use
     */
    public function setOutput(OutputInterface $output)
    {
        $this->output = $output;
    }

    /**
     * Disables the output.
     */
    public function close()
    {
        $this->output = null;

        parent::close();
    }

    /**
     * {@inheritdoc}
     */
    protected function write(array $record)
    {
        $this->output->write((string) $record['formatted']);
    }

    /**
     * {@inheritdoc}
     */
    protected function getDefaultFormatter()
    {
        $formatter = new ConsoleFormatter();
        $formatter->allowInlineLineBreaks();

        return $formatter;
    }

    /**
     * Updates the logging level based on the verbosity setting of the console output.
     *
     * @return bool Whether the handler is enabled and verbosity is not set to quiet
     */
    private function updateLevel()
    {
        if (null === $this->output) {
            return false;
        }

        $verbosity = $this->output->getVerbosity();
        if (isset($this->verbosityLevelMap[$verbosity])) {
            $this->setLevel($this->verbosityLevelMap[$verbosity]);
        } else {
            $this->setLevel(Logger::DEBUG);
        }

        return true;
    }
}


text:
USE openPDC
GO