text:
//
//  GROMapper.m
//  Pods
//
//  Created by Grant Robinson on 4/15/17.
//
//

#import "GROMapper.h"
#import <objc/runtime.h>

#import "Logging.h"

NSString *GROMapperErrorDomain = @"net.mr-r.GROMapper";

#define PROPERTY_MAP_PREFIX @"GROMapperPropertyFor_"
#define KEY_MAP_PREFIX @"GROMapperKeyFor_"
#define ARRAY_CLASS_PREFIX @"GROMapperArrayClassFor_"
#define CONVERTER_BLOCK_PREFIX @"GROMapperConvertBlockFor_"
#define CUSTOM_MAPPING_PREFIX @"GROMapperCustomMappingBlockFor_"
#define JSON_CONVERSION_PREFIX @"GROMapperConvertToJSONFor_"

typedef NS_ENUM(NSInteger, GROJsonType) {
	GROJsonTypeUnknown,
	GROJsonTypeObject,
	GROJsonTypeArray,
	GROJsonTypeString,
	GROJsonTypeNumber,
	GROJsonTypeNull,
};

typedef NS_ENUM(NSInteger, GROSourceType) {
	GROSourceTypeUnknown,
	GROSourceTypeDictionary,
	GROSourceTypeArray,
	GROSourceTypeCustomObject,
	GROSourceTypeString,
	GROSourceTypeNumber,
	GROSourceTypePrimitive,
	GROSourceTypeNull,
	GROSourceTypeNeedsConversionBlock,
	GROSourceTypeInconvertibleValue,
};

typedef NS_ENUM(NSInteger, GROTargetType) {
	GROTargetTypeUnknown,
	GROTargetTypeCustomObject,
	GROTargetTypeArray,
	GROTargetTypeBasicOrWrappedValue,
};

static GROJsonType jsonType(id source) {
	if ([source isKindOfClass:[NSString class]]) {
		return GROJsonTypeString;
	}
	else if ([source isKindOfClass:[NSNumber class]]) {
		return GROJsonTypeNumber;
	}
	else if ([source isKindOfClass:[NSDictionary class]]) {
		return GROJsonTypeObject;
	}
	else if ([source isKindOfClass:[NSArray class]]) {
		return GROJsonTypeArray;
	}
	else if (source == (id)[NSNull null]) {
		return GROJsonTypeNull;
	}
	else {
		return GROJsonTypeUnknown;
	}
}

static GROTargetType targetType(id source) {
	if ([source isKindOfClass:[NSDictionary class]]) {
		return GROTargetTypeCustomObject;
	}
	else if ([source isKindOfClass:[NSArray class]]) {
		return GROTargetTypeArray;
	}
	else {
		return GROTargetTypeBasicOrWrappedValue;
	}
}

static GROSourceType sourceObjectType(id source) {
	if (source == nil) {
		return GROSourceTypeNull;
	}
	if ([source isKindOfClass:[NSString class]]) {
		return GROSourceTypeString;
	}
	else if ([source isKindOfClass:[NSNumber class]]) {
		return GROSourceTypeNumber;
	}
	else if (source == [NSNull null]) {
		return GROSourceTypeNull;
	}
	else if ([source isKindOfClass:[NSArray class]]) {
		return GROSourceTypeArray;
	}
	else if ([source isKindOfClass:[NSDictionary class]]) {
		return GROSourceTypeDictionary;
	}
	return GROSourceTypeCustomObject;
}

static GROSourceType sourceTypeFromAttributes(const char *attr) {
	switch (attr[1]) {
		case 'v':
			// can't convert a void
			return GROSourceTypeInconvertibleValue;
			break;
		case '#':
			// can't convert a class object
			return GROSourceTypeInconvertibleValue;
			break;
		case ':':
			// can't convert a selector
			return GROSourceTypeInconvertibleValue;
			break;
		case '[':
		case '{':
		case '(':
			// look for a custom conversion block
			return GROSourceTypeNeedsConversionBlock;
			break;
		case 'b':
			// a bit-field, need a custom conversion block
			return GROSourceTypeNeedsConversionBlock;
			break;
		case '^':
			// a pointer to a type, not sure how we would convert that, unless it is with a custom conversion block
			return GROSourceTypeNeedsConversionBlock;
			break;
		case '?':
			// an unknown type
			return GROSourceTypeNeedsConversionBlock;
			break;
		case '@':
			if (attr[2] == '"' || attr[2] == ',') {
				// it is an object
				return GROSourceTypeCustomObject;
			}
			else if (attr[2] == '?') {
				// it is a block
				return GROSourceTypeInconvertibleValue;
			}
			else {
				// something else?
				return GROSourceTypeInconvertibleValue;
			}
			break;
	}
	// if we fall out of the switch, it is a primitive type that can/will be wrapped
	return GROSourceTypePrimitive;
}

static NSError * errorWithCodeAndDescription(NSInteger code, NSString *format, ...) {
	va_list varArgs;
	va_start(varArgs, format);
	NSString *str = [[NSString alloc] initWithFormat:format arguments:varArgs];
	va_end(varArgs);

	return [NSError errorWithDomain:GROMapperErrorDomain code:code userInfo:@{NSLocalizedDescriptionKey: str}];
}

static Class classForProperty(objc_property_t property) {
	if (property != NULL) {
		const char *attr = property_getAttributes(property);
		// per the Apple doc, the attribute string will start with a T and the 2nd character is the 'encode' type
		// which for an Objective-C object will be '@'
		if (attr[1] == '@' && attr[2] == '"') {
			/**
			  * it is an object type (not a block, which is encoded as 'T@?')
			  * grab the type name from the attributes
			  *
			  * String will look like this: T@"<class name>"
			  */
			int startPos =  3, endPos = startPos;
			while (attr[endPos] != '\0' && attr[endPos] != '"') {
				endPos++;
			}
			return NSClassFromString([[NSString alloc] initWithBytes:attr+startPos length:endPos - startPos encoding:NSUTF8StringEncoding]);
		}
		// if we get to here, it was either an Objective-C Block, or a non-object type (struct, etc)
		return nil;
	}
	return nil;
}

static Class classForKeyWithTarget(NSString *key, id target) {
	Class targetClass = [target class];
	SEL selector = NSSelectorFromString([ARRAY_CLASS_PREFIX stringByAppendingString:key]);
	if (class_respondsToSelector(targetClass, selector)) {
		IMP imp = [target methodForSelector:selector];
		Class (*func)(id, SEL) = (void *)imp;
		Class classForKey = func(target, selector);
		return classForKey;
	}
	return nil;
}

@implementation GROMapper

@synthesize ignoreNulls;

- (instancetype) init {
	self = [super init];
	if (self) {
		ignoreNulls = YES;
	}
	return self;
}

+ (instancetype) mapper {
	return [[GROMapper alloc] init];
}

+ (id) map:(id)source to:(Class)clazz error:(NSError *__autoreleasing *)error {
	return [[self mapper] mapSource:source to:clazz error:error];
}

+ (id) jsonObjectFrom:(id)object error:(NSError *__autoreleasing *)error {
	return [[self mapper] jsonObjectFor:object error:error];
}

- (id) mapSource:(id)source to:(Class)clazz error:(NSError *__autoreleasing *)error {
	id rootObj = nil;
	@try {
		if (source == nil) @throw errorWithCodeAndDescription(GROMapperErrorCodeSourceJSONIsNil, @"source JSON object is nil");
		if (clazz == nil) @throw errorWithCodeAndDescription(GROMapperErrorCodeMappingClassIsNil, @"Class to map to cannot be nil");

		switch (jsonType(source)) {
			case GROJsonTypeUnknown:
				@throw errorWithCodeAndDescription(GROMapperErrorCodeInvalidRootJSONObject, @"source object is an invalid JSON type (passed in %@)", source);
				break;
			case GROJsonTypeObject:
			{
				if ([clazz respondsToSelector:@selector(concreteClassForObject:)]) {
					Class concreteClass = [clazz concreteClassForObject:source];
					rootObj = [[concreteClass alloc] init];
				}
				else {
					rootObj = [[clazz alloc] init];
				}
				[self map:source toObject:rootObj];
				break;
			}
			case GROJsonTypeArray:
			{
				NSArray *sourceArray = source;
				if (sourceArray.count == 0) {
					rootObj = [NSArray array];
				}
				else if (jsonType(sourceArray.firstObject) == GROJsonTypeObject) {
					rootObj = [NSMutableArray arrayWithCapacity:sourceArray.count];
					[self map:sourceArray toArray:rootObj withClass:clazz];
				}
				else {
					// do nothing - it is an array of basic types (or should be)
					rootObj = source;
				}
				break;
			}
			case GROJsonTypeString:
			case GROJsonTypeNumber:
				@throw errorWithCodeAndDescription(GROMapperErrorCodeInvalidRootJSONObject, @"Cannot map a JSON basic type (string, number, etc).  Root of the JSON must be an array or object.");
				break;
			case GROJsonTypeNull:
				// if they pass in null, the resulting object should map to nil
				break;
		}
	} @catch (NSError *thrown) {
		if (error) {
			*error = thrown;
		}
		rootObj = nil;
	} @catch (NSException *exception) {
		NSError *toRaise = nil;
		if ([exception.name isEqualToString:NSUndefinedKeyException]) {
			NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:exception.userInfo];
			userInfo[NSLocalizedDescriptionKey] = exception.reason;
			toRaise = [NSError errorWithDomain:GROMapperErrorDomain code:GROMapperErrorCodeNotKeyValueCodingCompliant userInfo:userInfo];
		}
		else {
			NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:exception.userInfo];
			userInfo[NSLocalizedDescriptionKey] = exception.reason;
			toRaise = [NSError errorWithDomain:GROMapperErrorDomain code:GROMapperErrorCodeGeneralError userInfo:userInfo];
		}
		if (error) {
			*error = toRaise;
		}
		rootObj = nil;
	}@finally {

	}
	return rootObj;
}

- (void) map:(NSDictionary <NSString*,id> *)source toObject:(id)target {
	Class targetClass = [target class];
	id nullInstance = [NSNull null];
	for (NSString *key in source.allKeys) {
		@autoreleasepool {
			id origValue = source[key];
			if (ignoreNulls && origValue == nullInstance) {
				// we will ignore it at the end, short-circuit the whole process and move on
				continue;
			}
			SEL customMappingSelector = NSSelectorFromString([CUSTOM_MAPPING_PREFIX stringByAppendingString:key]);
			if (class_respondsToSelector(targetClass, customMappingSelector)) {
				IMP imp = class_getMethodImplementation(targetClass, customMappingSelector);
				id (*func)(id, SEL) = (void *)imp;
				void (^customMappingBlock)(id original) = func(target, customMappingSelector);
				if (customMappingBlock) {
					customMappingBlock(origValue);
					continue;
				}

			}
			// first, grab the property using only the key
			NSString *propertyName = key;
			objc_property_t property = class_getProperty(targetClass, key.UTF8String);
			if (!property) {
				// if that is not found, try a mapping
				SEL selector = NSSelectorFromString([PROPERTY_MAP_PREFIX stringByAppendingString:key]);
				if (class_respondsToSelector(targetClass, selector)) {
					IMP imp = class_getMethodImplementation(targetClass, selector);
					NSString* (*func)(id, SEL) = (void *)imp;
					propertyName = func(target, selector);
					property = class_getProperty(targetClass, propertyName.UTF8String);
				}
			}
			if (property == NULL) {
				// if there is no property, ignore it and move on.
				continue;
			}
			id actualValue = origValue;
			SEL conversionSelector = NSSelectorFromString([CONVERTER_BLOCK_PREFIX stringByAppendingString:key]);
			if (class_respondsToSelector(targetClass, conversionSelector)) {
				IMP imp = class_getMethodImplementation(targetClass, conversionSelector);
				id (*func)(id, SEL) = (void *)imp;
				id (^converterBlock)(id original) = func(target, conversionSelector);
				if (converterBlock) {
					actualValue = converterBlock(origValue);
				}
			}
			id valueToSet = nil;
			switch (targetType(actualValue)) {
				case GROTargetTypeUnknown:
					// can't hit this case currently
					break;
				case GROTargetTypeCustomObject:
				{
					Class propertyClass = classForProperty(property);
					if (!propertyClass) {
						// we have a custom object (aka a dict) and the property we are setting has no class
						// which means it is either a block or a primitive type, no mapping is therefore possible
						DDLogWarn(@"cannot map value of type '%@' to a block or primitive type for property %@", NSStringFromClass([actualValue class]), propertyName);
						continue;
					}
					else if ([actualValue isKindOfClass:propertyClass]) {
						// the value we are setting matches the property's class, just do a direct set
						valueToSet = actualValue;
					}
					else {
						if ([propertyClass respondsToSelector:@selector(concreteClassForObject:)]) {
							Class actualClass = [propertyClass concreteClassForObject:actualValue];
							valueToSet = [[actualClass alloc] init];
						}
						else {
							valueToSet = [[propertyClass alloc] init];
						}
						[self map:actualValue toObject:valueToSet];
					}
					break;
				}
				case GROTargetTypeArray:
				{
					NSArray *array = actualValue;
					if (array.count == 0) {
						valueToSet = [NSArray array];
					}
					else if (jsonType(array.firstObject) == GROJsonTypeObject) {
						valueToSet = [NSMutableArray arrayWithCapacity:array.count];
						Class arrayClass = classForKeyWithTarget(key, target);
						[self map:actualValue toArray:valueToSet withClass:arrayClass];
					}
					else {
						// do nothing - it is an array of basic (or wrapped) types (or should be)
						valueToSet = actualValue;
					}
					break;
				}
				case GROTargetTypeBasicOrWrappedValue:
				{
					valueToSet = actualValue;
					break;
				}
			}
			if (valueToSet || !ignoreNulls) {
				[target setValue:valueToSet forKey:propertyName];
			}
		}
	}
}

- (void) map:(NSArray *)source toArray:(NSMutableArray *)array withClass:(Class)clazz {
	if (source == nil) @throw errorWithCodeAndDescription(GROMapperErrorCodeSourceArrayIsNil, @"source array is nil");
	if (array == nil) @throw errorWithCodeAndDescription(GROMapperErrorCodeTargetArrayIsNil, @"target array is nil");
	BOOL respondsToCustomClass = [clazz respondsToSelector:@selector(concreteClassForObject:)];
	for (id item in source) {
		id targetItem = nil;
		if (respondsToCustomClass) {
			Class concreteClass = [clazz concreteClassForObject:item];
			targetItem = [[concreteClass alloc] init];
		}
		else {
			targetItem = [[clazz alloc] init];
		}
		if (!targetItem) @throw errorWithCodeAndDescription(GROMapperErrorCodeCouldNotCreateInstanceOfMappedClass, @"could not create object from class: %@", clazz);
		[array addObject:targetItem];
		[self map:item toObject:targetItem];
	}
}

- (id) jsonObjectFor:(id)source error:(NSError *__autoreleasing *)error {
	id rootObj = nil;
	@try {
		if (source == nil) @throw  errorWithCodeAndDescription(GROMapperErrorCodeSourceObjectIsNil, @"object to convert to JSON is nil");

		rootObj = [self convertToJSON:source];

	} @catch (NSError *thrown) {
		if (error) {
			*error = thrown;
		}
		rootObj = nil;
	} @catch (NSException *exception) {
		NSError *toRaise = nil;
		if ([exception.name isEqualToString:NSUndefinedKeyException]) {
			NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:exception.userInfo];
			userInfo[NSLocalizedDescriptionKey] = exception.reason;
			toRaise = [NSError errorWithDomain:GROMapperErrorDomain code:GROMapperErrorCodeNotKeyValueCodingCompliant userInfo:userInfo];
		}
		else {
			NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:exception.userInfo];
			userInfo[NSLocalizedDescriptionKey] = exception.reason;
			toRaise = [NSError errorWithDomain:GROMapperErrorDomain code:GROMapperErrorCodeGeneralError userInfo:userInfo];
		}
		if (error) {
			*error = toRaise;
		}
		rootObj = nil;
	} @finally {

	}
	return rootObj;
}

- (id) convertToJSON:(id)source {
	id convertedObj = nil;
	switch (sourceObjectType(source)) {
		case GROSourceTypeUnknown:
			break;
		case GROSourceTypeDictionary:
		{
			NSDictionary *sourceDict = source;
			convertedObj = [NSMutableDictionary dictionaryWithCapacity:sourceDict.count];
			NSMutableDictionary *convertedDict = convertedObj;
			[sourceDict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
				convertedDict[key] = [self convertToJSON:obj];
			}];
			break;
		}
		case GROSourceTypeArray:
		{
			NSArray *sourceArray = source;
			convertedObj = [NSMutableArray arrayWithCapacity:10];
			NSMutableArray *convertedArray = convertedObj;
			for (id object in sourceArray) {
				[convertedArray addObject:[self convertToJSON:object]];
			}
			break;
		}
		case GROSourceTypeCustomObject:
		{
			convertedObj = [self convertCustomObject:source];
			break;
		}
		case GROSourceTypeString:
			convertedObj = source;
			break;
		case GROSourceTypeNumber:
			convertedObj = source;
			break;
		case GROSourceTypePrimitive:
			break;
		case GROSourceTypeNull:
			convertedObj = [NSNull null];
			break;
		case GROSourceTypeNeedsConversionBlock:
			break;
		case GROSourceTypeInconvertibleValue:
			break;
	}
	return convertedObj;
}

- (NSMutableDictionary *) convertCustomObject:(id)customObj {
	Class customClass = [customObj class];
	NSSet<NSString*> *toInclude = nil;
	NSSet<NSString*> *toExclude = nil;
	unsigned int count = 0;

	if ([customClass respondsToSelector:@selector(excludePropertiesFromJSON)]) {
		toExclude = [customClass excludePropertiesFromJSON];
	}
	else if ([customClass respondsToSelector:@selector(includePropertiesInJSON)]) {
		toInclude = [customClass includePropertiesInJSON];
	}

	objc_property_t *propList = class_copyPropertyList(customClass, &count);
	NSMutableDictionary *convertedObj = [NSMutableDictionary dictionaryWithCapacity:count];
	for (int i = 0; i < count; i++) {
		objc_property_t property = propList[i];
		NSString *propName = [NSString stringWithUTF8String:property_getName(property)];
		if (toInclude != nil && [toInclude containsObject:propName] == NO) {
			continue;
		}
		if (toExclude != nil && [toExclude containsObject:propName] == YES) {
			continue;
		}
		const char *attr = property_getAttributes(property);
		GROSourceType propType = sourceTypeFromAttributes(attr);
		if (propType == GROSourceTypeInconvertibleValue) {
			DDLogInfo(@"property '%@' (@encode-type '%s') from class '%@' cannot be converted to JSON", propName, attr, NSStringFromClass(customClass));
			continue;
		}
		NSString *key = propName;
		// first check to see if there should be a different name for this object in the JSON
		SEL selector = NSSelectorFromString([KEY_MAP_PREFIX stringByAppendingString:propName]);
		if ([customObj respondsToSelector:selector]) {
			IMP imp = class_getMethodImplementation(customClass, selector);
			NSString* (*func)(id, SEL) = (void *)imp;
			key = func(customObj, selector);
		}
		selector = NSSelectorFromString([JSON_CONVERSION_PREFIX stringByAppendingString:propName]);
		if ([customObj respondsToSelector:selector]) {
			IMP imp = class_getMethodImplementation(customClass, selector);
			id (*func)(id, SEL) = (void *)imp;
			id (^converterBlock)(void) = func(customObj, selector);
			if (converterBlock) {
				id value = converterBlock();
				if (value && jsonType(value) != GROJsonTypeUnknown) {
					convertedObj[key] = value;
				}
				else if (value) {
					DDLogWarn(@"converter block for '%@' returned an invalid JSON value ('%@') of type %@", propName, value, NSStringFromClass([value class]));
				}
			}
			else {
				DDLogWarn(@"converter block for '%@' didn't return a valid block, value will not be converted", propName);
			}
			continue;
		}
		else if (propType == GROSourceTypePrimitive) {
			convertedObj[key] = [customObj valueForKey:propName];
		}
		else if (propType == GROSourceTypeCustomObject) {
			convertedObj[key] = [self convertToJSON:[customObj valueForKey:propName]];
		}
		else if (propType == GROSourceTypeNeedsConversionBlock) {
			DDLogInfo(@"property '%@' with @encode-type '%s' will not be converted to JSON because no conversion block was specified", propName, attr);
		}
	}
	if (propList) {
		free(propList);
	}
	return convertedObj;
}

@end


text:
Reports hashCode() being called
on an array. To get the same hash code for two arrays
with identical contents call Arrays.hashCode().
Use Arrays.deepHashCode() to calculate the hash
code of a multi-dimensional array.

New in 10.5, Powered by InspectionGadgets

redpajama_set_name: RedPajamaGithub


text:
#include <iostream>
#include <string>
#include <CGAL/internal/Surface_mesh_segmentation/K_means_clustering.h>
typedef CGAL::internal::K_means_clustering K_means;
/**
 * Test where number of points equal to number of centers,
 * Specifically useful for testing random and plus initializations (i.e. Selector class)
 */

int main(void)
{
  for(std::size_t init_type = 0; init_type < 2; ++init_type)
  {
    K_means::Initialization_types init_type_enum = init_type == 0 ? K_means::RANDOM_INITIALIZATION :
                                                                    K_means::PLUS_INITIALIZATION;
    // Test case: number of points equals to number of clusters
    //            and all points are unique
    for(std::size_t center_size = 1; center_size < 100; ++center_size)
    {
      // unique point generate
      std::vector<double> points;
      for(std::size_t i = 0; i < center_size; ++i) {
        points.push_back(static_cast<double>(i));
      }

      // test kmeans, expected result: each point has its own cluster
      K_means kmeans(center_size, points, init_type_enum);
      std::vector<std::size_t> center_ids;
      kmeans.fill_with_center_ids(center_ids);

      for(std::size_t i = 0; i < center_size -1; ++i) {
        if(center_ids[i] >= center_ids[i +1]) // center ids are ordered according to mean
        {                                     // and since points are generated ascendingly ...
          std::string init_type_s = init_type_enum == K_means::RANDOM_INITIALIZATION ? "Random " :
                                                                                "Plus plus ";
          std::cerr << "Init type: " << init_type_s << "center size: "  << center_size << std::endl;
          CGAL_assertion(false);
        }
      }
    }
  }
}


text:
void outputXML(std::vector<XMLSerializable*> & vObjects, std::ostream & output);

#endif


text:
package kvm

import (
	"fmt"

	"github.com/apigee/apigeecli/apiclient"
	"github.com/apigee/apigeecli/client/kvm"
	"github.com/spf13/cobra"
)

//Cmd to create kvms
var CreateCmd = &cobra.Command{
	Use:   "create",
	Short: "Create a KV Map",
	Long:  "Create a KV Map",
	Args: func(cmd *cobra.Command, args []string) (err error) {
		if env != "" {
			apiclient.SetApigeeEnv(env)
		}
		if env != "" && proxyName != "" {
			return fmt.Errorf("proxy and env flags cannot be used together")
		}
		return apiclient.SetApigeeOrg(org)
	},
	RunE: func(cmd *cobra.Command, args []string) (err error) {
		_, err = kvm.Create(proxyName, name, true)
		return
	},
}

func init() {

	CreateCmd.Flags().StringVarP(&env, "env", "e",
		"", "Environment name")
	CreateCmd.Flags().StringVarP(&proxyName, "proxy", "p",
		"", "API Proxy name")
	CreateCmd.Flags().StringVarP(&name, "name", "n",
		"", "KVM Map name")

	_ = CreateCmd.MarkFlagRequired("name")
}


text:
package me.graduation.domain.service.verified.organization;

import me.graduation.domain.model.verified.VerifiedType;
import me.graduation.domain.model.verified.organization.IOrganizationVerifiedRepository;
import me.graduation.domain.model.verified.organization.OrganizationVerified;
import me.graduation.domain.service.NoFoundException;
import me.graduation.infrastructure.persistence.hibernate.generic.Pagination;
import me.graduation.interfaces.verified.web.organization.command.CreateOrganizationCommand;
import me.graduation.interfaces.verified.web.organization.command.EditOrganizationCommand;
import me.graduation.interfaces.verified.web.organization.command.ListCommand;
import org.hibernate.FetchMode;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by ivan_ on 2015/4/10.
 */
@Service("organizationVerifiedService")
@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
public class OrganizationVerifiedService implements IOrganizationVerifiedService {

    @Autowired
    private IOrganizationVerifiedRepository<OrganizationVerified, String> organizationVerifiedRepository;

    @Override
    public OrganizationVerified findById(String id) {
        OrganizationVerified organizationVerified = organizationVerifiedRepository.get(id);
        if (null == organizationVerified) {
            throw new NoFoundException("没有发现该审核信息");
        }
        return organizationVerified;
    }

    @Override
    public Pagination<OrganizationVerified> pagination(ListCommand command) {

        command.setPageSize(10);

        List<Criterion> criterionList = new ArrayList<Criterion>();

        Criterion[] restrictions = null;
        int size = criterionList.size();
        if (size> 0) {
            restrictions = new Criterion[size];
            criterionList.toArray(restrictions);
        }

        Order[] orders = {Order.desc("createdDate")};

        Map<String, FetchMode> fetchModeMap = new HashMap<String, FetchMode>();
        fetchModeMap.put("creator", FetchMode.JOIN);

        return organizationVerifiedRepository.pagination(command.getPage(), command.getPageSize(), restrictions, orders, fetchModeMap);
    }

    @Override
    public void edit(EditOrganizationCommand command) {

        OrganizationVerified organizationVerified = this.findById(command.getId());

        organizationVerified.setStatus(command.getStatus());
        organizationVerified.setType(VerifiedType.ORGANIZATION_VERIFIED);
        organizationVerified.setCreatedDate(new Date());
        organizationVerified.setCreator(command.getCreator());
        organizationVerified.setSource(command.getSource());
        organizationVerified.setDestination(command.getDestination());
        organizationVerified.setReason(command.getReason());

        organizationVerifiedRepository.update(organizationVerified);
    }

    @Override
    public void create(CreateOrganizationCommand command) {

        OrganizationVerified organizationVerified = new OrganizationVerified();
        organizationVerified.setStatus(Boolean.FALSE);
        organizationVerified.setType(VerifiedType.ORGANIZATION_VERIFIED);
        organizationVerified.setCreatedDate(new Date());
        organizationVerified.setCreator(command.getCreator());
        organizationVerified.setSource(command.getSource());
        organizationVerified.setDestination(command.getDestination());
        organizationVerified.setReason(command.getReason());

        organizationVerifiedRepository.save(organizationVerified);
    }

    @Override
    public void delete(String id) {
        OrganizationVerified organizationVerified = this.findById(id);
        organizationVerifiedRepository.delete(organizationVerified);
    }
}


text:
<title>libogg - function - ogg_page_granulepos</title>
<link rel=stylesheet href="style.css" type="text/css">

libogg documentation

libogg release 1.3.4 - 20190830

ogg_page_granulepos

declared in "ogg/ogg.h";

Returns the exact granular position of the packet data contained at the end of this page.

This is useful for tracking location when seeking or decoding.

For example, in audio codecs this position is the pcm sample number and in video this is the frame number.

ogg_in64_t ogg_page_granulepos(ogg_page *og);

Parameters

og

Pointer to the current ogg_page struct.

Return Values

n is the specific last granular position of the decoded data contained in the page.

copyright © 2000-2019 Xiph.Org Foundation

Ogg Container Format

libogg documentation

libogg release 1.3.4 - 20190830


text:
to run the notebooks, first install [ipython](https://ipython.org/)

`pip install "ipython[all]"`

and then run the following command

`ipython notebook`


text:
package com.health.kidneystones.reducestones.Advice;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.kidneystones.reducestones.R;

import java.util.List;

/**
 * Created by Shakeel on 11/06/2017.
 */

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.CategoriesViewHolder> {

    public class CategoriesViewHolder extends RecyclerView.ViewHolder {

        CardView cardView;
        TextView cardTitle;
        TextView cardDesc;
        ImageView cardImage;

        public CategoriesViewHolder(View itemView) {
            super(itemView);
            //Gets the xml layouts of the specified objects
             cardView = (CardView) itemView.findViewById(R.id.cv);
             cardTitle = (TextView) itemView.findViewById(R.id.card_title);
             cardDesc = (TextView) itemView.findViewById(R.id.card_description);
             cardImage = (ImageView) itemView.findViewById(R.id.card_image);
        }
    }

    private List<Categories> categories;
    private Context context;

    RecyclerAdapter(List<Categories> categories, Context context) {
        this.categories = categories;
        this.context = context;
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        //attaches the activity to a recycle view
        super.onAttachedToRecyclerView(recyclerView);
    }

    @Override
    public CategoriesViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        //Inflates the layout with the layout file
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cardview_items, viewGroup, false);
        CategoriesViewHolder cvh = new CategoriesViewHolder(v);
        return cvh;
    }

    @Override
    public void onBindViewHolder(final CategoriesViewHolder categoriesViewHolder, final int i) {
        categoriesViewHolder.cardTitle.setText(categories.get(i).title);
        categoriesViewHolder.cardDesc.setText(categories.get(i).description);
        categoriesViewHolder.cardImage.setImageResource(categories.get(i).card_photo);

        //Onclicklistener for when the picture is touched, should change to the cardview
        categoriesViewHolder.cardImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //open the specified activity for each cardview
                if (i == 0) {
                    Intent intent = new Intent(context, General.class);
                    v.getContext().startActivity(intent);
                }
                if (i == 1) {
                    Intent intent = new Intent(context, GeneralAdvice.class);
                    v.getContext().startActivity(intent);
                }
                if (i == 2) {
                    Intent intent = new Intent(context, Diet.class);
                    v.getContext().startActivity(intent);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return categories.size();
    }
}


text:
package v1

import (
	internalinterfaces "github.com/contiv/vpp/plugins/crd/pkg/client/informers/externalversions/internalinterfaces"
)

// Interface provides access to all the informers in this group version.
type Interface interface {
	// CustomConfigurations returns a CustomConfigurationInformer.
	CustomConfigurations() CustomConfigurationInformer
	// CustomNetworks returns a CustomNetworkInformer.
	CustomNetworks() CustomNetworkInformer
	// ExternalInterfaces returns a ExternalInterfaceInformer.
	ExternalInterfaces() ExternalInterfaceInformer
	// ServiceFunctionChains returns a ServiceFunctionChainInformer.
	ServiceFunctionChains() ServiceFunctionChainInformer
}

type version struct {
	factory          internalinterfaces.SharedInformerFactory
	namespace        string
	tweakListOptions internalinterfaces.TweakListOptionsFunc
}

// New returns a new Interface.
func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {
	return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}
}

// CustomConfigurations returns a CustomConfigurationInformer.
func (v *version) CustomConfigurations() CustomConfigurationInformer {
	return &customConfigurationInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
}

// CustomNetworks returns a CustomNetworkInformer.
func (v *version) CustomNetworks() CustomNetworkInformer {
	return &customNetworkInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
}

// ExternalInterfaces returns a ExternalInterfaceInformer.
func (v *version) ExternalInterfaces() ExternalInterfaceInformer {
	return &externalInterfaceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
}

// ServiceFunctionChains returns a ServiceFunctionChainInformer.
func (v *version) ServiceFunctionChains() ServiceFunctionChainInformer {
	return &serviceFunctionChainInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
}


text:
package br.edu.fametro.portal.model.atores;

import java.util.Calendar;

import br.edu.fametro.portal.model.Endereco;
import br.edu.fametro.portal.model.Sistema;
import br.edu.fametro.portal.model.Telefone;
import br.edu.fametro.portal.model.enums.Curso;
import br.edu.fametro.portal.model.enums.TipoUsuario;

public class Aluno extends Pessoa implements AcessaSistema {
	private long id;
	private String matricula;
	private Curso curso;
	private Endereco endereco;
	private String email;
	private Telefone residencial;
	private Telefone celular;
	private Telefone opcional;
	private Usuario usuario;

	public Aluno(long id) {
		this.id = id;
		matricula = Sistema.geraMatricula(TipoUsuario.ALUNO, Calendar.getInstance().getTime(), id);
		usuario = Sistema.geraPrimeiroAcesso(matricula, TipoUsuario.ALUNO);
	}

	public long getId() {
		return id;
	}

	public String getMatricula() {
		return matricula;
	}

	public Curso getCurso() {
		return curso;
	}

	public void setCurso(Curso curso) {
		this.curso = curso;
	}

	public Endereco getEndereco() {
		return endereco;
	}

	public void setEndereco(Endereco endereco) {
		this.endereco = endereco;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Telefone getResidencial() {
		return residencial;
	}

	public void setResidencial(Telefone residencial) {
		this.residencial = residencial;
	}

	public Telefone getCelular() {
		return celular;
	}

	public void setCelular(Telefone celular) {
		this.celular = celular;
	}

	public Telefone getOpcional() {
		return opcional;
	}

	public void setOpcional(Telefone opcional) {
		this.opcional = opcional;
	}

	public Usuario getUsuario() {
		return usuario;
	}

	public void setUsuario(Usuario usuario) {
		this.usuario = usuario;
	}

	@Override
	public String toString() {
		return "Aluno [matricula=" + matricula + ", curso=" + curso + ", endereco=" + endereco + ", email=" + email
				+ ", residencial=" + residencial + ", celular=" + celular + ", opcional=" + opcional + ", usuario="
				+ usuario + "]";
	}
}


text:
#ifndef __ctkModuleDescriptionExecutionInterface_h
#define __ctkModuleDescriptionExecutionInterface_h

#include <QVariant>

#include "CTKModuleDescriptionExport.h"
#include "ctkModuleDescription.h"

/**
 * \brief Interface of ModuleDescription execution
 *
 * This allows to execute a filter using an executable application
 * or a DLL Command Line Plugin
 */
class CTK_MODULDESC_EXPORT ctkModuleDescriptionExecutionInterface : public QObject
{
    Q_OBJECT
public:
  ctkModuleDescriptionExecutionInterface(){};
  ~ctkModuleDescriptionExecutionInterface(){};

  //! Set input Module Description
  virtual void setModuleDescription(const ctkModuleDescription &val) = 0;

  //!
  virtual void Update( ) = 0;
};

#endif


text:
package com.ibm.watson.app.qaclassifier.selenium;

import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.ibm.watson.app.qaclassifier.selenium.drivers.Browser;
import com.ibm.watson.app.qaclassifier.selenium.drivers.Device;
import com.ibm.watson.app.qaclassifier.selenium.drivers.Multiplatform;
import com.ibm.watson.app.qaclassifier.selenium.drivers.Multiplatform.InjectDriver;
import com.ibm.watson.app.qaclassifier.selenium.drivers.Multiplatform.Platform;
import com.ibm.watson.app.qaclassifier.selenium.drivers.Multiplatform.Platforms;

@RunWith(Multiplatform.class)
@Platforms(
    devices = {Device.IPHONE_6, Device.IPHONE_4},
    fastPlatforms = { @Platform( browser = Browser.FIREFOX, device = Device.IPHONE_6) }
)
public class MenuMobileIT {
    @InjectDriver
    public WebDriver driver;

    @Test
    public void clickMenuIconShowsMenuOnMobile() {
        WebElement menuIconImg = driver.findElement(By.className("menuIconImg"));
        WebElement menuList = driver.findElement(By.className("menu-list"));

        // Click the menu icon, it should show the menu list
        menuIconImg.click();
        assertTrue("After clicking on the menu icon, the menu list is shown", menuList.isDisplayed());
    }

    @Test
    public void clickOnMenuOptionShowsContent() {
        WebElement menuIconImg = driver.findElement(By.className("menuIconImg"));
        WebElement menuList = driver.findElement(By.className("menu-list"));
        WebElement menuContent = driver.findElement(By.className("menu-content"));
        // Click the menu icon, it should show the menu list
        menuIconImg.click();

        //Get list of menu options
        List<WebElement> menuOptions = menuList.findElements(By.xpath(".//ul/li"));
        WebElement firstMenuOption = menuOptions.get(2); // Get content of "About" option that has content
        firstMenuOption.click();

        new WebDriverWait(driver, 1).until(ExpectedConditions.visibilityOf(menuContent));
        assertTrue("After clicking on the menu option, the menu option content is displayed", menuContent.isDisplayed());
    }

	@Test
    public void clickOnMenuOptionRedirectsPage() throws InterruptedException {
		WebElement menuIconImg = driver.findElement(By.className("menuIconImg"));
        WebElement menuList = driver.findElement(By.className("menu-list"));
        assertTrue("Menu Icon is displayed",
        		menuIconImg.isDisplayed());
        // Click the menu icon, it should show the menu list
        menuIconImg.click();

        // Unclear exactly why this is required.
        // Without this delay the findElements call might return less than the expected number of elements,
        // or some of the elements might not have any text.
        Thread.sleep(1000);

        //Get list of menu options
        List<WebElement> menuOptions = menuList.findElements(By.xpath(".//ul/li"));
        assertThat("Expect four menu options", menuOptions, hasSize(4));

        int menuIndex = 1;
        WebElement documentationOption = menuOptions.get(menuIndex); // "Documentation" option that will redirect to different page
        assertThat("Unexpected text for item at position " + menuIndex, documentationOption.getText(), is("Documentation"));
        documentationOption.click();

        //New tab with documentation is opened
        CommonFunctions.switchTabs(driver);
        assertThat("After clicking on the menu option, page is redirected",
        		driver.getTitle(), is("Natural Language Classifier service documentation | Watson Developer Cloud"));
        driver.close();
    }

}


text:
package com.alachisoft.tayzgrid.serialization.standard.io.surrogates;

import com.alachisoft.tayzgrid.serialization.core.io.CacheObjectInput;
import com.alachisoft.tayzgrid.serialization.core.io.CacheObjectOutput;
import com.alachisoft.tayzgrid.serialization.core.io.TypeSurrogateConstants;
import com.alachisoft.tayzgrid.serialization.core.io.surrogates.BuiltinSerializationSurrogate;
import com.alachisoft.tayzgrid.serialization.core.io.surrogates.CacheIOException;
import com.alachisoft.tayzgrid.serialization.core.io.surrogates.CacheInstantiationException;
import com.alachisoft.tayzgrid.serialization.core.io.surrogates.SerializationSurrogate;
import com.alachisoft.tayzgrid.serialization.core.io.surrogates.SerializationSurrogateImpl;
import com.alachisoft.tayzgrid.serialization.standard.io.TypeSurrogateSelectorImpl;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;

/**
 * ObjectArraySerializationSurrogate is responsible for writing and reading instances of Object[] classe.
 *
 * @version 1.0, September 18, 2008
 */
public class ObjectArraySerializationSurrogate
        extends SerializationSurrogateImpl
        implements BuiltinSerializationSurrogate
{

    /**
     * Specify a hard handle for this surrogate
     */
    public static final short HARD_HANDLE = TypeSurrogateConstants.FirstTypeHandle + 0x03;

    /**
     * Creates a new instance of ObjectArraySerializationSurrogate
     */
    public ObjectArraySerializationSurrogate()
    {
        super(Object[].class);
    }

    /**
     * Creates instance of type returned by getRealClass(). This is different from NxSerializationSurrogateBase.createTypeInstance() in the sense that an NCacheObjectInput object
     * is passed as parameter that can be used to read creation specific information from the stream. For example it can be used to read the length of the array before actually
     * reading the values.
     *
     * The default implementation simply delegates to super.createTypeInstance().
     *
     * @param input stream reader
     * @throws CacheInstantiationException Object creation related exceptions.
     * @return Object that this surrogate must deserialize
     */
    @Override
    public Object instantiate(CacheObjectInput input)
            throws CacheInstantiationException
    {
        try
        {
            int length = input.readInt();
            return new Object[length];
        }
        catch (IOException ex)
        {
            throw new CacheInstantiationException(ex);
        }
    }

    /**
     * Read an object of type returned by getRealClass() from the stream reader. A fresh instance of the object is passed as parameter. The surrogate should populate fields in the
     * object from data on the stream
     *
     * @param input stream reader
     * @param graph a fresh instance of the object that the surrogate must deserialize.
     * @throws CacheInstantiationException Object creation related exceptions.
     * @throws CacheIOException Any of the usual Input/Output related exceptions.
     * @return object read from the stream reader
     */
    public Object readDirect(CacheObjectInput input, Object graph)
            throws CacheInstantiationException, CacheIOException
    {
        try
        {
            Object[] array = (Object[]) graph;

            TypeSurrogateSelectorImpl mSelector = TypeSurrogateSelectorImpl.getDefault();
            short typeHandle = input.readShort();
            SerializationSurrogate surrogate = mSelector.getSurrogateForTypeHandle(typeHandle, input.getCacheContext());

            if (surrogate == null)
            {
                surrogate = mSelector.GetSurrogateForSubTypeHandle(typeHandle, input.readShort(), input.getCacheContext());
            }

            Class className = surrogate.getRealClass();

            Object obj = Array.newInstance(className, array.length);

            int len = array.length;
            for (int i = 0; i < len; i++)
            {
                Array.set(obj, i, input.readObject());
            }

            return obj;
        }
        catch (ClassNotFoundException ex)
        {
            throw new CacheInstantiationException(ex);
        }
        catch (IOException ex)
        {
            throw new CacheIOException(ex);
        }
    }

    /**
     * Write an object of type returned by getRealClass() to the stream writer
     *
     * @param output stream writer
     * @param graph object to be written to the stream reader
     * @throws CacheIOException Any of the usual Input/Output related exceptions.
     */
    public void writeDirect(CacheObjectOutput output, Object graph)
            throws CacheIOException
    {
        try
        {

            Object[] array = (Object[]) graph;
            int len = array.length;
            //length is read in SerializationSurrogateImpl ... which is wrong ... needs to be fixed for understanding and flow
            output.writeInt(len);

            TypeSurrogateSelectorImpl mSelector = TypeSurrogateSelectorImpl.getDefault();

            Object[] o = (Object[]) graph;
            Object[] tempObject = new Object[2];

            if (graph.getClass() != tempObject.getClass())
            {
                Object obj = null;
                for (int i = 0; i < o.length; i++)
                {
                    if (o[i] != null)
                    {
                        obj = o[i];
                        break;
                    }
                }
                SerializationSurrogate surrogateTemp = mSelector.getSurrogateForObject(obj, output.getCacheContext());
                surrogateTemp.writeHandle(output, obj);
                if (surrogateTemp.getSubHandle() > 0)
                {
                    surrogateTemp.writeSubHandle(output, obj);
                }
            }
            else
            {
                SerializationSurrogate surrogateTemp = mSelector.getDefaultSurrogate();
                surrogateTemp.writeHandle(output, new Object());
            }

            for (int i = 0; i < len; i++)
            {
                try
                {
                    output.writeObject(array[i]);

                }catch (IOException ex)
                {
                    throw new CacheIOException(ex);
                }
            }
        }
        catch (IOException ex)
        {
            throw new CacheIOException(ex);
        }
    }

    @Override
    public void skipDirect(CacheObjectInput input, Object graph) throws CacheInstantiationException, CacheIOException
    {
        try
        {
            Object[] array = (Object[]) graph;

            TypeSurrogateSelectorImpl mSelector = TypeSurrogateSelectorImpl.getDefault();
            short typeHandle = input.readShort();
            SerializationSurrogate surrogate = mSelector.getSurrogateForTypeHandle(typeHandle, input.getCacheContext());

            if (surrogate == null)
            {
                surrogate = mSelector.GetSurrogateForSubTypeHandle(typeHandle, input.readShort(), input.getCacheContext());
            }

            Class className = surrogate.getRealClass();

            int len = array.length;
            for (int i = 0; i < len; i++)
            {
                input.skipObject();
            }
        }
        catch (IOException ex)
        {
            throw new CacheIOException(ex);
        }
    }
}


text:
try:
    # installed by bootstrap.py
    import sqla_plugin_base as plugin_base
except ImportError:
    # assume we're a package, use traditional import
    from . import plugin_base

import argparse
import collections
from functools import update_wrapper
import inspect
import itertools
import operator
import os
import re
import sys

import pytest

try:
    import typing
except ImportError:
    pass
else:
    if typing.TYPE_CHECKING:
        from typing import Sequence

try:
    import xdist  # noqa

    has_xdist = True
except ImportError:
    has_xdist = False

def pytest_addoption(parser):
    group = parser.getgroup("sqlalchemy")

    def make_option(name, **kw):
        callback_ = kw.pop("callback", None)
        if callback_:

            class CallableAction(argparse.Action):
                def __call__(
                    self, parser, namespace, values, option_string=None
                ):
                    callback_(option_string, values, parser)

            kw["action"] = CallableAction

        zeroarg_callback = kw.pop("zeroarg_callback", None)
        if zeroarg_callback:

            class CallableAction(argparse.Action):
                def __init__(
                    self,
                    option_strings,
                    dest,
                    default=False,
                    required=False,
                    help=None,  # noqa
                ):
                    super(CallableAction, self).__init__(
                        option_strings=option_strings,
                        dest=dest,
                        nargs=0,
                        const=True,
                        default=default,
                        required=required,
                        help=help,
                    )

                def __call__(
                    self, parser, namespace, values, option_string=None
                ):
                    zeroarg_callback(option_string, values, parser)

            kw["action"] = CallableAction

        group.addoption(name, **kw)

    plugin_base.setup_options(make_option)
    plugin_base.read_config()

def pytest_configure(config):
    if hasattr(config, "slaveinput"):
        plugin_base.restore_important_follower_config(config.slaveinput)
        plugin_base.configure_follower(config.slaveinput["follower_ident"])
    else:
        if config.option.write_idents and os.path.exists(
            config.option.write_idents
        ):
            os.remove(config.option.write_idents)

    plugin_base.pre_begin(config.option)

    plugin_base.set_coverage_flag(
        bool(getattr(config.option, "cov_source", False))
    )

    plugin_base.set_fixture_functions(PytestFixtureFunctions)

def pytest_sessionstart(session):
    plugin_base.post_begin()

def pytest_sessionfinish(session):
    plugin_base.final_process_cleanup()

if has_xdist:
    import uuid

    def pytest_configure_node(node):
        # the master for each node fills slaveinput dictionary
        # which pytest-xdist will transfer to the subprocess

        plugin_base.memoize_important_follower_config(node.slaveinput)

        node.slaveinput["follower_ident"] = "test_%s" % uuid.uuid4().hex[0:12]
        from sqlalchemy.testing import provision

        provision.create_follower_db(node.slaveinput["follower_ident"])

    def pytest_testnodedown(node, error):
        from sqlalchemy.testing import provision

        provision.drop_follower_db(node.slaveinput["follower_ident"])

def pytest_collection_modifyitems(session, config, items):
    # look for all those classes that specify __backend__ and
    # expand them out into per-database test cases.

    # this is much easier to do within pytest_pycollect_makeitem, however
    # pytest is iterating through cls.__dict__ as makeitem is
    # called which causes a "dictionary changed size" error on py3k.
    # I'd submit a pullreq for them to turn it into a list first, but
    # it's to suit the rather odd use case here which is that we are adding
    # new classes to a module on the fly.

    rebuilt_items = collections.defaultdict(
        lambda: collections.defaultdict(list)
    )

    items[:] = [
        item
        for item in items
        if isinstance(item.parent, pytest.Instance)
        and not item.parent.parent.name.startswith("_")
    ]

    test_classes = set(item.parent for item in items)
    for test_class in test_classes:
        for sub_cls in plugin_base.generate_sub_tests(
            test_class.cls, test_class.parent.module
        ):
            if sub_cls is not test_class.cls:
                per_cls_dict = rebuilt_items[test_class.cls]

                # in pytest 5.4.0
                # for inst in pytest.Class.from_parent(
                #     test_class.parent.parent, name=sub_cls.__name__
                # ).collect():

                for inst in pytest.Class(
                    sub_cls.__name__, parent=test_class.parent.parent
                ).collect():
                    for t in inst.collect():
                        per_cls_dict[t.name].append(t)

    newitems = []
    for item in items:
        if item.parent.cls in rebuilt_items:
            newitems.extend(rebuilt_items[item.parent.cls][item.name])
        else:
            newitems.append(item)

    # seems like the functions attached to a test class aren't sorted already?
    # is that true and why's that? (when using unittest, they're sorted)
    items[:] = sorted(
        newitems,
        key=lambda item: (
            item.parent.parent.parent.name,
            item.parent.parent.name,
            item.name,
        ),
    )

def pytest_pycollect_makeitem(collector, name, obj):

    if inspect.isclass(obj) and plugin_base.want_class(name, obj):

        # in pytest 5.4.0
        # return [
        #     pytest.Class.from_parent(collector,
        # name=parametrize_cls.__name__)
        #     for parametrize_cls in _parametrize_cls(collector.module, obj)
        # ]

        return [
            pytest.Class(parametrize_cls.__name__, parent=collector)
            for parametrize_cls in _parametrize_cls(collector.module, obj)
        ]
    elif (
        inspect.isfunction(obj)
        and isinstance(collector, pytest.Instance)
        and plugin_base.want_method(collector.cls, obj)
    ):
        # None means, fall back to default logic, which includes
        # method-level parametrize
        return None
    else:
        # empty list means skip this item
        return []

_current_class = None

def _parametrize_cls(module, cls):
    """implement a class-based version of pytest parametrize."""

    if "_sa_parametrize" not in cls.__dict__:
        return [cls]

    _sa_parametrize = cls._sa_parametrize
    classes = []
    for full_param_set in itertools.product(
        *[params for argname, params in _sa_parametrize]
    ):
        cls_variables = {}

        for argname, param in zip(
            [_sa_param[0] for _sa_param in _sa_parametrize], full_param_set
        ):
            if not argname:
                raise TypeError("need argnames for class-based combinations")
            argname_split = re.split(r",\s*", argname)
            for arg, val in zip(argname_split, param.values):
                cls_variables[arg] = val
        parametrized_name = "_".join(
            # token is a string, but in py2k py.test is giving us a unicode,
            # so call str() on it.
            str(re.sub(r"\W", "", token))
            for param in full_param_set
            for token in param.id.split("-")
        )
        name = "%s_%s" % (cls.__name__, parametrized_name)
        newcls = type.__new__(type, name, (cls,), cls_variables)
        setattr(module, name, newcls)
        classes.append(newcls)
    return classes

def pytest_runtest_setup(item):
    # here we seem to get called only based on what we collected
    # in pytest_collection_modifyitems.   So to do class-based stuff
    # we have to tear that out.
    global _current_class

    if not isinstance(item, pytest.Function):
        return

    # ... so we're doing a little dance here to figure it out...
    if _current_class is None:
        class_setup(item.parent.parent)
        _current_class = item.parent.parent

        # this is needed for the class-level, to ensure that the
        # teardown runs after the class is completed with its own
        # class-level teardown...
        def finalize():
            global _current_class
            class_teardown(item.parent.parent)
            _current_class = None

        item.parent.parent.addfinalizer(finalize)

    test_setup(item)

def pytest_runtest_teardown(item):
    # ...but this works better as the hook here rather than
    # using a finalizer, as the finalizer seems to get in the way
    # of the test reporting failures correctly (you get a bunch of
    # py.test assertion stuff instead)
    test_teardown(item)

def test_setup(item):
    plugin_base.before_test(
        item, item.parent.module.__name__, item.parent.cls, item.name
    )

def test_teardown(item):
    plugin_base.after_test(item)

def class_setup(item):
    plugin_base.start_test_class(item.cls)

def class_teardown(item):
    plugin_base.stop_test_class(item.cls)

def getargspec(fn):
    if sys.version_info.major == 3:
        return inspect.getfullargspec(fn)
    else:
        return inspect.getargspec(fn)

def _pytest_fn_decorator(target):
    """Port of langhelpers.decorator with pytest-specific tricks."""

    from sqlalchemy.util.langhelpers import format_argspec_plus
    from sqlalchemy.util.compat import inspect_getfullargspec

    def _exec_code_in_env(code, env, fn_name):
        exec(code, env)
        return env[fn_name]

    def decorate(fn, add_positional_parameters=()):

        spec = inspect_getfullargspec(fn)
        if add_positional_parameters:
            spec.args.extend(add_positional_parameters)

        metadata = dict(target="target", fn="fn", name=fn.__name__)
        metadata.update(format_argspec_plus(spec, grouped=False))
        code = (
            """\
def %(name)s(%(args)s):
    return %(target)s(%(fn)s, %(apply_kw)s)
"""
            % metadata
        )
        decorated = _exec_code_in_env(
            code, {"target": target, "fn": fn}, fn.__name__
        )
        if not add_positional_parameters:
            decorated.__defaults__ = getattr(fn, "im_func", fn).__defaults__
            decorated.__wrapped__ = fn
            return update_wrapper(decorated, fn)
        else:
            # this is the pytest hacky part.  don't do a full update wrapper
            # because pytest is really being sneaky about finding the args
            # for the wrapped function
            decorated.__module__ = fn.__module__
            decorated.__name__ = fn.__name__
            return decorated

    return decorate

class PytestFixtureFunctions(plugin_base.FixtureFunctions):
    def skip_test_exception(self, *arg, **kw):
        return pytest.skip.Exception(*arg, **kw)

    _combination_id_fns = {
        "i": lambda obj: obj,
        "r": repr,
        "s": str,
        "n": operator.attrgetter("__name__"),
    }

    def combinations(self, *arg_sets, **kw):
        """facade for pytest.mark.paramtrize.

        Automatically derives argument names from the callable which in our
        case is always a method on a class with positional arguments.

        ids for parameter sets are derived using an optional template.

        """
        from sqlalchemy.testing import exclusions

        if sys.version_info.major == 3:
            if len(arg_sets) == 1 and hasattr(arg_sets[0], "__next__"):
                arg_sets = list(arg_sets[0])
        else:
            if len(arg_sets) == 1 and hasattr(arg_sets[0], "next"):
                arg_sets = list(arg_sets[0])

        argnames = kw.pop("argnames", None)

        def _filter_exclusions(args):
            result = []
            gathered_exclusions = []
            for a in args:
                if isinstance(a, exclusions.compound):
                    gathered_exclusions.append(a)
                else:
                    result.append(a)

            return result, gathered_exclusions

        id_ = kw.pop("id_", None)

        tobuild_pytest_params = []
        has_exclusions = False
        if id_:
            _combination_id_fns = self._combination_id_fns

            # because itemgetter is not consistent for one argument vs.
            # multiple, make it multiple in all cases and use a slice
            # to omit the first argument
            _arg_getter = operator.itemgetter(
                0,
                *[
                    idx
                    for idx, char in enumerate(id_)
                    if char in ("n", "r", "s", "a")
                ]
            )
            fns = [
                (operator.itemgetter(idx), _combination_id_fns[char])
                for idx, char in enumerate(id_)
                if char in _combination_id_fns
            ]

            for arg in arg_sets:
                if not isinstance(arg, tuple):
                    arg = (arg,)

                fn_params, param_exclusions = _filter_exclusions(arg)

                parameters = _arg_getter(fn_params)[1:]

                if param_exclusions:
                    has_exclusions = True

                tobuild_pytest_params.append(
                    (
                        parameters,
                        param_exclusions,
                        "-".join(
                            comb_fn(getter(arg)) for getter, comb_fn in fns
                        ),
                    )
                )

        else:

            for arg in arg_sets:
                if not isinstance(arg, tuple):
                    arg = (arg,)

                fn_params, param_exclusions = _filter_exclusions(arg)

                if param_exclusions:
                    has_exclusions = True

                tobuild_pytest_params.append(
                    (fn_params, param_exclusions, None)
                )

        pytest_params = []
        for parameters, param_exclusions, id_ in tobuild_pytest_params:
            if has_exclusions:
                parameters += (param_exclusions,)

            param = pytest.param(*parameters, id=id_)
            pytest_params.append(param)

        def decorate(fn):
            if inspect.isclass(fn):
                if has_exclusions:
                    raise NotImplementedError(
                        "exclusions not supported for class level combinations"
                    )
                if "_sa_parametrize" not in fn.__dict__:
                    fn._sa_parametrize = []
                fn._sa_parametrize.append((argnames, pytest_params))
                return fn
            else:
                if argnames is None:
                    _argnames = getargspec(fn).args[1:]  # type: Sequence(str)
                else:
                    _argnames = re.split(
                        r", *", argnames
                    )  # type: Sequence(str)

                if has_exclusions:
                    _argnames += ["_exclusions"]

                    @_pytest_fn_decorator
                    def check_exclusions(fn, *args, **kw):
                        _exclusions = args[-1]
                        if _exclusions:
                            exlu = exclusions.compound().add(*_exclusions)
                            fn = exlu(fn)
                        return fn(*args[0:-1], **kw)

                    def process_metadata(spec):
                        spec.args.append("_exclusions")

                    fn = check_exclusions(
                        fn, add_positional_parameters=("_exclusions",)
                    )

                return pytest.mark.parametrize(_argnames, pytest_params)(fn)

        return decorate

    def param_ident(self, *parameters):
        ident = parameters[0]
        return pytest.param(*parameters[1:], id=ident)

    def fixture(self, *arg, **kw):
        return pytest.fixture(*arg, **kw)

    def get_current_test_name(self):
        return os.environ.get("PYTEST_CURRENT_TEST")


text:
/* jshint latedef:false */
/* jshint forin:false */
/* jshint noempty:false */

'use strict';

exports.Duration = require('./duration');


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RawNotification.BusinessLogic.BLImplements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RawNotification.BusinessLogic.BLImplements.Tests
{
    [TestClass()]
    public class NotificationBLTests
    {
        [TestMethod()]
        public void AddNotificationTest()
        {
            Assert.Fail();
        }

        [TestMethod()]
        public void GetNotificationContentTest()
        {
            Assert.Fail();
        }
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package hr;

/**
 *
 * @author etcharn1
 */
public class Employee {

    private int idNumber;
    private String name;
    private Manager manager;

    public Employee( int id, String name, Manager manager)
    {
        idNumber = id;
        this.name = name;
        this.manager = manager;
        if ( manager != null )
        {
            manager.addEmployee(this);
        }

    }

    public String toString()
    {
        return "ID: " + idNumber + " - Name: " + name;
    }

}


text:
/**
 * @since 2021-06-24
 * @author vivaxy
 */
import * as Y from 'yjs';
import updateDecoder from '../data-visualization/src/update-decoder';

const TEXT_KEY = 'text-key';

const docA = new Y.Doc();
const textA = docA.getText(TEXT_KEY);
textA.insert(0, 'XA');
const updateA = Y.encodeStateAsUpdate(docA);

const docB = new Y.Doc();
const textB = docB.getText(TEXT_KEY);
textB.insert(0, 'XB');
textB.observeDeep(function (event) {
  console.log('change', event);
});
const svB = Y.encodeStateVector(docB);

const diff1 = Y.diffUpdate(updateA, svB);
console.log('diff1', updateDecoder(docA.clientID, diff1));
console.log('diff1', updateDecoder(docB.clientID, diff1));
Y.applyUpdate(docB, diff1);
console.log('textB', textB.toString(), docB);

const docC = new Y.Doc();
// force docC to be same client as docA
docC.clientID = docA.clientID;
const textC = docC.getText(TEXT_KEY);
textC.insert(0, 'XC');
const svC = Y.encodeStateVector(docC);
const diff2 = Y.diffUpdate(updateA, svC); // cannot diff
console.log('diff2', updateDecoder(docA.clientID, diff2));
console.log('diff2', updateDecoder(docC.clientID, diff2));
Y.applyUpdate(docC, diff2);
// missing updates
console.log('textC', textC.toString(), docC);


text:
/* eslint-env node, mocha */

'use strict'

var assert = require('assert')
  , Spectcl = require('../lib/spectcl')
  , _ = require('lodash')
  , mockSpawn = require('mock-spawn')
  , vm = require('vm')

// set up the mock spawn object
var mySpawn = mockSpawn()
  , myPtySpawn = mockSpawn()
  , ttycount = 0

require('child_process').spawn = mySpawn
require('child_pty').spawn = myPtySpawn

function nodeRepl(command){
    return vm.runInNewContext(command) + '\n'
}

mySpawn.setDefault(mySpawn.simple(0,'hello'))
mySpawn.setStrategy(function (command, args) {
    switch(command){
    case 'defnotacommand':
        return function(cb){
            this.emit('error', 'error')
            return cb(8)
        }
    case 'echo':
        if(args instanceof Array){
            args = args.join(' ')
        }
        return mySpawn.simple(0,args)
    case 'node':
        return function(cb){
            var self = this
            this.stdin.destroy = function(){
                return cb(0)
            }
            this.stdout.write('>')
            this.stdin.on('data',function(s){
                if(s instanceof Buffer){
                    s = s.toString('utf8')
                }
                if(/^process.exit\(\)/.test(s)){
                    return cb(0)
                }
                var out = nodeRepl(s)
                self.stdout.write(out)
                self.stdout.write('>')
            })
        }
    case 'ls':
        if(args[0] === '-G'){
            return mySpawn.simple(0, '\u001b[33mHello\nWorld\u001b[0m')
        }
        break
    case 'bash':
        switch(args){
        case 'fixtures/test_exp_continue.sh':
        default:
            return function(cb){
                var self = this
                self.stdout.write('"Connecting" to a server:\n')
                self.stdout.write('user:')
                self.stdin.on('data', function(d){
                    d = (d.toString('utf8') || d).trim()
                    switch(d){
                    case 'foo':
                        return self.stdout.write('password:')
                    case 'bar':
                        return self.stdout.write('\n[foo@test-server]$ ')
                    case 'exit':
                        self.stdout.write('output\n')
                        self.stdout.write('exiting...')
                        return cb(0)
                    default:
                        return cb(1)
                    }
                })
            }
        }
    default:
        return mySpawn.simple(0,'hello world')
    }
})

myPtySpawn.setSignals({SIGTERM:true})
myPtySpawn.setStrategy(function (command, args) {
    switch(command){
    case 'defnotacommand':
        return function(cb){
            this.emit('error', 'error')
            return cb(8)
        }
    case 'echo':
        if(args instanceof Array){
            args = args.join(' ')
        }
        return mySpawn.simple(0,args)
    case 'node':
        return function(cb){
            var self = this
            this.stdout.ttyname = 'tty'+ttycount++
            this.stdin.destroy = function(){
                return cb(0)
            }
            this.stdout.write('>')
            this.stdin.on('data',function(s){
                if(s instanceof Buffer){
                    s = s.toString('utf8')
                }
                if(/^process.exit\(\)/.test(s)){
                    return cb(0)
                }
                var out = nodeRepl(s)
                self.stdout.write(out)
                self.stdout.write('>')
            })
        }
    case 'ls':
        if(args[0] === '-G'){
            return mySpawn.simple(0, '\u001b[33mHello\nWorld\u001b[0m')
        }
        break
    case 'bash':
        switch(args){
        case 'fixtures/test_exp_continue.sh':
        default:
            return function(cb){
                var self = this
                self.stdout.write('"Connecting" to a server:\n')
                self.stdout.write('user:')
                self.stdin.on('data', function(d){
                    d = (d.toString('utf8') || d).trim()
                    switch(d){
                    case 'foo':
                        return self.stdout.write('password:')
                    case 'bar':
                        return self.stdout.write('\n[foo@test-server]$ ')
                    case 'exit':
                        self.stdout.write('output\n')
                        self.stdout.write('exiting...')
                        return cb(0)
                    default:
                        return cb(1)
                    }
                })
            }
        }
    default:
        return mySpawn.simple(0,'hello world')
    }
})

describe('spectcl', function(){

    it('should be an instance of Spectcl', function(){
        var session = new Spectcl()
        assert(session instanceof Spectcl)
    })
    it('should allow instantiation without new keyword', function(){
        /*eslint-disable new-cap*/
        var session = Spectcl()
        assert(session instanceof Spectcl)
        /*eslint-enable new-cap*/

    })
    it('should allow multiple spectcl instances to coexist', function(){
        var session1 = new Spectcl({maxMatch:5})
          , session2 = new Spectcl({maxMatch:6})
        assert(session1.options.maxMatch !== session2.options.maxMatch, 'Expected maxMatch to not match between instances')
    })

    describe('spawn', function(){
        it('should spawn a known command without emitting an error', function(done){
            var session = new Spectcl()
            session.on('error', function(err){
                assert.fail('unexpected error: %s',err)
            })
            session.on('exit', function(){
                done()
            })
            session.spawn('ls')
        })

        it('should spawn with a command string', function(done){
            var session = new Spectcl()
            session.on('error', function(err){
                assert.fail('unexpected error: %s',err)
            })
            session.on('exit', function(){
                done()
            })
            session.spawn('echo hello')
        })

        it('should spawn with a command string and args array', function(done){
            var session = new Spectcl()
            session.on('error', function(err){
                assert.fail('unexpected error: %s', err)
            })
            session.on('exit', function(code){
                assert.equal(code, 0, 'non-0 return code')
                done()
            })
            session.spawn('echo', ['hello'])
        })

        it('should spawn without pty when `noPty` set to true', function(done){
            var session = new Spectcl()
            session.on('error', function(err){
                assert.fail('unexpected error: '+err)
            })
            session.on('exit', function(code){
                assert.equal(0, code, 'child exited with non-0 return code')
                done()
            })
            session.spawn(['echo', 'hello'], {}, {noPty: true})
            assert.equal(session.child.ttyname, undefined, 'child was spawned with a pty session')
        })

        it('should spawn without cmdParams but with cmdOptions', function(done){
            var session = new Spectcl()
            session.on('error', function(err){
                assert.fail('unexpected error: '+err)
            })
            session.on('exit', function(code){
                assert.equal(0, code, 'child exited with non-0 return code')
                done()
            })
            session.spawn(['echo', 'hello'], {})
            assert.equal(session.child.ttyname, undefined, 'child was spawned with a pty session')
        })

        it('should throw an error if command is not string or array', function(done){
            var session = new Spectcl()
            try {
                session.spawn({'echo': 'hello'}, {})
            } catch(e){
                assert(e)
                done()
            }
        })

        it('should spawn with ignoreCase and stripColors options', function(done){
            var session = new Spectcl({stripColors:true,ignoreCase:true})
            session.on('error', function(err){
                assert.fail('unexpected error: %s',err)
            })
            session.on('exit', function(){
                done()
            })
            session.spawn(['ls', '-G'])
        })

        it('should emit `error` event when command cannot be spawned', function(done){
            var session = new Spectcl()
            session.on('error', function(err){
                assert.notEqual(null, err, 'recieved null error object')
                done()
            })
            session.spawn('defnotacommand')
        })

        it('should emit `error` event when command cannot be spawned with `noPty`', function(done){
            var session = new Spectcl()
            session.on('error', function(err){
                assert.notEqual(null, err, 'recieved null error object')
                done()
            })
            session.spawn('defnotacommand', [], {}, {noPty:true})
        })

        it('should emit `exit` event when child exits', function(done){
            var session = new Spectcl()
            session.on('exit', function(code){
                assert.equal(code, 0, 'non-0 return code')
                done()
            })
            session.spawn('echo hello')
        })
    })

    describe('expect', function(){
        it('should expect and match on a String', function(done){
            var session = new Spectcl()
              , finished = _.after(2,done)
            session.spawn('echo hello')
            session.expect([
                'hello', function(match, matched, cb){
                    cb(null, 'hello', match, matched)
                }
            ], function(err, data, match, matched){
                assert.equal(err, null, 'unexpected err in final callback')
                assert.equal(data, 'hello', 'final callback was called by function other than expecation handler, data: "'+data+'"')
                assert.equal(match, matched, 'expected string equals matched string')
                finished()
            })
            session.on('exit', function(){
                finished()
            })
        })

        it('should ignore multiple callbacks for the same string', function(done){
            var session = new Spectcl()
              , finished = _.after(2,done)
            session.spawn('echo hello')
            session.expect([
                'hello', function(match, matched, cb){
                    cb(null, 'hello')
                },
                'hello', function(match, matched, cb){
                    assert(false)
                    cb(null, 'hello')
                }
            ], function(err, data, match, matched){
                assert.equal(err, null, 'unexpected err in final callback')
                assert.equal(data, 'hello', 'final callback was called by function other than expecation handler, data: "'+data+'"')
                assert.equal(match, matched, 'expected string equals matched string')
                finished()
            })
            session.on('exit', function(){
                finished()
            })
        })

        it('should expect and match on a RegExp', function(done){
            var session = new Spectcl()
              , finished = _.after(2,done)
            session.spawn('echo hello')
            session.expect([
                /hello/, function(match, matched, cb){
                    cb(null, 'hello', match, matched)
                }
            ], function(err, data, match, matched){
                assert.equal(err, null, 'unexpected err in final callback')
                assert.equal(data, 'hello', 'final callback was called by function other than expecation handler, data: "'+data+'"')
                assert.equal(match.toString().replace(/\//g,''), matched[0], 'expected regex equals matched string')
                finished()
            })
            session.on('exit', function(){
                finished()
            })
        })

        it('should match on content already in the session cache', function(done){
            var session = new Spectcl()
            session.spawn('echo hello')
            // Wait until exit so that `hello` is for sure in the cache, and not read in as data
            session.child.on('exit',function(){
                session.expect([
                    'hello', function(match, matched, cb){
                        cb(null, 'hello')
                    }
                ], function(err, data){
                    assert.ifError(err)
                    assert.equal(data, 'hello')
                    done()
                })
            })
        })

        it('should populate expect_out object when match is found', function(done){
            var session = new Spectcl()
              , finished = _.after(2,done)
            session.spawn('node --interactive')
            session.expect([
                '>', function(){
                    assert.notEqual(session.expect_out.match, null, 'null expect_out match')
                    assert.notEqual(session.expect_out.buffer, '', 'empty expect_out buffer')
                    session.send('process.exit()\r')
                    finished()
                }
            ])
            session.on('exit', function(){
                finished()
            })
        })

        it('should emit error when given a non-String or non-RegExp parameter', function(done){
            var session = new Spectcl()
            session.spawn('echo hello')
            session.on('error', function(err){
                assert.notEqual(null, err, 'received null error object')
                done()
            })
            session.expect([
                1, function(){
                    assert.fail('unexpected match')
                }
            ])
        })

        it('should emit error when given non-function as expect callback', function(done){
            var session = new Spectcl()
            session.spawn('echo hello')
            session.on('error', function(err){
                assert.notEqual(null, err, 'received null error object')
                done()
            })
            session.expect([
                'foo', 'bar'
            ])

        })

        it('should emit error when given non-even expectations array', function(done){
            var session = new Spectcl()
            session.spawn('echo hello')
            session.on('error', function(err){
                assert.equal('cannot call expect with array that is odd in length', err.message, 'received unexpected error')
                done()
            })
            session.expect([
                'foo', function(){}, 'bar'
            ])
        })

        it('should emit error when given empty expectations array', function(done){
            var session = new Spectcl()
            session.spawn('echo hello')
            session.on('error', function(err){
                assert.equal('cannot call expect with empty array', err.message, 'received unexpected error')
                done()
            })
            session.expect([])
        })

        it('should emit error when calling expect() when already expecting', function(done){
            var session = new Spectcl()
            session.spawn('echo hello')
            session.on('error', function(err){
                assert.notEqual(null, err, 'received null error object')
                done()
            })
            session.expect([
                'foo', function(match){
                    assert.fail(match, 'error', 'should have thrown an error, not matched.')
                }
            ])
            session.expect([
                /foo/, function(match){
                    assert.fail(match, 'error', 'should have thrown an error, not matched.')
                }
            ])
        })

        it('should call the final callback after match handler has been called', function(done){
            var session = new Spectcl()
              , finished = _.after(2,done)
            session.on('error', function(err){
                assert.fail('unexpected error '+err)
            })
            session.spawn('echo hello')
            session.expect([
                /hello/, function(match, matched, cb){
                    cb(null, 'hello')
                }
            ], function(err, data){
                assert.ifError(err)
                assert.equal(data, 'hello')
                finished()
            })
            session.on('exit', function(){
                finished()
            })
        })

        it('should implement EXP_CONTINUE', function(done){
            var session = new Spectcl()
              , finished = _.after(2,done)
            session.spawn('bash',['fixtures/test_exp_continue.sh'],{cwd:__dirname})
            session.expect([
                /\$/, function(match, matched, cb){
                    session.send('exit\n')
                    cb(null, 'done')
                },
                /assword/, function(){
                    session.send('bar\n')
                    return session.EXP_CONTINUE
                },
                /user/, function(){
                    session.send('foo\n')
                    return session.EXP_CONTINUE
                }
            ], function(err, data){
                assert.equal(err, null, 'unexpected error in final callback')
                assert.equal(data, 'done')
                finished()
            })
            session.on('exit', function(){
                finished()
            })
        })

        it('should expect and match on TIMEOUT', function(done){
            var session = new Spectcl({timeout: 50})
              , finished = _.after(2,done)
            session.on('error', function(err){
                assert.fail('unexpected error '+err)
            })
            session.spawn('node --interactive')
            session.expect([
                'foo', function(){
                    session.send('process.exit()\r')
                    assert.fail('unexpected match')
                },
                session.TIMEOUT, function(match, matched, cb){
                    cb(new Error('timeout'))
                }
            ], function(err){
                assert.equal(err.message, 'timeout', 'received non-timeout error')
                session.send('process.exit()\r')
                finished()
            })
            session.on('exit', function(){
                finished()
            })
        })

        it('should call the final callback on TIMEOUT when no TIMEOUT expectation is specified', function(done){
            var session = new Spectcl({timeout: 50})
              , finished = _.after(2,done)
            session.on('error', function(err){
                assert.fail('unexpected error '+err)
            })
            session.spawn('node --interactive')
            session.expect([
                'foo', function(){
                    session.send('process.exit()\r')
                    assert.fail('unexpected match')
                }
            ], function(err){
                assert.ifError(err)
                session.send('process.exit()\r')
                finished()
            })
            session.on('exit', function(){
                finished()
            })
        })

        it('should expect and match on FULL_BUFFER', function(done){
            var session = new Spectcl({matchMax: 5})
              , finished = _.after(2,done)
            session.spawn('echo thequickbrownfoxjumpsoverthelazydog')
            session.expect([
                session.FULL_BUFFER, function(match, matched, cb){
                    cb(new Error('full buffer'))
                }
            ], function(err){
                assert(!!err)
                assert.equal(err.message, 'full buffer', 'unexpected error: '+err)
                finished()
            })
            session.on('exit', function(){
                finished()
            })
        })

        it('should expect and match on EOF', function(done){
            var session = new Spectcl()
            session.on('error', function(err){
                assert.fail('unexpected error '+err)
            })
            session.spawn('echo hello')
            session.expect([
                session.EOF, function(match, matched, cb){
                    cb(new Error('eof'))
                }
            ], function(err){
                assert.equal(err.message, 'eof', 'received non-eof error in final callback')
                done()
            })
        })

        it('should expect and match on EOF when `noPty` enabled', function(done){
            var session = new Spectcl()
            session.on('error', function(err){
                assert.fail('unexpected error '+err)
            })
            session.spawn('echo', ['hello'], {}, {noPty: true})
            session.expect([
                session.EOF, function(match, matched, cb){
                    cb(new Error('eof'))
                }
            ], function(err){
                assert.equal(err.message, 'eof', 'received non-eof error in final callback')
                done()
            })
        })

        it('should call the final callback on EOF when no EOF expectation is specified', function(done){
            var session = new Spectcl()
            session.spawn('echo hello')
            session.expect([
                /goodbye/, function(){
                    assert.fail('unexpected match')
                }
            ], function(err){
                assert.ifError(err)
                done()
            })
        })
    })

    describe('send', function(){
        it('should call the cb once data has been written to child', function(done){
            var session = new Spectcl()
              , finished = _.after(2,done)
            session.spawn('node --interactive')
            session.expect([
                '>', function(){
                    assert.notEqual(session.expect_out.match, null, 'null expect_out match')
                    assert.notEqual(session.expect_out.buffer, '', 'empty expect_out buffer')
                    session.child.on('exit', function(){
                        finished()
                    })
                    session.send('process.exit()\r', function(){
                        finished()
                    })
                }
            ])
        })
    })

    describe('sendEof', function(){
        it('should kill the child process, emitting an exit event', function(done){
            var session = new Spectcl()
            session.spawn('node --interactive')
            session.expect([
                '>', function(){
                    session.on('exit', function(){
                        done()
                    })
                    session.sendEof()
                }
            ])
        })

        it('should call the callback when given one', function(done){
            var session = new Spectcl()
            session.spawn('node --interactive')
            session.expect([
                '>', function(){
                    session.sendEof(function(){
                        done()
                    })
                }
            ])
        })

        it('should kill the child process, emitting an exit event, when `noPty` enabled', function(done){
            var session = new Spectcl()
            session.on('exit', function(){
                done()
            })
            session.on('error', function(err){
                assert.fail('unexpected error: '+err)
            })
            session.spawn('node', ['--interactive'], {}, {noPty:true})
            session.expect([
                '>', function(){
                    session.sendEof()
                }
            ])
        })
    })
})


text:
<img src="https://upload.wikimedia.org/wikipedia/commons/4/4a/Plato-raphael.jpg" width="150" />

[![npm version](https://badge.fury.io/js/republic.svg)](https://badge.fury.io/js/republic)

Republic is a library for React that gives you productive routing, controllers, and forms. It currently is built to work with Express + Next.js but has been built in mind that this may not always be the stack of choice.

If you miss the days of Rails forms and controllers, you'll love Republic.

- **[Start Here](https://github.com/lukemorton/republic/blob/master/GETTING_STARTED.md)** - for those who haven't used Republic before
- **[Concepts](#concepts)** - the reasons why you should use Republic
- **[Documentation](#documentation)** - for a reference of all the parts to Republic

## Beginners Guide

We have a lovely document for creating an application from scratch using Express + Next.js + Republic. The guide is a complete walkthrough that's ideal for first time users. [Read it to get started.](https://github.com/lukemorton/republic/blob/master/GETTING_STARTED.md)

## Concepts

There are three concepts that make Republic compelling to use.

- Routing
- Controllers
- Forms

Republic tries to fuse the productivity provided by web frameworks like Rails with the new world of React. Unfortunately React requires quite a lot of boilerplate when making forms, Redux isn't straight forward when dealing with data, and Next.js does not have any inbuilt routing. Republic aims to solve all of these problems.

### Routing

Republic provides routing functionality like Rails. You can build a URL or `<a href>` just by referencing the controller and action, perhaps providing some parameters.

#### Defining Routes

You define your routes in your Republic application. Your Republic application is universal, that is, it can be used both on the server and on the client side.

``` js
import Republic, { route } from 'republic/next'

export default new Republic(
  route.page('/blog', 'blog#index'),
  route.page('/blog/:slug', 'blog#show')
)
```

You can use express style routing, so for example parameters can be passed specified like `:slug`.

#### Building URLs

You can construct URLs given an action like `'blog#index'`, and optionally params like `{ slug: 'awesome-post' }`.

``` js
import app from '../../app'

app.url('blog#index') // => '/blog'
app.url('blog#show', { slug: 'awesome-post' }) // => '/blog/awesome-post'
```

Because your Republic application is universal, you can build URLs both on the server and a client.

#### Building `<a href>`

You can build links much like Next.js, but you do not need to hardcode URLs, instead you can specify an action and optionally params.

``` jsx
import React from 'react'
import { Link } from 'republic/react'

export default () =>
  <div>
    <Link action='blog#index'>
      <a>View posts</a>
    </Link>

    <Link action='blog#show' params={{ slug: 'awesome-post' }}>
      <a>Read awesome post</a>
    </Link>
  </div>
```

### Controllers

Republic provides the ability to define controller action handlers for your routes. These are similar to Express route handlers, however they are universal, they can run both on the server and client. This makes it really easy to handle form submissions in the client if JavaScript is available, or submit to the server if not.

#### Defining an Action Handler

You define your action handlers beside your routes, much like Express.

``` js
import Republic, { route } from 'republic/next'
import blog from './src/blog/'

export default new Republic(
  route.page('/blog', 'blog#index', () => {
    return { posts: blog.FetchLatestBlogPosts() }
  }),

  route.page('/blog/:slug', 'blog#show', ({ params }) => {
    return { post: blog.FetchPost(params.slug) }
  })
)
```

As you can see, you return an object with data in it. This data will be accessible within your React page by passing the object into your page component's props.

#### Accessing Action Handler Data

To illustrate, the access of the data returns from the action handler above, here is the page for `'blog#show'`. You can see we are accessing the post data returned from the action handler.

``` jsx
import React from 'react'
import app from '../../app'

export default app.page(({ post }) =>
  <article>
    <h1>{post.title}</h1>
    {post.content}
  </article>
)
```

### Forms

Republic provides universal forms that handle state management for you. No longer do you need to define your own onChange handlers, a huge bug bear for those coming from Rails. Also, because Republic provides universal forms, the form can be handled both server side if JavaScript is not available, or in the client if it is.

#### Defining an Action Handler for your Form

Before we build our form, we first want to define our action handler that will be called on submit. The process is similar to defining a page route.

``` js
import Republic, { route } from 'republic/next'
import blog from './src/blog/'

export default new Republic(
  route.page('/blog', 'blog#index', () => {
    return { posts: blog.FetchLatestBlogPosts() }
  }),

  route.POST('/blog/subscribe', 'blog#subscribe', async ({ params, redirectTo }) => {
    await blog.Subscribe(params.email)
    redirectTo('blog#index')
  })
)
```

This action will handle a new subscription to the blog's mailing list. Once the subscription has been created, we then redirect the user back to the blog index page.

#### Building your Form

Now we have defined our action handler, we can use it in a form. Within our `'blog#index'` page we can define our form and pass our action into it.

``` jsx
import React from 'react'
import { Form, Input } from 'republic/react'
import app from '../../app'
import PostList from '../../components/PostList'

export default app.page(({ posts, subscribe }) =>
  <Form action={subscribe}>
    <Input type='email' name='subscription[email]' />
    <Input type='checkbox' name='subscription[include_spam]' value='yes' />
    <button>Subscribe</button>
  </Form>
)
```

Because `'blog#index'` is in the same controller as `'blog#subscribe'` the subscribe action handler is automatically passed into the props of the page. You can see this handler is then passed into the `<Form>`'s `action` prop. The handler will be called onSubmit with the form data, or handled on the server if JavaScript is not available.

## Documentation

- **[Installation](#installation)** - how to install Republic
- **[`new Republic(...routes)`](#new-republicroutes)** - how to define your Republic application
- **[`app.page(Component)`](#apppagecomponent)** - how to define a Republic page
- **[`app.url(action, params = {})`](#appurlaction-params--)** - how to build a URL
- **[`<Link>`](#link)** - how to link to other pages
- **[`<Form>`](#form)** - how to create a universal form
- **[`<Input />`](#input-)** - how to add fields to your universal form
- **[`<Textarea />`](#textarea-)** - how to add textarea fields to your universal form
- **[`<Select>`](#select)** - how to add select fields to your universal form

### Installation

#### Install Express + Next.js

Use Next.js's [example of custom server using Express](https://github.com/zeit/next.js/tree/master/examples/custom-server-express) to setup your app ready to install Republic.

#### Install Republic

Install republic first with:

```
npm install --save republic
```

Now add two middleware to your Express setup. The following code adds parsing for POST data.

``` js
// Handle POST data
import bodyParser from 'body-parser'
server.use(bodyParser.urlencoded({ extended: true }))
```

And then we add republic into the mix:

``` js
// Hook up upcoming + express + next
import { asExpressMiddleware, nextHandler } from 'republic/express'
import app from './app'
server.use(asExpressMiddleware(app, nextHandler(nextApp)))
```

Make sure the path to your app file is correct.

### `new Republic(...routes)`

### `app.page(Component)`

### `app.url(action, params = {})`

### `<Link>`

### `<Form>`

### `<Input />`

#### `<Input type='radio' />`

#### `<Input type='checkbox' />`

### `<Textarea />`

### `<Select>`

## Roadmap

- [x] Form state handling
- [x] Connect form state to action handling
- [x] Form handling receives nested object rather than flattened string keys
- [x] Allow forms to have default state set
- [x] Pass actions in as functions rather than strings so they can be used with custom forms, and on other input events like click

**Nice to haves:**

- [x] Update route builders to accept middleware as arguments, array as single argument, or mix of both like Express
- [x] Pass rails-like params into handlers
- [x] Universal redirect
- [x] Provide all common form inputs
- [ ] Convention for express + next (helper wrappers)
- [ ] Form error handling
- [ ] Abstract pages away from Next.js
- [ ] Allow Form to have custom onSubmit
- [ ] Upcoming middleware: how to, make sure API is easy to understand, etc.


text:
<?xml version="1.0" encoding="utf-8"?>
<widget xmlns:cdv="http://cordova.apache.org/ns/1.0" xmlns:vs="http://schemas.microsoft.com/appx/2014/htmlapps" id="io.cordova.myapp49bfe31995624926b10397417db48cf9" version="1.0.0" xmlns="http://www.w3.org/ns/widgets">
  <name>MyBestPlaces</name>
  <description>A blank project that uses Apache Cordova to help you build an app that targets multiple mobile platforms: Android, iOS, Windows, and Windows Phone.</description>
  <author href="http://cordova.io" email="dev@cordova.apache.org">Apache Cordova Team </author>
  <content src="index.html" />
  <access origin="*" />
  <preference name="SplashScreen" value="screen" />
  <preference name="windows-target-version" value="8.1" />
  <preference name="windows-phone-target-version" value="8.1" />
  <vs:plugin name="org.apache.cordova.geolocation" version="0.3.10" />
  <vs:plugin name="org.apache.cordova.vibration" version="0.3.11" />
  <vs:plugin name="org.apache.cordova.dialogs" version="0.2.10" />
  <vs:platformSpecificValues />
</widget>


text:
;(function() {
  "use strict";

  var BaseController = require("BaseController");

  new BaseController({
    siteName: "Tidal",
    play: ".play-controls .js-play",
    pause: ".play-controls .js-pause",
    playNext: ".play-controls .js-next",
    playPrev: ".play-controls .js-previous",

    song: "[data-test-id=track-title]",
    artist: "[data-test-id=artist-title]"
  });
})();