text:
var express        = require('express');
var morgan         = require('morgan');                         // log requests to the console (express4)
var bodyParser     = require('body-parser');                    // pull information from HTML POST (express4)
var methodOverride = require('method-override');                // simulate DELETE and PUT (express4)
var mongoose       = require('mongoose');                       // mongoose for mongodb
var app            = express();                                 // create our app w/ express
var port  	       = process.env.PORT || 8080; 				    // set the port

// configuration ============================================================================================
app.use(express.static(__dirname + '/public'));                 // set the static files location
app.use(morgan('dev'));                                         // log every request to the console
app.use(bodyParser.urlencoded({'extended':'true'})); 			// parse application/x-www-form-urlencoded
app.use(bodyParser.json()); 									// parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride());                                      // simulate DELETE and PUT

// routes ===================================================================================================
routes = require('./routes/ticket.js')(app);

// MongoDB configuration ====================================================================================
mongoose.connect('mongodb://localhost/ticket', function(err, res) {
	if (err) {
		console.log('error connecting to MongoDB Database. ' + err);
	} else {
		console.log('Connected to Database');
	}
});

// listen (start app with node server.js) ===================================================================
app.listen(port);
console.log('Listenning on port ' + port);

app.get('/', function(req, res) {
	res.send("nodejs-angularjs-crud");
});

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.batch.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** The endpoint configuration for a pool. */
@Fluent
public final class PoolEndpointConfiguration {
    /*
     * A list of inbound NAT pools that can be used to address specific ports on an individual compute node externally.
     *
     * The maximum number of inbound NAT pools per Batch pool is 5. If the maximum number of inbound NAT pools is
     * exceeded the request fails with HTTP status code 400. This cannot be specified if the IPAddressProvisioningType
     * is NoPublicIPAddresses.
     */
    @JsonProperty(value = "inboundNatPools", required = true)
    private List<InboundNatPool> inboundNatPools;

    /** Creates an instance of PoolEndpointConfiguration class. */
    public PoolEndpointConfiguration() {
    }

    /**
     * Get the inboundNatPools property: A list of inbound NAT pools that can be used to address specific ports on an
     * individual compute node externally.
     *
     *
The maximum number of inbound NAT pools per Batch pool is 5. If the maximum number of inbound NAT pools is
     * exceeded the request fails with HTTP status code 400. This cannot be specified if the IPAddressProvisioningType
     * is NoPublicIPAddresses.
     *
     * @return the inboundNatPools value.
     */
    public List<InboundNatPool> inboundNatPools() {
        return this.inboundNatPools;
    }

    /**
     * Set the inboundNatPools property: A list of inbound NAT pools that can be used to address specific ports on an
     * individual compute node externally.
     *
     *
The maximum number of inbound NAT pools per Batch pool is 5. If the maximum number of inbound NAT pools is
     * exceeded the request fails with HTTP status code 400. This cannot be specified if the IPAddressProvisioningType
     * is NoPublicIPAddresses.
     *
     * @param inboundNatPools the inboundNatPools value to set.
     * @return the PoolEndpointConfiguration object itself.
     */
    public PoolEndpointConfiguration withInboundNatPools(List<InboundNatPool> inboundNatPools) {
        this.inboundNatPools = inboundNatPools;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (inboundNatPools() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property inboundNatPools in model PoolEndpointConfiguration"));
        } else {
            inboundNatPools().forEach(e -> e.validate());
        }
    }

    private static final ClientLogger LOGGER = new ClientLogger(PoolEndpointConfiguration.class);
}


text:
from nose.tools import *
from dateutil.parser import parse as time_parse
import yawhois

class TestWhoisNicCoStatusRegistered(object):

    def setUp(self):
        fixture_path = "spec/fixtures/responses/whois.nic.co/status_registered.txt"
        host         = "whois.nic.co"
        part         = yawhois.record.Part(open(fixture_path, "r").read(), host)
        self.record  = yawhois.record.Record(None, [part])

    def test_status(self):
        eq_(self.record.status, ["clientTransferProhibited"])

    def test_available(self):
        eq_(self.record.available, False)

    def test_domain(self):
        eq_(self.record.domain, "t.co")

    def test_nameservers(self):
        eq_(self.record.nameservers.__class__.__name__, 'list')
        eq_(len(self.record.nameservers), 4)
        eq_(self.record.nameservers[0].__class__.__name__, 'Nameserver')
        eq_(self.record.nameservers[0].name, "ns1.p34.dynect.net")
        eq_(self.record.nameservers[1].__class__.__name__, 'Nameserver')
        eq_(self.record.nameservers[1].name, "ns2.p34.dynect.net")
        eq_(self.record.nameservers[2].__class__.__name__, 'Nameserver')
        eq_(self.record.nameservers[2].name, "ns3.p34.dynect.net")
        eq_(self.record.nameservers[3].__class__.__name__, 'Nameserver')
        eq_(self.record.nameservers[3].name, "ns4.p34.dynect.net")

    def test_admin_contacts(self):
        eq_(self.record.admin_contacts.__class__.__name__, 'list')
        eq_(len(self.record.admin_contacts), 1)
        eq_(self.record.admin_contacts[0].__class__.__name__, 'Contact')
        eq_(self.record.admin_contacts[0].type, yawhois.record.Contact.TYPE_ADMINISTRATIVE)
        eq_(self.record.admin_contacts[0].id, "868543810568A633")
        eq_(self.record.admin_contacts[0].name, "Domain Admin")
        eq_(self.record.admin_contacts[0].organization, "Twitter, Inc.")
        eq_(self.record.admin_contacts[0].address, "1355 Market Street\nSuite 900")
        eq_(self.record.admin_contacts[0].city, "San Francisco")
        eq_(self.record.admin_contacts[0].zip, "94103")
        eq_(self.record.admin_contacts[0].state, "California")
        eq_(self.record.admin_contacts[0].country, "United States")
        eq_(self.record.admin_contacts[0].country_code, "US")
        eq_(self.record.admin_contacts[0].phone, "+1.4152229670")
        eq_(self.record.admin_contacts[0].fax, "+1.4152220922")
        eq_(self.record.admin_contacts[0].email, "domains@twitter.com")

    def test_registered(self):
        eq_(self.record.registered, True)

    def test_created_on(self):
        eq_(self.record.created_on.__class__.__name__, 'datetime')
        eq_(self.record.created_on, time_parse('2010-04-26 07:50:40 GMT'))

    def test_registrar(self):
        eq_(self.record.registrar.__class__.__name__, 'Registrar')
        eq_(self.record.registrar.id, "299")
        eq_(self.record.registrar.name, "CSC CORPORATE DOMAINS")

    def test_registrant_contacts(self):
        eq_(self.record.registrant_contacts.__class__.__name__, 'list')
        eq_(len(self.record.registrant_contacts), 1)
        eq_(self.record.registrant_contacts[0].__class__.__name__, 'Contact')
        eq_(self.record.registrant_contacts[0].type, yawhois.record.Contact.TYPE_REGISTRANT)
        eq_(self.record.registrant_contacts[0].id, "365684910586C791")
        eq_(self.record.registrant_contacts[0].name, "Twitter, Inc.")
        eq_(self.record.registrant_contacts[0].organization, "Twitter, Inc.")
        eq_(self.record.registrant_contacts[0].address, "1355 Market Street\nSuite 900")
        eq_(self.record.registrant_contacts[0].city, "San Francisco")
        eq_(self.record.registrant_contacts[0].zip, "94103")
        eq_(self.record.registrant_contacts[0].state, "CA")
        eq_(self.record.registrant_contacts[0].country, "United States")
        eq_(self.record.registrant_contacts[0].country_code, "US")
        eq_(self.record.registrant_contacts[0].phone, "+1.4152229670")
        eq_(self.record.registrant_contacts[0].fax, "+1.4152220922")
        eq_(self.record.registrant_contacts[0].email, "domains@twitter.com")

    def test_technical_contacts(self):
        eq_(self.record.technical_contacts.__class__.__name__, 'list')
        eq_(len(self.record.technical_contacts), 1)
        eq_(self.record.technical_contacts[0].__class__.__name__, 'Contact')
        eq_(self.record.technical_contacts[0].type, yawhois.record.Contact.TYPE_TECHNICAL)
        eq_(self.record.technical_contacts[0].id, "42101611057C7478")
        eq_(self.record.technical_contacts[0].name, "Tech Admin")
        eq_(self.record.technical_contacts[0].organization, "Twitter, Inc.")
        eq_(self.record.technical_contacts[0].address, "1355 Market Street\nSuite 900")
        eq_(self.record.technical_contacts[0].city, "San Francisco")
        eq_(self.record.technical_contacts[0].zip, "94103")
        eq_(self.record.technical_contacts[0].state, "California")
        eq_(self.record.technical_contacts[0].country, "United States")
        eq_(self.record.technical_contacts[0].country_code, "US")
        eq_(self.record.technical_contacts[0].phone, "+1.4152229670")
        eq_(self.record.technical_contacts[0].fax, "+1.4152220922")
        eq_(self.record.technical_contacts[0].email, "domains-tech@twitter.com")

    def test_updated_on(self):
        eq_(self.record.updated_on.__class__.__name__, 'datetime')
        eq_(self.record.updated_on, time_parse('2013-10-14 13:03:24 GMT'))

    def test_domain_id(self):
        eq_(self.record.domain_id, "D740225-CO")

    def test_expires_on(self):
        eq_(self.record.expires_on.__class__.__name__, 'datetime')
        eq_(self.record.expires_on, time_parse('2016-04-25 23:59:59 GMT'))


text:
<?xml version="1.0"?>
<package>
  <name>zubax_posekf</name>
  <version>0.0.0</version>
  <description>Zubax POSEKF</description>

  <maintainer email="pavel.kirienko@zubax.com">Pavel Kirienko</maintainer>

  <license>MIT</license>

  <url type="website">http://zubax.com</url>

  <!-- The *_depend tags are used to specify dependencies -->
  <!-- Dependencies can be catkin packages or system dependencies -->
  <!-- Examples: -->
  <!-- Use build_depend for packages you need at compile time: -->
  <!--   <build_depend>message_generation</build_depend> -->
  <!-- Use buildtool_depend for build tool packages: -->
  <!--   <buildtool_depend>catkin</buildtool_depend> -->
  <!-- Use run_depend for packages you need at runtime: -->
  <!--   <run_depend>message_runtime</run_depend> -->
  <!-- Use test_depend for packages you need only for testing: -->
  <!--   <test_depend>gtest</test_depend> -->
  <buildtool_depend>catkin</buildtool_depend>

  <build_depend>roscpp</build_depend>
  <build_depend>sensor_msgs</build_depend>
  <build_depend>std_msgs</build_depend>
  <build_depend>gps_common</build_depend>
  <build_depend>visualization_msgs</build_depend>
  <build_depend>nav_msgs</build_depend>
  <build_depend>geometry_msgs</build_depend>
  <build_depend>eigen</build_depend>
  <build_depend>eigen_conversions</build_depend>
  <build_depend>tf</build_depend>

  <run_depend>roscpp</run_depend>
  <run_depend>sensor_msgs</run_depend>
  <run_depend>std_msgs</run_depend>
  <run_depend>gps_common</run_depend>
  <run_depend>visualization_msgs</run_depend>
  <run_depend>nav_msgs</run_depend>
  <run_depend>geometry_msgs</run_depend>
  <run_depend>eigen</run_depend>
  <run_depend>eigen_conversions</run_depend>
  <run_depend>tf</run_depend>

  <export>
  </export>
</package>


text:
#include <ctime>
#include <string>
#include <iostream>
#include <fstream>

#include "interactions.h"
#include "logging.h"

#include <gdk/gdk.h>
#include <gdk/gdkkeysyms.h>
#include <X11/Xlib.h>
#include <time.h>
#include <stdlib.h>
#include <assert.h>
#include <list>
#include <algorithm>
#include <functional>

#include "translate_keycode_linux.h"
#include "interactions_linux.h"

using namespace std;

guint32 gLatestEventTime = 0;

// This is the timestamp needed in the GDK events.
guint32 TimeSinceBootMsec()
{
    struct timespec clk_tm;
    const int msec_nsec_factor = 1000000;
    const int sec_msec_factor = 1000;

    int clk_ret = clock_gettime(CLOCK_MONOTONIC, &clk_tm);
    if (clk_ret == 0)
    {
      return (clk_tm.tv_sec * sec_msec_factor +
              (clk_tm.tv_nsec / msec_nsec_factor));
    }
    return 0;
}

void sleep_for_ms(int sleep_time_ms)
{
  struct timespec sleep_time;
  sleep_time.tv_sec = sleep_time_ms / 1000;
  sleep_time.tv_nsec = (sleep_time_ms % 1000) * 1000000;
  nanosleep(&sleep_time, NULL);
}

bool is_gdk_keyboard_event(GdkEvent* ev)
{
  return ((ev->type == GDK_KEY_PRESS) || (ev->type == GDK_KEY_RELEASE));
}

bool is_gdk_mouse_event(GdkEvent* ev)
{
  return ((ev->type == GDK_BUTTON_PRESS) || (ev->type == GDK_BUTTON_RELEASE) ||
          (ev->type == GDK_MOTION_NOTIFY) || (ev->type == GDK_2BUTTON_PRESS));
}

bool event_earlier_than(GdkEvent* ev, guint32 compare_time)
{
  assert(is_gdk_keyboard_event(ev) || is_gdk_mouse_event(ev));
  return (ev->key.time <= compare_time);
}

void print_key_event(GdkEvent* p_ev)
{
  if (!((p_ev->type == GDK_KEY_PRESS) || (p_ev->type == GDK_KEY_RELEASE))) {
    LOG(DEBUG) << "Not a key event.";
    return;
  }
  const gchar* gdk_name = gdk_keyval_name(p_ev->key.keyval);
  const char* kNameUnknown = "UNKNOWN";
  const char* print_name = (gdk_name != NULL ? gdk_name : kNameUnknown);

  std::string ev_type = (p_ev->type == GDK_KEY_PRESS ? "press" : "release");
  LOG(DEBUG) << "Type: " << ev_type <<  "Key code: " << p_ev->key.keyval <<
             " (" << print_name << ") time: " <<
             p_ev->key.time << " state: " << p_ev->key.state << " hw keycode: "
             << (int) p_ev->key.hardware_keycode << " ";
}

bool additional_events_to_wait_for(GdkEvent* p_event)
{
  return ((p_event->type == GDK_LEAVE_NOTIFY) ||
          (p_event->type == GDK_ENTER_NOTIFY));

}

void init_logging()
{
#ifdef INTERACTIONS_DEBUG
  static bool log_initalized = false;
  if (!log_initalized) {
    LOG::Level("DEBUG");
    LOG::File(INTERACTIONS_LOG_FILE, "a");
    log_initalized = true;
  }
#endif
}

extern "C"
{
bool pending_input_events()
{
  LOG(DEBUG) << "Waiting for all events to be processed. Latest: " << gLatestEventTime;
  GdkEvent* lastEvent = gdk_event_peek();
  LOG(DEBUG) << "Got event: " <<
             (lastEvent != NULL ? lastEvent->type : 0);
  if ((lastEvent != NULL) && is_gdk_keyboard_event(lastEvent)) {
    print_key_event(lastEvent);
  }

  bool ret_val = false;
  if (lastEvent != NULL &&
      (((is_gdk_keyboard_event(lastEvent) || is_gdk_mouse_event(lastEvent)) &&
      event_earlier_than(lastEvent, gLatestEventTime))
       || (additional_events_to_wait_for(lastEvent)))) {
    ret_val = true;
  }

  if (lastEvent != NULL) {
    gdk_event_free(lastEvent);
  }
  LOG(DEBUG) << "Returning: " << ret_val;

  return ret_val;
}

// Does nothing on Linux
void stopPersistentEventFiring()
{
}

void setEnablePersistentHover(bool enablePersistentHover)
{
}

}


text:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <link rel="stylesheet" href="/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="/css/style.css"/>
    <link rel="stylesheet" href="/css/datepicker.css"/>

                Static header

Home

Define Parameter

                <form role="form" method="post" id="configureParameter" action="/config/parameters/define" class="form-horizontal">

                        Error Occurred.

                    <input id="paramIdEle" name="paramId" type="hidden" th:value="${configParameter.paramId}" />

                        Parameter Name

                            <input id="paramName" name="paramName" type="text" class="form-control" placeholder="Enter Parameter name" th:value="${configParameter.paramName}"/>

                        Parameter Value

                            <input id="paramValue" name="paramValue" type="text" class="form-control" placeholder="Enter value for Parameter" th:value="${configParameter.paramValue}"/>

                        Parameter Type

                            <select id="paramType" name="paramType" class="form-control">
                                <option th:each="supportedParamType : ${supportedParameterTypes}"
                                        th:value="${supportedParamType}" th:text="${supportedParamType}" th:selected="${supportedParamType.equals(configParameter.paramType)}">
                                    Select Option
                                </option>
                            </select>

                        Data Type

                            <select id="dataType" name="dataType" class="form-control">
                                <option th:each="supportedDataType : ${supportedParamDataTypes}"
                                        th:value="${supportedDataType}" th:text="${supportedDataType}" th:selected="${supportedDataType.equals(configParameter.dataType)}">
                                    String
                                </option>
                            </select>

                            <input type="submit" class="btn btn-default" value="Submit"/>

                </form>


text:
package sh.isaac.solor;

import java.io.InputStream;
import java.util.function.Supplier;

/**
 * A way to pass around closeable input streams for doing imports without passing around all the zip file mess.
 * @author Dan Armbrust
 */
public interface ContentStreamProvider extends Supplier<InputStream>, AutoCloseable
{

}


text:
package org.classified_event_aggregation.rest_api.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LogAction {

	@RequestMapping("/hello")
	public @ResponseBody String helloWorld() {
		return "helloWorld";
	}

}


text:
#ifndef CTKCOMMANDLINEMODULEAPPLOGIC_P_H
#define CTKCOMMANDLINEMODULEAPPLOGIC_P_H

// Qt includes
#include <QUuid>

// CTK includes
#include <ctkDicomAbstractApp.h>
#include <ctkDicomHostInterface.h>
#include <ctkCmdLineModuleManager.h>

#include <ctkServiceTracker.h>

// ui of this application
#include "ui_ctkCommandLineModuleAppWidget.h"

struct ctkDicomHostInterface;

class ctkCmdLineModuleFrontend;

class QWidget;

class ctkCommandLineModuleAppLogic : public ctkDicomAbstractApp
{
  Q_OBJECT
  Q_INTERFACES(ctkDicomAppInterface)

public:

  ctkCommandLineModuleAppLogic(const QString & modulelocation);
  virtual ~ctkCommandLineModuleAppLogic();

  // ctkDicomAppInterface

  /**
   * Method triggered by the host. By calling this method, the Hosting System is asking the Hosted Application to take whatever steps are
   * needed to make its GUI visible as the topmost window, and to gain focus.
   * \return TRUE if the Hosted Application received the request and will act on it. Otherwise it returns FALSE
   */
  virtual bool bringToFront(const QRect& requestedScreenArea);

  // some logic
  /** Test function for checking */
  void do_something();

protected Q_SLOTS:

  void onStartProgress();
  void onResumeProgress();
  void onSuspendProgress();
  void onCancelProgress();
  void onExitHostedApp();
  void onReleaseResources();

  void onLoadDataClicked();
  void onCreateSecondaryCapture();

  void onDataAvailable();
private:
  QWidget * AppWidget;
  Ui::ctkCommandLineModuleAppWidget ui;

  QString ModuleLocation;

  ctkCmdLineModuleManager ModuleManager;
  ctkCmdLineModuleFrontend* ModuleFrontend;

  QString OutputLocation;
}; // ctkCommandLineModuleAppLogic

#endif // CTKCOMMANDLINEMODULEAPPLOGIC_P_H


text:
package org.apache.nifi.controller.state;

public class ConfigParseException extends RuntimeException {
    private static final long serialVersionUID = 4956533590170361572L;

    public ConfigParseException(final String message) {
        super(message);
    }

    public ConfigParseException(final String message, final Throwable cause) {
        super(message, cause);
    }
}


text:
from setuptools import setup

NAME = "pythonpic"

VERSION = "0.3"

setup(
    name='pythonpic',
    version=VERSION,
    packages=[NAME],
    url='https://github.com/StanczakDominik/PythonPIC',
    license='',
    author='Dominik Stańczak',
    author_email='stanczakdominik@gmail.com',
    description='A particle-in-cell code written in Python optimized for speed as well as readability.',
    python_requires='>=3.6', install_requires=['matplotlib', 'numpy', 'scipy', 'h5py', 'pytest', 'pandas', 'numba']
    )


text:
package ca.ualberta.cmput301w14t08.geochan.test;

import java.util.ArrayList;
import java.util.Date;

import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;
import ca.ualberta.cmput301w14t08.geochan.activities.MainActivity;
import ca.ualberta.cmput301w14t08.geochan.helpers.LocationListenerService;
import ca.ualberta.cmput301w14t08.geochan.helpers.SortUtil;
import ca.ualberta.cmput301w14t08.geochan.models.Comment;
import ca.ualberta.cmput301w14t08.geochan.models.GeoLocation;
import ca.ualberta.cmput301w14t08.geochan.models.ThreadComment;

/**
 * Tests for the functionality of ThreadComment methods
 *
 */
public class ThreadCommentTest extends ActivityInstrumentationTestCase2<MainActivity> {

    private MainActivity activity;
    private LocationListenerService locationListenerService;

    public ThreadCommentTest(){
        super(MainActivity.class);
    }

    @Override
    protected void setUp() throws Exception {
        //Shamelessly ripped from GeolocationTest to test Comments with Geolocations.
        super.setUp();
        this.activity = getActivity();
        locationListenerService = new LocationListenerService(activity);
        locationListenerService.startListening();
    }

    /**
     * Tests adding a comment reply, adds a comment as a child,
     * verifies its presence in the children list
     */
    public void testAddComment(){
        ThreadComment t1 = new ThreadComment();
        Comment c1 = new Comment();

        t1.getBodyComment().addChild(c1);

        assertTrue("Comment added successfuly.", t1.getBodyComment().getChildren().contains(c1));
    }

    /**
     * Tests that distance between two geolocations is calculated correctly
     */
    public void testGetDistanceFrom(){
        ThreadComment t1 = new ThreadComment();
        GeoLocation g1 = new GeoLocation(5,5);

        t1.getBodyComment().getLocation().setCoordinates(0, 0);

        assertEquals("Distance calculated correctly.", t1.getDistanceFrom(g1),
                      Math.sqrt(50));
    }

    /**
     * Tests that the time difference between a comment and other date is correct
     */
    public void testGetTimeFrom(){
        ThreadComment t1 = new ThreadComment();
        Date d1 = new Date();

        assertEquals("Minimum time value calculated correctly.",t1.getTimeFrom(d1),
                    0.5);

        d1 = new Date(t1.getThreadDate().getTime() + 3600000);

        assertEquals("Time calculated correctly.", t1.getTimeFrom(d1),
                    1.0);
    }

    /**
     * Check that scores of different comments are calculated correctly
     */
    public void testGetScoreFromUser(){
        ThreadComment t1 = new ThreadComment();
        ThreadComment t2 = new ThreadComment();
        GeoLocation g = new GeoLocation(0,0);

        t1.getBodyComment().getLocation().setCoordinates(0,0);
        t2.getBodyComment().getLocation().setCoordinates(5, 5);

        assertTrue("Scores calculated relatively correctly.",
                    t1.getScoreFromUser(g) >
                    t2.getScoreFromUser(g));
    }

    /**
     * Tests comment sorting by newest creation time
     */
    public void testSortByDateNewest(){
        ArrayList<ThreadComment> carrier = new ArrayList<ThreadComment>();
        ThreadComment t1 = new ThreadComment();
        ThreadComment t2 = new ThreadComment();
        ThreadComment t3 = new ThreadComment();
        ThreadComment t4 = new ThreadComment();
        ThreadComment t5 = new ThreadComment();
        ThreadComment t6 = new ThreadComment();
        ThreadComment t7 = new ThreadComment();
        ThreadComment t8 = new ThreadComment();
        ThreadComment t9 = new ThreadComment();
        ThreadComment t10 = new ThreadComment();
        long extraTime = 1320000;
        Comment c1 = new Comment();
        Comment c2 = new Comment();
        Comment c3 = new Comment();
        Comment c4 = new Comment();
        Comment c5 = new Comment();
        Comment c6 = new Comment();
        Comment c7 = new Comment();
        Comment c8 = new Comment();
        Comment c9 = new Comment();
        Comment c10 = new Comment();
        Date currentDate = new Date();

        c1.setCommentDate(new Date(currentDate.getTime() + 1*extraTime));
        c2.setCommentDate(new Date(currentDate.getTime() + 2*extraTime));
        c3.setCommentDate(new Date(currentDate.getTime() + 3*extraTime));
        c4.setCommentDate(new Date(currentDate.getTime() + 4*extraTime));
        c5.setCommentDate(new Date(currentDate.getTime() + 5*extraTime));
        c6.setCommentDate(new Date(currentDate.getTime() + 6*extraTime));
        c7.setCommentDate(new Date(currentDate.getTime() + 7*extraTime));
        c8.setCommentDate(new Date(currentDate.getTime() + 8*extraTime));
        c9.setCommentDate(new Date(currentDate.getTime() + 9*extraTime));
        c10.setCommentDate(new Date(currentDate.getTime() + 10*extraTime));

        t1.setBodyComment(c1);
        t2.setBodyComment(c2);
        t3.setBodyComment(c3);
        t4.setBodyComment(c4);
        t5.setBodyComment(c5);
        t6.setBodyComment(c6);
        t7.setBodyComment(c7);
        t8.setBodyComment(c8);
        t9.setBodyComment(c9);
        t10.setBodyComment(c10);

        carrier.add(t1);
        carrier.add(t2);
        carrier.add(t3);
        carrier.add(t4);
        carrier.add(t5);
        carrier.add(t6);
        carrier.add(t7);
        carrier.add(t8);
        carrier.add(t9);
        carrier.add(t10);

        SortUtil.setThreadSortGeo(new GeoLocation(0,0));

        SortUtil.sortThreads(SortUtil.SORT_DATE_NEWEST,
                            carrier);

        assertTrue("t10 at index 0", carrier.get(0) == t10);
        assertTrue("t9 at index 1", carrier.get(1) == t9);
        assertTrue("t8 at index 2", carrier.get(2) == t8);
        assertTrue("t7 at index 3", carrier.get(3) == t7);
        assertTrue("t6 at index 4", carrier.get(4) == t6);
        assertTrue("t5 at index 5", carrier.get(5) == t5);
        assertTrue("t4 at index 6", carrier.get(6) == t4);
        assertTrue("t3 at index 7", carrier.get(7) == t3);
        assertTrue("t2 at index 8", carrier.get(8) == t2);
        assertTrue("t1 at index 9", carrier.get(9) == t1);
    }

    /**
     * Tests sorting by oldest date by creating a sequence of comments
     * then checking they appear in reverse order after sorting
     */
    public void testSortByDateOldest(){
        ArrayList<ThreadComment> carrier = new ArrayList<ThreadComment>();
        ThreadComment t1 = new ThreadComment();
        ThreadComment t2 = new ThreadComment();
        ThreadComment t3 = new ThreadComment();
        ThreadComment t4 = new ThreadComment();
        ThreadComment t5 = new ThreadComment();
        ThreadComment t6 = new ThreadComment();
        ThreadComment t7 = new ThreadComment();
        ThreadComment t8 = new ThreadComment();
        ThreadComment t9 = new ThreadComment();
        ThreadComment t10 = new ThreadComment();
        long extraTime = 1320000;
        Comment c1 = new Comment();
        Comment c2 = new Comment();
        Comment c3 = new Comment();
        Comment c4 = new Comment();
        Comment c5 = new Comment();
        Comment c6 = new Comment();
        Comment c7 = new Comment();
        Comment c8 = new Comment();
        Comment c9 = new Comment();
        Comment c10 = new Comment();
        Date currentDate = new Date();

        c1.setCommentDate(new Date(currentDate.getTime() + 1*extraTime));
        c2.setCommentDate(new Date(currentDate.getTime() + 2*extraTime));
        c3.setCommentDate(new Date(currentDate.getTime() + 3*extraTime));
        c4.setCommentDate(new Date(currentDate.getTime() + 4*extraTime));
        c5.setCommentDate(new Date(currentDate.getTime() + 5*extraTime));
        c6.setCommentDate(new Date(currentDate.getTime() + 6*extraTime));
        c7.setCommentDate(new Date(currentDate.getTime() + 7*extraTime));
        c8.setCommentDate(new Date(currentDate.getTime() + 8*extraTime));
        c9.setCommentDate(new Date(currentDate.getTime() + 9*extraTime));
        c10.setCommentDate(new Date(currentDate.getTime() + 10*extraTime));

        t1.setBodyComment(c1);
        t2.setBodyComment(c2);
        t3.setBodyComment(c3);
        t4.setBodyComment(c4);
        t5.setBodyComment(c5);
        t6.setBodyComment(c6);
        t7.setBodyComment(c7);
        t8.setBodyComment(c8);
        t9.setBodyComment(c9);
        t10.setBodyComment(c10);

        carrier.add(t1);
        carrier.add(t2);
        carrier.add(t3);
        carrier.add(t4);
        carrier.add(t5);
        carrier.add(t6);
        carrier.add(t7);
        carrier.add(t8);
        carrier.add(t9);
        carrier.add(t10);

        SortUtil.setThreadSortGeo(new GeoLocation(0,0));

        SortUtil.sortThreads(SortUtil.SORT_DATE_OLDEST,
                            carrier);

        assertTrue("t1 at index 0", carrier.get(0) == t1);
        assertTrue("t2 at index 1", carrier.get(1) == t2);
        assertTrue("t3 at index 2", carrier.get(2) == t3);
        assertTrue("t4 at index 3", carrier.get(3) == t4);
        assertTrue("t5 at index 4", carrier.get(4) == t5);
        assertTrue("t6 at index 5", carrier.get(5) == t6);
        assertTrue("t7 at index 6", carrier.get(6) == t7);
        assertTrue("t8 at index 7", carrier.get(7) == t8);
        assertTrue("t9 at index 8", carrier.get(8) == t9);
        assertTrue("t10 at index 9", carrier.get(9) == t10);
    }

    /**
     * Tests the sorting of comments in a thread by the score relative to the user.
     */
    public void testSortByUserScoreHighest(){
        ArrayList<ThreadComment> carrier = new ArrayList<ThreadComment>();
        ThreadComment t1 = new ThreadComment();
        ThreadComment t2 = new ThreadComment();
        ThreadComment t3 = new ThreadComment();
        ThreadComment t4 = new ThreadComment();
        ThreadComment t5 = new ThreadComment();
        ThreadComment t6 = new ThreadComment();
        ThreadComment t7 = new ThreadComment();
        ThreadComment t8 = new ThreadComment();
        ThreadComment t9 = new ThreadComment();
        ThreadComment t10 = new ThreadComment();
        long extraTime = 1320000;
        Comment c1 = new Comment();
        Comment c2 = new Comment();
        Comment c3 = new Comment();
        Comment c4 = new Comment();
        Comment c5 = new Comment();
        Comment c6 = new Comment();
        Comment c7 = new Comment();
        Comment c8 = new Comment();
        Comment c9 = new Comment();
        Comment c10 = new Comment();
        Date currentDate = new Date();
        GeoLocation geoLocation1 = new GeoLocation(5,5);
        GeoLocation geoLocation2 = new GeoLocation(10,10);
        GeoLocation geoLocation3 = new GeoLocation(15,15);
        GeoLocation geoLocation4 = new GeoLocation(20,20);
        GeoLocation geoLocation5 = new GeoLocation(25,25);
        GeoLocation geoLocation6 = new GeoLocation(30,30);
        GeoLocation geoLocation7 = new GeoLocation(35,35);
        GeoLocation geoLocation8 = new GeoLocation(40,40);
        GeoLocation geoLocation9 = new GeoLocation(45,45);
        GeoLocation geoLocation10 = new GeoLocation(50,50);

        c1.setCommentDate(new Date(currentDate.getTime() - 1*extraTime));
        c2.setCommentDate(new Date(currentDate.getTime() - 2*extraTime));
        c3.setCommentDate(new Date(currentDate.getTime() - 3*extraTime));
        c4.setCommentDate(new Date(currentDate.getTime() - 4*extraTime));
        c5.setCommentDate(new Date(currentDate.getTime() - 5*extraTime));
        c6.setCommentDate(new Date(currentDate.getTime() - 6*extraTime));
        c7.setCommentDate(new Date(currentDate.getTime() - 7*extraTime));
        c8.setCommentDate(new Date(currentDate.getTime() - 8*extraTime));
        c9.setCommentDate(new Date(currentDate.getTime() - 9*extraTime));
        c10.setCommentDate(new Date(currentDate.getTime() - 10*extraTime));

        c1.setLocation(geoLocation1);
        c2.setLocation(geoLocation2);
        c3.setLocation(geoLocation3);
        c4.setLocation(geoLocation4);
        c5.setLocation(geoLocation5);
        c6.setLocation(geoLocation6);
        c7.setLocation(geoLocation7);
        c8.setLocation(geoLocation8);
        c9.setLocation(geoLocation9);
        c10.setLocation(geoLocation10);

        t1.setBodyComment(c1);
        t2.setBodyComment(c2);
        t3.setBodyComment(c3);
        t4.setBodyComment(c4);
        t5.setBodyComment(c5);
        t6.setBodyComment(c6);
        t7.setBodyComment(c7);
        t8.setBodyComment(c8);
        t9.setBodyComment(c9);
        t10.setBodyComment(c10);

        carrier.add(t3);
        carrier.add(t2);
        carrier.add(t4);
        carrier.add(t1);
        carrier.add(t5);
        carrier.add(t7);
        carrier.add(t6);
        carrier.add(t10);
        carrier.add(t8);
        carrier.add(t9);

        for(ThreadComment thread: carrier){
            Log.e("Score of thread:", String.valueOf(thread.getScoreFromUser(new GeoLocation(0,0))));
        }

        SortUtil.setThreadSortGeo(new GeoLocation(0,0));

        SortUtil.sortThreads(SortUtil.SORT_USER_SCORE_HIGHEST,
                            carrier);

        Log.e(""," ");
        for(ThreadComment thread: carrier){
            Log.e("Score of thread:", String.valueOf(thread.getScoreFromUser(new GeoLocation(0,0))));
        }

        assertTrue("t1 at index 0", carrier.get(0) == t1);
        assertTrue("t2 at index 1", carrier.get(1) == t2);
        assertTrue("t3 at index 2", carrier.get(2) == t3);
        assertTrue("t4 at index 3", carrier.get(3) == t4);
        assertTrue("t5 at index 4", carrier.get(4) == t5);
        assertTrue("t6 at index 5", carrier.get(5) == t6);
        assertTrue("t7 at index 6", carrier.get(6) == t7);
        assertTrue("t8 at index 7", carrier.get(7) == t8);
        assertTrue("t9 at index 8", carrier.get(8) == t9);
        assertTrue("t10 at index 9", carrier.get(9) == t10);
    }

    /**
     * Tests the sorting of threads by the score relative to the user.
     */
    public void testSortByUserScoreLowest(){
        ArrayList<ThreadComment> carrier = new ArrayList<ThreadComment>();
        ThreadComment t1 = new ThreadComment();
        ThreadComment t2 = new ThreadComment();
        ThreadComment t3 = new ThreadComment();
        ThreadComment t4 = new ThreadComment();
        ThreadComment t5 = new ThreadComment();
        ThreadComment t6 = new ThreadComment();
        ThreadComment t7 = new ThreadComment();
        ThreadComment t8 = new ThreadComment();
        ThreadComment t9 = new ThreadComment();
        ThreadComment t10 = new ThreadComment();
        long extraTime = 1320000;
        Comment c1 = new Comment();
        Comment c2 = new Comment();
        Comment c3 = new Comment();
        Comment c4 = new Comment();
        Comment c5 = new Comment();
        Comment c6 = new Comment();
        Comment c7 = new Comment();
        Comment c8 = new Comment();
        Comment c9 = new Comment();
        Comment c10 = new Comment();
        Date currentDate = new Date();
        GeoLocation geoLocation1 = new GeoLocation(5,5);
        GeoLocation geoLocation2 = new GeoLocation(10,10);
        GeoLocation geoLocation3 = new GeoLocation(15,15);
        GeoLocation geoLocation4 = new GeoLocation(20,20);
        GeoLocation geoLocation5 = new GeoLocation(25,25);
        GeoLocation geoLocation6 = new GeoLocation(30,30);
        GeoLocation geoLocation7 = new GeoLocation(35,35);
        GeoLocation geoLocation8 = new GeoLocation(40,40);
        GeoLocation geoLocation9 = new GeoLocation(45,45);
        GeoLocation geoLocation10 = new GeoLocation(50,50);

        c1.setCommentDate(new Date(currentDate.getTime() - 1*extraTime));
        c2.setCommentDate(new Date(currentDate.getTime() - 2*extraTime));
        c3.setCommentDate(new Date(currentDate.getTime() - 3*extraTime));
        c4.setCommentDate(new Date(currentDate.getTime() - 4*extraTime));
        c5.setCommentDate(new Date(currentDate.getTime() - 5*extraTime));
        c6.setCommentDate(new Date(currentDate.getTime() - 6*extraTime));
        c7.setCommentDate(new Date(currentDate.getTime() - 7*extraTime));
        c8.setCommentDate(new Date(currentDate.getTime() - 8*extraTime));
        c9.setCommentDate(new Date(currentDate.getTime() - 9*extraTime));
        c10.setCommentDate(new Date(currentDate.getTime() - 10*extraTime));

        c1.setLocation(geoLocation1);
        c2.setLocation(geoLocation2);
        c3.setLocation(geoLocation3);
        c4.setLocation(geoLocation4);
        c5.setLocation(geoLocation5);
        c6.setLocation(geoLocation6);
        c7.setLocation(geoLocation7);
        c8.setLocation(geoLocation8);
        c9.setLocation(geoLocation9);
        c10.setLocation(geoLocation10);

        t1.setBodyComment(c1);
        t2.setBodyComment(c2);
        t3.setBodyComment(c3);
        t4.setBodyComment(c4);
        t5.setBodyComment(c5);
        t6.setBodyComment(c6);
        t7.setBodyComment(c7);
        t8.setBodyComment(c8);
        t9.setBodyComment(c9);
        t10.setBodyComment(c10);

        carrier.add(t3);
        carrier.add(t2);
        carrier.add(t4);
        carrier.add(t1);
        carrier.add(t5);
        carrier.add(t7);
        carrier.add(t6);
        carrier.add(t10);
        carrier.add(t8);
        carrier.add(t9);

        SortUtil.setThreadSortGeo(new GeoLocation(0,0));

        SortUtil.sortThreads(SortUtil.SORT_USER_SCORE_LOWEST,
                            carrier);

        assertTrue("t10 at index 0", carrier.get(0) == t10);
        assertTrue("t9 at index 1", carrier.get(1) == t9);
        assertTrue("t8 at index 2", carrier.get(2) == t8);
        assertTrue("t7 at index 3", carrier.get(3) == t7);
        assertTrue("t6 at index 4", carrier.get(4) == t6);
        assertTrue("t5 at index 5", carrier.get(5) == t5);
        assertTrue("t4 at index 6", carrier.get(6) == t4);
        assertTrue("t3 at index 7", carrier.get(7) == t3);
        assertTrue("t2 at index 8", carrier.get(8) == t2);
        assertTrue("t1 at index 9", carrier.get(9) == t1);
    }

    /**
     * Tests the sorting of threads by some location.
     */
    public void testSortByLocation(){
        ArrayList<ThreadComment> carrier = new ArrayList<ThreadComment>();
        ThreadComment t1 = new ThreadComment();
        ThreadComment t2 = new ThreadComment();
        ThreadComment t3 = new ThreadComment();
        ThreadComment t4 = new ThreadComment();
        ThreadComment t5 = new ThreadComment();
        ThreadComment t6 = new ThreadComment();
        ThreadComment t7 = new ThreadComment();
        ThreadComment t8 = new ThreadComment();
        ThreadComment t9 = new ThreadComment();
        ThreadComment t10 = new ThreadComment();
        Comment c1 = new Comment();
        Comment c2 = new Comment();
        Comment c3 = new Comment();
        Comment c4 = new Comment();
        Comment c5 = new Comment();
        Comment c6 = new Comment();
        Comment c7 = new Comment();
        Comment c8 = new Comment();
        Comment c9 = new Comment();
        Comment c10 = new Comment();
        GeoLocation geoLocation1 = new GeoLocation(5,5);
        GeoLocation geoLocation2 = new GeoLocation(10,10);
        GeoLocation geoLocation3 = new GeoLocation(15,15);
        GeoLocation geoLocation4 = new GeoLocation(20,20);
        GeoLocation geoLocation5 = new GeoLocation(25,25);
        GeoLocation geoLocation6 = new GeoLocation(30,30);
        GeoLocation geoLocation7 = new GeoLocation(35,35);
        GeoLocation geoLocation8 = new GeoLocation(40,40);
        GeoLocation geoLocation9 = new GeoLocation(45,45);
        GeoLocation geoLocation10 = new GeoLocation(50,50);

        c1.setLocation(geoLocation1);
        c2.setLocation(geoLocation2);
        c3.setLocation(geoLocation3);
        c4.setLocation(geoLocation4);
        c5.setLocation(geoLocation5);
        c6.setLocation(geoLocation6);
        c7.setLocation(geoLocation7);
        c8.setLocation(geoLocation8);
        c9.setLocation(geoLocation9);
        c10.setLocation(geoLocation10);

        t1.setBodyComment(c1);
        t2.setBodyComment(c2);
        t3.setBodyComment(c3);
        t4.setBodyComment(c4);
        t5.setBodyComment(c5);
        t6.setBodyComment(c6);
        t7.setBodyComment(c7);
        t8.setBodyComment(c8);
        t9.setBodyComment(c9);
        t10.setBodyComment(c10);

        carrier.add(t3);
        carrier.add(t2);
        carrier.add(t4);
        carrier.add(t1);
        carrier.add(t5);
        carrier.add(t7);
        carrier.add(t6);
        carrier.add(t10);
        carrier.add(t8);
        carrier.add(t9);

        SortUtil.setThreadSortGeo(new GeoLocation(0,0));

        SortUtil.sortThreads(SortUtil.SORT_LOCATION,
                            carrier);

        assertTrue("t1 at index 0", carrier.get(0) == t1);
        assertTrue("t2 at index 1", carrier.get(1) == t2);
        assertTrue("t3 at index 2", carrier.get(2) == t3);
        assertTrue("t4 at index 3", carrier.get(3) == t4);
        assertTrue("t5 at index 4", carrier.get(4) == t5);
        assertTrue("t6 at index 5", carrier.get(5) == t6);
        assertTrue("t7 at index 6", carrier.get(6) == t7);
        assertTrue("t8 at index 7", carrier.get(7) == t8);
        assertTrue("t9 at index 8", carrier.get(8) == t9);
        assertTrue("t10 at index 9", carrier.get(9) == t10);
    }
}


text:
import argparse
import csv
import json
import logging
import os
import tempfile
import zipfile
import shutil
import uuid

logger = logging.getLogger('MindMeister')
logger.setLevel(logging.DEBUG)

ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(name)s: %(asctime)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)

logger.addHandler(ch)

class ExtractorError(Exception):
    """
    This represents a general extractor error.
    """
    pass

class MindMeisterExtractor:
    """
    This class will extract a .mind file and convert it to a flat .csv file.
    """

    def __init__(self, print_numbers, print_ids, print_leaf_nodes):
        self.input_file = None
        self.output_file = None
        self.csv_writer = None
        self.print_numbers = print_numbers
        self.print_ids = print_ids
        self.print_leaf_nodes = print_leaf_nodes

    @staticmethod
    def generate_id():
        return str(uuid.uuid4())

    def parse(self, parent_id, depth, numbers, node):
        """
        This is a recursive function that is used to walk the Mind Meister hierarchy and output the
        title with a number prefix.

        :param depth: The current depth in the hierarchy.
        :param numbers: The string of numbers for the current node e.g. '1.2.4.5'.
        :param node: The node element currently processed, this is a dictionary.
        """
        id = self.generate_id()
        has_children = False

        if 'children' in node and len(node['children']) > 0:
            has_children = True

        if 'title' in node:
            if self.csv_writer:
                row = list()

                if self.print_numbers:
                    row.append(numbers)
                if self.print_ids:
                    row.append(id)
                    row.append(parent_id)
                if self.print_leaf_nodes:
                    if not has_children:
                        row.append('L')
                    else:
                        row.append('')

                row.append(node['title'])

                self.csv_writer.writerow(row)
            else:
                row = ''

                if self.print_numbers:
                    row += '{0},'.format(numbers)
                if self.print_ids:
                    row += '{0},{1},'.format(id, parent_id)
                if self.print_leaf_nodes:
                    if not has_children:
                        row += 'L,'
                    else:
                        row += ','

                row += node['title']

                print row

        if has_children:
            count = 1

            for child_node in node['children']:
                self.parse(id, depth + 1, numbers + '.{0}'.format(count), child_node)
                count += 1

    def unzip(self, file_path):
        """
        This will unzip the given file into a temporary folder.

        :param file_path: The path of the file to extract.
        :returns: The path to the temporary folder that was extracted.
        """
        temp_dir = tempfile.gettempdir()
        dest_dir = os.path.join(temp_dir, 'mindmeister')

        with zipfile.ZipFile(file_path) as zip_file:
            for member in zip_file.infolist():
                # Path traversal defense copied from
                # http://hg.python.org/cpython/file/tip/Lib/http/server.py#l789
                words = member.filename.split('/')
                path = dest_dir
                for word in words[:-1]:
                    drive, word = os.path.splitdrive(word)
                    head, word = os.path.split(word)
                    if word in (os.curdir, os.pardir, ''): continue
                    path = os.path.join(path, word)
                zip_file.extract(member, path)

        return dest_dir

    def convert(self, input_file_path, output_file_path):
        """
        Opens and parses the input file and if the data is in the correct format it will
        produce a flat representation of the Mind Meister hierarchy.

        :param input_file_path: The file path of the .mind file to read from.
        :param output_file_path: The file path of the .csv file to write to, if this is an empty string
                                 it will print the result to stdout.
        :raises ExtractorError: An ExtractorError is raised with the data format is incorrect.
        """
        mind_meister_dir = self.unzip(input_file_path)

        try:
            self.input_file = open(os.path.join(mind_meister_dir, 'map.json'))
        except IOError, e:
            logger.error("File error: {0}".format(e))
            shutil.rmtree(mind_meister_dir)
            return

        if output_file_path != '':
            self.output_file = open(output_file_path, 'wb')
            self.csv_writer = csv.writer(
                self.output_file,
                delimiter=',',
                quotechar='"',
                quoting=csv.QUOTE_MINIMAL
            )

        try:
            data = json.load(self.input_file)
        except ValueError, e:
            raise ExtractorError("Could not load the MindMeister map file, is this a correct .mind file?")

        if 'root' in data:
            self.parse(self.generate_id(), 0, '1', data['root'])
        else:
            raise ExtractorError("Incorrect data format, is this a correct .mind file?")

        # Close file descriptors and remove temporary files
        self.input_file.close()
        if self.output_file:
            self.output_file.close()

        shutil.rmtree(mind_meister_dir)

if __name__ == '__main__':
    # Setup arguments
    args_parser = argparse.ArgumentParser(
        description='This extracts a Mind Meister .mind file and converts it to a flat .csv file.'
    )
    args_parser.add_argument(
        'file',
        help="The .mind file to convert.",
    )
    args_parser.add_argument(
        '--output',
        type=str,
        nargs=1,
        default=[''],
        help="The .csv file to save to.",
    )
    args_parser.add_argument(
        '--numbers',
        help="Print hierarchy numbers for each item e.g. 1.2.3 (False).",
        action='store_true'
    )
    args_parser.add_argument(
        '--ids',
        help="Generate parent child ids to retain hierarchy relationships (False).",
        action='store_true'
    )
    args_parser.add_argument(
        '--leaf',
        help="Mark leaf nodes with an 'L' (False).",
        action='store_true'
    )
    args = args_parser.parse_args()

    extractor = MindMeisterExtractor(
        print_numbers=args.numbers,
        print_ids=args.ids,
        print_leaf_nodes=args.leaf
    )

    try:
        extractor.convert(
            input_file_path=args.file,
            output_file_path=args.output[0]
        )

    except IOError, e:
        logger.error("File error: {0}".format(e))

    except ExtractorError, e:
        logger.error(e)


text:
Rigidbody::Rigidbody(Entity* entity) : Component(entity)
{
    // Rigidbodies update rotation by default
    mCanRotate = true;

    // Set entity pointer shortcut
    mEntity->rigidbody = this;
}

Rigidbody::~Rigidbody()
{
    GameWorld::getInstance()->getb2World()->DestroyBody(body);
}

void Rigidbody::createBody(type bodyType)
{
    // Get Graphics Position
    sf::Vector2f position = mEntity->getWorldPosition();

    // Create Box2D Body
    if (bodyType == dynamicBody)
    {
        bodyDef.type = b2_dynamicBody;
    }
    else if (bodyType == staticBody)
    {
        bodyDef.type = b2_staticBody;
    }

    bodyDef.position.Set(position.x * Game::p2m, position.y * Game::p2m);
    body = GameWorld::getInstance()->getb2World()->CreateBody(&bodyDef);

    // Store reference to entity in body
    body->SetUserData(mEntity);

}

void Rigidbody::canRotate(bool canRotate)
{
    mCanRotate = canRotate;
}

void Rigidbody::setBits(uint16 categoryBits, uint16 maskBits)
{
    mCategoryBits = categoryBits;
    mMaskBits = maskBits;
}

void Rigidbody::onFixedUpdate(sf::Time dt)
{
    // note parent doesn't necessarily have a body
    // therefore process of conversion requires this body's position to be in world coordinates

    // position in meters
    b2Vec2 mPosition = body->GetPosition();

    // pPosition holds the world pixel coordinates of this
    Vector2f pPhysicsPosition(mPosition.x * Game::m2p, mPosition.y * Game::m2p);

    SceneNode* parent = mEntity->getParent();
    if (parent != nullptr && pPhysicsPosition.x != 640)
    {
        //std::cout << "Phyics World in pixels: " << pPhysicsPosition.x << ", " << pPhysicsPosition.y << std::endl;
        pPhysicsPosition -= parent->getWorldPosition();
        //std::cout << "local: " << pPhysicsPosition.x << ", " << pPhysicsPosition.y << std::endl;
    }
    //std::cout << "physics: " << body->GetPosition().x << ", " << body->GetPosition().y << std::endl;

    // setPosition using pixel coordinates
    // since pPosition is local, must add parent's position
    mEntity->setPosition(pPhysicsPosition);

    // Update rotation if canRotate flag is set
    if (mCanRotate)
    {
        float angle = body->GetAngle();
        mEntity->setRotation((angle * 180.0f) / M_PI);
    }
}


text:
/**
 * @file        src/common/response/ListResponse.cpp
 * @author      Lukasz Wojciechowski <l.wojciechow@partner.samsung.com>
 * @version     1.0
 * @brief       This file implements policies list response class
 */

#include <response/ResponseTaker.h>

#include "ListResponse.h"

namespace Cynara {

void ListResponse::execute(ResponseTaker &taker, const RequestContext &context) const {
    taker.execute(context, *this);
}

} // namespace Cynara


text:
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "multiset.hpp"

TEST_SUITE_BEGIN("multiset");

TEST_CASE("binary_multiset")
{
  test_multiset<cereal::BinaryInputArchive, cereal::BinaryOutputArchive>();
}

TEST_CASE("portable_binary_multiset")
{
  test_multiset<cereal::PortableBinaryInputArchive, cereal::PortableBinaryOutputArchive>();
}

TEST_CASE("xml_multiset")
{
  test_multiset<cereal::XMLInputArchive, cereal::XMLOutputArchive>();
}

TEST_CASE("json_multiset")
{
  test_multiset<cereal::JSONInputArchive, cereal::JSONOutputArchive>();
}

TEST_SUITE_END();


text:
from __future__ import unicode_literals

import random
from datetime import datetime, date

try:
    import unittest2 as unittest
except ImportError:
    import unittest

from sphinxit.core.constants import RESERVED_KEYWORDS, ESCAPED_CHARS
from sphinxit.core.exceptions import SphinxQLSyntaxException
from sphinxit.core.helpers import (
    list_of_integers_only,
    int_from_digit,
    sparse_free_sequence,
    unix_timestamp
)
from sphinxit.core.convertors import (
    FilterCtx,
    MatchQueryCtx,
    AliasFieldCtx,
    LimitCtx,
    OrderCtx,
    FieldCtx,
    OptionsCtx,
    UpdateSetCtx,
)

class DebugConfig(object):
    DEBUG = True

class ProductionConfig(object):
    DEBUG = False

class TestListOfIntegersOnlyConverter(unittest.TestCase):

    def test_clean_sequence(self):
        sequence = [1, 2, 3, 4, 5]
        self.assertListEqual(list_of_integers_only(sequence), sequence)

    def test_digit_str_sequence(self):
        sequence = [1, '2', 3, 4, '5']
        self.assertListEqual(list_of_integers_only(sequence), [1, 2, 3, 4, 5])

    def test_str_sequence(self):
        sequence = [1, 'boom', 3, 4, '5']
        self.assertListEqual(list_of_integers_only(sequence), [1, 3, 4, 5])

    def test_str_sequence_strict(self):
        sequence = [1, 'boom', 3, 4, '5']
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: list_of_integers_only(sequence, is_strict=True),
        )

class TestIntFromDigit(unittest.TestCase):

    def test_int(self):
        self.assertEqual(int_from_digit(42), 42)

    def test_digit_str(self):
        self.assertEqual(int_from_digit('42'), 42)

    def test_str(self):
        self.assertIsNone(int_from_digit('boom'))

    def test_str_strict(self):
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: int_from_digit('boom', is_strict=True),
        )

class TestSparseFreeSequence(unittest.TestCase):

    def test_sparse(self):
        dirty_list = ['1', 2, None, '4', '  ', 6, {'key': 'value'}, [], ()]
        self.assertEqual(
            sparse_free_sequence(dirty_list),
            ['1', 2, '4', 6, {'key': 'value'}]
        )

FilterCtxStrict = lambda *args, **kwargs: FilterCtx(*args, **kwargs).with_config(DebugConfig)
FilterCtxSoft = lambda *args, **kwargs: FilterCtx(*args, **kwargs).with_config(ProductionConfig)

class TestFilterCtx(unittest.TestCase):

    def test_eq_non_strict(self):
        with FilterCtxSoft('age__eq', 25) as value:
            self.assertEqual(value, 'age=25')

        with FilterCtxSoft('age__eq', '25') as value:
            self.assertEqual(value, 'age=25')

        with FilterCtxSoft('age__eq', '25d') as value:
            self.assertIsNone(value)

    def test_eq_strict(self):
        with FilterCtxStrict('age__eq', 25) as value:
            self.assertEqual(value, 'age=25')

        with FilterCtxStrict('age__eq', '25') as value:
            self.assertEqual(value, 'age=25')

        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: FilterCtxStrict('age__eq', '25d').__enter__()
        )

    def test_neq_non_strict(self):
        with FilterCtxSoft('age__neq', 25) as value:
            self.assertEqual(value, 'age!=25')

        with FilterCtxSoft('age__neq', '25') as value:
            self.assertEqual(value, 'age!=25')

        with FilterCtxSoft('age__neq', '25d') as value:
            self.assertIsNone(value)

    def test_neq_strict(self):
        with FilterCtxStrict('age__neq', 25) as value:
            self.assertEqual(value, 'age!=25')

        with FilterCtxStrict('age__neq', '25') as value:
            self.assertEqual(value, 'age!=25')

        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: FilterCtxStrict('age__neq', '25d').__enter__()
        )

    def test_gt_non_strict(self):
        with FilterCtxSoft('age__gt', 25) as value:
            self.assertEqual(value, 'age>25')

        with FilterCtxSoft('age__gt', '25') as value:
            self.assertEqual(value, 'age>25')

        with FilterCtxSoft('age__gt', '25d') as value:
            self.assertIsNone(value)

    def test_gt_strict(self):
        with FilterCtxStrict('age__gt', 25) as value:
            self.assertEqual(value, 'age>25')

        with FilterCtxStrict('age__gt', '25') as value:
            self.assertEqual(value, 'age>25')

        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: FilterCtxStrict('age__gt', '25d').__enter__()
        )

    def test_gte_non_strict(self):
        with FilterCtxSoft('age__gte', 25) as value:
            self.assertEqual(value, 'age>=25')

        with FilterCtxSoft('age__gte', '25') as value:
            self.assertEqual(value, 'age>=25')

        with FilterCtxSoft('age__gte', '25d') as value:
            self.assertIsNone(value)

    def test_gte_strict(self):
        with FilterCtxStrict('age__gte', 25) as value:
            self.assertEqual(value, 'age>=25')

        with FilterCtxStrict('age__gte', '25') as value:
            self.assertEqual(value, 'age>=25')

        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: FilterCtxStrict('age__gte', '25d').__enter__()
        )

    def test_lt_non_strict(self):
        with FilterCtxSoft('age__lt', 25) as value:
            self.assertEqual(value, 'age<25')

        with FilterCtxSoft('age__lt', '25') as value:
            self.assertEqual(value, 'age<25')

        with FilterCtxSoft('age__lt', '25d') as value:
            self.assertEqual(value, None)

    def test_lt_strict(self):
        with FilterCtxStrict('age__lt', 25) as value:
            self.assertEqual(value, 'age<25')

        with FilterCtxStrict('age__lt', '25') as value:
            self.assertEqual(value, 'age<25')

        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: FilterCtxStrict('age__lt', '25d').__enter__()
        )

    def test_lte_non_strict(self):
        with FilterCtxSoft('age__lte', 25) as value:
            self.assertEqual(value, 'age<=25')

        with FilterCtxSoft('age__lte', '25') as value:
            self.assertEqual(value, 'age<=25')

        with FilterCtxSoft('age__lte', '25d') as value:
            self.assertEqual(value, None)

    def test_lte_strict(self):
        with FilterCtxStrict('age__lte', 25) as value:
            self.assertEqual(value, 'age<=25')

        with FilterCtxStrict('age__lte', '25') as value:
            self.assertEqual(value, 'age<=25')

        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: FilterCtxStrict('age__lte', '25d').__enter__()
        )

    def test_in_non_strict(self):
        with FilterCtxSoft('age__in', (1, 2, 3)) as value:
            self.assertEqual(value, 'age IN (1,2,3)')

        with FilterCtxSoft('age__in', (1, '2', 3)) as value:
            self.assertEqual(value, 'age IN (1,2,3)')

        with FilterCtxSoft('age__in', (1, '2', 'string', 3, '42d')) as value:
            self.assertEqual(value, 'age IN (1,2,3)')

        with FilterCtxSoft('age__in', []) as value:
            self.assertIsNone(value)

        with FilterCtxSoft('age__in', None) as value:
            self.assertIsNone(value)

    def test_in_strict(self):
        with FilterCtxStrict('age__in', (1, 2, 3)) as value:
            self.assertEqual(value, 'age IN (1,2,3)')

        with FilterCtxStrict('age__in', (1, '2', 3)) as value:
            self.assertEqual(value, 'age IN (1,2,3)')

        with FilterCtxStrict('age__in', []) as value:
            self.assertIsNone(value)

        with FilterCtxStrict('age__in', None) as value:
            self.assertIsNone(value)

        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: FilterCtxStrict('age__in', [1, 2, 3, '42d']).__enter__()
        )

    def test_between_non_strict(self):
        with FilterCtxSoft('age__between', (1, 25)) as value:
            self.assertEqual(value, 'age BETWEEN 1 AND 25')

        with FilterCtxSoft('age__between', (1, 25, 35)) as value:
            self.assertIsNone(value)

        with FilterCtxSoft('age__between', (1, '25')) as value:
            self.assertEqual(value, 'age BETWEEN 1 AND 25')

        with FilterCtxSoft('age__between', (1, 'string')) as value:
            self.assertIsNone(value)

        with FilterCtxSoft('age__between', ()) as value:
            self.assertIsNone(value)

    def test_between_strict(self):
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: FilterCtxStrict('age__between', (1, 25, 35)).__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: FilterCtxStrict('age__between', (1, 'string')).__enter__()
        )
        with FilterCtxStrict('age__between', (1, 25)) as value:
            self.assertEqual(value, 'age BETWEEN 1 AND 25')

        with FilterCtxStrict('age__between', ()) as value:
            self.assertIsNone(value)

    def test_invalid_condition(self):
        with FilterCtxSoft('age__range', (1, 25)) as value:
            self.assertIsNone(value)

    def test_invalid_condition_strict(self):
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: FilterCtxStrict('age__range', (1, 25)).__enter__()
        )

    def test_datetime_condition(self):
        today_stamp = unix_timestamp(date.today())
        with FilterCtxStrict('age__eq', today_stamp) as value:
            self.assertEqual(value, 'age=%s' % today_stamp)

        now_stamp = unix_timestamp(datetime.now())
        with FilterCtxStrict('age__eq', now_stamp) as value:
            self.assertEqual(value, 'age=%s' % now_stamp)

    def test_float_condition(self):
        with FilterCtxStrict('age__eq', 5.5) as value:
            self.assertEqual(value, 'age=5.5')

MatchQueryCtxSoft = lambda *args, **kwargs: MatchQueryCtx(*args, **kwargs).with_config(ProductionConfig)
MatchQueryCtxStrict = lambda *args, **kwargs: MatchQueryCtx(*args, **kwargs).with_config(DebugConfig)

class TestMatchQueryCtx(unittest.TestCase):

    def test_single_slash(self):
        symbol = random.choice(ESCAPED_CHARS.single_escape)
        with MatchQueryCtxSoft(symbol) as value:
            self.assertEqual(value, r"\{0}".format(symbol))

    def test_double_slash(self):
        symbol = random.choice(ESCAPED_CHARS.double_escape)
        with MatchQueryCtxSoft(symbol) as value:
            self.assertEqual(value, r"\\{0}".format(symbol))

    def test_single_slash_raw(self):
        symbol = random.choice(ESCAPED_CHARS.single_escape)
        with MatchQueryCtxSoft(symbol, raw=True) as value:
            self.assertEqual(value, symbol)

    def test_raw_double_slash(self):
        symbol = random.choice(ESCAPED_CHARS.double_escape)
        with MatchQueryCtxSoft(symbol, raw=True) as value:
            self.assertEqual(value, symbol)

    def test_simple_valid_string(self):
        with MatchQueryCtxSoft('Find me some money') as value:
            self.assertEqual(value, "Find me some money")

    def test_symbol_escape(self):
        with MatchQueryCtxSoft('@full_name ^Roman') as value:
            self.assertEqual(value, r'\\@full_name \\^Roman')

    def test_quotes_escape(self):
        with MatchQueryCtxSoft('"name') as value:
            self.assertEqual(value, r'\\"name')

    def test_quote_escape(self):
        with MatchQueryCtxSoft("l'amour") as value:
            self.assertEqual(value, r"l\'amour")

    def test_raw_query(self):
        mail_query = '@email "semirook@gmail.com"'
        with MatchQueryCtxSoft(mail_query, raw=True) as value:
            self.assertEqual(value, mail_query)

    def test_invalid_query(self):
        with MatchQueryCtxSoft(42) as value:
            self.assertIsNone(value)

        with MatchQueryCtxSoft('') as value:
            self.assertIsNone(value)

        with MatchQueryCtxSoft('   ') as value:
            self.assertIsNone(value)

    def test_invalid_query_strict(self):
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: MatchQueryCtxStrict(42).__enter__()
        )
        with MatchQueryCtxStrict('') as value:
            self.assertIsNone(value)

        with MatchQueryCtxStrict('   ') as value:
            self.assertIsNone(value)

AliasFieldCtxSoft = lambda x, y: AliasFieldCtx(x, y).with_config(ProductionConfig)
AliasFieldCtxStrict = lambda x, y: AliasFieldCtx(x, y).with_config(DebugConfig)

class TestAliasFieldCtx(unittest.TestCase):

    def test_valid_attrs(self):
        with AliasFieldCtxSoft('name', 'another_name') as value:
            self.assertEqual(value, 'name AS another_name')

    def test_valid_attrs_strict(self):
        with AliasFieldCtxStrict('name', 'another_name') as value:
            self.assertEqual(value, 'name AS another_name')

    def test_invalid_attrs(self):
        with AliasFieldCtxSoft('name', 42) as value:
            self.assertIsNone(value)

        with AliasFieldCtxSoft('name', random.choice(RESERVED_KEYWORDS)) as value:
            self.assertIsNone(value)

        with AliasFieldCtxSoft(random.choice(RESERVED_KEYWORDS), 'alias') as value:
            self.assertIsNone(value)

        with AliasFieldCtxSoft('', '') as value:
            self.assertIsNone(value)

        with AliasFieldCtxSoft('   ', '   ') as value:
            self.assertIsNone(value)

    def test_invalid_attrs_strict(self):
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: AliasFieldCtxStrict('name', 42).__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: AliasFieldCtxStrict('name', random.choice(RESERVED_KEYWORDS)).__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: AliasFieldCtxStrict(random.choice(RESERVED_KEYWORDS), 'alias').__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: AliasFieldCtxStrict('', '').__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: AliasFieldCtxStrict('   ', '   ').__enter__()
        )

FieldCtxSoft = lambda field: FieldCtx(field).with_config(ProductionConfig)
FieldCtxStrict = lambda field: FieldCtx(field).with_config(DebugConfig)

class TestFieldCtx(unittest.TestCase):

    def test_valid_attrs(self):
        with FieldCtxSoft('name') as lex:
            self.assertEqual(lex, 'name')

    def test_valid_attrs_strict(self):
        with FieldCtxStrict('name') as lex:
            self.assertEqual(lex, 'name')

    def test_invalid_attrs(self):
        with FieldCtxSoft('') as lex:
            self.assertIsNone(lex)

        with FieldCtxSoft('   ') as lex:
            self.assertIsNone(lex)

        with FieldCtxSoft(random.choice(RESERVED_KEYWORDS)) as lex:
            self.assertIsNone(lex)

    def test_invalid_attrs_strict(self):
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: FieldCtxStrict('').__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: FieldCtxStrict('   ').__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: FieldCtxStrict(random.choice(RESERVED_KEYWORDS)).__enter__()
        )

LimitCtxSoft = lambda x, y: LimitCtx(x, y).with_config(ProductionConfig)
LimitCtxStrict = lambda x, y: LimitCtx(x, y).with_config(DebugConfig)

class TestLimitCtx(unittest.TestCase):

    def test_valid_attrs(self):
        with LimitCtxSoft(0, 100) as lex:
            self.assertEqual([0, 100], lex)

        with LimitCtxSoft(0, '100') as lex:
            self.assertEqual([0, 100], lex)

    def test_invalid_attrs(self):
        with LimitCtxSoft(0, 0) as lex:
            self.assertIsNone(lex)

        with LimitCtxSoft(-2, 100) as lex:
            self.assertIsNone(lex)

        with LimitCtxSoft(0, 'boom') as lex:
            self.assertIsNone(lex)

    def test_invalid_attrs_strict(self):
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: LimitCtxStrict(0, 0).__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: LimitCtxStrict(-2, 100).__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: LimitCtxStrict(0, 'boom').__enter__()
        )

OrderCtxSoft = lambda x, y: OrderCtx(x, y).with_config(ProductionConfig)
OrderCtxStrict = lambda x, y: OrderCtx(x, y).with_config(DebugConfig)

class TestOrderCtx(unittest.TestCase):

    def test_valid_attrs(self):
        with OrderCtxSoft('name', 'ASC') as lex:
            self.assertEqual(lex, 'name ASC')

        with OrderCtxSoft('name', 'DESC') as lex:
            self.assertEqual(lex, 'name DESC')

        with OrderCtxSoft('name', 'asc') as lex:
            self.assertEqual(lex, 'name ASC')

        with OrderCtxSoft('name', 'desc') as lex:
            self.assertEqual(lex, 'name DESC')

    def test_invalid_attrs(self):
        with OrderCtxSoft('', 'ASC') as lex:
            self.assertIsNone(lex)

        with OrderCtxSoft('   ', 'ASC') as lex:
            self.assertIsNone(lex)

        with OrderCtxSoft('name', 'DEC') as lex:
            self.assertIsNone(lex)

        with OrderCtxSoft(42, 'ASC') as lex:
            self.assertIsNone(lex)

        with OrderCtxSoft('asc', 'name') as lex:
            self.assertIsNone(lex)

    def test_invalid_attrs_strict(self):
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OrderCtxStrict('', 'ASC').__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OrderCtxStrict('   ', 'ASC').__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OrderCtxStrict('name', 'DEC').__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OrderCtxStrict(42, 'ASC').__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OrderCtxStrict('asc', '').__enter__()
        )

OptionsCtxSoft = lambda x, y: OptionsCtx(x, y).with_config(ProductionConfig)
OptionsCtxStrict = lambda x, y: OptionsCtx(x, y).with_config(DebugConfig)

class TestOptionsCtx(unittest.TestCase):

    def test_get_ranker_valid_attrs(self):
        with OptionsCtxSoft('ranker', 'proximity_bm25') as lex:
            self.assertEqual(lex, 'ranker=proximity_bm25')

        with OptionsCtxSoft('ranker', 'bm25') as lex:
            self.assertEqual(lex, 'ranker=bm25')

        with OptionsCtxSoft('ranker', 'none') as lex:
            self.assertEqual(lex, 'ranker=none')

        with OptionsCtxSoft('ranker', 'wordcount') as lex:
            self.assertEqual(lex, 'ranker=wordcount')

        with OptionsCtxSoft('ranker', 'proximity') as lex:
            self.assertEqual(lex, 'ranker=proximity')

        with OptionsCtxSoft('ranker', 'matchany') as lex:
            self.assertEqual(lex, 'ranker=matchany')

        with OptionsCtxSoft('ranker', 'fieldmask') as lex:
            self.assertEqual(lex, 'ranker=fieldmask')

    def test_get_ranker_invalid_attrs(self):
        with OptionsCtxSoft('ranker', 'yandex') as lex:
            self.assertIsNone(lex)

    def test_get_ranker_invalid_attrs_strict(self):
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('ranker', 'yandex').__enter__()
        )

    def test_get_max_matches_valid_attrs(self):
        with OptionsCtxSoft('max_matches', 3000) as lex:
            self.assertEqual(lex, 'max_matches=3000')

        with OptionsCtxSoft('max_matches', '3000') as lex:
            self.assertEqual(lex, 'max_matches=3000')

    def test_get_max_matches_invalid_attrs(self):
        with OptionsCtxSoft('max_matches', 0) as lex:
            self.assertIsNone(lex)

        with OptionsCtxSoft('max_matches', '') as lex:
            self.assertIsNone(lex)

        with OptionsCtxSoft('max_matches', 'many') as lex:
            self.assertIsNone(lex)

    def test_get_max_matches_invalid_attrs_strict(self):
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('max_matches', 0).__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('max_matches', '').__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('max_matches', 'many').__enter__()
        )

    def test_get_cutoff_valid_attrs(self):
        with OptionsCtxSoft('cutoff', 7) as lex:
            self.assertEqual(lex, 'cutoff=7')

        with OptionsCtxSoft('cutoff', '7') as lex:
            self.assertEqual(lex, 'cutoff=7')

    def test_get_cutoff_invalid_attrs(self):
        with OptionsCtxSoft('cutoff', 0) as lex:
            self.assertIsNone(lex)

        with OptionsCtxSoft('cutoff', '') as lex:
            self.assertIsNone(lex)

        with OptionsCtxSoft('cutoff', 'many') as lex:
            self.assertIsNone(lex)

    def test_get_cutoff_invalid_attrs_strict(self):
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('cutoff', 0).__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('cutoff', '').__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('cutoff', 'many').__enter__()
        )

    def test_max_query_time_valid_attrs(self):
        with OptionsCtxSoft('max_query_time', 100) as lex:
            self.assertEqual(lex, 'max_query_time=100')

        with OptionsCtxSoft('max_query_time', '100') as lex:
            self.assertEqual(lex, 'max_query_time=100')

    def test_max_query_time_invalid_attrs(self):
        with OptionsCtxSoft('max_query_time', '') as lex:
            self.assertIsNone(lex)

        with OptionsCtxSoft('max_query_time', 0) as lex:
            self.assertIsNone(lex)

    def test_max_query_time_invalid_attrs_strict(self):
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('max_query_time', '').__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('max_query_time', 0).__enter__()
        )

    def test_retry_count_valid_attrs(self):
        with OptionsCtxSoft('retry_count', 3) as lex:
            self.assertEqual(lex, 'retry_count=3')

        with OptionsCtxSoft('retry_count', '3') as lex:
            self.assertEqual(lex, 'retry_count=3')

    def test_retry_count_invalid_attrs(self):
        with OptionsCtxSoft('retry_count', '') as lex:
            self.assertIsNone(lex)

        with OptionsCtxSoft('retry_count', 0) as lex:
            self.assertIsNone(lex)

    def test_retry_count_invalid_attrs_strict(self):
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('retry_count', '').__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('retry_count', 0).__enter__()
        )

    def test_retry_delay_valid_attrs(self):
        with OptionsCtxSoft('retry_delay', 3) as lex:
            self.assertEqual(lex, 'retry_delay=3')

        with OptionsCtxSoft('retry_delay', '3') as lex:
            self.assertEqual(lex, 'retry_delay=3')

    def test_retry_delay_invalid_attrs(self):
        with OptionsCtxSoft('retry_delay', '') as lex:
            self.assertIsNone(lex)

        with OptionsCtxSoft('retry_delay', 0) as lex:
            self.assertIsNone(lex)

    def test_retry_delay_invalid_attrs_strict(self):
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('retry_delay', '').__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('retry_delay', 0).__enter__()
        )

    def test_field_weights_valid_attrs(self):
        with OptionsCtxSoft('field_weights', {'title': 100, 'body': 50}) as lex:
            self.assertTrue(lex in [
                'field_weights=(body=50, title=100)',
                'field_weights=(title=100, body=50)'
            ])
        with OptionsCtxSoft('field_weights', {'title': '100', 'body': '50'}) as lex:
            self.assertTrue(lex in [
                'field_weights=(body=50, title=100)',
                'field_weights=(title=100, body=50)'
            ])

    def test_field_weights_invalid_attrs(self):
        with OptionsCtxSoft('field_weights', ('title', 0)) as lex:
            self.assertIsNone(lex)

        with OptionsCtxSoft('field_weights', 100) as lex:
            self.assertIsNone(lex)

        with OptionsCtxSoft('field_weights', {'title': 10, 'body': 0}) as lex:
            self.assertEqual(lex, 'field_weights=(title=10)')

    def test_field_weights_invalid_attrs_strict(self):
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('field_weights', ('title', 0)).__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('field_weights', 100).__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('field_weights', {'title': 10, 'body': 0}).__enter__()
        )

    def test_index_weights_valid_attrs(self):
        with OptionsCtxSoft('index_weights', {'company': 1, 'company_delta': 2}) as lex:
            self.assertTrue(lex in [
                'index_weights=(company=1, company_delta=2)',
                'index_weights=(company_delta=2, company=1)'
            ])
        with OptionsCtxSoft('index_weights', {'company': '1', 'company_delta': '2'}) as lex:
            self.assertTrue(lex in [
                'index_weights=(company=1, company_delta=2)',
                'index_weights=(company_delta=2, company=1)'
            ])

    def test_index_weights_invalid_attrs(self):
        with OptionsCtxSoft('index_weights', ('company', 0)) as lex:
            self.assertIsNone(lex)

        with OptionsCtxSoft('index_weights', 100) as lex:
            self.assertIsNone(lex)

        with OptionsCtxSoft('index_weights', {'company': 1, 'company_delta': 0}) as lex:
            self.assertEqual(lex, 'index_weights=(company=1)')

    def test_index_weights_invalid_attrs_strict(self):
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('index_weights', ('company', 0)).__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('index_weights', 100).__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('index_weights', {'company': 1, 'company_delta': 0}).__enter__()
        )

    def test_reverse_scan_valid_attrs(self):
        with OptionsCtxSoft('reverse_scan', True) as lex:
            self.assertEqual(lex, 'reverse_scan=1')

        with OptionsCtxSoft('reverse_scan', False) as lex:
            self.assertEqual(lex, 'reverse_scan=0')

    def test_reverse_scan_invalid_attrs(self):
        with OptionsCtxSoft('reverse_scan', 1) as lex:
            self.assertIsNone(lex)

        with OptionsCtxSoft('reverse_scan', 0) as lex:
            self.assertIsNone(lex)

        with OptionsCtxSoft('reverse_scan', '1') as lex:
            self.assertIsNone(lex)

    def test_reverse_scan_invalid_attrs_strict(self):
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('reverse_scan', 1).__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('reverse_scan', 0).__enter__()
        )
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('reverse_scan', '0').__enter__()
        )

    def test_comment_valid_attrs(self):
        with OptionsCtxSoft('comment', 'Comment text') as lex:
            self.assertEqual(lex, 'comment=Comment text')

    def test_comment_invalid_attrs(self):
        with OptionsCtxSoft('comment', 42) as lex:
            self.assertIsNone(lex)

    def test_comment_invalid_attrs_strict(self):
        self.assertRaises(
            SphinxQLSyntaxException,
            lambda: OptionsCtxStrict('comment', 42).__enter__()
        )

UpdateSetCtxSoft = lambda x, y: UpdateSetCtx(x, y).with_config(ProductionConfig)
UpdateSetCtxStrict = lambda x, y: UpdateSetCtx(x, y).with_config(DebugConfig)

class TestUpdateSetCtx(unittest.TestCase):

    def test_valid_attrs(self):
        with UpdateSetCtxSoft('intattr', 1000) as lex:
            self.assertEqual(lex, 'intattr=1000')

        with UpdateSetCtxSoft('intattr', '1000') as lex:
            self.assertEqual(lex, 'intattr=1000')

        with UpdateSetCtxSoft('fattr', 100.002) as lex:
            self.assertEqual(lex, 'fattr=100.002')

        with UpdateSetCtxSoft('mvattr', [1, 2, 3]) as lex:
            self.assertEqual(lex, 'mvattr=(1,2,3)')

        with UpdateSetCtxSoft('mvattr', [1, '2', 3]) as lex:
            self.assertEqual(lex, 'mvattr=(1,2,3)')

        with UpdateSetCtxSoft('mvattr', (1, '2', 3)) as lex:
            self.assertEqual(lex, 'mvattr=(1,2,3)')

        with UpdateSetCtxSoft('attr', '') as lex:
            self.assertEqual(lex, 'attr=()')

        with UpdateSetCtxSoft('attr', []) as lex:
            self.assertEqual(lex, 'attr=()')

        with UpdateSetCtxSoft('attr', ()) as lex:
            self.assertEqual(lex, 'attr=()')

        with UpdateSetCtxSoft('attr', None) as lex:
            self.assertEqual(lex, 'attr=()')

    def test_invalid_attrs(self):
        with UpdateSetCtxSoft('', 1000) as lex:
            self.assertIsNone(lex)

        with UpdateSetCtxSoft('attr', 'string_is_not_supported') as lex:
            self.assertIsNone(lex)

        with UpdateSetCtxSoft('attr', ['1', 2, None, 'string']) as lex:
            self.assertEqual(lex, 'attr=(1,2)')