text:
namespace NVerify
{
  using System;
  using System.IO;
  using NUnit.Framework;
  using NVerify.Core;

  public static class MethodExtensions
  {
    /// <summary>
    /// Tests tha a Func<typeparamref name="T"></typeparamref> throws an exception.
    /// </summary>
    /// <typeparam name="T">Return type</typeparam>
    /// <param name="function">The function.</param>
    /// <param name="message">The message.</param>
    public static IVerifiable<Func<T>> ThrowsException<T>(
      this IAssertion<Func<T>> function,
      string message = "")
    {
      return new Verifiable<Func<T>>(function, target =>
              Assert.IsNotNull(target.GetThrownException(),
                              string.Format("The function should've not thrown an exception, but it did.\n{0}",
                                            message)));
    }

    /// <summary>
    /// Tests that an Action should throw an exception
    /// </summary>
    /// <param name="action">The action.</param>
    /// <param name="message">The message.</param>
    public static IVerifiable<Action> ThrowsException(
      this IAssertion<Action> action,
      string message = "")
    {
      return new Verifiable<Action>(action, target =>
      {
        Assert.IsNotNull(target.GetThrownException(), message);
      });
    }

    /// <summary>
    /// Tests tha a Func<typeparamref name="T"/> does not throw an exception.
    /// </summary>
    /// <typeparam name="T">Return type</typeparam>
    /// <param name="function">The function.</param>
    /// <param name="message">The message.</param>
    public static IVerifiable<Func<T>> DoesNotThrowException<T>(
      this IAssertion<Func<T>> function,
      string message = "")
    {
      return new Verifiable<Func<T>>(function, target =>
              Assert.IsNull(
                  target.GetThrownException(),
                  string.Format(
                    "The function should've not thrown an exception, but it did.\n{0}",
                    message)));
    }

    /// <summary>
    /// Tests that an Action should not throw an exception
    /// </summary>
    /// <param name="action">The action.</param>
    /// <param name="message">The message.</param>
    public static IVerifiable<Action> DoesNotThrowException(
      this IAssertion<Action> action,
      string message = "")
    {
      return new Verifiable<Action>(action, target =>
      {
        Assert.IsNull(target.GetThrownException(), message);
      });
    }

    /// <summary>
    /// Verifies that a methods writes exactly some output to console.
    /// </summary>
    /// <param name="assertion">The action assertion.</param>
    /// <param name="expectedWritten">The expected written message to console.</param>
    /// <param name="message">The message for the error.</param>
    /// <returns>The verification continuation</returns>
    public static IVerifiable<Action> WritesExactlyToConsole(
      this IAssertion<Action> assertion,
      string expectedWritten,
      string message = "")
    {
      return new Verifiable<Action>(assertion, target =>
      {

        StringWriter consoleOut = new StringWriter();
        Console.SetOut(consoleOut);
        target();
        string actualWritten = consoleOut.ToString();
        Console.SetOut(Console.Out);
        Assert.AreEqual(actualWritten,
                        expectedWritten,
                        message);
      });
    }

    /// <summary>
    /// Verifies that a methods does not write exactly some output to console.
    /// </summary>
    /// <param name="assertion">The action assertion.</param>
    /// <param name="expectedWritten">The expected message not written to console.</param>
    /// <param name="message">The message for the error.</param>
    /// <returns>The verification continuation</returns>
    public static IVerifiable<Action> DoesntWriteExactlyToConsole(
      this IAssertion<Action> assertion,
      string expectedWritten,
      string message = "")
    {
      return new Verifiable<Action>(assertion, target =>
      {

        StringWriter consoleOut = new StringWriter();
        Console.SetOut(consoleOut);
        target();
        string actualWritten = consoleOut.ToString();
        Console.SetOut(Console.Out);
        Assert.AreNotEqual(actualWritten,
                           expectedWritten,
                           message);
      });
    }

    /// <summary>
    /// Verifies that a methods writes exactly some output to console.
    /// </summary>
    /// <param name="assertion">The action assertion.</param>
    /// <param name="expectedWritten">The expected written message to console.</param>
    /// <param name="message">The message for the error.</param>
    /// <returns>The verification continuation</returns>
    public static IVerifiable<Action> WritesToConsole(
      this IAssertion<Action> assertion,
      string expectedWritten,
      string message = "")
    {
      return new Verifiable<Action>(assertion, target =>
      {

        StringWriter consoleOut = new StringWriter();
        Console.SetOut(consoleOut);
        target();
        string actualWritten = consoleOut.ToString();
        Console.SetOut(Console.Out);
        Assert.That(actualWritten,
                    Is.StringContaining(expectedWritten),
                    message);
      });
    }

    /// <summary>
    /// Verifies that a methods does not write some output to console.
    /// </summary>
    /// <param name="assertion">The action assertion.</param>
    /// <param name="expectedWritten">The written message not expected.</param>
    /// <param name="message">The message for the error.</param>
    /// <returns>The verification continuation</returns>
    public static IVerifiable<Action> DoesntWriteToConsole(
      this IAssertion<Action> assertion,
      string expectedWritten,
      string message = "")
    {
      return new Verifiable<Action>(assertion, target =>
      {

        StringWriter consoleOut = new StringWriter();
        Console.SetOut(consoleOut);
        target();
        string actualWritten = consoleOut.ToString();
        Console.SetOut(Console.Out);
        Assert.That(actualWritten,
                    Is.Not.StringContaining(expectedWritten),
                    message);
      });
    }

    /// <summary>
    /// Gets the exception thrown.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="function">The function.</param>
    /// <returns></returns>
    private static Exception GetThrownException<T>(this Func<T> function)
    {
      Exception x = null;
      try
      {
        function();
      }
      catch (Exception ex)
      {
        x = ex;
      }

      return x;
    }

    /// <summary>
    /// Gets the exception thrown.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="action">The action.</param>
    /// <returns></returns>
    private static Exception GetThrownException(this Action action)
    {
      Exception x = null;
      try
      {
        action();
      }
      catch (Exception ex)
      {
        x = ex;
      }

      return x;
    }
  }
}


text:
"use strict";

const useMin = require("../../../src/lib/use-min");

describe("useMin", () => {
  it('returns "" when isDebug is true', () => {
    expect(useMin(true)).toBe("");
  });

  it('returns ".min" when isDebug is false', () => {
    expect(useMin(false)).toBe(".min");
  });
});

redpajama_set_name: RedPajamaGithub


text:
/** @module "iterable-query/fn" */

import { assert, ToPossiblyAsyncIterable } from "../internal";
import { AsyncQueryable } from "../types";
import { Comparison, Comparer } from '@esfx/equatable';

/**
 * Gets the maximum element of an [[AsyncQueryable]], optionally comparing the keys of each element using the supplied callback.
 *
 * @param source An [[AsyncQueryable]] object.
 * @param keySelector A callback used to choose the key to compare.
 * @param keyComparer An optional callback used to compare the keys.
 * @category Scalar
 */
export async function maxByAsync<T, K>(source: AsyncQueryable<T>, keySelector: (value: T) => K, keyComparer: Comparison<K> | Comparer<K> = Comparer.defaultComparer): Promise<T | undefined> {
    if (typeof keyComparer === "function") keyComparer = Comparer.create(keyComparer);
    assert.mustBeAsyncQueryable<T>(source, "source");
    assert.mustBeFunction(keySelector, "keySelector");
    assert.mustBeComparer(keyComparer, "keyComparer");
    let hasResult = false;
    let result: T | undefined;
    let resultKey: K | undefined;
    for await (const element of ToPossiblyAsyncIterable(source)) {
        const key = keySelector(element);
        if (!hasResult) {
            result = element;
            resultKey = key;
            hasResult = true;
        }
        else if (keyComparer.compare(key, resultKey!) > 0) {
            result = element;
            resultKey = key;
        }
    }
    return result;
}


text:
import React          from "react"
import ReactTestUtils from "react-dom/test-utils"

import VerbdSelect from './VerbdSelect'

describe("VerbdSelect", () => {

    it("renders a VerbdSelect", () => {
        const tuRenderer = ReactTestUtils.createRenderer()
        const props = {}
        const noundSelect = tuRenderer.render(<VerbdSelect {...props} />)
    })

})


text: sendemail: https://github.com/gpepe/esp8266-sendemail


text:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    // 控件被按下时候的背景
    <item android:state_pressed="true" android:drawable="@drawable/table_selected" />
    // 控件被选择时候的背景
    <item android:state_selected="true" android:drawable="@drawable/table_selected"/>
    // 控件一般状态下的背景
    <item android:drawable="@drawable/table_normal"/>
</selector>


text:
import mapToFields from './mapToFields';
import DefineMap from 'can-define/map/map';
import Field from '../Field';

test('mapToFields', () => {
    const MyMap = DefineMap.extend({
        field1: 'string',
        field2: 'string'
    });

    const ExtendedMyMap = MyMap.extend({
        field3: 'number',
        field4: 'string'
    });

    const tests = [{
        test: mapToFields(MyMap),
        length: 2
    }, {
        test: mapToFields(new MyMap()),
        length: 2
    }, {
        test: mapToFields(ExtendedMyMap),
        length: 4
    }];
    tests.forEach((r) => {
        expect(r.test.length).toEqual(r.length);
        r.test.forEach((f) => {
            expect(f instanceof Field).toBeTruthy();
        });
    });
});


text:
ng.directive('ng-controller', ['$'], function ($) {
  return {
    priority: 10,
    terminal: true,
    scope: true,
    link: function (scope, el, attrs) {
      var tokens = attrs[this.name].split(' ');

      var controllerName = tokens[0];
      var scopeReference = tokens[2];

      if (scopeReference) scope[scopeReference] = scope;

      var controller = ng.controllers[controllerName];
      if (controller) controller.init(scope);

      scope.$controller = controllerName;

      el.children().each(function () {
        ng.compile(scope, $(this));
      });
    }
  };
});


text:
package org.tomighty.bus.messages.timer;

import org.tomighty.Phase;
import org.tomighty.time.Time;

public abstract class TimerStopped extends TimerEvent {

    protected TimerStopped(Time time, Phase phase) {
        super(time, phase);
    }

}


text:
namespace swift {

class ValueDecl;

namespace constraints {
  class ConstraintSystem;

/// The kind of overload choice.
enum class OverloadChoiceKind : int {
  /// The overload choice selects a particular declaration from a
  /// set of declarations.
  Decl,
  /// The overload choice selects a particular declaration that was
  /// found via dynamic lookup and, therefore, might not actually be
  /// available at runtime.
  DeclViaDynamic,
  /// The overload choice selects a key path subscripting operation.
  KeyPathApplication,
  /// The member is looked up using @dynamicMemberLookup.
  DynamicMemberLookup,
  /// The member with KeyPath parameter is looked up using
  /// @dynamicMemberLookup.
  KeyPathDynamicMemberLookup,
  /// The overload choice selects a particular declaration that
  /// was found by bridging the base value type to its Objective-C
  /// class type.
  DeclViaBridge,
  /// The overload choice selects a particular declaration that
  /// was found by unwrapping an optional context type.
  DeclViaUnwrappedOptional,
  /// The overload choice indexes into a tuple. Index zero will
  /// have the value of this enumerator, index one will have the value of this
  /// enumerator + 1, and so on. Thus, this enumerator must always be last.
  TupleIndex,
};

/// The kind of implicitly unwrapped optional for an overload reference.
enum class IUOReferenceKind : uint8_t {
  /// This overload references an IUO value which may be directly unwrapped.
  Value,

  /// This overload references a function, the return value of which may be
  /// unwrapped.
  ReturnValue,
};

/// Describes a particular choice within an overload set.
///
class OverloadChoice {
  enum : unsigned {
    /// Indicates that this is a normal "Decl" kind, or isn't a decl.
    IsDecl = 0x00,
    /// Indicates that this declaration was bridged, turning a
    /// "Decl" kind into "DeclViaBridge" kind.
    IsDeclViaBridge = 0x01,
    /// Indicates that this declaration was resolved by unwrapping an
    /// optional context type, turning a "Decl" kind into
    /// "DeclViaUnwrappedOptional".
    IsDeclViaUnwrappedOptional = 0x02,
    /// Indicates that there are viable members found on `Optional`
    /// type and its underlying type. And current overload choice
    /// is a backup one, which should be picked only if members
    /// found directly on `Optional` do not match.
    IsFallbackDeclViaUnwrappedOptional = 0x03,
    /// Indicates that this declaration was dynamic, turning a
    /// "Decl" kind into "DeclViaDynamic" kind.
    IsDeclViaDynamic = 0x07,
  };

  /// The base type to be used when referencing the declaration
  /// along with the three bits above.
  llvm::PointerIntPair<Type, 3, unsigned> BaseAndDeclKind;

  /// We mash together OverloadChoiceKind with tuple indices into a single
  /// integer representation.
  using OverloadChoiceKindWithTupleIndex =
      llvm::PointerEmbeddedInt<uint32_t, 29>;

  /// Depending on the OverloadChoiceKind, this could be one of two cases:
  /// 1) A ValueDecl for the cases that match to a Decl.  The exactly kind of
  ///    decl reference is disambiguated with the DeclKind bits in
  ///    BaseAndDeclKind.
  /// 2) An OverloadChoiceKindWithTupleIndex if this is an overload kind without
  ///    a decl (e.g., a BaseType, keypath, tuple, etc).
  ///
  llvm::PointerUnion<ValueDecl*, OverloadChoiceKindWithTupleIndex> DeclOrKind;

  /// If this OverloadChoice represents a DynamicMemberLookup result,
  /// then this holds the identifier for the original member being
  /// looked up, as well as 1 bit tag which identifies whether this
  /// choice represents a key-path based dynamic lookup.
  llvm::PointerIntPair<Identifier, 1, unsigned> DynamicMember;

  /// This holds the kind of function reference (Unapplied, SingleApply,
  /// DoubleApply, Compound).
  /// FIXME: This needs two bits. Can we pack them somewhere?
  FunctionRefKind TheFunctionRefKind;

public:
  OverloadChoice()
    : BaseAndDeclKind(nullptr, 0), DeclOrKind(),
      TheFunctionRefKind(FunctionRefKind::Unapplied) {}

  OverloadChoice(Type base, ValueDecl *value,
                 FunctionRefKind functionRefKind)
    : BaseAndDeclKind(base, 0),
      TheFunctionRefKind(functionRefKind) {
    assert(!base || !base->hasTypeParameter());
    assert((reinterpret_cast<uintptr_t>(value) & (uintptr_t)0x03) == 0 &&
           "Badly aligned decl");

    DeclOrKind = value;
  }

  OverloadChoice(Type base, OverloadChoiceKind kind)
      : BaseAndDeclKind(base, 0), DeclOrKind(uint32_t(kind)),
        TheFunctionRefKind(FunctionRefKind::Unapplied) {
    assert(base && "Must have a base type for overload choice");
    assert(!base->hasTypeParameter());
    assert(kind != OverloadChoiceKind::Decl &&
           kind != OverloadChoiceKind::DeclViaDynamic &&
           kind != OverloadChoiceKind::DeclViaBridge &&
           kind != OverloadChoiceKind::DeclViaUnwrappedOptional &&
           "wrong constructor for decl");
  }

  OverloadChoice(Type base, unsigned index)
      : BaseAndDeclKind(base, 0),
        DeclOrKind(uint32_t(OverloadChoiceKind::TupleIndex)+index),
        TheFunctionRefKind(FunctionRefKind::Unapplied) {
    assert(base->getRValueType()->is<TupleType>() && "Must have tuple type");
  }

  bool isInvalid() const {
    return BaseAndDeclKind.getPointer().isNull() &&
           BaseAndDeclKind.getInt() == 0 &&
           DeclOrKind.isNull() &&
           TheFunctionRefKind == FunctionRefKind::Unapplied;
  }

  /// Retrieve an overload choice for a declaration that was found via
  /// dynamic lookup.
  static OverloadChoice getDeclViaDynamic(Type base, ValueDecl *value,
                                          FunctionRefKind functionRefKind) {
    OverloadChoice result;
    result.BaseAndDeclKind.setPointer(base);
    result.BaseAndDeclKind.setInt(IsDeclViaDynamic);
    result.DeclOrKind = value;
    result.TheFunctionRefKind = functionRefKind;
    return result;
  }

  /// Retrieve an overload choice for a declaration that was found via
  /// bridging to an Objective-C class.
  static OverloadChoice getDeclViaBridge(Type base, ValueDecl *value,
                                         FunctionRefKind functionRefKind) {
    OverloadChoice result;
    result.BaseAndDeclKind.setPointer(base);
    result.BaseAndDeclKind.setInt(IsDeclViaBridge);
    result.DeclOrKind = value;
    result.TheFunctionRefKind = functionRefKind;
    return result;
  }

  /// Retrieve an overload choice for a declaration that was found
  /// by unwrapping an optional context type.
  ///
  /// \param isFallback Indicates that this result should be used
  /// as a backup, if member found directly on `Optional` doesn't
  /// match.
  static OverloadChoice
  getDeclViaUnwrappedOptional(Type base, ValueDecl *value, bool isFallback,
                              FunctionRefKind functionRefKind) {
    OverloadChoice result;
    result.BaseAndDeclKind.setPointer(base);
    result.BaseAndDeclKind.setInt(isFallback
                                      ? IsFallbackDeclViaUnwrappedOptional
                                      : IsDeclViaUnwrappedOptional);
    result.DeclOrKind = value;
    result.TheFunctionRefKind = functionRefKind;
    return result;
  }

  /// Retrieve an overload choice for a declaration that was found via
  /// dynamic member lookup. The `ValueDecl` is a `subscript(dynamicMember:)`
  /// method.
  static OverloadChoice getDynamicMemberLookup(Type base, ValueDecl *value,
                                               Identifier name,
                                               bool isKeyPathBased) {
    OverloadChoice result;
    result.BaseAndDeclKind.setPointer(base);
    result.DeclOrKind = value;
    result.DynamicMember.setPointer(name);
    result.DynamicMember.setInt(isKeyPathBased);
    result.TheFunctionRefKind = FunctionRefKind::SingleApply;
    return result;
  }

  /// Retrieve the base type used to refer to the declaration.
  Type getBaseType() const {
    return BaseAndDeclKind.getPointer();
  }

  /// Determines the kind of overload choice this is.
  OverloadChoiceKind getKind() const {
    if (!DynamicMember.getPointer().empty()) {
      return DynamicMember.getInt()
                 ? OverloadChoiceKind::KeyPathDynamicMemberLookup
                 : OverloadChoiceKind::DynamicMemberLookup;
    }

    if (DeclOrKind.is<ValueDecl*>()) {
      switch (BaseAndDeclKind.getInt()) {
      case IsDeclViaBridge: return OverloadChoiceKind::DeclViaBridge;
      case IsDeclViaDynamic: return OverloadChoiceKind::DeclViaDynamic;
      case IsDeclViaUnwrappedOptional:
      case IsFallbackDeclViaUnwrappedOptional:
        return OverloadChoiceKind::DeclViaUnwrappedOptional;
      default: return OverloadChoiceKind::Decl;
      }
    }
    uint32_t kind = DeclOrKind.get<OverloadChoiceKindWithTupleIndex>();
    if (kind >= (uint32_t)OverloadChoiceKind::TupleIndex)
      return OverloadChoiceKind::TupleIndex;

    return (OverloadChoiceKind)kind;
  }

  /// Determine whether this choice is for a declaration.
  bool isDecl() const {
    return DeclOrKind.is<ValueDecl*>();
  }

  /// Retrieve the declaration that corresponds to this overload choice.
  ValueDecl *getDecl() const {
    return DeclOrKind.get<ValueDecl*>();
  }

  /// Retrieves the declaration that corresponds to this overload choice, or
  /// \c nullptr if this choice is not for a declaration.
  ValueDecl *getDeclOrNull() const {
    return isDecl() ? getDecl() : nullptr;
  }

  /// Retrieve the type of implicitly unwrapped optional for a reference to this
  /// overload choice, or \c None if the choice is not for an IUO decl.
  Optional<IUOReferenceKind>
  getIUOReferenceKind(ConstraintSystem &cs,
                      bool forSecondApplication = false) const;

  bool isKeyPathDynamicMemberLookup() const {
    return getKind() == OverloadChoiceKind::KeyPathDynamicMemberLookup;
  }

  /// Determine whether this member is a backup in case
  /// members found directly on `Optional` didn't match.
  bool isFallbackMemberOnUnwrappedBase() const {
    return BaseAndDeclKind.getInt() == IsFallbackDeclViaUnwrappedOptional;
  }

  /// Whether this choice is for any kind of dynamic member lookup.
  bool isAnyDynamicMemberLookup() const {
    return getKind() == OverloadChoiceKind::DynamicMemberLookup ||
           isKeyPathDynamicMemberLookup();
  }

  /// Get the name of the overload choice.
  DeclName getName() const;

  /// Retrieve the tuple index that corresponds to this overload
  /// choice.
  unsigned getTupleIndex() const {
    assert(getKind() == OverloadChoiceKind::TupleIndex);
    uint32_t kind = DeclOrKind.get<OverloadChoiceKindWithTupleIndex>();
    return kind-(uint32_t)OverloadChoiceKind::TupleIndex;
  }

  /// Retrieves an opaque choice that ignores the base type.
  void *getOpaqueChoiceSimple() const {
    return DeclOrKind.getOpaqueValue();
  }

  FunctionRefKind getFunctionRefKind() const {
    assert(isDecl() && "only makes sense for declaration choices");
    return TheFunctionRefKind;
  }
};

} // end namespace constraints
} // end namespace swift

#endif // LLVM_SWIFT_SEMA_OVERLOADCHOICE_H


text:
var Q = require('q');
var Service = Utensils.Service;

describe('Service', function() {

  describe('#constructor', function(){

    it('executes the base constructor', function(){
      var baseConstructor = sinon.spy( Utensils.Base.prototype, 'constructor' );
      var service = new (Utensils.Service.extend({
        procedure: ['firstOperation', 'secondOperation'],
        firstOperation: function() { a = arguments[0]; return 'firstOperation'; },
        secondOperation: function() { b = arguments[0]; return 'secondOperation'; }
      }));

      expect(baseConstructor).to.have.been.calledOnce;
      baseConstructor.restore();
    });

  });

  describe('.procedure', function(){

    it('is required unless only one method is defined', function(){
      var createNewServiceWithoutMethods = function() {
        return new (Utensils.Service.extend());
      }

      var createNewServiceWithOneMethod = function() {
        return new (Utensils.Service.extend({
          firstOperation: function() {}
        }));
      }

      var createNewServiceWithMultipleMethods = function() {
        return new (Utensils.Service.extend({
          firstOperation: function() {},
          secondOperation: function() {},
        }));
      }

      expect( createNewServiceWithoutMethods ).to.throw( Error );
      expect( createNewServiceWithOneMethod ).to.not.throw( Error );
      expect( createNewServiceWithMultipleMethods ).to.throw( Error );
    });

  });

  describe('run', function(){

    it('calls the methods in the order defined', function( done ){
      var a, b, c;
      var service = new (Utensils.Service.extend({
        procedure: ['firstOperation', 'secondOperation'],
        firstOperation: function() { a = arguments[0]; return 'firstOperation'; },
        secondOperation: function() { b = arguments[0]; return 'secondOperation'; }
      }));

      service.run('initialValue').then(function(){
        c = arguments[0];

        expect(a).to.equal('initialValue');
        expect(b).to.equal('firstOperation');
        expect(c).to.equal('secondOperation');
        done();
      });
    });

    it('returns a promise', function(){
      var service = new (Utensils.Service.extend({
        firstOperation: function() {}
      }));

      expect( service.run() ).to.be.an.instanceOf( Q.makePromise );
    });

    it('fails if any error is thrown along the chain', function(){
      var b;
      var service = new (Utensils.Service.extend({
        procedure: ['firstOperation', 'secondOperation'],
        firstOperation: function() { throw new Error('first operation errored'); },
        secondOperation: function() {}
      }));

      return expect( service.run() ).to.eventually.be.rejectedWith(Error, 'first operation errored');
    });

    it('executes #error if defined', function( done ){
      var errorResult;
      var service = new (Utensils.Service.extend({
        procedure: ['firstOperation', 'secondOperation'],
        firstOperation: function() { throw new Error('first operation errored'); },
        secondOperation: function() {},
        error: function() { errorResult = arguments; }
      }));

      service.run().fin(function() {
        expect(errorResult[0]).to.be.instanceOf( Error, 'first operation errored' );
        done();
      })
    });

  });

});


text:
module ETL
  # The root directory of the etl code tree
  def ETL.root
    File.expand_path('../..', __FILE__)
  end
end

$LOAD_PATH.unshift(ETL.root + "/lib")

# Process our configuration files
require 'etl/config'

# Include the rest of code needed for ETL system
require 'etl/core'


text:
@implementation Snippet

-(instancetype)initWithSnippetString:(NSString *)snippetString{
    self = [super init];
    if (self) {

    }
    return self;
}

@end


text:
package com.github.vonnagy.service.container.listener

import com.github.vonnagy.service.container.service.ContainerService

/**
  * Created by alexsilva on 1/28/17.
  */
class TestContainerLifecycleListener extends ContainerLifecycleListener {
  override def onShutdown(container: ContainerService): Unit = {
    println("Listener onShutdown called.")
  }

  override def onStartup(container: ContainerService): Unit = {
    println("Listener onStartup called.")
  }
}


text:
#ifndef LEMON_FLOW_TERMINAL_DUMP_H
#define LEMON_FLOW_TERMINAL_DUMP_H

#include <string>
#include <iostream>
#include <iterator>

#include "copy.h"

namespace lemon {
    namespace flow {
        namespace terminal {

/// <summary>
/// Prints the stream elements to the <c>ostream</c> with the given delimeter between each element.
/// The output stream is returned.
/// </summary>
/// <param name="out">The output stream to print to.</param>
/// <param name="delimeter">The delimeter to add after each element, by default a single space is added.</param>
/// <returns>The <see cref="Terminal{F}"/> operation which print the stream elements to the output stream given.</returns>
auto dump(std::ostream& out = std::cout, const std::string& delimeter = " ") {
    return detail::make_terminal([&out, &delimeter](auto&& stream) -> std::ostream& {
        stream | copy(std::ostream_iterator<typename std::remove_reference_t<decltype(stream)>::value_type>(out, delimeter.c_str()));
        return out;
    });

}
        }
    }
}
#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>web</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>web</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 激活 Tomcat 的 defaultServlet 来处理静态文件, 另外一种方式在配置 mvc 容器的 web-servlet.xml 文件内采用 mvc 映射排除静态资源   -->
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/assets/*</url-pattern>
    </servlet-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
</web-app>


text:
import {Container} from 'flux/utils'
import TheirTeamView from '../views/TheirTeamView.js'
import {getStores, getState} from './utils.js'

export default Container.createFunctional(TheirTeamView, getStores, getState)


text:
namespace blink {

TestDictionaryDerivedImplementedAs::TestDictionaryDerivedImplementedAs() {
  setDerivedStringMemberWithDefault(String("default string value"));
}

TestDictionaryDerivedImplementedAs::~TestDictionaryDerivedImplementedAs() {}

TestDictionaryDerivedImplementedAs::TestDictionaryDerivedImplementedAs(const TestDictionaryDerivedImplementedAs&) = default;

TestDictionaryDerivedImplementedAs& TestDictionaryDerivedImplementedAs::operator=(const TestDictionaryDerivedImplementedAs&) = default;

bool TestDictionaryDerivedImplementedAs::hasDerivedStringMember() const {
  return !m_derivedStringMember.isNull();
}
String TestDictionaryDerivedImplementedAs::derivedStringMember() const {
  return m_derivedStringMember;
}
void TestDictionaryDerivedImplementedAs::setDerivedStringMember(String value) {
  m_derivedStringMember = value;
}
bool TestDictionaryDerivedImplementedAs::hasDerivedStringMemberWithDefault() const {
  return !m_derivedStringMemberWithDefault.isNull();
}
String TestDictionaryDerivedImplementedAs::derivedStringMemberWithDefault() const {
  return m_derivedStringMemberWithDefault;
}
void TestDictionaryDerivedImplementedAs::setDerivedStringMemberWithDefault(String value) {
  m_derivedStringMemberWithDefault = value;
}
bool TestDictionaryDerivedImplementedAs::hasRequiredLongMember() const {
  return m_hasRequiredLongMember;
}
int TestDictionaryDerivedImplementedAs::requiredLongMember() const {
  DCHECK(m_hasRequiredLongMember);
  return m_requiredLongMember;
}
void TestDictionaryDerivedImplementedAs::setRequiredLongMember(int value) {
  m_requiredLongMember = value;
  m_hasRequiredLongMember = true;
}
bool TestDictionaryDerivedImplementedAs::hasStringOrDoubleSequenceMember() const {
  return m_hasStringOrDoubleSequenceMember;
}
const HeapVector<StringOrDouble>& TestDictionaryDerivedImplementedAs::stringOrDoubleSequenceMember() const {
  DCHECK(m_hasStringOrDoubleSequenceMember);
  return m_stringOrDoubleSequenceMember;
}
void TestDictionaryDerivedImplementedAs::setStringOrDoubleSequenceMember(const HeapVector<StringOrDouble>& value) {
  m_stringOrDoubleSequenceMember = value;
  m_hasStringOrDoubleSequenceMember = true;
}

DEFINE_TRACE(TestDictionaryDerivedImplementedAs) {
  visitor->trace(m_stringOrDoubleSequenceMember);
  TestDictionary::trace(visitor);
}

}  // namespace blink


text:
{-# LANGUAGE ScopedTypeVariables  #-}
{-# LANGUAGE LambdaCase           #-}
{-# LANGUAGE DeriveFunctor        #-}
{-# LANGUAGE StandaloneDeriving   #-}
{-# LANGUAGE FlexibleContexts     #-}
{-# LANGUAGE UndecidableInstances #-}
module Language.Indent.PostParsing where

{-

  import           Data.Map (Map)
  import qualified Data.Map as M
  import           Data.Set (Set)
  import qualified Data.Set as S

  data PPEnv = PPEnv
             { boundVars  :: Map Variable ElemPos
             , freeVars   :: Map Variable ElemPos
             , opFixities :: Map Variable (Fixity ElemPos)
             , typeAnnots :: Map Variable (Type ElemPos)
             } deriving (Eq, Show)
  emptyPPEnv = PPEnv M.empty M.empty M.empty M.empty

  gatherDecls :: [Decl ElemPos] -> Decl PPEnv
  gatherDecls decls = foldr buildEnv emptyPPEnv decls
    where
      insertBoundVar :: Map Variable ElemPos -> (Variable, ElemPos) -> m (Map Variable ElemPos)
      insertBoundVar env (var, pos) = case M.lookup var env of
        Just pos' -> throwError $ errorBoundVarRedefined var pos' pos
        Nothing   -> return $ M.insert var pos env

      buildEnv (DeclFn lhs _ _ pos) env
        | FnArgs (Var var) = insertBoundVar bound

  foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b Source
  Monadic fold over the elements of a structure, associating to the right, i.e. from right to left.

        insertLookupWithKey ::
        Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> (Maybe a, Map k a) Source

        O(log n). Combines insert operation with old value retrieval. The expression (insertLookupWithKey f k x map) is a pair where the first element is equal to (lookup k map) and the second element equal to (insertWithKey f k x map).

      DeclFn (FnLhs a) (Expr a) [Decl a] a
                  | DeclTypeSig [Var a] (Type a) a
                  | DeclFixity  (Fixity a) a

  (a -> b -> b) -> b -> t a -> b

  {-
  (a -> b -> b) -> b -> t a -> b

  data Environment a = Environment
                     { annotations :: Map Variable (Type a)
                     , boundVars   :: Set Variable
                     , freeVars    :: Set Variable
                     , opDecls     :: Map Variable (Fixity a)
                     }

  --merge :: Environment a -> Environment a
  impossible = error "Confident Impossbility!"

  gatherEnv :: Environment a -> m (Environment a)
  gatherEnv decls = do
    let funcs  = concatMap gatherFunc   decls
    let annots = concatMap gatherAnnot  decls
    let fixity = concatMap gatherFixity decls
    boundVars'   <- buildBoundVars   funcs
    annotations' <- buildAnnotations annots
    opDecls      <- buildOpDecls     fixity
    return $ Environment boundVars' annotations S.empty opDecls
    where
      gatherFunc   (DeclFn lhs _ _ pos)
        | FnArgs (Var var _) _ _  <- lhs = [(var, pos)]
        | FnOp _ (Op op _) _ _    <- lhs = [(op, pos)]
      gatherFunc   _ = []
      gatherAnnots (DeclTypeSig vars ty pos) = map build vars
        where build var = (var, (ty, pos))
      gatherAnnots _ = []
      gatherFixity (DeclFixity x pos)

  findFuncs  (DeclFn lhs _ _ pos)
    | FnArgs (Var var _) _ _  <- lhs = (var, pos)
    | FnOp _ (Op op _) _ _    <- lhs = (op, pos)
  findFuncs  _                  = impossible
  findAnnots (DeclTypeSig vars ty pos) = map build vars
    where build var = (var, (ty, pos))
  findAnnots _                         = impossible
  findFixity
  --
  -- postParse :: forall a. [Decl a] -> [Decl (Environment a, a)]
  -- postParse =
  --   where
  --     processDecls :: [Decl a] -> [Decl (Environment a, a)]
  --     processDecls decls = let
  --       blockAnnots = filter (\case decls ->
  --         DeclTypeSig vars ty _ ->
  --           envWithAnnots $ M.fromList $ zip vars $ repeat ty
  --         _
  --       )
  -}
  --
-}


text:
from yowsup.common import YowConstants
from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity
from yowsup.structs import ProtocolTreeNode

class GetStatusesIqProtocolEntity(IqProtocolEntity):
    XMLNS = "status"

    def __init__(self, jids, _id = None):
        """
        Request the statuses of users. Should be sent once after login.

        Args:
            - jids: A list of jids representing the users whose statuses you are
                trying to get.
        """
        super(GetStatusesIqProtocolEntity, self).__init__(self.__class__.XMLNS, _id, _type = "get", to = YowConstants.WHATSAPP_SERVER)
        self.setGetStatusesProps(jids)

    def setGetStatusesProps(self, jids):
        assert type(jids) is list, "jids must be a list of jids"
        self.jids = jids

    def __str__(self):
        out = super(GetStatusesIqProtocolEntity, self).__str__()
        out += "Numbers: %s\n" % (",".join(self.numbers))
        return out

    def toProtocolTreeNode(self):
        users = [ProtocolTreeNode("user", {'jid': jid}) for jid in self.jids]

        node = super(GetStatusesIqProtocolEntity, self).toProtocolTreeNode()
        statusNode = ProtocolTreeNode("status", None, users)
        node.addChild(statusNode)

        return node

    @staticmethod
    def fromProtocolTreeNode(node):
        entity = IqProtocolEntity.fromProtocolTreeNode(node)
        entity.__class__ = GetStatusesIqProtocolEntity
        statusNode = node.getChild("status")
        userNodes = statusNode.getAllChildren()
        jids = [user['jid'] for user in userNodes]

        entity.setGetStatusesProps(jids)

        return entity


text:
% makeGridUniform Enforce uniform Image grid
%
%    >> object=makeGridUniform(object);
%
% See also Image
%

%
% created November 20, 2013 by Daniel Dolan (Sandia National Laboratories)
%
function object=makeGridUniform(object)

if object.Grid1Uniform && object.Grid2Uniform
    return
end

persistent AutoRegrid
if isempty(AutoRegrid)
    AutoRegrid=false;
elseif AutoRegrid
    object=regrid(object);
    return
end

% ask user to regrid
callstack=dbstack('-completenames');
name=callstack(2).name;

fig=SMASH.MUI.Dialog;
fig.Hidden=true;
fig.Name='Regrid object';

message=sprintf(...
    ['This object has a non-uniform grid, but the "%s" method requires a uniform grid. '...
    'Should the object be mapped onto a uniform grid?'],name);
message=textwrap({message},50);
addblock(fig,'Text',message);
button=addblock(fig,'Buttons',{' yes ',' no '});
choice='no';
set(button,'Callback',@PushButton)
    function PushButton(src,varargin)
        choice=strtrim(get(src,'String'));
        fig.Modal=false;
    end
addblock(fig,'CheckBox','Always regrid');

locate(fig,'center');
fig.Hidden=false;
fig.Modal=true;
waitfor(fig.Handle,'WindowStyle');

if strcmpi(choice,'no')
    delete(fig);
    error('ERROR: uniform grid required');
end
object=regrid(object);

choice=probe(fig);
AutoRegrid=logical(choice{1});
delete(fig);

end


text:
package com.amazonservices.mws.orders.samples;

import java.util.*;
import javax.xml.datatype.XMLGregorianCalendar;

import com.amazonservices.mws.client.*;

/** Sample call for ListOrders. */
public class ListOrdersSample {

    /**
     * Call the service, log response and exceptions.
     *
     * @param client
     * @param request
     *
     * @return The response.
     */
    public static com.amazonservices.mws.orders.model.ListOrdersResponse invokeListOrders(
            com.amazonservices.mws.orders.MarketplaceWebServiceOrders client,
            com.amazonservices.mws.orders.model.ListOrdersRequest request) {
        try {
            // Call the service.
            com.amazonservices.mws.orders.model.ListOrdersResponse response = client.listOrders(request);
            com.amazonservices.mws.orders.model.ResponseHeaderMetadata rhmd = response.getResponseHeaderMetadata();
            // We recommend logging every the request id and timestamp of every call.
            System.out.println("Response:");
            System.out.println("RequestId: "+rhmd.getRequestId());
            System.out.println("Timestamp: "+rhmd.getTimestamp());
            String responseXml = response.toXML();
            System.out.println(responseXml);
            return response;
        } catch (com.amazonservices.mws.orders.MarketplaceWebServiceOrdersException ex) {
            // Exception properties are important for diagnostics.
            System.out.println("Service Exception:");
            com.amazonservices.mws.orders.model.ResponseHeaderMetadata rhmd = ex.getResponseHeaderMetadata();
            if(rhmd != null) {
                System.out.println("RequestId: "+rhmd.getRequestId());
                System.out.println("Timestamp: "+rhmd.getTimestamp());
            }
            System.out.println("Message: "+ex.getMessage());
            System.out.println("StatusCode: "+ex.getStatusCode());
            System.out.println("ErrorCode: "+ex.getErrorCode());
            System.out.println("ErrorType: "+ex.getErrorType());
            throw ex;
        }
    }

    /**
     *  Command line entry point.
     */
    public static void main(String[] args) {

        // Get a client connection.
        // Make sure you've set the variables in MarketplaceWebServiceOrdersSampleConfig.
        com.amazonservices.mws.orders.MarketplaceWebServiceOrdersClient client = MarketplaceWebServiceOrdersSampleConfig.getClient();

        // Create a request.
        com.amazonservices.mws.orders.model.ListOrdersRequest request = new com.amazonservices.mws.orders.model.ListOrdersRequest();
        String sellerId = "example";
        request.setSellerId(sellerId);
        String mwsAuthToken = "example";
        request.setMWSAuthToken(mwsAuthToken);
        XMLGregorianCalendar createdAfter = MwsUtl.getDTF().newXMLGregorianCalendar();
        request.setCreatedAfter(createdAfter);
        XMLGregorianCalendar createdBefore = MwsUtl.getDTF().newXMLGregorianCalendar();
        request.setCreatedBefore(createdBefore);
        XMLGregorianCalendar lastUpdatedAfter = MwsUtl.getDTF().newXMLGregorianCalendar();
        request.setLastUpdatedAfter(lastUpdatedAfter);
        XMLGregorianCalendar lastUpdatedBefore = MwsUtl.getDTF().newXMLGregorianCalendar();
        request.setLastUpdatedBefore(lastUpdatedBefore);
        List<String> orderStatus = new ArrayList<String>();
        request.setOrderStatus(orderStatus);
        List<String> marketplaceId = new ArrayList<String>();
        request.setMarketplaceId(marketplaceId);
        List<String> fulfillmentChannel = new ArrayList<String>();
        request.setFulfillmentChannel(fulfillmentChannel);
        List<String> paymentMethod = new ArrayList<String>();
        request.setPaymentMethod(paymentMethod);
        String buyerEmail = "example";
        request.setBuyerEmail(buyerEmail);
        String sellerOrderId = "example";
        request.setSellerOrderId(sellerOrderId);
        Integer maxResultsPerPage = 1;
        request.setMaxResultsPerPage(maxResultsPerPage);
        List<String> tfmShipmentStatus = new ArrayList<String>();
        request.setTFMShipmentStatus(tfmShipmentStatus);

        // Make the call.
        ListOrdersSample.invokeListOrders(client, request);

    }

}


text:
package controller.similarity;

import java.io.Serializable;

import org.apache.log4j.Logger;

import interfaces.SimilarityInterface;
import model.DataModel;
import run.Configuration;

/**
 * This class is responsible for creating relative {@link SimilairityRepository} based on the given {@link Configuration}
 *
 * @author FBM
 */
public final class SimilarityRepository implements SimilarityInterface,Serializable {

    /**
	 * Unique id used for serialization
	 */
	private static final long serialVersionUID = -1351308470553215704L;
	/**
     * Logger for this class
     */
    private static final Logger LOG = Logger.getLogger(SimilarityRepository.class.getCanonicalName());
    private final SimilarityInterface similairtyRepository;
    private final Configuration configuration;

    /**
     * Constructor
     * @param trainData
     * @param configuration
     */
    public SimilarityRepository(final DataModel trainData, final Configuration configuration) {
	if (trainData == null) {
	    throw new IllegalArgumentException("Train data model is null");
	}
	if (configuration == null) {
	    throw new IllegalArgumentException("Configuration is null");
	}
	this.configuration = configuration;

	if (configuration.isUseLowLevel() && configuration.isUseGenre()) {
	    similairtyRepository = new LowLevelGenreSimilarityRepository(trainData);
	} else if (configuration.isUseTag()) {
	    similairtyRepository = new TagSimilarityRepository(trainData);
	} else if (configuration.isUseLowLevel()) {
	    similairtyRepository = new LowLevelSimilarityRepository(trainData);
	} else if (configuration.isUseGenre()) {
	    similairtyRepository = new GenreSimilarityRepository(trainData);
	} else if (configuration.isUseRating()) {
	    similairtyRepository = new RatingSimilarityRepository(trainData);
	} else {
	    LOG.warn("Default similairty repository is selected");
	    similairtyRepository = new RatingSimilarityRepository(trainData);
	}
    }

    /*
     * @see interfaces.SimilarityInterface#getItemSimilairty(int, int)
     */
    @Override
    public Float getItemSimilairty(final int itemId1, final int itemId2) {
	return this.similairtyRepository.getItemSimilairty(itemId1, itemId2);
    }

    /**
     * @return The configuration
     */
    public final Configuration getConfiguration() {
	return configuration;
    }

}


text:
package org.apache.sling.settings.impl;

import java.util.Dictionary;
import java.util.Hashtable;

import org.apache.sling.launchpad.api.StartupHandler;
import org.apache.sling.settings.SlingSettingsService;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;

/**
 * The ServicesListener listens for the required services
 * and registers the settings service once all required services are
 * available
 */
public class ServicesListener {

    /** The bundle context. */
    private final BundleContext bundleContext;

    /** The listener for the startup handler. */
    private final Listener startupListener;

    /** The listener for configuration admin. */
    private ConfigAdminListener configAdminListener;

    /** The listener for the shell. */
    private ShellListener shellListener;

    /** The registration of the settings service. */
    private ServiceRegistration settingsReg;

    /**
     * Start listeners
     */
    public ServicesListener(final BundleContext bundleContext) {
        this.bundleContext = bundleContext;
        this.startupListener = new Listener(StartupHandler.class.getName());
        this.startupListener.start();
    }

    /**
     * Notify of service changes from the listeners.
     * If all services are available, register listener and pass resources
     * to the OSGi installer.
     */
    public synchronized void notifyChange() {
        // check if all services are available
        final StartupHandler handler = (StartupHandler)this.startupListener.getService();
        if ( handler != null && this.settingsReg == null ) {
            this.activate(handler);
        }
    }

    private void activate(final StartupHandler handler) {
        final SlingSettingsServiceImpl settingsService = new SlingSettingsServiceImpl(bundleContext, handler);

        final Dictionary<String, String> props = new Hashtable<String, String>();
        props.put(Constants.SERVICE_DESCRIPTION,
            "Apache Sling Settings Service");
        props.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation");
        this.settingsReg = bundleContext.registerService(new String[] {
                                               SlingSettingsService.class.getName()},
                                               settingsService, props);
        SlingPropertiesPrinter.initPlugin(bundleContext);
        SlingSettingsPrinter.initPlugin(bundleContext, settingsService);

        // add config admin support
        this.configAdminListener = new ConfigAdminListener(settingsService);
        this.configAdminListener.start();

        // add shell support
        this.shellListener = new ShellListener(settingsService);
        this.shellListener.start();
    }

    /**
     * Deactivate this listener.
     */
    public void deactivate() {
        if ( this.shellListener != null ) {
            this.shellListener.deactivate();
            this.shellListener = null;
        }
        if ( this.configAdminListener != null ) {
            this.configAdminListener.deactivate();
            this.configAdminListener = null;
        }
        this.startupListener.deactivate();
        if ( this.settingsReg != null ) {
            this.settingsReg.unregister();
            this.settingsReg = null;
        }

        SlingSettingsPrinter.destroyPlugin();
        SlingPropertiesPrinter.destroyPlugin();
    }

    /**
     * Helper class listening for service events for a defined service.
     */
    private abstract class AbstractListener implements ServiceListener {

        /** The name of the service. */
        private final String serviceName;

        /** The service reference. */
        private volatile ServiceReference reference;

        /** The service. */
        private volatile Object service;

        /**
         * Constructor
         */
        public AbstractListener(final String serviceName) {
            this.serviceName = serviceName;
        }

        /**
         * Start the listener.
         * First register a service listener and then check for the service.
         */
        public void start() {
            try {
                bundleContext.addServiceListener(this, "("
                        + Constants.OBJECTCLASS + "=" + serviceName + ")");
            } catch (final InvalidSyntaxException ise) {
                // this should really never happen
                throw new RuntimeException("Unexpected exception occured.", ise);
            }
            this.retainService();
        }

        /**
         * Unregister the listener.
         */
        public void deactivate() {
            bundleContext.removeServiceListener(this);
        }

        /**
         * Return the service (if available)
         */
        public synchronized Object getService() {
            return this.service;
        }

        /**
         * Try to get the service and notify the change.
         */
        private synchronized void retainService() {
            if ( this.reference == null ) {
                this.reference = bundleContext.getServiceReference(this.serviceName);
                if ( this.reference != null ) {
                    this.service = bundleContext.getService(this.reference);
                    if ( this.service == null ) {
                        this.reference = null;
                    } else {
                        serviceChanged();
                    }
                }
            }
        }

        /**
         * Try to release the service and notify the change.
         */
        private synchronized void releaseService() {
            if ( this.reference != null ) {
                this.service = null;
                bundleContext.ungetService(this.reference);
                this.reference = null;
                serviceChanged();
            }
        }

        /**
         * @see org.osgi.framework.ServiceListener#serviceChanged(org.osgi.framework.ServiceEvent)
         */
        public void serviceChanged(ServiceEvent event) {
            if (event.getType() == ServiceEvent.REGISTERED) {
                this.retainService();
            } else if ( event.getType() == ServiceEvent.UNREGISTERING ) {
                this.releaseService();
            }
        }

        protected abstract void serviceChanged();
    }

    /**
     * Helper class listening for service events for a defined service.
     */
    private final class Listener extends AbstractListener {

        /**
         * Constructor
         */
        public Listener(final String serviceName) {
            super(serviceName);
        }

        @Override
        protected void serviceChanged() {
            notifyChange();
        }
    }

    /**
     * Helper class listening for service events for config admin
     */
    private final class ConfigAdminListener extends AbstractListener {

        private Object settingsServiceConfigurator;

        private final SlingSettingsServiceImpl settings;

        /**
         * Constructor
         */
        public ConfigAdminListener(final SlingSettingsServiceImpl settings) {
            super("org.osgi.service.cm.ConfigurationAdmin");
            this.settings = settings;
        }

        @Override
        protected void serviceChanged() {
            if ( this.getService() != null && this.settingsServiceConfigurator == null ) {
                this.settingsServiceConfigurator = new SettingsServiceConfigurator(bundleContext, settings);
            }
        }

        @Override
        public void deactivate() {
            super.deactivate();
            if ( settingsServiceConfigurator != null ) {
                ((SettingsServiceConfigurator)settingsServiceConfigurator).destroy();
                settingsServiceConfigurator = null;
            }
        }

    }

    /**
     * Helper class listening for service events for config admin
     */
    private final class ShellListener extends AbstractListener {

        private Object runModeCommand;

        private final SlingSettingsServiceImpl settings;

        /**
         * Constructor
         */
        public ShellListener(final SlingSettingsServiceImpl settings) {
            super("org.apache.felix.shell.ShellService");
            this.settings = settings;
        }

        @Override
        protected void serviceChanged() {
            if ( this.getService() != null && this.runModeCommand == null ) {
                this.runModeCommand = new RunModeCommand(bundleContext, settings.getRunModes());
            }
        }

        @Override
        public void deactivate() {
            super.deactivate();
            if ( runModeCommand != null ) {
                ((RunModeCommand)runModeCommand).destroy();
                runModeCommand = null;
            }
        }

    }
}


text:
import bus from './eventBus';
import logger from './logger';

let errors = [];
bus.on("error", (msg)=>{
    errors.push(msg);
    //logger.error("ERROR::"+msg);
});

export default function error(message){
    errors.push(message);
    bus.emit("error", message);
}

export function doesErrorExist(msg){
    return errors.includes(msg);
}


text:
package unluac.decompile.branch

import unluac.decompile.Registers
import unluac.decompile.expression.BinaryExpression
import unluac.decompile.expression.Expression

case class OrBranch(left: Branch, right: Branch) extends Branch(right.line, right.begin, right.end) {

  def invert: Branch = {
    new AndBranch(left.invert, right.invert)
  }

  def getRegister: Int = {
    val rleft: Int = left.getRegister
    val rright: Int = right.getRegister
    if (rleft == rright) rleft else -1
  }

  def asExpression(r: Registers): Expression = {
    new BinaryExpression("or", left.asExpression(r), right.asExpression(r), Expression.PRECEDENCE_OR, Expression.ASSOCIATIVITY_NONE)
  }

  def useExpression(expression: Expression) {
    left.useExpression(expression)
    right.useExpression(expression)
  }
}


text:
===================
Admin Customization
===================

Mezzanine uses the standard `Django admin interface
<http://docs.djangoproject.com/en/dev/ref/contrib/admin/>`_ allowing you to
add admin classes as you normally would with a Django project, but also
provides the following enhancements to the admin interface that are
configurable by the developer.

Navigation
==========

When first logging into the standard Django admin interface a user is
presented with the list of models that they have permission to modify data
for. Mezzanine takes this feature and uses it to provide a navigation menu
that persists across every section of the admin interface making the list
of models always accessible.

Using the standard Django admin the grouping and ordering of these models
aren't configurable, so Mezzanine provides the setting
``ADMIN_MENU_ORDER`` that can be used to control the grouping and
ordering of models when listed in the admin area.

This setting is a sequence of pairs where each pair represents a group of
models. The first item in each pair is the name to give the group and the
second item is the sequence of app/model names to use for the group. The
ordering of both the groups and their models is maintained when they are
displayed in the admin area.

For example, to specify two groups ``Content`` and ``Site`` in your admin
with the first group containing models from Mezzanine's ``pages`` and
``blog`` apps, and the second with the remaining models provided by Django,
you would define the following in your projects's ``settings`` module::

    ADMIN_MENU_ORDER = (
        ("Content", ("pages.Page", "blog.BlogPost", "blog.Comment",)),
        ("Site", ("auth.User", "auth.Group", "sites.Site", "redirects.Redirect")),
    )

Any admin classes that aren't specifed are included using Django's normal
approach of grouping models alphabetically by application name.

Custom Items
============

It is possible to inject custom navigation items into the
``ADMIN_MENU_ORDER`` setting by specifying an
item using a two item sequence, the first item containing the title and
second containing the named urlpattern that resolves to the url to be used.

Continuing on from the previous example, Mezzanine includes a fork of the
popular `django-filebrowser <http://code.google.com/p/django-filebrowser/>`_
application which contains a named urlpattern ``fb_browse`` and is given
the title ``Media Library`` to create a custom navigation item::

    ADMIN_MENU_ORDER = (
        ("Content", ("pages.Page", "blog.BlogPost", "blog.Comment",
            ("Media Library", "fb_browse"),)),
        ("Site", ("auth.User", "auth.Group", "sites.Site", "redirects.Redirect")),
    )

You can also use this two-item sequence approach for regular app/model
names if you'd like to give them a custom title.

Dashboard
=========

When using the standard Django admin interface, the dashboard area shown
when a user first logs in provides the list of available models and a list
of the user's recent actions. Mezzanine makes this dashboard configurable
by the developer by providing a system for specifying Django `Inclusion Tags
<http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags>`_
that will be displayed in the dashboard area.

The dashboard area is broken up into three columns, the first being wide and
the second and third being narrow. Mezzanine then provides the setting
``DASHBOARD_TAGS`` which is a sequence of three sequences - one for
each the three columns. Each sequence contains the names of the inclusion
tags in the format ``tag_lib.tag_name`` that will be rendered in each of the
columns .

The list of models and recent actions normally found in the Django admin are
available as inclusion tags via ``mezzanine_tags.app_list`` and
``mezzanine_tags.recent_actions`` respectively. For example, to configure the
dashboard with a blog form above the model list in
the first column, a list of recent comments in the second column and the
recent actions list in the third column, you would define the following in
your projects's ``settings`` module::

    DASHBOARD_TAGS = (
        ("blog_tags.quick_blog", "mezzanine_tags.app_list"),
        ("comment_tags.recent_comments",),
        ("mezzanine_tags.recent_actions",),
    )

Here we can see the ``quick_blog`` inclusion tag provided by the
``mezzanine.blog.templatetags.blog_tags`` module and the
``recent_comments`` inclusion tag provided by the
``mezzanine.generic.templatetags.comment_tags`` module.

WYSIWYG Editor
==============

By default, Mezzanine uses the
`TinyMCE editor <http://tinymce.moxiecode.com/>`_ to provide rich
editing for all model fields of the type
``mezzanine.core.fields.RichTextField``. The setting ``RICHTEXT_WIDGET_CLASS``
contains the import path to the widget class that will be used for
editing each of these fields, which therefore provides the ability for
implementing your own editor widget which could be a modified version
of TinyMCE, a different editor or even no editor at all.

.. note::

    If you'd only like to customize the TinyMCE options specified in its
    JavaScript setup, you can do so via the ``TINYMCE_SETUP_JS`` setting
    which lets you specify the URL to your own TinyMCE setup JavaScript
    file.

The default value for the ``RICHTEXT_WIDGET_CLASS`` setting is the
string ``"mezzanine.core.forms.TinyMceWidget"``. The ``TinyMceWidget``
class referenced here provides the necessary media files and HTML for
implementing the TinyMCE editor, and serves as a good reference point
for implementing your own widget class which would then be specified
via the ``RICHTEXT_WIDGET_CLASS`` setting.

In addition to ``RICHTEXT_WIDGET_CLASS`` you may need to customize the
way your content is rendered at the template level. Post processing of
the content can be achieved through the ``RICHTEXT_FILTERS`` setting,
which is a sequence of string, each one containing the dotted path to
a Python function, that will be used as a processing pipeline for the
content. Think of them like Django's middleware or context processors.

Say, for example, you had a ``RICHTEXT_WIDGET_CLASS`` that allowed you
to write your content in a popular wiki syntax such as markdown. You'd
need a way to convert that wiki syntax into HTML right before the
content was rendered::

    # ... in myproj.filter
    from markdown import markdown

    def markdown_filter(content):
        """
        Converts markdown formatted content to html
        """
        return markdown(content)

    # ... in myproj.settings
    RICHTEXT_FILTERS = (
        "myproj.filter.markdown_filter",
    )

With the above, you'd now see the converted HTML content rendered to
the template, rather than the raw markdown formatting.

Media Library Integration
=========================

Mezzanine's Media Library (based on django-filebrowser) provides a
`jQuery UI <http://jqueryui.com/>`_ `dialog <http://jqueryui.com/dialog/>`_ that can be used by custom widgets to allow users to select previously
uploaded files.

When using a custom widget for the WYSIWYG editor via the
``RICHTEXT_WIDGET_CLASS`` setting, you can show the Media Library dialog
from your custom widget, by doing the following:

1. Load the following media resources in your widget, perhaps using a
   `Django Media inner class
   <https://docs.djangoproject.com/en/dev/topics/forms/media/>`_:

   :css:
      ``filebrowser/css/smoothness/jquery-ui-1.9.1.custom.min.css``
   :js:
      | ``mezzanine/js/%s' % settings.JQUERY_FILENAME``
      | ``filebrowser/js/jquery-ui-1.9.1.custom.min.js``
      | ``filebrowser/js/filebrowser-popup.js``

2. Call the JavaScript function ``browseMediaLibrary`` to show the
   dialog. The function is defined in
   ``filebrowser/js/filebrowser-popup.js``, and takes the following
   two arguments:

   :Callback function:
      The function that will be called after the dialog is closed. The
      function will be called with a single argument, which will be:

      - null: if no selection was made (e.g. dialog is closed by
        hitting `ESC`), or
      - the path of the selected file.

   :Type (optional): Type of files that are selectable in the
      dialog. Defaults to image.


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebFeedReader.Models;
using WebFeedReader.Services;
using WebFeedReader.ViewModels;
using static WebFeedReader.Persistence.OrderByDescription<object>;

namespace WebFeedReader.Controllers
{
    public class HomeController : Controller
    {
        private readonly IFeedService feedService;

        public HomeController(IFeedService feedService)
        {
            this.feedService = feedService;
        }

        public ActionResult Index(long? selectedFeedId, long? selectedFeedItemId)
        {
            Feed selectedFeed;
            IEnumerable<FeedItem> filteredFeedItems;
            FeedItem selectedFeedItem;

            if (selectedFeedId == null)
            {
                selectedFeed = null;
                filteredFeedItems = feedService.GetAllFeedItems(
                    Ord<FeedItem>(fi => fi.PublishedOn, ListSortDirection.Descending));
            }
            else
            {
                selectedFeed = feedService.FindFeedById((long)selectedFeedId);

                if (selectedFeed == null)
                {
                    return HttpNotFound();
                }

                filteredFeedItems = feedService.GetFeedItemsInFeed(
                    selectedFeed, Ord<FeedItem>(fi => fi.PublishedOn, ListSortDirection.Descending));
            }

            if (selectedFeedItemId == null)
            {
                selectedFeedItem = filteredFeedItems.FirstOrDefault();
            }
            else
            {
                selectedFeedItem = feedService.FindFeedItemById((long)selectedFeedItemId);

                if (selectedFeedItem == null)
                {
                    return HttpNotFound();
                }
            }

            MainFeedDisplayViewModel vm = new MainFeedDisplayViewModel(
                feedService.GetAllFeeds(),
                filteredFeedItems,
                selectedFeed,
                selectedFeedItem
            );

            return View(vm);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}


text:
.. image:: _static/pymatgen.png
   :width: 300 px
   :alt: pymatgen
   :align: center

============
Introduction
============

.. image:: https://github.com/materialsproject/pymatgen/actions/workflows/test.yml/badge.svg
      :alt: CI Status
      :target: https://github.com/materialsproject/pymatgen/actions/workflows/test.yml

.. image:: https://anaconda.org/conda-forge/pymatgen/badges/downloads.svg

.. image:: https://coveralls.io/repos/github/materialsproject/pymatgen/badge.svg?branch=master
      :alt: Coveralls Coverage Report
      :target: https://coveralls.io/github/materialsproject/pymatgen?branch=master

Pymatgen (Python Materials Genomics) is a robust, open-source Python library
for materials analysis. These are some of the main features:

1. Highly flexible classes for the representation of Element, Site, Molecule,
   Structure objects.
2. Extensive input/output support, including support for VASP
   (http://cms.mpi.univie.ac.at/vasp/), ABINIT (http://www.abinit.org/), CIF,
   Gaussian, XYZ, and many other file formats.
3. Powerful analysis tools, including generation of phase diagrams, Pourbaix
   diagrams, diffusion analyses, reactions, etc.
4. Electronic structure analyses, such as density of states and band structure.
5. Integration with the Materials Project REST API, Crystallography Open
   Database and other external data sources.

As of 2022, pymatgen only supports Python 3.8 and above. Our support schedule follows closely that of the Scientific
Python software stack, i.e., when packages such as numpy drops support for Python versions, we will drop support for
newer versions. Similarly, support for new Python versions will be adopted only when most of the core dependencies
support the new Python versions.

Pymatgen is free to use. However, we also welcome your help to improve this library by making your own contributions.
These contributions can be in the form of additional tools or modules you develop, or feature requests and bug
reports. The following are resources for pymatgen:

* `Official documentation <http://pymatgen.org>`_
* Offline docs: HTML are in the pymatgen Github repo's `docs` folder. `Dash <http://kapeli.com/dash>`_ or
  `Zeal <http://zealdocs.org/>`_ docs can be searched and downloaded from "User Contributed Docsets".
* Bug reports or feature requests: Please submit a `GitHub Issue <http://github.com/materialsproject/pymatgen/issues>`_.
* Code contributions via `pull requests <https://github.com/materialsproject/pymatgen/pulls>`_ welcome.
* For help with usage that are unrelated to bugs or feature requests, please use the pymatgen `Discourse page
  <https://discuss.matsci.org/c/pymatgen>`_.
* `matgenb <http://matgenb.materialsvirtuallab.org>`_ provides some Jupyter notebooks demonstrating functionality.
* Follow us on `Twitter <http://twitter.com/pymatgen>`_ to get news and tips.

    *The code is mightier than the pen.*

Major Announcement (v2022.0.*)
==============================

A **backwards incompatible** change has been introduced in v2022.0.*. Pymatgen root-level convenience imports have been
removed from in preparation for a change to a more modular, extensible namespace package architecture that will allow
more developers to contribute. If your existing code uses `from pymatgen import <something>`, you will need to make
modifications. MPRester should now be imported from `pymatgen.ext.matproj`. All other convenience objects such as
`Element`, `Species`, `Lattice`, `Structure`, etc. should be imported from `pymatgen.core`. There are a few simple ways
you can respond to this change:

* To migrate your code to be compatible with v2022.0.* (it will still be compatible with pymatgen<2022.0.0 since all
  the imports were already available in previous versions), you need to replace all instances of
  `from pymatgen import MPRester` with `from pymatgen.ext.matproj import MPRester`, followed by replacing all instances
  of `from pymatgen import` with `from pymatgen.core import`. These two steps have to be done in that sequence, since
  MPRester and the other core imports exist in different subpackages. The easiest way is to use an IDE such
  as Pycharm to run a `Replace in Files` on the root directory of your code.
* The pymatgen maintainers have also come up with the following terminal commands you can use to perform the migration.
  On a Mac::

    find . -name '*.py' | xargs sed -i "" 's/from pymatgen import MPRester/from pymatgen.ext.matproj import MPRester/g'
    find . -name '*.py' | xargs sed -i "" 's/from pymatgen import/from pymatgen.core import/g'

  On Linux::

    find . -name '*.py' | xargs sed -i 's/from pymatgen import MPRester/from pymatgen.ext.matproj import MPRester/g'
    find . -name '*.py' | xargs sed -i 's/from pymatgen import/from pymatgen.core import/g'

  This should resolve most import errors, though you may have to fix a few issues manually, e.g., if your code contains
  something like `from pymatgen import Element, MPRester`, which will now need to be split into two lines.

Last but not least, one option is to pin to pymatgen==2021.*.*, which is the last version to contain the root-level
convenience imports, if you are not planning to use future new pymatgen functionality. The new breaking change will
become default from year 2022. Backports to 2021.*.* will still occur for critical bug fixes.

Matgenie & Examples
===================

The `Materials Virtual Lab`_ has developed a `matgenie web app <http://matgenie.materialsvirtuallab.org>`_ which
demonstrates some of the basic functionality of pymatgen, as well as a
`matgenb repository <http://matgenb.materialsvirtuallab.org>`_ of Jupyter notebooks for common and advanced use cases.
One of the ways you can contribute is to fork the matgenb repo and add your own examples.

Below are a quick look at some of the graphical output possible.

.. figure:: _static/examples.png
   :width: 100%
   :alt: Examples
   :align: center

   Top: (left) Phase and (right) Pourbaix diagram from the Materials API.
   Bottom left: Calculated bandstructure plot using pymatgen's parsing and
   plotting utilities. Bottom right: Arrhenius plot using pymatgen's
   DiffusionAnalyzer.

Why use pymatgen?
=================

There are many materials analysis codes out there, both commercial and free.
So you might ask - why should I use pymatgen over others? Pymatgen offer
several advantages over other codes out there:

1. **It is (fairly) robust.** Pymatgen is used by thousands of researchers, and is the analysis code powering the
   `Materials Project`_. The analysis it produces survives rigorous scrutiny every single day. Bugs tend to be
   found and corrected quickly. Pymatgen also uses Github Actions for continuous integration, which ensures that every
   new code passes a comprehensive suite of unittests.
2. **It is well documented.** A fairly comprehensive documentation has been written to help you get to grips with it
   quickly.
3. **It is open.** You are free to use and contribute to pymatgen. It also means that pymatgen is continuously being
   improved. We will attribute any code you contribute to any publication you specify. Contributing to pymatgen means
   your research becomes more visible, which translates to greater impact.
4. **It is fast.** Many of the core numerical methods in pymatgen have been optimized by vectorizing in numpy/scipy.
   This means that coordinate manipulations are extremely fast and are in fact comparable to codes written in other
   languages. Pymatgen also comes with a complete system for handling periodic boundary conditions.
5. **It will be around.** Pymatgen is not a pet research project. It is used in the well-established Materials Project.
   It is also actively being developed and maintained by the `Materials Virtual Lab`_, the ABINIT group and many
   other research groups.
6. **A growing ecosystem of developers and add-ons**. Pymatgen has contributions from materials scientists all over the
   world. We also now have an architecture to support add-ons that expand pymatgen's functionality even further. Check
   out the `contributing page <http://pymatgen.org/contributing>`_ and `add-ons page <http://pymatgen.org/addons>`_ for
   details and examples.

Please review the `coding guidelines </contributing>`_.

.. include:: latest_changes.rst

:doc:`Older versions </change_log>`

Getting pymatgen
================

Via conda (recommended)
~~~~~~~~~~~~~~~~~~~~~~~

If you are absolutely new to Python and/or are using Windows, the easiest
installation process is using `conda <http://conda.pydata.org>`_. If you
already have conda installed, pymatgen can be installed from the `conda-forge
channel <https://anaconda.org/conda-forge>`_ using the following command::

    conda install --channel conda-forge pymatgen

Note that you might need to ensure a relatively recent version of gcc is
available to compile pymatgen. You can use conda to get that::

    conda install gcc

Pymatgen is under active development, and new features are added regularly. To
upgrade pymatgen to the latest version, use the following command::

    conda upgrade pymatgen

Step-by-step instructions for all platforms are available at the
:doc:`installation page </installation>`.

Via pip
~~~~~~~

The version at the Python Package Index (PyPI) is always the latest stable
release that is relatively bug-free. The easiest way to install pymatgen on
any system is to use pip::

    pip install pymatgen

Wheels for Mac and Windows have been built for convenience. Similarly, you might
need to ensure you have a relatively recent version of gcc.

To upgrade pymatgen via pip::

    pip install --upgrade pymatgen

The bleeding edge developmental version is at the pymatgen `Github repo
<https://github.com/materialsproject/pymatgen>`_. The developmental
version is likely to be more buggy, but may contain new features. The
Github version include complete test files. After
cloning the source, you can type in the root of the repo::

    pip install .

or to install the package in developmental mode::

    pip install -e .

Detailed installation instructions, including installation of
option dependencies, set up for POTCAR generation, Materials Project REST
interface usage, setup for developers, etc.are given on this
:doc:`page </installation>`.

For some extras, you can also install the optional dependencies using::

   pip install pymatgen[extra]

For an always up-to-date list of extras, consult the `setup.py's extras_require
<https://github.com/materialsproject/pymatgen/blob/master/setup.py>`_.

Shared cluster installation
~~~~~~~~~~~~~~~~~~~~~~~~~~~

If you are installing pymatgen on shared computing clusters, e.g., the XSEDE
or NERSC resources in the US, the best way is to use conda to perform a local
install. This guarantees the right version of python and all dependencies::

    wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh
    bash Miniconda3-latest-Linux-x86_64.sh -b

    # Reload bash profile.
    source $HOME/.bashrc
    source $HOME/.bash_profile

    # Install numpy and other pydata stack packages via conda.
    conda install --yes numpy scipy pandas
    conda install --yes --channel conda-forge pymatgen

Usage
=====

.. figure:: _static/overview.jpg
   :width: 100%
   :alt: pymatgen overview
   :align: center

   Overview of a typical workflow for pymatgen.

The figure above provides an overview of the functionality in pymatgen. A typical workflow would involve a user
converting data (structure, calculations, etc.) from various sources (first principles calculations, crystal and
molecule input files, Materials Project, etc.) into Python objects using pymatgen's io packages, which are then used to
perform further structure manipulation or analyses.

.. _quick_start:

Quick start
~~~~~~~~~~~

Here are some quick examples of the core capabilities and objects:

.. code-block:: pycon

    >>> import pymatgen.core as mg
    >>>
    >>> si = mg.Element("Si")
    >>> si.atomic_mass
    28.0855
    >>> print(si.melting_point)
    1687.0 K
    >>>
    >>> comp = mg.Composition("Fe2O3")
    >>> comp.weight
    159.6882
    >>> # Note that Composition conveniently allows strings to be treated just
    >>> # like an Element object.
    >>> comp["Fe"]
    2.0
    >>> comp.get_atomic_fraction("Fe")
    0.4
    >>> lattice = mg.Lattice.cubic(4.2)
    >>> structure = mg.Structure(lattice, ["Cs", "Cl"],
    ...                          [[0, 0, 0], [0.5, 0.5, 0.5]])
    >>> structure.volume
    74.088000000000008
    >>> structure[0]
    PeriodicSite: Cs (0.0000, 0.0000, 0.0000) [0.0000, 0.0000, 0.0000]
    >>>
    >>> # You can create a Structure using spacegroup symmetry as well.
    >>> li2o = mg.Structure.from_spacegroup("Fm-3m", mg.Lattice.cubic(3),
                                            ["Li", "O"],
                                            [[0.25, 0.25, 0.25], [0, 0, 0]])
    >>>
    >>> # Integrated symmetry analysis tools from spglib.
    >>> from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
    >>> finder = SpacegroupAnalyzer(structure)
    >>> finder.get_space_group_symbol()
    'Pm-3m'
    >>>
    >>> # Convenient IO to various formats. You can specify various formats.
    >>> # Without a filename, a string is returned. Otherwise,
    >>> # the output is written to the file. If only the filenmae is provided,
    >>> # the format is intelligently determined from a file.
    >>> structure.to(fmt="poscar")
    >>> structure.to(filename="POSCAR")
    >>> structure.to(filename="CsCl.cif")
    >>>
    >>> # Reading a structure is similarly easy.
    >>> structure = mg.Structure.from_str(open("CsCl.cif").read(), fmt="cif")
    >>> structure = mg.Structure.from_file("CsCl.cif")
    >>>
    >>> # Reading and writing a molecule from a file. Supports XYZ and
    >>> # Gaussian input and output by default. Support for many other
    >>> # formats via the optional openbabel dependency (if installed).
    >>> methane = mg.Molecule.from_file("methane.xyz")
    >>> mol.to("methane.gjf")
    >>>
    >>> # Pythonic API for editing Structures and Molecules (v2.9.1 onwards)
    >>> # Changing the specie of a site.
    >>> structure[1] = "F"
    >>> print(structure)
    Structure Summary (Cs1 F1)
    Reduced Formula: CsF
    abc   :   4.200000   4.200000   4.200000
    angles:  90.000000  90.000000  90.000000
    Sites (2)
    1 Cs     0.000000     0.000000     0.000000
    2 F     0.500000     0.500000     0.500000
    >>>
    >>> # Changes species and coordinates (fractional assumed for structures)
    >>> structure[1] = "Cl", [0.51, 0.51, 0.51]
    >>> print(structure)
    Structure Summary (Cs1 Cl1)
    Reduced Formula: CsCl
    abc   :   4.200000   4.200000   4.200000
    angles:  90.000000  90.000000  90.000000
    Sites (2)
    1 Cs     0.000000     0.000000     0.000000
    2 Cl     0.510000     0.510000     0.510000
    >>>
    >>> # Replaces all Cs in the structure with K
    >>> structure["Cs"] = "K"
    >>> print(structure)
    Structure Summary (K1 Cl1)
    Reduced Formula: KCl
    abc   :   4.200000   4.200000   4.200000
    angles:  90.000000  90.000000  90.000000
    Sites (2)
    1 K     0.000000     0.000000     0.000000
    2 Cl     0.510000     0.510000     0.510000
    >>>
    >>> # Replaces all K in the structure with K: 0.5, Na: 0.5, i.e.,
    >>> # a disordered structure is created.
    >>> structure["K"] = "K0.5Na0.5"
    >>> print(structure)
    Full Formula (K0.5 Na0.5 Cl1)
    Reduced Formula: K0.5Na0.5Cl1
    abc   :   4.209000   4.209000   4.209000
    angles:  90.000000  90.000000  90.000000
    Sites (2)
      #  SP                   a    b    c
    ---  -----------------  ---  ---  ---
      0  K:0.500, Na:0.500  0    0    0
      1  Cl                 0.5  0.5  0.5
    >>>
    >>> # Because structure is like a list, it supports most list-like methods
    >>> # such as sort, reverse, etc.
    >>> structure.reverse()
    >>> print(structure)
    Structure Summary (Cs1 Cl1)
    Reduced Formula: CsCl
    abc   :   4.200000   4.200000   4.200000
    angles:  90.000000  90.000000  90.000000
    Sites (2)
    1 Cl     0.510000     0.510000     0.510000
    2 Cs     0.000000     0.000000     0.000000
    >>>
    >>> # Molecules function similarly, but with Site and Cartesian coords.
    >>> # The following changes the C in CH4 to an N and displaces it by 0.01A
    >>> # in the x-direction.
    >>> methane[0] = "N", [0.01, 0, 0]
    >>>

The above illustrates only the most basic capabilities of pymatgen. Users are
strongly encouraged to explore the :doc:`usage pages </usage>` (toc given below).

API documentation
~~~~~~~~~~~~~~~~~

For detailed documentation of all modules and classes, please refer to the
:doc:`API docs </modules>`.

More resources
~~~~~~~~~~~~~~

The founder and maintainer of pymatgen, Shyue Ping Ong, has conducted several
workshops (together with Anubhav Jain) on how to effectively use pymatgen (as
well as the extremely useful `custodian`_ error management and `FireWorks`_
workflow software. The slides for these workshops are available on the
`Materials Virtual Lab`_.

pmg - Command line tool
~~~~~~~~~~~~~~~~~~~~~~~

To demonstrate the capabilities of pymatgen and to make it easy for users to
quickly use the functionality, pymatgen comes with a set of useful scripts
that utilize the library to perform all kinds of analyses. These are
installed to your path by default when you install pymatgen through the
typical installation routes.

Here, we will discuss the most versatile of these scripts, known as
pmg. The typical usage of pmg is::

    pmg {setup, config, analyze, plotdos, plotchgint, convert, symm, view, compare} additional_arguments

At any time, you can use ``"pmg --help"`` or ``"pmg subcommand
--help"`` to bring up a useful help message on how to use these subcommands.
With effect from v4.6.0, ``pmg`` also supports bash completion using
argcomplete, which is useful given the many options available in the cli tool.
To enable argcomplete, ``pip install argcomplete`` and either follow
argcomplete's instructions for enabling global completion, or add the following
line to your ``.bash_profile`` (this method usually works more reliably)::

   eval "$(register-python-argcomplete pmg)"

Here are a few examples of typical usages::

    # Parses all vasp runs in a directory and display the basic energy
    # information. Saves the data in a file called vasp_data.gz for subsequent
    # reuse.

    pmg analyze .

    # Plot the dos from the vasprun.xml file.

    pmg plot --dos vasprun.xml

    # Convert between file formats. The script attempts to intelligently
    # determine the file type. Input file types supported include CIF,
    # vasprun.xml, POSCAR, CSSR. You can force the script to assume certain file
    # types by specifying additional arguments. See pmg convert -h.

    pmg structure --convert --filenames input_filename output_filename.

    # Obtain spacegroup information using a tolerance of 0.1 angstroms.

    pmg structure --symmetry 0.1 --filenames filename1 filename2

    # Visualize a structure. Requires VTK to be installed.

    pmg view filename

    # Compare two structures for similarity

    pmg structure --group element --filenames filename1 filename2

    # Generate a POTCAR with symbols Li_sv O and the PBE functional

    pmg potcar --symbols Li_sv O --functional PBE

Add-ons
~~~~~~~

Some add-ons are available for pymatgen today:

1. The `pymatgen-db <https://pypi.python.org/pypi/pymatgen-db>`_ add-on
   provides tools to create databases of calculated run data using pymatgen.
2. The `custodian`_ package provides a JIT job management and error correction for calculations and is used by the
   Materials Project for high-throughput calculations.
3. `pymatgen-analysis-diffusion <http://pypi.org/project/pymatgen-analysis-diffusion/>`_ by the `Materials Virtual Lab`_
   provides modules for diffusion analysis, including path determination for NEB calculations, analysis of MD
   trajectories (RDF, van Hove, Arrhenius plots, etc.)

A comprehensive listing is provided at the :doc:`addons page </addons>`.

Contributing
============

Pymatgen is developed by a team of volunteers. It is started by a team comprising of MIT and Lawrence Berkeley National
Laboratory staff to be a robust toolkit for materials researchers to perform advanced manipulations of structures and
analyses.

For pymatgen to continue to grow in functionality and robustness, we rely on other volunteers to develop new analyses
and report and fix bugs. We welcome anyone to use our code as-is, but if you could take a few moment to give back
to pymatgen in some small way, it would be greatly appreciated. A benefit of contributing is that your code will now be
used by other researchers who use pymatgen, and we will include an acknowledgement to you (and any related
publications) in pymatgen.

Reporting bugs
--------------

A simple way that anyone can contribute is simply to report bugs and issues
to the developing team. Please report any bugs and issues at pymatgen's
`Github Issues page <https://github.com/materialsproject/pymatgen/issues>`_.
For help with any pymatgen issue, consult `Stack Overflow
<https://stackoverflow.com/questions/tagged/pymatgen>`_ and if
you cannot find an answer, please post a question with the tag `pymatgen`.

Developing new functionality
----------------------------

Another way to contribute is to submit new code/bugfixes to pymatgen. The
best way for anyone to develop pymatgen is by adopting the collaborative
Github workflow (see `contributing page </contributing>`_).

How to cite pymatgen
====================

If you use pymatgen in your research, please consider citing the following work:

    Shyue Ping Ong, William Davidson Richards, Anubhav Jain, Geoffroy Hautier,
    Michael Kocher, Shreyas Cholia, Dan Gunter, Vincent Chevrier, Kristin A.
    Persson, Gerbrand Ceder. *Python Materials Genomics (pymatgen) : A Robust,
    Open-Source Python Library for Materials Analysis.* Computational
    Materials Science, 2013, 68, 314–319. `doi:10.1016/j.commatsci.2012.10.028
    <https://doi.org/10.1016/j.commatsci.2012.10.028>`_

In addition, some of pymatgen's functionality is based on scientific advances / principles developed by various
scientists. Please refer to the :doc:`references page </references>` for citation info.

License
=======

Pymatgen is released under the MIT License.

.. literalinclude:: ../LICENSE.rst

About the Team
==============

Shyue Ping Ong of the `Materials Virtual Lab`_ started Pymatgen in 2011, and is still the project lead.

The Pymatgen Development Team is the set of all contributors to the pymatgen project, including all subprojects.

The full list of contributors are listed in the :doc:`team page </team>`.

Copyright Policy
================

Pymatgen uses a shared copyright model. Each contributor maintains copyright
over their contributions to pymatgen. But, it is important to note that these
contributions are typically only changes to the repositories. Thus, the
pymatgen source code, in its entirety is not the copyright of any
single person or institution. Instead, it is the collective copyright of the
entire pymatgen Development Team. If individual contributors want to maintain a
record of what changes/contributions they have specific copyright on, they
should indicate their copyright in the commit message of the change, when
they commit the change to one of the pymatgen repositories.

With this in mind, the following banner should be used in any source code file
to indicate the copyright and license terms::

    # Copyright (c) Pymatgen Development Team.
    # Distributed under the terms of the MIT License.

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

.. _`PyPI`: http://pypi.python.org/pypi/pymatgen
.. _`Github page`: https://github.com/materialsproject/pymatgen/issues
.. _`custodian`: https://pypi.python.org/pypi/custodian
.. _`FireWorks`: https://materialsproject.github.io/fireworks
.. _`Materials Project`: https://www.materialsproject.org
.. _`Materials Virtual Lab`: http://www.materialsvirtuallab.org


text:
<?php

namespace Dephpug\Console\concerns;

class PhpInfo
{
    public $info;

    public function getInfo()
    {
        if (null === $this->info) {
            ob_start();
            phpinfo();
            $this->info = ob_get_clean();
        }

        return $this->info;
    }

    public function getVar($variable)
    {
        $info = $this->getInfo();
        $variable = str_replace('.', '\.', $variable);
        $pattern = "/{$variable} \=\> (.+)\n/";

        if (preg_match($pattern, $info, $variableInfo)) {
            return $variableInfo[1];
        }

        return null;
    }

    public function printVar($variable, $label)
    {
        return "{$label}: <fg=red>{$this->getVar($variable)}</>";
    }

    public function getVars($pattern)
    {
        $info = $this->getInfo();
        if (preg_match_all($pattern, $info, $variablesInfo)) {
            return $variablesInfo;
        }

        return null;
    }

    public function checkPHPVersion()
    {
        return (int) phpversion()[0] >= 7;
    }

    public function xdebugInstalled()
    {
        return extension_loaded('xdebug');
    }

    public function socketsInstalled()
    {
        return extension_loaded('sockets');
    }

    public function xdebugIsActive()
    {
        if ($this->xdebugInstalled()) {
            return xdebug_is_enabled();
        }

        return false;
    }
}


text:
package it.cnr.isti.zigbee.ha.device.api.lighting;

import it.cnr.isti.zigbee.ha.cluster.glue.general.Groups;
import it.cnr.isti.zigbee.ha.cluster.glue.general.LevelControl;
import it.cnr.isti.zigbee.ha.cluster.glue.general.OnOff;
import it.cnr.isti.zigbee.ha.cluster.glue.general.Scenes;
import it.cnr.isti.zigbee.ha.cluster.glue.measureament_sensing.OccupancySensing;
import it.cnr.isti.zigbee.ha.driver.ArraysUtil;
import it.cnr.isti.zigbee.ha.driver.core.HADevice;
import it.cnr.isti.zigbee.ha.driver.core.HAProfile;

/**
 *
 * @author Stefano "Kismet" Lenzi
 * @author Francesco Furfari
 * @version $LastChangedRevision$ ($LastChangedDate$)
 *
 */
public interface DimmableLight extends HADevice{

	public static final int DEVICE_ID = 0x0101;
	public static final String NAME = "Dimmable Light";
	public static final int[] MANDATORY = ArraysUtil.append(HADevice.MANDATORY, new int[]{
		HAProfile.ON_OFF,HAProfile.LEVEL_CONTROL,HAProfile.SCENES,HAProfile.GROUPS
	});
	public static final int[] OPTIONAL = ArraysUtil.append(HADevice.OPTIONAL, new int[]{
		HAProfile.OCCUPANCY_SENSING
	});
	public static final int[] STANDARD = ArraysUtil.append(MANDATORY, OPTIONAL);
	public static final int[] CUSTOM = {};

	/**
	 * Access method for the Mandatory cluster: {@link OnOff}
	 *
	 * @return the {@link OnOff} cluster object
	 */
	public OnOff getOnOff();

	/**
	 * Access method for the Mandatory cluster: {@link Scenes}
	 *
	 * @return the {@link Scenes} cluster object
	 */
	public Scenes getScenes();

	/**
	 * Access method for the Mandatory cluster: {@link Groups}
	 *
	 * @return the {@link Groups} cluster object
	 */
	public Groups getGroups();

	/**
	 * Access method for the Mandatory cluster: {@link LevelControl}
	 *
	 * @return the {@link LevelControl} cluster object
	 */
	public LevelControl getLevelControl();

	/**
	 * Access method for the Optional cluster: {@link OccupancySensing}
	 *
	 * @return the {@link OccupancySensing} cluster object if implemented by the device, otherwise null
	 */
	public abstract OccupancySensing getOccupacySensing();

}