text:
/*
 *
 * TINKER Source Code
 *
 *
 *  [2009] - [2013] Samuel Steven Truscott
 *  All Rights Reserved.
 */
#include "memory/mem_section.h"

#include "kernel_assert.h"
#include "utils/util_memset.h"
#include "utils/util_strcpy.h"

mem_section_t * mem_sec_create(
		mem_pool_info_t * const pool,
		const mem_t real_addr,
		const mem_t virt_addr,
		const mem_t size,
		const mmu_memory_t mem_type,
		const mmu_privilege_t mem_priv,
		const mmu_access_t mem_access,
		const char * const name)
{
	mem_section_t * const ms = mem_alloc(pool, sizeof(mem_section_t));
	mem_sec_initialise(ms, pool, real_addr, virt_addr, size, mem_type, mem_priv, mem_access, name);
	return ms;
}

void mem_sec_initialise(
		mem_section_t * const ms,
		mem_pool_info_t * const pool,
		const mem_t real_addr,
		const mem_t virt_addr,
		const mem_t size,
		const mmu_memory_t mem_type,
		const mmu_privilege_t mem_priv,
		const mmu_access_t mem_access,
		const char * const name)
{
	if (ms)
	{
		util_memset(ms, 0, sizeof(mem_section_t));
		ms->real_address = real_addr;
		ms->virt_address = virt_addr;
		ms->size = size;
		ms->memory_type = mem_type;
		ms->privilege = mem_priv;
		ms->access_rights = mem_access;
		ms->pool = pool;
		util_strcpy(ms->name, name, 32);
	}
}

void mem_sec_delete(const mem_section_t * const section)
{
	kernel_assert("mem_sec_delete - check that the section is valid", section != NULL);
	mem_free(section->pool, section);
}

mem_t mem_sec_get_real_addr(const mem_section_t * const ms)
{
	return ms->real_address;
}

mem_t mem_sec_get_virt_addr(const mem_section_t * const ms)
{
	return ms->virt_address;
}

mem_t mem_sec_get_size(const mem_section_t * const ms)
{
	return ms->size;
}

mmu_memory_t mem_sec_get_mem_type(const mem_section_t * const ms)
{
	return ms->memory_type;
}

mmu_privilege_t mem_sec_get_priv(const mem_section_t * const ms)
{
	return ms->privilege;
}

mmu_access_t mem_sec_get_access(const mem_section_t * const ms)
{
	return ms->access_rights;
}

mem_section_t * mem_sec_get_next(const mem_section_t * const ms)
{
	return ms->next;
}

void mem_sec_set_next(mem_section_t * const ms, const mem_section_t * const next)
{
	if (ms)
	{
		ms->next = (mem_section_t*)next;
	}
}

const char * mem_sec_get_name(const mem_section_t * const ms)
{
	return ms->name;
}


text:
[![NPM Version](https://img.shields.io/npm/v/igdb-api-node.svg)](https://www.npmjs.com/package/igdb-api-node)
[![Downloads](https://img.shields.io/npm/dm/igdb-api-node.svg)](https://www.npmjs.com/package/igdb-api-node)

# igdb-api-node

A Node.js wrapper for the IGDB.com Free Video Game Database API.

!!! Updated with Twitch Authentication.

## About IGDB
One of the principles behind IGDB.com is accessibility of data. We wish to share the data with anyone who wants to build cool videogame oriented websites, apps and services. This means that the information you contribute to IGDB.com can be used by other projects as well.

Thus, you are not only contributing to the value of this site but to thousands of other projects as well. We are looking forward to see what exciting game related projects you come up with. Happy coding!

More info here:
* [About the API](https://www.igdb.com/api)
* [API Documentation](https://api-docs.igdb.com)

## Installation and Setup

### Via [npm](https://www.npmjs.com/package/igdb-api-node):
```bash
$ npm install igdb-api-node
```

### In your code:

#### ES5:
```javascript
const igdb = require('igdb-api-node').default;
```

#### ES6 or later:
```javascript
import igdb from 'igdb-api-node';
```

#### Using your API key

* Pass API key directly:
```javascript
const client = igdb('YOUR_TWITCH_CLIENT_ID', 'YOUR_TWITCH_APP_ACCESS_TOKEN');
```

* OR set a process environment variable:
```bash
$ TWITCH_CLIENT_ID='YOUR_TWITCH_CLIENT_ID' TWITCH_APP_ACCESS_TOKEN='YOUR_TWITCH_APP_ACCESS_TOKEN' node yourCode.js
```

## Usage

This library wraps node-apicalypse and further examples can be seen here: https://github.com/igdb/node-apicalypse

```js
// Example using all methods.
const response = await igdb()
    .fields(['name', 'movies', 'age']) // fetches only the name, movies, and age fields
    .fields('name,movies,age') // same as above

    .limit(50) // limit to 50 results
    .offset(10) // offset results by 10

    .sort('name') // default sort direction is 'asc' (ascending)
    .sort('name', 'desc') // sorts by name, descending
    .search('mario') // search for a specific name (search implementations can vary)

    .where(`first_release_date > ${new Date().getTime() / 1000}`) // filter the results

    .request('/games'); // execute the query and return a response object

console.log(response.data);
```

### client.tagNumber(category, id)

`igdb-api-node` provides handy method for generating [tag numbers](https://api-docs.igdb.com/#tag-numbers) when doing advanced filtering.

__Arguments__

* `category` - An integer representing the tag category (game, genre, theme)
* `id` - The ID of the category entity

__Example__
```javascript
import igdb from 'igdb-api-node';

const client = igdb('YOUR_TWITCH_CLIENT_ID', 'YOUR_TWITCH_APP_ACCESS_TOKEN'),
    category = 1, // Genre
    id = 5; // Shooter

client.tagNumber(1, 5); // 268435461
```

More tag number options and information are available in the [IGDB API documentation](https://api-docs.igdb.com/#tag-numbers).

redpajama_set_name: RedPajamaGithub


text:
struct TangentFrameStruct
{
    float3 tangent, bitangent, normal;
    float handiness;
};

TangentFrameStruct BuildTangentFrame(float3 tangent, float3 bitangent, float3 normal, float handiness)
{
    TangentFrameStruct result;
    result.tangent = tangent;
    result.bitangent = bitangent;
    result.normal = normal;
    result.handiness = handiness;
    return result;
}

float3 SampleNormalMap(Texture2D normalMap, SamplerState samplerObject, bool dxtFormatNormalMap, float2 texCoord)
{
	if (dxtFormatNormalMap) {
		return normalMap.Sample(samplerObject, texCoord).xyz * 2.f - 1.0.xxx;
    } else {
		float2 result = normalMap.Sample(samplerObject, texCoord).xy * 2.f - 1.0.xx;

            // The following seems to give the best results on the "nyra" model currently...
            // It seems that maybe that model is using a wierd coordinate scheme in the normal map?
        float2 coordTwiddle = float2(result.x, -result.y);
		return float3(coordTwiddle, sqrt(saturate(1.f + dot(result.xy, -result.xy))));
        // return normalize(float3(coordTwiddle, 1.f - saturate(dot(result.xy, result.xy))));
    }
}

float3 NormalMapAlgorithm(  Texture2D normalMap, SamplerState samplerObject, bool dxtFormatNormalMap,
                            float2 texCoord, TangentFrameStruct tangentFrame)
{
    float3x3 normalsTextureToWorld = float3x3(tangentFrame.tangent.xyz, tangentFrame.bitangent, tangentFrame.normal);
    float3 normalTextureSample = SampleNormalMap(normalMap, samplerObject, dxtFormatNormalMap, texCoord);
		// Note -- matrix multiply opposite from normal
        //          (so we can initialise normalsTextureToWorld easily)
	return mul(normalTextureSample, normalsTextureToWorld);
}

void AlphaTestAlgorithm(Texture2D textureObject, SamplerState samplerObject,
                        float2 texCoord, float alphaThreshold)
{
	if (textureObject.Sample(samplerObject, texCoord).a < alphaThreshold) {
		clip(-1);
	}
}

float3x3 AutoCotangentFrame(float3 inputNormal, float3 negativeViewVector, float2 texCoord)
{
		// get edge vectors of the pixel triangle
	float3 dp1	= ddx(negativeViewVector);
	float3 dp2	= ddy(negativeViewVector);
	float2 duv1	= ddx(texCoord);
	float2 duv2	= ddy(texCoord);

		// solve the linear system
	float3 dp2perp = cross(dp2, inputNormal);
	float3 dp1perp = cross(inputNormal, dp1);
	float3 T = dp2perp * duv1.x + dp1perp * duv2.x;
	float3 B = dp2perp * duv1.y + dp1perp * duv2.y;

		// construct a scale-invariant frame
	float invmax = rsqrt( max( dot(T,T), dot(B,B) ) );
	return float3x3(T * invmax, B * invmax, inputNormal);
}

#endif


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    {% block title %}
    <title>CQF Project</title>
    {% endblock title %}
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    {% block styles %}

        <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"
              rel="stylesheet">
        <link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/css/datepicker3.min.css"
              rel="stylesheet">

    {% endblock styles %}

{% from "_formhelpers.html" import render_field, render_checkbox %}

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>
      CQF Project

BCD

HJM

    {% block content %}

    {% endblock content %}

{% block scripts %}

{% endblock scripts %}


text:
package org.joinfaces.autoconfigure.rewrite;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.ocpsoft.rewrite.servlet.config.HttpConfigurationProvider;

import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;

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

public class RewriteAutoConfigurationTest {

	private WebApplicationContextRunner webApplicationContextRunner;

	@BeforeEach
	public void setUp() {
		this.webApplicationContextRunner = new WebApplicationContextRunner()
				.withConfiguration(AutoConfigurations.of(RewriteAutoConfiguration.class, FooConfiguration.class));
	}

	@Test
	public void testConfigurationProvider() {
		this.webApplicationContextRunner
				.run(context -> {
					Foo1ConfigurationProvider fooConfigurationProvider = (Foo1ConfigurationProvider) context.getBean("foo1ConfigurationProvider");

					assertThat(fooConfigurationProvider)
						.isNotNull();

					SpringBootBeanNameResolver beanNameResolver = new SpringBootBeanNameResolver(context);
					assertThat(beanNameResolver.getBeanName(HttpConfigurationProvider.class))
						.isNull();
					assertThat(beanNameResolver.getBeanName(Foo1ConfigurationProvider.class))
						.isEqualTo("foo1ConfigurationProvider");
					assertThat(beanNameResolver.getBeanName(Foo2ConfigurationProvider.class))
						.isEqualTo("foo2ConfigurationProvider");
					assertThat(beanNameResolver.getBeanName(Foo3ConfigurationProvider.class))
						.isNull();

					SpringBootServiceLocator serviceLocator = new SpringBootServiceLocator();
					assertThat(serviceLocator.locate(HttpConfigurationProvider.class))
						.hasSize(3);
					assertThat(serviceLocator.locate(Foo1ConfigurationProvider.class))
						.hasSize(1);
					assertThat(serviceLocator.locate(Foo2ConfigurationProvider.class))
						.hasSize(1);
					assertThat(serviceLocator.locate(Foo3ConfigurationProvider.class))
						.isEmpty();
				});
	}
}


text:
template< class TObj > uint32_t getType();
template< class TObj > const char* getTypeName();
uint32_t getTypeByName(const char* name);

// ----------------------------------------------
struct THandle {
  static const unsigned n_index_bits = 12;    // 4096 instances
  static const unsigned n_type_bits = 7;
  static const unsigned n_counter_bits = 32 - n_index_bits - n_type_bits;
  static const unsigned max_types = 1 << n_type_bits;

  // ----------------------------------
  // Ctors
  THandle() : index(0), age(0), type(0) {}
  THandle(uint32_t aindex, uint32_t aage, uint32_t atype) : index(aindex), age(aage), type(atype) {}

  // ----------------------------------
  // Create a handle given the address on an obj
  template< class TObj >
  THandle(const TObj *obj) {
    *this = getObjsManager< std::remove_const<TObj>::type >()->getHandleByObj(obj);
  }

  // Creates a new instance of object TObj
  template< class TObj, class... Args >
  static THandle create(Args&&... args) {
    return getObjsManager<TObj>()->createObj(args...);
  }

  bool destroy() const;

  THandle clone() const;

  // ----------------------------------
  // Conversion
  uint32_t asUnsigned() const { return *(uint32_t*)this; }
  operator bool() const { return isValid(); }

  // ----------------------------------
  // Given the handle, return the object pointer
  template< class TObj >
  inline operator TObj*() const {
    CObjsManager<TObj> *om = getObjsManager< std::remove_const<TObj>::type >();
    assert(om);
    if (type == 0)
      return nullptr;
    assert(::getType< std::remove_const<TObj>::type >() == type
      || fatal("Trying to convert handle of type '%s' to wrong type '%s'\n", om->getTypeName(), getTypeName<std::remove_const<TObj>::type>()));
    return om->getObjByHandle(*this);
  }

  // ----------------------------------
  // Operator
  bool operator==(THandle h) const {
    return index == h.index && age == h.age && type == h.type;
  }
  bool isValid() const;

  // ----------------------------------
  // Get's
  uint32_t getType() const { return type; }
  uint32_t getIndex() const { return index; }
  uint32_t getAge() const { return age; }

  // ----------------------------------
  // Owner
  THandle getOwner() const;
  bool setOwner(THandle new_owner) const;

private:
  uint32_t index : n_index_bits;
  uint32_t age : n_counter_bits;
  uint32_t type : n_type_bits;
};

#endif


text:
'use strict';

console.log('Hello, renderer window!');
console.log('electron version: ' + process.versions.electron);


text:
package org.locationtech.geomesa.tools.export.formats

import org.apache.arrow.vector.ipc.message.IpcOption
import org.geotools.data.{DataStore, Query, Transaction}
import org.geotools.util.factory.Hints
import org.locationtech.geomesa.arrow.ArrowProperties
import org.locationtech.geomesa.arrow.io.{DictionaryBuildingWriter, FormatVersion, SimpleFeatureArrowFileWriter}
import org.locationtech.geomesa.arrow.vector.ArrowDictionary
import org.locationtech.geomesa.arrow.vector.SimpleFeatureVector.SimpleFeatureEncoding
import org.locationtech.geomesa.tools.`export`.formats.FeatureExporter.ExportStream
import org.locationtech.geomesa.tools.export.formats.ArrowExporter.{BatchDelegate, DictionaryDelegate, EncodedDelegate}
import org.locationtech.geomesa.tools.export.formats.FeatureExporter.ByteCounterExporter
import org.locationtech.geomesa.utils.collection.SelfClosingIterator
import org.locationtech.geomesa.utils.io.CloseWithLogging
import org.opengis.feature.simple.{SimpleFeature, SimpleFeatureType}

import java.io._
import scala.reflect.ClassTag

class ArrowExporter(stream: ExportStream, hints: Hints, queryDictionaries: => Map[String, Array[AnyRef]])
    extends ByteCounterExporter(stream) {

  import org.locationtech.geomesa.index.conf.QueryHints.RichHints

  private lazy val sort = hints.getArrowSort
  private lazy val encoding = SimpleFeatureEncoding.min(hints.isArrowIncludeFid, hints.isArrowProxyFid)
  private lazy val ipc = hints.getArrowFormatVersion.getOrElse(FormatVersion.ArrowFormatVersion.get)
  private lazy val batchSize = hints.getArrowBatchSize.getOrElse(ArrowProperties.BatchSize.get.toInt)
  private lazy val dictionaryFields = hints.getArrowDictionaryFields

  private var delegate: FeatureExporter = _

  override def start(sft: SimpleFeatureType): Unit = {
    delegate = if (sft == org.locationtech.geomesa.arrow.ArrowEncodedSft) {
      new EncodedDelegate(stream.os)
    } else {
      val providedDictionaries = hints.getArrowDictionaryEncodedValues(sft)
      if (dictionaryFields.forall(providedDictionaries.contains)) {
        var id = -1
        val dictionaries = (queryDictionaries ++ providedDictionaries).map { case (k, v) =>
          id += 1
          k -> ArrowDictionary.create(sft.getTypeName, id, v)(ClassTag[AnyRef](sft.getDescriptor(k).getType.getBinding))
        }
        // note: features should be sorted already, even if arrow encoding wasn't performed
        new BatchDelegate(stream.os, encoding, FormatVersion.options(ipc), sort, batchSize, dictionaries)
      } else {
        if (sort.isDefined) {
          throw new NotImplementedError("Sorting and calculating dictionaries at the same time is not supported")
        }
        new DictionaryDelegate(stream.os, dictionaryFields, encoding, FormatVersion.options(ipc), batchSize)
      }
    }
    delegate.start(sft)
  }

  override def export(features: Iterator[SimpleFeature]): Option[Long] = delegate.export(features)

  override def close(): Unit = {
    CloseWithLogging(Option(delegate))
    stream.close()
  }
}

object ArrowExporter {

  def queryDictionaries(ds: DataStore, query: Query): Map[String, Array[AnyRef]] = {
    import org.locationtech.geomesa.index.conf.QueryHints.RichHints

    import scala.collection.JavaConverters._

    val hints = query.getHints
    val dictionaryFields = {
      val provided = hints.getArrowDictionaryEncodedValues(ds.getSchema(query.getTypeName))
      hints.getArrowDictionaryFields.filterNot(provided.contains)
    }

    if (dictionaryFields.isEmpty) { Map.empty } else {
      // if we're hitting this, we can't do a stats query as we're not dealing with a geomesa store
      val dictionaryQuery = new Query(query.getTypeName, query.getFilter)
      dictionaryQuery.setPropertyNames(dictionaryFields.asJava)
      val map = dictionaryFields.map(f => f -> scala.collection.mutable.HashSet.empty[AnyRef]).toMap
      SelfClosingIterator(ds.getFeatureReader(dictionaryQuery, Transaction.AUTO_COMMIT)).foreach { sf =>
        map.foreach { case (k, values) => Option(sf.getAttribute(k)).foreach(values.add) }
      }
      map.map { case (k, values) => (k, values.toArray) }
    }
  }

  private class EncodedDelegate(os: OutputStream) extends FeatureExporter {
    override def start(sft: SimpleFeatureType): Unit = {}
    override def export(features: Iterator[SimpleFeature]): Option[Long] = {
      // just copy bytes directly out
      features.foreach(f => os.write(f.getAttribute(0).asInstanceOf[Array[Byte]]))
      None // we don't know the actual count
    }
    override def bytes: Long = 0L
    override def close(): Unit = {}
  }

  private class DictionaryDelegate(
      os: OutputStream,
      dictionaryFields: Seq[String],
      encoding: SimpleFeatureEncoding,
      ipcOpts: IpcOption,
      batchSize: Int
    ) extends FeatureExporter {

    private var writer: DictionaryBuildingWriter = _
    private var count = 0L

    override def start(sft: SimpleFeatureType): Unit = {
      writer = new DictionaryBuildingWriter(sft, dictionaryFields, encoding, ipcOpts)
    }

    override def export(features: Iterator[SimpleFeature]): Option[Long] = {
      val start = count
      features.foreach { f =>
        writer.add(f)
        count += 1
        if (count % batchSize == 0) {
          writer.encode(os)
          writer.clear()
        }
      }
      Some(count - start)
    }

    override def bytes: Long = 0L

    override def close(): Unit = {
      if (writer != null) {
        if (count % batchSize != 0) {
          writer.encode(os)
          writer.clear()
        }
        CloseWithLogging(writer)
      }
    }
  }

  private class BatchDelegate(
      os: OutputStream,
      encoding: SimpleFeatureEncoding,
      ipcOpts: IpcOption,
      sort: Option[(String, Boolean)],
      batchSize: Int,
      dictionaries: Map[String, ArrowDictionary]
    ) extends FeatureExporter {

    private var writer: SimpleFeatureArrowFileWriter = _
    private var count = 0L

    override def start(sft: SimpleFeatureType): Unit = {
      writer = SimpleFeatureArrowFileWriter(os, sft, dictionaries, encoding, ipcOpts, sort)
    }

    override def export(features: Iterator[SimpleFeature]): Option[Long] = {
      val start = count
      features.foreach { f =>
        writer.add(f)
        count += 1
        if (count % batchSize == 0) {
          writer.flush()
        }
      }
      Some(count - start)
    }

    override def bytes: Long = 0L

    override def close(): Unit = {
      if (writer != null) {
        CloseWithLogging(writer)
      }
    }
  }
}


text:
/*
 * Write a method GetMax() with two parameters
 * that returns the larger of two integers.
 * Write a program that reads 3 integers from the console
 * and prints the largest of them using the method GetMax().
 */

using System;
class GetLargestNumber
{
    static int GetMax(int first, int second)
    {
        int larger;
        if (first > second)
        {
            larger = first;
        }
        else
        {
            larger = second;
        }
        return larger;
    }
    static void Main()
    {
        Console.Write("Enter first integer: ");
        int x1 = int.Parse(Console.ReadLine());
        Console.Write("Enter second integer: ");
        int x2 = int.Parse(Console.ReadLine());
        Console.Write("Enter third integer: ");
        int x3 = int.Parse(Console.ReadLine());

        int larger = GetMax(x1, x2);
        int largest = GetMax(larger, x3);
        Console.WriteLine("The largest numbers is {0}", largest);
    }
}


text:
namespace ark {

class ARK_API IDHeap {
public:
//  [[script::bindings::auto]]
    IDHeap(size_t heapSize, size_t heapSizeL1 = 0, size_t chunkSizeL1 = 0);

//  [[script::bindings::auto]]
    size_t allocate(size_t size, size_t alignment = 1);
//  [[script::bindings::auto]]
    void free(size_t ptr);

private:
    class IDMemory {
    public:
        IDMemory(size_t begin, size_t end);

        size_t begin() const;
        size_t end() const;

    private:
        size_t _begin;
        size_t _end;
    };

private:
    typedef Heap<IDMemory, size_t, 1> HeapType;

    HeapType _heap;
};

}

#endif


text:
package org.apache.ofbiz.minilang.method;

import org.apache.ofbiz.base.util.ObjectType;
import org.apache.ofbiz.base.util.UtilGenerics;
import org.apache.ofbiz.base.util.collections.FlexibleMapAccessor;
import org.apache.ofbiz.minilang.SimpleMethod;
import org.w3c.dom.Element;

/**
 * Implements the <field> element.
 *
 * @see Mini-language Reference
 */
public final class FieldObject<T> extends MethodObject<T> {

    private final FlexibleMapAccessor<Object> fieldFma;
    private final String type;

    public FieldObject(Element element, SimpleMethod simpleMethod) {
        super(element, simpleMethod);
        this.fieldFma = FlexibleMapAccessor.getInstance(element.getAttribute("field"));
        String typeAttribute = element.getAttribute("type");
        if (typeAttribute.isEmpty()) {
            this.type = "java.lang.String";
        } else {
            this.type = typeAttribute;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public T getObject(MethodContext methodContext) {
        return (T) this.fieldFma.get(methodContext.getEnvMap());
    }

    @Override
    public Class<T> getTypeClass(MethodContext methodContext) throws ClassNotFoundException {
        return UtilGenerics.cast(ObjectType.loadClass(this.type, methodContext.getLoader()));
    }

    @Override
    public String getTypeName() {
        return this.type;
    }
}


text:
import React from 'react';
import Reflux from 'reflux';
import ChatStore from '../events/chat-store';
import ChatActions from '../events/chat-actions';
var $ = require('jquery');
var Switch = require('react-bootstrap-switch');

var IntegrationsPane = React.createClass({
    mixins: [Reflux.connect(ChatStore, 'store')],

    onChange: function(integrationId, state) {
        if (state && !this.state.store.integrations.find(i => i.id == integrationId).enabled) {
            ChatActions.enableIntegration(integrationId);
            window.location.replace("/integration/" + integrationId + "/enable?id=" +
                integrationId + "&redirectUrl=" + encodeURIComponent(document.location.href));
        } else if (!state && this.state.store.integrations.find(i => i.id == integrationId).enabled) {
            $.ajax({
                context: this,
                type: "GET",
                url: "/integration/" + integrationId + "/disable",
                success: function (message) {
                    ChatActions.disableIntegration(integrationId);
                },
                fail: function (e) {
                    console.error(e);
                }
            })
        }
    },

    render: function() {
        var self = this;
        var integrationItems = this.state.store.integrations.map(function(integration) {
            var checked = integration.enabled ? 'true' : null;
            return (

{integration.name}

                        <Switch size="mini" state={checked}
                                data-integration-id={integration.id} onChange={self.onChange.bind(self, integration.id)}/>

            );
        });
        return (

Integrations

                {integrationItems}

        );
    }
});

export default IntegrationsPane;


text:
body{
	font-family:sans-serif;
	font-size:13px;
	color:black;
	margin: 0px;
	padding: 0px;
}

.menu
{
	display: none;
}

.rootVoices{
	background-color: #f3f3f3;
	padding: 0px;
	white-space: nowrap;
}
.rootVoices td.rootVoice {
	background-color:transparent;
	line-height:18px;
	font-family:Arial,Helvetica,sans-serif;
	color: gray;
	font-size:12px;
	padding:5px;
	padding-left: 8px;
	padding-right: 8px;
	text-align: center;
	border-right: solid 1px #e2e2e2;
	white-space: nowrap;
	overflow: none;
	line-break:soft;
	/*cursor: pointer;*/
}
.rootVoices td.selected{
	/*
	background-color: gray;
	color:#ffffff;
	*/
	background-color: #e9e9e9;
	cursor: pointer;
	font-size:12px;
}

.menuShadow{
	padding:2px;
	padding-bottom:0px;
	left:-2;
	top:1px;
}

.menuContainer{
	background-color:gray;
	border-bottom: none; /*solid 1px gray;*/
	border: solid 1px #999;
}

.menuContainer .line{
	background-color:white;
	width:100%;
	padding-left:-5;
}

.menuContainer .line.title {
	text-align:right;
}

.menuContainer .line.title a{
	color:dimgray;
	font-size:14px;
}

.menuContainer td a{
	text-decoration:none;
	color: #000000;
}

.menuContainer td.voice{
	font-family:Arial,Helvetica,sans-serif;
	font-size:12px;
	padding:5px;
}

.menuContainer .separator{
	background-color:#f1f1f1;
	height:1px;
}
.menuContainer td.img{
	border-top:1px solid #f3f3f3;
	font-family:Arial,Helvetica,sans-serif;
	text-align:center;
	font-size:12px;
	color: #c3c3c3;
	background-color:#f9f9f9;
	width: 4px;
	padding:4px;
}
.menuContainer td.img img{
	width:20px;
	display:none;
}
.menuContainer .textBox{
	padding: 5px;
	font-family:Arial,Helvetica,sans-serif;
	font-size:12px;
	background-color:#ffffff;
	color: #c3c3c3;
}
.menuContainer .selected td{
	background-color:#fdfdfd;
	background-image:url("../../images/bgnd_sel_2.jpg");
	background-repeat: repeat-x;
	background-position: bottom;
}
.menuContainer .selected td a{
	color:#000;
}
.menuContainer .disabled td, .menuContainer .disabled td a {
	color: #cccccc;
}
.menuContainer .subMenuOpener{
	background-image:url("../../images/menuArrow.gif");
	background-repeat:no-repeat;
	background-position:right;
}

/*
vertical menu
*/

/**/

.rootVerticalVoices{
	background-color:#333;
	padding:0px;
}
.rootVerticalVoices td.rootVoice {
/*border-top:1px solid #666;*/
	width:130px;
	font-family:Arial,Helvetica,sans-serif;
	color: gray;
	font-size:13px;
	padding:7px;
	cursor: pointer;
}
.rootVerticalVoices td.selected{
	background-image:url("../../images/bgnd_sel_4.png");
	color:#ffffff;
	cursor: pointer;
}

.verticalMenu{
	background-color:#000;
	/*
 The menu container style must be set via the options paramiter
 within the function call due to a Safari bug interpreting css on the fly...
 */
}
.verticalMenu .line{
	background-color:#333;
	width:100%;
	padding-left:-5px;
}
.verticalMenu td a{
	text-decoration:none;
	color: #d3d3d3;
}
.verticalMenu td.voice{
	border-top:0px solid #666;
	font-family:Arial,Helvetica,sans-serif;
	font-size:12px;
	padding:5px;
}
.verticalMenu .separator{
	background-color:#666;
	height:1px;
}
.verticalMenu td.img{
	border-top:0px solid #666;
	font-family:Arial,Helvetica,sans-serif;
	text-align:center;
	font-size:12px;
	color: #c3c3c3;
	background-color:#333;
	width:24px;
	padding:5px;
}
.verticalMenu td.img img{
	width:20px;
}
.verticalMenu .textBox{
	padding: 10px;
	font-family:Arial,Helvetica,sans-serif;
	font-size:12px;
	color: #c3c3c3;
}
.verticalMenu .selected td{
	background-image:url("../../images/bgnd_sel_4.png");
}
.verticalMenu .selected td a{
	color:#fff;
}
.verticalMenu .disabled td, .verticalMenu .disabled td a {
	color: #666;
}
.verticalMenu .subMenuOpener{
	background-image:url("../../images/menuArrow_w.gif");
	background-repeat:no-repeat;
	background-position:right;
}
.verticalMenu .menuShadow{
	background:black;
	padding:5px;
}
.mbShortCut
{
		color:#c0c0c0;
		font-size:9px;
		padding-right:2px;
		text-align:right;
		width:20px;
		white-space:nowrap;
}


text:
//
//  FanTestViewController.m
//  FanKit
//
//  Created by 向阳凡 on 2017/3/10.
//  Copyright © 2017年 凡向阳. All rights reserved.
//

#import "FanTestViewController.h"
#import "FanRSA.h"
#import "FanVideoRecord.h"

@interface FanTestViewController ()
@property(nonatomic,strong)FanVideoRecord *videoView;

@end

@implementation FanTestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    [self testRSA];
    UIButton *openButton=[UIButton buttonWithType:UIButtonTypeSystem];
    [openButton setFrame:CGRectMake(60, 60, 80, 32)];
    [openButton setTitle:@"开启" forState:UIControlStateNormal];
    [openButton setTitleColor:FanBlackColor(1.0) forState:UIControlStateNormal];
    openButton.titleLabel.font=FanBoldFont(16);
    [openButton addTarget:self action:@selector(openLocalCameraClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:openButton];

    UIButton *recordButton=[UIButton buttonWithType:UIButtonTypeSystem];
    [recordButton setFrame:CGRectMake(60+100, 60, 80, 32)];
    [recordButton setTitle:@"录制" forState:UIControlStateNormal];
    [recordButton setTitleColor:FanBlackColor(1.0) forState:UIControlStateNormal];
    recordButton.titleLabel.font=FanBoldFont(16);
    [recordButton addTarget:self action:@selector(recoardVideoClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:recordButton];

    UIButton *saveButton=[UIButton buttonWithType:UIButtonTypeSystem];
    [saveButton setFrame:CGRectMake(60+200, 60, 80, 32)];
    [saveButton setTitle:@"保存" forState:UIControlStateNormal];
    [saveButton setTitleColor:FanBlackColor(1.0) forState:UIControlStateNormal];
    saveButton.titleLabel.font=FanBoldFont(16);
    [saveButton addTarget:self action:@selector(saveRecoardVideoClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveButton];

    UIButton *stopButton=[UIButton buttonWithType:UIButtonTypeSystem];
    [stopButton setFrame:CGRectMake(60+300, 60, 80, 32)];
    [stopButton setTitle:@"停止" forState:UIControlStateNormal];
    [stopButton setTitleColor:FanBlackColor(1.0) forState:UIControlStateNormal];
    stopButton.titleLabel.font=FanBoldFont(16);
    [stopButton addTarget:self action:@selector(cancelVideoClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:stopButton];
    UIButton *tackButton=[UIButton buttonWithType:UIButtonTypeSystem];
    [tackButton setFrame:CGRectMake(60+400, 60, 80, 32)];
    [tackButton setTitle:@"拍照" forState:UIControlStateNormal];
    [tackButton setTitleColor:FanBlackColor(1.0) forState:UIControlStateNormal];
    tackButton.titleLabel.font=FanBoldFont(16);
    [tackButton addTarget:self action:@selector(tackPhotoClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:tackButton];
}
-(FanVideoRecord *)videoView{
    if (_videoView==nil) {
        //本地录制
        _videoView = [[FanVideoRecord alloc]initWithFrame:self.view.bounds];
        //    _videoView.backgroundColor=[UIColor blackColor];
        _videoView.autoSaveToAlbum=YES;
        _videoView.maxRecordTime=30.0f;
        [self.view insertSubview:_videoView atIndex:0];

        __weak typeof(self) weakSelf=self;
        [_videoView setRecordBlock:^(FanVideoRecord * _Nonnull videoRecord, FanRecordState recordState, CGFloat recordTime) {
            NSLog(@"状态:%ld",recordState);
            switch (recordState) {
                case FanRecordStateRecording:
                {
                    NSLog(@"录制时间:%.2f/%.2f",recordTime,videoRecord.maxRecordTime);
                }
                    break;
                case FanRecordStateFinish:
                {

                    [weakSelf.videoView fan_closeVideo];
                    weakSelf.videoView.hidden=YES;
                }
                    break;
                case FanRecordStateEnterBack:
                {
                    //进入后台,库里面自动停止了

                }
                    break;
                case FanRecordStateBecomeActive:
                {

                }
                    break;

                default:
                    break;
            }
        }];
        [_videoView setSaveAlbumBlock:^(NSInteger saveType) {
            NSLog(@"保存状态:%ld",saveType);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (saveType==0) {
                }else if(saveType==1){

                }else if(saveType==2){

                }else if (saveType==-1) {
                    //编码中

                }else if(saveType==-2){

                }else if(saveType==-3){

                }else if(saveType==-4){

                }else if(saveType==-5){

                }
            });

        }];

    }
    return _videoView;
}

#pragma mark - 本地视频录制
///打开摄像头
-(void)openLocalCameraClick{
    FanWeakSelf;
    [FanAuthManager requestAVAuthorizationBlock:^(NSInteger status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (status==-2) {
                //用户点击不允许
            }else if(status==-1){
                //不允许
            }else if(status==0){
                //询问
            }else if(status==1){
                //允许
                [weakSelf openLocalCameraReal];
            }
        });
    }];
}
-(void)openLocalCameraReal{
    if ([self.videoView fan_openVideo]) {
        self.videoView.recordState=FanRecordStateOpenCamera;
        //修正每次拍摄时的方向,每次录制时,记录当前屏幕方向
//        self.currentOrientation=[self videoDeviceOrientation:[UIDevice currentDevice].orientation];
        self.videoView.hidden=NO;
    }else{
    }
}
-(void)cancelAllUI{
    [self.videoView fan_stopVideoRecord];
    [self.videoView fan_closeVideo];
    [self.videoView fan_deleteVideoRecord];
    [self.videoView removeFromSuperview];
    _videoView=nil;
}
///关闭录制+摄像头
-(void)cancelVideoClick{
    NSLog(@"关闭录制-摄像头");
    [self.videoView fan_clearAllRecord];
    self.videoView.hidden=YES;
}
///重新录制
-(void)refreshVideoClick{
    if([self.videoView fan_reStartVideoRecord]){
        self.videoView.hidden=NO;
    }else{
    }
}
//打开录制 保存录制
-(void)recoardVideoClick{
    if (self.videoView.recordState==FanRecordStateRecording) {
        //关闭录制
//        [self.videoView fan_stopVideoRecord];
//        [self.videoView fan_closeVideo];
//        self.videoView.hidden=YES;
    }else{
        //打开录制
//        [[AVAudioSession sharedInstance]setCategory:AVAudioSessionCategoryPlayback error:nil];
        if([self.videoView fan_startVideoRecord]){
            self.videoView.hidden=NO;
        }else{
        }
    }
}
///保存录制
-(void)saveRecoardVideoClick{
    if (self.videoView.recordState==FanRecordStateRecording) {
        //关闭录制
        [self.videoView fan_stopVideoRecord];
        [self.videoView fan_closeVideo];
        self.videoView.hidden=YES;
    }
}
-(void)tackPhotoClick{
    if ([self.videoView fan_openVideo]) {
        [self.videoView fan_startCapturePhoto];
    }
}
-(void)testRSA{
    NSString *siyao = @"-----BEGIN PRIVATE KEY-----\nMIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEA0YEsIeIpbyYhzWSf\npa1ZteoGFxJsH+VXc3HngEneK3PlSIj//Q39TAzQprIJtNoI6k7RDHOZggffZJ+v\njN41RwIDAQABAkANJEwvZ+9vcHXoW2qESwZ4mdB9/ALaUVmV/UwnSPrtwL8/jMgL\ndbaR4gYGqK0qlaKW89xizfnGAAdaNQYaCxoBAiEA96NTUnL/9mRQy2ui7Og22TwA\ncNDnQp00Xd7NoayHAQECIQDYlDUkhqUYzWsydbzctIzxvveMN6oxqB+UkDJOsn7u\nRwIhANjgXTS0Kp9rM6cz2TiKFp8iAXDMQ/z/GMGtQ4H4SzQBAiEAx14/QV11E0zd\ntjit35mQ+WTq6je/wzBZyd+nf8xOjjcCIQDzreOntgLL91+Pyea034PSgljOVIda\nlScgsEauudnJHg==\n-----END PRIVATE KEY-----";

    NSString *gongyao = @"-----BEGIN PUBLIC KEY-----\nMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANGBLCHiKW8mIc1kn6WtWbXqBhcSbB/l V3Nx54BJ3itz5UiI//0N/UwM0KayCbTaCOpO0QxzmYIH32Sfr4zeNUcCAwEAAQ==\n-----END PUBLIC KEY-----";

    NSString *str=@"我看门狗的啥控件地方了啥控件法律手段";

    NSString *eStr=[FanRSA fan_encryptString:str publicKey:gongyao];

    FanPrintf(@"加密:%@",eStr);
//
//    eStr=@"K6y/zW4fKlmtfYkeOYtsbsoKmkuSdNXjLgW1GMTRUaAuSmerqFWrAVrf0A4+N+CvMBRUw4zcguRjAxYtXulHww==";
//
//    eStr=@"E0nEn3IcAORjoZJPQOuOw5lLPCqh6wjpS110z9HNTPmK3eMhfOX19U5VMm8lgri3nu07DTEXazgPHz743FJnpA==";
    NSString *dStr=[FanRSA fan_decryptString:eStr privateKey:siyao];

    FanPrintf(@"解密:%@",dStr);

}

//int (*orig_sysctlbyname)(const char *name, void *oldp, size_t *oldlenp, void *newp, size_t newlen);
//
//int mysysctlbyname(const char *name, void *oldp, size_t *oldlenp, void *newp, size_t newlen){
//    if (strcmp(name,"hw.machine") == 0) {
//        if (oldp != NULL) {
//            int ret = orig_sysctlbyname(name,oldp,oldlenp,newp,newlen);
//            const char* mechine = "iWatch Edition";
//            strncpy((char *)oldp,mechine,strlen(mechine));
//            return ret;
//        }else{
//            int ret = orig_sysctlbyname(name,oldp,oldlenp,newp,newlen);
//            return ret;
//        }
//    }else{
//        return orig_sysctlbyname(name,oldp,oldlenp,newp,newlen);
//    }
//}
//%ctor {
//    MSHookFunction((void *)MSFindSymbol(NULL,"_sysctlbyname"), (void *)mysysctlbyname, (void **)&orig_sysctlbyname);
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
package gorpc

import (
	"time"

	"go-common/app/service/main/up/conf"
	"go-common/app/service/main/up/model"
	"go-common/app/service/main/up/service"
	"go-common/library/ecode"
	"go-common/library/log"
	"go-common/library/net/rpc"
	"go-common/library/net/rpc/context"
)

//RPC rpc server
type RPC struct {
	s *service.Service
}

//New create rpc
func New(c *conf.Config, s *service.Service) (svr *rpc.Server) {
	r := &RPC{s: s}
	svr = rpc.NewServer(c.RPCServer)
	if err := svr.Register(r); err != nil {
		panic(err)
	}
	return
}

// Ping check connection success.
func (r *RPC) Ping(c context.Context, arg *struct{}, res *struct{}) (err error) {
	return
}

// Special rpc call region
func (r *RPC) Special(c context.Context, arg *model.ArgSpecial, res *[]*model.UpSpecial) (err error) {
	*res = r.s.UpsByGroup(c, arg.GroupID)
	log.Info("[rpc.Special] arg=%+v, res count=%d", arg, len(*res))
	return
}

//Info get up info
func (r *RPC) Info(c context.Context, arg *model.ArgInfo, res *model.UpInfo) (err error) {
	if arg.Mid <= 0 {
		err = ecode.RequestErr
		log.Error("[rpc.Info] error, request mid <= 0, %d", arg.Mid)
		return
	}
	isAuthor, err := r.s.Info(c, arg.Mid, uint8(arg.From))
	if err != nil {
		log.Error("[rpc.Info] error, mid=%d, from=%d, err=%s", arg.Mid, arg.From, err)
		return
	}
	*res = model.UpInfo{IsAuthor: int32(isAuthor)}
	//log.Info("[rpc.Info] mid=%d, from=%d, result=%+v", arg.Mid, arg.From, *res)
	return
}

//UpStatBase get up stat
func (r *RPC) UpStatBase(c context.Context, arg *model.ArgMidWithDate, res *model.UpBaseStat) (err error) {
	if arg.Date.IsZero() {
		// 如果没有填,则取最新的数据,如果有填,则取对应天数的数据,这里不需要做什么操作
		arg.Date = time.Now()
		// 12点更新数据,数据表为昨天日期,所以在12点以前,要读前天的表
		arg.Date = arg.Date.Add(-12*time.Hour).AddDate(0, 0, -1)
	}
	var data, e = r.s.Data.BaseUpStat(c, arg.Mid, arg.Date.Format("20060102"))
	err = e
	if err == nil {
		data.CopyTo(res)
		log.Info("[rpc.UpStatBase] arg=%+v, res=%+v", arg, res)
	} else {
		log.Error("[rpc.UpStatBase] fail arg=%+v, err=%v", arg, err)
	}
	return
}

//SetUpSwitch set up switch
func (r *RPC) SetUpSwitch(c context.Context, arg *model.ArgUpSwitch, res *model.PBSetUpSwitchRes) (err error) {
	id, err := r.s.SetSwitch(c, arg.Mid, arg.State, uint8(arg.From))
	if err == nil {
		log.Info("[rpc.SetUpSwitch] arg=%+v, res=%+v", arg, res)
	} else {
		log.Error("[rpc.SetUpSwitch] fail arg=%+v, err=%v", arg, err)
	}
	*res = model.PBSetUpSwitchRes{Id: id}
	return
}

//UpSwitch get up switch
func (r *RPC) UpSwitch(c context.Context, arg *model.ArgUpSwitch, res *model.PBUpSwitch) (err error) {
	if arg.Mid <= 0 {
		err = ecode.RequestErr
		log.Error("[rpc.UpSwitch] error, request mid <= 0, %d", arg.Mid)
		return
	}
	state, err := r.s.UpSwitchs(c, arg.Mid, uint8(arg.From))
	if err != nil {
		log.Error("[rpc.UpSwitchs] error, mid=%d, from=%d, err=%s", arg.Mid, arg.From, err)
		return
	}
	*res = model.PBUpSwitch{State: int32(state)}
	return
}


text:
package com.lovecws.mumu.hazelcast.set;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ISet;
import com.lovecws.mumu.hazelcast.HazelcastConfiguration;

import java.util.Iterator;
import java.util.ListIterator;

/**
 * @author babymm
 * @version 1.0-SNAPSHOT
 * @Description: 分布式set
 * @date 2017-09-18 10:24
 */
public class HazelcastSet {

    public void set(String setName) {
        HazelcastInstance hazelcastInstance = new HazelcastConfiguration().instance();
        ISet<Object> hazelcastInstanceSet = hazelcastInstance.getSet(setName);
        for (int i = 0; i < 10000; i++) {
            hazelcastInstanceSet.add("lover");
        }
        Iterator<Object> objectIterator = hazelcastInstanceSet.iterator();
        while (objectIterator.hasNext()) {
            Object next = objectIterator.next();
            System.out.println(next);
        }
        System.out.println("set数量" + hazelcastInstanceSet.size());
    }
}


text:
package protomoto.ast;

import java.util.Arrays;
import java.util.List;

public interface ASTFactory<T> {
    T createList(List<T> items);
    default T createList(T... items) {
        return createList(Arrays.asList(items));
    }
    T createString(String str);
    T createInt(int i);
}


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

package sistema_escolar.repository;

import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import sistema_escolar.qualifier.MyDatabase;
import sistema_escolar.model.Turma;

/**
 *
 * @author Vitor Freitas
 */
public class TurmaRepository extends AbstractRepository<Long, Turma>
{
    @Inject @MyDatabase
    private EntityManager manager;

    @Override
    public List<Turma> getAll()
    {
        return manager.createNamedQuery(Turma.GET_ALL).getResultList();
    }

    @Override
    public List<Turma> getAllLazyLoad(int startingAt, int maxPerPage)
    {
        return (List<Turma>) manager.createNamedQuery(Turma.GET_ALL)
                .setFirstResult(startingAt)
                .setMaxResults(maxPerPage)
                .getResultList();
    }
}


text:
'use strict';

describe('directive sdcoCustomEventActions', function(){
    // common vars for tests
    var scope, directiveElement;

    //mock Application to allow us to inject our own dependencies
    beforeEach(angular.mock.module('sdco-tools.directives'));
    //we need to compile our directive
    beforeEach(angular.mock.inject(function($compile, $rootScope){
        //create an empty scope
        scope = $rootScope.$new();
        //declare the controller and inject our empty scope
        directiveElement= angular.element('<div sdco-custom-event-actions current-index="initialIndex"></div>');
        $compile(directiveElement)(scope);
    }));

    it('Decrement index, should be 0', function(){
        scope.$apply(function(){
            scope.initialIndex= 1;
        })
        tuUtils.triggerKeydown(directiveElement, 37);
        scope.$digest();
        expect(directiveElement.isolateScope().currentIndex).toBe(0);
        expect(scope.initialIndex).toBe(0);
    });

    it('Increment index, should be 2', function(){
        scope.$apply(function(){
            scope.initialIndex= 1;
        })
        tuUtils.triggerKeydown(directiveElement, 39);
        scope.$digest();
        expect(directiveElement.isolateScope().currentIndex).toBe(2);
        expect(scope.initialIndex).toBe(2);
    });
});


text:
package org.redisson;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;

import org.redisson.api.RFuture;
import org.redisson.api.RLock;
import org.redisson.client.codec.LongCodec;
import org.redisson.client.protocol.RedisCommands;
import org.redisson.client.protocol.RedisStrictCommand;
import org.redisson.command.CommandAsyncExecutor;
import org.redisson.pubsub.LockPubSub;

/**
 * Distributed implementation of {@link java.util.concurrent.locks.Lock}
 * Implements reentrant lock.

 * Lock will be removed automatically if client disconnects.
 *

 * Implements a fair locking so it guarantees an acquire order by threads.
 *
 * @author Nikita Koksharov
 *
 */
public class RedissonFairLock extends RedissonLock implements RLock {

    private final long threadWaitTime;
    private final CommandAsyncExecutor commandExecutor;
    private final String threadsQueueName;
    private final String timeoutSetName;

    public RedissonFairLock(CommandAsyncExecutor commandExecutor, String name) {
        this(commandExecutor, name, 60000*5);
    }

    public RedissonFairLock(CommandAsyncExecutor commandExecutor, String name, long threadWaitTime) {
        super(commandExecutor, name);
        this.commandExecutor = commandExecutor;
        this.threadWaitTime = threadWaitTime;
        threadsQueueName = prefixName("redisson_lock_queue", name);
        timeoutSetName = prefixName("redisson_lock_timeout", name);
    }

    @Override
    protected CompletableFuture<RedissonLockEntry> subscribe(long threadId) {
        return pubSub.subscribe(getEntryName() + ":" + threadId,
                getChannelName() + ":" + getLockName(threadId));
    }

    @Override
    protected void unsubscribe(RedissonLockEntry entry, long threadId) {
        pubSub.unsubscribe(entry, getEntryName() + ":" + threadId,
                getChannelName() + ":" + getLockName(threadId));
    }

    @Override
    protected CompletableFuture<Void> acquireFailedAsync(long waitTime, TimeUnit unit, long threadId) {
        long wait = threadWaitTime;
        if (waitTime > 0) {
            wait = unit.toMillis(waitTime);
        }

        RFuture<Void> f = evalWriteAsync(getRawName(), LongCodec.INSTANCE, RedisCommands.EVAL_VOID,
                // get the existing timeout for the thread to remove
                "local queue = redis.call('lrange', KEYS[1], 0, -1);" +
                        // find the location in the queue where the thread is
                        "local i = 1;" +
                        "while i <= #queue and queue[i] ~= ARGV[1] do " +
                        "i = i + 1;" +
                        "end;" +
                        // go to the next index which will exist after the current thread is removed
                        "i = i + 1;" +
                        // decrement the timeout for the rest of the queue after the thread being removed
                        "while i <= #queue do " +
                        "redis.call('zincrby', KEYS[2], -tonumber(ARGV[2]), queue[i]);" +
                        "i = i + 1;" +
                        "end;" +
                        // remove the thread from the queue and timeouts set
                        "redis.call('zrem', KEYS[2], ARGV[1]);" +
                        "redis.call('lrem', KEYS[1], 0, ARGV[1]);",
                Arrays.asList(threadsQueueName, timeoutSetName),
                getLockName(threadId), wait);
        return f.toCompletableFuture();
    }

    @Override
    <T> RFuture<T> tryLockInnerAsync(long waitTime, long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand<T> command) {
        long wait = threadWaitTime;
        if (waitTime > 0) {
            wait = unit.toMillis(waitTime);
        }

        long currentTime = System.currentTimeMillis();
        if (command == RedisCommands.EVAL_NULL_BOOLEAN) {
            return evalWriteAsync(getRawName(), LongCodec.INSTANCE, command,
                    // remove stale threads
                    "while true do " +
                        "local firstThreadId2 = redis.call('lindex', KEYS[2], 0);" +
                        "if firstThreadId2 == false then " +
                            "break;" +
                        "end;" +
                        "local timeout = tonumber(redis.call('zscore', KEYS[3], firstThreadId2));" +
                        "if timeout <= tonumber(ARGV[3]) then " +
                            // remove the item from the queue and timeout set
                            // NOTE we do not alter any other timeout
                            "redis.call('zrem', KEYS[3], firstThreadId2);" +
                            "redis.call('lpop', KEYS[2]);" +
                        "else " +
                            "break;" +
                        "end;" +
                    "end;" +

                    "if (redis.call('exists', KEYS[1]) == 0) " +
                        "and ((redis.call('exists', KEYS[2]) == 0) " +
                            "or (redis.call('lindex', KEYS[2], 0) == ARGV[2])) then " +
                        "redis.call('lpop', KEYS[2]);" +
                        "redis.call('zrem', KEYS[3], ARGV[2]);" +

                        // decrease timeouts for all waiting in the queue
                        "local keys = redis.call('zrange', KEYS[3], 0, -1);" +
                        "for i = 1, #keys, 1 do " +
                            "redis.call('zincrby', KEYS[3], -tonumber(ARGV[4]), keys[i]);" +
                        "end;" +

                        "redis.call('hset', KEYS[1], ARGV[2], 1);" +
                        "redis.call('pexpire', KEYS[1], ARGV[1]);" +
                        "return nil;" +
                    "end;" +
                    "if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " +
                        "redis.call('hincrby', KEYS[1], ARGV[2], 1);" +
                        "redis.call('pexpire', KEYS[1], ARGV[1]);" +
                        "return nil;" +
                    "end;" +
                    "return 1;",
                    Arrays.asList(getRawName(), threadsQueueName, timeoutSetName),
                    unit.toMillis(leaseTime), getLockName(threadId), currentTime, wait);
        }

        if (command == RedisCommands.EVAL_LONG) {
            return evalWriteAsync(getRawName(), LongCodec.INSTANCE, command,
                    // remove stale threads
                    "while true do " +
                        "local firstThreadId2 = redis.call('lindex', KEYS[2], 0);" +
                        "if firstThreadId2 == false then " +
                            "break;" +
                        "end;" +

                        "local timeout = tonumber(redis.call('zscore', KEYS[3], firstThreadId2));" +
                        "if timeout <= tonumber(ARGV[4]) then " +
                            // remove the item from the queue and timeout set
                            // NOTE we do not alter any other timeout
                            "redis.call('zrem', KEYS[3], firstThreadId2);" +
                            "redis.call('lpop', KEYS[2]);" +
                        "else " +
                            "break;" +
                        "end;" +
                    "end;" +

                    // check if the lock can be acquired now
                    "if (redis.call('exists', KEYS[1]) == 0) " +
                        "and ((redis.call('exists', KEYS[2]) == 0) " +
                            "or (redis.call('lindex', KEYS[2], 0) == ARGV[2])) then " +

                        // remove this thread from the queue and timeout set
                        "redis.call('lpop', KEYS[2]);" +
                        "redis.call('zrem', KEYS[3], ARGV[2]);" +

                        // decrease timeouts for all waiting in the queue
                        "local keys = redis.call('zrange', KEYS[3], 0, -1);" +
                        "for i = 1, #keys, 1 do " +
                            "redis.call('zincrby', KEYS[3], -tonumber(ARGV[3]), keys[i]);" +
                        "end;" +

                        // acquire the lock and set the TTL for the lease
                        "redis.call('hset', KEYS[1], ARGV[2], 1);" +
                        "redis.call('pexpire', KEYS[1], ARGV[1]);" +
                        "return nil;" +
                    "end;" +

                    // check if the lock is already held, and this is a re-entry
                    "if redis.call('hexists', KEYS[1], ARGV[2]) == 1 then " +
                        "redis.call('hincrby', KEYS[1], ARGV[2],1);" +
                        "redis.call('pexpire', KEYS[1], ARGV[1]);" +
                        "return nil;" +
                    "end;" +

                    // the lock cannot be acquired
                    // check if the thread is already in the queue
                    "local timeout = redis.call('zscore', KEYS[3], ARGV[2]);" +
                    "if timeout ~= false then " +
                        // the real timeout is the timeout of the prior thread
                        // in the queue, but this is approximately correct, and
                        // avoids having to traverse the queue
                        "return timeout - tonumber(ARGV[3]) - tonumber(ARGV[4]);" +
                    "end;" +

                    // add the thread to the queue at the end, and set its timeout in the timeout set to the timeout of
                    // the prior thread in the queue (or the timeout of the lock if the queue is empty) plus the
                    // threadWaitTime
                    "local lastThreadId = redis.call('lindex', KEYS[2], -1);" +
                    "local ttl;" +
                    "if lastThreadId ~= false and lastThreadId ~= ARGV[2] then " +
                        "ttl = tonumber(redis.call('zscore', KEYS[3], lastThreadId)) - tonumber(ARGV[4]);" +
                    "else " +
                        "ttl = redis.call('pttl', KEYS[1]);" +
                    "end;" +
                    "local timeout = ttl + tonumber(ARGV[3]) + tonumber(ARGV[4]);" +
                    "if redis.call('zadd', KEYS[3], timeout, ARGV[2]) == 1 then " +
                        "redis.call('rpush', KEYS[2], ARGV[2]);" +
                    "end;" +
                    "return ttl;",
                    Arrays.asList(getRawName(), threadsQueueName, timeoutSetName),
                    unit.toMillis(leaseTime), getLockName(threadId), wait, currentTime);
        }

        throw new IllegalArgumentException();
    }

    @Override
    protected RFuture<Boolean> unlockInnerAsync(long threadId) {
        return evalWriteAsync(getRawName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
                // remove stale threads
                "while true do "
                + "local firstThreadId2 = redis.call('lindex', KEYS[2], 0);"
                + "if firstThreadId2 == false then "
                    + "break;"
                + "end; "
                + "local timeout = tonumber(redis.call('zscore', KEYS[3], firstThreadId2));"
                + "if timeout <= tonumber(ARGV[4]) then "
                    + "redis.call('zrem', KEYS[3], firstThreadId2); "
                    + "redis.call('lpop', KEYS[2]); "
                + "else "
                    + "break;"
                + "end; "
              + "end;"

              + "if (redis.call('exists', KEYS[1]) == 0) then " +
                    "local nextThreadId = redis.call('lindex', KEYS[2], 0); " +
                    "if nextThreadId ~= false then " +
                        "redis.call('publish', KEYS[4] .. ':' .. nextThreadId, ARGV[1]); " +
                    "end; " +
                    "return 1; " +
                "end;" +
                "if (redis.call('hexists', KEYS[1], ARGV[3]) == 0) then " +
                    "return nil;" +
                "end; " +
                "local counter = redis.call('hincrby', KEYS[1], ARGV[3], -1); " +
                "if (counter > 0) then " +
                    "redis.call('pexpire', KEYS[1], ARGV[2]); " +
                    "return 0; " +
                "end; " +

                "redis.call('del', KEYS[1]); " +
                "local nextThreadId = redis.call('lindex', KEYS[2], 0); " +
                "if nextThreadId ~= false then " +
                    "redis.call('publish', KEYS[4] .. ':' .. nextThreadId, ARGV[1]); " +
                "end; " +
                "return 1; ",
                Arrays.asList(getRawName(), threadsQueueName, timeoutSetName, getChannelName()),
                LockPubSub.UNLOCK_MESSAGE, internalLockLeaseTime, getLockName(threadId), System.currentTimeMillis());
    }

    @Override
    public Condition newCondition() {
        throw new UnsupportedOperationException();
    }

    @Override
    public RFuture<Boolean> deleteAsync() {
        return deleteAsync(getRawName(), threadsQueueName, timeoutSetName);
    }

    @Override
    public RFuture<Long> sizeInMemoryAsync() {
        List<Object> keys = Arrays.asList(getRawName(), threadsQueueName, timeoutSetName);
        return super.sizeInMemoryAsync(keys);
    }

    @Override
    public RFuture<Boolean> expireAsync(long timeToLive, TimeUnit timeUnit, String param, String... keys) {
        return super.expireAsync(timeToLive, timeUnit, param, getRawName(), threadsQueueName, timeoutSetName);
    }

    @Override
    protected RFuture<Boolean> expireAtAsync(long timestamp, String param, String... keys) {
        return super.expireAtAsync(timestamp, param, getRawName(), threadsQueueName, timeoutSetName);
    }

    @Override
    public RFuture<Boolean> clearExpireAsync() {
        return clearExpireAsync(getRawName(), threadsQueueName, timeoutSetName);
    }

    @Override
    public RFuture<Boolean> forceUnlockAsync() {
        cancelExpirationRenewal(null);
        return evalWriteAsync(getRawName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
                // remove stale threads
                "while true do "
                + "local firstThreadId2 = redis.call('lindex', KEYS[2], 0);"
                + "if firstThreadId2 == false then "
                    + "break;"
                + "end; "
                + "local timeout = tonumber(redis.call('zscore', KEYS[3], firstThreadId2));"
                + "if timeout <= tonumber(ARGV[2]) then "
                    + "redis.call('zrem', KEYS[3], firstThreadId2); "
                    + "redis.call('lpop', KEYS[2]); "
                + "else "
                    + "break;"
                + "end; "
              + "end;"
                +

                "if (redis.call('del', KEYS[1]) == 1) then " +
                    "local nextThreadId = redis.call('lindex', KEYS[2], 0); " +
                    "if nextThreadId ~= false then " +
                        "redis.call('publish', KEYS[4] .. ':' .. nextThreadId, ARGV[1]); " +
                    "end; " +
                    "return 1; " +
                "end; " +
                "return 0;",
                Arrays.asList(getRawName(), threadsQueueName, timeoutSetName, getChannelName()),
                LockPubSub.UNLOCK_MESSAGE, System.currentTimeMillis());
    }

}


text:
Given a person's allergy score, determine whether or not they're allergic to a given item, and their full list of allergies.

An allergy test produces a single numeric score which contains the
information about all the allergies the person has (that they were
tested for).

The list of items (and their value) that were tested are:

* eggs (1)
* peanuts (2)
* shellfish (4)
* strawberries (8)
* tomatoes (16)
* chocolate (32)
* pollen (64)
* cats (128)

So if Tom is allergic to peanuts and chocolate, he gets a score of 34.

Now, given just that score of 34, your program should be able to say:

- Whether Tom is allergic to any one of those allergens listed above.
- All the allergens Tom is allergic to.

Note: a given score may include allergens **not** listed above (i.e.
allergens that score 256, 512, 1024, etc.).  Your program should
ignore those components of the score.  For example, if the allergy
score is 257, your program should only report the eggs (1) allergy.

## Getting Started

Make sure you have read the
[C page](http://exercism.io/languages/c) on the Exercism site. This covers
the basic information on setting up the development environment expected
by the exercises.

## Passing the Tests

Get the first test compiling, linking and passing by following the [three
rules of test-driven development][3-tdd-rules].

The included makefile can be used to create and run the tests using the `test`
task.

    make test

Create just the functions you need to satisfy any compiler errors and get the
test to fail. Then write just enough code to get the test to pass. Once you've
done that, move onto the next test.

[3-tdd-rules]: http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd

As you progress through the tests, take the time to refactor your
implementation for readability and expressiveness and then go on to the next
test.

Try to use standard C99 facilities in preference to writing your own
low-level algorithms or facilities by hand.

## Source

Jumpstart Lab Warm-up [http://jumpstartlab.com](http://jumpstartlab.com)

## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.


text:
i created this repro to leverage AzureRM on Mooncake.

all endpoint of AzureRM repro has been fixed with Mooncake endpoint.

China Developer can leverage this to create/update/delete resource simply.

I'm considering make it available on PIP so that you can pip install mcazurerm later.

feel free to let me know if you have any question -> raise issues

# Mooncake AzureRM
Easy to use Python library for Azure Resource Manager.

The mcazurerm philosophy is ease of use over completeness of API. Rather than support every possible attribute the goal is to provide a set of simple functions for the most common tasks that anyone can extend.

Note: This is not an official Microsoft library, just some REST wrappers to make it easier to call the Azure REST API. For the official Microsoft Azure library for Python please go here: https://github.com/Azure/azure-sdk-for-python.

#### Example to list Azure subscriptions, create a Resource Group, list Resource Groups
```
import mcazurerm

tenant_id = 'your-tenant-id'
application_id = 'your-application-id'
application_secret = 'your-application-secret'

# create an authentication token
access_token = mcazurerm.get_access_token(
    tenant_id,
    application_id,
    application_secret
)

# list subscriptions
subscriptions = mcazurerm.list_subscriptions(access_token)
for sub in subscriptions["value"]:
    print(sub["displayName"] + ': ' + sub["subscriptionId"])

# select the first subscription
subscription_id = subscriptions["value"][0]["subscriptionId"]

# create a resource group
print('Enter Resource group name to create.')
rgname = input()
location = 'southeastasia'
rgreturn = mcazurerm.create_resource_group(access_token, subscription_id, rgname, location)
print(rgreturn)
print(json.dumps(rgreturn.json(), sort_keys=False, indent=2, separators=(',', ': ')))

# list resource groups
resource_groups = mcazurerm.list_resource_groups(access_token, subscription_id)
for rg in resource_groups["value"]:
    print(rg["name"] + ', ' + rg["location"] + ', ' + rg["properties"]["provisioningState"])
```

#### Example to create a virtual machine
```
import mcazurerm
impor json

tenant_id = 'your-tenant-id'
application_id = 'your-application-id'
application_secret = 'your-application-secret'

# authenticate
access_token = mcazurerm.get_access_token(tenant_id, app_id, app_secret)

# create resource group
print('Creating resource group: ' + name)
rmreturn = mcazurerm.create_resource_group(access_token, subscription_id, name, location)
print(rmreturn)

# create NSG
nsg_name = name + 'nsg'
print('Creating NSG: ' + nsg_name)
rmreturn = mcazurerm.create_nsg(access_token, subscription_id, name, nsg_name, location)
nsg_id = rmreturn.json()['id']
print('nsg_id = ' + nsg_id)

# create NSG rule
nsg_rule = 'ssh'
print('Creating NSG rule: ' + nsg_rule)
rmreturn = mcazurerm.create_nsg_rule(access_token, subscription_id, name, nsg_name, nsg_rule, description='ssh rule',
                                  destination_range='22')
print(rmreturn)
print(json.dumps(rmreturn.json(), sort_keys=False, indent=2, separators=(',', ': ')))

# create storage account
print('Creating storage account: ' + name)
rmreturn = mcazurerm.create_storage_account(access_token, subscription_id, name, name, location, storage_type='Premium_LRS')
print(rmreturn)

# create VNET
vnetname = name + 'vnet'
print('Creating VNet: ' + vnetname)
rmreturn = mcazurerm.create_vnet(access_token, subscription_id, name, vnetname, location, nsg_id=nsg_id)
print(rmreturn)
# print(json.dumps(rmreturn.json(), sort_keys=False, indent=2, separators=(',', ': ')))
subnet_id = rmreturn.json()['properties']['subnets'][0]['id']
print('subnet_id = ' + subnet_id)

# create public IP address
public_ip_name = name + 'ip'
dns_label = name + 'ip'
print('Creating public IP address: ' + public_ip_name)
rmreturn = mcazurerm.create_public_ip(access_token, subscription_id, name, public_ip_name, dns_label, location)
print(rmreturn)
ip_id = rmreturn.json()['id']
print('ip_id = ' + ip_id)

# create NIC
nic_name = name + 'nic'
print('Creating NIC: ' + nic_name)
rmreturn = mcazurerm.create_nic(access_token, subscription_id, name, nic_name, ip_id, subnet_id, location)
print(rmreturn)
nic_id = rmreturn.json()['id']

# create VM
vm_name = name
vm_size = 'Standard_DS1'
publisher = 'Canonical'
offer = 'UbuntuServer'
sku = '16.04.0-LTS'
version = 'latest'
os_uri = 'http://' + name + '.blob.core.chinacloudapi.cn/vhds/osdisk.vhd'
username = 'rootuser'
password = 'myPassw0rd'

print('Creating VM: ' + vm_name)
rmreturn = mcazurerm.create_vm(access_token, subscription_id, name, vm_name, vm_size, publisher, offer, sku,
                             version, name, os_uri, username, password, nic_id, location)
print(rmreturn)
print(json.dumps(rmreturn.json(), sort_keys=False, indent=2, separators=(',', ': ')))
```

#### Example to create a Media Services Account
```
import json
import mcazurerm

# Load Azure app defaults
try:
        with open('config.json') as configFile:
                configData = json.load(configFile)
except FileNotFoundError:
        print("ERROR: Expecting config.json in current folder")
        sys.exit()

tenant_id = configData['tenantId']
app_id = configData['appId']
app_secret = configData['appSecret']
subscription_id = configData['subscriptionId']
resourceGroup = configData['resourceGroup']
stoaccountName = configData['stoaccountName']
region = configData['region']

access_token = mcazurerm.get_access_token(
        tenant_id,
        app_id,
        app_secret
)

# list subscriptions
subscriptions = mcazurerm.list_subscriptions(access_token)
for sub in subscriptions["value"]:
        print("SUBSCRIPTION: " + sub["displayName"] + ': ' + sub["subscriptionId"])

# use the first subscription
subscription_id = subscriptions["value"][0]["subscriptionId"]

# create a media service account in a resource group
name = "itisjustasimpletest"
response = mcazurerm.create_media_service_rg(access_token, subscription_id, resourceGroup, region, stoaccountName, name)
if (response.status_code == 201):
        print("MEDIA SERVICE ACCOUNT: '" + name.upper() + "' CREATED OK.")
else:
        print("ERROR: Creating New MEDIA SERVICE ACCOUNT: " + name.upper())
```

## Functions currently supported
A basic set of infrastructure create, list, query functions are implemented. If you want to add something please send me a PR (don't forget to update this readme too).

### Deployments
```
show_deployment(access_token, subscription_id, resource_group, deployment_name) # show deployment status/details
list_deployment_operations(access_token, subscription_id, resource_group, deployment_name) # list operations involved in a given deployment
```

### Image/Publisher catalog
```
list_offers(access_token, subscription_id, location, publisher) # list available VM image offers from a publisher
list_publishers(access_token, subscription_id, location) # list available image publishers for a location
list_sku_versions(access_token, subscription_id, location, publisher, offer, sku) # list available versions for a given publisher's sku
list_skus(access_token, subscription_id, location, publisher, offer) # list available VM image skus for a publisher offer
```

### Network
```
create_nsg(access_token, subscription_id, resource_group, nsg_name, location) # create network security group (use create_nsg_rule() to add rules to it)
create_nsg_rule(access_token, subscription_id, resource_group, nsg_name, nsg_rule_name, description, protocol='Tcp', source_range='*', destination_range='*', source_prefix='Internet', destination_prefix='*', access = 'Allow', priority=100, direction='Inbound') # create network security group rule to apply to a named NSG
create_public_ip(access_token, subscription_id, resource_group) # list the public ip addresses in a resource group
create_vnet(access_token, subscription_id, resource_group, name, location, address_prefix='10.0.0.0/16', nsg_id=None)) # create a VNet with specified name and location, optional address prefix and NSG id
delete_nic(access_token, subscription_id, resource_group, nic_name) # delete a network interface
delete_nsg(access_token, subscription_id, resource_group, nsg_name) # delete network security group
delete_nsg_rule(access_token, subscription_id, resource_group, nsg_name, nsg_rule_name) # delete network security group rule
delete_public_ip(access_token, subscription_id, resource_group, public_ip_name) # delete a public ip addresses associated with a resource group
get_lb_nat_rule(access_token, subscription_id, resource_group, lb_name, rule_name) # get details about a load balancer inbound NAT rule
get_load_balancer(access_token, subscription_id, resource_group, lb_name) # get details about a load balancer
get_network_usage(access_token, subscription_id, location) # list network usage and limits for a location
get_public_ip(access_token, subscription_id, resource_group) # get details about the named public ip address
get_vnet(access_token, subscription_id, resource_group, vnet_name) # get details about the named virtual network
list_lb_nat_rules(access_token, subscription_id, resource_group, lb_name) # list the inbound NAT rules for a load balancer
list_load_balancers(access_token, subscription_id) # list the load balancers in a subscription
list_load_balancers_rg(access_token, subscription_id, resource_group) # list the load balancers in a resource group
create_nic(access_token, subscription_id, resource_group, nic_name, public_ip_id, subnet_id, location) # create a network interface
list_nics(access_token, subscription_id) # list the network interfaces in a subscription
list_nics_rg(access_token, subscription_id, resource_group) # list the network interfaces in a resource group
list_public_ips(access_token, subscription_id, resource_group) # list the public ip addresses in a resource group
list_vnets(access_token, subscription_id) # list the VNETs in a subscription
```

### Insights
```
list_autoscale_settings(access_token, subscription_id) # list the autoscale settings in a subscription_id
list_insights_components(access_token, subscription_id, resource_group) # list the Microsoft Insights components in a resource group
list_metric_definitions_for_resource(access_token, subscription_id, resource_group, resource_provider, resource_type, resource_name) # list the monitoring metric definitions for a resource
get_metrics_for_resource(access_token, subscription_id, resource_group, resource_provider, resource_type, resource_name) # get the monitoring metrics for a resource
```

#### Media Services (Media Resource provider)
```
create_media_service_rg(access_token, subscription_id, rgname) # create a media services account in a resource group
check_name_availability(access_token, subscription_id, rgname) # verify the availability of an media services account name
delete_media_service_rg(access_token, subscription_id, rgname) # delete a media services account in a resource group
list_media_endpoint_keys(access_token, subscription_id, rgname, msname) # list media services endpoint keys in a resource group and specifig media services account
list_media_services(access_token, subscription_id) # list media services in a subscription
list_media_services_rg(access_token, subscription_id, rgname) # list media services in a specific resource group
```

#### Resource groups
```
create_resource_group(access_token, subscription_id, rgname, location) # create a resource group in the specified location
delete_resource_group(access_token, subscription_id, rgname) # delete the named resource group
get_resource_group(access_token, subscription_id, rgname) # get details about the named resource group
list_resource_groups(access_token, subscription_id) # list the resource groups in your subscription
```

#### Storage
```
create_storage_account(access_token, subscription_id, rgname, location, storage_type='Standard_LRS') # create a new storage account
delete_storage_account(access_token, subscription_id, rgname) # delete a storage account in the specified resource group
get_storage_account(access_token, subscription_id, rgname) # get details for the specified storage account
get_storage_account_keys(access_token, subscription_id, rgname, account_name) # get the access keys for the specified storage account
get_storage_usage(access_token, subscription_id) # returns storage usage and quota information for the specified subscription
list_storage_accounts_rg(access_token, subscription_id, rgname) # list the storage accounts in the specified resource group
list_storage_accounts_sub(access_token, subscription_id) # list the storage accounts in the specified subscription
```

#### Subscription, location, and access token
```
get_access_token(tenant_id, application_id, application_secret) # get an Azure access token for your application
    # Note get_access_token has optional endpoint parameters which allow you to join national clouds
    # - authentication_endpoint='https://login.microsoftonline.com/', resource='https://management.core.windows.net/
list_locations(access_token, subscription_id) # list available locations for a subscription
list_subscriptions(access_token) # list the available Azure subscriptions for this application
```

### Template functions
```
deploy_template(access_token, subscription_id, resource_group, deployment_name, template, parameters) # deploy a template referenced by a JSON string, with parameters as a JSON string
deploy_template_uri(access_token, subscription_id, resource_group, deployment_name, template_uri, parameters) # deploy a template referenced by a URI, with parameters as a JSON string
deploy_template_uri_param_uri(access_token, subscription_id, resource_group, deployment_name, template_uri, parameters_uri) # deploy a template with both template and parameters referenced by URIs
```

#### Virtual machines and VM Scale Sets (Compute Resource provider)
```
create_vm(access_token, subscription_id, resource_group, vm_name, vm_size, publisher, offer, sku, version,
              storage_account, os_uri, username, password, nic_id, location) # simple vm create function
deallocate_vm(access_token, subscription_id, resource_group, vm_name) # stop#deallocate a virtual machine
delete_vm(access_token, subscription_id, resource_group, vm_name) # delete a virtual machine
delete_vmss(access_token, subscription_id, resource_group, vmss_name) # delete a virtual machine scale set
delete_vmss_vms(access_token, subscription_id, resource_group, vm_ids) # delete a VM in a VM Scale Set
get_compute_usage(access_token, subscription_id, location) # list compute usage and limits for a location
get_vm(access_token, subscription_id, resource_group, vm_name) # get virtual machine details
get_vm_extension(access_token, subscription_id, resource_group, vm_name, extension_name) # get details about a VM extension
get_vmss(access_token, subscription_id, resource_group, vmss_name) # get virtual machine scale set details
get_vmss_instance_view(access_token, subscription_id, resource_group, vmss_name) # get virtual machine scale set instance view
get_vmss_nics(access_token, subscription_id, resource_group, vmss_name) # get NIC details for a VM Scale Set
get_vmss_vm(access_token, subscription_id, resource_group, vmss_name, instance_id) # get individual VMSS VM details
get_vmss_vm_instance_view(access_token, subscription_id, resource_group, vmss_name, instance_id) # get individual VMSS VM instance view
get_vmss_vm_nics(access_token, subscription_id, resource_group, vmss_name, instance_id) # get NIC details for a VMSS VM
list_as(access_token, subscription_id, resource_group) # list availability sets in a resource_group
list_as_sub(access_token, subscription_id) # list availability sets in a subscription
list_vm_images_sub(access_token, subscription_id) # list VM images in a subscription
list_vms(access_token, subscription_id, resource_group) # list VMs in a resource group
list_vms_sub(access_token, subscription_id) # list the VMs in a subscription
list_vmss(access_token, subscription_id, resource_group) # list the VM Scale Sets in a resource group
list_vmss_sub(access_token, subscription_id) # list the VM Scale Sets in a subscription
list_vmss_vm_instance_view(access_token, subscription_id, resource_group, vmss_name) # list the VMSS VM instance views in a scale set
list_vmss_vms(access_token, subscription_id, resource_group, vmss_name) # list the VMs in a VM Scale Set
restart_vm(access_token, subscription_id, resource_group, vm_name) # restart a virtual machine
restart_vmss(access_token, subscription_id, resource_group, vmss_name) # restart all the VMs in a virtual machine scale set
restart_vmss_vms(access_token, subscription_id, resource_group, vmss_name, instance_id) # restart VMs in a virtual machine scale set
scale_vmss(access_token, subscription_id, resource_group, vmss_name, size, tier, capacity) # change the instance count of an existing VM Scale Set
start_vm(access_token, subscription_id, resource_group, vm_name) # start a virtual machine
start_vmss(access_token, subscription_id, resource_group, vmss_name) # start all the VMs in a virtual machine scale set
start_vmss_vms(access_token, subscription_id, resource_group, vmss_name, vm_ids) # start VMs in a virtual machine scale set
stop_vm(access_token, subscription_id, resource_group, vm_name) # stop a VM, don't deallocate resources
stopdealloc_vmss(access_token, subscription_id, resource_group, vmss_name) # stop all the VMs in a virtual machine scale set
stopdealloc_vmss_vms(access_token, subscription_id, resource_group, vm_ids) # stop VMs in a virtual machine scale set
poweroff_vmss(access_token, subscription_id, resource_group, vmss_name) # poweroff all the VMs in a virtual machine scale set
poweroff_vmss_vms(access_token, subscription_id, resource_group, vmss_name, vm_ids) # poweroff VMs in a virtual machine scale set
update_vm(access_token, subscription_id, resource_group, vm_name, body) # updates a VM model, that is put an updated virtual machine scale set body
update_vmss(access_token, subscription_id, resource_group, vmss_name, body) # updates a VMSS model, that is put an updated virtual machine scale set body
upgrade_vmss_vms(access_token, subscription_id, resource_group, vmss_name, instance_ids) # upgrade a specific VMs a virtual machine scale set
```


text:
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(VotingApplication.Web.Startup))]
namespace VotingApplication.Web
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            app.MapSignalR();
        }
    }
}


text:
title: Redirect — Eregansu Framework
package: framework
packageTitle: Eregansu Framework
layout: default
className: Redirect
type: class
---

# Redirect

Perform a redirect when a route is requested.

Redirect is a class derived from Routable.

## Synopsis

uses('routable');

## Public Methods

* Redirect::process()


text:
"""
Pure SciPy implementation of Locally Optimal Block Preconditioned Conjugate
Gradient Method (LOBPCG), see
http://www-math.cudenver.edu/~aknyazev/software/BLOPEX/

License: BSD

Authors: Robert Cimrman, Andrew Knyazev

Examples in tests directory contributed by Nils Wagner.
"""

import sys
import numpy as np
import scipy as sp

from scipy.sparse.linalg import aslinearoperator, LinearOperator

__all__ = ['lobpcg']

## try:
##     from symeig import symeig
## except:
##     raise ImportError('lobpcg requires symeig')

def symeig( mtxA, mtxB = None, eigenvectors = True, select = None ):
    import scipy.linalg as sla
    import scipy.lib.lapack as ll
    if select is None:
        if np.iscomplexobj( mtxA ):
            if mtxB is None:
                fun = ll.get_lapack_funcs( ['heev'], arrays = (mtxA,) )[0]
            else:
                fun = ll.get_lapack_funcs( ['hegv'], arrays = (mtxA,) )[0]
        else:
            if mtxB is None:
                fun = ll.get_lapack_funcs( ['syev'], arrays = (mtxA,) )[0]
            else:
                fun = ll.get_lapack_funcs( ['sygv'], arrays = (mtxA,) )[0]
##         print fun
        if mtxB is None:
            out = fun( mtxA )
        else:
            out = fun( mtxA, mtxB )
##         print w
##         print v
##         print info
##         from symeig import symeig
##         print symeig( mtxA, mtxB )
    else:
        out = sla.eig( mtxA, mtxB, right = eigenvectors )
        w = out[0]
        ii = np.argsort( w )
        w = w[slice( *select )]
        if eigenvectors:
            v = out[1][:,ii]
            v = v[:,slice( *select )]
            out = w, v, 0
        else:
            out = w, 0

    return out[:-1]

def pause():
    raw_input()

def save( ar, fileName ):
    from numpy import savetxt
    savetxt( fileName, ar, precision = 8 )

##
# 21.05.2007, c
def as2d( ar ):
    """
    If the input array is 2D return it, if it is 1D, append a dimension,
    making it a column vector.
    """
    if ar.ndim == 2:
        return ar
    else: # Assume 1!
        aux = np.array( ar, copy = False )
        aux.shape = (ar.shape[0], 1)
        return aux

class CallableLinearOperator(LinearOperator):
    def __call__(self, x):
        return self.matmat(x)

def makeOperator( operatorInput, expectedShape ):
    """Internal. Takes a dense numpy array or a sparse matrix or
    a function and makes an operator performing matrix * blockvector
    products.

    Example
    -------

    >>> A = makeOperator( arrayA, (n, n) )
    >>> vectorB = A( vectorX )

    """
    if operatorInput is None:
        def ident(x):
            return x
        operator = LinearOperator(expectedShape, ident, matmat=ident)
    else:
        operator = aslinearoperator(operatorInput)

    if operator.shape != expectedShape:
        raise ValueError('operator has invalid shape')

    if sys.version_info[0] >= 3:
        # special methods are looked up on the class -- so make a new one
        operator.__class__ = CallableLinearOperator
    else:
        operator.__call__ = operator.matmat

    return operator

def applyConstraints( blockVectorV, factYBY, blockVectorBY, blockVectorY ):
    """Internal. Changes blockVectorV in place."""
    gramYBV = sp.dot( blockVectorBY.T, blockVectorV )
    import scipy.linalg as sla
    tmp = sla.cho_solve( factYBY, gramYBV )
    blockVectorV -= sp.dot( blockVectorY, tmp )

def b_orthonormalize( B, blockVectorV,
                      blockVectorBV = None, retInvR = False ):
    """Internal."""
    import scipy.linalg as sla
    if blockVectorBV is None:
        if B is not None:
            blockVectorBV = B( blockVectorV )
        else:
            blockVectorBV = blockVectorV # Shared data!!!
    gramVBV = sp.dot( blockVectorV.T, blockVectorBV )
    gramVBV = sla.cholesky( gramVBV )
    gramVBV = sla.inv( gramVBV, overwrite_a = True )
    # gramVBV is now R^{-1}.
    blockVectorV = sp.dot( blockVectorV, gramVBV )
    if B is not None:
        blockVectorBV = sp.dot( blockVectorBV, gramVBV )

    if retInvR:
        return blockVectorV, blockVectorBV, gramVBV
    else:
        return blockVectorV, blockVectorBV

def lobpcg( A, X,
            B=None, M=None, Y=None,
            tol= None, maxiter=20,
            largest = True, verbosityLevel = 0,
            retLambdaHistory = False, retResidualNormsHistory = False ):
    """Solve symmetric partial eigenproblems with optional preconditioning

    This function implements the Locally Optimal Block Preconditioned
    Conjugate Gradient Method (LOBPCG).

    Parameters
    ----------
    A : {sparse matrix, dense matrix, LinearOperator}
        The symmetric linear operator of the problem, usually a
        sparse matrix.  Often called the "stiffness matrix".
    X : array_like
        Initial approximation to the k eigenvectors. If A has
        shape=(n,n) then X should have shape shape=(n,k).
    B : {dense matrix, sparse matrix, LinearOperator}, optional
        the right hand side operator in a generalized eigenproblem.
        by default, B = Identity
        often called the "mass matrix"
    M : {dense matrix, sparse matrix, LinearOperator}, optional
        preconditioner to A; by default M = Identity
        M should approximate the inverse of A
    Y : array_like, optional
        n-by-sizeY matrix of constraints, sizeY < n
        The iterations will be performed in the B-orthogonal complement
        of the column-space of Y. Y must be full rank.

    Returns
    -------
    w : array
        Array of k eigenvalues
    v : array
        An array of k eigenvectors.  V has the same shape as X.

    Other Parameters
    ----------------
    tol : scalar, optional
        Solver tolerance (stopping criterion)
        by default: tol=n*sqrt(eps)
    maxiter: integer, optional
        maximum number of iterations
        by default: maxiter=min(n,20)
    largest : boolean, optional
        when True, solve for the largest eigenvalues, otherwise the smallest
    verbosityLevel : integer, optional
        controls solver output.  default: verbosityLevel = 0.
    retLambdaHistory : boolean, optional
        whether to return eigenvalue history
    retResidualNormsHistory : boolean, optional
        whether to return history of residual norms

    Notes
    -----
    If both retLambdaHistory and retResidualNormsHistory are True, the
    return tuple has the following format
    (lambda, V, lambda history, residual norms history)

    """
    failureFlag = True
    import scipy.linalg as sla

    blockVectorX = X
    blockVectorY = Y
    residualTolerance = tol
    maxIterations = maxiter

    if blockVectorY is not None:
        sizeY = blockVectorY.shape[1]
    else:
        sizeY = 0

    # Block size.
    if len(blockVectorX.shape) != 2:
        raise ValueError('expected rank-2 array for argument X')

    n, sizeX = blockVectorX.shape
    if sizeX > n:
        raise ValueError('X column dimension exceeds the row dimension')

    A = makeOperator(A, (n,n))
    B = makeOperator(B, (n,n))
    M = makeOperator(M, (n,n))

    if (n - sizeY) < (5 * sizeX):
        #warn('The problem size is small compared to the block size.' \
        #        ' Using dense eigensolver instead of LOBPCG.')

        if blockVectorY is not None:
            raise NotImplementedError('symeig does not support constraints')

        if largest:
            lohi = (n - sizeX, n)
        else:
            lohi = (1, sizeX)

        A_dense = A(np.eye(n))

        if B is not None:
            B_dense = B(np.eye(n))
            _lambda, eigBlockVector = symeig(A_dense, B_dense, select=lohi )
        else:
            _lambda, eigBlockVector = symeig(A_dense, select=lohi )

        return _lambda, eigBlockVector

    if residualTolerance is None:
        residualTolerance = np.sqrt( 1e-15 ) * n

    maxIterations = min( n, maxIterations )

    if verbosityLevel:
        aux = "Solving "
        if B is None:
            aux += "standard"
        else:
            aux += "generalized"
        aux += " eigenvalue problem with"
        if M is None:
            aux += "out"
        aux += " preconditioning\n\n"
        aux += "matrix size %d\n" % n
        aux += "block size %d\n\n" % sizeX
        if blockVectorY is None:
            aux += "No constraints\n\n"
        else:
            if sizeY > 1:
                aux += "%d constraints\n\n" % sizeY
            else:
                aux += "%d constraint\n\n" % sizeY
        print aux

    ##
    # Apply constraints to X.
    if blockVectorY is not None:

        if B is not None:
            blockVectorBY = B( blockVectorY )
        else:
            blockVectorBY = blockVectorY

        # gramYBY is a dense array.
        gramYBY = sp.dot( blockVectorY.T, blockVectorBY )
        try:
            # gramYBY is a Cholesky factor from now on...
            gramYBY = sla.cho_factor( gramYBY )
        except:
            raise ValueError('cannot handle linearly dependent constraints')

        applyConstraints( blockVectorX, gramYBY, blockVectorBY, blockVectorY )

    ##
    # B-orthonormalize X.
    blockVectorX, blockVectorBX = b_orthonormalize( B, blockVectorX )

    ##
    # Compute the initial Ritz vectors: solve the eigenproblem.
    blockVectorAX = A( blockVectorX )
    gramXAX = sp.dot( blockVectorX.T, blockVectorAX )
    # gramXBX is X^T * X.
    gramXBX = sp.dot( blockVectorX.T, blockVectorX )

    _lambda, eigBlockVector = symeig( gramXAX )
    ii = np.argsort( _lambda )[:sizeX]
    if largest:
        ii = ii[::-1]
    _lambda = _lambda[ii]

    eigBlockVector = np.asarray( eigBlockVector[:,ii] )
    blockVectorX  = sp.dot( blockVectorX,  eigBlockVector )
    blockVectorAX = sp.dot( blockVectorAX, eigBlockVector )
    if B is not None:
        blockVectorBX = sp.dot( blockVectorBX, eigBlockVector )

    ##
    # Active index set.
    activeMask = np.ones( (sizeX,), dtype = np.bool )

    lambdaHistory = [_lambda]
    residualNormsHistory = []

    previousBlockSize = sizeX
    ident  = np.eye( sizeX, dtype = A.dtype )
    ident0 = np.eye( sizeX, dtype = A.dtype )

    ##
    # Main iteration loop.
    for iterationNumber in xrange( maxIterations ):
        if verbosityLevel > 0:
            print 'iteration %d' %  iterationNumber

        aux = blockVectorBX * _lambda[np.newaxis,:]
        blockVectorR = blockVectorAX - aux

        aux = np.sum( blockVectorR.conjugate() * blockVectorR, 0 )
        residualNorms = np.sqrt( aux )

        residualNormsHistory.append( residualNorms )

        ii = np.where( residualNorms > residualTolerance, True, False )
        activeMask = activeMask & ii
        if verbosityLevel > 2:
            print activeMask

        currentBlockSize = activeMask.sum()
        if currentBlockSize != previousBlockSize:
            previousBlockSize = currentBlockSize
            ident = np.eye( currentBlockSize, dtype = A.dtype )

        if currentBlockSize == 0:
            failureFlag = False # All eigenpairs converged.
            break

        if verbosityLevel > 0:
            print 'current block size:', currentBlockSize
            print 'eigenvalue:', _lambda
            print 'residual norms:', residualNorms
        if verbosityLevel > 10:
            print eigBlockVector

        activeBlockVectorR = as2d( blockVectorR[:,activeMask] )

        if iterationNumber > 0:
            activeBlockVectorP  = as2d( blockVectorP [:,activeMask] )
            activeBlockVectorAP = as2d( blockVectorAP[:,activeMask] )
            activeBlockVectorBP = as2d( blockVectorBP[:,activeMask] )

        if M is not None:
            # Apply preconditioner T to the active residuals.
            activeBlockVectorR = M( activeBlockVectorR )

        ##
        # Apply constraints to the preconditioned residuals.
        if blockVectorY is not None:
            applyConstraints( activeBlockVectorR,
                              gramYBY, blockVectorBY, blockVectorY )

        ##
        # B-orthonormalize the preconditioned residuals.

        aux = b_orthonormalize( B, activeBlockVectorR )
        activeBlockVectorR, activeBlockVectorBR = aux

        activeBlockVectorAR = A( activeBlockVectorR )

        if iterationNumber > 0:
            aux = b_orthonormalize( B, activeBlockVectorP,
                                    activeBlockVectorBP, retInvR = True )
            activeBlockVectorP, activeBlockVectorBP, invR = aux
            activeBlockVectorAP = sp.dot( activeBlockVectorAP, invR )

        ##
        # Perform the Rayleigh Ritz Procedure:
        # Compute symmetric Gram matrices:

        xaw = sp.dot( blockVectorX.T,       activeBlockVectorAR )
        waw = sp.dot( activeBlockVectorR.T, activeBlockVectorAR )
        xbw = sp.dot( blockVectorX.T,       activeBlockVectorBR )

        if iterationNumber > 0:
            xap = sp.dot( blockVectorX.T,       activeBlockVectorAP )
            wap = sp.dot( activeBlockVectorR.T, activeBlockVectorAP )
            pap = sp.dot( activeBlockVectorP.T, activeBlockVectorAP )
            xbp = sp.dot( blockVectorX.T,       activeBlockVectorBP )
            wbp = sp.dot( activeBlockVectorR.T, activeBlockVectorBP )

            gramA = np.bmat( [[np.diag( _lambda ),   xaw,  xap],
                              [             xaw.T,   waw,  wap],
                              [             xap.T, wap.T,  pap]] )

            gramB = np.bmat( [[ident0,    xbw,    xbp],
                              [ xbw.T,  ident,    wbp],
                              [ xbp.T,  wbp.T,  ident]] )
        else:
            gramA = np.bmat( [[np.diag( _lambda ),  xaw],
                              [             xaw.T,  waw]] )
            gramB = np.bmat( [[ident0,    xbw],
                              [ xbw.T,  ident]] )

        try:
            assert np.allclose( gramA.T, gramA )
        except:
            print gramA.T - gramA
            raise

        try:
            assert np.allclose( gramB.T, gramB )
        except:
            print gramB.T - gramB
            raise

        if verbosityLevel > 10:
            save( gramA, 'gramA' )
            save( gramB, 'gramB' )

        ##
        # Solve the generalized eigenvalue problem.
#        _lambda, eigBlockVector = la.eig( gramA, gramB )
        _lambda, eigBlockVector = symeig( gramA, gramB )
        ii = np.argsort( _lambda )[:sizeX]
        if largest:
            ii = ii[::-1]
        if verbosityLevel > 10:
            print ii

        _lambda = _lambda[ii].astype( np.float64 )
        eigBlockVector = np.asarray( eigBlockVector[:,ii].astype( np.float64 ) )

        lambdaHistory.append( _lambda )

        if verbosityLevel > 10:
            print 'lambda:', _lambda
##         # Normalize eigenvectors!
##         aux = np.sum( eigBlockVector.conjugate() * eigBlockVector, 0 )
##         eigVecNorms = np.sqrt( aux )
##         eigBlockVector = eigBlockVector / eigVecNorms[np.newaxis,:]
#        eigBlockVector, aux = b_orthonormalize( B, eigBlockVector )

        if verbosityLevel > 10:
            print eigBlockVector
            pause()

        ##
        # Compute Ritz vectors.
        if iterationNumber > 0:
            eigBlockVectorX = eigBlockVector[:sizeX]
            eigBlockVectorR = eigBlockVector[sizeX:sizeX+currentBlockSize]
            eigBlockVectorP = eigBlockVector[sizeX+currentBlockSize:]

            pp  = sp.dot( activeBlockVectorR, eigBlockVectorR )
            pp += sp.dot( activeBlockVectorP, eigBlockVectorP )

            app  = sp.dot( activeBlockVectorAR, eigBlockVectorR )
            app += sp.dot( activeBlockVectorAP, eigBlockVectorP )

            bpp  = sp.dot( activeBlockVectorBR, eigBlockVectorR )
            bpp += sp.dot( activeBlockVectorBP, eigBlockVectorP )
        else:
            eigBlockVectorX = eigBlockVector[:sizeX]
            eigBlockVectorR = eigBlockVector[sizeX:]

            pp  = sp.dot( activeBlockVectorR,  eigBlockVectorR )
            app = sp.dot( activeBlockVectorAR, eigBlockVectorR )
            bpp = sp.dot( activeBlockVectorBR, eigBlockVectorR )

        if verbosityLevel > 10:
            print pp
            print app
            print bpp
            pause()

        blockVectorX  = sp.dot( blockVectorX, eigBlockVectorX )  + pp
        blockVectorAX = sp.dot( blockVectorAX, eigBlockVectorX ) + app
        blockVectorBX = sp.dot( blockVectorBX, eigBlockVectorX ) + bpp

        blockVectorP, blockVectorAP, blockVectorBP = pp, app, bpp

    aux = blockVectorBX * _lambda[np.newaxis,:]
    blockVectorR = blockVectorAX - aux

    aux = np.sum( blockVectorR.conjugate() * blockVectorR, 0 )
    residualNorms = np.sqrt( aux )

    if verbosityLevel > 0:
        print 'final eigenvalue:', _lambda
        print 'final residual norms:', residualNorms

    if retLambdaHistory:
        if retResidualNormsHistory:
            return _lambda, blockVectorX, lambdaHistory, residualNormsHistory
        else:
            return _lambda, blockVectorX, lambdaHistory
    else:
        if retResidualNormsHistory:
            return _lambda, blockVectorX, residualNormsHistory
        else:
            return _lambda, blockVectorX

###########################################################################
if __name__ == '__main__':
    from scipy.sparse import spdiags, speye, issparse
    import time

##     def B( vec ):
##         return vec

    n = 100
    vals = [np.arange( n, dtype = np.float64 ) + 1]
    A = spdiags( vals, 0, n, n )
    B = speye( n, n )
#    B[0,0] = 0
    B = np.eye( n, n )
    Y = np.eye( n, 3 )

#    X = sp.rand( n, 3 )
    xfile = {100 : 'X.txt', 1000 : 'X2.txt', 10000 : 'X3.txt'}
    X = np.fromfile( xfile[n], dtype = np.float64, sep = ' ' )
    X.shape = (n, 3)

    ivals = [1./vals[0]]
    def precond( x ):
        invA = spdiags( ivals, 0, n, n )
        y = invA  * x
        if issparse( y ):
            y = y.toarray()

        return as2d( y )

    precond = spdiags( ivals, 0, n, n )
#    precond = None
    tt = time.clock()
#    B = None
    eigs, vecs = lobpcg( X, A, B, blockVectorY = Y,
                         M = precond,
                         residualTolerance = 1e-4, maxIterations = 40,
                         largest = False, verbosityLevel = 1 )
    print 'solution time:', time.clock() - tt

    print vecs
    print eigs