text:
package org.infobip.mobile.messaging;

import androidx.annotation.NonNull;

import com.google.gson.reflect.TypeToken;

import org.infobip.mobile.messaging.api.support.http.serialization.JsonSerializer;
import org.infobip.mobile.messaging.util.DateTimeUtil;
import org.infobip.mobile.messaging.util.StringUtils;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CustomAttributesMapper {

    private static final JsonSerializer nullSerializer = new JsonSerializer(true);

    public static Map<String, Object> customAttsToBackend(@NonNull Map<String, CustomAttributeValue> customAttributes) {
        Map<String, Object> customAttributesToReport = new HashMap<>(customAttributes.size());
        for (Map.Entry<String, CustomAttributeValue> entry : customAttributes.entrySet()) {
            customAttributesToReport.put(entry.getKey(), customValueToBackend(entry.getValue()));
        }
        return customAttributesToReport;
    }

    public static Object customValueToBackend(CustomAttributeValue value) {
        if (value == null) {
            return null;
        }

        switch (value.getType()) {
            case Date:
                return DateTimeUtil.dateToYMDString(value.dateValue());
            case DateTime:
                return DateTimeUtil.dateTimeToISO8601UTCString(value.dateTimeValue());
            case Number:
                return value.numberValue();
            case String:
                return value.stringValue();
            case Boolean:
                return value.booleanValue();
            case CustomList:
                return value.listMapValue();
            default:
                return null;
        }
    }

    public static Boolean validate(Map<String, Object> customAttributes) {
        for (Map.Entry<String, Object> entry: customAttributes.entrySet()) {
            if (!(entry.getValue() instanceof List)) continue;

            List valueList = (List) entry.getValue();
            Set<String> keys = new HashSet<>();
            Map<String, CustomAttributeValue> valuesMap = new HashMap<>();
            for (Object valueItem: valueList) {
                if (!(valueItem instanceof Map)) {
                    return false;
                }
                Map<String, Object> map = (Map<String, Object>) valueItem;
                if (map.keySet().isEmpty()) {
                    return false;
                }
                if (keys.isEmpty()) {
                    keys.addAll(map.keySet());
                    for (Map.Entry<String, Object> listEntry: map.entrySet()) {
                        valuesMap.put(listEntry.getKey(), parseValue(listEntry.getValue()));
                    }
                    continue;
                }
                if (keys.size() != map.keySet().size()) {
                    return false;
                }
                if (!keys.containsAll(map.keySet()) || !map.keySet().containsAll(keys)) {
                    return false;
                }

                for (Map.Entry<String, Object> listEntry: map.entrySet()) {
                    CustomAttributeValue value = parseValue(listEntry.getValue());
                    CustomAttributeValue existedValue = valuesMap.get(listEntry.getKey());
                    if (existedValue != null && !existedValue.getType().equals(value.getType())) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    public static Map<String, CustomAttributeValue> customAttsFrom(String json) {
        Type type = new TypeToken<Map<String, CustomAttributeValue>>() {
        }.getType();
        return nullSerializer.deserialize(json, type);
    }

    public static Map<String, CustomAttributeValue> customAttsFromBackend(Map<String, Object> customAttributes) {
        Map<String, CustomAttributeValue> customUserDataValueMap = new HashMap<>();
        if (customAttributes == null) {
            return customUserDataValueMap;
        }

        for (Map.Entry<String, Object> entry : customAttributes.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();

            if (value instanceof List) {
                List valueList = (List) value;
                List<ListCustomAttributeItem> customAttributeItems = new LinkedList<>();
                for (Object valueItem: valueList) {
                    if (!(valueItem instanceof Map)) {
                        continue;
                    }
                    Map<String, Object> map = (Map<String, Object>) valueItem;
                    ListCustomAttributeItem.Builder attributeItem = ListCustomAttributeItem.builder();
                    for (Map.Entry<String, Object> mapEntry: map.entrySet()) {
                        CustomAttributeValue customAttribute = parseValue(mapEntry.getValue());
                        switch (customAttribute.getType()) {
                            case String: attributeItem.putString(mapEntry.getKey(), customAttribute.stringValue()); break;
                            case Date: attributeItem.putDate(mapEntry.getKey(), customAttribute.dateValue()); break;
                            case DateTime: attributeItem.putDateTime(mapEntry.getKey(), customAttribute.dateTimeValue()); break;
                            case Number: attributeItem.putNumber(mapEntry.getKey(), customAttribute.numberValue()); break;
                            case Boolean: attributeItem.putBoolean(mapEntry.getKey(), customAttribute.booleanValue()); break;
                        }
                    }
                    customAttributeItems.add(attributeItem.build());
                }
                customUserDataValueMap.put(key, new CustomAttributeValue(customAttributeItems));
            } else {
                customUserDataValueMap.put(key, parseValue(value));
            }
        }

        return customUserDataValueMap;
    }

    private static CustomAttributeValue parseValue(Object value) {
        if (value instanceof String) {
            String stringValue = (String) value;

            if (isPossiblyDateOrDateTime(stringValue)) {
                Date dateValue;
                try {
                    dateValue = DateTimeUtil.dateFromISO8601DateUTCString((String) value);
                    return new CustomAttributeValue(new CustomAttributeValue.DateTime(dateValue));
                } catch (ParseException ex1) {
                    try {
                        dateValue = DateTimeUtil.dateFromYMDString((String) value);
                        return new CustomAttributeValue(dateValue);
                    } catch (ParseException ignored) {
                    }
                }
            }
            return new CustomAttributeValue(stringValue);
        } else if (value instanceof Number) {
            return new CustomAttributeValue((Number) value);
        } else {
            return new CustomAttributeValue((Boolean) value);
        }
    }

    private static boolean isPossiblyDateOrDateTime(String stringValue) {
        return StringUtils.isNotBlank(stringValue) && Character.isDigit(stringValue.charAt(0)) &&
                (stringValue.length() == DateTimeUtil.DATE_YMD_FORMAT.length() ||
                        stringValue.length() == DateTimeUtil.DATE_TIME_LENGTH_DATE_FORMAT3);
    }

}


text:
Put the following in 1 program (e.g. CHomework3A):

 - Write a loop that will print all the whole numbers from 1 to 100.
 - Write a loop that will add all the whole numbers from 1 to 1000 and print only the total.
 - Write a loop that will add all the ODD numbers from 1 to 300 and print only the total.
 - Write a loop that will add all the EVEN numbers from 2 to 146 and print only the total.
 - Write a loop that will add every 3rd number from 2000 to 6 and print the total. DO NOT flip the numbers around and count from 6 to 2000.

## Step 2

Put the following in 1 program (e.g. CHomework3B):

 - Read in an integer value from the user and print out if the number is even or odd.
 - Read in an integer value from the user from 1 and 100.  Loop until a value in that range is entered.  After a number in that range is entered print it out.

## Step 3

Zip both your .java files and submit them to Blackboard.

redpajama_set_name: RedPajamaGithub


text:
//
//  NSString+HTML.m
//  MWFeedParser
//
//  Copyright (c) 2010 Michael Waterfall
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  1. The above copyright notice and this permission notice shall be included
//     in all copies or substantial portions of the Software.
//
//  2. This Software cannot be used to archive or collect data such as (but not
//     limited to) that of events, news, experiences and activities, for the
//     purpose of any concept relating to diary/journal keeping.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//

#import "NSString+HTML.h"
#import "GTMNSString+HTML.h"

@implementation NSString (HTML)

#pragma mark -
#pragma mark Class Methods

#pragma mark -
#pragma mark Instance Methods

// Strip HTML tags
- (NSString *)stringByConvertingHTMLToPlainText {

	// Pool
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	// Character sets
	NSCharacterSet *stopCharacters = [NSCharacterSet characterSetWithCharactersInString:[NSString stringWithFormat:@"< \t\n\r%C%C%C%C", 0x0085, 0x000C, 0x2028, 0x2029]];
	NSCharacterSet *newLineAndWhitespaceCharacters = [NSCharacterSet characterSetWithCharactersInString:[NSString stringWithFormat:@" \t\n\r%C%C%C%C", 0x0085, 0x000C, 0x2028, 0x2029]];
	NSCharacterSet *tagNameCharacters = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"]; /**/

	// Scan and find all tags
	NSMutableString *result = [[NSMutableString alloc] initWithCapacity:self.length];
	NSScanner *scanner = [[NSScanner alloc] initWithString:self];
	[scanner setCharactersToBeSkipped:nil];
	[scanner setCaseSensitive:YES];
	NSString *str = nil, *tagName = nil;
	BOOL dontReplaceTagWithSpace = NO;
	do {

		// Scan up to the start of a tag or whitespace
		if ([scanner scanUpToCharactersFromSet:stopCharacters intoString:&str]) {
			[result appendString:str];
			str = nil; // reset
		}

		// Check if we've stopped at a tag/comment or whitespace
		if ([scanner scanString:@"<" intoString:NULL]) {

			// Stopped at a comment or tag
			if ([scanner scanString:@"!--" intoString:NULL]) {

				// Comment
				[scanner scanUpToString:@"-->" intoString:NULL];
				[scanner scanString:@"-->" intoString:NULL];

			} else {

				// Tag - remove and replace with space unless it's
				// a closing inline tag then dont replace with a space
				if ([scanner scanString:@"/" intoString:NULL]) {

					// Closing tag - replace with space unless it's inline
					tagName = nil; dontReplaceTagWithSpace = NO;
					if ([scanner scanCharactersFromSet:tagNameCharacters intoString:&tagName]) {
						tagName = [tagName lowercaseString];
						dontReplaceTagWithSpace = ([tagName isEqualToString:@"a"] ||
												   [tagName isEqualToString:@"b"] ||
												   [tagName isEqualToString:@"i"] ||
												   [tagName isEqualToString:@"q"] ||
												   [tagName isEqualToString:@"span"] ||
												   [tagName isEqualToString:@"em"] ||
												   [tagName isEqualToString:@"strong"] ||
												   [tagName isEqualToString:@"cite"] ||
												   [tagName isEqualToString:@"abbr"] ||
												   [tagName isEqualToString:@"acronym"] ||
												   [tagName isEqualToString:@"label"]);
					}

					// Replace tag with string unless it was an inline
					if (!dontReplaceTagWithSpace && result.length > 0 && ![scanner isAtEnd]) [result appendString:@" "];

				}

				// Scan past tag
				[scanner scanUpToString:@">" intoString:NULL];
				[scanner scanString:@">" intoString:NULL];

			}

		} else {

			// Stopped at whitespace - replace all whitespace and newlines with a space
			if ([scanner scanCharactersFromSet:newLineAndWhitespaceCharacters intoString:NULL]) {
				if (result.length > 0 && ![scanner isAtEnd]) [result appendString:@" "]; // Dont append space to beginning or end of result
			}

		}

	} while (![scanner isAtEnd]);

	// Cleanup
	[scanner release];

	// Decode HTML entities and return
	NSString *retString = [[result stringByDecodingHTMLEntities] retain];
	[result release];

	// Drain
	[pool drain];

	// Return
	return [retString autorelease];

}

// Decode all HTML entities using GTM
- (NSString *)stringByDecodingHTMLEntities {
	// gtm_stringByUnescapingFromHTML can return self so create new string ;)
	return [NSString stringWithString:[self gtm_stringByUnescapingFromHTML]];
}

// Encode all HTML entities using GTM
- (NSString *)stringByEncodingHTMLEntities {
	// gtm_stringByUnescapingFromHTML can return self so create new string ;)
	return [NSString stringWithString:[self gtm_stringByEscapingForAsciiHTML]];
}

// Replace newlines with
 tags
- (NSString *)stringWithNewLinesAsBRs {

	// Pool
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	// Strange New lines:
	//	Next Line, U+0085
	//	Form Feed, U+000C
	//	Line Separator, U+2028
	//	Paragraph Separator, U+2029

	// Scanner
	NSScanner *scanner = [[NSScanner alloc] initWithString:self];
	[scanner setCharactersToBeSkipped:nil];
	NSMutableString *result = [[NSMutableString alloc] init];
	NSString *temp;
	NSCharacterSet *newLineCharacters = [NSCharacterSet characterSetWithCharactersInString:
										 [NSString stringWithFormat:@"\n\r%C%C%C%C", 0x0085, 0x000C, 0x2028, 0x2029]];
	// Scan
	do {

		// Get non new line characters
		temp = nil;
		[scanner scanUpToCharactersFromSet:newLineCharacters intoString:&temp];
		if (temp) [result appendString:temp];
		temp = nil;

		// Add
 s
		if ([scanner scanString:@"\r\n" intoString:nil]) {

			// Combine \r\n into just 1

			[result appendString:@"
"];

		} else if ([scanner scanCharactersFromSet:newLineCharacters intoString:&temp]) {

			// Scan other new line characters and add
 s
			if (temp) {
				for (int i = 0; i < temp.length; i++) {
					[result appendString:@"
"];
				}
			}

		}

	} while (![scanner isAtEnd]);

	// Cleanup & return
	[scanner release];
	NSString *retString = [[NSString stringWithString:result] retain];
	[result release];

	// Drain
	[pool drain];

	// Return
	return [retString autorelease];

}

// Remove newlines and white space from strong
- (NSString *)stringByRemovingNewLinesAndWhitespace {

	// Pool
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	// Strange New lines:
	//	Next Line, U+0085
	//	Form Feed, U+000C
	//	Line Separator, U+2028
	//	Paragraph Separator, U+2029

	// Scanner
	NSScanner *scanner = [[NSScanner alloc] initWithString:self];
	[scanner setCharactersToBeSkipped:nil];
	NSMutableString *result = [[NSMutableString alloc] init];
	NSString *temp;
	NSCharacterSet *newLineAndWhitespaceCharacters = [NSCharacterSet characterSetWithCharactersInString:
													  [NSString stringWithFormat:@" \t\n\r%C%C%C%C", 0x0085, 0x000C, 0x2028, 0x2029]];
	// Scan
	while (![scanner isAtEnd]) {

		// Get non new line or whitespace characters
		temp = nil;
		[scanner scanUpToCharactersFromSet:newLineAndWhitespaceCharacters intoString:&temp];
		if (temp) [result appendString:temp];

		// Replace with a space
		if ([scanner scanCharactersFromSet:newLineAndWhitespaceCharacters intoString:NULL]) {
			if (result.length > 0 && ![scanner isAtEnd]) // Dont append space to beginning or end of result
				[result appendString:@" "];
		}

	}

	// Cleanup
	[scanner release];

	// Return
	NSString *retString = [[NSString stringWithString:result] retain];
	[result release];

	// Drain
	[pool drain];

	// Return
	return [retString autorelease];

}

// Strip HTML tags
// DEPRECIATED - Please use NSString stringByConvertingHTMLToPlainText
- (NSString *)stringByStrippingTags {

	// Pool
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	// Find first & and short-cut if we can
	NSUInteger ampIndex = [self rangeOfString:@"<" options:NSLiteralSearch].location;
	if (ampIndex == NSNotFound) {
		return [NSString stringWithString:self]; // return copy of string as no tags found
	}

	// Scan and find all tags
	NSScanner *scanner = [NSScanner scannerWithString:self];
	[scanner setCharactersToBeSkipped:nil];
	NSMutableSet *tags = [[NSMutableSet alloc] init];
	NSString *tag;
	do {

		// Scan up to <
		tag = nil;
		[scanner scanUpToString:@"<" intoString:NULL];
		[scanner scanUpToString:@">" intoString:&tag];

		// Add to set
		if (tag) {
			NSString *t = [[NSString alloc] initWithFormat:@"%@>", tag];
			[tags addObject:t];
			[t release];
		}

	} while (![scanner isAtEnd]);

	// Strings
	NSMutableString *result = [[NSMutableString alloc] initWithString:self];
	NSString *finalString;

	// Replace tags
	NSString *replacement;
	for (NSString *t in tags) {

		// Replace tag with space unless it's an inline element
		replacement = @" ";
		if ([t isEqualToString:@""] ||
			[t isEqualToString:@""] ||
			[t isEqualToString:@""] ||
			[t isEqualToString:@""] ||
			[t isEqualToString:@""] ||
			[t isEqualToString:@""] ||
			[t isEqualToString:@""] ||
			[t isEqualToString:@""]) {
			replacement = @"";
		}

		// Replace
		[result replaceOccurrencesOfString:t
								withString:replacement
								   options:NSLiteralSearch
									 range:NSMakeRange(0, result.length)];
	}

	// Remove multi-spaces and line breaks
	finalString = [[result stringByRemovingNewLinesAndWhitespace] retain];

	// Cleanup
	[result release];
	[tags release];

	// Drain
	[pool drain];

	// Return
    return [finalString autorelease];

}

@end


text:
While this library targets to eliminate this boilerplate, it is crucial to understand how it works under the hood – there is no magic, it is just a convenient abstraction; but without understanding you'll likely bump into some troubles, and will try to solve some problems in weird way. So, don't overlook basic stuff – also, there are plently of good resources on this topic, right from the creator of Redux (for example, free video courses, [1](https://egghead.io/series/getting-started-with-redux) and [2](https://egghead.io/courses/building-react-applications-with-idiomatic-redux)). [Official docs](http://redux.js.org/) are superb as well – take a look before diving into this library!

So, just to quickly refresh the principles of Redux, let's briefly create one small module. But first, let's recap general flow: redux has unidirectional data flow, which looks a little bit weird in the beginning – we create constants as unique identifiers, and then pass data from actions along with this constant, and then we put this data to it's own place in the store (each handler reacts only to the specific constant). Also, it is possible to trigger these actions only from the store instance, so it is "approved" by our store (which in case of React is stored inside context), and therefore we know for sure where this data came from. Later components (or just parts of the application – you can subscribe to parts of the store manually) just retrieve this data, and they have no power to mutate the state.

So, with this knowledge in mind, let's build a simple notification module in Redux. Let's assume we have predefined list of notifications and we just pass data to it, or set it to null, in case we close it (remember these annoying popups for accepting cookies?).

We will start with action:
```javascript
export const ADD_NOTIFICATION = 'ADD_NOTIFICATION';
export const REMOVE_NOTIFICATION = 'REMOVE_NOTIFICATION';

export const addNotification = ({ notification, id }) => {
  return {
    type: ADD_NOTIFICATION,
    payload: { notification, id },
  };
};

export const removeNotification = (id) => {
  return {
    type: REMOVE_NOTIFICATION,
    payload: { id },
  },
};
```

And now the reducer:
```javascript
import { ADD_NOTIFICATION, REMOVE_NOTIFICATION } from './actions';

const initialState = {
  cookies: null,
  login: null,
  details: null,
};

export const reducer = (state = initialState, action) {
  switch (action.type) {
    case ADD_NOTIFICATION: {
      const { id, notification } = action.payload;
      return {
        ...state,
        [id]: notification,
      }
    };
    case REMOVE_NOTIFICATION: {
      const { id } = action.payload;
      return {
        ...state,
        [id]: null
      }
    };
    default:
      return state;
  }
}
```

So, what is the problem here? It is not very long, and we now have guaranteed consistent update in our UI! Well, the problem is that it is fine for really small applications, but usually with growth of the application, it will get more hairy – because it is a lot of boilerplate code, there is a big chance that eventually old actions/reducers will be extended instead of creating small composable pieces. Also, combineReducers is usually performed only on the top level, so you will end up combining several UI states in the single reducer, or something like `notificationsUI`.

Consider the previous example, but now with redux-tiles:
```javascript
import { createSyncTile } from 'redux-tiles';

const notifications = createSyncTile({
  type: ['ui', 'notifications'],
  fn: ({ params: { notification = null } }) => notification,
  nesting: ({ id }) => [id],
});
```
You'll get the same constant for free, nice nesting functionality, and your reducer in the state will be nicely put under `state.ui.notifications`.

In the end I can recommend couple of rants about verbosity of Redux and analysis why is it so:
- [SOME PROBLEMS WITH REACT/REDUX by André Staltz](https://staltz.com/some-problems-with-react-redux.html)
- [Idiomatic Redux by Mark Erikson](http://blog.isquaredsoftware.com/2017/05/idiomatic-redux-tao-of-redux-part-1/) – pretty good resource to deep your knowledge about redux itself
- [Practice and Philosophy of Redux by Mark Erikson](http://blog.isquaredsoftware.com/2017/05/idiomatic-redux-tao-of-redux-part-2/) – analyzing of each part of Redux


text:
'use strict';

const chai = require('chai'),
  expect = chai.expect,
  Support = require('../support'),
  current = Support.sequelize,
  sinon = require('sinon'),
  DataTypes = require('../../../lib/data-types'),
  Promise = require('bluebird').getNewLibraryCopy();

describe(Support.getTestDialectTeaser('Model'), () => {
  describe('findAndCountAll', () => {
    describe('should handle promise rejection', () => {
      before(function() {
        this.stub = sinon.stub();

        Promise.onPossiblyUnhandledRejection(() => {
          this.stub();
        });

        this.User = current.define('User', {
          username: DataTypes.STRING,
          age: DataTypes.INTEGER
        });

        this.findAll = sinon.stub(this.User, 'findAll').rejects(new Error());

        this.count = sinon.stub(this.User, 'count').rejects(new Error());
      });

      after(function() {
        this.findAll.resetBehavior();
        this.count.resetBehavior();
      });

      it('with errors in count and findAll both', function() {
        return this.User.findAndCountAll({})
          .then(() => {
            throw new Error();
          })
          .catch(() => {
            expect(this.stub.callCount).to.eql(0);
          });
      });
    });
  });
});


text:
#ifndef __vdfArchiveSourceInfo_h
#define __vdfArchiveSourceInfo_h

#include <QStringList>

//-----------------------------------------------------------------------------
struct vdfArchiveFileType
{
  QString Description;
  QStringList Patterns;
};

//-----------------------------------------------------------------------------
struct vdfArchivePluginInfo
{
  QList<vdfArchiveFileType> SupportedFileTypes;
};

#endif


text:
"""A simple object-document mapping for mongodb-motor and tornado applications."""

import motor
from tornado.concurrent import TracebackFuture
from tornado.gen import coroutine
from pyenty.types import Entity

class EntityManager(object):
    """Class responsible for object-document mapping.

    Wraps motor functions and provide mapping of instance of Entity
    Entity is a pyenty's base class needed to use with EntityManager

    Example::

        class Product(Entity):
            name = Str()
            description = Str()
            price = Float()

            def __init__(self, name="", description="", price=0.0)
                self.name = name
                self.description = description
                self.price = price

        # using with tornado.gen.coroutine
        @coroutine
        def create_product():
            emanager = EntityManager(Product)
            product = Product(name="p", description="cell phone", price=150.38)
            object_id = yield emanager.save(product)
            saved_product = yield emanager.find_one(_id=object_id)
    """
    def __init__(self, entity, pluralize=False):
        assert isinstance(pluralize, bool), "Error: pluralize parameter must be bool"
        self.__pluralize = pluralize
        self.__session = EntityConnection.get_session()
        self.__entity = entity
        self.__collection_name = None
        self.__collection = None

        self.set_collection(self.__entity)

    def set_pluralize(self, pluralize):
        """enabled/disable pluralization"""
        self.__pluralize = pluralize

    def save(self, entity):
        """Maps entity to dict and returns future"""
        assert isinstance(entity, Entity), " entity must have an instance of Entity"
        return self.__collection.save(entity.as_dict())

    def remove(self, **kwargs):
        """Returns future.

        Executes collection's remove method based on keyword args

        Example::

            manager = EntityManager(Product)
            yield manager.remove(_id=object_id})

        """
        return self.__collection.remove(kwargs)

    def find_one(self, **kwargs):
        """Returns future.

        Executes collection's find_one method based on keyword args
        maps result ( dict to instance ) and return future

        Example::

           manager = EntityManager(Product)
           product_saved = yield manager.find_one(_id=object_id)

         """
        future = TracebackFuture()

        def handle_response(result, error):
            if error:
                future.set_exception(error)
            else:
                instance = self.__entity()
                instance.map_dict(result)
                future.set_result(instance)

        self.__collection.find_one(kwargs, callback=handle_response)

        return future

    @coroutine
    def find(self, **kwargs):
        """Returns List(typeof=).

        Executes collection's find method based on keyword args
        maps results ( dict to list of entity instances).

        Set max_limit parameter to limit the amount of data send back through network

        Example::

            manager = EntityManager(Product)
            products = yield manager.find(age={'$gt': 17}, max_limit=100)

         """
        max_limit = None
        if 'max_limit' in kwargs:
            max_limit = kwargs.pop('max_limit')
        cursor = self.__collection.find(kwargs)
        instances = []
        for doc in (yield cursor.to_list(max_limit)):
            instance = self.__entity()
            instance.map_dict(doc)
            instances.append(instance)
        return instances

    def update(self, entity):
        """ Executes collection's update method based on keyword args.

        Example::

            manager = EntityManager(Product)
            p = Product()
            p.name = 'new name'
            p.description = 'new description'
            p.price = 300.0

            yield manager.update(p)

         """
        assert isinstance(entity, Entity), "Error: entity must have an instance of Entity"
        return self.__collection.update({'_id': entity._id}, {'$set': entity.as_dict()})

    def remove_all(self):
        """ Erase all documents from collection """
        return self.__collection.remove({})

    def set_collection(self, class_):
        assert isinstance(class_, type), "Error: class_ must be an type"
        self.__set_collection(class_.__name__.lower())

    def __set_collection(self, collection_name):
        assert collection_name is not None, "Error: collection_name must be set"
        self.__collection_name = collection_name
        if self.__pluralize:
            self.__collection_name += "s"
        self.__collection = self.__session[self.__collection_name]

class EntityConnection(object):
    """Create a session to be used in all mongodb requests

    Examples::
         - EntitySession.open(db="db_name", io_loop=self.io_loop)
         - EntitySession.open(db="db_name")
         - EntityConnection.open('localhost', port_number, db="db_name")
         - EntityConnection.open('localhost', port_number, db="db_name", io_loop=self.io_loop)
    """

    @classmethod
    def open(cls, *args, **kwargs):
        if 'io_loop' in kwargs:
            motor_client = motor.MotorClient(*args, io_loop=kwargs.pop('io_loop'))
        else:
            motor_client = motor.MotorClient(*args)

        if 'db' in kwargs:
            db_name = kwargs.pop('db')
            setattr(cls, 'session', motor_client[db_name])
        else:
            raise KeyError('db is a Required Argument')

    @classmethod
    def close(cls):
        """Close session"""
        cls.motor_client.close()
        delattr(cls, 'session')

    @classmethod
    def get_session(cls):
        """Get current session"""
        assert hasattr(cls, 'session'), "Error: Session does not exist. First, call EntitySesion.create"
        return cls.session


text:
<?php
namespace ItBlaster\FixturesBundle\Command;

use ItBlaster\FixturesBundle\DataFixtures\Loader\YamlDataLoader;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;

use Propel\PropelBundle\Command\AbstractCommand;
use Propel\PropelBundle\DataFixtures\Loader\XmlDataLoader;

class FixturesLoadCommand extends AbstractCommand
{
    /**
     * Default fixtures directory.
     * @var string
     */
    private $defaultFixturesDir = 'app/propel/fixtures';

    /**
     * Absolute path for fixtures directory
     * @var string
     */
    private $absoluteFixturesPath = '';

    /**
     * Filesystem for manipulating files
     * @var \Symfony\Component\Filesystem\Filesystem
     */
    private $filesystem = null;

    protected $output;

    /**
     * Вывод ссобщения в консоль
     *
     * @param $message
     */
    protected function log($message)
    {
        $this->output->writeln($message);
    }

    /**
     * Конфигурация таска
     */
    protected function configure()
    {
        $this
            ->setName('it-blaster:fixtures:load')
            ->setDescription('Загрузка fixtures из yml,xml файлов')
            ->addArgument('bundle', InputArgument::OPTIONAL, 'The bundle to load fixtures from')
            ->addOption(
                'dir', 'd', InputOption::VALUE_OPTIONAL,
                'The directory where XML, SQL and/or YAML fixtures files are located',
                $this->defaultFixturesDir
            )
            ->addOption('xml', '', InputOption::VALUE_NONE, 'Load XML fixtures')
            ->addOption('sql', '', InputOption::VALUE_NONE, 'Load SQL fixtures')
            ->addOption('yml', '', InputOption::VALUE_NONE, 'Load YAML fixtures')
            ->addOption('connection', null, InputOption::VALUE_OPTIONAL, 'Set this parameter to define a connection to use')
            ->setHelp(<<<EOT
The <info>it-blaster:fixtures:load</info> loads <info>XML</info>, <info>SQL</info> and/or <info>YAML</info> fixtures.

  <info>php app/console it-blaster:fixtures:load</info>

The <info>--connection</info> parameter allows you to change the connection to use.
The default connection is the active connection (propel.dbal.default_connection).

The <info>--dir</info> parameter allows you to change the directory that contains <info>XML</info> or/and <info>SQL</info> fixtures files <comment>(default: app/propel/fixtures)</comment>.

The <info>--xml</info> parameter allows you to load only <info>XML</info> fixtures.
The <info>--sql</info> parameter allows you to load only <info>SQL</info> fixtures.
The <info>--yml</info> parameter allows you to load only <info>YAML</info> fixtures.

You can mix <info>--xml</info>, <info>--sql</info> and <info>--yml</info> parameters to load XML, YAML and SQL fixtures at the same time.
If none of this parameter is set, all XML, YAML and SQL files in the directory will be load.

XML fixtures files are the same XML files you can get with the command <info>propel:data-dump</info>:
<comment>
    <Fixtures>
        <Object Namespace="Awesome">
            <o1 Title="My title" MyFoo="bar" />
        </Object>
        <Related Namespace="Awesome">
            <r1 ObjectId="o1" Description="Hello world !" />
        </Related>
    </Fixtures>
</comment>

YAML fixtures are:
<comment>
    \Awesome\Object:
        o1:
            Title: My title
            MyFoo: bar

    \Awesome\Related:
        r1:
            ObjectId: o1
            Description: Hello world !
</comment>
EOT
            )
        ;
    }

    /**
     * Запуск таска
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int|null|void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->output = $output;

        $this->filesystem = new Filesystem();

        if (null !== $this->bundle) {
            $this->absoluteFixturesPath = $this->getFixturesPath($this->bundle);
        } else {
            $this->absoluteFixturesPath = realpath($this->getApplication()->getKernel()->getRootDir() . '/../' . $input->getOption('dir'));
        }

        if (!$this->absoluteFixturesPath && !file_exists($this->absoluteFixturesPath)) {
            return $this->writeSection($output, array(
                'The fixtures directory "' . $this->absoluteFixturesPath . '" does not exist.'
            ), 'fg=white;bg=red');
        }

        $noOptions = (!$input->getOption('xml') && !$input->getOption('sql') && !$input->getOption('yml'));

        if ($input->getOption('sql') || $noOptions) {
            if (-1 === $this->loadSqlFixtures($input, $output)) {
                $output->writeln('No <info>SQL</info> fixtures found.');
            }
        }

        if ($input->getOption('xml') || $noOptions) {
            if (-1 === $this->loadFixtures($input, $output, 'xml')) {
                $output->writeln('No <info>XML</info> fixtures found.');
            }
        }

        if ($input->getOption('yml') || $noOptions) {
            if (-1 === $this->loadFixtures($input, $output, 'yml')) {
                $output->writeln('No <info>YML</info> fixtures found.');
            }
        }
    }

    /**
     * Load fixtures
     *
     * @param  \Symfony\Component\Console\Input\InputInterface   $input
     * @param  \Symfony\Component\Console\Output\OutputInterface $output
     * @return void
     */
    protected function loadFixtures(InputInterface $input, OutputInterface $output, $type = null)
    {
        if (null === $type) {
            return;
        }

        $datas = $this->getFixtureFiles($type);

        if (count(iterator_to_array($datas)) === 0) {
            return -1;
        }

        list($name, $defaultConfig) = $this->getConnection($input, $output);

        if ('yml' === $type) {
            $loader = new YamlDataLoader($this->getApplication()->getKernel()->getRootDir(), $this->getContainer());
        } elseif ('xml' === $type) {
            $loader = new XmlDataLoader($this->getApplication()->getKernel()->getRootDir());
        } else {
            return;
        }

        try {
            $nb = $loader->load($datas, $name);
        } catch (\Exception $e) {
            $this->writeSection($output, array(
                '[Propel] Exception',
                '',
                $e->getMessage()), 'fg=white;bg=red');

            return false;
        }

        $output->writeln(sprintf('<comment>%s</comment> %s fixtures file%s loaded.', $nb, strtoupper($type), $nb > 1 ? 's' : ''));

        return true;
    }

    /**
     * Load SQL fixtures
     *
     * @param  \Symfony\Component\Console\Input\InputInterface   $input
     * @param  \Symfony\Component\Console\Output\OutputInterface $output
     * @return void
     */
    protected function loadSqlFixtures(InputInterface $input, OutputInterface $output)
    {
        $tmpdir = $this->getApplication()->getKernel()->getRootDir() . '/cache/propel';
        $datas  = $this->getFixtureFiles('sql');

        $this->prepareCache($tmpdir);

        list($name, $defaultConfig) = $this->getConnection($input, $output);

        // Create a "sqldb.map" file
        $sqldbContent = '';
        foreach ($datas as $data) {
            $output->writeln(sprintf('<info>Loading SQL fixtures from</info> <comment>%s</comment>.', $data));

            $sqldbContent .= $data->getFilename() . '=' . $name . PHP_EOL;
            $this->filesystem->copy($data, $tmpdir . '/fixtures/' . $data->getFilename(), true);
        }

        if ('' === $sqldbContent) {
            return -1;
        }

        $sqldbFile = $tmpdir . '/fixtures/sqldb.map';
        file_put_contents($sqldbFile, $sqldbContent);

        if (!$this->insertSql($defaultConfig, $tmpdir . '/fixtures', $tmpdir, $output)) {
            return -1;
        }

        $this->filesystem->remove($tmpdir);

        return 0;
    }

    /**
     * Prepare the cache directory
     *
     * @param string $tmpdir The temporary directory path.
     */
    protected function prepareCache($tmpdir)
    {
        // Recreate a propel directory in cache
        $this->filesystem->remove($tmpdir);
        $this->filesystem->mkdir($tmpdir);

        $fixturesdir = $tmpdir . '/fixtures/';
        $this->filesystem->remove($fixturesdir);
        $this->filesystem->mkdir($fixturesdir);
    }

    /**
     * Insert SQL
     */
    protected function insertSql($config, $sqlDir, $schemaDir, $output)
    {
        // Insert SQL
        $ret = $this->callPhing('insert-sql', array(
            'propel.database.url'       => $config['connection']['dsn'],
            'propel.database.database'  => $config['adapter'],
            'propel.database.user'      => $config['connection']['user'],
            'propel.database.password'  => $config['connection']['password'],
            'propel.schema.dir'         => $schemaDir,
            'propel.sql.dir'            => $sqlDir,
        ));

        if (true === $ret) {
            $output->writeln('All SQL statements have been inserted.');
        } else {
            $this->writeTaskError($output, 'insert-sql', false);

            return false;
        }

        return true;
    }

    /**
     * Returns the fixtures files to load.
     *
     * @param string $type The extension of the files.
     * @param string $in   The directory in which we search the files. If null,
     *                      we'll use the absoluteFixturesPath property.
     *
     * @return \Iterator An iterator through the files.
     */
    protected function getFixtureFiles($type = 'sql', $in = null)
    {
        $finder = new Finder();
        $finder->sortByName()->name('*.' . $type);

        $files = $finder->in(null !== $in ? $in : $this->absoluteFixturesPath);

        if (null === $this->bundle) {
            return $files;
        }

        $finalFixtureFiles = array();
        foreach ($files as $file) {
            $fixtureFilePath = str_replace($this->getFixturesPath($this->bundle) . DIRECTORY_SEPARATOR, '', $file->getRealPath());
            $logicalName = sprintf('@%s/Resources/fixtures/%s', $this->bundle->getName(), $fixtureFilePath);
            $finalFixtureFiles[] = new \SplFileInfo($this->getFileLocator()->locate($logicalName));
        }

        return new \ArrayIterator($finalFixtureFiles);
    }

    /**
     * Returns the path the command will look into to find fixture files
     *
     * @return String
     */
    protected function getFixturesPath(BundleInterface $bundle)
    {
        return $bundle->getPath() . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'fixtures';
    }
}


text:
<?php

namespace MB\DashboardBundle\Model\Connector;

use MB\DashboardBundle\Model\Project\SourceProjectInterface;
use MB\DashboardBundle\Model\Group\SourceGroupInterface;
use MB\DashboardBundle\Model\Commit\CommitInterface;
interface ConnectorInterface
{
    /**
     * Return the id of the given project raw data
     *
     * @param \stdClass $project
     * @return integer
     */
    public function getProjectId(\stdClass $project);

    /**
     * Return the id of the given project's group raw data
     *
     * @param \stdClass $project
     * @return integer
     */
    public function getGroupId(\stdClass $project);

    /**
     * Return the id of the given commit raw data
     *
     * @param \stdClass $project
     * @return integer
     */
    public function getCommitId(\stdClass $project);

    /**
     * Return the name of the connector
     *
     * @return string
     */
    public function getName();

    /**
     * Return the type of the connector
     *
     * @return string
     */
    public function getType();

    /**
     * Return the list of parameters to include in the GET query
     *
     * @return array
     */
    public function getParamsGet();

    /**
     * Return the list of parameters to include in the POST query
     *
     * @return array
     */
    public function getParamsPost();

    /**
     * Return the list of headers to include to the HTTP query
     *
     * @return array
     */
    public function getHeaders();

    /**
     * Return the user-agent which will be used for the curl query
     *
     * @return string
     */
    public function getUserAgent();

    /**
     * Add the authentication on all curl queries
     */
    public function addAuthentication();

    /**
     * ! Do not call this function yourself !
     *
     * Build the curl query which will be used by execute()
     *
     * @param string $target
     */
    public function prepareQuery($target = null);

    /**
     * Execute the curl query with the configured host for this connection (config.yml) and the given subpath
     *
     * @param string $target
     * @return mixed
     */
    public function execute($target = null);

    /**
     * Import all projects available with the current connection
     *
     * @throws FunctionNotImplementedException
     *
     * @return array
     */
    public function importAllProjects();

    /**
     * Import all projects available with the current connection
     *
     * @param SourceProjectInterface $project
     *
     * @throws FunctionNotImplementedException
     *
     * @return array
     */
    public function importAllCommits(SourceProjectInterface $project);

    /**
     * Fill a given SourceProjectInterface with the given object data
     *
     * @param SourceProjectInterface $project
     * @param \stdClass $data
     * @param SourceGroupInterface $sourceGroup
     *
     * @throws FunctionNotImplementedException
     *
     * @return SourceProjectInterface
     */
    public function fillProject(SourceProjectInterface $project, \stdClass $data, SourceGroupInterface $sourceGroup = null);

    /**
     * Fill a given SourceGroupInterface with the given object data
     *
     * @param SourceGroupInterface $project
     * @param \stdClass $data
     *
     * @throws FunctionNotImplementedException
     *
     * @return SourceGroupInterface
     */
    public function fillGroup(SourceGroupInterface $group, \stdClass $data);

    /**
     * Fill a given CommitInterface with the given object data
     *
     * @param CommitInterface $commit
     * @param \stdClass $data
     * @param SourceProjectInterface $project
     *
     * @throws FunctionNotImplementedException
     *
     * @return CommitInterface
     */
    public function fillCommit(CommitInterface $commit, \stdClass $data, SourceProjectInterface $project);

    /**
     * Refresh the given project information and refresh/include the commits if configured
     *
     * @param SourceProjectInterface $project
     *
     * @throws FunctionNotImplementedException
     *
     * @return \stdClass
     */
    public function importProject(SourceProjectInterface $project);
}


text:
using UnityEngine;
using UnityEngine.UI;

namespace CurvedVRKeyboard {
    [SelectionBase]
    public class KeyboardStatus: KeyboardComponent {

        //------SET IN UNITY-------
        [Tooltip("Text field receiving input from the keyboard")]
        public Text output;
        //@SENIORVRPROJECT
        [Tooltip("bowser receiving input from the keyboard")]
        public ZenFulcrum.EmbeddedBrowser.VRBrowserUI browserUI;
        //@SENIORVRPROJECT
        [Tooltip("Maximum output text length")]
        public int maxOutputLength;

        //----CurrentKeysStatus----
        private KeyboardItem[] keys;
        private bool areLettersActive = true;
        private bool isLowercase = true;
        private static readonly char BLANKSPACE = ' ';

        /// <summary>
        /// Handles click on keyboarditem
        /// </summary>
        /// <param name="clicked">keyboard item clicked</param>
        public void HandleClick ( KeyboardItem clicked ) {
            string value = clicked.GetValue();
            if(value.Equals(QEH) || value.Equals(ABC)) { // special signs pressed
                ChangeSpecialLetters();
            } else if(value.Equals(UP) || value.Equals(LOW)) { // upper/lower case pressed
                LowerUpperKeys();
            } else if(value.Equals(SPACE)) {
                TypeKey(BLANKSPACE);
            } else if(value.Equals(BACK)) {
                BackspaceKey();
            } else {// Normal letter
                TypeKey(value[0]);
            }
        }

        /// <summary>
        /// Displays special signs
        /// </summary>
        private void ChangeSpecialLetters () {
            KeyLetterEnum ToDisplay = areLettersActive ? KeyLetterEnum.NonLetters : KeyLetterEnum.LowerCase;
            areLettersActive =!areLettersActive;
            isLowercase = true;
            for(int i = 0;i < keys.Length;i++) {
                keys[i].SetKeyText(ToDisplay);
            }
        }

        /// <summary>
        /// Changes between lower and upper keys
        /// </summary>
        private void LowerUpperKeys () {
            KeyLetterEnum ToDisplay = isLowercase ? KeyLetterEnum.UpperCase : KeyLetterEnum.LowerCase;
            isLowercase = !isLowercase;
            for(int i = 0;i < keys.Length;i++) {
                keys[i].SetKeyText(ToDisplay);
            }
        }

        private void BackspaceKey()
        {
            //@SENIORVRPROJECT
            if (browserUI != null)
            {
                Event ev = new Event();
                ev.keyCode = KeyCode.Backspace;
                browserUI.InjectKeyEvent(ev);
            }
            if (output != null && output.text.Length >= 1)
                output.text = output.text.Remove(output.text.Length - 1, 1);
            //@SENIORVRPROJECT
        }

        private void TypeKey(char key)
        {
            //@SENIORVRPROJECT
            if (browserUI != null)
            {
                Event ev = new Event();
                ev.character = key;
                ev.keyCode = CharToKeyUnityKeyCode(key);
                browserUI.InjectKeyEvent(ev);
            }

            if (output != null && output.text.Length < maxOutputLength)
                output.text = output.text + key.ToString();
            //@SENIORVRPROJECT
        }
        //@SENIORVRPROJECT
        private KeyCode CharToKeyUnityKeyCode(char key)
        {
            switch (key)
            {
                case 'a':
                    return KeyCode.A;
                case 'b':
                    return KeyCode.B;
                case 'c':
                    return KeyCode.C;
                case 'd':
                    return KeyCode.D;
                case 'e':
                    return KeyCode.E;
                case 'f':
                    return KeyCode.F;
                case 'g':
                    return KeyCode.G;
                case 'h':
                    return KeyCode.H;
                case 'i':
                    return KeyCode.I;
                case 'j':
                    return KeyCode.J;
                case 'k':
                    return KeyCode.K;
                case 'l':
                    return KeyCode.L;
                case 'm':
                    return KeyCode.M;
                case 'n':
                    return KeyCode.N;
                case 'o':
                    return KeyCode.O;
                case 'p':
                    return KeyCode.P;
                case 'q':
                    return KeyCode.Q;
                case 'r':
                    return KeyCode.R;
                case 's':
                    return KeyCode.S;
                case 't':
                    return KeyCode.T;
                case 'u':
                    return KeyCode.U;
                case 'v':
                    return KeyCode.V;
                case 'w':
                    return KeyCode.W;
                case 'x':
                    return KeyCode.X;
                case 'y':
                    return KeyCode.Y;
                case 'z':
                    return KeyCode.Z;
                case '0':
                    return KeyCode.Alpha0;
                case '1':
                    return KeyCode.Alpha1;
                case '2':
                    return KeyCode.Alpha2;
                case '3':
                    return KeyCode.Alpha3;
                case '4':
                    return KeyCode.Alpha4;
                case '5':
                    return KeyCode.Alpha5;
                case '6':
                    return KeyCode.Alpha6;
                case '7':
                    return KeyCode.Alpha7;
                case '8':
                    return KeyCode.Alpha8;
                case '9':
                    return KeyCode.Alpha9;
                case '?':
                    return KeyCode.Question;
                case '!':
                    return KeyCode.Exclaim;
                case '#':
                    return KeyCode.Hash;
                case '.':
                    return KeyCode.Period;
                case '@':
                    return KeyCode.At;
                case '_':
                    return KeyCode.Underscore;
                case '&':
                    return KeyCode.Ampersand;
                case '-':
                    return KeyCode.Minus;
                case '+':
                    return KeyCode.Plus;
                case '(':
                    return KeyCode.LeftParen;
                case ')':
                    return KeyCode.RightParen;
                case '*':
                    return KeyCode.Asterisk;
                case '\"':
                    return KeyCode.DoubleQuote;
                case '\'':
                    return KeyCode.Quote;
                case '/':
                    return KeyCode.Slash;
                case ':':
                    return KeyCode.Colon;
                case ';':
                    return KeyCode.Semicolon;
                case ' ':
                default:
                    return KeyCode.Space;
            }
        }
        //@SENIORVRPROJECT

        public void SetKeys ( KeyboardItem[] keys ) {
            this.keys = keys;
        }
    }
}


text:
Meteor.methods({
	AccountsCreateUser: function(doc) {
console.log("before AccountsCreateUser check");
console.log(doc);
		check(doc, Schemas_User);
		doc.password = doc.profile.password;
		doc.email = doc.profile.email;

console.log("before Accounts.createUser");
console.log(doc);
		var id = Accounts.createUser(doc);
console.log("after Accounts.createUser");
console.log(id);
		Roles.addUsersToRoles(id, [doc.profile.role], Roles.GLOBAL_GROUP);
		return null;
	},

	AccountsChangeUser: function(doc, _id) {
console.log("before AccountsChangeUser check");
console.log(doc);
		check(doc, Schemas_User);
	//	doc.password = doc.profile.password;
	//	doc.email = doc.profile.email;

		try {
			Meteor.users.update({ _id: _id}, doc);
		} catch (e) {
			console.log(e.name);
			console.log(e.message);
			if (e.message.indexOf("profile.username") > 0) {
				throw new Meteor.Error('Username already exists.');
			}
			if (e.message.indexOf("profile.email") > 0) {
				throw new Meteor.Error('Email already exists.');
			}
		}

console.log("before Accounts.setPassword");
console.log(doc['$set']['profile.password']);
		Accounts.setPassword(_id, doc['$set']['profile.password']);
console.log("after Accounts.setPassword");
		return null;
	},

});


text:
namespace minigo {

namespace {

// Returns the Q of the best legal child move for the node.
// Returns the node's Q if there are no legal moves.
float GetBestMoveQ(const MctsNode* node) {
  float scale = node->position.to_play() == Color::kBlack ? 1 : -1;
  float bestChildQ = node->Q();
  for (int i = 0; i < kNumMoves; ++i) {
    if (!node->position.legal_move(i)) {
      continue;
    }
    if (node->child_Q(i) * scale > bestChildQ * scale) {
      bestChildQ = node->child_Q(i);
    }
  }
  return bestChildQ;
}

}  // namespace

MiniguiGtpClient::MiniguiGtpClient(
    std::string device,
    std::shared_ptr<ThreadSafeInferenceCache> inference_cache,
    const std::string& model_path, const Game::Options& game_options,
    const MctsPlayer::Options& player_options,
    const GtpClient::Options& client_options)
    : GtpClient(std::move(device), inference_cache, model_path, game_options,
                player_options, client_options) {
  RegisterCmd("echo", &MiniguiGtpClient::HandleEcho);
  RegisterCmd("genmove", &MiniguiGtpClient::HandleGenmove);
  RegisterCmd("play", &MiniguiGtpClient::HandlePlay);
  RegisterCmd("report_search_interval",
              &MiniguiGtpClient::HandleReportSearchInterval);
  RegisterCmd("select_position", &MiniguiGtpClient::HandleSelectPosition);
  RegisterCmd("winrate_evals", &MiniguiGtpClient::HandleWinrateEvals);

  player_->SetTreeSearchCallback(
      std::bind(&MiniguiGtpClient::TreeSearchCb, this, std::placeholders::_1));

  variation_tree_ = absl::make_unique<VariationTree>();

  int num_workers = 16;
  int num_win_rate_evals = 8;
  auto worker_options = player_options;
  worker_options.virtual_losses = 1;
  win_rate_evaluator_ = absl::make_unique<WinRateEvaluator>(
      num_workers, num_win_rate_evals, device_, inference_cache, model_path,
      game_options, worker_options);
}

MiniguiGtpClient::~MiniguiGtpClient() = default;

void MiniguiGtpClient::NewGame() {
  GtpClient::NewGame();
  variation_tree_ = absl::make_unique<VariationTree>();
  ReportRootPosition();
  RefreshPendingWinRateEvals();
}

void MiniguiGtpClient::Ponder() {
  if (win_rate_evaluator_->all_nodes_have_at_least_one_read()) {
    GtpClient::Ponder();
  }
  win_rate_evaluator_->EvalNodes();
}

GtpClient::Response MiniguiGtpClient::HandleCmd(const std::string& line) {
  auto response = GtpClient::HandleCmd(line);
  // Write __GTP_CMD_DONE__ to stderr to signify that handling a GTP command is
  // done. The Minigui Python server waits for this magic string before it
  // consumes the output of each GTP command. This keeps the outputs written to
  // stderr and stdout synchronized so that all data written to stderr while
  // processing a GTP command is consumed before the GTP result written to
  // stdout.
  MG_LOG(INFO) << "__GTP_CMD_DONE__";
  return response;
}

GtpClient::Response MiniguiGtpClient::HandleEcho(CmdArgs args) {
  return Response::Ok(absl::StrJoin(args, " "));
}

GtpClient::Response MiniguiGtpClient::HandleGenmove(CmdArgs args) {
  ReportSearchStatus(nullptr, true);
  auto response = GtpClient::HandleGenmove(args);
  if (response.ok) {
    variation_tree_->PlayMove(player_->root()->move);
    ReportRootPosition();
  }
  RefreshPendingWinRateEvals();
  return response;
}

GtpClient::Response MiniguiGtpClient::HandlePlay(CmdArgs args) {
  auto response = GtpClient::HandlePlay(args);
  if (response.ok) {
    variation_tree_->PlayMove(player_->root()->move);
    ReportRootPosition();
  }
  RefreshPendingWinRateEvals();
  return response;
}

GtpClient::Response MiniguiGtpClient::HandleReportSearchInterval(CmdArgs args) {
  auto response = CheckArgsExact(1, args);
  if (!response.ok) {
    return response;
  }

  int x;
  if (!absl::SimpleAtoi(args[0], &x) || x < 0) {
    return Response::Error("couldn't parse ", args[0], " as an integer >= 0");
  }
  report_search_interval_ = absl::Milliseconds(x);

  return Response::Ok();
}

GtpClient::Response MiniguiGtpClient::HandleSelectPosition(CmdArgs args) {
  auto response = CheckArgsExact(1, args);
  if (!response.ok) {
    return response;
  }

  if (!variation_tree_->SelectNode(std::string(args[0]))) {
    return Response::Error("unknown position id");
  }

  player_->NewGame();
  for (auto c : variation_tree_->current_node()->GetVariation()) {
    MG_CHECK(player_->PlayMove(c));
  }

  RefreshPendingWinRateEvals();

  return Response::Ok();
}

GtpClient::Response MiniguiGtpClient::HandleWinrateEvals(CmdArgs args) {
  int num_reads;
  if (!absl::SimpleAtoi(args[1], &num_reads) || num_reads < 0) {
    return Response::Error("invalid num_reads");
  }
  win_rate_evaluator_->SetNumEvalReads(num_reads);
  RefreshPendingWinRateEvals();
  return Response::Ok();
}

GtpClient::Response MiniguiGtpClient::ReplaySgf(
    const sgf::Collection& collection) {
  // Traverse the SGF's game trees, loading them into the backend & running
  // inference on the positions in batches.
  std::function<Response(const sgf::Tree&)> traverse =
      [&](const sgf::Tree& tree) {
        const auto* original_root = player_->root();
        // Play moves for all nodes in this tree.
        for (const auto& node : tree.nodes) {
          if (node->move.c == Coord::kInvalid) {
            // Skip nodes that don't contain a move, appending any comments to
            // the current position.
            absl::StrAppend(&variation_tree_->current_node()->comment,
                            node->GetCommentAndProperties());
            continue;
          }

          if (node->move.color != player_->root()->position.to_play()) {
            // The move color is different than expected. Play a pass move to
            // flip the colors.
            if (player_->root()->move == Coord::kPass) {
              auto expected = ColorToCode(player_->root()->position.to_play());
              auto actual = node->move.ToSgf();
              MG_LOG(ERROR)
                  << "expected move by " << expected << ", got " << actual
                  << " but can't play an intermediate pass because the"
                  << " previous move was also a pass";
              return Response::Error("cannot load file");
            }
            MG_LOG(WARNING) << "Inserting pass move";
            MG_CHECK(player_->PlayMove(Coord::kPass));
            variation_tree_->PlayMove(Coord::kPass);
            ReportRootPosition();
          }

          if (!player_->PlayMove(node->move.c)) {
            MG_LOG(ERROR) << "error playing " << node->move.ToSgf();
            return Response::Error("cannot load file");
          }
          variation_tree_->PlayMove(node->move.c);
          variation_tree_->current_node()->comment =
              node->GetCommentAndProperties();
          ReportRootPosition();
        }

        // Traverse all sub-trees.
        for (const auto& sub_tree : tree.sub_trees) {
          auto response = traverse(*sub_tree);
          if (!response.ok) {
            return response;
          }
        }

        // Undo the moves in this tree before returning.
        while (player_->root() != original_root) {
          player_->UndoMove();
          variation_tree_->GoToParent();
        }
        return Response::Ok();
      };

  for (const auto& tree : collection.trees) {
    auto response = traverse(*tree);
    if (!response.ok) {
      return response;
    }
  }

  // Play the main line.
  player_->NewGame();
  variation_tree_->GoToStart();

  // The root node of the SGF is created by NewGame, before the SGF is loaded:
  // explicitly update the root node comment.
  if (!variation_tree_->current_node()->comment.empty()) {
    nlohmann::json j = {
        {"id", variation_tree_->current_node()->id},
        {"comment", variation_tree_->current_node()->comment},
    };
    MG_LOG(INFO) << "mg-update: " << j.dump();
  }

  if (!collection.trees.empty()) {
    for (const auto& move : collection.trees[0]->ExtractMainLine()) {
      // We already validated that all the moves could be played in traverse(),
      // so if PlayMove fails here, something has gone seriously awry.
      MG_CHECK(player_->PlayMove(move.c));
      variation_tree_->PlayMove(move.c);
    }
    RefreshPendingWinRateEvals();
    ReportRootPosition();
  }

  return Response::Ok();
}

void MiniguiGtpClient::ReportSearchStatus(const MctsNode* leaf,
                                          bool include_tree_stats) {
  auto sorted_child_info = player_->tree().CalculateRankedMoveInfo();
  auto* root = player_->root();

  nlohmann::json j = {
      {"id", variation_tree_->current_node()->id},
      {"n", root->N()},
      {"q", GetBestMoveQ(root)},
  };

  // TODO(tommadams): Make the number of child variations sent back
  // configurable.
  nlohmann::json variations;
  for (int i = 0; i < 10; ++i) {
    Coord c = sorted_child_info[i].c;
    const auto child_it = root->children.find(c);
    if (child_it == root->children.end() || root->child_N(c) == 0) {
      break;
    }

    nlohmann::json moves = {c.ToGtp()};
    const auto* node = child_it->second.get();
    for (const auto c : node->GetMostVisitedPath()) {
      moves.push_back(c.ToGtp());
    }
    variations[c.ToGtp()] = {
        {"n", root->child_N(c)},
        {"q", root->child_Q(c)},
        {"moves", std::move(moves)},
    };
  }
  if (!variations.empty()) {
    j["variations"] = std::move(variations);
  }

  // Current live search variation.
  if (leaf != nullptr) {
    std::vector<const MctsNode*> live;
    for (const auto* node = leaf; node != root; node = node->parent) {
      live.push_back(node);
    }
    if (!live.empty()) {
      std::reverse(live.begin(), live.end());
      nlohmann::json moves;
      for (const auto* node : live) {
        moves.push_back(node->move.ToGtp());
      }
      j["variations"]["live"] = {
          {"n", live.front()->N()},
          {"q", GetBestMoveQ(live.front())},
          {"moves", std::move(moves)},
      };
    }
  }

  // Child N.
  auto& child_N = j["childN"];
  for (auto N : root->edges.N) {
    child_N.push_back(static_cast<int>(N));
  }

  // Child Q.
  auto& child_Q = j["childQ"];
  for (int i = 0; i < kNumMoves; ++i) {
    child_Q.push_back(static_cast<int>(std::round(root->child_Q(i) * 1000)));
  }

  if (include_tree_stats) {
    auto tree_stats = player_->tree().CalculateStats();
    j["treeStats"] = {
        {"numNodes", tree_stats.num_nodes},
        {"numLeafNodes", tree_stats.num_leaf_nodes},
        {"maxDepth", tree_stats.max_depth},
    };
  }

  MG_LOG(INFO) << "mg-update:" << j.dump();
}

void MiniguiGtpClient::ReportRootPosition() {
  const auto* root = player_->root();
  const auto& position = root->position;

  std::ostringstream oss;
  for (const auto& stone : position.stones()) {
    char ch;
    if (stone.color() == Color::kBlack) {
      ch = 'X';
    } else if (stone.color() == Color::kWhite) {
      ch = 'O';
    } else {
      ch = '.';
    }
    oss << ch;
  }

  nlohmann::json j = {
      {"id", variation_tree_->current_node()->id},
      {"toPlay", position.to_play() == Color::kBlack ? "B" : "W"},
      {"moveNum", position.n()},
      {"stones", oss.str()},
      {"gameOver", root->game_over()},
  };

  const auto& captures = position.num_captures();
  if (captures[0] != 0 || captures[1] != 0) {
    j["caps"].push_back(captures[0]);
    j["caps"].push_back(captures[1]);
  }
  if (root->parent != nullptr) {
    j["parentId"] = variation_tree_->current_node()->parent->id;
    if (root->N() > 0) {
      // Only send Q if the node has been read at least once.
      j["q"] = GetBestMoveQ(root);
    }
  }
  if (root->move != Coord::kInvalid) {
    j["move"] = root->move.ToGtp();
  }
  const auto& comment = variation_tree_->current_node()->comment;
  if (!comment.empty()) {
    j["comment"] = comment;
  }

  MG_LOG(INFO) << "mg-position: " << j.dump();
}

void MiniguiGtpClient::RefreshPendingWinRateEvals() {
  // Build a new list of nodes that require win rate evaluation.
  // First, traverse to the leaf node of the current position's main line.
  auto* node = variation_tree_->current_node();
  while (!node->children.empty()) {
    node = node->children[0];
  }

  std::vector<VariationTree::Node*> variation;
  while (node != nullptr) {
    variation.push_back(node);
    node = node->parent;
  }
  std::reverse(variation.begin(), variation.end());

  win_rate_evaluator_->SetCurrentVariation(std::move(variation));
}

void MiniguiGtpClient::TreeSearchCb(
    const std::vector<const MctsNode*>& leaves) {
  if (!leaves.empty() && report_search_interval_ != absl::ZeroDuration()) {
    auto now = absl::Now();
    if (now - last_report_time_ > report_search_interval_) {
      last_report_time_ = now;
      ReportSearchStatus(leaves.back(), false);
    }
  }
}

MiniguiGtpClient::VariationTree::Node::Node(Node* parent, Coord move)
    : parent(parent),
      move(move),
      id(parent == nullptr ? "root" : absl::StrFormat("%p", this)),
      n(parent != nullptr ? parent->n + 1 : 0) {}

std::vector<Coord> MiniguiGtpClient::VariationTree::Node::GetVariation() const {
  std::vector<Coord> variation;
  for (auto* node = this; node->parent != nullptr; node = node->parent) {
    variation.push_back(node->move);
  }
  std::reverse(variation.begin(), variation.end());
  return variation;
}

MiniguiGtpClient::VariationTree::VariationTree() {
  auto root = absl::make_unique<Node>(nullptr, Coord::kInvalid);
  current_node_ = root.get();
  id_map_.emplace(root->id, std::move(root));
}

void MiniguiGtpClient::VariationTree::PlayMove(Coord c) {
  // Check if the current node already has a child with the given move.
  for (auto* child : current_node_->children) {
    if (child->move == c) {
      current_node_ = child;
      return;
    }
  }

  // Create a new child.
  auto child = absl::make_unique<Node>(current_node_, c);
  current_node_->children.push_back(child.get());
  current_node_ = current_node_->children.back();
  id_map_.emplace(current_node_->id, std::move(child));
}

void MiniguiGtpClient::VariationTree::GoToParent() {
  MG_CHECK(current_node_->parent != nullptr);
  current_node_ = current_node_->parent;
}

void MiniguiGtpClient::VariationTree::GoToStart() {
  while (current_node_->parent != nullptr) {
    current_node_ = current_node_->parent;
  }
}

bool MiniguiGtpClient::VariationTree::SelectNode(const std::string& id) {
  auto it = id_map_.find(id);
  if (it == id_map_.end()) {
    return false;
  }
  current_node_ = it->second.get();
  return true;
}

MiniguiGtpClient::WinRateEvaluator::WinRateEvaluator(
    int num_workers, int num_eval_reads, const std::string& device,
    std::shared_ptr<ThreadSafeInferenceCache> inference_cache,
    const std::string& model_path, const Game::Options& game_options,
    const MctsPlayer::Options& player_options)
    : num_eval_reads_(num_eval_reads) {
  MG_CHECK(inference_cache != nullptr);

  batcher_ = absl::make_unique<BatchingModelFactory>(device, 2);
  for (int i = 0; i < num_workers; ++i) {
    auto game = absl::make_unique<Game>("b", "w", game_options);
    auto player = absl::make_unique<MctsPlayer>(batcher_->NewModel(model_path),
                                                inference_cache, game.get(),
                                                player_options);
    workers_.push_back(absl::make_unique<Worker>(
        std::move(game), std::move(player), &eval_queue_));
    workers_.back()->Start();
  }
}

MiniguiGtpClient::WinRateEvaluator::~WinRateEvaluator() = default;

void MiniguiGtpClient::WinRateEvaluator::SetNumEvalReads(int num_eval_reads) {
  num_eval_reads_ = num_eval_reads;
  UpdateNodesToEval();
}

void MiniguiGtpClient::WinRateEvaluator::SetCurrentVariation(
    std::vector<VariationTree::Node*> nodes) {
  variation_ = std::move(nodes);
  UpdateNodesToEval();
}

void MiniguiGtpClient::WinRateEvaluator::EvalNodes() {
  auto num_inferences = std::min(workers_.size(), to_eval_.size());
  if (num_inferences == 0) {
    return;
  }

  // Inform each worker how many inferences we want to run in parallel.
  // This allows the batcher to know how many inferences to expect.
  for (size_t i = 0; i < num_inferences; ++i) {
    workers_[i]->Prepare();
  }

  // Run win rate evaluation in parallel.
  for (size_t i = 0; i < num_inferences; ++i) {
    workers_[i]->EvalAsync(to_eval_.front());
    to_eval_.pop_front();
  }

  // Wait for the workers to finish.
  for (size_t i = 0; i < num_inferences; ++i) {
    auto* node = eval_queue_.Pop();
    // auto* node = workers_[i]->Wait();
    if (node->num_eval_reads < num_eval_reads_) {
      to_eval_.push_back(node);
    }
  }
}

void MiniguiGtpClient::WinRateEvaluator::UpdateNodesToEval() {
  to_eval_.clear();
  for (auto* node : variation_) {
    if (node->num_eval_reads < num_eval_reads_) {
      to_eval_.push_back(node);
    }
  }

  // Sort the nodes for eval by number of eval reads, breaking ties by the move
  // number.
  std::sort(to_eval_.begin(), to_eval_.end(),
            [](VariationTree::Node* a, VariationTree::Node* b) {
              if (a->num_eval_reads != b->num_eval_reads) {
                return a->num_eval_reads < b->num_eval_reads;
              }
              return a->n < b->n;
            });
}

MiniguiGtpClient::WinRateEvaluator::Worker::Worker(
    std::unique_ptr<Game> game, std::unique_ptr<MctsPlayer> player,
    ThreadSafeQueue<VariationTree::Node*>* eval_queue)
    : game_(std::move(game)),
      player_(std::move(player)),
      eval_queue_(eval_queue) {}

MiniguiGtpClient::WinRateEvaluator::Worker::~Worker() {
  absl::MutexLock lock(&mutex_);
  MG_CHECK(!pending_.has_value());
  pending_ = nullptr;
  Join();
}

void MiniguiGtpClient::WinRateEvaluator::Worker::Prepare() {
  absl::MutexLock lock(&mutex_);
  BatchingModelFactory::StartGame(player_->model(), player_->model());
}

void MiniguiGtpClient::WinRateEvaluator::Worker::EvalAsync(
    VariationTree::Node* node) {
  absl::MutexLock lock(&mutex_);
  MG_CHECK(!pending_.has_value());
  pending_ = node;
}

void MiniguiGtpClient::WinRateEvaluator::Worker::Run() {
  for (;;) {
    absl::MutexLock lock(&mutex_);
    mutex_.Await(absl::Condition(this, &Worker::has_pending_value));
    auto* node = *pending_;
    pending_.reset();
    if (node == nullptr) {
      break;
    }

    player_->NewGame();
    for (auto c : node->GetVariation()) {
      MG_CHECK(player_->PlayMove(c));
    }
    player_->TreeSearch(player_->options().virtual_losses, 1024);
    BatchingModelFactory::EndGame(player_->model(), player_->model());

    nlohmann::json j = {
        {"id", node->id},
        {"n", player_->root()->N()},
        {"q", GetBestMoveQ(player_->root())},
    };
    MG_LOG(INFO) << "mg-update:" << j.dump();

    node->num_eval_reads = player_->root()->N();
    eval_queue_->Push(node);
  }
}

}  // namespace minigo


text:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="scripts/jquery-2.1.1.min.js"></script>
</head>
<body>
    <div id="target">
        This functionality is native in jQuery
    </div>
    <script src="scripts/2.add-before-or-after.js"></script>
</body>
</html>


text:
html, body, div, span, applet, object, iframe,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    box-sizing: border-box;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}


text:
include_recipe 'mongodb::mongo_gem'

users = []
admin = node['mongodb']['admin']

# If authentication is required,
# add the admin to the users array for adding/updating
users << admin if node['mongodb']['config']['auth'] == true

users.concat(node['mongodb']['users'])

# Add each user specified in attributes
users.each do |user|
  mongodb_user user['username'] do
    password user['password']
    roles user['roles']
    database user['database']
    connection node['mongodb']
    action :add
  end
end


text:
<?php
namespace Contato;

class Module
{
    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getViewHelperConfig()
    {
        return array(
            'factories' => array(
               'menu_ativo' => function($sm){
                    return new View\Helper\MenuAtivo($sm->getServiceLocator()->get('Request'));
               },
                'message' => function($sm) {
                    return new View\Helper\Message($sm->getServiceLocator()->get('ControllerPluginManager')->get('flashmessenger'));
                },
            ),
        );
    }
}


text:
#pragma once
#include <aws/elasticache/ElastiCache_EXPORTS.h>
#include <aws/elasticache/ElastiCacheRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace ElastiCache
{
namespace Model
{

  /**
   *
Represents the input of a DeleteCacheSecurityGroup
   * operation.

   */
  class AWS_ELASTICACHE_API DeleteCacheSecurityGroupRequest : public ElastiCacheRequest
  {
  public:
    DeleteCacheSecurityGroupRequest();
    Aws::String SerializePayload() const override;

    /**
     *
The name of the cache security group to delete.
 <note>
You cannot
     * delete the default security group.
 </note>
     */
    inline const Aws::String& GetCacheSecurityGroupName() const{ return m_cacheSecurityGroupName; }

    /**
     *
The name of the cache security group to delete.
 <note>
You cannot
     * delete the default security group.
 </note>
     */
    inline void SetCacheSecurityGroupName(const Aws::String& value) { m_cacheSecurityGroupNameHasBeenSet = true; m_cacheSecurityGroupName = value; }

    /**
     *
The name of the cache security group to delete.
 <note>
You cannot
     * delete the default security group.
 </note>
     */
    inline void SetCacheSecurityGroupName(Aws::String&& value) { m_cacheSecurityGroupNameHasBeenSet = true; m_cacheSecurityGroupName = value; }

    /**
     *
The name of the cache security group to delete.
 <note>
You cannot
     * delete the default security group.
 </note>
     */
    inline void SetCacheSecurityGroupName(const char* value) { m_cacheSecurityGroupNameHasBeenSet = true; m_cacheSecurityGroupName.assign(value); }

    /**
     *
The name of the cache security group to delete.
 <note>
You cannot
     * delete the default security group.
 </note>
     */
    inline DeleteCacheSecurityGroupRequest& WithCacheSecurityGroupName(const Aws::String& value) { SetCacheSecurityGroupName(value); return *this;}

    /**
     *
The name of the cache security group to delete.
 <note>
You cannot
     * delete the default security group.
 </note>
     */
    inline DeleteCacheSecurityGroupRequest& WithCacheSecurityGroupName(Aws::String&& value) { SetCacheSecurityGroupName(value); return *this;}

    /**
     *
The name of the cache security group to delete.
 <note>
You cannot
     * delete the default security group.
 </note>
     */
    inline DeleteCacheSecurityGroupRequest& WithCacheSecurityGroupName(const char* value) { SetCacheSecurityGroupName(value); return *this;}

  private:
    Aws::String m_cacheSecurityGroupName;
    bool m_cacheSecurityGroupNameHasBeenSet;
  };

} // namespace Model
} // namespace ElastiCache
} // namespace Aws


text:
/* Author: Ryu Woon Jung (Leon) */

//
// *********     Sync Read and Sync Write Example      *********
//
//
// Available Dynamixel model on this example : All models using Protocol 2.0
// This example is tested with two Dynamixel PRO 54-200, and an USB2DYNAMIXEL
// Be sure that Dynamixel PRO properties are already set as %% ID : 1 / Baudnum : 1 (Baudrate : 57600)
//

#if defined(__linux__) || defined(__APPLE__)
#include <fcntl.h>
#include <termios.h>
#define STDIN_FILENO 0
#elif defined(_WIN32) || defined(_WIN64)
#include <conio.h>
#endif

#include <stdlib.h>
#include <stdio.h>

#include "dynamixel_sdk.h"                                  // Uses Dynamixel SDK library

// Control table address
#define ADDR_PRO_TORQUE_ENABLE          562                 // Control table address is different in Dynamixel model
#define ADDR_PRO_GOAL_POSITION          596
#define ADDR_PRO_PRESENT_POSITION       611

// Data Byte Length
#define LEN_PRO_GOAL_POSITION           4
#define LEN_PRO_PRESENT_POSITION        4

// Protocol version
#define PROTOCOL_VERSION                2.0                 // See which protocol version is used in the Dynamixel

// Default setting
#define DXL1_ID                         1                   // Dynamixel#1 ID: 1
#define DXL2_ID                         2                   // Dynamixel#2 ID: 2
#define BAUDRATE                        57600
#define DEVICENAME                      "/dev/ttyUSB0"      // Check which port is being used on your controller
                                                            // ex) Windows: "COM1"   Linux: "/dev/ttyUSB0" Mac: "/dev/tty.usbserial-*"

#define TORQUE_ENABLE                   1                   // Value for enabling the torque
#define TORQUE_DISABLE                  0                   // Value for disabling the torque
#define DXL_MINIMUM_POSITION_VALUE      -150000             // Dynamixel will rotate between this value
#define DXL_MAXIMUM_POSITION_VALUE      150000              // and this value (note that the Dynamixel would not move when the position value is out of movable range. Check e-manual about the range of the Dynamixel you use.)
#define DXL_MOVING_STATUS_THRESHOLD     20                  // Dynamixel moving status threshold

#define ESC_ASCII_VALUE                 0x1b

int getch()
{
#if defined(__linux__) || defined(__APPLE__)
  struct termios oldt, newt;
  int ch;
  tcgetattr(STDIN_FILENO, &oldt);
  newt = oldt;
  newt.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &newt);
  ch = getchar();
  tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
  return ch;
#elif defined(_WIN32) || defined(_WIN64)
  return _getch();
#endif
}

int kbhit(void)
{
#if defined(__linux__) || defined(__APPLE__)
  struct termios oldt, newt;
  int ch;
  int oldf;

  tcgetattr(STDIN_FILENO, &oldt);
  newt = oldt;
  newt.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &newt);
  oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
  fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

  ch = getchar();

  tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
  fcntl(STDIN_FILENO, F_SETFL, oldf);

  if (ch != EOF)
  {
    ungetc(ch, stdin);
    return 1;
  }

  return 0;
#elif defined(_WIN32) || defined(_WIN64)
  return _kbhit();
#endif
}

int main()
{
  // Initialize PortHandler instance
  // Set the port path
  // Get methods and members of PortHandlerLinux or PortHandlerWindows
  dynamixel::PortHandler *portHandler = dynamixel::PortHandler::getPortHandler(DEVICENAME);

  // Initialize PacketHandler instance
  // Set the protocol version
  // Get methods and members of Protocol1PacketHandler or Protocol2PacketHandler
  dynamixel::PacketHandler *packetHandler = dynamixel::PacketHandler::getPacketHandler(PROTOCOL_VERSION);

  // Initialize GroupSyncWrite instance
  dynamixel::GroupSyncWrite groupSyncWrite(portHandler, packetHandler, ADDR_PRO_GOAL_POSITION, LEN_PRO_GOAL_POSITION);

  // Initialize Groupsyncread instance for Present Position
  dynamixel::GroupSyncRead groupSyncRead(portHandler, packetHandler, ADDR_PRO_PRESENT_POSITION, LEN_PRO_PRESENT_POSITION);

  int index = 0;
  int dxl_comm_result = COMM_TX_FAIL;               // Communication result
  bool dxl_addparam_result = false;                 // addParam result
  bool dxl_getdata_result = false;                  // GetParam result
  int dxl_goal_position[2] = {DXL_MINIMUM_POSITION_VALUE, DXL_MAXIMUM_POSITION_VALUE};  // Goal position

  uint8_t dxl_error = 0;                            // Dynamixel error
  uint8_t param_goal_position[4];
  int32_t dxl1_present_position = 0, dxl2_present_position = 0;                         // Present position

  // Open port
  if (portHandler->openPort())
  {
    printf("Succeeded to open the port!\n");
  }
  else
  {
    printf("Failed to open the port!\n");
    printf("Press any key to terminate...\n");
    getch();
    return 0;
  }

  // Set port baudrate
  if (portHandler->setBaudRate(BAUDRATE))
  {
    printf("Succeeded to change the baudrate!\n");
  }
  else
  {
    printf("Failed to change the baudrate!\n");
    printf("Press any key to terminate...\n");
    getch();
    return 0;
  }

  // Enable Dynamixel#1 Torque
  dxl_comm_result = packetHandler->write1ByteTxRx(portHandler, DXL1_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_ENABLE, &dxl_error);
  if (dxl_comm_result != COMM_SUCCESS)
  {
    printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result));
  }
  else if (dxl_error != 0)
  {
    printf("%s\n", packetHandler->getRxPacketError(dxl_error));
  }
  else
  {
    printf("Dynamixel#%d has been successfully connected \n", DXL1_ID);
  }

  // Enable Dynamixel#2 Torque
  dxl_comm_result = packetHandler->write1ByteTxRx(portHandler, DXL2_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_ENABLE, &dxl_error);
  if (dxl_comm_result != COMM_SUCCESS)
  {
    printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result));
  }
  else if (dxl_error != 0)
  {
    printf("%s\n", packetHandler->getRxPacketError(dxl_error));
  }
  else
  {
    printf("Dynamixel#%d has been successfully connected \n", DXL2_ID);
  }

  // Add parameter storage for Dynamixel#1 present position value
  dxl_addparam_result = groupSyncRead.addParam(DXL1_ID);
  if (dxl_addparam_result != true)
  {
    fprintf(stderr, "[ID:%03d] groupSyncRead addparam failed", DXL1_ID);
    return 0;
  }

  // Add parameter storage for Dynamixel#2 present position value
  dxl_addparam_result = groupSyncRead.addParam(DXL2_ID);
  if (dxl_addparam_result != true)
  {
    fprintf(stderr, "[ID:%03d] groupSyncRead addparam failed", DXL2_ID);
    return 0;
  }

  while(1)
  {
    printf("Press any key to continue! (or press ESC to quit!)\n");
    if (getch() == ESC_ASCII_VALUE)
      break;

    // Allocate goal position value into byte array
    param_goal_position[0] = DXL_LOBYTE(DXL_LOWORD(dxl_goal_position[index]));
    param_goal_position[1] = DXL_HIBYTE(DXL_LOWORD(dxl_goal_position[index]));
    param_goal_position[2] = DXL_LOBYTE(DXL_HIWORD(dxl_goal_position[index]));
    param_goal_position[3] = DXL_HIBYTE(DXL_HIWORD(dxl_goal_position[index]));

    // Add Dynamixel#1 goal position value to the Syncwrite storage
    dxl_addparam_result = groupSyncWrite.addParam(DXL1_ID, param_goal_position);
    if (dxl_addparam_result != true)
    {
      fprintf(stderr, "[ID:%03d] groupSyncWrite addparam failed", DXL1_ID);
      return 0;
    }

    // Add Dynamixel#2 goal position value to the Syncwrite parameter storage
    dxl_addparam_result = groupSyncWrite.addParam(DXL2_ID, param_goal_position);
    if (dxl_addparam_result != true)
    {
      fprintf(stderr, "[ID:%03d] groupSyncWrite addparam failed", DXL2_ID);
      return 0;
    }

    // Syncwrite goal position
    dxl_comm_result = groupSyncWrite.txPacket();
    if (dxl_comm_result != COMM_SUCCESS) printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result));

    // Clear syncwrite parameter storage
    groupSyncWrite.clearParam();

    do
    {
      // Syncread present position
      dxl_comm_result = groupSyncRead.txRxPacket();
      if (dxl_comm_result != COMM_SUCCESS)
      {
        printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result));
      }
      else if (groupSyncRead.getError(DXL1_ID, &dxl_error))
      {
        printf("[ID:%03d] %s\n", DXL1_ID, packetHandler->getRxPacketError(dxl_error));
      }
      else if (groupSyncRead.getError(DXL2_ID, &dxl_error))
      {
        printf("[ID:%03d] %s\n", DXL2_ID, packetHandler->getRxPacketError(dxl_error));
      }

      // Check if groupsyncread data of Dynamixel#1 is available
      dxl_getdata_result = groupSyncRead.isAvailable(DXL1_ID, ADDR_PRO_PRESENT_POSITION, LEN_PRO_PRESENT_POSITION);
      if (dxl_getdata_result != true)
      {
        fprintf(stderr, "[ID:%03d] groupSyncRead getdata failed", DXL1_ID);
        return 0;
      }

      // Check if groupsyncread data of Dynamixel#2 is available
      dxl_getdata_result = groupSyncRead.isAvailable(DXL2_ID, ADDR_PRO_PRESENT_POSITION, LEN_PRO_PRESENT_POSITION);
      if (dxl_getdata_result != true)
      {
        fprintf(stderr, "[ID:%03d] groupSyncRead getdata failed", DXL2_ID);
        return 0;
      }

      // Get Dynamixel#1 present position value
      dxl1_present_position = groupSyncRead.getData(DXL1_ID, ADDR_PRO_PRESENT_POSITION, LEN_PRO_PRESENT_POSITION);

      // Get Dynamixel#2 present position value
      dxl2_present_position = groupSyncRead.getData(DXL2_ID, ADDR_PRO_PRESENT_POSITION, LEN_PRO_PRESENT_POSITION);

      printf("[ID:%03d] GoalPos:%03d  PresPos:%03d\t[ID:%03d] GoalPos:%03d  PresPos:%03d\n", DXL1_ID, dxl_goal_position[index], dxl1_present_position, DXL2_ID, dxl_goal_position[index], dxl2_present_position);

    }while((abs(dxl_goal_position[index] - dxl1_present_position) > DXL_MOVING_STATUS_THRESHOLD) || (abs(dxl_goal_position[index] - dxl2_present_position) > DXL_MOVING_STATUS_THRESHOLD));

    // Change goal position
    if (index == 0)
    {
      index = 1;
    }
    else
    {
      index = 0;
    }
  }

  // Disable Dynamixel#1 Torque
  dxl_comm_result = packetHandler->write1ByteTxRx(portHandler, DXL1_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_DISABLE, &dxl_error);
  if (dxl_comm_result != COMM_SUCCESS)
  {
    printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result));
  }
  else if (dxl_error != 0)
  {
    printf("%s\n", packetHandler->getRxPacketError(dxl_error));
  }

  // Disable Dynamixel#2 Torque
  dxl_comm_result = packetHandler->write1ByteTxRx(portHandler, DXL2_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_DISABLE, &dxl_error);
  if (dxl_comm_result != COMM_SUCCESS)
  {
    printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result));
  }
  else if (dxl_error != 0)
  {
    printf("%s\n", packetHandler->getRxPacketError(dxl_error));
  }

  // Close port
  portHandler->closePort();

  return 0;
}


text:
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  <title>Mixmax · Quick Charts by Sammie Bae</title>

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

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css">

  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.1/nv.d3.min.css">

    Create a chart

      <select id="chart-type">
        <option value="pie">Pie</option>
        <option value="bar">Bar</option>
      </select>
      Choose Chart Type

    <select id="input-type">
      <option value="space"> (space)</option>
      <option value="comma">, (comma)</option>
    </select>
    Seperate by

<form id="test-form" class="row">

      <input placeholder="Enter seperated label values" id="labels" type="text" class="validate">
      Labels

      <input placeholder="Enter seperated data values" id="datas" type="text" class="validate">
      Data Entries

  Submit

  <svg></svg>

Attach Graph
<canvas id="canvas" width="400" height="400"></canvas>


text:
<?php
/*
 * PIP v0.5.3
 */

//Start the Session
session_start();

// Defines
define('ROOT_DIR', realpath(dirname(__FILE__)) .'/');
define('APP_DIR', ROOT_DIR .'application/');

// FOR INSTALLER
$_CF_FILE = APP_DIR .'config/config.php';
if (!file_exists($_CF_FILE)) {
	echo '
';
	echo 'It Seems you did not set up the MonoLead. Please go here: Setup';
	echo '
';
	die();
}

// Includes
require(APP_DIR .'config/config.php');
require(ROOT_DIR .'system/model.php');
require(ROOT_DIR .'system/view.php');
require(ROOT_DIR .'system/controller.php');
require(ROOT_DIR .'system/pip.php');

// Define base URL
global $config;
define('BASE_URL', $config['base_url']);
define('STATIC_DIR', $config['base_url'].'static/');

function pr($var) {
	$template = php_sapi_name() !== 'cli' ? '
%s
' : "\n%s\n";
	printf($template, print_r($var, true));

}

pip();

?>