text:
package springfox.documentation.swagger.readers.operation;

import com.fasterxml.classmate.ResolvedType;
import com.fasterxml.classmate.TypeResolver;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.ExampleBuilder;
import springfox.documentation.schema.Example;
import springfox.documentation.schema.property.ModelSpecificationFactory;
import springfox.documentation.service.Header;
import springfox.documentation.service.Response;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.contexts.ModelContext;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import springfox.documentation.spi.service.contexts.ResponseContext;
import springfox.documentation.spring.web.plugins.DocumentationPluginsManager;
import springfox.documentation.swagger.common.SwaggerPluginSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.Optional.*;
import static org.springframework.util.StringUtils.*;
import static springfox.documentation.swagger.annotations.Annotations.*;
import static springfox.documentation.swagger.readers.operation.ResponseHeaders.*;

@Component
//@Conditional(OasPresentCondition.class)
@Order(SwaggerPluginSupport.OAS_PLUGIN_ORDER)
public class OpenApiResponseReader implements OperationBuilderPlugin {

  private final TypeResolver typeResolver;
  private final ModelSpecificationFactory modelSpecifications;
  private final DocumentationPluginsManager documentationPlugins;

  @Autowired
  public OpenApiResponseReader(
      TypeResolver typeResolver,
      ModelSpecificationFactory modelSpecifications,
      DocumentationPluginsManager documentationPlugins) {
    this.typeResolver = typeResolver;
    this.modelSpecifications = modelSpecifications;
    this.documentationPlugins = documentationPlugins;
  }

  @Override
  public void apply(OperationContext context) {
    context.operationBuilder().responses(read(context));
  }

  @Override
  public boolean supports(DocumentationType delimiter) {
    return SwaggerPluginSupport.pluginDoesApply(delimiter);
  }

  @SuppressWarnings({
      "CyclomaticComplexity",
      "NPathComplexity"})
  protected Set<Response> read(OperationContext context) {
    ResolvedType defaultResponse = context.getReturnType();
    Optional<Operation> operationAnnotation = context.findAnnotation(Operation.class);
    Optional<ApiResponses> responsesAnnotation = context.findAnnotation(ApiResponses.class);
    Optional<ApiResponse> responseAnnotation = context.findAnnotation(ApiResponse.class);
    List<ApiResponse> allApiResponses
        = Stream.concat(
        operationAnnotation.map(fromOperationAnnotation())
            .orElse(new ArrayList<>()).stream(),
        responsesAnnotation.map(fromApiResponsesAnnotation())
            .orElse(new ArrayList<>()).stream())
        .collect(Collectors.toList());
    responseAnnotation.ifPresent(allApiResponses::add);

    Set<Response> responses = new HashSet<>();
    for (ApiResponse apiResponse : allApiResponses) {
      Map<String, Header> headers = new HashMap<>();
      List<Example> examples = new ArrayList<>();
      Optional<ResolvedType> type;
      ResponseContext responseContext = new ResponseContext(
          context.getDocumentationContext(),
          context);
      for (Content each : apiResponse.content()) {
        type = resolvedType(each.schema());
        if (isSuccessful(apiResponse.responseCode())) {
          type = type.map(Optional::of).orElse(Optional.of(defaultResponse));
        }
        if (!type.isPresent()) {
          continue;
        }
        ModelContext modelContext = context.operationModelsBuilder()
            .addReturn(
                typeResolver.resolve(each.schema().implementation()),
                Optional.empty());
        for (ExampleObject eachExample : each.examples()) {
          if (!isEmpty(eachExample.value())) {
            examples.add(new ExampleBuilder()
                .mediaType(each.mediaType())
                .description(eachExample.description())
                .summary(eachExample.summary())
                .id(eachExample.name())
                .value(eachExample.value()).build());
          }
        }
        headers.putAll(headers(apiResponse.headers()));

        type.ifPresent(t -> responseContext.responseBuilder()
            .representation(each.mediaType().isEmpty() ? MediaType.ALL : MediaType.valueOf(each.mediaType()))
            .apply(r -> r.model(
                m -> m.copyOf(modelSpecifications.create(modelContext, t)))));
      }
      responseContext.responseBuilder()
          .examples(examples)
          .description(apiResponse.description())
          .headers(headers.values())
          .code(apiResponse.responseCode());
      responses.add(documentationPlugins.response(responseContext));
    }
    return responses;
  }

  static boolean isSuccessful(String code) {
    try {
      return HttpStatus.Series.SUCCESSFUL.equals(HttpStatus.Series.valueOf(code));
    } catch (Exception ignored) {
      return false;
    }
  }

  private Optional<ResolvedType> resolvedType(
      Schema apiResponse) {
    return ofNullable(resolvedTypeFromSchema(
        typeResolver,
        null).apply(apiResponse));
  }
}


text:
package org.olat.resource.accesscontrol.manager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.persistence.TemporalType;
import javax.persistence.TypedQuery;

import org.olat.core.commons.persistence.DB;
import org.olat.core.id.Identity;
import org.olat.core.manager.BasicManager;
import org.olat.resource.OLATResource;
import org.olat.resource.accesscontrol.model.Offer;
import org.olat.resource.accesscontrol.model.OfferAccess;
import org.olat.resource.accesscontrol.model.Order;
import org.olat.resource.accesscontrol.model.OrderImpl;
import org.olat.resource.accesscontrol.model.OrderLine;
import org.olat.resource.accesscontrol.model.OrderLineImpl;
import org.olat.resource.accesscontrol.model.OrderPart;
import org.olat.resource.accesscontrol.model.OrderPartImpl;
import org.olat.resource.accesscontrol.model.OrderStatus;

/**
 *
 * Description:

 * manager for the order. Orders are a part of the confirmation of an access
 * to a resource. The second part is the transaction.
 *
 *

 * Initial Date:  19 avr. 2011

 * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
 */
public class ACOrderManagerImpl extends BasicManager implements ACOrderManager {

	private DB dbInstance;

	private ACOrderManagerImpl() {
		//
	}

	/**
	 * [used by Spring]
	 * @param dbInstance
	 */
	public void setDbInstance(DB dbInstance) {
		this.dbInstance = dbInstance;
	}

	@Override
	public OrderImpl createOrder(Identity delivery) {
		OrderImpl order = new OrderImpl();
		order.setDelivery(delivery);
		order.setOrderStatus(OrderStatus.NEW);
		dbInstance.saveObject(order);
		return order;
	}

	@Override
	public OrderPart addOrderPart(Order order) {
		OrderPartImpl orderPart = new OrderPartImpl();
		dbInstance.saveObject(orderPart);
		order.getParts().add(orderPart);
		return orderPart;
	}

	@Override
	public OrderLine addOrderLine(OrderPart part, Offer offer) {
		OrderLineImpl line = new OrderLineImpl();
		line.setOffer(offer);
		line.setUnitPrice(offer.getPrice().clone());
		line.setTotal(line.getUnitPrice().clone());
		dbInstance.saveObject(line);
		part.getOrderLines().add(line);
		return line;
	}

	@Override
	public Order save(Order order) {
		if(order.getKey() == null) {
			dbInstance.saveObject(order);
		} else {
			dbInstance.updateObject(order);
		}
		return order;
	}

	@Override
	public Order save(Order order, OrderStatus status) {
		((OrderImpl)order).setOrderStatus(status);
		if(order.getKey() == null) {
			dbInstance.saveObject(order);
		} else {
			dbInstance.updateObject(order);
		}
		return order;
	}

	@Override
	public Order saveOneClick(Identity delivery, OfferAccess link) {
		return saveOneClick(delivery, link, OrderStatus.PAYED);
	}

	@Override
	public Order saveOneClick(Identity delivery, OfferAccess link, OrderStatus status) {
		OrderImpl order = createOrder(delivery);
		order.setOrderStatus(status);
		if(link.getOffer().getPrice().isEmpty()) {
			order.setCurrencyCode("CHF");
		} else {
			order.setCurrencyCode(link.getOffer().getPrice().getCurrencyCode());
		}
		OrderPart part = addOrderPart(order);
		addOrderLine(part, link.getOffer());
		order.recalculate();

		dbInstance.updateObject(order);
		dbInstance.updateObject(part);

		return order;
	}

	@Override
	public List<Order> findOrdersByDelivery(Identity delivery, OrderStatus... status) {
		StringBuilder sb = new StringBuilder();
		sb.append("select order from ").append(OrderImpl.class.getName()).append(" order")
			.append(" where order.delivery.key=:deliveryKey");
		if(status != null && status.length > 0) {
			sb.append(" and order.orderStatusStr in (:status)");
		}

		TypedQuery<Order> query = dbInstance.getCurrentEntityManager()
				.createQuery(sb.toString(), Order.class)
				.setParameter("deliveryKey", delivery.getKey());
		if(status != null && status.length > 0) {
			List<String> statusStr = new ArrayList<String>();
			for(OrderStatus s:status) {
				statusStr.add(s.name());
			}
			query.setParameter("status", statusStr);
		}

		List<Order> orders = query.getResultList();
		return orders;
	}

	@Override
	public List<Order> findOrdersByResource(OLATResource resource, OrderStatus... status) {
		StringBuilder sb = new StringBuilder();
		sb.append("select distinct(o) from ").append(OrderImpl.class.getName()).append(" o")
			.append(" inner join o.parts orderPart ")
			.append(" inner join orderPart.orderLines orderLine ")
			.append(" inner join orderLine.offer offer ")
			.append(" where offer.resource.key=:resourceKey");
		if(status != null && status.length > 0) {
			sb.append(" and o.orderStatusStr in (:status)");
		}

		TypedQuery<Order> query = dbInstance.getCurrentEntityManager()
				.createQuery(sb.toString(), Order.class)
				.setParameter("resourceKey", resource.getKey());
		if(status != null && status.length > 0) {
			List<String> statusStr = new ArrayList<String>();
			for(OrderStatus s:status) {
				statusStr.add(s.name());
			}
			query.setParameter("status", statusStr);
		}

		List<Order> orders = query.getResultList();
		return orders;
	}

	@Override
	public List<Order> findOrders(OLATResource resource, Identity delivery, Long orderNr, Date from, Date to, OrderStatus... status) {
		StringBuilder sb = new StringBuilder();
		sb.append("select distinct(o) from ").append(OrderImpl.class.getName()).append(" o");
		if(resource != null) {
			sb.append(" inner join o.parts orderPart ")
				.append(" inner join orderPart.orderLines orderLine ")
				.append(" inner join orderLine.offer offer");
		}

		boolean where = false;
		if(resource != null) {
			where = appendAnd(sb, where);
			sb.append("offer.resource.key=:resourceKey");
		}
		if(delivery != null) {
			where = appendAnd(sb, where);
			sb.append("order.delivery.key=:deliveryKey");
		}
		if(status != null && status.length > 0) {
			where = appendAnd(sb, where);
			sb.append("o.orderStatusStr in (:status)");
		}
		if(from != null) {
			where = appendAnd(sb, where);
			sb.append("o.creationDate >=:from");
		}
		if(to != null) {
			where = appendAnd(sb, where);
			sb.append("o.creationDate <=:to");
		}
		if(orderNr != null) {
			where = appendAnd(sb, where);
			sb.append("o.key=:orderNr");
		}

		TypedQuery<Order> query = dbInstance.getCurrentEntityManager().createQuery(sb.toString(), Order.class);
		if(status != null && status.length > 0) {
			List<String> statusStr = new ArrayList<String>();
			for(OrderStatus s:status) {
				statusStr.add(s.name());
			}
			query.setParameter("status", statusStr);
		}
		if(resource != null) {
			query.setParameter("resourceKey", resource.getKey());
		}
		if(delivery != null) {
			query.setParameter("deliveryKey", delivery.getKey());
		}
		if(orderNr != null) {
			query.setParameter("orderNr", orderNr);
		}
		if(from != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(from);
			cal.set(Calendar.HOUR, 0);
			cal.set(Calendar.MINUTE, 0);
			cal.set(Calendar.SECOND, 0);
			cal.set(Calendar.MILLISECOND, 0);
			query.setParameter("from", cal.getTime(), TemporalType.TIMESTAMP);
		}
		if(to != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(to);
			cal.set(Calendar.HOUR, 23);
			cal.set(Calendar.MINUTE, 59);
			cal.set(Calendar.SECOND, 59);
			cal.set(Calendar.MILLISECOND, 0);
			query.setParameter("to", cal.getTime(), TemporalType.TIMESTAMP);
		}

		List<Order> orders = query.getResultList();
		return orders;
	}

	private boolean appendAnd(StringBuilder sb, boolean where) {
		if(where) sb.append(" and ");
		else sb.append(" where ");
		return true;
	}

	@Override
	public Order loadOrderByKey(Long orderKey) {
		StringBuilder sb = new StringBuilder();
		sb.append("select order from ").append(OrderImpl.class.getName()).append(" order")
			.append(" where order.key=:orderKey");

		List<Order> orders = dbInstance.getCurrentEntityManager()
				.createQuery(sb.toString(), Order.class)
				.setParameter("orderKey", orderKey)
				.getResultList();
		if(orders.isEmpty()) return null;
		return orders.get(0);
	}

	@Override
	public Order loadOrderByNr(String orderNr) {
		Long orderKey = new Long(orderNr);
		return loadOrderByKey(orderKey);
	}
}

redpajama_set_name: RedPajamaGithub


text:
//
//  ViewController.m
//  PayeezyClient
//
//  Created by First Data Corporation on 8/28/14.
//  Copyright (c) 2014 First Data Corporation. All rights reserved.
//

#import "ViewController.h"
#import "PayeezySDK.h"

// Credentials for shared test account in CERT environment
// Does NOT process actual transactions
// cert credentials
#define KApiKey     @"y6pWAJNyJyjGv66IsVuWnklkKUPFbb0a"
#define KApiSecret  @"86fbae7030253af3cd15faef2a1f4b67353e41fb6799f576b5093ae52901e6f786fbae7030253af3cd15faef2a1f4b67353e41fb6799f576b5093ae52901e6f7"
#define KToken      @"fdoa-a480ce8951daa73262734cf102641994c1e55e7cdf4c02b6"

#define KURL        @"https://api-cert.payeezy.com/v1/transactions"

@implementation ViewController

/*!
 * authorize Capture Visa Transaction
 * \param id
 * \returns IBAction
 */
- (IBAction)authorizeCaptureVisaTransactionCVV:(id)sender {

    NSString* cardHolderName = _card_holder_name.text;
    NSDecimalNumber* valueEntered = [NSDecimalNumber decimalNumberWithString:_amountEntered.text];
    NSString* cardNumber  = _card_number.text;
    NSString* cardSecurityCode = _card_security_code.text;

    if (![valueEntered isEqualToNumber:[NSDecimalNumber notANumber]]) {

        NSString *amount = [[NSString stringWithFormat:@"%@",valueEntered] stringByReplacingOccurrencesOfString:@"." withString:@""];

        // Test credit card inf
        NSDictionary* credit_card = @{
                                      @"type":@"visa",
                                      @"cardholder_name":cardHolderName,
                                      @"card_number":cardNumber,
                                      @"exp_date":@"0450",
                                      @"cvv":cardSecurityCode
                                      };
        PayeezySDK* myClient = [[PayeezySDK alloc]initWithApiKey:KApiKey apiSecret:KApiSecret merchantToken:KToken url:KURL];

        //myClient.url = KURL;

        [myClient submitAuthorizeTransactionWithCreditCardDetails:credit_card[@"type"] cardHolderName:credit_card[@"cardholder_name"] cardNumber:credit_card[@"card_number"] cardExpirymMonthAndYear:credit_card[@"exp_date"] cardCVV:credit_card[@"cvv"] currencyCode:@"USD" totalAmount:amount merchantRefForProcessing:@"abc1412096293369"

                                                       completion:^(NSDictionary *dict, NSError *error) {

                                                           NSString *authStatusMessage = nil;

                                                           if (error == nil)
                                                           {
                                                               authStatusMessage = [NSString stringWithFormat:@"Transaction Successful\rType:%@\rTransaction ID:%@\rTransaction Tag:%@\rCorrelation Id:%@\rBank Response Code:%@",
                                                                                [dict objectForKey:@"transaction_type"],
                                                                                [dict objectForKey:@"transaction_id"],
                                                                                [dict objectForKey:@"transaction_tag"],
                                                                                [dict objectForKey:@"correlation_id"],
                                                                                [dict objectForKey:@"bank_resp_code"]];
                                                               [self voidRefundCaptureTransaction:@"abc1412096293369" :[dict objectForKey:@"transaction_tag"] :@"capture" :[dict objectForKey:@"transaction_id"] :amount];

                                                           }
                                                           else
                                                           {
                                                               authStatusMessage = [NSString stringWithFormat:@"Error was encountered processing transaction: %@", error.debugDescription];
                                                           }

                                                           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"First Data Payment Authorization"
                                                                                message:authStatusMessage delegate:self
                                                                                cancelButtonTitle:@"Dismiss"
                                                                                otherButtonTitles:nil];
                                                           [alert show];
                                                       }];
    }
}

/*!
 *
 * \param id
 * \returns IBAction
 */

- (IBAction)purchaseVoidTransaction:(id)sender {

    NSDecimalNumber* valueEntered = [NSDecimalNumber decimalNumberWithString:_amountEntered.text];

    if (![valueEntered isEqualToNumber:[NSDecimalNumber notANumber]]) {

        NSString *amount = [[NSString stringWithFormat:@"%@",valueEntered] stringByReplacingOccurrencesOfString:@"." withString:@""];

        // Test credit card info
        NSDictionary* credit_card = @{
                                      @"type":@"visa",
                                      @"cardholder_name":@"Eck Test 3",
                                      @"card_number":@"4012000033330026",
                                      @"exp_date":@"0416",
                                      @"cvv":@"123"
                                      };
        PayeezySDK* myClient = [[PayeezySDK alloc]initWithApiKey:KApiKey apiSecret:KApiSecret merchantToken:KToken url:KURL];

        //myClient.url = KURL;

        [myClient submitAuthorizeTransactionWithCreditCardDetails:credit_card[@"type"] cardHolderName:credit_card[@"cardholder_name"] cardNumber:credit_card[@"card_number"] cardExpirymMonthAndYear:credit_card[@"exp_date"] cardCVV:credit_card[@"cvv"] currencyCode:@"USD" totalAmount:amount merchantRefForProcessing:@"Test Authorization Transaction - PayeezyClient"

                                                       completion:^(NSDictionary *dict, NSError *error) {

                                                           NSString *authStatusMessage = nil;

                                                           if (error == nil)
                                                           {
                                                               authStatusMessage = [NSString stringWithFormat:@"Transaction Successful\rType:%@\rTransaction ID:%@\rTransaction Tag:%@\rCorrelation Id:%@\rBank Response Code:%@",
                                                                                [dict objectForKey:@"transaction_type"],
                                                                                [dict objectForKey:@"transaction_id"],
                                                                                [dict objectForKey:@"transaction_tag"],
                                                                                [dict objectForKey:@"correlation_id"],
                                                                                [dict objectForKey:@"bank_resp_code"]];                                                           }
                                                           else
                                                           {
                                                               authStatusMessage = [NSString stringWithFormat:@"Error was encountered processing transaction: %@", error.debugDescription];
                                                           }

                                                           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"First Data Payment Authorization"
                                                                                message:authStatusMessage delegate:self
                                                                                cancelButtonTitle:@"Dismiss"
                                                                                otherButtonTitles:nil];
                                                           [alert show];
                                                       }];
    }
}

/*!
 *
 * \param id
 * \returns IBAction
 */

- (IBAction)purchaseRefundTransaction:(id)sender {

    NSDecimalNumber* valueEntered = [NSDecimalNumber decimalNumberWithString:_amountEntered.text];

    if (![valueEntered isEqualToNumber:[NSDecimalNumber notANumber]]) {

        NSString *amount = [[NSString stringWithFormat:@"%@",valueEntered] stringByReplacingOccurrencesOfString:@"." withString:@""];

        // Test credit card info
        NSDictionary* credit_card = @{
                                      @"type":@"visa",
                                      @"cardholder_name":@"Eck Test 3",
                                      @"card_number":@"4012000033330026",
                                      @"exp_date":@"0416",
                                      @"cvv":@"123"
                                      };
        PayeezySDK* myClient = [[PayeezySDK alloc]initWithApiKey:KApiKey apiSecret:KApiSecret merchantToken:KToken url:KURL];

        //myClient.url = KURL;

        [myClient submitAuthorizeTransactionWithCreditCardDetails:credit_card[@"type"] cardHolderName:credit_card[@"cardholder_name"] cardNumber:credit_card[@"card_number"] cardExpirymMonthAndYear:credit_card[@"exp_date"] cardCVV:credit_card[@"cvv"] currencyCode:@"USD" totalAmount:amount merchantRefForProcessing:@"Test Authorization Transaction - PayeezyClient"

                                                       completion:^(NSDictionary *dict, NSError *error) {

                                                           NSString *authStatusMessage = nil;

                                                           if (error == nil)
                                                           {
                                                               authStatusMessage = [NSString stringWithFormat:@"Transaction Successful\rType:%@\rTransaction ID:%@\rTransaction Tag:%@\rCorrelation Id:%@\rBank Response Code:%@",
                                                                                [dict objectForKey:@"transaction_type"],
                                                                                [dict objectForKey:@"transaction_id"],
                                                                                [dict objectForKey:@"transaction_tag"],
                                                                                [dict objectForKey:@"correlation_id"],
                                                                                [dict objectForKey:@"bank_resp_code"]];
                                                           }
                                                           else
                                                           {
                                                               authStatusMessage = [NSString stringWithFormat:@"Error was encountered processing transaction: %@", error.debugDescription];
                                                           }

                                                           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"First Data Payment Authorization"
                                                                                message:authStatusMessage delegate:self
                                                                                cancelButtonTitle:@"Dismiss"
                                                                                otherButtonTitles:nil];
                                                           [alert show];
                                                       }];
    }
}

/*!
 * voidTransaction
 * \param
 * \returns
 */
- (IBAction)voidRefundCaptureTransaction:(NSString *)merchant_ref :(NSString *)transaction_tag  :(NSString *)transaction_type   :(NSString *)transaction_id :(NSString *)totalamount  {

    NSDecimalNumber* valueEntered = [NSDecimalNumber decimalNumberWithString:_amountEntered.text];

    if (![valueEntered isEqualToNumber:[NSDecimalNumber notANumber]]) {

        //   NSString *amount = [[NSString stringWithFormat:@"%@",valueEntered] stringByReplacingOccurrencesOfString:@"." withString:@""];

        // Test credit card info
        NSDictionary* void_transaction = @{
                                           @"merchant_ref": merchant_ref,
                                           @"transaction_tag": transaction_tag,
                                           @"transaction_type": transaction_type,
                                           @"transaction_id": transaction_id,
                                           @"method": @"credit_card",
                                           @"amount": totalamount,
                                           @"currency_code": @"USD"
                                           };

        NSString *vcrURL = [NSString stringWithFormat: @"%@/%@", KURL, transaction_id];

        PayeezySDK* myClient = [[PayeezySDK alloc]initWithApiKey:KApiKey apiSecret:KApiSecret merchantToken:KToken url:vcrURL];

        [myClient submitVoidCaptureRefundTransactionWithCreditCardDetails:void_transaction[@"merchant_ref"] transactiontag:void_transaction[@"transaction_tag"] transactionType:void_transaction[@"transaction_type"] transactionId:void_transaction[@"transaction_id"] paymentMethodType:void_transaction[@"method"] totalAmount:void_transaction[@"amount"] currencyCode:@"USD" completion:^(NSDictionary *dict, NSError *error) {

            NSString *authStatusMessage = nil;

            if (error == nil)
            {
                authStatusMessage = [NSString stringWithFormat:@"Transaction Successful\rType:%@\rTransaction ID:%@\rTransaction Tag:%@",
                                     [dict objectForKey:@"transaction_type"],
                                     [dict objectForKey:@"transaction_id"],
                                     [dict objectForKey:@"transaction_tag"]];
            }
            else
            {
                authStatusMessage = [NSString stringWithFormat:@"Error was encountered processing transaction: %@", error.debugDescription];
            }

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"First Data Payment Authorization"
                                                            message:authStatusMessage delegate:self
                                                  cancelButtonTitle:@"Dismiss"
                                                  otherButtonTitles:nil];
            [alert show];
        }];
    }
}

/*!
 * voidTransaction
 * \param
 * \returns
 */

-(NSString*) splitTransaction:(NSString *)merchant_ref :(NSString *)transaction_tag  :(NSString *)transaction_type   :(NSString *)transaction_id :(NSString *)split_shipment :(NSString *)totalamount  {

    NSDecimalNumber* valueEntered = [NSDecimalNumber decimalNumberWithString:_amountEntered.text];

    if (![valueEntered isEqualToNumber:[NSDecimalNumber notANumber]]) {

        //   NSString *amount = [[NSString stringWithFormat:@"%@",valueEntered] stringByReplacingOccurrencesOfString:@"." withString:@""];

        // Test credit card info
        NSDictionary* split_transaction = @{
                                           @"merchant_ref": merchant_ref,
                                           @"transaction_tag": transaction_tag,
                                           @"transaction_type": transaction_type,
                                           @"split_shipment": split_shipment,
                                           @"method": @"credit_card",
                                           @"amount": totalamount,
                                           @"currency_code": @"USD"
                                           };

        NSString *vcrURL = [NSString stringWithFormat: @"%@/%@", KURL, transaction_id];
        //NSString *transtag = @"1849617";

        PayeezySDK* myClient = [[PayeezySDK alloc]initWithApiKey:KApiKey apiSecret:KApiSecret merchantToken:KToken url:vcrURL];

        [myClient submitSplitTransactionWithCreditCardDetails:split_transaction[@"merchant_ref"] transactiontag:split_transaction[@"transaction_tag"] transactionType:split_transaction[@"transaction_type"]  paymentMethodType:split_transaction[@"method"]  splitShipment:split_transaction[@"split_shipment"] totalAmount:totalamount currencyCode:@"USD" completion:^(NSDictionary *dict, NSError *error) {

            NSString *authStatusMessage = nil;

            if (error == nil)
            {
                authStatusMessage = [NSString stringWithFormat:@"Transaction Successful\rType:%@\rTransaction ID:%@\rTransaction Tag:%@\rCorrelation Id:%@\rBank Response Code:%@",
                                     [dict objectForKey:@"transaction_type"],
                                     [dict objectForKey:@"transaction_id"],
                                     [dict objectForKey:@"transaction_tag"],
                                     [dict objectForKey:@"correlation_id"],
                                     [dict objectForKey:@"bank_resp_code"]];

            }
            else
            {
                authStatusMessage = [NSString stringWithFormat:@"Error was encountered processing transaction: %@", error.debugDescription];
            }

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"First Data Payment Authorization"
                                                            message:authStatusMessage delegate:self
                                                  cancelButtonTitle:@"Dismiss"
                                                  otherButtonTitles:nil];
            [alert show];
        }];

    }
    return @"";
}

/*!
 *
 * \param
 * \returns
 */
// capture transactions
- (IBAction)captureTransaction:(id)sender{}

/*!
 *
 * \param
 * \returns
 */
// refund transctions
- (IBAction)refundTransaction:(id)sender{}
/*!
 *
 * \param
 * \returns
 */
- (void)viewDidLoad {
    [super viewDidLoad];
}

/*!
 *
 * \param
 * \returns
 */
- (void)viewDidAppear:(BOOL)animated{

    _amountEntered.text = @"";
}

/*!
 *
 * \param
 * \returns
 */
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end


text:
package org.apache.s2graph.core.mysqls

/**
 * Created by shon on 6/3/15.
 */

import org.apache.s2graph.core.GraphExceptions.MaxPropSizeReachedException
import org.apache.s2graph.core.{GraphExceptions, JSONParser}
import play.api.libs.json.Json
import scalikejdbc._

object LabelMeta extends Model[LabelMeta] with JSONParser {

  /** dummy sequences */

  val fromSeq = -4.toByte
  val toSeq = -5.toByte
  val lastOpSeq = -3.toByte
  val lastDeletedAt = -2.toByte
  val timeStampSeq = 0.toByte
  val countSeq = (Byte.MaxValue - 2).toByte
  val degreeSeq = (Byte.MaxValue - 1).toByte
  val maxValue = Byte.MaxValue
  val emptyValue = Byte.MaxValue

  /** reserved sequences */
  //  val deleted = LabelMeta(id = Some(lastDeletedAt), labelId = lastDeletedAt, name = "lastDeletedAt",
  //    seq = lastDeletedAt, defaultValue = "", dataType = "long")
  val from = LabelMeta(id = Some(fromSeq), labelId = fromSeq, name = "_from",
    seq = fromSeq, defaultValue = fromSeq.toString, dataType = "long")
  val to = LabelMeta(id = Some(toSeq), labelId = toSeq, name = "_to",
    seq = toSeq, defaultValue = toSeq.toString, dataType = "long")
  val timestamp = LabelMeta(id = Some(-1), labelId = -1, name = "_timestamp",
    seq = timeStampSeq, defaultValue = "0", dataType = "long")
  val degree = LabelMeta(id = Some(-1), labelId = -1, name = "_degree",
    seq = degreeSeq, defaultValue = "0", dataType = "long")
  val count = LabelMeta(id = Some(-1), labelId = -1, name = "_count",
    seq = countSeq, defaultValue = "-1", dataType = "long")

  // Each reserved column(_timestamp, timestamp) has same seq number, starts with '_' has high priority
  val reservedMetas = List(from, to, degree, timestamp, count).flatMap { lm => List(lm, lm.copy(name = lm.name.drop(1))) }.reverse
  val reservedMetasInner = List(from, to, degree, timestamp, count)

  def apply(rs: WrappedResultSet): LabelMeta = {
    LabelMeta(Some(rs.int("id")), rs.int("label_id"), rs.string("name"), rs.byte("seq"), rs.string("default_value"), rs.string("data_type").toLowerCase)
  }

  def isValidSeq(seq: Byte): Boolean = seq >= 0 && seq <= countSeq
  def isValidSeqForAdmin(seq: Byte): Boolean = seq > 0 && seq < countSeq

  def findById(id: Int)(implicit session: DBSession = AutoSession): LabelMeta = {
    val cacheKey = "id=" + id

    withCache(cacheKey) {
      sql"""select * from label_metas where id = ${id}""".map { rs => LabelMeta(rs) }.single.apply
    }.get
  }

  def findAllByLabelId(labelId: Int, useCache: Boolean = true)(implicit session: DBSession = AutoSession): List[LabelMeta] = {
    val cacheKey = "labelId=" + labelId
    lazy val labelMetas = sql"""select *
    		  						from label_metas
    		  						where label_id = ${labelId} order by seq ASC""".map(LabelMeta(_)).list.apply()

    if (useCache) withCaches(cacheKey)(labelMetas)
    else labelMetas
  }

  def findByName(labelId: Int, name: String, useCache: Boolean = true)(implicit session: DBSession = AutoSession): Option[LabelMeta] = {
    name match {
      case timestamp.name => Some(timestamp)
      case from.name => Some(from)
      case to.name => Some(to)
      case _ =>
        val cacheKey = "labelId=" + labelId + ":name=" + name
        lazy val labelMeta = sql"""
            select *
            from label_metas where label_id = ${labelId} and name = ${name}"""
          .map { rs => LabelMeta(rs) }.single.apply()

        if (useCache) withCache(cacheKey)(labelMeta)
        else labelMeta
    }
  }

  def insert(labelId: Int, name: String, defaultValue: String, dataType: String)(implicit session: DBSession = AutoSession) = {
    val ls = findAllByLabelId(labelId, useCache = false)
    val seq = ls.size + 1

    if (seq < maxValue) {
      sql"""insert into label_metas(label_id, name, seq, default_value, data_type)
    select ${labelId}, ${name}, ${seq}, ${defaultValue}, ${dataType}""".updateAndReturnGeneratedKey.apply()
    } else {
      throw MaxPropSizeReachedException("max property size reached")
    }
  }

  def findOrInsert(labelId: Int,
                   name: String,
                   defaultValue: String,
                   dataType: String)(implicit session: DBSession = AutoSession): LabelMeta = {

    findByName(labelId, name) match {
      case Some(c) => c
      case None =>
        insert(labelId, name, defaultValue, dataType)
        val cacheKey = "labelId=" + labelId + ":name=" + name
        val cacheKeys = "labelId=" + labelId
        expireCache(cacheKey)
        expireCaches(cacheKeys)
        findByName(labelId, name, useCache = false).get
    }
  }

  def delete(id: Int)(implicit session: DBSession = AutoSession) = {
    val labelMeta = findById(id)
    val (labelId, name) = (labelMeta.labelId, labelMeta.name)
    sql"""delete from label_metas where id = ${id}""".execute.apply()
    val cacheKeys = List(s"id=$id", s"labelId=$labelId", s"labelId=$labelId:name=$name")
    cacheKeys.foreach { key =>
      expireCache(key)
      expireCaches(key)
    }
  }

  def findAll()(implicit session: DBSession = AutoSession) = {
    val ls = sql"""select * from label_metas""".map { rs => LabelMeta(rs) }.list.apply
    putsToCache(ls.map { x =>
      val cacheKey = s"id=${x.id.get}"
      cacheKey -> x
    })
    putsToCache(ls.map { x =>
      val cacheKey = s"labelId=${x.labelId}:name=${x.name}"
      cacheKey -> x
    })
    putsToCache(ls.map { x =>
      val cacheKey = s"labelId=${x.labelId}:seq=${x.seq}"
      cacheKey -> x
    })

    putsToCaches(ls.groupBy(x => x.labelId).map { case (labelId, ls) =>
      val cacheKey = s"labelId=${labelId}"
      cacheKey -> ls
    }.toList)
  }
}

case class LabelMeta(id: Option[Int], labelId: Int, name: String, seq: Byte, defaultValue: String, dataType: String) extends JSONParser {
  lazy val toJson = Json.obj("name" -> name, "defaultValue" -> defaultValue, "dataType" -> dataType)
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
        "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

        <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"/>
        <title>Welcome to WSO2 Identity Server v3.2.0!</title>
        <link href="css/is-docs.css" rel="stylesheet"/>

[Download] | [
            Documentation Index
            ] | [Release Note]

Overview

This project uses
            JIRA
            a J2EE-based, issue tracking and project management application.

Issue Tracking

Issues, bugs, and feature requests should be submitted to following issue tracking
            systems for this project.

                https://www.wso2.org/jira/browse/IDENTITY

            https://wso2.org/jira/browse/CARBON


text:
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.graph.impl;

import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.util.Chunk;
import com.intellij.util.containers.Stack;
import com.intellij.util.graph.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;

/**
 * @author nik
 */
public class GraphAlgorithmsImpl extends GraphAlgorithms {
  @Override
  public <Node> List<Node> findShortestPath(@NotNull Graph<Node> graph, @NotNull Node start, @NotNull Node finish) {
    return findShortestPath((InboundSemiGraph<Node>)graph, start, finish);
  }

  @Nullable
  @Override
  public <Node> List<Node> findShortestPath(@NotNull InboundSemiGraph<Node> graph, @NotNull Node start, @NotNull Node finish) {
    return new ShortestPathFinder<>(graph).findPath(start, finish);
  }

  @NotNull
  @Override
  public <Node> List<List<Node>> findKShortestPaths(@NotNull Graph<Node> graph, @NotNull Node start, @NotNull Node finish, int k,
                                                    @NotNull ProgressIndicator progressIndicator) {
    return new KShortestPathsFinder<>(graph, start, finish, progressIndicator).findShortestPaths(k);
  }

  @NotNull
  @Override
  public <Node> Set<List<Node>> findCycles(@NotNull Graph<Node> graph, @NotNull Node node) {
    return new CycleFinder<>(graph).getNodeCycles(node);
  }

  @NotNull
  @Override
  public <Node> Graph<Node> invertEdgeDirections(@NotNull final Graph<Node> graph) {
    return new Graph<Node>() {
      @Override
      @NotNull
      public Collection<Node> getNodes() {
        return graph.getNodes();
      }

      @Override
      @NotNull
      public Iterator<Node> getIn(final Node n) {
        return graph.getOut(n);
      }

      @Override
      @NotNull
      public Iterator<Node> getOut(final Node n) {
        return graph.getIn(n);
      }

    };
  }

  @NotNull
  @Override
  public <Node> Graph<Chunk<Node>> computeSCCGraph(@NotNull final Graph<Node> graph) {
    final DFSTBuilder<Node> builder = new DFSTBuilder<>(graph);

    final Collection<Collection<Node>> components = builder.getComponents();
    final List<Chunk<Node>> chunks = new ArrayList<>(components.size());
    final Map<Node, Chunk<Node>> nodeToChunkMap = new LinkedHashMap<>();
    for (Collection<Node> component : components) {
      final Set<Node> chunkNodes = component.size() == 1
                                   ? Collections.singleton(component.iterator().next())
                                   : new LinkedHashSet<>(component);
      final Chunk<Node> chunk = new Chunk<>(chunkNodes);
      chunks.add(chunk);
      for (Node node : component) {
        nodeToChunkMap.put(node, chunk);
      }
    }

    return GraphGenerator.generate(CachingSemiGraph.cache(new InboundSemiGraph<Chunk<Node>>() {
      @NotNull
      @Override
      public Collection<Chunk<Node>> getNodes() {
        return chunks;
      }

      @NotNull
      @Override
      public Iterator<Chunk<Node>> getIn(Chunk<Node> chunk) {
        final Set<Node> chunkNodes = chunk.getNodes();
        final Set<Chunk<Node>> ins = new LinkedHashSet<>();
        for (final Node node : chunkNodes) {
          for (Iterator<Node> nodeIns = graph.getIn(node); nodeIns.hasNext(); ) {
            final Node in = nodeIns.next();
            if (!chunk.containsNode(in)) {
              ins.add(nodeToChunkMap.get(in));
            }
          }
        }
        return ins.iterator();
      }
    }));
  }

  @Override
  public <Node> void collectOutsRecursively(@NotNull Graph<Node> graph, Node start, Set<? super Node> set) {
    if (!set.add(start)) {
      return;
    }
    final Stack<Node> stack = new Stack<>();
    stack.push(start);
    while (!stack.empty()) {
      final Node currentNode = stack.pop();
      final Iterator<Node> successorIterator = graph.getOut(currentNode);
      while (successorIterator.hasNext()) {
        Node successor = successorIterator.next();
        if (set.add(successor)) {
          stack.push(successor);
        }
      }
    }
  }

  @NotNull
  @Override
  public <Node> Collection<Chunk<Node>> computeStronglyConnectedComponents(@NotNull Graph<Node> graph) {
    return computeSCCGraph(graph).getNodes();
  }

  @NotNull
  @Override
  public <Node> List<List<Node>> removePathsWithCycles(@NotNull List<? extends List<Node>> paths) {
    final List<List<Node>> result = new ArrayList<>();
    for (List<Node> path : paths) {
      if (!containsCycle(path)) {
        result.add(path);
      }
    }
    return result;
  }

  private static boolean containsCycle(List<?> path) {
    return new HashSet<Object>(path).size() != path.size();
  }
}


text:
require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/classes', __FILE__)
require File.expand_path('../shared/length', __FILE__)

describe "Hash#size" do
  it_behaves_like(:hash_length, :size)
end


text:
import logging

from django.core.urlresolvers import reverse

logger = logging.getLogger(__name__)

def resolve_list(item):
    return item[0] if is_single_element_list(item) else item

def is_single_element_list(item):
    return bool(isinstance(item, list)) and (len(item) == 1)

def is_unselected_list(answer):
    return len(answer) == 0

def is_empty_text_box(answer):
    return len(answer) == 1 and not answer[0]

def get_by_pk(items, pk):
    for item in items:
        if str(item.get('pk')) == str(resolve_list(pk)):
            return item
    else:
        return {}

class SerializedDataHelper(object):
    # TODO: move the zip functionality to PageForm or FormManager
    conditional_fields = [
        'extra_info',
        'extra_options',
    ]
    question_id_error_message = 'field_id={} not found in {}'
    choice_id_error_message = 'Choice(pk={}) not found in {}'
    choice_option_id_error_message = 'ChoiceOption(pk={}) not found in {}'
    not_answered_text = '[ Not Answered ]'

    @classmethod
    def get_zipped_data(cls, data={}, forms={}):
        self = cls()
        self.data = data
        self.zipped_data = []
        self._parse_forms(forms)
        return self.zipped_data

    def _parse_forms(self, forms):
        for form in forms:
            self._parse_questions(form)

    def _parse_questions(self, form):
        for question in form:
            answer = self._get_question_answer(question)
            self._parse_answers(question, answer)

    def _parse_answers(self, question, answer):
        if question.get('type') in ['Singlelinetext', 'Textarea']:
            self._append_text_answer(answer, question)
        else:
            self._append_list_answers(answer, question)

    def _get_question_answer(self, question):
        return self.data.get(question.get('field_id'), '')

    def _append_text_answer(self, answer, question):
        self._append_answer(question, [answer])

    def _append_list_answers(self, answers, question):
        if not isinstance(answers, list):
            answers = [answers]
        choice_list = [
            self._get_choice_text(answer, question)
            for answer in answers
        ]
        self._append_answer(question, choice_list)

    def _append_answer(self, question, answer):
        if is_empty_text_box(answer) or is_unselected_list(answer):
            answer = [self.not_answered_text]
        self.zipped_data.append({
            question['question_text']: answer,
        })

    def _get_choice_text(self, answer, question):
        choice = self._get_choice(question, answer)
        choice_text = choice.get('text')
        return choice_text

    def _get_choice(self, question, answer):
        return get_by_pk(question.get('choices', []), answer)

class StepsHelper(object):
    done_name = 'done'
    review_name = 'Review'
    next_name = 'Next'
    back_name = 'Back'
    wizard_goto_name = 'wizard_goto_step'
    wizard_current_name = 'wizard_current_step'
    wizard_form_fields = [
        wizard_current_name,
        wizard_goto_name,
    ]

    def __init__(self, view):
        self.view = view

    @property
    def step_count(self):
        return len(self.view.forms)

    @property
    def current(self):
        step = getattr(self.view, 'curent_step', 0)
        if isinstance(step, str):
            return step
        elif step <= self.last:
            return step
        else:
            return self.last

    @property
    def last(self):
        return self.step_count - 1

    @property
    def next(self):
        return self.adjust_step(1)

    @property
    def next_is_done(self):
        if isinstance(self.current, int):
            return self.next == self.done_name
        else:
            return False

    @property
    def current_is_done(self):
        return self.current == self.done_name

    @property
    def current_url(self):
        return self.url(self.current)

    @property
    def first_url(self):
        return self.url(0)

    @property
    def last_url(self):
        return self.url(self.last)

    @property
    def done_url(self):
        return self.url(self.done_name)

    @property
    def _goto_step_back(self):
        return self._goto_step(self.back_name)

    @property
    def _goto_step_next(self):
        return self._goto_step(self.next_name)

    @property
    def _goto_step_review(self):
        return self._goto_step(self.review_name)

    def parse_step(self, step):
        if step == self.done_name:
            return step
        else:
            return int(step)

    def url(self, step):
        return reverse(
            self.view.request.resolver_match.view_name,
            kwargs={'step': step},
        )

    def overflowed(self, step):
        return int(step) > int(self.last)

    def finished(self, step):
        return self._goto_step_review or step == self.done_name

    def set_from_post(self):
        if self._goto_step_back:
            self.view.curent_step = self.adjust_step(-1)
        if self._goto_step_next:
            self.view.curent_step = self.adjust_step(1)

    def adjust_step(self, adjustment):
        step = self.view.curent_step + adjustment
        if step >= self.step_count:
            return self.done_name
        else:
            return step

    def _goto_step(self, step_type):
        post = self.view.request.POST
        return post.get(self.wizard_goto_name, None) == step_type

class StorageHelper(object):
    data_manager = SerializedDataHelper
    storage_data_key = 'wizard_form_data'
    storage_form_key = 'wizard_form_serialized'

    def __init__(self, view):
        # TODO: scope down inputs
        self.view = view
        self.init_storage()

    @property
    def form_data(self):
        return self.current_data_from_storage()

    @property
    def cleaned_form_data(self):
        storage = self.current_data_from_storage()
        return self.data_manager.get_zipped_data(
            data=storage[self.storage_data_key],
            forms=storage[self.storage_form_key],
        )

    @property
    def current_data(self):
        storage = self.current_data_from_storage()
        return storage[self.storage_data_key]

    @property
    def current_and_post_data(self):
        data = self.current_data
        data.update(self.view.current_step_data)
        return data

    def update(self):
        '''
        primary class functionality method, updates the data in storage
        '''
        data = self.current_and_post_data
        self.add_data_to_storage(data)

    def current_data_from_storage(self):
        # TODO: base class with NotImplementedError checks
        session = self.view.request.session
        return {
            self.storage_data_key: session.get(self.storage_data_key, {}),
            self.storage_form_key: session.get(self.storage_form_key, {}),
        }

    def add_data_to_storage(self, data):
        # TODO: base class with NotImplementedError checks
        session = self.view.request.session
        session[self.storage_data_key] = data

    def init_storage(self):
        # TODO: base class with NotImplementedError checks
        session = self.view.request.session
        session.setdefault(
            self.storage_form_key,
            self.view.get_serialized_forms(),
        )
        session.setdefault(
            self.storage_data_key,
            {},
        )

class WizardViewTemplateHelpers(object):
    # TODO: these sould all be context variables instead

    @property
    def wizard_prev_step_exists(self):
        return self.steps.current

    @property
    def wizard_next_is_done(self):
        return self.steps.next_is_done

    @property
    def wizard_current_step(self):
        return self.steps.current

    @property
    def wizard_goto_name(self):
        return self.steps.wizard_goto_name

    @property
    def wizard_current_name(self):
        return self.steps.wizard_current_name

    @property
    def wizard_review_name(self):
        return self.steps.review_name

    @property
    def wizard_next_name(self):
        return self.steps.next_name

    @property
    def wizard_back_name(self):
        return self.steps.back_name


text:
#pragma once

#include "engine/Holding.h"
#include "pokerstove/peval/Card.h"

#include <exception>

namespace ps = pokerstove;

/*
 * This is not an actual class to be used. Only here to serve as a spec for the class to be used
 * as a template parameter for HoldingDistribution.
 */
struct AbstractWeightedHolding {
  void init(Holding holding, float weight);

  Holding getHolding() const;
  void setHolding(Holding holding);

  float getWeight() const;
  void setWeight(float weight);
};

/*
 * A probability distribution over Holding's.
 *
 * Does not support O(1) lookups.
 *
 * Item must implement the class signature of AbstractWeightedHolding above.
 */
template<typename Unit> class HoldingDistribution
{
private:
  static const size_t sMaxSize = 52*51/2;
  uint32_t _size;
  float _total_weight;
  Unit _units[sMaxSize];

  bool _validate() const;

public:
  /*
   * Default constructor intializes a uniform distribution over all (52-choose-2) possible holdings,
   * collapsing preflop-isomorphic holdings.
   */
  HoldingDistribution();

  /*
   * Removes all holdings that contains <card>.
   */
  void remove(ps::Card card);

  template <class Compare> void sort(Compare comp);
};

#include "HoldingDistributionINLINES.cpp"


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Tao's Page</title>
    <meta name="description" content="与机器,人,神共舞 - 编程,读书,思考,旅行,与机器对话,与人交谈,对神发问,探索,体验人生美丽的风景" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="/assets/images/favicon.ico" >

    <link rel="stylesheet" type="text/css" href="/assets/css/screen.css" />
    <link rel="stylesheet" type="text/css"
          href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />
    <link rel="stylesheet" type="text/css" href="/assets/css/syntax.css" />

        <link rel="canonical" href="/" />
    <meta name="referrer" content="origin" />
    <link rel="next" href="/page2/" />

    <meta property="og:site_name" content="与机器,人,神共舞" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="与机器,人,神共舞" />
    <meta property="og:description" content="编程,读书,思考,旅行,与机器对话,与人交谈,对神发问,探索,体验人生美丽的风景" />
    <meta property="og:url" content="/" />
    <meta property="og:image" content="/assets/images/cover1.jpg" />

    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content="与机器,人,神共舞" />
    <meta name="twitter:description" content="编程,读书,思考,旅行,与机器对话,与人交谈,对神发问,探索,体验人生美丽的风景" />
    <meta name="twitter:url" content="/" />
    <meta name="twitter:image:src" content="/assets/images/cover1.jpg" />

    <meta name="generator" content="Jekyll 3.0.0" />
    <link rel="alternate" type="application/rss+xml" title="与机器,人,神共舞" href="/rss.xml" />

Menu

        Close

Home

About

Machine

Human

God

Author

    Subscribe

            Menu

与机器,人,神共舞

编程,读书,思考,旅行,与机器对话,与人交谈,对神发问,探索,体验人生美丽的风景

    Scroll Down

            « Newer Posts

     Page 17 of 17

Split a String in C++

There are many ways to split a string in C++, but what's the most elegant way to split a string in C++? May be we can... »

            Tao He

                on

                       Machine

            <time class="post-date" datetime="2010-12-29">29 Dec 2010</time>

Forward declaration in C++

Why need use forward declaration? when we can use it? I will figure out these problem separately.

Why

Forward-declarations can significantly reduce build times

Break... »

            Tao He

                on

                       Machine

            <time class="post-date" datetime="2010-11-03">03 Nov 2010</time>

            « Newer Posts

     Page 17 of 17

与机器,人,神共舞 © 2021


text:
using LiteDB.Engine;
using System;
using System.Collections.Generic;
using System.Globalization;
using static LiteDB.Constants;

namespace LiteDB
{
    /// <summary>
    /// Manage ConnectionString to connect and create databases. Connection string are NameValue using Name1=Value1; Name2=Value2
    /// </summary>
    public class ConnectionString
    {
        private readonly Dictionary<string, string> _values;

        /// <summary>
        /// "connection": Return how engine will be open (default: Direct)
        /// </summary>
        public ConnectionType Connection { get; set; } = ConnectionType.Direct;

        /// <summary>
        /// "filename": Full path or relative path from DLL directory
        /// </summary>
        public string Filename { get; set; } = "";

        /// <summary>
        /// "password": Database password used to encrypt/decypted data pages
        /// </summary>
        public string Password { get; set; } = null;

        /// <summary>
        /// "initial size": If database is new, initialize with allocated space - support KB, MB, GB (default: 0)
        /// </summary>
        public long InitialSize { get; set; } = 0;

        /// <summary>
        /// "readonly": Open datafile in readonly mode (default: false)
        /// </summary>
        public bool ReadOnly { get; set; } = false;

        /// <summary>
        /// "upgrade": Check if data file is an old version and convert before open (default: false)
        /// </summary>
        public bool Upgrade { get; set; } = false;

        /// <summary>
        /// "collation": Set default collaction when database creation (default: "[CurrentCulture]/IgnoreCase")
        /// </summary>
        public Collation Collation { get; set; }

        /// <summary>
        /// Initialize empty connection string
        /// </summary>
        public ConnectionString()
        {
            _values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        }

        /// <summary>
        /// Initialize connection string parsing string in "key1=value1;key2=value2;...." format or only "filename" as default (when no ; char found)
        /// </summary>
        public ConnectionString(string connectionString)
            : this()
        {
            if (string.IsNullOrEmpty(connectionString)) throw new ArgumentNullException(nameof(connectionString));

            // create a dictionary from string name=value collection
            if (connectionString.Contains("="))
            {
                _values.ParseKeyValue(connectionString);
            }
            else
            {
                _values["filename"] = connectionString;
            }

            // setting values to properties
            this.Connection = _values.GetValue("connection", this.Connection);
            this.Filename = _values.GetValue("filename", this.Filename).Trim();

            this.Password = _values.GetValue("password", this.Password);

            if(this.Password == string.Empty)
            {
                this.Password = null;
            }

            this.InitialSize = _values.GetFileSize(@"initial size", this.InitialSize);
            this.ReadOnly = _values.GetValue("readonly", this.ReadOnly);

            this.Collation = _values.ContainsKey("collation") ? new Collation(_values.GetValue<string>("collation")) : this.Collation;

            this.Upgrade = _values.GetValue("upgrade", this.Upgrade);
        }

        /// <summary>
        /// Get value from parsed connection string. Returns null if not found
        /// </summary>
        public string this[string key] => _values.GetOrDefault(key);

        /// <summary>
        /// Create ILiteEngine instance according string connection parameters. For now, only Local/Shared are supported
        /// </summary>
        internal ILiteEngine CreateEngine()
        {
            var settings = new EngineSettings
            {
                Filename = this.Filename,
                Password = this.Password,
                InitialSize = this.InitialSize,
                ReadOnly = this.ReadOnly,
                Collation = this.Collation
            };

            // create engine implementation as Connection Type
            if (this.Connection == ConnectionType.Direct)
            {
                return new LiteEngine(settings);
            }
            else if (this.Connection == ConnectionType.Shared)
            {
                return new SharedEngine(settings);
            }
            else
            {
                throw new NotImplementedException();
            }
        }
    }
}


text:
// @ifdef DEBUG
/**
 * Note that the debug namespace is only exported in "debug" builds.
 * In production builds, this namespace is not included.
 *
 * @namespace debug
 */

/**
 * @memberof debug
 * @param {boolean} bool - The condition to ensure is true.
 * @param {string} message - The message to display if the first param is not true.
 */
export function ASSERT(bool, message)
{
    if (!bool) throw new Error(`[Fae ASSERT] ${message}`);
}
// @endif


text:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:bind="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="video"
            type="com.example.mydemo.greendaotdemo.LocalVideo" />

        <variable
            name="presenter"
            type="com.example.mydemo.greendaotdemo.DbTestActivity.Presenter" />

    </data>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:padding="10dp"
            tools:context="com.example.mydemo.greendaotdemo.DbTestActivity">

            <Button
                android:id="@+id/create_database"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Create database" />

            <Button
                android:id="@+id/query"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:onClick="@{()->presenter.query()}"
                android:text="query_next_data" />

            <ViewStub
                android:id="@+id/viewstub"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout="@layout/widget" />

            <include
                layout="@layout/layout_databinding"
                bind:presenter="@{presenter}"
                bind:video="@{video}" />

            <Button
                android:id="@+id/update"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="update_file_name" />

        </LinearLayout>
    </ScrollView>
</layout>


text:
from django.core.exceptions import ValidationError
from arcanelab.ouroboros.executors import Workflow
from arcanelab.ouroboros.models import NodeSpec, WorkflowSpec, CourseSpec
from arcanelab.ouroboros import exceptions
from .support import ValidationErrorWrappingTestCase

############################################
# WorkflowSpec tests
############################################

# TODO WARNING I MADE CHANGES TO THE WAY THE BRANCHES BEHAVE.
# TODO   AT MODEL LEVEL, COURSES DO NOT ALLOW UNREACHABLE NODES AND
# TODO   -IF BEING CHILDREN COURSES- DO NOT ALLOW AN AUTOMATIC PATH
# TODO   FROM THE ENTER NODE TO ANY EXIT NODE, WITHOUT NODES OF TYPE
# TODO   SPLIT OR INPUT. TESTS MUST BE CHANGED ACCORDINGLY SO THEY
# TODO   TEST THESE VALIDATIONS AND DO NOT FAIL THEM IN THE BRANCHES
# TODO   NOT BEING TESTED (ALSO, CERTAIN TESTS WILL CHANGE THE WAY
# TODO   THEY FAIL, SO AN INTENSIVE CHECK MUST BE DONE). THESE CHANGES
# TODO   IN THE TESTS MUST BE AMEND-COMMITTED

class WorkflowSpecTestCase(ValidationErrorWrappingTestCase):

    def test_unexpected_input_format_or_bad_model_is_bad(self):
        """
        Input format verification.
        :return:
        """

        with self.assertRaises(ValueError):
            # JSON validation on strings
            Workflow.Spec.install('{')

        with self.assertRaises(TypeError):
            # type validation when non-string (dict is good)
            Workflow.Spec.install(1)

        with self.assertRaises(LookupError):
            # model validation (concrete/exists)
            Workflow.Spec.install({'model': 'ouroboros.Document'})

        with self.assertRaises(TypeError):
            # model validation (hierarchy)
            Workflow.Spec.install({'model': 'auth.User'})

    def test_empty_workflow_is_bad(self):
        with self.assertRaises(exceptions.WorkflowInvalidState) as ar:
            spec = {'model': 'sample.Task', 'code': 'empty-wfspec', 'name': 'Empty Workflow Spec'}
            Workflow.Spec.install(spec)
        exc = self.unwrapValidationError(ar.exception)
        self.assertEqual(exc.code, exceptions.WorkflowSpecHasNoMainCourse.CODE, 'Invalid subclass of ValidationError '
                                                                                'raised')

    def test_single_main_course_is_good(self):
        try:
            spec = {'model': 'sample.Task', 'code': 'wfspec', 'name': 'Workflow Spec', 'create_permission': '',
                    'cancel_permission': '',
                    'courses': [{
                        'code': '', 'name': 'Single',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin',
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit',
                            'exit_value': 100,
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }],
                        'transitions': [{
                            'origin': 'origin', 'destination': 'exit', 'name': 'Initial transition',
                            'permission': 'sample.start_task',
                        }]
                    }]}
            Workflow.Spec.install(spec)
        except Exception as e:
            self.assertFalse(True, 'An exception was raised (%s): %s' % (type(e).__name__, e))

    def test_cyclical_course_dependencies_is_bad(self):
        with self.assertRaises(exceptions.WorkflowInvalidState) as ar:
            spec = {'model': 'sample.Task', 'code': 'wfspec', 'name': 'Workflow Spec', 'create_permission': '',
                    'cancel_permission': '',
                    'courses': [{
                        'code': '', 'name': 'Root',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin',
                        }, {
                            'type': NodeSpec.SPLIT, 'code': 'parallel-1', 'name': 'Parallel', 'branches': ['foo', 'bar']
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit',
                            'exit_value': 100,
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }],
                        'transitions': [{
                            'origin': 'origin', 'destination': 'parallel-1', 'name': 'Initial transition',
                            'permission': 'sample.start_task',
                        }, {
                            'origin': 'parallel-1', 'action_name': 'escape', 'destination': 'exit',
                            'name': 'Final transition',
                        }]
                    }, {
                        'code': 'foo', 'name': 'Foo',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin'
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit', 'exit_value': 100,
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }],
                        'transitions': [{
                            'origin': 'origin', 'destination': 'exit', 'name': 'Initial transition',
                            'permission': 'sample.start_task',
                        }]
                    }, {
                        'code': 'bar', 'name': 'Bar',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin'
                        }, {
                            'type': NodeSpec.SPLIT, 'code': 'bad-parallel', 'name': 'Bad-Parallel',
                            'branches': ['foo', 'bar']
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit', 'exit_value': 100,
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }],
                        'transitions': [{
                            'origin': 'origin', 'destination': 'bad-parallel', 'name': 'Initial transition',
                            'permission': 'sample.start_task',
                        }, {
                            'origin': 'bad-parallel', 'action_name': 'escape', 'destination': 'exit',
                            'name': 'Final transition',
                        }]
                    }]}
            Workflow.Spec.install(spec)
        exc = self.unwrapValidationError(ar.exception)
        self.assertEqual(exc.code, exceptions.WorkflowSpecHasCircularDependentCourses.CODE,
                         'Invalid subclass of ValidationError raised')

############################################
# CourseSpec tests
############################################

class CourseSpecTestCase(ValidationErrorWrappingTestCase):

    def test_no_cancel_node_is_bad(self):
        with self.assertRaises(exceptions.WorkflowInvalidState) as ar:
            spec = {'model': 'sample.Task', 'code': 'wfspec', 'name': 'Workflow Spec', 'create_permission': '',
                    'cancel_permission': '',
                    'courses': [{
                        'code': '', 'name': 'Single',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin',
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit', 'exit_value': 100,
                        }],
                        'transitions': [{
                            'origin': 'origin', 'destination': 'exit', 'name': 'Initial transition',
                            'permission': 'sample.start_task',
                        }]
                    }]}
            Workflow.Spec.install(spec)
        exc = self.unwrapValidationError(ar.exception)
        self.assertEqual(exc.code, exceptions.WorkflowCourseSpecHasNoRequiredNode.CODE,
                         'Invalid subclass of ValidationError raised')

    def test_multi_cancel_node_is_bad(self):
        with self.assertRaises(exceptions.WorkflowInvalidState) as ar:
            spec = {'model': 'sample.Task', 'code': 'wfspec', 'name': 'Workflow Spec', 'create_permission': '',
                    'cancel_permission': '',
                    'courses': [{
                        'code': '', 'name': 'Single',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin',
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit', 'exit_value': 100,
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel-2', 'name': 'Cancel 2',
                        }],
                        'transitions': [{
                            'origin': 'origin', 'destination': 'exit', 'name': 'Initial transition',
                            'permission': 'sample.start_task',
                        }]
                    }]}
            Workflow.Spec.install(spec)
        exc = self.unwrapValidationError(ar.exception)
        self.assertEqual(exc.code, exceptions.WorkflowCourseSpecMultipleRequiredNodes.CODE,
                         'Invalid subclass of ValidationError raised')

    def test_no_enter_node_is_bad(self):
        with self.assertRaises(exceptions.WorkflowInvalidState) as ar:
            spec = {'model': 'sample.Task', 'code': 'wfspec', 'name': 'Workflow Spec', 'create_permission': '',
                    'cancel_permission': '',
                    'courses': [{
                        'code': '', 'name': 'Single',
                        'nodes': [{
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit', 'exit_value': 100,
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }],
                        'transitions': []
                    }]}
            Workflow.Spec.install(spec)
        exc = self.unwrapValidationError(ar.exception)
        self.assertEqual(exc.code, exceptions.WorkflowCourseSpecHasNoRequiredNode.CODE,
                         'Invalid subclass of ValidationError raised')

    def test_multi_enter_node_is_bad(self):
        with self.assertRaises(exceptions.WorkflowInvalidState) as ar:
            spec = {'model': 'sample.Task', 'code': 'wfspec', 'name': 'Workflow Spec', 'create_permission': '',
                    'cancel_permission': '',
                    'courses': [{
                        'code': '', 'name': 'Single',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin',
                        }, {
                            'type': NodeSpec.ENTER, 'code': 'origin-2', 'name': 'Origin-2',
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit', 'exit_value': 100,
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }],
                        'transitions': [{
                            'origin': 'origin', 'destination': 'exit', 'name': 'Initial transition',
                            'permission': 'sample.start_task',
                        }]
                    }]}
            Workflow.Spec.install(spec)
        exc = self.unwrapValidationError(ar.exception)
        self.assertEqual(exc.code, exceptions.WorkflowCourseSpecMultipleRequiredNodes.CODE,
                         'Invalid subclass of ValidationError raised')

    def test_no_exit_node_is_bad(self):
        with self.assertRaises(exceptions.WorkflowInvalidState) as ar:
            spec = {'model': 'sample.Task', 'code': 'wfspec', 'name': 'Workflow Spec', 'create_permission': '',
                    'cancel_permission': '',
                    'courses': [{
                        'code': '', 'name': 'Single',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin',
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }],
                        'transitions': []
                    }]}
            Workflow.Spec.install(spec)
        exc = self.unwrapValidationError(ar.exception)
        self.assertEqual(exc.code, exceptions.WorkflowCourseSpecHasNoRequiredNode.CODE,
                         'Invalid subclass of ValidationError raised')

    def test_no_joined_node_when_caller_uses_joiner_is_bad(self):
        with self.assertRaises(exceptions.WorkflowInvalidState) as ar:
            spec = {'model': 'sample.Task', 'code': 'wfspec', 'name': 'Workflow Spec', 'create_permission': '',
                    'cancel_permission': '',
                    'courses': [{
                        'code': '', 'name': 'Root',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin',
                        }, {
                            'type': NodeSpec.SPLIT, 'code': 'parallel-1', 'name': 'Parallel',
                            'joiner': 'sample.support.dummy_joiner', 'branches': ['foo', 'bar']
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit', 'exit_value': 100,
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit-2', 'name': 'Exit 2', 'exit_value': 100,
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }],
                        'transitions': [{
                            'origin': 'origin', 'destination': 'parallel-1', 'name': 'Initial transition',
                            'permission': 'sample.start_task',
                        }, {
                            'origin': 'parallel-1', 'action_name': 'escape-1', 'destination': 'exit',
                            'name': 'Final transition 1',
                        }, {
                            'origin': 'parallel-1', 'action_name': 'escape-2', 'destination': 'exit-2',
                            'name': 'Final transition 2',
                        }]
                    }, {
                        'code': 'foo', 'name': 'Foo',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin',
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit', 'exit_value': 100,
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }],
                        'transitions': [{
                            'origin': 'origin', 'destination': 'exit', 'name': 'Initial transition',
                            'permission': 'sample.start_task',
                        }]
                    }, {
                        'code': 'bar', 'name': 'Bar',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin',
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit', 'exit_value': 100,
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }],
                        'transitions': [{
                            'origin': 'origin', 'destination': 'exit', 'name': 'Initial transition',
                            'permission': 'sample.start_task',
                        }]
                    }]}
            Workflow.Spec.install(spec)
        exc = self.unwrapValidationError(ar.exception)
        self.assertEqual(exc.code, exceptions.WorkflowCourseSpecHasNoRequiredNode.CODE,
                         'Invalid subclass of ValidationError raised')

    def test_bad_caller_type_is_bad(self):
        try:
            spec = {'model': 'sample.Task', 'code': 'wf-badnode', 'name': 'Workflow Spec', 'create_permission': '',
                    'cancel_permission': '',
                    'courses': [{
                        'code': '', 'name': 'Root',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin',
                        }, {
                            'type': NodeSpec.SPLIT, 'code': 'parallel-1', 'name': 'Parallel',
                            'joiner': 'sample.support.dummy_joiner', 'branches': ['foo', 'bar']
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit', 'exit_value': 100,
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit-2', 'name': 'Exit 2', 'exit_value': 100,
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }],
                        'transitions': [{
                            'origin': 'origin', 'destination': 'parallel-1', 'name': 'Initial transition',
                            'permission': 'sample.start_task',
                        }, {
                            'origin': 'parallel-1', 'action_name': 'escape-1', 'destination': 'exit',
                            'name': 'Final transition 1',
                        }, {
                            'origin': 'parallel-1', 'action_name': 'escape-2', 'destination': 'exit-2',
                            'name': 'Final transition 2',
                        }]
                    }, {
                        'code': 'foo', 'name': 'Foo',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin',
                        }, {
                            'type': NodeSpec.INPUT, 'code': 'input', 'name': 'Input',
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit', 'exit_value': 100,
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }, {
                            'type': NodeSpec.JOINED, 'code': 'joined', 'name': 'Joined',
                        }],
                        'transitions': [{
                            'origin': 'origin', 'destination': 'input', 'name': 'Initial transition',
                            'permission': 'sample.start_task',
                        }, {
                            'origin': 'input', 'destination': 'exit', 'name': 'Final transition',
                            'action_name': 'go-exit',
                        }]
                    }, {
                        'code': 'bar', 'name': 'Bar',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin',
                        }, {
                            'type': NodeSpec.INPUT, 'code': 'input', 'name': 'Input',
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit', 'exit_value': 100,
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }, {
                            'type': NodeSpec.JOINED, 'code': 'joined', 'name': 'Joined',
                        }],
                        'transitions': [{
                            'origin': 'origin', 'destination': 'input', 'name': 'Initial transition',
                            'permission': 'sample.start_task',
                        }, {
                            'origin': 'input', 'destination': 'exit', 'name': 'Final transition',
                            'action_name': 'go-exit',
                        }]
                    }]}
            Workflow.Spec.install(spec)
            node_spec = NodeSpec.objects.get(code='parallel-1', course_spec__code='',
                                             course_spec__workflow_spec__code='wf-badnode')
            node_spec.type = NodeSpec.INPUT
            node_spec.save()
            course_spec = CourseSpec.objects.get(code='foo', workflow_spec__code='wf-badnode')
        except Exception as e:
            self.assertFalse(True, 'An exception was raised (%s): %s' % (type(e).__name__, e))
        else:
            with self.assertRaises(ValidationError) as ar:
                course_spec.full_clean()
            exc = self.unwrapValidationError(ar.exception)
            self.assertEqual(exc.code, exceptions.WorkflowCourseSpecHasInvalidCallers.CODE,
                             'Invalid subclass of ValidationError raised')

    def test_unreachable_node_by_enter_is_bad(self):
        with self.assertRaises(exceptions.WorkflowInvalidState) as ar:
            spec = {'model': 'sample.Task', 'code': 'wfspec', 'name': 'Workflow Spec', 'create_permission': '',
                    'cancel_permission': '',
                    'courses': [{
                        'code': '', 'name': 'Single',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin',
                        }, {
                            'type': NodeSpec.INPUT, 'code': 'loop-1', 'name': 'Loop 1',
                        }, {
                            'type': NodeSpec.INPUT, 'code': 'loop-2', 'name': 'Loop 2',
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit',
                            'exit_value': 100,
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }],
                        'transitions': [{
                            'origin': 'origin', 'destination': 'exit', 'name': 'Initial transition',
                            'permission': 'sample.start_task',
                        }, {
                            'origin': 'loop-1', 'destination': 'loop-2', 'name': 'Loop', 'action_name': 'loop'
                        }, {
                            'origin': 'loop-2', 'destination': 'loop-1', 'name': 'Loop', 'action_name': 'loop'
                        }, {
                            'origin': 'loop-1', 'destination': 'exit', 'name': 'Break Loop', 'action_name': 'break-loop'
                        }]
                    }]}
            Workflow.Spec.install(spec)
        exc = self.unwrapValidationError(ar.exception)
        self.assertEqual(exc.code, exceptions.WorkflowCourseSpecHasUnreachableNodesByEnter.CODE,
                         'Invalid subclass of ValidationError raised')

    def test_unreachable_node_by_exit_is_bad(self):
        with self.assertRaises(exceptions.WorkflowInvalidState) as ar:
            spec = {'model': 'sample.Task', 'code': 'wfspec', 'name': 'Workflow Spec', 'create_permission': '',
                    'cancel_permission': '',
                    'courses': [{
                        'code': '', 'name': 'Single',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin',
                        }, {
                            'type': NodeSpec.INPUT, 'code': 'input', 'name': 'Input',
                        }, {
                            'type': NodeSpec.INPUT, 'code': 'loop-1', 'name': 'Loop 1',
                        }, {
                            'type': NodeSpec.INPUT, 'code': 'loop-2', 'name': 'Loop 2',
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit',
                            'exit_value': 100,
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }],
                        'transitions': [{
                            'origin': 'origin', 'destination': 'input', 'name': 'Initial transition',
                            'permission': 'sample.start_task',
                        }, {
                            'origin': 'input', 'destination': 'exit', 'name': 'Final transition',
                            'permission': 'sample.start_task', 'action_name': 'hop-end'
                        }, {
                            'origin': 'input', 'destination': 'loop-1', 'name': 'Loop transition',
                            'permission': 'sample.start_task', 'action_name': 'enter-loop'
                        }, {
                            'origin': 'loop-1', 'destination': 'loop-2', 'name': 'Loop', 'action_name': 'loop'
                        }, {
                            'origin': 'loop-2', 'destination': 'loop-1', 'name': 'Loop', 'action_name': 'loop'
                        }]
                    }]}
            Workflow.Spec.install(spec)
        exc = self.unwrapValidationError(ar.exception)
        self.assertEqual(exc.code, exceptions.WorkflowCourseSpecHasUnreachableNodesByExit.CODE,
                         'Invalid subclass of ValidationError raised')

    def test_automatic_paths_in_branches_are_bad(self):
        with self.assertRaises(exceptions.WorkflowInvalidState) as ar:
            spec = {'model': 'sample.Task', 'code': 'wf-badnode', 'name': 'Workflow Spec', 'create_permission': '',
                    'cancel_permission': '',
                    'courses': [{
                        'code': '', 'name': 'Root',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin',
                        }, {
                            'type': NodeSpec.SPLIT, 'code': 'parallel-1', 'name': 'Parallel',
                            'joiner': 'sample.support.dummy_joiner', 'branches': ['foo', 'bar']
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit', 'exit_value': 100,
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit-2', 'name': 'Exit 2', 'exit_value': 100,
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }],
                        'transitions': [{
                            'origin': 'origin', 'destination': 'parallel-1', 'name': 'Initial transition',
                            'permission': 'sample.start_task',
                        }, {
                            'origin': 'parallel-1', 'action_name': 'escape-1', 'destination': 'exit',
                            'name': 'Final transition 1',
                        }, {
                            'origin': 'parallel-1', 'action_name': 'escape-2', 'destination': 'exit-2',
                            'name': 'Final transition 2',
                        }]
                    }, {
                        'code': 'foo', 'name': 'Foo',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin',
                        }, {
                            'type': NodeSpec.STEP, 'code': 'step', 'name': 'Step',
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit', 'exit_value': 100,
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }, {
                            'type': NodeSpec.JOINED, 'code': 'joined', 'name': 'Joined',
                        }],
                        'transitions': [{
                            'origin': 'origin', 'destination': 'step', 'name': 'Initial transition',
                            'permission': 'sample.start_task',
                        }, {
                            'origin': 'step', 'destination': 'exit', 'name': 'Final transition',
                        }]
                    }, {
                        'code': 'bar', 'name': 'Bar',
                        'nodes': [{
                            'type': NodeSpec.ENTER, 'code': 'origin', 'name': 'Origin',
                        }, {
                            'type': NodeSpec.INPUT, 'code': 'input', 'name': 'Input',
                        }, {
                            'type': NodeSpec.EXIT, 'code': 'exit', 'name': 'Exit', 'exit_value': 100,
                        }, {
                            'type': NodeSpec.CANCEL, 'code': 'cancel', 'name': 'Cancel',
                        }, {
                            'type': NodeSpec.JOINED, 'code': 'joined', 'name': 'Joined',
                        }],
                        'transitions': [{
                            'origin': 'origin', 'destination': 'input', 'name': 'Initial transition',
                            'permission': 'sample.start_task',
                        }, {
                            'origin': 'input', 'destination': 'exit', 'name': 'Final transition',
                            'action_name': 'go-exit',
                        }]
                    }]}
            Workflow.Spec.install(spec)
        exc = self.unwrapValidationError(ar.exception)
        self.assertEqual(exc.code, exceptions.WorkflowCourseSpecHasAutomaticPath.CODE,
                         'Invalid subclass of ValidationError raised')


text:
PLAY = 'plays'
NOPE = 'does not play'

def areYouPlayingBanjo(name):
    """ are_you_playing_banjo == PEP8 (forced mixedCase by CodeWars) """
    return '{} {} banjo'.format(name, PLAY if name[0].lower() == 'r' else NOPE)


text:
0. New a benchmark project, say: demo.benchmark
1. Import both service interface (your service API jar) and `dubbo.benchmark.jar` into the project
2. Create a new class to implement `AbstractClientRunnable`:
    * Override parent's constructor
    * Implement `invoke` method, use `ServiceFactory` to create local proxy for the interface, and then implement business logic as below:

    ```java
    public class MyClient implements AbstractClientRunnable {
       public Object invoke(ServiceFactory serviceFactory) {
        DemoService demoService = (DemoService) serviceFactory.get(DemoService.class);
        return demoService.sendRequest("hello");
       }
    }
```

3. build the project and package the result into a jar file, for example: `demo.benchmark.jar`
4. put `demo.benchmark.jar` under `dubbo.benchmark/lib`
5. config in `dubbo.proerties`
6. run `run.bat` on windows, or `run.sh` on unix-like platforms


text:
require('../lib/globals');

let React = require('react');

/*
    * renderIntoDocument vs render
    * finding elements in the component tree
    * scry vs find
    * simulating events
    * stubbing components
*/


text:
package com.sejelli.messaging.services;

import com.sejelli.messaging.domain.model.ErrorCode;
import com.sejelli.messaging.domain.model.Setting;
import com.sejelli.messaging.domain.model.SmsMessage;
import com.sejelli.messaging.services.YamamahServiceProvider.YamamahServiceProvider;
import com.sejelli.messaging.services.mobilywssp.MobilyServiceProvider;
import com.sejelli.messaging.services.mqamsmsserviceprovider.MqamsmsServiceProvider;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by aibano on 10/16/2016.
 */
public class SmsServiceProviderImpl implements SmsServicerProvider {

    private SmsServicerProvider servicerProvider;
    private Setting setting;

    @Override
    public ErrorCode send(SmsMessage smsMessage) {

        return this.servicerProvider.send(smsMessage);
    }

    @Override
    public SmsServicerProvider setSetting(Setting setting) {
        this.setting = setting;
        if(setting.getProvider().getId() == 1L) // YAMAMAH
            this.servicerProvider = new YamamahServiceProvider(setting.getUsername(),
                    setting.getPassword());
        else if(setting.getProvider().getId() == 2L) // mobily.com
            this.servicerProvider = new MobilyServiceProvider(setting.getUsername(),
                    setting.getPassword());
        /*else if(setting.getProvider().getId() == 3) // mqamsms.com
            this.servicerProvider = new MqamsmsServiceProvider(setting.getUsername(),
                    setting.getPassword());*/
        else
            throw new RuntimeException(String.format("Undefined Settings with id %s", setting.getProvider().getId()));

        return this;
    }
}