text:
import os
import logging

##########################################################################
# Core Err configuration                                                 #
##########################################################################

# BACKEND selection.
# This configures the type of chat server you which to use Err with.
#
# The current choices:

# Debug backends to test your plugins manually:
# 'Text'     - on the text console
# 'Graphic'  - in a GUI window

# Commercial backends:
# 'Campfire' - see https://campfirenow.com/
# 'Hipchat'  - see https://www.hipchat.com/
# 'Slack'    - see https://slack.com/

# Open protocols:
# 'TOX'      - see https://tox.im/
# 'IRC'      - for classic IRC or bridged services like https://gitter.im
# 'XMPP'

BACKEND = os.environ.get('BACKEND', 'Text')

# The location where all of Err's data should be stored. Make sure to set
# this to a directory that is writable by the user running the bot.
BOT_DATA_DIR = '/srv/data'

# Set this to a directory on your system where you want to load extra
# plugins from, which is useful mostly if you want to develop a plugin
# locally before publishing it. Note that you can specify only a single
# directory, however you are free to create subdirectories with multiple
# plugins inside this directory.
BOT_EXTRA_PLUGIN_DIR = '/srv/plugins'

# If you use an external backend as a plugin,
# this is where you tell err where to find it.
BOT_EXTRA_BACKEND_DIR = '/srv/errbackends'

# Should plugin dependencies be installed automatically? If this is true
# then Err will use pip to install any missing dependencies automatically.
#
# If you have installed Err in a virtualenv, this will run the equivalent
# of `pip install -r requirements.txt`.
# If no virtualenv is detected, the equivalent of `pip install --user -r
# requirements.txt` is used to ensure the package(s) is/are only installed for
# the user running Err.
if 'AUTOINSTALL_DEPS' in os.environ:
    AUTOINSTALL_DEPS = os.environ['AUTOINSTALL_DEPS']
else:
    AUTOINSTALL_DEPS = False

# The location of the log file. If you set this to None, then logging will
# happen to console only.
BOT_LOG_FILE = '/srv/err.log'

# The verbosity level of logging that is done to the above logfile, and to
# the console. This takes the standard Python logging levels, DEBUG, INFO,
# WARN, ERROR. For more info, see http://docs.python.org/library/logging.html
#
# If you encounter any issues with Err, please set your log level to
# logging.DEBUG and attach a log with your bug report to aid the developers
# in debugging the issue.
BOT_LOG_LEVEL = logging.getLevelName(os.environ.get('BOT_LOG_LEVEL', 'INFO'))

# Enable logging to sentry (find out more about sentry at www.getsentry.com).
# This is optional and disabled by default.
SENTRY_DSN = os.environ.get('SENTRY_DSN', '')
BOT_LOG_SENTRY = bool(SENTRY_DSN)
SENTRY_LOGLEVEL = BOT_LOG_LEVEL

# Execute commands in asynchronous mode. In this mode, Err will spawn 3
# seperate threads to handle commands, instead of blocking on each
# single command.
BOT_ASYNC = True

##########################################################################
# Account and chatroom (MUC) configuration                               #
##########################################################################

BOT_IDENTITY = {}

# username
if 'BOT_USERNAME' in os.environ:
    BOT_IDENTITY['username'] = os.environ['BOT_USERNAME']

# password
if 'BOT_PASSWORD' in os.environ:
    BOT_IDENTITY['password'] = os.environ['BOT_PASSWORD']

# server
if 'BOT_SERVER' in os.environ:
    if ':' in os.environ['BOT_SERVER']:
        server, port = os.environ['BOT_SERVER'].split(':')
        BOT_IDENTITY['server'] = (server, int(port))
    else:
        BOT_IDENTITY['server'] = os.environ['BOT_SERVER']

# token
if 'BOT_TOKEN' in os.environ:
    BOT_IDENTITY['token'] = os.environ['BOT_TOKEN']

# endpoint
if 'BOT_ENDPOINT' in os.environ:
    BOT_IDENTITY['endpoint'] = os.environ['BOT_ENDPOINT']

# nickname
if 'BOT_NICKNAME' in os.environ:
    BOT_IDENTITY['nickname'] = os.environ['BOT_NICKNAME']

# port
if 'BOT_PORT' in os.environ:
    BOT_IDENTITY['port'] = os.environ['BOT_PORT']

# ssl
if 'BOT_SSL' in os.environ:
    BOT_IDENTITY['ssl'] = os.environ['BOT_SSL']

# The identity, or credentials, used to connect to a server
# BOT_IDENTITY = {
# XMPP (Jabber) mode
# 'username': 'err@localhost',  # The JID of the user you have created for the bot
# 'password': 'changeme',       # The corresponding password for this user
# 'server': ('host.domain.tld',5222), # server override

# Slack Mode (comment the others above if using this mode)
# 'token': 'xoxb-4426949411-aEM7...',

# BOT_ADMINS = ['F9886B47503FB80E6347CC0907D8000144305796DE54693253AA5E574E5E8106C7D002557189', ]
BOT_ADMINS = tuple(
    os.environ.get('BOT_ADMINS', 'admin@localhost').split(','),
)
# Chatrooms your bot should join on startup. For the IRC backend you
# should include the # sign here. For XMPP rooms that are password
# protected, you can specify another tuple here instead of a string,
# using the format (RoomName, Password).
CHATROOM_PRESENCE = tuple(
    os.environ.get('CHATROOM_PRESENCE',
                   'err@conference.localhost').split(','),
)
# The FullName, or nickname, your bot should use. What you set here will
# be the nickname that Err shows in chatrooms. Note that some XMPP
# implementations, notably HipChat, are very picky about what name you
# use. In the case of HipChat, make sure this matches exactly with the
# name you gave the user.
CHATROOM_FN = os.environ.get('CHATROOM_FN', 'Err')

##########################################################################
# Prefix configuration                                                   #
##########################################################################

# Command prefix, the prefix that is expected in front of commands directed
# at the bot.
#
# Note: When writing plugins,you should always use the default '!'.
# If the prefix is changed from the default, the help strings will be
# automatically adjusted for you.
#
BOT_PREFIX = os.environ.get('BOT_PREFIX', '!')

# Uncomment the following and set it to True if you want the prefix to be
# optional for normal chat.
# (Meaning messages sent directly to the bot as opposed to within a MUC)
# BOT_PREFIX_OPTIONAL_ON_CHAT = False
BOT_PREFIX_OPTIONAL_ON_CHAT = bool(
    os.environ.get('BOT_PREFIX_OPTIONAL_ON_CHAT', False)
)

# You might wish to have your bot respond by being called with certain
# names, rather than the BOT_PREFIX above. This option allows you to
# specify alternative prefixes the bot will respond to in addition to
# the prefix above.
# BOT_ALT_PREFIXES = ('Err',)
BOT_ALT_PREFIXES = tuple(
    os.environ.get('BOT_ALT_PREFIXES', 'Err').split(','),
)

# If you use alternative prefixes, you might want to allow users to insert
# separators like , and ; between the prefix and the command itself. This
# allows users to refer to your bot like this (Assuming 'Err' is in your
# BOT_ALT_PREFIXES):
# "Err, status" or "Err: status"
#
# Note: There's no need to add spaces to the separators here
#
# BOT_ALT_PREFIX_SEPARATORS = (':', ',', ';')
BOT_ALT_PREFIX_SEPARATORS = tuple(
    os.environ.get('BOT_ALT_PREFIX_SEPARATORS', ': , ;').split(' '),
)

# Continuing on this theme, you might want to permit your users to be
# lazy and not require correct capitalization, so they can do 'Err',
# 'err' or even 'ERR'.
# BOT_ALT_PREFIX_CASEINSENSITIVE = True
BOT_ALT_PREFIX_CASEINSENSITIVE = bool(
    os.environ.get('BOT_ALT_PREFIX_CASEINSENSITIVE', False)
)

##########################################################################
# Access controls and message diversion                                  #
##########################################################################

# Access controls, allowing commands to be restricted to specific users/rooms.
# Available filters (you can omit a filter or set it to None to disable it):
#   allowusers: Allow command from these users only
#   denyusers: Deny command from these users
#   allowrooms: Allow command only in these rooms (and direct messages)
#   denyrooms: Deny command in these rooms
#   allowprivate: Allow command from direct messages to the bot
#   allowmuc: Allow command inside rooms
# Rules listed in ACCESS_CONTROLS_DEFAULT are applied when a command cannot
# be found inside ACCESS_CONTROLS
#
# Example:
# ACCESS_CONTROLS_DEFAULT = {} # Allow everyone access by default
# ACCESS_CONTROLS = {'status': {'allowrooms': ('someroom@conference.localhost',)},
#                   'about': {'denyusers': ('baduser@localhost',), 'allowrooms': ('room1@conference.localhost', 'room2@conference.localhost')},
#                   'uptime': {'allowusers': BOT_ADMINS},
#                   'help': {'allowmuc': False},
#                  }

# Uncomment and set this to True to hide the restricted commands from
# the help output.
# HIDE_RESTRICTED_COMMANDS = False
HIDE_RESTRICTED_COMMANDS = bool(
    os.environ.get('HIDE_RESTRICTED_COMMANDS', False)
)

# Uncomment and set this to True to ignore commands from users that have no
# access for these instead of replying with error message.
# HIDE_RESTRICTED_ACCESS = False
HIDE_RESTRICTED_ACCESS = bool(
    os.environ.get('HIDE_RESTRICTED_ACCESS', False)
)

# A list of commands which should be responded to in private, even if
# the command was given in a MUC. For example:
# DIVERT_TO_PRIVATE = ('help', 'about', 'status')
# DIVERT_TO_PRIVATE = ()
DIVERT_TO_PRIVATE = tuple(
    os.environ.get('DIVERT_TO_PRIVATE', '').split(','),
)

# Chat relay
# Can be used to relay one to one message from specific users to the bot
# to MUCs. This can be useful with XMPP notifiers like for example  the
# standard Altassian Jira which don't have native support for MUC.
# For example: CHATROOM_RELAY = {'gbin@localhost' : (_TEST_ROOM,)}
CHATROOM_RELAY = {}

# Reverse chat relay
# This feature forwards whatever is said to a specific user.
# It can be useful if you client like gtalk doesn't support MUC correctly
# For example: REVERSE_CHATROOM_RELAY = {_TEST_ROOM : ('gbin@localhost',)}
REVERSE_CHATROOM_RELAY = {}

##########################################################################
# Miscellaneous configuration options                                    #
##########################################################################

# Define the maximum length a single message may be. If a plugin tries to
# send a message longer than this length, it will be broken up into multiple
# shorter messages that do fit.
# MESSAGE_SIZE_LIMIT = 10000
MESSAGE_SIZE_LIMIT = int(os.environ.get('MESSAGE_SIZE_LIMIT', 10000))

# XMPP TLS certificate verification. In order to validate offered certificates,
# you must supply a path to a file containing certificate authorities. By
# default, "/etc/ssl/certs/ca-certificates.crt" is used, which on most Linux
# systems holds the default system trusted CA certificates. You might need to
# change this depending on your environment. Setting this to None disables
# certificate validation, which can be useful if you have a self-signed
# certificate for example.
XMPP_CA_CERT_FILE = None
if 'XMPP_CA_CERT_FILE' in os.environ:
    if 'default' == os.environ['XMPP_CA_CERT_FILE'].lower():
        XMPP_CA_CERT_FILE = '/etc/ssl/certs/ca-certificates.crt'
    else:
        XMPP_CA_CERT_FILE = os.environ['XMPP_CA_CERT_FILE']

# Influence the security methods used on connection with XMPP-based
# backends. You can use this to work around authentication issues with
# some buggy XMPP servers.
#
# The default is to try anything:
# XMPP_FEATURE_MECHANISMS = {}
# To use only unencrypted plain auth:
# XMPP_FEATURE_MECHANISMS =  {'use_mech': 'PLAIN', 'unencrypted_plain': True, 'encrypted_plain': False}

# Modify the default keep-alive interval. By default, Err will send
# some whitespace to the XMPP server every 300 seconds to keep the TCP
# connection alive. On some servers, or when running Err from behind
# a NAT router, the default might not be fast enough and you will need
# to set it to a lower value.
#
# It has been reported that HipChat also times out without setting this
# to a lower value (60 seems to work well with HipChat)
#
# If you're having issues with your bot getting constantly disconnected,
# try to gradually lower this value until it no longer happens.
# XMPP_KEEPALIVE_INTERVAL = 300

# Message rate limiting for the IRC backend. This will delay subsequent
# messages by this many seconds (floats are supported). Setting these
# to a value of 0 effectively disables rate limiting.
# IRC_CHANNEL_RATE = 1  # Regular channel messages
# IRC_PRIVATE_RATE = 1  # Private messages

# Allow messages sent in a chatroom to be directed at requester.
# GROUPCHAT_NICK_PREFIXED = False


text:
.. _vim.fault.VimFault: ../../vim/fault/VimFault.rst

vim.fault.NoDiskFound
=====================
    :extends:

        `vim.fault.VimFault`_

  This exception is thrown when a virtual machine which has no virtual disks is being upgraded or relaid out using the VirtualMachine.upgradeVirtualHardware or upgradeVmLayout commands.

Attributes:

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 * @author greg (at) myrobotlab.org
 *
 * This file is part of MyRobotLab (http://myrobotlab.org).
 *
 * MyRobotLab is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version (subject to the "Classpath" exception
 * as provided in the LICENSE.txt file that accompanied this code).
 *
 * MyRobotLab is distributed in the hope that it will be useful or fun,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * All libraries in thirdParty bundle are subject to their own license
 * requirements - please refer to http://myrobotlab.org/libraries for
 * details.
 *
 * Enjoy !
 *
 * */

package org.myrobotlab.service.data;

import java.io.Serializable;
import java.util.ArrayList;

import org.myrobotlab.logging.LoggerFactory;
import org.slf4j.Logger;

public class IOSequence implements Serializable {
	private static final long serialVersionUID = 1L;

	public final static Logger log = LoggerFactory.getLogger(IOSequence.class);

	public int ID;
	public ArrayList<IOSequenceEntry> sequenceList; // list of a IOAddress
													// values to run sequentialy

	// option constants

	public static String name() {
		if (log.isDebugEnabled()) {
			StringBuilder logString = new StringBuilder("IOSequence.getName()()");
			log.debug("{}", logString);
		} // if

		String ret = new String("IOSequence");
		return ret;
	}

	public static String scope() {
		String ret = new String("myrobotlab");
		return ret;
	}

	// ctors begin ----
	public IOSequence() {
		sequenceList = new ArrayList<IOSequenceEntry>();
	}

	// assignment end ---

	public IOSequence(final IOSequence other) {
		this();
		set(other);
	};

	// ctors end ----
	// assignment begin --- todo - look @ clone copy
	public void set(final IOSequence other) {
		ID = other.ID;
		sequenceList = other.sequenceList;

	};

	/*
	 * Default format was xml is now JSON TODO - make toStringStyler like spring
	 */
	@Override
	public String toString() {
		StringBuffer ret = new StringBuffer();
		// ret.append("{<IOSequence");
		ret.append("{");
		ret.append("\"ID\":\"" + ID + "\"");
		ret.append("\"sequenceList\":" + "\"" + sequenceList.toString() + "\"");

		// ret.append("</IOSequence>");
		ret.append("}");
		return ret.toString();
	}

}


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="header_height">150dp</dimen>

</resources>


text:
NS_ASSUME_NONNULL_BEGIN

@interface ABI42_0_0EXUpdatesLegacyUpdate : NSObject

+ (ABI42_0_0EXUpdatesUpdate *)updateWithLegacyManifest:(ABI42_0_0EXManifestsLegacyManifest *)manifest
                                       config:(ABI42_0_0EXUpdatesConfig *)config
                                     database:(ABI42_0_0EXUpdatesDatabase *)database;

+ (NSURL *)bundledAssetBaseUrlWithManifest:(ABI42_0_0EXManifestsLegacyManifest *)manifest config:(ABI42_0_0EXUpdatesConfig *)config;

@end

NS_ASSUME_NONNULL_END


text:
package org.apache.hyracks.dataflow.std.collectors;

import java.util.List;

import org.apache.hyracks.api.comm.IFrameReader;
import org.apache.hyracks.api.exceptions.HyracksDataException;

public interface IPartitionBatchManager extends IPartitionAcceptor {
    public void getNextBatch(List<IFrameReader> batch, int size) throws HyracksDataException;
}


text:
package org.leandreck.endpoints.processor.model.typefactories;

import org.leandreck.endpoints.annotations.TypeScriptType;
import org.leandreck.endpoints.processor.config.TemplateConfiguration;
import org.leandreck.endpoints.processor.model.TypeNode;
import org.leandreck.endpoints.processor.model.TypeNodeFactory;

import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import static org.leandreck.endpoints.processor.model.typefactories.TypeNodeUtils.NO_TEMPLATE;

/**
 */
final class MapTypeNodeFactory implements ConcreteTypeNodeFactory {

    private final TypeNodeFactory typeNodeFactory;
    private final Types typeUtils;
    private final TypeMirror objectMirror;

    /**
     * Prototype Constructor for Registration in {@link TypeNodeKind}.
     */
    MapTypeNodeFactory() {
        typeUtils = null;
        typeNodeFactory = null;
        objectMirror = null;
    }

    private MapTypeNodeFactory(final TypeNodeFactory typeNodeFactory,
                               final Types typeUtils,
                               final Elements elementUtils) {
        this.typeNodeFactory = typeNodeFactory;
        this.typeUtils = typeUtils;
        objectMirror = TypeNodeUtils.getObjectMirror(elementUtils);
    }

    @Override
    public ConcreteTypeNodeFactory newConfiguredInstance(final TypeNodeFactory typeNodeFactory, final TemplateConfiguration configuration, final Types typeUtils, final Elements elementUtils) {
        return new MapTypeNodeFactory(typeNodeFactory, typeUtils, elementUtils);
    }

    @Override
    public TypeNode createTypeNode(final String fieldName, final String parameterName, final boolean optional, final TypeMirror typeMirror, final DeclaredType containingType) {
        final List<TypeNode> typeParameters = defineTypeParameters(typeMirror, containingType);
        final TypeScriptType typeScriptTypeAnnotation = TypeNodeUtils.getAnnotationForClass(typeMirror, TypeScriptType.class, typeUtils);
        final String typeName = TypeNodeUtils.defineName(typeMirror, typeScriptTypeAnnotation, it -> defineNameFromMapType(typeParameters));
        return new MapTypeNode(optional, fieldName, parameterName, typeName, typeParameters);
    }

    private List<TypeNode> defineTypeParameters(final TypeMirror typeMirror, final DeclaredType containingType) {
        final List<TypeNode> typeParameters;
        final DeclaredType declaredType = (DeclaredType) typeMirror;
        final List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();

        typeParameters = typeArguments.stream()
                .map(it -> it.getKind().equals(TypeKind.WILDCARD) ? objectMirror : it)
                .map(it -> typeNodeFactory.createTypeNode(it, containingType))
                .collect(toList());

        if (typeParameters.isEmpty()) {
            typeParameters.add(typeNodeFactory.createTypeNode(objectMirror));
            typeParameters.add(typeNodeFactory.createTypeNode(objectMirror));
        }
        return typeParameters;
    }

    private String defineNameFromMapType(final List<TypeNode> typeParameters) {
        final TypeNode key = typeParameters.get(0);
        final TypeNode value = typeParameters.get(1);

        final String keyName = key.getTypeName();
        final String valueName = value.getTypeName();

        return keyName + "/" + valueName;
    }

    class MapTypeNode extends TypeNode {

        private final String fieldName;
        private final String parameterName;
        private final String typeName;
        private final String type;
        private final List<TypeNode> typeParameters;

        //lazy
        private Set<TypeNode> imports;
        private Set<TypeNode> types;

        MapTypeNode(final boolean optional,
                    final String fieldName,
                    final String parameterName,
                    final String typeName,
                    final List<TypeNode> typeParameters) {

            super(optional);
            this.fieldName = fieldName;
            this.parameterName = parameterName;
            this.typeName = typeName;
            this.type = "{ [index: " + typeParameters.get(0).getType() + "]: " + typeParameters.get(1).getType() + " }";
            this.typeParameters = typeParameters;
        }

        @Override
        public String getFieldName() {
            return fieldName;
        }

        @Override
        public String getParameterName() {
            return parameterName;
        }

        @Override
        public String getTypeName() {
            return typeName;
        }

        @Override
        public String getType() {
            return type;
        }

        @Override
        public String getTemplate() {
            return NO_TEMPLATE;
        }

        @Override
        public TypeNodeKind getKind() {
            return TypeNodeKind.MAP;
        }

        @Override
        public List<TypeNode> getTypeParameters() {
            return typeParameters;
        }

        @Override
        public List<TypeNode> getChildren() {
            return Collections.emptyList();
        }

        @Override
        public Set<TypeNode> getTypes() {
            if (types == null) {
                types = typeParameters.stream().filter(it -> !it.isMappedType()).flatMap(it -> it.getTypes().stream()).collect(toSet());
            }
            return types;
        }

        @Override
        public Set<TypeNode> getImports() {
            if (imports == null) {
                imports = typeParameters.stream().filter(it -> !it.isMappedType()).flatMap(it -> it.getImports().stream()).collect(toSet());
            }
            return imports;
        }
    }
}


text:
using Codeer.Friendly;
using Codeer.Friendly.Dynamic;
using Codeer.TestAssistant.GeneratorToolKit;
using RM.Friendly.WPFStandardControls;

namespace Driver.Windows
{
    [UserControlDriver(TypeFullName = "Kamishibai.NavigationFrame")]
    public class NavigationFrameDriver
    {
        public WPFUIElement Core { get; }
        public AppVar Current => Core.Dynamic().Current;

        public NavigationFrameDriver(AppVar core)
        {
            Core = new WPFUIElement(core);
        }
    }
}


text:
The PDFKit guide can be read a number of ways.  The first is online at [pdfkit.org](http://pdfkit.org/).
You can also read the guide in PDF form, in this directory or [online](http://pdfkit.org/docs/guide.pdf).

Both the website and the PDF guide are generated from the Markdown files
in this directory. The examples are actually run when generating the PDF in order to show the results inline.
The `generate.js` file in this directory is actually quite short.  It parses the markdown files into a
tree structure using [markdown-js](https://github.com/evilstreak/markdown-js), syntax highlights the code
examples using [codemirror](https://github.com/marijnh/codemirror), compiles and runs the code examples and puts the results
inline, and generates the PDF using PDFKit. You can read the generator script source code to get a feeling for
how you might do something slightly more complex than the guide itself shows.

The markdown syntax used is pretty much standard, with a couple tweaks.

1. Code example output is references using the image notation, using the alt text as the example number starting from
    zero in the current file, and the title as the example output height. E.g. `![x](name "height")`.

2. Page breaks are added before `h1` and `h2`s, unless there are two in a row. `h3` is treated the same as `h2` but
    can be used to avoid this in the case you need multiple `h2`s on the same page.

3. The horizontal rule syntax (`* * *`) denotes an explicit page break


text:
is a fast, light algorithm that transforms data (a list of schedules) into metadata (availability groups and conflicts).

Previously, I drafted a course scheduling platform that took in a list of courses, figured out the right combinations of sections, and return all the possible combinations of schedules possible. However, all my code for making REST requests and figuring out the schedules was jumbled together. In "Scheduler API" I hope to define a standard metadata transformation protocol to make not only course scheduling possible, but also a host of other possible projects relating to schedule-conflict matching, such as a more sophisticated When-is-Good-type application.

## How to use

This API only transforms data, so it will pass through like a function. There are multiple options depending on how you want to handle your data. You can process the data synchronously and receive a return value, or you can use an asynchronous function that's basically the synchronous function wrapped in a promise, or you can process every item asynchronously as it comes via a callback...

```javascript
var scheduler = require('scheduler-api');
var corpus = {...}; // see section "Data models"

// synchronous:
var transformed = scheduler.combinations.sync(corpus);

// thenable:
scheduler.combinations.async(corpus, function (piece) {
  console.log(piece);
}).then(function (transformed) {
  console.log(transformed);
});
```

## Data models

The input-output data models are going to be very complex. They are designed with a course scheduling algorithm in mind. I'll try to explain them as simply as possible:

### Input

Overall, we say that there are multiple independent `entities`, e.g. courses or persons. Within an `entity`, we have a list of every possible parallel universe, which we refer to as `scenarios`. Situations like course scheduling will require multiple scenarios, but situations like WhenIsGood should only need 1 scenario. Within each `scenario`, we have a list of `blocks` in the schedule. Each `block` is assigned with a `startTime`, an `endTime`, and a `day`. The times are assigned from 0 to 1440, which represent the minutes in a 24-hour period (60*24=1440). The day doesn't have to be a date, it just has to be a unique identifier, such as the day of the week.

```javascript
var entities = {
  entityid1: {
    scenarioid1: {
      blockid1: [{start: '10:30', end: '13:30', day ['M', 'W']}],
      blockid2: [{...}],
      ...
    },
    scenarioid2: {},
    ...
  },
  entityid2: {
    ...
  },
  ...
};
```

Take a hard look at how this JSON tree is organized and nested. Entities and blocks are allowed to have metadata, but scenarios don't. Scenario ID's are not important; they only have to be unique within the group (incremented). Entities and blocks all have unique identifiers.

### Output

There are two types of outputs: `combinations` and `conflicts`. In the case of course scheduling, we are more interested in combinations of scenarios that work for as many entities as possible. However for WhenIsGood, we are actually looking for intersections of availabilities. So, our solution will transform both types of data.

```javascript
var combinations = [
  {
    entityid1: scenarioid1,
    entityid2: scenarioid2,
    ...
  },
  {
    entityid1: scenarioid2,
    entityid2: scenarioid3,
    ...
  },
  ...
];

var conflict = {
  // coming soon...
};
```

### Conclusion

Thanks for taking a look at this light javascript scheduling API!

Authored by Andrew Jiang.


text:
.divscroll
{
    height:252px;
    overflow: auto;
	margin-top:-29px;

}
#divSearch { margin-top:0px;}
#dvaddNew, #divSearch{background-color:#fff; border:1px solid #dadada; padding:20px; height:254px;
border-radius:6px; -webkit-border-radius:6px; -ms-border-radius:6px; -o-border-radius:6px;}
#dvaddNew h4 { margin-bottom:10px; color:#515357; font-weight:bold;}
#dvaddNew div { margin-bottom:10px;}
#dvaddNew div label { float:left; width:80px;}
#dvaddNew textarea { height:100px;}
#dvaddNew div.sfButtonwrapper { margin-left:80px;}
#dvaddNew div.sfButtonwrapper label { width:auto;}
.sfInputbox
{
    width: 40%;
    height: 18px;
}

#ErrorMsg
{
    color: #FF0000;
}
.scrollTodayTask
{
    height:200px;
    width: 100%;
    overflow: auto;
}
.sfTaskToDoWrapper { position:relative;}
.sfTaskToDoWrapper h2 { padding-right:50px;}

.tasktodo { border-bottom:1px solid #e8e8e8; padding:10px 18px; position:relative;}
.tasktodo.active { background:#E4EFFA;}

.EditTaskWrapper textarea, .EditTaskWrapper input{ float:left; width:auto;}
.EditTaskWrapper textarea { height:56px; margin-right:5px;}
.EditTaskWrapper input#EditDate { width:115px;margin-right:5px;}

.btnDelete  { position:absolute; top:15px; right:15px; color:#8C8C8C; font-size:14px; cursor:pointer;}
.sftaskNote { display:block; position:inherit; margin-right:15px;}
.sftaskNote:before { position:absolute; top:15px; right:40px; cursor:pointer; color:#8C8C8C; font-size:14px;
content: "\e616";
font-family: "sageframe" !important;
font-style: normal !important;
font-weight: normal !important;
font-variant: normal !important;
text-transform: none !important;
speak: none;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.sftaskNote:hover:before { color:#1a1a1a;}
.btnDelete:hover { color:#1a1a1a;}

.sfSearch, #AddTaskTab
{
    position: absolute;
    top: -2px;
    right: 0px;
}
.sfSearch { right:73px; }
.sfSearch input#txtSearchDate
{
    margin:0 5px 5px 0;
	color:#515357;
	padding:8px 6px;
	display:inline-block;
	background:#fff;
	border:1px solid #bbbbbb;
	border-bottom:2px solid #cbcbcb;
	font-weight:bold;
	-webkit-border-radius: 3px;
	-moz-border-radius: 3px;
	-o-border-radius: 3px;
	-ms-border-radius: 3px;
	border-radius: 3px;
}
.sfSearch span
{
    cursor: pointer;
}
.sfSearch span.icon-search
{
	cursor:pointer;
    position: inherit;
    color:#F27337;
    top: 8px;
    right:14px;
    font-size: 18px;
}
.sfSearch span.icon-search:hover{ color:#C43E00;}

.sftaskNote {}
.taskDate { background:#e9e9e9; padding:2px 6px; font-size:11px;
	-webkit-border-radius: 3px;
	-moz-border-radius: 3px;
	-o-border-radius: 3px;
	-ms-border-radius: 3px;
	border-radius: 3px;}


text:
/*jshint node:true, mocha:true*/
/**
 * @author pmeijer / https://github.com/pmeijer
 */

var testFixture = require('../../../_globals.js');

describe('storage-connection', function () {
    'use strict';
    var EditorStorage = testFixture.requirejs('common/storage/storageclasses/editorstorage'),
        WebSocket = testFixture.requirejs('common/storage/socketio/websocket'),
        socketIO = require('socket.io-client'),
        STORAGE_CONSTANTS = testFixture.requirejs('common/storage/constants'),
        gmeConfig = testFixture.getGmeConfig(),
        WebGME = testFixture.WebGME,
        openSocketIo = testFixture.openSocketIo,
        superagent = testFixture.superagent,
        Q = testFixture.Q,
        projectName2Id = testFixture.projectName2Id,

        logger = testFixture.logger.fork('connection.spec'),

        guestAccount = gmeConfig.authentication.guestAccount,
        server,
        gmeAuth,
        safeStorage,
        ir,

        projectName = 'ConnectionProject';

    before(function (done) {
        testFixture.clearDBAndGetGMEAuth(gmeConfig, [projectName])
            .then(function (gmeAuth_) {
                gmeAuth = gmeAuth_;
                safeStorage = testFixture.getMongoStorage(logger, gmeConfig, gmeAuth);
                return safeStorage.openDatabase();
            })
            .then(function () {
                return Q.allDone([
                    testFixture.importProject(safeStorage, {
                        projectSeed: 'seeds/EmptyProject.json',
                        projectName: projectName,
                        gmeConfig: gmeConfig,
                        logger: logger
                    })
                ]);
            })
            .then(function (res) {
                ir = res[0];
                return Q.allDone([
                    ir.project.createBranch('b1', ir.commitHash),
                    ir.project.createBranch('b2', ir.commitHash),
                    ir.project.createBranch('b3', ir.commitHash),
                    ir.project.createBranch('b4', ir.commitHash),
                    ir.project.createBranch('b5', ir.commitHash),
                    ir.project.createBranch('b6', ir.commitHash)
                ]);
            })
            .nodeify(done);
    });

    after(function (done) {
        Q.allDone([
            gmeAuth.unload(),
            safeStorage.closeDatabase()
        ])
            .nodeify(done);
    });

    function createStorage(host, webgmeToken, logger, gmeConfig) {
        var ioClient,
            webSocket,
            result = {
                socket: null,
                storage: null,
                webSocket: null
            };

        function IoClient(host, webgmeToken, mainLogger, gmeConfig) {
            var logger = mainLogger.fork('socketio-nodeclient');

            this.connect = function (callback) {
                var socketIoOptions = JSON.parse(JSON.stringify(gmeConfig.socketIO.clientOptions)),
                    protocol = 'http',
                    hostUrl = protocol + '://' + host + ':' + gmeConfig.server.port;

                if (webgmeToken) {
                    socketIoOptions.extraHeaders = {
                        Cookies: 'access_token=' + webgmeToken
                    };
                }

                logger.debug('Connecting to "' + hostUrl + '" with options', {metadata: socketIoOptions});

                result.socket = socketIO.connect(hostUrl, socketIoOptions);
                callback(null, result.socket);
            };

            this.getToken = function () {
                return webgmeToken;
            };
        }

        ioClient = new IoClient(host, webgmeToken, logger, gmeConfig);
        webSocket = new WebSocket(ioClient, logger, gmeConfig);
        result.storage = new EditorStorage(webSocket, logger, gmeConfig);
        result.webSocket = webSocket;

        return result;
    }

    it('should disconnect when server stops', function (done) {
        var agent = superagent.agent(),
            connected = false,
            serverStopped = false,
            res,
            storage,
            socket,
            webgmeToken;

        server = WebGME.standaloneServer(gmeConfig);
        Q.ninvoke(server, 'start')
            .then(function () {
                return openSocketIo(server, agent, guestAccount, guestAccount);
            })
            .then(function (result) {
                var deferred = Q.defer();
                socket = result.socket;
                webgmeToken = result.webgmeToken;
                res = createStorage('127.0.0.1', /*server.getUrl()*/
                    result.webgmeToken,
                    logger,
                    gmeConfig);

                storage = res.storage;

                storage.open(function (networkState) {
                    if (networkState === STORAGE_CONSTANTS.CONNECTED) {
                        connected = true;
                        server.stop(function () {
                            serverStopped = true;
                        });

                    } else if (networkState === STORAGE_CONSTANTS.DISCONNECTED) {
                        if (connected === true) {
                            deferred.resolve();
                        } else {
                            deferred.reject(new Error('Was never connected'));
                        }
                    } else {
                        deferred.reject(new Error('Unexpected network state: ' + networkState));
                    }
                });

                return deferred.promise;
            })
            .nodeify(function (err) {
                socket.disconnect();
                Q.ninvoke(storage, 'close')
                    .finally(function (err2) {
                        // Make sure server has been closed.
                        Q.ninvoke(server, 'stop')
                            .finally(function (err3) {
                                done(err || err2 || err3);
                            });
                    });
            });
    });

    it('should disconnect and reconnect when disconnect on actual socket', function (done) {
        var agent = superagent.agent(),
            connected = false,
            disconnected = false,
            res,
            storage,
            socket,
            webgmeToken;

        server = WebGME.standaloneServer(gmeConfig);
        Q.ninvoke(server, 'start')
            .then(function () {
                return openSocketIo(server, agent, guestAccount, guestAccount);
            })
            .then(function (result) {
                var deferred = Q.defer();
                socket = result.socket;
                webgmeToken = result.webgmeToken;
                res = createStorage('127.0.0.1', /*server.getUrl()*/
                    result.webgmeToken,
                    logger,
                    gmeConfig);

                storage = res.storage;

                storage.open(function (networkState) {
                    if (networkState === STORAGE_CONSTANTS.CONNECTED) {
                        connected = true;
                        res.socket.disconnect();
                    } else if (networkState === STORAGE_CONSTANTS.DISCONNECTED) {
                        if (connected === true) {
                            disconnected = true;
                        } else {
                            deferred.reject(new Error('Was not connected before reconnected'));
                        }
                    } else if (networkState === STORAGE_CONSTANTS.RECONNECTED) {
                        if (disconnected === true) {
                            deferred.resolve();
                        } else {
                            deferred.reject(new Error('Was not connected before reconnected'));
                        }
                    } else {
                        deferred.reject(new Error('Unexpected network state: ' + networkState));
                    }
                });

                return deferred.promise;
            })
            .nodeify(function (err) {
                socket.disconnect();
                Q.ninvoke(storage, 'close')
                    .finally(function (err2) {
                        Q.ninvoke(server, 'stop')
                            .finally(function (err3) {
                                done(err || err2 || err3);
                            });
                    });
            });
    });

    it('should reconnect with branch open', function (done) {
        var agent = superagent.agent(),
            connected = false,
            disconnected = false,
            res,
            storage,
            socket,
            project,
            webgmeToken;

        server = WebGME.standaloneServer(gmeConfig);
        Q.ninvoke(server, 'start')
            .then(function () {
                return openSocketIo(server, agent, guestAccount, guestAccount);
            })
            .then(function (result) {
                var deferred = Q.defer();
                socket = result.socket;
                webgmeToken = result.webgmeToken;
                res = createStorage('127.0.0.1', /*server.getUrl()*/
                    result.webgmeToken,
                    logger,
                    gmeConfig);

                storage = res.storage;

                storage.open(function (networkState) {
                    if (networkState === STORAGE_CONSTANTS.CONNECTED) {
                        connected = true;
                        Q.nfcall(storage.openProject, projectName2Id(projectName))
                            .then(function (result) {
                                project = result[0];

                                function hashUpdateHandler(data, commitQueue, updateQueue, callback) {
                                    callback(null, true);
                                }

                                function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) {

                                }

                                return Q.nfcall(storage.openBranch, projectName2Id(projectName), 'master',
                                    hashUpdateHandler, branchStatusHandler);
                            })
                            .then(function () {
                                res.socket.disconnect();
                            });
                    } else if (networkState === STORAGE_CONSTANTS.DISCONNECTED) {
                        if (connected === true) {
                            disconnected = true;
                        } else {
                            deferred.reject(new Error('Was not connected before reconnected'));
                        }
                    } else if (networkState === STORAGE_CONSTANTS.RECONNECTED) {
                        if (disconnected === true) {
                            deferred.resolve();
                        } else {
                            deferred.reject(new Error('Was not connected before reconnected'));
                        }
                    } else {
                        deferred.reject(new Error('Unexpected network state: ' + networkState));
                    }
                });

                return deferred.promise;
            })
            .nodeify(function (err) {
                socket.disconnect();
                Q.ninvoke(storage, 'close')
                    .finally(function (err2) {
                        Q.ninvoke(server, 'stop')
                            .finally(function (err3) {
                                done(err || err2 || err3);
                            });
                    });
            });
    });

    it('should reconnect and commit uncommitted commit', function (done) {
        var agent = superagent.agent(),
            connected = false,
            disconnected = false,
            res,
            storage,
            socket,
            project,
            webgmeToken;

        server = WebGME.standaloneServer(gmeConfig);
        Q.ninvoke(server, 'start')
            .then(function () {
                return openSocketIo(server, agent, guestAccount, guestAccount);
            })
            .then(function (result) {
                var deferred = Q.defer();
                socket = result.socket;
                webgmeToken = result.webgmeToken;
                res = createStorage('127.0.0.1', /*server.getUrl()*/
                    result.webgmeToken,
                    logger,
                    gmeConfig);

                storage = res.storage;

                storage.open(function (networkState) {
                    if (networkState === STORAGE_CONSTANTS.CONNECTED) {
                        connected = true;

                        Q.nfcall(storage.openProject, projectName2Id(projectName))
                            .then(function (result) {
                                var branchOpened = false;

                                project = result[0];

                                function hashUpdateHandler(data, commitQueue, updateQueue, callback) {
                                    if (branchOpened) {
                                        res.socket.disconnect();
                                    }
                                    branchOpened = true;
                                    callback(null, true);
                                }

                                function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) {

                                }

                                return Q.nfcall(storage.openBranch, projectName2Id(projectName), 'b2',
                                    hashUpdateHandler, branchStatusHandler);
                            })
                            .then(function () {
                                return project.makeCommit('b2', [ir.commitHash], ir.rootHash, {}, 'new committt');
                            })
                            .then(function (commitStatus) {
                                if (disconnected && commitStatus.status === STORAGE_CONSTANTS.SYNCED) {
                                    deferred.resolve();
                                } else {
                                    deferred.reject('Not synced after commit ' +  commitStatus.status);
                                }
                            })
                            .catch(deferred.reject);
                    } else if (networkState === STORAGE_CONSTANTS.DISCONNECTED) {
                        if (connected === true) {
                            disconnected = true;
                        } else {
                            deferred.reject(new Error('Was not connected before reconnected'));
                        }
                    } else if (networkState === STORAGE_CONSTANTS.RECONNECTED) {
                        if (disconnected === true) {
                            // All is fine. Wait for the branch status SYNC (could come before this event too).
                        } else {
                            deferred.reject(new Error('Was not connected before reconnected'));
                        }
                    } else {
                        deferred.reject(new Error('Unexpected network state: ' + networkState));
                    }
                });

                return deferred.promise;
            })
            .nodeify(function (err) {
                socket.disconnect();
                Q.ninvoke(storage, 'close')
                    .finally(function (err2) {
                        Q.ninvoke(server, 'stop')
                            .finally(function (err3) {
                                done(err || err2 || err3);
                            });
                    });
            });
    });

    it('should reconnect get into sync with commit send to server but acknowledge did not return', function (done) {
        //  Hc
        //  |
        var agent = superagent.agent(),
            connected = false,
            disconnected = false,
            res,
            storage,
            socket,
            project,
            webgmeToken;

        server = WebGME.standaloneServer(gmeConfig);
        Q.ninvoke(server, 'start')
            .then(function () {
                return openSocketIo(server, agent, guestAccount, guestAccount);
            })
            .then(function (result) {
                var deferred = Q.defer();
                socket = result.socket;
                webgmeToken = result.webgmeToken;
                res = createStorage('127.0.0.1', /*server.getUrl()*/
                    result.webgmeToken,
                    logger,
                    gmeConfig);

                storage = res.storage;

                storage.open(function (networkState) {
                    if (networkState === STORAGE_CONSTANTS.CONNECTED) {
                        connected = true;
                        Q.nfcall(storage.openProject, projectName2Id(projectName))
                            .then(function (result) {
                                project = result[0];

                                function hashUpdateHandler(data, commitQueue, updateQueue, callback) {
                                    callback(null, true);
                                }

                                function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) {
                                }

                                return Q.nfcall(storage.openBranch, projectName2Id(projectName), 'b3',
                                    hashUpdateHandler, branchStatusHandler);
                            })
                            .then(function () {
                                // Overwrite makeCommit function to block acknowledgement.
                                res.webSocket.makeCommit = function (data/*, callback*/) {
                                    res.webSocket.socket.emit('makeCommit', data, function (err /*, commitStatus*/) {
                                        if (err) {
                                            done(new Error(err));
                                        }
                                        res.socket.disconnect();
                                    });
                                };

                                return project.makeCommit('b3', [ir.commitHash], ir.rootHash, {}, 'new commie');
                            })
                            .then(function (commitStatus) {
                                if (disconnected && commitStatus.status === STORAGE_CONSTANTS.SYNCED) {
                                    deferred.resolve();
                                } else {
                                    deferred.reject('Not synced after commit ' +  commitStatus.status);
                                }
                            })
                            .catch(function (err) {
                                done(err);
                            });
                    } else if (networkState === STORAGE_CONSTANTS.DISCONNECTED) {
                        if (connected === true) {
                            disconnected = true;
                        } else {
                            deferred.reject(new Error('Was not connected before reconnected'));
                        }
                    } else if (networkState === STORAGE_CONSTANTS.RECONNECTED) {
                        if (disconnected === true) {
                            // All is fine. Wait for the branch status SYNC (could come before this event too).
                        } else {
                            deferred.reject(new Error('Was not connected before reconnected'));
                        }
                    } else {
                        deferred.reject(new Error('Unexpected network state: ' + networkState));
                    }
                });

                return deferred.promise;
            })
            .nodeify(function (err) {
                socket.disconnect();
                Q.ninvoke(storage, 'close')
                    .finally(function (err2) {
                        Q.ninvoke(server, 'stop')
                            .finally(function (err3) {
                                done(err || err2 || err3);
                            });
                    });
            });
    });

    it('should reconnect get into forked with commit send to server but acknowledge did not return', function (done) {
        // This test sets the branch hash using the safe-storage after the first commit.
        //  c
        //  H
        var agent = superagent.agent(),
            connected = false,
            disconnected = false,
            res,
            storage,
            socket,
            project,
            webgmeToken;

        server = WebGME.standaloneServer(gmeConfig);
        Q.ninvoke(server, 'start')
            .then(function () {
                return openSocketIo(server, agent, guestAccount, guestAccount);
            })
            .then(function (result) {
                var deferred = Q.defer();
                socket = result.socket;
                webgmeToken = result.webgmeToken;
                res = createStorage('127.0.0.1', /*server.getUrl()*/
                    result.webgmeToken,
                    logger,
                    gmeConfig);

                storage = res.storage;

                storage.open(function (networkState) {
                    if (networkState === STORAGE_CONSTANTS.CONNECTED) {
                        connected = true;
                        Q.nfcall(storage.openProject, projectName2Id(projectName))
                            .then(function (result) {
                                project = result[0];

                                function hashUpdateHandler(data, commitQueue, updateQueue, callback) {
                                    callback(null, true);
                                }

                                function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) {
                                }

                                return Q.nfcall(storage.openBranch, projectName2Id(projectName), 'b4',
                                    hashUpdateHandler, branchStatusHandler);
                            })
                            .then(function () {
                                // Overwrite makeCommit function to block acknowledgement.
                                res.webSocket.makeCommit = function (data/*, callback*/) {
                                    res.webSocket.socket.emit('makeCommit', data, function (err, commitStatus) {
                                        if (err) {
                                            done(new Error(err));
                                        }
                                        ir.project.setBranchHash('b4', ir.commitHash, commitStatus.hash)
                                            .then(function (commitStatus) {
                                                if (commitStatus.status === STORAGE_CONSTANTS.SYNCED) {
                                                    res.socket.disconnect();
                                                } else {
                                                    deferred.reject('Server setBranchHash not synced ' +
                                                        commitStatus.status);
                                                }
                                            })
                                            .catch(deferred.reject);
                                    });
                                };

                                return project.makeCommit('b4', [ir.commitHash], ir.rootHash, {}, 'new commie');
                            })
                            .then(function (commitStatus) {
                                if (disconnected && commitStatus.status === STORAGE_CONSTANTS.FORKED) {
                                    deferred.resolve();
                                } else {
                                    deferred.reject('Not FORKED after commit ' +  commitStatus.status);
                                }
                            })
                            .catch(function (err) {
                                done(err);
                            });
                    } else if (networkState === STORAGE_CONSTANTS.DISCONNECTED) {
                        if (connected === true) {
                            disconnected = true;
                        } else {
                            deferred.reject(new Error('Was not connected before reconnected'));
                        }
                    } else if (networkState === STORAGE_CONSTANTS.RECONNECTED) {
                        if (disconnected === true) {
                            // All is fine. Wait for the branch status SYNC (could come before this event too).
                        } else {
                            deferred.reject(new Error('Was not connected before reconnected'));
                        }
                    } else {
                        deferred.reject(new Error('Unexpected network state: ' + networkState));
                    }
                });

                return deferred.promise;
            })
            .nodeify(function (err) {
                socket.disconnect();
                Q.ninvoke(storage, 'close')
                    .finally(function (err2) {
                        Q.ninvoke(server, 'stop')
                            .finally(function (err3) {
                                done(err || err2 || err3);
                            });
                    });
            });
    });

    it('should reconnect get into forked with commit send to server but acknowledge did not return 2', function (done) {
        // This test sets the branch hash and makes a commit using the safe-storage after the first commit.
        var agent = superagent.agent(),
            connected = false,
            disconnected = false,
            res,
            storage,
            socket,
            project,
            webgmeToken;

        server = WebGME.standaloneServer(gmeConfig);
        Q.ninvoke(server, 'start')
            .then(function () {
                return openSocketIo(server, agent, guestAccount, guestAccount);
            })
            .then(function (result) {
                var deferred = Q.defer();
                socket = result.socket;
                webgmeToken = result.webgmeToken;
                res = createStorage('127.0.0.1', /*server.getUrl()*/
                    result.webgmeToken,
                    logger,
                    gmeConfig);

                storage = res.storage;

                storage.open(function (networkState) {
                    if (networkState === STORAGE_CONSTANTS.CONNECTED) {
                        connected = true;
                        Q.nfcall(storage.openProject, projectName2Id(projectName))
                            .then(function (result) {
                                project = result[0];

                                function hashUpdateHandler(data, commitQueue, updateQueue, callback) {
                                    callback(null, true);
                                }

                                function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) {
                                }

                                return Q.nfcall(storage.openBranch, projectName2Id(projectName), 'b5',
                                    hashUpdateHandler, branchStatusHandler);
                            })
                            .then(function () {
                                // Overwrite makeCommit function to block acknowledgement.
                                res.webSocket.makeCommit = function (data/*, callback*/) {
                                    res.webSocket.socket.emit('makeCommit', data, function (err, commitStatus) {
                                        if (err) {
                                            done(new Error(err));
                                        }
                                        ir.project.setBranchHash('b5', ir.commitHash, commitStatus.hash)
                                            .then(function (commitStatus) {
                                                if (commitStatus.status === STORAGE_CONSTANTS.SYNCED) {
                                                    ir.project.makeCommit('b5', [ir.commitHash], ir.rootHash, {}, 's')
                                                        .then(function (commitStatus) {
                                                            if (commitStatus.status === STORAGE_CONSTANTS.SYNCED) {
                                                                res.socket.disconnect();
                                                            } else {
                                                                deferred.reject('Server commit not synced ' +
                                                                    commitStatus.status);
                                                            }
                                                        });
                                                } else {
                                                    deferred.reject('Server setBranchHash not synced ' +
                                                        commitStatus.status);
                                                }
                                            })
                                            .catch(deferred.reject);
                                    });
                                };

                                return project.makeCommit('b5', [ir.commitHash], ir.rootHash, {}, 'new commie');
                            })
                            .then(function (commitStatus) {
                                if (disconnected && commitStatus.status === STORAGE_CONSTANTS.FORKED) {
                                    deferred.resolve();
                                } else {
                                    deferred.reject('Not FORKED after commit ' +  commitStatus.status);
                                }
                            })
                            .catch(function (err) {
                                done(err);
                            });
                    } else if (networkState === STORAGE_CONSTANTS.DISCONNECTED) {
                        if (connected === true) {
                            disconnected = true;
                        } else {
                            deferred.reject(new Error('Was not connected before reconnected'));
                        }
                    } else if (networkState === STORAGE_CONSTANTS.RECONNECTED) {
                        if (disconnected === true) {
                            // All is fine. Wait for the branch status SYNC (could come before this event too).
                        } else {
                            deferred.reject(new Error('Was not connected before reconnected'));
                        }
                    } else {
                        deferred.reject(new Error('Unexpected network state: ' + networkState));
                    }
                });

                return deferred.promise;
            })
            .nodeify(function (err) {
                socket.disconnect();
                Q.ninvoke(storage, 'close')
                    .finally(function (err2) {
                        Q.ninvoke(server, 'stop')
                            .finally(function (err3) {
                                done(err || err2 || err3);
                            });
                    });
            });
    });

    it('should reconnect and commit uncommitted commits', function (done) {
        var agent = superagent.agent(),
            connected = false,
            disconnected = false,
            res,
            storage,
            socket,
            project,
            webgmeToken;

        server = WebGME.standaloneServer(gmeConfig);
        Q.ninvoke(server, 'start')
            .then(function () {
                return openSocketIo(server, agent, guestAccount, guestAccount);
            })
            .then(function (result) {
                var deferred = Q.defer();
                socket = result.socket;
                webgmeToken = result.webgmeToken;
                res = createStorage('127.0.0.1', /*server.getUrl()*/
                    result.webgmeToken,
                    logger,
                    gmeConfig);

                storage = res.storage;

                storage.open(function (networkState) {
                    if (networkState === STORAGE_CONSTANTS.CONNECTED) {
                        connected = true;

                        Q.nfcall(storage.openProject, projectName2Id(projectName))
                            .then(function (result) {
                                var branchOpened;

                                project = result[0];

                                function hashUpdateHandler(data, commitQueue, updateQueue, callback) {
                                    if (branchOpened === true) {
                                        res.socket.disconnect();
                                        branchOpened = false; // Only trigger disconnect once.
                                        project.makeCommit('b6', [data.commitData.commitObject._id],
                                            ir.rootHash, {}, 'new com')
                                            .then(function (commitStatus) {
                                                if (disconnected && commitStatus.status === STORAGE_CONSTANTS.SYNCED) {
                                                    deferred.resolve();
                                                } else {
                                                    deferred.reject('Not synced after 2nd commit ' +
                                                        commitStatus.status);
                                                }
                                            })
                                            .catch(deferred.reject);
                                    } else if (typeof branchOpened === 'undefined') {
                                        branchOpened = true;
                                    }

                                    callback(null, true);
                                }

                                function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) {

                                }

                                return Q.nfcall(storage.openBranch, projectName2Id(projectName), 'b6',
                                    hashUpdateHandler, branchStatusHandler);
                            })
                            .then(function () {
                                return project.makeCommit('b6', [ir.commitHash], ir.rootHash, {}, 'new commit');
                            })
                            .catch(deferred.reject);
                    } else if (networkState === STORAGE_CONSTANTS.DISCONNECTED) {
                        if (connected === true) {
                            disconnected = true;
                        } else {
                            deferred.reject(new Error('Was not connected before reconnected'));
                        }
                    } else if (networkState === STORAGE_CONSTANTS.RECONNECTED) {
                        if (disconnected === true) {
                            // All is fine. Wait for the branch status SYNC (could come before this event too).
                        } else {
                            deferred.reject(new Error('Was not connected before reconnected'));
                        }
                    } else {
                        deferred.reject(new Error('Unexpected network state: ' + networkState));
                    }
                });

                return deferred.promise;
            })
            .nodeify(function (err) {
                socket.disconnect();
                Q.ninvoke(storage, 'close')
                    .finally(function (err2) {
                        Q.ninvoke(server, 'stop')
                            .finally(function (err3) {
                                done(err || err2 || err3);
                            });
                    });
            });
    });
});


text:
                        <form class="om-slider-form text-center" action="#">

Запишитесь
на бесплатное
пробное тестирование

                            <input class="om-slider-form__input" type="text" required placeholder="имя"/>
                            <input class="om-slider-form__input" type="tel" required placeholder="телефон"/>
                            <button class="om-btn om-btn--cta om-btn--slider " type="submit">оставить заявку</button>
                        </form>

                        <form class="om-slider-form text-center" action="#">

Запишитесь
на бесплатное
пробное тестирование

                            <input class="om-slider-form__input" type="text" required placeholder="имя"/>
                            <input class="om-slider-form__input" type="tel" required placeholder="телефон"/>
                            <button class="om-btn om-btn--cta om-btn--slider " type="submit">оставить заявку</button>
                        </form>

                        <form class="om-slider-form text-center" action="#">

Оставить заявку

                            <input class="om-slider-form__input" type="text" required placeholder="имя"/>
                            <input class="om-slider-form__input" type="tel" required placeholder="телефон"/>
                            <button class="om-btn om-btn--cta om-btn--slider " type="submit">оставить заявку</button>
                        </form>

                        <form class="om-slider-form text-center" action="#">

Оставить заявку

                            <input class="om-slider-form__input" type="text" required placeholder="имя"/>
                            <input class="om-slider-form__input" type="tel" required placeholder="телефон"/>
                            <button class="om-btn om-btn--cta om-btn--slider " type="submit">оставить заявку</button>
                        </form>

        Ранний старт подготовки — залог поступления в хороший вуз!


text:
package com.intuso.housemate.webserver.database.mongo;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.intuso.housemate.webserver.database.Database;
import com.intuso.housemate.webserver.database.model.Page;
import com.intuso.housemate.webserver.database.model.User;
import com.intuso.utilities.collection.ManagedCollection;
import com.intuso.utilities.collection.ManagedCollectionFactory;
import com.intuso.utilities.properties.api.PropertyRepository;
import com.intuso.utilities.properties.api.WriteableMapPropertyRepository;
import com.intuso.utilities.webserver.oauth.model.Authorisation;
import com.intuso.utilities.webserver.oauth.model.Client;
import com.intuso.utilities.webserver.oauth.model.Token;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.UpdateOptions;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import static com.mongodb.client.model.Filters.*;

/**
 * Created by tomc on 21/01/17.
 */
public class MongoDatabaseImpl implements Database {

    public final static String HOST = "mongo.host";
    public final static String PORT = "mongo.port";
    public final static String DATABASE = "mongo.database";

    public static void configureDefaults(WriteableMapPropertyRepository defaultProperties) {
        defaultProperties.set(HOST, "localhost");
        defaultProperties.set(PORT, "27017");
        defaultProperties.set(DATABASE, "housemate");
    }

    private final Logger logger = LoggerFactory.getLogger(MongoDatabaseImpl.class);

    private final ManagedCollection<Listener> listeners;

    private final MongoCollection<Document> userCollection;
    private final MongoCollection<Document> clientCollection;
    private final MongoCollection<Document> authorisationCollection;
    private final MongoCollection<Document> tokenCollection;

    private final LoadingCache<String, Optional<User>> userCache;
    private final LoadingCache<String, Optional<Client>> clientCache;

    private final Function<Document, User> toUser;
    private final Function<User, Document> fromUser;
    private final Function<Document, Client> toClient;
    private final Function<Client, Document> fromClient;
    private final Function<Document, Authorisation> toAuthorisation;
    private final Function<Authorisation, Document> fromAuthorisation;
    private final Function<Document, Token> toToken;
    private final Function<Token, Document> fromToken;

    @Inject
    public MongoDatabaseImpl(PropertyRepository properties, ManagedCollectionFactory managedCollectionFactory) {

        listeners = managedCollectionFactory.createSet();

        MongoClient mongoClient = new MongoClient(properties.get(HOST), Integer.parseInt(properties.get(PORT)));

        logger.info("Connecting to mongod at " + mongoClient.getConnectPoint());

        MongoDatabase database = mongoClient.getDatabase(properties.get(DATABASE));

        logger.info("Using database " + database.getName());

        userCollection = database.getCollection("user");
        userCollection.createIndex(new Document().append("email", 1));
        clientCollection = database.getCollection("client");
        clientCollection.createIndex(new Document().append("owner", 1));
        authorisationCollection = database.getCollection("authorisation");
        tokenCollection = database.getCollection("token");
        tokenCollection.createIndex(new Document().append("client", 1));
        tokenCollection.createIndex(new Document().append("user", 1));
        tokenCollection.createIndex(new Document().append("token", 1));
        tokenCollection.createIndex(new Document().append("refresh", 1));

        userCache = CacheBuilder.newBuilder()
                .expireAfterAccess(7, TimeUnit.DAYS)
                .build(new CacheLoader<String, Optional<User>>() {
                    @Override
                    public Optional<User> load(String s) throws Exception {
                        return loadAll(Lists.newArrayList(s)).get(s);
                    }

                    @Override
                    public Map<String, Optional<User>> loadAll(Iterable<? extends String> keys) throws Exception {
                        Map<String, Optional<User>> result = StreamSupport.stream(userCollection.find(in("_id", keys)).spliterator(), false)
                                .map(toUser)
                                .collect(Collectors.toMap(User::getId, Optional::of));
                        for(String key : keys)
                            if(!result.containsKey(key))
                                result.put(key, Optional.empty());
                        return result;
                    }
                });

        clientCache = CacheBuilder.newBuilder()
                .expireAfterAccess(7, TimeUnit.DAYS)
                .build(new CacheLoader<String, Optional<Client>>() {
                    @Override
                    public Optional<Client> load(String s) throws Exception {
                        return loadAll(Lists.newArrayList(s)).get(s);
                    }

                    @Override
                    public Map<String, Optional<Client>> loadAll(Iterable<? extends String> keys) throws Exception {
                        Map<String, Optional<Client>> result = StreamSupport.stream(clientCollection.find(in("_id", keys)).spliterator(), false)
                                .map(toClient)
                                .collect(Collectors.toMap(Client::getId, Optional::of));
                        for(String key : keys)
                            if(!result.containsKey(key))
                                result.put(key, Optional.empty());
                        return result;
                    }
                });

        toUser = document -> document == null ? null : new User(
                document.getString("_id"),
                document.getString("email"),
                document.getString("server"));
        fromUser = user -> user == null ? null : new Document()
                .append("_id", user.getId())
                .append("email", user.getEmail())
                .append("server", user.getServerAddress());
        toClient = document -> document == null ? null : new Client(
                document.getString("owner"),
                document.getString("_id"),
                document.getString("secret"),
                document.getString("name"));
        fromClient = client -> client == null ? null : new Document()
                .append("_id", client.getId())
                .append("secret", client.getSecret())
                .append("owner", client.getOwnerId())
                .append("name", client.getName());
        toAuthorisation = document -> document == null ? null : new Authorisation(
                clientCache.getUnchecked(document.getString("client")).orElse(null),
                document.getString("user"),
                document.getString("_id"));
        fromAuthorisation = authorisation -> authorisation == null ? null : new Document()
                .append("client", authorisation.getClient().getId())
                .append("user", authorisation.getUserId())
                .append("_id", authorisation.getCode());
        toToken = document -> document == null ? null : new Token(
                document.getString("_id"),
                clientCache.getUnchecked(document.getString("client")).orElse(null),
                document.getString("user"),
                document.getString("token"),
                document.getString("token"),
                document.getLong("expires-at"));
        fromToken = token -> token == null ? null : new Document()
                .append("_id", token.getId())
                .append("client", token.getClient().getId())
                .append("user", token.getUserId())
                .append("token", token.getToken())
                .append("refresh", token.getRefreshToken())
                .append("expires-at", token.getExpiresAt());
    }

    @Override
    public Stream<User> getUsers() {
        return StreamSupport.stream(userCollection.find().spliterator(), false)
                .map(toUser);
    }

    @Override
    public Page<User> getUserPage(long offset, int limit) {
        return new Page<>(offset,
                userCollection.count(),
                StreamSupport.stream(userCollection.find().skip((int) offset).limit(limit).spliterator(), false)
                        .map(toUser)
                        .collect(Collectors.toList()));
    }

    @Override
    public void updateUser(User user) {
        userCache.invalidate(user.getId());
        userCollection.updateOne(eq("_id", user.getId()), new Document("$set", fromUser.apply(user)), new UpdateOptions().upsert(true));
        for(Listener listener : listeners)
            listener.userUpdated(user);
    }

    @Override
    public User getUser(String id) {
        return userCache.getUnchecked(id).orElse(null);
    }

    @Override
    public void deleteUser(String id) {
        userCache.invalidate(id);
        userCollection.deleteOne(eq("_id", id));
    }

    @Override
    public User getUserByEmail(String email) {
        return toUser.apply(userCollection.find(and(
                eq("email", email)
        )).limit(1).first());
    }

    @Override
    public void setUserPassword(String id, String passwordHash) {
        userCache.invalidate(id);
        userCollection.updateOne(eq("_id", id), new Document("$set", new Document("passwordHash", passwordHash)), new UpdateOptions().upsert(true));
    }

    @Override
    public boolean authenticateUser(String id, String passwordHash) {
        return userCollection.count(and(
                eq("_id", id),
                eq("passwordHash", passwordHash)
        )) > 0;
    }

    @Override
    public Page<Client> getClientPage(long offset, int limit) {
        return new Page<>(offset,
                clientCollection.count(),
                StreamSupport.stream(clientCollection.find().skip((int) offset).limit(limit).spliterator(), false)
                        .map(toClient)
                        .collect(Collectors.toList()));
    }

    @Override
    public void updateClient(Client client) {
        clientCache.invalidate(client.getId());
        clientCollection.updateOne(eq("_id", client.getId()), new Document("$set", fromClient.apply(client)), new UpdateOptions().upsert(true));
        for(Listener listener : listeners)
            listener.clientUpdated(client);
    }

    @Override
    public Client getClient(String id) {
        return clientCache.getUnchecked(id).orElse(null);
    }

    @Override
    public void deleteClient(String id) {
        clientCache.invalidate(id);
        clientCollection.deleteOne(eq("_id", id));
    }

    @Override
    public void updateAuthorisation(Authorisation authorisation) {
        authorisationCollection.updateOne(eq("_id", authorisation.getCode()), new Document("$set", fromAuthorisation.apply(authorisation)), new UpdateOptions().upsert(true));
    }

    @Override
    public Authorisation getAuthorisation(String code) {
        return toAuthorisation.apply(authorisationCollection.find(eq("_id", code)).first());
    }

    @Override
    public void deleteAuthorisation(String code) {
        authorisationCollection.deleteOne(eq("_id", code));
    }

    @Override
    public void updateToken(Token token) {
        tokenCollection.updateOne(eq("_id", token.getId()), new Document("$set", fromToken.apply(token)), new UpdateOptions().upsert(true));
    }

    @Override
    public Token getToken(String id) {
        return toToken.apply(tokenCollection.find(eq("_id", id)).first());
    }

    @Override
    public void deleteToken(String token) {
        tokenCollection.deleteOne(eq("_id", token));
    }

    @Override
    public Token getTokenForToken(String token) {
        return toToken.apply(tokenCollection.find(eq("token", token)).first());
    }

    @Override
    public Token getTokenForRefreshToken(String refreshToken) {
        return toToken.apply(tokenCollection.find(eq("refresh", refreshToken)).first());
    }

    @Override
    public Page<Token> getUserTokenPage(String id, long offset, int limit) {
        return new Page<>(offset,
                tokenCollection.count(eq("user", id)),
                StreamSupport.stream(tokenCollection.find(eq("user", id)).skip((int) offset).limit(limit).spliterator(), false)
                        .map(toToken)
                        .collect(Collectors.toList()));
    }

    @Override
    public Page<Token> getClientTokenPage(String id, long offset, int limit) {
        return new Page<>(offset,
                tokenCollection.count(eq("client", id)),
                StreamSupport.stream(tokenCollection.find(eq("client", id)).skip((int) offset).limit(limit).spliterator(), false)
                        .map(toToken)
                        .collect(Collectors.toList()));
    }

    @Override
    public ManagedCollection.Registration addListener(Listener listener) {
        return listeners.add(listener);
    }
}


text:
learn-asterisk-freeswitch
=========================

自学asterisk和freeswitch


text:
package org.apache.camel.component.mail;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.camel.Attachment;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;

import static org.assertj.core.api.Assertions.assertThat;

@RunWith(Parameterized.class)
public class MailBindingAttachmentFileTest {

    @Parameter
    public String name;

    private final MailBinding binding = new MailBinding();

    @Test
    public void shouldSanitizeAttachmentFileNames() throws MessagingException, IOException {
        final Session session = Session.getInstance(new Properties());
        final Message message = new MimeMessage(session);

        final Multipart multipart = new MimeMultipart();
        final MimeBodyPart part = new MimeBodyPart();
        part.attachFile(name);
        multipart.addBodyPart(part);
        message.setContent(multipart);

        final Map<String, Attachment> attachments = new HashMap<>();
        binding.extractAttachmentsFromMail(message, attachments);

        assertThat(attachments).containsKey("file.txt");
        final Attachment attachment = attachments.get("file.txt");
        final DataHandler dataHandler = attachment.getDataHandler();
        assertThat(dataHandler.getName()).isEqualTo("file.txt");
    }

    @Parameters(name = "{0}")
    public static Iterable<String> fileNames() {
        return Arrays.asList("file.txt", "../file.txt", "..\\file.txt", "/absolute/file.txt", "c:\\absolute\\file.txt");
    }
}


text:
#ifndef TVM_META_SCHEDULE_UTILS_H_
#define TVM_META_SCHEDULE_UTILS_H_

#include <dmlc/memory_io.h>
#include <tvm/arith/analyzer.h>
#include <tvm/meta_schedule/arg_info.h>
#include <tvm/meta_schedule/builder.h>
#include <tvm/meta_schedule/cost_model.h>
#include <tvm/meta_schedule/database.h>
#include <tvm/meta_schedule/feature_extractor.h>
#include <tvm/meta_schedule/measure_callback.h>
#include <tvm/meta_schedule/runner.h>
#include <tvm/meta_schedule/schedule_rule.h>
#include <tvm/meta_schedule/search_strategy.h>
#include <tvm/meta_schedule/space_generator.h>
#include <tvm/meta_schedule/task_scheduler.h>
#include <tvm/meta_schedule/tune_context.h>
#include <tvm/node/node.h>
#include <tvm/node/serialization.h>
#include <tvm/support/parallel_for.h>
#include <tvm/tir/schedule/schedule.h>

#include <string>
#include <vector>

#include "../printer/text_printer.h"
#include "../support/array.h"
#include "../support/base64.h"
#include "../support/nd_int_set.h"
#include "../support/utils.h"
#include "../tir/schedule/primitive.h"
#include "../tir/schedule/utils.h"

namespace tvm {
namespace meta_schedule {

/*! \brief The type of the random state */
using TRandState = support::LinearCongruentialEngine::TRandState;

/*!
 * \brief Read lines from a json file.
 * \param path The path to the json file.
 * \param allow_missing Whether to create new file when the given path is not found.
 * \return An array containing lines read from the json file.
 */
inline Array<String> JSONFileReadLines(const String& path, bool allow_missing) {
  std::ifstream is(path);
  if (is.good()) {
    Array<String> results;
    for (std::string str; std::getline(is, str);) {
      results.push_back(str);
    }
    return results;
  }
  CHECK(allow_missing) << "ValueError: File doesn't exist: " << path;
  std::ofstream os(path);
  CHECK(os.good()) << "ValueError: Cannot create new file: " << path;
  return {};
}

/*!
 * \brief Append a line to a json file.
 * \param path The path to the json file.
 * \param line The line to append.
 */
inline void JSONFileAppendLine(const String& path, const std::string& line) {
  std::ofstream os(path, std::ofstream::app);
  CHECK(os.good()) << "ValueError: Cannot open the file to write: " << path;
  os << line << std::endl;
}

/*!
 * \brief Get the base64 encoded result of a string.
 * \param str The string to encode.
 * \return The base64 encoded string.
 */
inline std::string Base64Encode(std::string str) {
  std::string result;
  dmlc::MemoryStringStream m_stream(&result);
  support::Base64OutStream b64stream(&m_stream);
  static_cast<dmlc::Stream*>(&b64stream)->Write(str);
  b64stream.Finish();
  return result;
}

/*!
 * \brief Get the base64 decoded result of a string.
 * \param str The string to decode.
 * \return The base64 decoded string.
 */
inline std::string Base64Decode(std::string str) {
  std::string result;
  dmlc::MemoryStringStream m_stream(&str);
  support::Base64InStream b64stream(&m_stream);
  b64stream.InitPosition();
  static_cast<dmlc::Stream*>(&b64stream)->Read(&result);
  return result;
}

/*!
 * \brief Parse lines of json string into a json object.
 * \param lines The lines of json string.
 * \return Array of json objects parsed.
 * \note The function calls the python-side json parser in runtime registry.
 */
inline Array<ObjectRef> JSONStr2Obj(const Array<String>& lines) {
  static const runtime::PackedFunc* f_to_obj =
      runtime::Registry::Get("meta_schedule.batch_json_str2obj");
  ICHECK(f_to_obj) << "IndexError: Cannot find the packed function "
                      "`meta_schedule.batch_json_str2obj` in the global registry";
  return (*f_to_obj)(lines);
}

/*!
 * \brief Serialize a json object into a json string.
 * \param json_obj The json object to serialize.
 * \return A string containing the serialized json object.
 * \note The function calls the python-side json obj serializer in runtime registry.
 */
inline String JSONObj2Str(const ObjectRef& json_obj) {
  static const runtime::PackedFunc* f_to_str = runtime::Registry::Get("meta_schedule.json_obj2str");
  ICHECK(f_to_str) << "IndexError: Cannot find the packed function "
                      "`meta_schedule.json_obj2str` in the global registry";
  return (*f_to_str)(json_obj);
}

/*!
 * \brief Converts a structural hash code to string
 * \param hash_code The hash code
 * \return The string representation of the hash code
 */
inline String SHash2Str(Workload::THashCode hash_code) { return std::to_string(hash_code); }

/*!
 * \brief Find the entry function of the given IRModule, i.e, functions marked by
 * `tir::attr::kIsEntryFunc`, whose name is `main` or being the only PrimeFunc.
 * \param mod The IRModule to find the entry function.
 * \return The entry function.
 */
inline tir::PrimFunc FindEntryFunc(const IRModule& mod) {
  // Priority 1: PrimFunc marked as `tir::attr::kIsEntryFunc`
  int num_prim_func = 0;
  const tir::PrimFuncNode* main_func = nullptr;
  const tir::PrimFuncNode* last_func = nullptr;
  for (const auto& kv : mod->functions) {
    GlobalVar gv = kv.first;
    BaseFunc base_func = kv.second;
    if (const auto* func = base_func.as<tir::PrimFuncNode>()) {
      last_func = func;
      if (func->HasNonzeroAttr(tir::attr::kIsEntryFunc)) {
        return GetRef<tir::PrimFunc>(func);
      }
      if (gv->name_hint == "main") {
        main_func = func;
      }
      ++num_prim_func;
    }
  }
  // Priority 2: PrimFunc whose name is `main`
  if (main_func != nullptr) {
    return GetRef<tir::PrimFunc>(main_func);
  }
  // Priority 3: The only PrimFunc in the IRModule
  if (num_prim_func == 0) {
    LOG(FATAL) << "ValueError: Cannot find any PrimFunc in the given IRModule: "
               << tir::AsTVMScript(mod);
  }
  if (num_prim_func > 1) {
    LOG(FATAL) << "ValueError: Multiple PrimFuncs exist in the IRModule, but none of them are "
                  "annotated with `kIsEntryFunc`, i.e. `tir.is_entry_func`"
               << tir::AsTVMScript(mod);
  }
  return GetRef<tir::PrimFunc>(last_func);
}

/*!
 * \brief Fork a random state into another, i.e. PRNG splitting.
 * The given random state is also mutated.
 * \param rand_state The random state to be forked
 * \return The forked random state
 */
inline support::LinearCongruentialEngine::TRandState ForkSeed(
    support::LinearCongruentialEngine::TRandState* rand_state) {
  return support::LinearCongruentialEngine(rand_state).ForkSeed();
}

/*!
 * \brief Fork a random state into another ones, i.e. PRNG splitting.
 *  The given random state is also mutated.
 * \param rand_state The random state to be forked
 * \param n The number of forks
 * \return The forked random states
 */
inline std::vector<support::LinearCongruentialEngine::TRandState> ForkSeed(
    support::LinearCongruentialEngine::TRandState* rand_state, int n) {
  std::vector<support::LinearCongruentialEngine::TRandState> results;
  results.reserve(n);
  for (int i = 0; i < n; ++i) {
    results.push_back(support::LinearCongruentialEngine(rand_state).ForkSeed());
  }
  return results;
}

/*!
 * \brief Get deep copy of an IRModule.
 * \param mod The IRModule to make a deep copy.
 * \return The deep copy of the IRModule.
 */
inline IRModule DeepCopyIRModule(IRModule mod) {
  return Downcast<IRModule>(LoadJSON(SaveJSON(mod)));
}

/*!
 * \brief Concatenate strings
 * \param strs The strings to concatenate
 * \param delim The delimiter
 * \return The concatenated string
 */
inline std::string Concat(const Array<String>& strs, const std::string& delim) {
  if (strs.empty()) {
    return "";
  }
  std::ostringstream os;
  os << strs[0];
  for (int i = 1, n = strs.size(); i < n; ++i) {
    os << delim << strs[i];
  }
  return os.str();
}

/*!
 * \brief A helper data structure that replays a trace and collects failure counts
 * for each postprocessor
 */
struct ThreadedTraceApply {
  /*! \brief Constructor */
  explicit ThreadedTraceApply(const Array<Postproc>& postprocs)
      : n_(postprocs.size()), items_(new Item[n_]) {
    for (int i = 0; i < n_; ++i) {
      items_[i].postproc = postprocs[i];
      items_[i].fail_counter = 0;
    }
  }

  /*! \brief Destructor */
  ~ThreadedTraceApply() { delete[] items_; }

  /*!
   * \brief Apply the trace and postprocessors to an IRModule
   * \param mod The IRModule to be applied
   * \param trace The trace to apply to the IRModule
   * \param rand_state The random seed
   * \return The schedule created, or NullOpt if any postprocessor fails
   */
  Optional<tir::Schedule> Apply(const IRModule& mod, const tir::Trace& trace,
                                TRandState* rand_state) {
    tir::Schedule sch =
        tir::Schedule::Traced(mod,
                              /*rand_state=*/ForkSeed(rand_state),
                              /*debug_mode=*/0,
                              /*error_render_level=*/tir::ScheduleErrorRenderLevel::kNone);
    trace->ApplyToSchedule(sch, /*remove_postproc=*/true);
    sch->EnterPostproc();
    for (int i = 0; i < n_; ++i) {
      Item& item = items_[i];
      if (!item.postproc->Apply(sch)) {
        ++item.fail_counter;
        return NullOpt;
      }
    }
    return sch;
  }

  /*! \brief Returns a string summarizing the failures on each postprocessor */
  std::string SummarizeFailures() const {
    std::ostringstream os;
    for (int i = 0; i < n_; ++i) {
      const Item& item = items_[i];
      os << "Postproc #" << i << " [" << item.postproc  //
         << "]: " << item.fail_counter.load() << " failure(s)";
      if (i != n_ - 1) {
        os << "\n";
      }
    }
    return os.str();
  }

 private:
  /*! \brief A helper data structure that stores the fail count for each postprocessor. */
  struct Item {
    /*! \brief The postprocessor. */
    Postproc postproc{nullptr};
    /*! \brief The thread-safe postprocessor failure counter. */
    std::atomic<int> fail_counter{0};
  };

  /*! \brief The number of total postprocessors. */
  int n_;
  /*! \brief The pointer to the list of postprocessor items. */
  Item* items_;
};

}  // namespace meta_schedule
}  // namespace tvm

#endif  // TVM_META_SCHEDULE_UTILS_H_


text:
<?php
namespace Payum\Braintree\Reply\Api;

use Braintree\Transaction;
use Payum\Braintree\Util\ArrayUtils;

class TransactionArray
{
    public static function toArray(Transaction $object)
    {
        if (null == $object) {
            return;
        }

        $array = ArrayUtils::extractPropertiesToArray($object, [
            'id', 'status', 'type', 'currentIsoCode', 'amount',
            'merchantAccountId', 'subMerchantAccountId', 'masterMerchantAccountId',
            'orderId', 'createdAt', 'updatedAt', 'customer', 'billing', 'refundId',
            'refundIds', 'refundedTransactionId', 'partialSettlementTransactionIds',
            'authorizedTransactionId', 'settlementBatchId', 'shipping', 'customFields',
            'avsErrorResponseCode', 'avsPostalCodeResponseCode', 'avsStreetAddressResponseCode',
            'cvvResponseCode', 'gatewayRejectionReason', 'processorAuthorizationCode',
            'processorResponseCode', 'processorResponseText', 'additionalProcessorResponse',
            'voiceReferralNumber', 'purchaseOrderNumber', 'taxAmount', 'taxExempt', 'creditCard',
            'planId', 'subscriptionId', 'subscription', 'addOns', 'discounts', 'recurring',
            'channel', 'serviceFeeAmount', 'escrowStatus', /*disbursementDetails,*/
            'paymentInstrumentType', 'processorSettlementResponseCode',
            'processorSettlementResponseText', 'threeDSecureInfo' /*, creditCardDetails */
        ]);

        return $array;
    }
}


text:
__version__ = '0.3.1' #remember to update setup.py
__version_info__ = tuple([ int(num) for num in __version__.split('.')])

from concurrence.core import dispatch, quit, disable_threading, get_version_info, TIMEOUT_NEVER, TIMEOUT_CURRENT
from concurrence.core import Channel, Tasklet, Message, Deque, FileDescriptorEvent, SignalEvent, TimeoutEvent
from concurrence.core import TimeoutError, TaskletError, JoinError
from concurrence.extra import TaskletPool, DeferredQueue, Lock, Semaphore, QueueChannel
from concurrence.local import TaskLocal, TaskInstance
from concurrence.timer import Timeout

import concurrence._unittest as unittest

try:
    import json
except:
    try:
        import simplejson as json
    except:
        import logging
        logging.exception("could not import json library!', pls install simplejson or use python 2.6+")