text:
<?php

error_reporting( E_ALL | E_STRICT );

/**
 * Zend_Console_Getopt
 */
require_once 'Zend/Console/Getopt.php';

/**
 * PHPUnit test case
 */
require_once 'PHPUnit/Framework/TestCase.php';

/**
 * @category   Zend
 * @package    Zend_Console_Getopt
 * @subpackage UnitTests
 */
class Zend_Console_GetoptTest extends PHPUnit_Framework_TestCase
{
    public function testGetoptShortOptionsGnuMode()
    {
        $opts = new Zend_Console_Getopt('abp:', array('-a', '-p', 'p_arg'));
        $this->assertEquals(true, $opts->a);
        $this->assertNull(@$opts->b);
        $this->assertEquals($opts->p, 'p_arg');
    }

    public function testGetoptLongOptionsZendMode()
    {
        $opts = new Zend_Console_Getopt(array(
                'apple|a' => 'Apple option',
                'banana|b' => 'Banana option',
                'pear|p=s' => 'Pear option'
            ),
            array('-a', '-p', 'p_arg'));
        $this->assertTrue($opts->apple);
        $this->assertNull(@$opts->banana);
        $this->assertEquals($opts->pear, 'p_arg');
    }

    public function testGetoptZendModeEqualsParam()
    {
        $opts = new Zend_Console_Getopt(array(
                'apple|a' => 'Apple option',
                'banana|b' => 'Banana option',
                'pear|p=s' => 'Pear option'
            ),
            array('--pear=pear.phpunit.de'));
        $this->assertEquals($opts->pear, 'pear.phpunit.de');
    }

    public function testGetoptToString()
    {
        $opts = new Zend_Console_Getopt('abp:', array('-a', '-p', 'p_arg'));
        $this->assertEquals($opts->__toString(), 'a=true p=p_arg');
    }

    public function testGetoptDumpString()
    {
        $opts = new Zend_Console_Getopt('abp:', array('-a', '-p', 'p_arg'));
        $this->assertEquals($opts->toString(), 'a=true p=p_arg');
    }

    public function testGetoptDumpArray()
    {
        $opts = new Zend_Console_Getopt('abp:', array('-a', '-p', 'p_arg'));
        $this->assertEquals(implode(',', $opts->toArray()), 'a,p,p_arg');
    }

    public function testGetoptDumpJson()
    {
        $opts = new Zend_Console_Getopt('abp:', array('-a', '-p', 'p_arg'));
        $this->assertEquals($opts->toJson(),
            '{"options":[{"option":{"flag":"a","parameter":true}},{"option":{"flag":"p","parameter":"p_arg"}}]}');

    }

    public function testGetoptDumpXml()
    {
        $opts = new Zend_Console_Getopt('abp:', array('-a', '-p', 'p_arg'));
        $this->assertEquals($opts->toXml(),
            "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<options><option flag=\"a\"/><option flag=\"p\" parameter=\"p_arg\"/></options>\n");
    }

    public function testGetoptExceptionForMissingFlag()
    {
        try {
            $opts = new Zend_Console_Getopt(array('|a'=>'Apple option'));
            $this->fail('Expected to catch Zend_Console_Getopt_Exception');
        } catch (Zend_Exception $e) {
            $this->assertType('Zend_Console_Getopt_Exception', $e,
                'Expected Zend_Console_Getopt_Exception, got '.get_class($e));
            $this->assertEquals($e->getMessage(),
                'Blank flag not allowed in rule "|a".');
        }
    }

    public function testGetoptExceptionForDuplicateFlag()
    {
        try {
            $opts = new Zend_Console_Getopt(
                array('apple|apple'=>'apple-option'));
            $this->fail('Expected to catch Zend_Console_Getopt_Exception');
        } catch (Zend_Exception $e) {
            $this->assertType('Zend_Console_Getopt_Exception', $e,
                'Expected Zend_Console_Getopt_Exception, got '.get_class($e));
            $this->assertEquals($e->getMessage(),
                'Option "--apple" is being defined more than once.');
        }

        try {
            $opts = new Zend_Console_Getopt(
                array('a'=>'Apple option', 'apple|a'=>'Apple option'));
            $this->fail('Expected to catch Zend_Console_Getopt_Exception');
        } catch (Zend_Exception $e) {
            $this->assertType('Zend_Console_Getopt_Exception', $e,
                'Expected Zend_Console_Getopt_Exception, got '.get_class($e));
            $this->assertEquals($e->getMessage(),
                'Option "-a" is being defined more than once.');
        }
    }

    public function testGetoptAddRules()
    {
        $opts = new Zend_Console_Getopt(
            array(
                'apple|a' => 'Apple option',
                'banana|b' => 'Banana option'
            ),
            array('--pear', 'pear_param'));
        try {
            $opts->parse();
            $this->fail('Expected to catch Zend_Console_Getopt_Exception');
        } catch (Zend_Exception $e) {
            $this->assertType('Zend_Console_Getopt_Exception', $e,
                'Expected Zend_Console_Getopt_Exception, got '.get_class($e));
            $this->assertEquals($e->getMessage(), 'Option "pear" is not recognized.');
        }
        $opts->addRules(array('pear|p=s' => 'Pear option'));
        $this->assertEquals($opts->pear, 'pear_param');
    }

    public function testGetoptExceptionMissingParameter()
    {
        $opts = new Zend_Console_Getopt(
            array(
                'apple|a=s' => 'Apple with required parameter',
                'banana|b' => 'Banana'
            ),
            array('--apple'));
        try {
            $opts->parse();
            $this->fail('Expected to catch Zend_Console_Getopt_Exception');
        } catch (Zend_Exception $e) {
            $this->assertType('Zend_Console_Getopt_Exception', $e,
                'Expected Zend_Console_Getopt_Exception, got '.get_class($e));
            $this->assertEquals($e->getMessage(), 'Option "apple" requires a parameter.');
        }
    }

    public function testGetoptOptionalParameter()
    {
        $opts = new Zend_Console_Getopt(
            array(
                'apple|a-s' => 'Apple with optional parameter',
                'banana|b' => 'Banana'
            ),
            array('--apple', '--banana'));
        $this->assertTrue($opts->apple);
        $this->assertTrue($opts->banana);
    }

    public function testGetoptIgnoreCaseGnuMode()
    {
        $opts = new Zend_Console_Getopt('aB', array('-A', '-b'),
            array(Zend_Console_Getopt::CONFIG_IGNORECASE => true));
        $this->assertEquals(true, $opts->a);
        $this->assertEquals(true, $opts->B);
    }

    public function testGetoptIgnoreCaseZendMode()
    {
        $opts = new Zend_Console_Getopt(
            array(
                'apple|a' => 'Apple-option',
                'Banana|B' => 'Banana-option'
            ),
            array('--Apple', '--bAnaNa'),
            array(Zend_Console_Getopt::CONFIG_IGNORECASE => true));
        $this->assertEquals(true, $opts->apple);
        $this->assertEquals(true, $opts->BANANA);
    }

    public function testGetoptIsSet()
    {
        $opts = new Zend_Console_Getopt('ab', array('-a'));
        $this->assertTrue(isset($opts->a));
        $this->assertFalse(isset($opts->b));
    }

    public function testGetoptIsSetAlias()
    {
        $opts = new Zend_Console_Getopt('ab', array('-a'));
        $opts->setAliases(array('a' => 'apple', 'b' => 'banana'));
        $this->assertTrue(isset($opts->apple));
        $this->assertFalse(isset($opts->banana));
    }

    public function testGetoptIsSetInvalid()
    {
        $opts = new Zend_Console_Getopt('ab', array('-a'));
        $opts->setAliases(array('a' => 'apple', 'b' => 'banana'));
        $this->assertFalse(isset($opts->cumquat));
    }

    public function testGetoptSet()
    {
        $opts = new Zend_Console_Getopt('ab', array('-a'));
        $this->assertFalse(isset($opts->b));
        $opts->b = true;
        $this->assertTrue(isset($opts->b));
    }

    public function testGetoptSetBeforeParse()
    {
        $opts = new Zend_Console_Getopt('ab', array('-a'));
        $opts->b = true;
        $this->assertTrue(isset($opts->b));
    }

    public function testGetoptUnSet()
    {
        $opts = new Zend_Console_Getopt('ab', array('-a'));
        $this->assertTrue(isset($opts->a));
        unset($opts->a);
        $this->assertFalse(isset($opts->a));
    }

    public function testGetoptUnSetBeforeParse()
    {
        $opts = new Zend_Console_Getopt('ab', array('-a'));
        unset($opts->a);
        $this->assertFalse(isset($opts->a));
    }

    public function testGetoptAddArguments()
    {
        $opts = new Zend_Console_Getopt('abp:', array('-a'));
        $this->assertNull(@$opts->p);
        $opts->addArguments(array('-p', 'p_arg'));
        $this->assertEquals($opts->p, 'p_arg');
    }

    public function testGetoptRemainingArgs()
    {
        $opts = new Zend_Console_Getopt('abp:', array('-a', '--', 'file1', 'file2'));
        $this->assertEquals(implode(',', $opts->getRemainingArgs()), 'file1,file2');
        $opts = new Zend_Console_Getopt('abp:', array('-a', 'file1', 'file2'));
        $this->assertEquals(implode(',', $opts->getRemainingArgs()), 'file1,file2');
    }

    public function testGetoptDashDashFalse()
    {
        try {
            $opts = new Zend_Console_Getopt('abp:', array('-a', '--', '--fakeflag'),
                array(Zend_Console_Getopt::CONFIG_DASHDASH => false));
            $opts->parse();
            $this->fail('Expected to catch Zend_Console_Getopt_Exception');
        } catch (Zend_Exception $e) {
            $this->assertType('Zend_Console_Getopt_Exception', $e,
                'Expected Zend_Console_Getopt_Exception, got '.get_class($e));
            $this->assertEquals($e->getMessage(), 'Option "fakeflag" is not recognized.');
        }
    }

    public function testGetoptGetOptions()
    {
        $opts = new Zend_Console_Getopt('abp:', array('-a', '-p', 'p_arg'));
        $this->assertEquals(implode(',', $opts->getOptions()), 'a,p');
    }

    public function testGetoptGetUsageMessage()
    {
        $opts = new Zend_Console_Getopt('abp:', array('-x'));
        $message = preg_replace('/Usage: .* \[ options \]/',
            'Usage: <progname> [ options ]',
            $opts->getUsageMessage());
        $message = preg_replace('/ /', '_', $message);
        $this->assertEquals($message,
            "Usage:_<progname>_[_options_]\n-a___________________\n-b___________________\n-p_<string>__________\n");
    }

    public function testGetoptUsageMessageFromException()
    {
        try {
            $opts = new Zend_Console_Getopt(array(
                'apple|a-s' => 'apple',
                'banana1|banana2|banana3|banana4' => 'banana',
                'pear=s' => 'pear'),
                array('-x'));
            $opts->parse();
            $this->fail('Expected to catch Zend_Console_Getopt_Exception');
        } catch (Zend_Exception $e) {
            $this->assertType('Zend_Console_Getopt_Exception', $e,
                'Expected Zend_Console_Getopt_Exception, got '.get_class($e));
            $message = preg_replace('/Usage: .* \[ options \]/',
                'Usage: <progname> [ options ]',
                $e->getUsageMessage());
            $message = preg_replace('/ /', '_', $message);
            $this->assertEquals($message,
                "Usage:_<progname>_[_options_]\n--apple|-a_[_<string>_]_________________apple\n--banana1|--banana2|--banana3|--banana4_banana\n--pear_<string>_________________________pear\n");

        }
    }

    public function testGetoptSetAliases()
    {
        $opts = new Zend_Console_Getopt('abp:', array('--apple'));
        $opts->setAliases(array('a' => 'apple'));
        $this->assertTrue($opts->a);
    }

    public function testGetoptSetAliasesIgnoreCase()
    {
        $opts = new Zend_Console_Getopt('abp:', array('--apple'),
            array(Zend_Console_Getopt::CONFIG_IGNORECASE => true));
        $opts->setAliases(array('a' => 'APPLE'));
        $this->assertTrue($opts->apple);
    }

    public function testGetoptSetAliasesWithNamingConflict()
    {
        $opts = new Zend_Console_Getopt('abp:', array('--apple'));
        $opts->setAliases(array('a' => 'apple'));
        try {
            $opts->setAliases(array('b' => 'apple'));
            $this->fail('Expected to catch Zend_Console_Getopt_Exception');
        } catch (Zend_Exception $e) {
            $this->assertType('Zend_Console_Getopt_Exception', $e,
                'Expected Zend_Console_Getopt_Exception, got '.get_class($e));
            $this->assertEquals($e->getMessage(), 'Option "--apple" is being defined more than once.');
        }
    }

    public function testGetoptSetAliasesInvalid()
    {
        $opts = new Zend_Console_Getopt('abp:', array('--apple'));
        $opts->setAliases(array('c' => 'cumquat'));
        $opts->setArguments(array('-c'));
        try {
            $opts->parse();
            $this->fail('Expected to catch Zend_Console_Getopt_Exception');
        } catch (Zend_Exception $e) {
            $this->assertType('Zend_Console_Getopt_Exception', $e,
                'Expected Zend_Console_Getopt_Exception, got '.get_class($e));
            $this->assertEquals('Option "c" is not recognized.', $e->getMessage());
        }
    }

    public function testGetoptSetHelp()
    {
        $opts = new Zend_Console_Getopt('abp:', array('-a'));
        $opts->setHelp(array(
            'a' => 'apple',
            'b' => 'banana',
            'p' => 'pear'));
        $message = preg_replace('/Usage: .* \[ options \]/',
            'Usage: <progname> [ options ]',
            $opts->getUsageMessage());
        $message = preg_replace('/ /', '_', $message);
        $this->assertEquals($message,
            "Usage:_<progname>_[_options_]\n-a___________________apple\n-b___________________banana\n-p_<string>__________pear\n");

    }

    public function testGetoptSetHelpInvalid()
    {
        $opts = new Zend_Console_Getopt('abp:', array('-a'));
        $opts->setHelp(array(
            'a' => 'apple',
            'b' => 'banana',
            'p' => 'pear',
            'c' => 'cumquat'));
        $message = preg_replace('/Usage: .* \[ options \]/',
            'Usage: <progname> [ options ]',
            $opts->getUsageMessage());
        $message = preg_replace('/ /', '_', $message);
        $this->assertEquals($message,
            "Usage:_<progname>_[_options_]\n-a___________________apple\n-b___________________banana\n-p_<string>__________pear\n");
    }

    public function testGetoptCheckParameterType()
    {
        $opts = new Zend_Console_Getopt(array(
            'apple|a=i' => 'apple with integer',
            'banana|b=w' => 'banana with word',
            'pear|p=s' => 'pear with string',
            'orange|o-i' => 'orange with optional integer',
            'lemon|l-w' => 'lemon with optional word',
            'kumquat|k-s' => 'kumquat with optional string'));

        $opts->setArguments(array('-a', 327));
        $opts->parse();
        $this->assertEquals(327, $opts->a);

        $opts->setArguments(array('-a', 'noninteger'));
        try {
            $opts->parse();
            $this->fail('Expected to catch Zend_Console_Getopt_Exception');
        } catch (Zend_Exception $e) {
            $this->assertType('Zend_Console_Getopt_Exception', $e,
                'Expected Zend_Console_Getopt_Exception, got '.get_class($e));
            $this->assertEquals($e->getMessage(), 'Option "apple" requires an integer parameter, but was given "noninteger".');
        }

        $opts->setArguments(array('-b', 'word'));
        $this->assertEquals('word', $opts->b);

        $opts->setArguments(array('-b', 'two words'));
        try {
            $opts->parse();
            $this->fail('Expected to catch Zend_Console_Getopt_Exception');
        } catch (Zend_Exception $e) {
            $this->assertType('Zend_Console_Getopt_Exception', $e,
                'Expected Zend_Console_Getopt_Exception, got '.get_class($e));
            $this->assertEquals($e->getMessage(), 'Option "banana" requires a single-word parameter, but was given "two words".');
        }

        $opts->setArguments(array('-p', 'string'));
        $this->assertEquals('string', $opts->p);

        $opts->setArguments(array('-o', 327));
        $this->assertEquals(327, $opts->o);

        $opts->setArguments(array('-o'));
        $this->assertTrue($opts->o);

        $opts->setArguments(array('-l', 'word'));
        $this->assertEquals('word', $opts->l);

        $opts->setArguments(array('-k', 'string'));
        $this->assertEquals('string', $opts->k);

    }

}


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.activiti.idm.engine.delegate.event.impl;

import org.activiti.idm.api.event.ActivitiIdmEventType;
import org.activiti.idm.api.event.ActivitiIdmMembershipEvent;

/**
 * Implementation of {@link ActivitiMembershipEvent}.
 *
 * @author Frederik Heremans
 */
public class ActivitiIdmMembershipEventImpl extends ActivitiIdmEventImpl implements ActivitiIdmMembershipEvent {

  protected String userId;
  protected String groupId;

  public ActivitiIdmMembershipEventImpl(ActivitiIdmEventType type) {
    super(type);
  }

  public void setUserId(String userId) {
    this.userId = userId;
  }

  public String getUserId() {
    return userId;
  }

  public void setGroupId(String groupId) {
    this.groupId = groupId;
  }

  public String getGroupId() {
    return groupId;
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.facebook.buck.cli;

import com.facebook.buck.event.ConsoleEvent;
import com.facebook.buck.parser.ParserPythonInterpreterProvider;
import com.facebook.buck.parser.ParsingContext;
import com.facebook.buck.parser.PerBuildState;
import com.facebook.buck.parser.PerBuildStateFactory;
import com.facebook.buck.parser.SpeculativeParsing;
import com.facebook.buck.rules.coercer.DefaultConstructorArgMarshaller;
import com.facebook.buck.util.ExitCode;
import com.facebook.buck.util.MoreExceptions;
import com.google.common.collect.ImmutableSet;
import java.util.ArrayList;
import java.util.List;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;

public class AuditOwnerCommand extends AbstractCommand {

  @Option(name = "--json", usage = "Output in JSON format")
  private boolean generateJsonOutput;

  public boolean shouldGenerateJsonOutput() {
    return generateJsonOutput;
  }

  @Argument private List<String> arguments = new ArrayList<>();

  public List<String> getArguments() {
    return arguments;
  }

  @Override
  public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception {
    if (params.getConsole().getAnsi().isAnsiTerminal()) {
      params
          .getBuckEventBus()
          .post(
              ConsoleEvent.info(
                  "'buck audit owner' is deprecated. Please use 'buck query' instead. e.g.\n\t%s\n\n"
                      + "The query language is documented at https://buckbuild.com/command/query.html",
                  QueryCommand.buildAuditOwnerQueryExpression(
                      getArguments(), shouldGenerateJsonOutput())));
    }

    try (CommandThreadManager pool =
            new CommandThreadManager("Audit", getConcurrencyLimit(params.getBuckConfig()));
        PerBuildState parserState =
            PerBuildStateFactory.createFactory(
                    params.getTypeCoercerFactory(),
                    new DefaultConstructorArgMarshaller(params.getTypeCoercerFactory()),
                    params.getKnownRuleTypesProvider(),
                    new ParserPythonInterpreterProvider(
                        params.getCell().getBuckConfig(), params.getExecutableFinder()),
                    params.getCell().getBuckConfig(),
                    params.getWatchman(),
                    params.getBuckEventBus(),
                    params.getManifestServiceSupplier(),
                    params.getFileHashCache(),
                    params.getUnconfiguredBuildTargetFactory())
                .create(
                    ParsingContext.builder(params.getCell(), pool.getListeningExecutorService())
                        .setProfilingEnabled(getEnableParserProfiling())
                        .setSpeculativeParsing(SpeculativeParsing.ENABLED)
                        .build(),
                    params.getParser().getPermState(),
                    getTargetPlatforms())) {
      BuckQueryEnvironment env =
          BuckQueryEnvironment.from(
              params,
              parserState,
              ParsingContext.builder(params.getCell(), pool.getListeningExecutorService())
                  .setProfilingEnabled(getEnableParserProfiling())
                  .setExcludeUnsupportedTargets(getExcludeIncompatibleTargets())
                  .build());
      QueryCommand.runMultipleQuery(
          params,
          env,
          "owner('%s')",
          getArguments(),
          shouldGenerateJsonOutput(),
          ImmutableSet.of(),
          params.getConsole().getStdOut());
    } catch (Exception e) {
      if (e.getCause() instanceof InterruptedException) {
        throw (InterruptedException) e.getCause();
      }
      params
          .getBuckEventBus()
          .post(ConsoleEvent.severe(MoreExceptions.getHumanReadableOrLocalizedMessage(e)));
      // TODO(buck_team): catch specific exceptions and output appropriate code
      return ExitCode.BUILD_ERROR;
    }
    return ExitCode.SUCCESS;
  }

  @Override
  public boolean isReadOnly() {
    return true;
  }

  @Override
  public String getShortDescription() {
    return "prints targets that own specified files";
  }
}


text:
package org.apache.xmlbeans.impl.xpath.saxon;

import net.sf.saxon.value.DateTimeValue;
import net.sf.saxon.value.GDateValue;
import org.apache.xmlbeans.*;
import org.apache.xmlbeans.impl.store.Cur;
import org.apache.xmlbeans.impl.store.DomImpl;
import org.apache.xmlbeans.impl.store.Locale;
import org.apache.xmlbeans.impl.xpath.XPathEngine;
import org.apache.xmlbeans.impl.xpath.XPathExecutionContext;
import org.w3c.dom.Node;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.List;

public class SaxonXPathEngine extends XPathExecutionContext implements XPathEngine {
    // full datetime format: yyyy-MM-dd'T'HH:mm:ss'Z'
    private final DateFormat xmlDateFormat = new SimpleDateFormat("yyyy-MM-dd", java.util.Locale.ROOT);

    private Cur _cur;
    private SaxonXPath _engine;
    private boolean _firstCall = true;
    private final long _version;

    SaxonXPathEngine(SaxonXPath xpathImpl, Cur c) {
        _engine = xpathImpl;
        _version = c.getLocale().version();
        _cur = c.weakCur(this);
    }

    public boolean next(Cur c) {
        if (!_firstCall) {
            return false;
        }

        _firstCall = false;

        if (_cur != null && _version != _cur.getLocale().version()) {
            throw new ConcurrentModificationException("Document changed during select");
        }

        List resultsList = _engine.selectPath(_cur.getDom());

        int i;
        for (i = 0; i < resultsList.size(); i++) {
            //simple type function results
            Object node = resultsList.get(i);
            Cur pos = null;
            if (!(node instanceof Node)) {
                Object obj = resultsList.get(i);
                String value;
                if (obj instanceof Date) {
                    value = xmlDateFormat.format((Date) obj);
                } else if (obj instanceof GDateValue) {
                    value = ((GDateValue) obj).getStringValue();
                } else if (obj instanceof DateTimeValue) {
                    value = ((DateTimeValue) obj).getStringValue();
                } else if (obj instanceof BigDecimal) {
                    value = ((BigDecimal) obj).toPlainString();
                } else {
                    value = obj.toString();
                }

                //we cannot leave the cursor's locale, as
                //everything is done in the selections of this cursor

                org.apache.xmlbeans.impl.store.Locale l = c.getLocale();
                try {
                    pos = l.load("<xml-fragment/>").tempCur();
                    pos.setValue(value);
                    SchemaType type = getType(node);
                    Locale.autoTypeDocument(pos, type, null);
                    //move the cur to the actual text
                    pos.next();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            } else {
                assert (node instanceof DomImpl.Dom) :
                    "New object created in XPATH!";
                pos = ((DomImpl.Dom) node).tempCur();

            }
            c.addToSelection(pos);
            pos.release();
        }
        release();
        _engine = null;
        return true;
    }

    private SchemaType getType(Object node) {
        SchemaType type;
        if (node instanceof Integer) {
            type = XmlInteger.type;
        } else if (node instanceof Double) {
            type = XmlDouble.type;
        } else if (node instanceof Long) {
            type = XmlLong.type;
        } else if (node instanceof Float) {
            type = XmlFloat.type;
        } else if (node instanceof BigDecimal) {
            type = XmlDecimal.type;
        } else if (node instanceof Boolean) {
            type = XmlBoolean.type;
        } else if (node instanceof String) {
            type = XmlString.type;
        } else if (node instanceof GDateValue) {
            type = XmlDate.type;
        } else if (node instanceof DateTimeValue) {
            type = XmlDateTime.type;
        } else {
            type = XmlAnySimpleType.type;
        }
        return type;
    }

    public void release() {
        if (_cur != null) {
            _cur.release();
            _cur = null;
        }
    }

}


text:
#import "UAPushSettingsTokenViewController.h"
#import "UAirship.h"

#if __IPHONE_OS_VERSION_MAX_ALLOWED < 60000
// This is available in iOS 6.0 and later, define it for older versions
#define NSLineBreakByWordWrapping 0
#endif

@implementation UAPushSettingsTokenViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"Device Token";

    self.text = @"Your current device token. Test a push notification at "
           @"https://go.urbanairship.com";
}

- (void)viewWillAppear:(BOOL)animated {
    self.tokenLabel.text = [UAirship shared].deviceToken ? [UAirship shared].deviceToken : @"Unavailable";
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)viewDidUnload {
    [super viewDidUnload];
    self.emailButton = nil;
    self.tokenLabel = nil;
}

#pragma mark -
#pragma mark UITableViewDelegate

#define kCellPaddingHeight 10

- (CGFloat)tableView: (UITableView *) tableView heightForRowAtIndexPath:(NSIndexPath *) indexPath {
    UIFont *font = [UIFont systemFontOfSize:17];
    CGFloat height = [self.text sizeWithFont:font
                      constrainedToSize:CGSizeMake(280.0, 1500.0)
                          lineBreakMode:NSLineBreakByWordWrapping].height;
    return height + kCellPaddingHeight;
}

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UIImage *bgImage = [UIImage imageNamed:@"middle-detail.png"];
    UIImage *stretchableBgImage = [bgImage stretchableImageWithLeftCapWidth:20 topCapHeight:0];
    UIImageView *bgImageView = [[UIImageView alloc] initWithImage: stretchableBgImage];

    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"description-cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:@"description-cell"];
    }

    UIFont *font = [UIFont systemFontOfSize: 17];

    UILabel* description = [[UILabel alloc] init];
    description.text = self.text;
    description.lineBreakMode = UILineBreakModeWordWrap;
    description.numberOfLines = 0;
    description.backgroundColor = [UIColor clearColor];
    [description setFont: font];
    CGFloat height = [self.text sizeWithFont:font
                      constrainedToSize:CGSizeMake(280.0, 800.0)
                          lineBreakMode:NSLineBreakByWordWrapping].height;
    [description setFrame: CGRectMake(0.0f, 10.0f, 320.0f, height)];
    [description setBounds: CGRectMake(0.20f, 0.0f, 290.0f, height)];
    [description setAutoresizingMask:UIViewAutoresizingFlexibleWidth];

    [cell addSubview: description];
    [cell setSelectionStyle: UITableViewCellSelectionStyleNone];
    [cell setBackgroundView: bgImageView];

    return cell;
}

#pragma mark -
#pragma mark UI Button Actions
- (IBAction)copyDeviceToken {
    NSString *token = [UAirship shared].deviceToken;
    if (token) {
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = token;
    }
}

- (IBAction)emailDeviceToken {

    if ([MFMailComposeViewController canSendMail]) {
		MFMailComposeViewController *mfViewController = [[MFMailComposeViewController alloc] init];
		mfViewController.mailComposeDelegate = self;

        NSString *messageBody = [NSString stringWithFormat:@"Your device token is %@\n\nSend a test push at http://go.urbanairship.com", [UAirship shared].deviceToken];

        [mfViewController setSubject:@"Device Token"];
        [mfViewController setMessageBody:messageBody isHTML:NO];

		[self presentModalViewController:mfViewController animated:YES];
	}else {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Your device is not currently configured to send mail." delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];

		[alert show];
	}
}

#pragma mark -
#pragma mark MFMailComposeViewControllerDelegate Methods

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message Status" message:@"" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

	switch (result) {
		case MFMailComposeResultCancelled:
			//alert.message = @"Canceled";
			break;
		case MFMailComposeResultSaved:
			//alert.message = @"Saved";
			break;
		case MFMailComposeResultSent:
			alert.message = @"Sent";
            [alert show];
			break;
		case MFMailComposeResultFailed:
			//alert.message = @"Message Failed";
			break;
		default:
			//alert.message = @"Message Not Sent";
        break;
    }

	[self dismissModalViewControllerAnimated:YES];

}

@end


text:
/*body .well, .container .well, .container-fluid .well, body .jumbotron, .container .jumbotron, .container-fluid .jumbotron, body .well-default, .container .well-default, .container-fluid .well-default, body .jumbotron-default, .container .jumbotron-default, .container-fluid .jumbotron-default {
  background-color:#3498db;
  color:#ecf0f1;
}*/
body .well, .container .well, .container-fluid .well, body .jumbotron, .container .jumbotron, .container-fluid .jumbotron, body .well-default, .container .well-default, .container-fluid .well-default, body .jumbotron-default, .container .jumbotron-default, .container-fluid .jumbotron-default h1 {
  font-family: lobster, sans-serif;
}
body .well, .container .well, .container-fluid .well, body .jumbotron, .container .jumbotron, .container-fluid .jumbotron, body .well-default, .container .well-default, .container-fluid .well-default, body .jumbotron-default, .container .jumbotron-default, .container-fluid .jumbotron-default h3 {
  font-family: Open sans;
}
body {
  padding-top:100px;
}

.search {
  width:100vw;
  padding:5px;
  font-family:open sans;
  font-size:1.2em;
}


text:
import * as vscode from 'vscode';
import { ITextDocument } from '../types/textDocument';
import { Disposable } from '../util/dispose';
import { isMarkdownFile, looksLikeMarkdownPath } from '../util/file';
import { InMemoryDocument } from './inMemoryDocument';
import { ResourceMap } from '../util/resourceMap';

/**
 * Provides set of markdown files known to VS Code.
 *
 * This includes both opened text documents and markdown files in the workspace.
 */
export class VsCodeMdWorkspace extends Disposable {

	private _watcher: vscode.FileSystemWatcher | undefined;

	private readonly _documentCache = new ResourceMap<ITextDocument>();

	private readonly _utf8Decoder = new TextDecoder('utf-8');

	constructor() {
		super();

		this._watcher = this._register(vscode.workspace.createFileSystemWatcher('**/*.md'));

		this._register(this._watcher.onDidChange(async resource => {
			this._documentCache.delete(resource);
		}));

		this._register(this._watcher.onDidDelete(resource => {
			this._documentCache.delete(resource);
		}));

		this._register(vscode.workspace.onDidOpenTextDocument(e => {
			this._documentCache.delete(e.uri);
		}));

		this._register(vscode.workspace.onDidCloseTextDocument(e => {
			this._documentCache.delete(e.uri);
		}));
	}

	private _isRelevantMarkdownDocument(doc: vscode.TextDocument) {
		return isMarkdownFile(doc) && doc.uri.scheme !== 'vscode-bulkeditpreview';
	}

	public async getOrLoadMarkdownDocument(resource: vscode.Uri): Promise<ITextDocument | undefined> {
		const existing = this._documentCache.get(resource);
		if (existing) {
			return existing;
		}

		const matchingDocument = vscode.workspace.textDocuments.find((doc) => this._isRelevantMarkdownDocument(doc) && doc.uri.toString() === resource.toString());
		if (matchingDocument) {
			this._documentCache.set(resource, matchingDocument);
			return matchingDocument;
		}

		if (!looksLikeMarkdownPath(resource)) {
			return undefined;
		}

		try {
			const bytes = await vscode.workspace.fs.readFile(resource);

			// We assume that markdown is in UTF-8
			const text = this._utf8Decoder.decode(bytes);
			const doc = new InMemoryDocument(resource, text, 0);
			this._documentCache.set(resource, doc);
			return doc;
		} catch {
			return undefined;
		}
	}
}


text:
CREATE TABLE STREAM_DEFINITIONS  (
	DEFINITION_NAME VARCHAR(255) NOT NULL PRIMARY KEY,
	DEFINITION TEXT DEFAULT NULL
) ENGINE=InnoDB;

CREATE TABLE STREAM_DEPLOYMENTS  (
	STREAM_NAME VARCHAR(255) NOT NULL PRIMARY KEY,
	DEPLOYMENT_PROPS VARCHAR(1000)
) ENGINE=InnoDB;


text:
<?php

// You should move the config.ini outside the web directory.
$config_file_path = "/opt/config/config.ini"; // Path to config file, replace the expression after the "=" sign. Don't forget to leave the ";" at the end of the line. You should place it outside of web root
// Don't forget to make sure this is set properly...

Ini_Set( 'display_errors', false);
include 'init.php';
include 'lib/phpseclib0.3.5/Net/SSH2.php';
require_once 'MinecraftServerStatus.class.php';

if (!file_exists ($config_file_path)) {
    $config_file_path = "../../config.ini";
}

$config = parse_ini_file($config_file_path, true);

// Import variables from config file
// Network Details
$local_server_ip = $config['network_details']['local_server_ip'];
$wan_domain = $config['network_details']['wan_domain'];
$wan1_ip = $config['network_details']['wan1_ip'];
$wan2_ip = $config['network_details']['wan2_ip'];
$ping_ip = $config['network_details']['ping_ip'];

// Weather
$weather_always_display = $config['weather']['weather_always_display'];
$weather_lat = $config['weather']['weather_lat'];
$weather_long = $config['weather']['weather_long'];
$weather_name = $config['weather']['weather_name'];
$forecast_api = $config['weather']['forecast_api'];
$weather_units = $config['weather']['weather_units'];

// Misc
//$trakt_username = $config['misc']['trakt_username'];
//$trakt_api_key = $config['misc']['trakt_api_key'];
//$trakt_redirect_url = $config['misc']['trakt_redirect_url'];
if (isset($config['misc']['cpu_cores'])) {
	$cpu_cores = $config['misc']['cpu_cores'];
}
else {
	$cpu_cores = num_cpus();
}

// storage
$volume_names[] = $config['storage']['volume_name'];
$volume_paths[] = $config['storage']['volume_path'];

//This is a new attempt at using objects to track different services
/*
global $services;

function add_service($instances) {
	global $services;

	foreach ($instances as $instance) {
		$temp_object = new service(array_values($instance)[0],array_values($instance)[1],array_values($instance)[2],array_values($instance)[3]);
		$services[] = $temp_object;
	}
}

foreach ($service_instances as $service_instance) {
	add_service($service_instance);
}
*/
//print_r(array_values($config['plex']['server_name']));

// Services
$pfSense_config_lines = 6;
$plex_config_lines = 6;
$sabnzbd_config_lines = 8;
$couchpotato_config_lines = 6;
$sickbeard_config_lines = 6;
$minecraft_config_lines = 4;
$deluge_config_lines = 6;

global	$pfSense_instances;
global	$plex_instances;
global	$couchpotato_instances;
global	$sickbeard_instances;
global	$sabnzbd_instances;
global	$deluge_instances;
global	$minecraft_instances;

//global $pfSense_instances;
$pfSense_instances = array();
if (isset($config['pfSense'])) {
	$pfSense_config_line_count = (count($config['pfSense'], COUNT_RECURSIVE) - $pfSense_config_lines);
	if ($pfSense_config_line_count >= $pfSense_config_lines){
		for ($i=1; $i <= $pfSense_config_line_count; $i++) {
			$num = ceil($i/$pfSense_config_lines); //this is checking to make sure there are only x number of config lines.... it is probably a really dumb way to do this.
			$pfSense_instances[$num][0] = $config['pfSense']['server_name'][$num];
			$pfSense_instances[$num][1] = $config['pfSense']['local_port'][$num];
			$pfSense_instances[$num][2] = $config['pfSense']['URL'][$num];
			$pfSense_instances[$num][3] = $config['pfSense']['local_ip'][$num];
			$pfSense_instances[$num][4] = $config['pfSense']['username'][$num];
			$pfSense_instances[$num][5] = $config['pfSense']['password'][$num];
		}
	}
	else {
		$pfSense_instances = NULL;
	}
}

//global $plex_instances;
$plex_instances = array();
if (isset($config['plex'])) {
	$plex_config_line_count = (count($config['plex'], COUNT_RECURSIVE) - $plex_config_lines);
	if ($plex_config_line_count >= $plex_config_lines){
		for ($i=1; $i <= $plex_config_line_count; $i++) {
			$num = ceil($i/$plex_config_lines);
			$plex_instances[$num][0] = $config['plex']['server_name'][$num];
			$plex_instances[$num][1] = $config['plex']['local_port'][$num];
			$plex_instances[$num][2] = $config['plex']['URL'][$num];
			$plex_instances[$num][3] = $config['plex']['local_ip'][$num];
			$plex_instances[$num][4] = $config['plex']['username'][$num];
			$plex_instances[$num][5] = $config['plex']['password'][$num];
		}
	}
	else {
		$plex_instances = NULL;
	}
}

//global $couchpotato_instances;
$couchpotato_instances = array();
if (isset($config['couchpotato'])) {
	$couchpotato_config_line_count = (count($config['couchpotato'], COUNT_RECURSIVE) - $couchpotato_config_lines);
	if ($couchpotato_config_line_count >= $couchpotato_config_lines) {
		for ($i=1; $i <= $couchpotato_config_line_count; $i++) {
			$num = ceil($i/$couchpotato_config_lines);
			$couchpotato_instances[$num][0] = $config['couchpotato']['server_name'][$num];
			$couchpotato_instances[$num][1] = $config['couchpotato']['local_port'][$num];
			$couchpotato_instances[$num][2] = $config['couchpotato']['URL'][$num];
			$couchpotato_instances[$num][3] = $config['couchpotato']['local_ip'][$num];
			$couchpotato_instances[$num][4] = $config['couchpotato']['username'][$num];
			$couchpotato_instances[$num][5] = $config['couchpotato']['password'][$num];
		}
	}
	else {
		$couchpotato_instances = NULL;
	}
}

//global $sickbeard_instances;
$sickbeard_instances = array();
if (isset($config['sickbeard'])) {
	$sickbeard_config_line_count = (count($config['sickbeard'], COUNT_RECURSIVE) - $sickbeard_config_lines);
	if ($sickbeard_config_line_count >= $sickbeard_config_lines) {
		for ($i=1; $i <= $sickbeard_config_line_count; $i++) {
			$num = ceil($i/$sickbeard_config_lines);
			$sickbeard_instances[$num][0] = $config['sickbeard']['server_name'][$num];
			$sickbeard_instances[$num][1] = $config['sickbeard']['local_port'][$num];
			$sickbeard_instances[$num][2] = $config['sickbeard']['URL'][$num];
			$sickbeard_instances[$num][3] = $config['sickbeard']['local_ip'][$num];
			$sickbeard_instances[$num][4] = $config['sickbeard']['username'][$num];
			$sickbeard_instances[$num][5] = $config['sickbeard']['password'][$num];
		}
	}
	else {
		$sickbeard_instances = NULL;
	}
}

//global $minecraft_instances;
$minecraft_instances = array();
if (isset($config['minecraft'])) {
	$minecraft_config_line_count = (count($config['minecraft'], COUNT_RECURSIVE) - $minecraft_config_lines);

	if ($minecraft_config_line_count >= $minecraft_config_lines) {
		for ($i=1; $i <= $minecraft_config_line_count; $i++) {
			$num = ceil($i/$minecraft_config_lines);
			$minecraft_instances[$num][0] = $config['minecraft']['server_name'][$num];
			$minecraft_instances[$num][1] = $config['minecraft']['local_port'][$num];
			$minecraft_instances[$num][2] = $config['minecraft']['URL'][$num];
			$minecraft_instances[$num][3] = $config['minecraft']['local_ip'][$num];
		}
	}
	else {
		$minecraft_instances = NULL;
	}
}

//global $deluge_instances;
$deluge_instances = array();
if (isset($config['deluge'])) {
	$deluge_config_line_count = (count($config['deluge'], COUNT_RECURSIVE) - $deluge_config_lines);
	if ($deluge_config_line_count >= $deluge_config_lines) {
		for ($i=1; $i <= $deluge_config_line_count; $i++) {
			$num = ceil($i/$deluge_config_lines);
			$deluge_instances[$num][0] = $config['deluge']['server_name'][$num];
			$deluge_instances[$num][1] = $config['deluge']['local_port'][$num];
			$deluge_instances[$num][2] = $config['deluge']['URL'][$num];
			$deluge_instances[$num][3] = $config['deluge']['local_ip'][$num];
			$deluge_instances[$num][4] = $config['deluge']['username'][$num];
			$deluge_instances[$num][5] = $config['deluge']['password'][$num];
		}
	}
	else {
		$deluge_instances = NULL;
	}
}

//global $sabnzbd_instances;
$sabnzbd_instances = array();
if (isset($config['sabnzbd'])) {
	$sabnzbd_config_line_count = (count($config['sabnzbd'], COUNT_RECURSIVE) - $sabnzbd_config_lines);
	if ($sabnzbd_config_line_count >= $sabnzbd_config_lines) {
		for ($i=1; $i <= $sabnzbd_config_line_count; $i++) {
			$num = ceil($i/$sabnzbd_config_lines);
			$sabnzbd_instances[$num][0] = $config['sabnzbd']['server_name'][$num];
			$sabnzbd_instances[$num][1] = $config['sabnzbd']['local_port'][$num];
			$sabnzbd_instances[$num][2] = $config['sabnzbd']['URL'][$num];
			$sabnzbd_instances[$num][3] = $config['sabnzbd']['local_ip'][$num];
			$sabnzbd_instances[$num][4] = $config['sabnzbd']['api'][$num];
			$sabnzbd_instances[$num][5] = $config['sabnzbd']['sabSpeedLimitMax'][$num];
			$sabnzbd_instances[$num][6] = $config['sabnzbd']['sabSpeedLimitMin'][$num];
			$sabnzbd_instances[$num][7] = $config['sabnzbd']['ping_throttle'][$num];
		}
	}
	else {
		$sabnzbd_instances = NULL;
	}
}

$service_instances = array(
	$pfSense_instances,
	$plex_instances,
	$couchpotato_instances,
	$sickbeard_instances,
	$sabnzbd_instances,
	$deluge_instances,
	$minecraft_instances
	);

/*
// Global variable declarations
global $plex_server_name;
global $couchpotato_server_name;
global $sickbeard_server_name;
global $sabnzbd_server_name;
global $minecraft_server_name;

//global $pfSense_ip;
//global $pfSense_URL;
//global $pfSense_username;
//global $pfSense_password;
global $local_server_ip;
global $wan_domain;
global $plex_ip;
global $plex_port;
global $plex_username;
global $plex_password;
global $plex_URL;
global $sabnzbd_ip;
global $sabnzbd_port;
global $sabnzbd_URL;
global $sabnzbd_api;
global $sabnzbdSpeedLimitMin;
global $sabnabdSpeedLimitMax;
global $couchpotato_ip;
global $couchpotato_port;
global $couchpotato_username;
global $couchpotato_password;
global $couchpotato_URL;
global $sickbeard_ip;
global $sickbeard_port;
global $sickbeard_username;
global $sickbeard_password;
global $sickbeard_URL;
*/
// Set the path for the Plex Token
$plexTokenCache = ROOT_DIR . '/assets/caches/plex_token.txt';
// Check to see if the plex token exists and is younger than one week
// if not grab it and write it to our caches folder
if (file_exists($plexTokenCache) && (filemtime($plexTokenCache) > (time() - 60 * 60 * 24 * 7))) {
	$plexToken = file_get_contents(ROOT_DIR . '/assets/caches/plex_token.txt');
} else {
	file_put_contents($plexTokenCache, getPlexToken());
	$plexToken = file_get_contents(ROOT_DIR . '/assets/caches/plex_token.txt');
}

// Calculate server load
$loads = sys_getloadavg();
#else
#	$loads = Array(0.55,0.7,1);

// Set the total disk space
$ereborTotalSpace = 8.961019766e+12; // This is in bytes
$televisionTotalSpace = 1.196268651e+13; // This is in bytes
$television2TotalSpace = 5.959353023e+12; // This is in bytes

// This is if you want to get a % of cpu usage in real time instead of load.
// After using it for a week I determined that it gave me a lot less information than load does.
function getCpuUsage()
{
	$top = shell_exec('top -l 1 -n 0');
	$findme = 'idle';
	$cpuIdleStart = strpos($top, $findme);
	$cpuIdle = substr($top, ($cpuIdleStart - 7), 2);
	$cpuUsage = 100 - $cpuIdle;
	return $cpuUsage;
}

function makeCpuBars()
{
	printBar(getCpuUsage(), "Usage");
}

// The below function's copyright information:
/**
 * Copyright © 2011 Erin Millard
 */

/**
 * Returns the number of available CPU cores
 *
 *  Should work for Linux, Windows, Mac & BSD
 *
 * @return integer
 */

function num_cpus()
{
  $numCpus = 1;

  if (is_file('/proc/cpuinfo'))
  {
    $cpuinfo = file_get_contents('/proc/cpuinfo');
    preg_match_all('/^processor/m', $cpuinfo, $matches);

    $numCpus = count($matches[0]);
  }
  else if ('WIN' == strtoupper(substr(PHP_OS, 0, 3)))
  {
    $process = @popen('wmic cpu get NumberOfCores', 'rb');

    if (false !== $process)
    {
      fgets($process);
      $numCpus = intval(fgets($process));

      pclose($process);
    }
  }
  else
  {
    $process = @popen('sysctl -a', 'rb');

    if (false !== $process)
    {
      $output = stream_get_contents($process);

      preg_match('/hw.ncpu: (\d+)/', $output, $matches);
      if ($matches)
      {
        $numCpus = intval($matches[1][0]);
      }

      pclose($process);
    }
  }

  return $numCpus;
}

function makeTotalDiskSpace()
{
	$du = getDiskspaceUsed("/");
	/*+ getDiskspaceUsed("/Volumes/Time Machine") + getDiskspaceUsed("/Volumes/Isengard") + getDiskspaceUsed("/Volumes/1TB Portable") + getDiskspaceUsed("/Volumes/WD2.2") + getDiskspaceUsed("/Volumes/WD2.1") + getDiskspaceUsed("/Volumes/Barad-dur") + getDiskspaceUsed("/Volumes/Erebor") + getDiskspaceUsed("/Volumes/Television") + getDiskspaceUsed("/Volumes/Television 2");
	*/
	$dts = disk_total_space("/");
	/*+ disk_total_space("/Volumes/Time Machine") + disk_total_space("/Volumes/Isengard") + disk_total_space("/Volumes/1TB Portable") + disk_total_space("/Volumes/WD2.2") + disk_total_space("/Volumes/WD2.1") + disk_total_space("/Volumes/Barad-dur") + $GLOBALS['ereborTotalSpace'] + $GLOBALS['televisionTotalSpace'] + $GLOBALS['television2TotalSpace']
	*/
	$dfree = $dts - $du;
	printTotalDiskBar(sprintf('%.0f',($du / $dts) * 100), "Total Capacity", $dfree, $dts);
}

function byteFormat($bytes, $unit = "", $decimals = 2) {
	$units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4,
			'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);

	$value = 0;
	if ($bytes > 0) {
		// Generate automatic prefix by bytes
		// If wrong prefix given
		if (!array_key_exists($unit, $units)) {
			$pow = floor(log($bytes)/log(1000));
			$unit = array_search($pow, $units);
		}

		// Calculate byte value by prefix
		$value = ($bytes/pow(1000,floor($units[$unit])));
	}

	// If decimals is not numeric or decimals is less than 0
	// then set default value
	if (!is_numeric($decimals) || $decimals < 0) {
		$decimals = 2;
	}

	// Format output
	return sprintf('%.' . $decimals . 'f '.$unit, $value);
  }

  function autoByteFormat($bytes) {
  	// If we are working with more than 0 and less than 1000GB (Apple filesystem).
  	if (($bytes >= 0) && ($bytes < 1000000000000)) {
  		$unit = 'GB';
  		$decimals = 0;
  	// 1TB to 999TB
   	} elseif (($bytes >= 1000000000000) && ($bytes < 1.1259e15)) {
   		$unit = 'TB';
   		$decimals = 2;
   	}
   	return array($bytes, $unit, $decimals);
  }

function makeDiskBars()
{
	// For special drives like my Drobos I have to set the total disk space manually.
	// That is why you see the total space in bytes.
	printDiskBar(getDiskspace("/"), "SSD", disk_free_space("/"), disk_total_space("/"));
	/*
	printDiskBar(getDiskspace("/Volumes/Time Machine"), "Time Machine", disk_free_space("/Volumes/Time Machine"), disk_total_space("/Volumes/Time Machine"));
	printDiskBar(getDiskspace("/Volumes/Isengard"), "Isengard", disk_free_space("/Volumes/Isengard"), disk_total_space("/Volumes/Isengard"));
	printDiskBar(getDiskspace("/Volumes/WD2.2"), "Minas Tirith", disk_free_space("/Volumes/WD2.2"), disk_total_space("/Volumes/WD2.2"));
	printDiskBar(getDiskspace("/Volumes/WD2.1"), "Minas Morgul", disk_free_space("/Volumes/WD2.1"), disk_total_space("/Volumes/WD2.1"));
	printDiskBar(getDiskspace("/Volumes/Barad-dur"), "Barad-dûr", disk_free_space("/Volumes/Barad-dur"), disk_total_space("/Volumes/Barad-dur"));
	printDiskBar(getDiskspaceErebor("/Volumes/Erebor"), "Erebor", ($GLOBALS['ereborTotalSpace'] - getDiskspaceUsed("/Volumes/Erebor")), $GLOBALS['ereborTotalSpace']);
	printDiskBar(getDiskspaceTV1("/Volumes/Television"), "Narya", ($GLOBALS['televisionTotalSpace'] - getDiskspaceUsed("/Volumes/Television")), $GLOBALS['televisionTotalSpace']);
	printDiskBar(getDiskspaceTV2("/Volumes/Television 2"), "Nenya", ($GLOBALS['television2TotalSpace'] - getDiskspaceUsed("/Volumes/Television 2")), $GLOBALS['television2TotalSpace']);
	*/
}

function makeRamBars()
{
	printRamBar(getFreeRam()[0],getFreeRam()[1],getFreeRam()[2],getFreeRam()[3]);
}

function makeLoadBars()
{
	printBar(getLoad(0), "1 min");
	printBar(getLoad(1), "5 min");
	printBar(getLoad(2), "15 min");
}

function getFreeRam()
{
	// This is very customized to OS X, if using another OS you'll have to roll your own
	// This will output exactly what activity monitor in 10.9 reports as Memory Used
	// And while this works very well I disabled it because it's almost
	// meaningless to keep track of in OS X. What I care more about is Swap Used.
	$top = shell_exec('top -l 1 -n 0');
	$find_str_1 = 'unused.';
	$unusedStart = strpos($top, $find_str_1);
	// Grab the unused ram amount
	$unusedRam = trim(substr($top,($unusedStart-6),4))/1024; // GB
	// What is the total ram in the computer
	$totalRam = (substr(shell_exec('sysctl hw.memsize'), 12))/1024/1024/1024; // GB
	// Find the amount of used ram
	$usedRam = $totalRam - $unusedRam; // Find how much ram is used in GB.
	return array (sprintf('%.0f',($usedRam / $totalRam) * 100), 'Used Ram', $usedRam, $totalRam);
}

function getDiskspace($dir)
{
	$df = disk_free_space($dir);
	$dt = disk_total_space($dir);
	$du = $dt - $df;
	return sprintf('%.0f',($du / $dt) * 100);
}

function getDiskspaceUsed($dir)
{
	$df = disk_free_space($dir);
	$dt = disk_total_space($dir);
	$du = $dt - $df;
	return $du;
}

function getLoad($id)
{
	global $cpu_cores;
	return 100 * ($GLOBALS["loads"][$id] / $cpu_cores);
}

function printBar($value, $name = "")
{
	if ($name != "") echo '';
	echo '
';
		if ($name != "")
			echo $name . ": ";
			echo number_format($value, 0) . "%";
		echo '
';
			echo '

';
		echo '
';
	echo '
';
}

function printRamBar($percent, $name = "", $used, $total)
{
	if ($percent < 90)
	{
		$progress = "progress-bar";
	}
	else if (($percent >= 90) && ($percent < 95))
	{
		$progress = "progress-bar progress-bar-warning";
	}
	else
	{
		$progress = "progress-bar progress-bar-danger";
	}

	if ($name != "") echo '';
	echo '
';
		if ($name != "")
			echo $name . ": ";
			echo number_format($percent, 0) . "%";
		echo '
';
			echo '

';
		echo '
';
	echo '
';
}

function printDiskBar($dup, $name = "", $dsu, $dts)
{
	// Using autoByteFormat() the amount of space will be formatted as GB or TB as needed.
	if ($dup < 90)
	{
		$progress = "progress-bar";
	}
	else if (($dup >= 90) && ($dup < 95))
	{
		$progress = "progress-bar progress-bar-warning";
	}
	else
	{
		$progress = "progress-bar progress-bar-danger";
	}

	if ($name != "") echo '';
	echo '
';
		if ($name != "")
			echo $name . ": ";
			echo number_format($dup, 0) . "%";
		echo '
';
			echo '

';
		echo '
';
	echo '
';
}

function printTotalDiskBar($dup, $name = "", $dsu, $dts)
{
	// Using autoByteFormat() the amount of space will be formatted as GB or TB as needed.
	if ($dup < 95)
	{
		$progress = "progress-bar";
	}
	else if (($dup >= 95) && ($dup < 99))
	{
		$progress = "progress-bar progress-bar-warning";
	}
	else
	{
		$progress = "progress-bar progress-bar-danger";
	}

	if ($name != "") echo '';
	echo '
';
		if ($name != "")
			echo $name . ": ";
			echo number_format($dup, 0) . "%";
		echo '
';
			echo '

';
		echo '
';
	echo '
';
}

function ping()
{
	global $pfSense_ip;
	global $ping_ip;

	$clientIP = get_client_ip();
	//$pingIP = '8.8.8.8';
	if($clientIP != $pfSense_ip) {
		$ping_ip = $clientIP;
	}
	$terminal_output = shell_exec('ping -c 5 -q '.$ping_ip);
	// If using something besides OS X you might want to customize the following variables for proper output of average ping.
	$findme_start = '= ';
	$start = strpos($terminal_output, $findme_start);
	$ping_return_value_str = substr($terminal_output, ($start +2), 100);
	$findme_stop1 = '.';
	$stop = strpos($ping_return_value_str, $findme_stop1);
	$findme_avgPing_decimal = '.';
	$avgPing_decimal = strpos($ping_return_value_str, $findme_avgPing_decimal, 6);
	$findme_forward_slash = '/';
	$avgPing_forward_slash = strpos($ping_return_value_str, $findme_forward_slash);
	$avgPing = substr($ping_return_value_str, ($stop + 5), ($avgPing_decimal - $avgPing_forward_slash - 1));
	return $avgPing;
}

function getNetwork($plex_ip)
{
	// It should be noted that this function is designed specifically for getting the local / wan name for Plex.
	global $wan_domain;
	//global $plex_ip;
    #global $isRFCSpace;

    $isRFCSpace = preg_match("/(^10\.)|(^127\.0\.0\.1)|(^192\.168\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)/", get_client_ip());
	if($isRFCSpace):
		$network='http://'.$plex_ip;
	else:
		$network='http://'.$wan_domain;
	endif;
	return $network;
}

function get_client_ip()
{
	if ( isset($_SERVER["REMOTE_ADDR"])) {
		$ipaddress = $_SERVER["REMOTE_ADDR"];
	}else if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
		$ipaddress = $_SERVER["HTTP_X_FORWARDED_FOR"];
	}else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
		$ipaddress = $_SERVER["HTTP_CLIENT_IP"];
	}
	return $ipaddress;
}

function sabSpeedAdjuster()
{
	global $sabnzbd_ip;
	global $sabnzbd_port;
	global $sabnzbd_api;
	global $sabnabdSpeedLimitMax;
	global $sabnzbdSpeedLimitMin;
	// Set how high ping we want to hit before throttling
	global $ping_throttle;

	// Check the current ping
	$avgPing = ping();
	// Get SABnzbd XML
	$sabnzbdXML = simplexml_load_file('http://'.$sabnzbd_ip.':'.$sabnzbd_port.'/api?mode=queue&start=START&limit=LIMIT&output=xml&apikey='.$sabnzbd_api);
	// Get current SAB speed limit
	$sabSpeedLimitCurrent = $sabnzbdXML->speedlimit;

	// Check to see if SAB is downloading
	if (($sabnzbdXML->status) == 'Downloading'):
			// If it is downloading and ping is over X value, slow it down
			if ($avgPing > $ping_throttle):
				if ($sabSpeedLimitCurrent > $sabnzbdSpeedLimitMin):
					// Reduce speed by 256KBps
					echo 'Ping is over '.$ping_throttle;
					echo '
';
					echo 'Slowing down SAB';
					$sabSpeedLimitSet = $sabSpeedLimitCurrent - 256;
					shell_exec('curl "http://'.$sabnzbd_ip.':'.$sabnzbd_port.'/api?mode=config&name=speedlimit&value='.$sabSpeedLimitSet.'&apikey='.$sabnzbd_api.'"');
				else:
					echo 'Ping is over '.$ping_throttle.' but SAB cannot slow down anymore';
				endif;
			elseif (($avgPing . 9) < $ping_throttle):
				if ($sabSpeedLimitCurrent < $sabnabdSpeedLimitMax):
					// Increase speed by 256KBps
					echo 'SAB is downloading and ping is '.($avgPing . 9).'  so increasing download speed.';
					$sabSpeedLimitSet = $sabSpeedLimitCurrent + 256;
					shell_exec('curl "http://'.$sabnzbd_ip.':'.$sabnzbd_port.'/api?mode=config&name=speedlimit&value='.$sabSpeedLimitSet.'&apikey='.$sabnzbd_api.'"');
				else:
					echo 'SAB is downloading. Ping is low enough but we are at global download speed limit.';
				endif;
			else:
				echo 'SAB is downloading. Ping is ok but not low enough to speed up SAB.';
			endif;
		else:
			// do nothing,
			echo 'SAB is not downloading.';
		endif;
}

function makeRecentlyViewed()
{
	//global $pfSense_ip;
	//global $plex_port;
	global $trakt_username;
	global $weather_lat;
	global $weather_long;
	global $weather_name;
	global $plex_instances;

	foreach ($plex_instances as $instance) {
		$plex_port = $instance[1];
		$network = getNetwork($instance[3]);
		$clientIP = get_client_ip();
		$plexSessionXML = simplexml_load_file($network.':'.$plex_port.'/status/sessions');
/*		$trakt_url = 'http://trakt.tv/users/'.$trakt_username.'/widgets/watched/all-tvthumb.jpg';
		$traktThumb = 'assets/caches/thumbnails/all-tvthumb.jpg';
        callTraktAPI();
		echo '
';
		echo '';
		if (file_exists($traktThumb) && (filemtime($traktThumb) > (time() - 60 * 15))) {
			// Trakt image is less than 15 minutes old.
			// Don't refresh the image, just use the file as-is.
			echo '';
		} else {
			// Either file doesn't exist or our cache is out of date,
			// so check if the server has different data,
			// if it does, load the data from our remote server and also save it over our cache for next time.
			$thumbFromTrakt_md5 = md5_file($trakt_url);
			$traktThumb_md5 = md5_file($traktThumb);
			if ($thumbFromTrakt_md5 === $traktThumb_md5) {
				echo '';
			} else {
				$thumbFromTrakt = file_get_contents($trakt_url);
				file_put_contents($traktThumb, $thumbFromTrakt, LOCK_EX);
				echo '';

			}
		}
		*/
		// This checks to see if you are inside your local network. If you are it gives you the forecast as well.
		if($clientIP != getNetwork($clientIP) && count($plexSessionXML->Video) == 0) {
			echo '
';
			echo '
';
			echo 'Forecast
';
			echo ' ';
		}
		echo '
';

	}
}
/*
function callTraktAPI()
{
    global $trakt_api_key;
    global $trakt_username;
    echo $trakt_api_key;
    echo $trakt_username;
    $trakt_api_url = 'https://api-v2launch.trakt.tv/users/'.$trakt_username;
    $trakt_call['https']['method'] = 'GET';
    $trakt_call['https']['header'] = "Content-type: application/json\r\n";
    $trakt_call['https']['header'] .= "trakt-api-key: ".$trakt_api_key."\r\n";
    $trakt_call['https']['header'] .= "trakt-api-version: 2\r\n";
    $trakt_call['https']['header']
    $context = stream_context_create($trakt_call);
    $contents = file_get_contents($trakt_api_url, false, $context);
    echo $contents;

    $request = new HttpRequest();
    $request->setUrl('https://api-v2launch.trakt.tv/users/scytherswings');
    $request->setMethod(HTTP_METH_GET);

    $request->setHeaders(array(
        'trakt-api-version' => '2',
        'trakt-api-key' => 'c70dbe0b15d57f97e7baad16024ba0fd32a26ba9531a938f3b893d03e026b742',
        'content-type' => 'application/json'
    ));

    try {
        $response = $request->send();

        echo $response->getBody();
    } catch (HttpException $ex) {
        echo $ex;
    }
}*/

function makeRecentlyReleased()
{
    global $plex_instances;
	foreach ($plex_instances as $instance) {
		$plex_port = $instance[1];
		$network = getNetwork($instance[3]);
		$clientIP = get_client_ip();
		// Various items are commented out as I was playing with what information to include.

		$plexNewestXML = simplexml_load_file($network.':'.$plex_port.'/library/sections/1/newest'); //the number relates to how many libraries you have..i think..

		//echo '
';
		echo '
';
		echo '
';
		echo '
';
		echo '';
		echo '
';
		echo '
';
		$mediaKey = $plexNewestXML->Video[0]['key'];
		$mediaXML = simplexml_load_file($network.':'.$plex_port.$mediaKey);
		$movieTitle = $mediaXML->Video['title'];
		$movieArt = $mediaXML->Video['thumb'];
		echo '';
		echo '
'; // Close item div
		$i=1;
		for ( ; ; ) {
			if($i==15) break;
			$mediaKey = $plexNewestXML->Video[$i]['key'];
			$mediaXML = simplexml_load_file($network.':'.$plex_port.$mediaKey);
			$movieTitle = $mediaXML->Video['title'];
			$movieArt = $mediaXML->Video['thumb'];
			$movieYear = $mediaXML->Video['year'];
			echo '
';
			echo '';
			//echo '
';
			//echo '
'.$movieTitle.$movieYear.'
';
			//echo '
Summary
';
			//echo '
';
			echo '
'; // Close item div
			$i++;
		}
		echo '
'; // Close carousel-inner div
		echo '
'; // Close thumbnail div
		echo '';
		echo '';
		//echo '';
		echo '';
		echo '';
		//echo '';
		echo '';
		echo '
'; // Close carousel slide div
		echo '
'; // Close column div
	}
}

function makeNowPlaying()
{
	global $plex_instances;

	foreach ($plex_instances as $instance) {
		$plex_port = $instance[1];
		$network = getNetwork($instance[3]);
		$clientIP = get_client_ip();
		$plexSessionXML = simplexml_load_file($network.':'.$plex_port.'/status/sessions');

		if (!$plexSessionXML):
			makeRecentlyViewed();
		elseif (count($plexSessionXML->Video) == 0):
			makeRecentlyReleased();
		else:
			$i = 0; // Initiate and assign a value to i & t
			$t = 0; // T is the total amount of sessions
			echo '
';
			//echo '
';
			foreach ($plexSessionXML->Video as $sessionInfo):
				$t++;
			endforeach;
			foreach ($plexSessionXML->Video as $sessionInfo):
				$mediaKey = $sessionInfo['key'];
				$playerTitle = $sessionInfo->Player['title'];
				$mediaXML = simplexml_load_file($network.':'.$plex_port.$mediaKey);
				$type = $mediaXML->Video['type'];
				echo '
';
				$i++; // Increment i every pass through the array
				if ($type == "movie"):
					// Build information for a movie
					$movieArt = $mediaXML->Video['thumb'];
					$movieTitle = $mediaXML->Video['title'];
					$duration = $plexSessionXML->Video[$i-1]['duration'];
					$viewOffset = $plexSessionXML->Video[$i-1]['viewOffset'];
					$progress = sprintf('%.0f',($viewOffset / $duration) * 100);
					$user = $plexSessionXML->Video[$i-1]->User['title'];
					$device = $plexSessionXML->Video[$i-1]->Player['title'];
					$state = $plexSessionXML->Video[$i-1]->Player['state'];
					// Truncate movie summary if it's more than 50 words
					if (countWords($mediaXML->Video['summary']) < 51):
						$movieSummary = $mediaXML->Video['summary'];
					else:
						$movieSummary = limitWords($mediaXML->Video['summary'],50); // Limit to 50 words
						$movieSummary .= "..."; // Add ellipsis
					endif;
					echo '';
					// Make now playing progress bar
					//echo 'div id="now-playing-progress-bar">';
					echo '
';
					echo '
';
					echo '
';
					echo '
';
					echo '
';
					//echo '
'.$movieTitle.'
';
					echo '
'.$movieSummary.'
';
					if ($state == "playing"):
						// Show the playing icon
						echo '';
					else:
						echo '';
					endif;
					if ($user == ""):
						echo '
'.$device.'
';
					else:
						echo '
'.$user.'
';
					endif;
				else:
					// Build information for a tv show
					$tvArt = $mediaXML->Video['grandparentThumb'];
					$showTitle = $mediaXML->Video['grandparentTitle'];
					$episodeTitle = $mediaXML->Video['title'];
					$episodeSummary = $mediaXML->Video['summary'];
					$episodeSeason = $mediaXML->Video['parentIndex'];
					$episodeNumber = $mediaXML->Video['index'];
					$duration = $plexSessionXML->Video[$i-1]['duration'];
					$viewOffset = $plexSessionXML->Video[$i-1]['viewOffset'];
					$progress = sprintf('%.0f',($viewOffset / $duration) * 100);
					$user = $plexSessionXML->Video[$i-1]->User['title'];
					$device = $plexSessionXML->Video[$i-1]->Player['title'];
					$state = $plexSessionXML->Video[$i-1]->Player['state'];
					//echo '
';
					echo '';
					// Make now playing progress bar
					//echo 'div id="now-playing-progress-bar">';
					echo '
';
					echo '
';
					echo '
';
					echo '
';
					//echo '
';
					// Make description below thumbnail
					echo '
';
					//echo '
'.$showTitle.'
';
					echo '
Season '.$episodeSeason.'
';
					echo '
E'.$episodeNumber.' - '.$episodeTitle.'
';
					// Truncate episode summary if it's more than 50 words
					if (countWords($mediaXML->Video['summary']) < 51):
						$episodeSummary = $mediaXML->Video['summary'];
					else:
						$episodeSummary = limitWords($mediaXML->Video['summary'],50); // Limit to 50 words
						$episodeSummary .= "..."; // Add ellipsis
					endif;
					echo '
'.$episodeSummary.'
';
					if ($state == "playing"):
						// Show the playing icon
						echo '';
					else:
						echo '';
					endif;
					if ($user == ""):
						echo '
'.$device.'
';
					else:
						echo '
'.$user.'
';
					endif;
				endif;
				// Action buttons if we ever want to do something with them.
				//echo '
Action Action
';
				echo "
";
				echo "
";
				// Should we make
? Only if there is more than one video and it's not the last thumbnail created.
				if (($i > 0) && ($i < $t)):
					echo '
';
				else:
					// Do nothing
				endif;
			endforeach;
			echo '
';
		endif;
	}
}

function getTranscodeSessions()
{
	global $plex_instances;
	foreach ($plex_instances as $instance) {

		$plex_port = $instance[1];
		$network = getNetwork($instance[3]);
		$plexSessionXML = simplexml_load_file($network.':'.$plex_port.'/status/sessions');

		if (count($plexSessionXML->Video) > 0):
			$i = 0; // i is the variable that gets iterated each pass through the array
			$t = 0; // t is the total amount of sessions
			$transcodeSessions = 0; // this is the number of active transcodes
			foreach ($plexSessionXML->Video as $sessionInfo):
				$t++;
			endforeach;
			foreach ($plexSessionXML->Video as $sessionInfo):
				if ($sessionInfo->TranscodeSession['videoDecision'] == 'transcode') {
					$transcodeSessions++;
				};
				$i++; // Increment i every pass through the array
			endforeach;
			return $transcodeSessions;
		endif;
	    return 0;
	}
}

function makeBandwidthBars($interface)
{
	$array = getBandwidth($interface);
	$dPercent = sprintf('%.0f',($array[0] / 55) * 100);
	$uPercent = sprintf('%.0f',($array[1] / 5) * 100);
	printBandwidthBar($dPercent, 'Download', $array[0]);
	printBandwidthBar($uPercent, 'Upload', $array[1]);
}

function getBandwidth($interface)
{
	// For this to work with pfSense you have to have vnstat package installed and
	// you need to change the -i rl0 to the name of your interface for WAN e.g. -i <interface>
	// You will also probably need to do a var_dump of $output below and figure out exactly which array
	// values you need as they might be off by one or two each.
	global $pfSense_ip;
	global $pfSense_username;
	global $pfSense_password;
	$ssh = new Net_SSH2($pfSense_ip);
	if (!$ssh->login($pfSense_username,$pfSense_password)) {
		//exit('Login Failed');
		return array(0,0);
	}

	$dump = $ssh->exec('vnstat -i '.$interface.' -tr');
	$output = preg_split('/[,;| \s]/', $dump);
	for ($i=count($output)-1; $i>=0; $i--) {
		if ($output[$i] == '') unset ($output[$i]);
	}
	$output = array_values($output);
	$rxRate = $output[50];
	$rxFormat = $output[51];
	$txRate = $output[55];
	$txFormat = $output[56];
	if ($rxFormat == 'kbit/s') {
		$rxRateMB = $rxRate / 1024;
	} else {
		$rxRateMB = $rxRate;
	}
	if ($txFormat == 'kbit/s') {
		$txRateMB = $txRate / 1024;
	} else {
		$txRateMB = $txRate;
	}
	return  array($rxRateMB, $txRateMB);
}

function getPing($sourceIP,$destinationIP)
{
	// This will work with any pfSense install. $sourceIP is the IP address of the WAN that you want to
	// use to ping with. This allows you to ping the same address from multiple WANs if you need to.

	global $pfSense_ip;
	global $pfSense_username;
	global $pfSense_password;

	$ssh = new Net_SSH2($pfSense_ip);
	if (!$ssh->login($pfSense_username,$pfSense_password)) {
		//exit('Login Failed');
		return array(0,0);
	}
	$terminal_output = $ssh->exec('ping -c 5 -q -S '.$sourceIP.' '.$destinationIP);
	// If using something besides OS X you might want to customize the following variables for proper output of average ping.
	$findme_start = '= ';
	$start = strpos($terminal_output, $findme_start);
	$ping_return_value_str = substr($terminal_output, ($start +2), 100);
	$findme_stop1 = '.';
	$stop = strpos($ping_return_value_str, $findme_stop1);
	$findme_avgPing_decimal = '.';
	$avgPing_decimal = strpos($ping_return_value_str, $findme_avgPing_decimal, 6);
	$findme_forward_slash = '/';
	$avgPing_forward_slash = strpos($ping_return_value_str, $findme_forward_slash);
	$avgPing = substr($ping_return_value_str, ($stop + 5), ($avgPing_decimal - $avgPing_forward_slash - 1));
	return $avgPing;
}

function printBandwidthBar($percent, $name = "", $Mbps)
{
	if ($name != "") echo '';
	echo '
';
		if ($name != "")
			echo $name . ": ";
			echo number_format($Mbps, 2) . " Mbps";
		echo '
';
			echo '

';
		echo '
';
	echo '
';
}

function getMinecraftPlayers($port)
{
	$server = new MinecraftServerStatus('127.0.0.1',$port);
	$players = false;
	$numplayers = 0;
	if($server->Get('numplayers')>"0") {
		$players = true;
		$numplayers = $server->Get('numplayers');
	}

	return array($players, $numplayers);
}

function getPlexToken()
{
	global $plex_username;
	global $plex_password;
	$myPlex = shell_exec('curl -H "Content-Length: 0" -H "X-Plex-Client-Identifier: my-app" -u "'.$plex_username.'"":""'.$plex_password.'" -X POST https://my.plexapp.com/users/sign_in.xml 2> /dev/null');
	$myPlex_xml = simplexml_load_string($myPlex);
	$token = $myPlex_xml['authenticationToken'];
	return $token;
}

function countWords($string)
{
	$words = explode(" ",$string);
    return count($words);
}

function limitWords($string, $word_limit)
{
	$words = explode(" ",$string);
    return implode(" ",array_splice($words,0,$word_limit));
}

function getWindDir($b)
{
   $dirs = array('N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N');
   return $dirs[round($b/45)];
}

function makeWeatherSidebar()
{
	global $forecast_api;
	global $weather_lat;
	global $weather_long;
    global $weather_units;
    $wind_speed_units = "mph";
	$forecastExcludes = '?exclude=flags'; // Take a look at https://developer.forecast.io/docs/v2 to configure your weather information.
    if (strtoupper($weather_units) == "C") {
        $forecastExcludes = "?exclude=flags&units=ca";
        $wind_speed_units = "km/h";
    }
	$currentForecast = json_decode(file_get_contents('https://api.forecast.io/forecast/'.$forecast_api.'/'.$weather_lat.','.$weather_long.$forecastExcludes));

	$currentSummary = $currentForecast->currently->summary;
	$currentSummaryIcon = $currentForecast->currently->icon;
	$currentTemp = round($currentForecast->currently->temperature);
	$currentWindSpeed = round($currentForecast->currently->windSpeed);
	if ($currentWindSpeed > 0) {
		$currentWindBearing = $currentForecast->currently->windBearing;
	}
	$minutelySummary = $currentForecast->minutely->summary;
	$hourlySummary = $currentForecast->hourly->summary;

	$sunriseTime = $currentForecast->daily->data[0]->sunriseTime;
	$sunsetTime = $currentForecast->daily->data[0]->sunsetTime;

	if ($sunriseTime > time()) {
		$rises = 'Rises';
	} else {
		$rises = 'Rose';
	}

	if ($sunsetTime > time()) {
		$sets = 'Sets';
	} else {
		$sets = 'Set';
	}

	// If there are alerts, make the alerts variables
	if (isset($currentForecast->alerts)) {
		$alertTitle = $currentForecast->alerts[0]->title;
		$alertExpires = $currentForecast->alerts[0]->expires;
		$alertDescription = $currentForecast->alerts[0]->description;
		$alertUri = $currentForecast->alerts[0]->uri;
	}
	// Make the array for weather icons
	$weatherIcons = [
		'clear-day' => 'B',
		'clear-night' => 'C',
		'rain' => 'R',
		'snow' => 'W',
		'sleet' => 'X',
		'wind' => 'F',
		'fog' => 'L',
		'cloudy' => 'N',
		'partly-cloudy-day' => 'H',
		'partly-cloudy-night' => 'I',
	];
	$weatherIcon = $weatherIcons[$currentSummaryIcon];
	// If there is a severe weather warning, display it
	//if (isset($currentForecast->alerts)) {
	//	echo '
';
	//	echo '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>';
	//	echo ''.$alertTitle.'';
	//	echo '
';
	//}
	echo '
';
	echo '

';
	echo '

';
	echo '

'.$currentTemp.'°

';
	echo '

'.$currentSummary.'

';
	echo '

';
	echo '
';
	if ($currentWindSpeed > 0) {
		$direction = getWindDir($currentWindBearing);
		echo '
Wind: '.$currentWindSpeed.' '.$wind_speed_units.' from the '.$direction.'
';
	} else {
		echo '
Wind: Calm
';
	}
	echo '
Next Hour
';
	echo '
'.$minutelySummary.'
';
	echo '
Next 24 Hours
';
	echo '
'.$hourlySummary.'
';
	echo '
The Sun
';
	echo '
'.$rises.' at '.date('g:i A', $sunriseTime).'
';
	echo '
'.$sets.' at '.date('g:i A', $sunsetTime).'
';
	echo '
Forecast.io
 ';
}

?>


text:
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Contents**

- [Changing The Access Level of Users](#changing-the-access-level-of-users)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

## Changing The Access Level of Users

  1. Click on the **Employees** option on the left-hand side. Three options soon appear below (Search, Load New Census, Add New Employee) after clicking the Employees option.

  ![Imgur](http://i.imgur.com/Vk9bEec.png)

  2. Click **Search** to search for the Employee that you want to edit permissions for. This brings you to the **All Employees** screen.

  ![Imgur](http://i.imgur.com/ICBWU6U.png)

  3.  Under the **Filter All** box, enter the name or the email address of the person you want to edit the permissions for.

  **Note:** Please keep in mind that the CLEAN Marsalis platform does on the fly filtering, so there won't be any need to press enter after searching for the name you want to edit. The name should just appear within the requested company you are searching under.
  ![Imgur](http://i.imgur.com/aKsZIul.png)
  ![Imgur](http://i.imgur.com/5RSPFnW.png)
  4.	Click on the green **Edit** button. The **Employee/Company Information** screen appears.
  ![Imgur](http://i.imgur.com/3nSi2k8.png)
  5. Under the Employee/Company Information section, there are three additional options. Click on the **User Role** option. The User Roles drop-down appears.
  6.	Here you will have the option to set the user's access level or group level (they all represent the same level of permission that previously exists in our _older_ system). **Access Levels** range from Levels 1-5, with Level 5 being the lowest and Level 1 being the highest. **Group Levels Range** from 1-8 with 8 being the lowest and 1 being the highest.
  ![Imgur](http://img.prntscr.com/img?url=http://i.imgur.com/S2cICFF.png)
  7.	Click on the ratio box on the level or group that you want to assign to the requested user, and press the **Submit** button below for the option to take.
  ![Imgur](http://i.imgur.com/eaFICK9.png)
  Congratulations. You have now changed the Access Level of a User.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Hedwigia 62(3-4): 515 (1996)

#### Original name
Mamillisphaeria dimorphospora K.D. Hyde, S.W. Wong & E.B.G. Jones

### Remarks
null


text:
var Backbone = require('backbone');

module.exports = Backbone.View.extend({
  el: 'body',

  events: {
    'click #explain': function() {
      Backbone.history.navigate('explain', true);
    }
  },

  render: function() {
    this.$el.html('This is one router. It loads one set of files.

Clicking <button id="explain">here</button> will load another one.');
    return this;
  }
});


text:
usage()
{
  echo "usage: `basename $0` <osfamily>"
  echo ; echo "Supported osfamilies: redhat, suse, solaris10, solaris10x86"
}

#-----------------------------------------------
# Main
#-----------------------------------------------

osfamily=$1
[ -z $osfamily ] && (usage ; exit 1)

PATH="/bin:/usr/bin"
netbackup_clients=/usr/openv/netbackup/client
netbackup_bin=/usr/openv/netbackup/bin

nb_packages="SYMCnbclt:client_bin.tar.gz \
SYMCnbjre:JRE.tar.gz \
SYMCnbjava:NB-Java.tar.gz \
VRTSpbx:PBX.tar.gz \
SYMCpddea:pddeagent.tar.gz"

case $osfamily in
  redhat)
    package_type='rpm'
    client_dir="${netbackup_clients}/Linux/RedHat2.6.18"
    os='el'
  ;;
  suse)
    package_type='rpm'
    client_dir="${netbackup_clients}/Linux/SuSE2.6.16"
    os=$osfamily
  ;;
  solaris10)
    package_type='solaris'
    client_dir="${netbackup_clients}/Solaris/Solaris10"
    os=$osfamily
  ;;
  solaris10x86)
    package_type='solaris'
    client_dir="${netbackup_clients}/Solaris/Solaris_x86_10_64"
    os=$osfamily
    nb_packages="SYMCnbclt:client_bin.tar.gz \
SYMCnbjre:JRE.tar.gz \
SYMCnbjava:NB-Java.tar.gz \
VRTSpbx:PBX.tar.gz"
  ;;
  *)
  usage ; exit 1
  ;;
esac

destdir=`mktemp -d /tmp/nbclient.XXX`

for p in $nb_packages; do
  name=`echo $p | cut -f1 -d:`
  targz=`echo $p |cut -f2 -d:`

  echo "Extracting package ${name}"

  if [ ! -f "${client_dir}/${targz}" ]; then
    echo "ERROR: Could not find archive ${client_dir}/${targz}."
    continue
  fi

  cd $destdir
  tar xf "${client_dir}/${targz}"

  if [ $package_type = 'rpm' ]; then
    if [ $name = 'SYMCnbclt' ]; then
      nbclt_version=`rpm -qp --qf "%{VERSION}" ${destdir}/${name}*.rpm`
      nbclt_release=`rpm -qp --qf "%{RELEASE}" ${destdir}/${name}*.rpm`
      nbclt_arch=`rpm -qp --qf "%{ARCH}" ${destdir}/${name}*.rpm`
    fi
    package_name=`rpm -qp --qf "%{NAME}-%{VERSION}-%{RELEASE}.${os}.%{ARCH}.rpm" ${destdir}/${name}*.rpm`
    mv ${destdir}/${name}*.rpm ${destdir}/${package_name}

    # Build additional nbtar package
    nbtar_version=$nbclt_version
    nbtar_release=$nbclt_release
    nbtar_arch=$nbclt_arch
    echo "Building package nbtar"
    if [ -d $client_dir ]; then
      fpm -C $client_dir -s dir -t $package_type -n nbtar -p ${destdir}/nbtar-${nbtar_version}-${nbtar_release}.${os}.${nbtar_arch}.${package_type} -v $nbtar_version --iteration ${nbtar_release}.${os} -a ${nbtar_arch} --prefix $netbackup_bin --description "NetBackup GNU tar" --epoch $nbtar_release tar
    else
      echo "ERROR: Could not find client directory ${client_dir}"
    fi
  elif [ $package_type = 'solaris' ]; then
    echo "Creating solaris adminfile"
    cat >> ${destdir}/admin << EOF
mail=
instance=unique
partial=nocheck
runlevel=quit
idepend=quit
rdepend=nocheck
space=quit
setuid=nocheck
conflict=nocheck
action=nocheck
basedir=default
EOF
  fi
done

echo "Client packages written to ${destdir}"


text:
package java.util.zip;

import java.util.Calendar;

/**
 * This class represents a member of a zip archive.  ZipFile and
 * ZipInputStream will give you instances of this class as information
 * about the members in an archive.  On the other hand ZipOutputStream
 * needs an instance of this class to create a new member.
 *
 * @author Jochen Hoenicke
 */
public class ZipEntry implements ZipConstants, Cloneable
{
  private static final int KNOWN_SIZE   = 1;
  private static final int KNOWN_CSIZE  = 2;
  private static final int KNOWN_CRC    = 4;
  private static final int KNOWN_TIME   = 8;
  private static final int KNOWN_EXTRA  = 16;

  private static Calendar cal;

  private String name;
  private int size;
  private long compressedSize = -1;
  private int crc;
  private int dostime;
  private short known = 0;
  private short method = -1;
  private byte[] extra = null;
  private String comment = null;

  int flags;              /* used by ZipOutputStream */
  int offset;             /* used by ZipFile and ZipOutputStream */

  /**
   * Compression method.  This method doesn't compress at all.
   */
  public static final int STORED = 0;
  /**
   * Compression method.  This method uses the Deflater.
   */
  public static final int DEFLATED = 8;

  /**
   * Creates a zip entry with the given name.
   * @param name the name. May include directory components separated
   * by '/'.
   *
   * @exception NullPointerException when name is null.
   * @exception IllegalArgumentException when name is bigger then 65535 chars.
   */
  public ZipEntry(String name)
  {
    int length = name.length();
    if (length > 65535)
      throw new IllegalArgumentException("name length is " + length);
    this.name = name;
  }

  /**
   * Creates a copy of the given zip entry.
   * @param e the entry to copy.
   */
  public ZipEntry(ZipEntry e)
  {
    this(e, e.name);
  }

  ZipEntry(ZipEntry e, String name)
  {
    this.name = name;
    known = e.known;
    size = e.size;
    compressedSize = e.compressedSize;
    crc = e.crc;
    dostime = e.dostime;
    method = e.method;
    extra = e.extra;
    comment = e.comment;
  }

  final void setDOSTime(int dostime)
  {
    this.dostime = dostime;
    known |= KNOWN_TIME;
  }

  final int getDOSTime()
  {
    if ((known & KNOWN_TIME) == 0)
      return 0;
    else
      return dostime;
  }

  /**
   * Creates a copy of this zip entry.
   */
  /**
   * Clones the entry.
   */
  public Object clone()
  {
    try
      {
	// The JCL says that the `extra' field is also copied.
	ZipEntry clone = (ZipEntry) super.clone();
	if (extra != null)
	  clone.extra = (byte[]) extra.clone();
	return clone;
      }
    catch (CloneNotSupportedException ex)
      {
	throw new InternalError();
      }
  }

  /**
   * Returns the entry name.  The path components in the entry are
   * always separated by slashes ('/').
   */
  public String getName()
  {
    return name;
  }

  /**
   * Sets the time of last modification of the entry.
   * @time the time of last modification of the entry.
   */
  public void setTime(long time)
  {
    Calendar cal = getCalendar();
    synchronized (cal)
      {
	cal.setTimeInMillis(time);
	dostime = (cal.get(Calendar.YEAR) - 1980 & 0x7f) << 25
	  | (cal.get(Calendar.MONTH) + 1) << 21
	  | (cal.get(Calendar.DAY_OF_MONTH)) << 16
	  | (cal.get(Calendar.HOUR_OF_DAY)) << 11
	  | (cal.get(Calendar.MINUTE)) << 5
	  | (cal.get(Calendar.SECOND)) >> 1;
      }
    this.known |= KNOWN_TIME;
  }

  /**
   * Gets the time of last modification of the entry.
   * @return the time of last modification of the entry, or -1 if unknown.
   */
  public long getTime()
  {
    // The extra bytes might contain the time (posix/unix extension)
    parseExtra();

    if ((known & KNOWN_TIME) == 0)
      return -1;

    int sec = 2 * (dostime & 0x1f);
    int min = (dostime >> 5) & 0x3f;
    int hrs = (dostime >> 11) & 0x1f;
    int day = (dostime >> 16) & 0x1f;
    int mon = ((dostime >> 21) & 0xf) - 1;
    int year = ((dostime >> 25) & 0x7f) + 1980; /* since 1900 */

    try
      {
	cal = getCalendar();
	synchronized (cal)
	  {
	    cal.set(year, mon, day, hrs, min, sec);
	    return cal.getTimeInMillis();
	  }
      }
    catch (RuntimeException ex)
      {
	/* Ignore illegal time stamp */
	known &= ~KNOWN_TIME;
	return -1;
      }
  }

  private static synchronized Calendar getCalendar()
  {
    if (cal == null)
      cal = Calendar.getInstance();

    return cal;
  }

  /**
   * Sets the size of the uncompressed data.
   * @exception IllegalArgumentException if size is not in 0..0xffffffffL
   */
  public void setSize(long size)
  {
    if ((size & 0xffffffff00000000L) != 0)
	throw new IllegalArgumentException();
    this.size = (int) size;
    this.known |= KNOWN_SIZE;
  }

  /**
   * Gets the size of the uncompressed data.
   * @return the size or -1 if unknown.
   */
  public long getSize()
  {
    return (known & KNOWN_SIZE) != 0 ? size & 0xffffffffL : -1L;
  }

  /**
   * Sets the size of the compressed data.
   */
  public void setCompressedSize(long csize)
  {
    this.compressedSize = csize;
  }

  /**
   * Gets the size of the compressed data.
   * @return the size or -1 if unknown.
   */
  public long getCompressedSize()
  {
    return compressedSize;
  }

  /**
   * Sets the crc of the uncompressed data.
   * @exception IllegalArgumentException if crc is not in 0..0xffffffffL
   */
  public void setCrc(long crc)
  {
    if ((crc & 0xffffffff00000000L) != 0)
	throw new IllegalArgumentException();
    this.crc = (int) crc;
    this.known |= KNOWN_CRC;
  }

  /**
   * Gets the crc of the uncompressed data.
   * @return the crc or -1 if unknown.
   */
  public long getCrc()
  {
    return (known & KNOWN_CRC) != 0 ? crc & 0xffffffffL : -1L;
  }

  /**
   * Sets the compression method.  Only DEFLATED and STORED are
   * supported.
   * @exception IllegalArgumentException if method is not supported.
   * @see ZipOutputStream#DEFLATED
   * @see ZipOutputStream#STORED
   */
  public void setMethod(int method)
  {
    if (method != ZipOutputStream.STORED
	&& method != ZipOutputStream.DEFLATED)
	throw new IllegalArgumentException();
    this.method = (short) method;
  }

  /**
   * Gets the compression method.
   * @return the compression method or -1 if unknown.
   */
  public int getMethod()
  {
    return method;
  }

  /**
   * Sets the extra data.
   * @exception IllegalArgumentException if extra is longer than 0xffff bytes.
   */
  public void setExtra(byte[] extra)
  {
    if (extra == null)
      {
	this.extra = null;
	return;
      }
    if (extra.length > 0xffff)
      throw new IllegalArgumentException();
    this.extra = extra;
  }

  private void parseExtra()
  {
    // Already parsed?
    if ((known & KNOWN_EXTRA) != 0)
      return;

    if (extra == null)
      {
	known |= KNOWN_EXTRA;
	return;
      }

    try
      {
	int pos = 0;
	while (pos < extra.length)
	  {
	    int sig = (extra[pos++] & 0xff)
	      | (extra[pos++] & 0xff) << 8;
	    int len = (extra[pos++] & 0xff)
	      | (extra[pos++] & 0xff) << 8;
	    if (sig == 0x5455)
	      {
		/* extended time stamp */
		int flags = extra[pos];
		if ((flags & 1) != 0)
		  {
		    long time = ((extra[pos+1] & 0xff)
			    | (extra[pos+2] & 0xff) << 8
			    | (extra[pos+3] & 0xff) << 16
			    | (extra[pos+4] & 0xff) << 24);
		    setTime(time);
		  }
	      }
	    pos += len;
	  }
      }
    catch (ArrayIndexOutOfBoundsException ex)
      {
	/* be lenient */
      }

    known |= KNOWN_EXTRA;
    return;
  }

  /**
   * Gets the extra data.
   * @return the extra data or null if not set.
   */
  public byte[] getExtra()
  {
    return extra;
  }

  /**
   * Sets the entry comment.
   * @exception IllegalArgumentException if comment is longer than 0xffff.
   */
  public void setComment(String comment)
  {
    if (comment != null && comment.length() > 0xffff)
      throw new IllegalArgumentException();
    this.comment = comment;
  }

  /**
   * Gets the comment.
   * @return the comment or null if not set.
   */
  public String getComment()
  {
    return comment;
  }

  /**
   * Gets true, if the entry is a directory.  This is solely
   * determined by the name, a trailing slash '/' marks a directory.
   */
  public boolean isDirectory()
  {
    int nlen = name.length();
    return nlen > 0 && name.charAt(nlen - 1) == '/';
  }

  /**
   * Gets the string representation of this ZipEntry.  This is just
   * the name as returned by getName().
   */
  public String toString()
  {
    return name;
  }

  /**
   * Gets the hashCode of this ZipEntry.  This is just the hashCode
   * of the name.  Note that the equals method isn't changed, though.
   */
  public int hashCode()
  {
    return name.hashCode();
  }
}


text:
package com.novicehacks.autobot.core.types;

/**
 * Executable is a simple abstraction for server, command mapping that will be
 * scheduled for execution.
 *
 * @author Sharath Chand Bhaskara for NoviceHacks
 * @see ExecutableManager
 */
public class Executable implements Comparable<Executable> {
	private String line;
	private String serverId;
	private String commandId;

	public Executable (String line) {
		this.line = line;
	}

	public String getServerId() {
		return this.serverId;
	}

	public void setServerId(String serverId) {
		this.serverId = serverId;
	}

	public String getCommandId() {
		return this.commandId;
	}

	public void setCommandId(String commandId) {
		this.commandId = commandId;
	}

	public String getLine() {
		return this.line;
	}

	@Override
	public String toString() {
		return this.line;
	}

	@Override
	public int compareTo(Executable o) {
		return o.getLine ().compareTo (getLine ());
	}

	@Override
	public boolean equals(Object object) {
		if (object instanceof Executable) {
			Executable temp = (Executable) object;
			if (temp.getLine ().equals (getLine ())) {
				return true;
			}
		}
		return false;
	}

	@Override
	public int hashCode() {
		return super.hashCode ();
	}
}


text:
using System;
using MathNet.Numerics.Properties;

namespace MathNet.Numerics
{
    /// <summary>
    /// An algorithm failed to converge.
    /// </summary>
    [Serializable]
    public class NonConvergenceException : Exception
    {
        public NonConvergenceException() : base(Resources.ConvergenceFailed)
        {
        }

        public NonConvergenceException(string message) : base(message)
        {
        }

        public NonConvergenceException(string message, Exception innerException) : base(message, innerException)
        {
        }
#if !PORTABLE
        protected NonConvergenceException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
            : base(info, context)
        {
        }
#endif
    }

    /// <summary>
    /// An algorithm failed to converge due to a numerical breakdown.
    /// </summary>
    [Serializable]
    public class NumericalBreakdownException : NonConvergenceException
    {
        public NumericalBreakdownException()
            : base(Resources.NumericalBreakdown)
        {
        }

        public NumericalBreakdownException(string message)
            : base(message)
        {
        }

        public NumericalBreakdownException(string message, Exception innerException)
            : base(message, innerException)
        {
        }
#if !PORTABLE
        protected NumericalBreakdownException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
            : base(info, context)
        {
        }
#endif
    }

    /// <summary>
    /// An error occured calling native provider function.
    /// </summary>
    [Serializable]
    public abstract class NativeInterfaceException : Exception
    {
        protected NativeInterfaceException()
        {
        }

        protected NativeInterfaceException(string message)
            : base(message)
        {
        }

        protected NativeInterfaceException(string message, Exception innerException)
            : base(message, innerException)
        {
        }
#if !PORTABLE
        protected NativeInterfaceException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
            : base(info, context)
        {
        }
#endif
    }

    /// <summary>
    /// An error occured calling native provider function.
    /// </summary>
    [Serializable]
    public class InvalidParameterException : NativeInterfaceException
    {
        public InvalidParameterException()
            : base(Resources.InvalidParameter)
        {
        }

        public InvalidParameterException(int parameter)
            : base(string.Format(Resources.InvalidParameterWithNumber, parameter))
        {
        }

        public InvalidParameterException(int parameter, Exception innerException)
            : base(string.Format(Resources.InvalidParameterWithNumber, parameter), innerException)
        {
        }
#if !PORTABLE
        protected InvalidParameterException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
            : base(info, context)
        {
        }
#endif
    }

    /// <summary>
    /// Native provider was unable to allocate sufficent memory.
    /// </summary>
    [Serializable]
    public class MemoryAllocationException : NativeInterfaceException
    {
        public MemoryAllocationException()
            : base(Resources.MemoryAllocation)
        {
        }

        public MemoryAllocationException(Exception innerException)
            : base(Resources.MemoryAllocation, innerException)
        {
        }
#if !PORTABLE
        protected MemoryAllocationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
            : base(info, context)
        {
        }
#endif
    }

    /// <summary>
    /// Native provider failed LU inversion do to a singular U matrix.
    /// </summary>
    [Serializable]
    public class SingularUMatrixException : NativeInterfaceException
    {
        public SingularUMatrixException()
            : base(Resources.SingularUMatrix)
        {
        }

        public SingularUMatrixException(int element)
            : base(string.Format(Resources.SingularUMatrixWithElement, element))
        {
        }

        public SingularUMatrixException(int element, Exception innerException)
            : base(string.Format(Resources.SingularUMatrixWithElement, element), innerException)
        {
        }
#if !PORTABLE
        protected SingularUMatrixException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
            : base(info, context)
        {
        }
#endif
    }
}


text:
# Contributing to TradeOfferManager

Thanks for your interest in making `TradeOfferManager` better! I'd appreciate it if you read over this document quickly
before you submit your issue or pull request. It'll make things go much smoother.

# Issues

Submitting an issue?

- If you're **reporting a bug**, please include all relevant details.
	- A descriptive title helps for one. Titles of just "Error" or "It doesn't work" really don't help.
	- Please describe what you're trying to do, what actually happens, and what you can do to reproduce the problem.
	- If you have an error message or a crash, please include the full text of the error message and the stack trace.
	- Include the relevant snippet of your code. Wrap it in \`\`\`js /* code */ \`\`\` and GitHub [will format it nicely for you](https://help.github.com/articles/github-flavored-markdown/#syntax-highlighting).
- If you're **requesting a feature**, please be descriptive and understanding.
	- A good title makes a difference. Please briefly describe what you're requesting in the title.
	- Be descriptive in the issue body, too. Say what you want to do, and ideally what the method should be named.
	- Be understanding if I don't think that your feature request falls within the scope of this module.
- If you're **asking a question** or **requesting support**, please don't submit a GitHub issue.
	- Issues are only for problems directly relating to the module's code.
	- Please [post a thread in the Steam group](https://steamcommunity.com/groups/SteamRE/discussions/3/) instead.

# Pull Requests

Submitting a pull request? Great! Thanks for contributing your time and code! Please keep the following in mind.

- Please follow the existing code style.
	- Tabs for indentation
	- camelCase for variables and functions
	- Opening braces on the same line as the if/for/while statement
	- etc.
- Please avoid breaking changes. If you make a breaking change that can be done in a backwards-compatible manner, I won't accept it.
- Please don't increment the version number in `package.json`. I'll do that myself when I publish it to npm.
- Please include a brief description of your change in the pull request if it's not immediately apparent from the code.
- Be understanding if I don't think that your change falls within the scope of this module.


text:
import gettext
import os
import sys

import config
import db
import listener

from ovirt_engine import configfile
from ovirt_engine import service

_ = lambda m: gettext.dgettext(message=m, domain="ovirt-fence-kdump-listener")

class Daemon(service.Daemon):

    def __init__(self):
        super(Daemon, self).__init__()
        self._defaults = os.path.abspath(
            os.path.join(
                os.path.dirname(sys.argv[0]),
                'ovirt-fence-kdump-listener.conf',
            )
        )
        self._engineDefaults = os.path.abspath(
            os.path.join(
                os.path.dirname(sys.argv[0]),
                'ovirt-engine.conf',
            )
        )

    def _checkInstallation(
        self,
        pidfile,
    ):
        if pidfile is not None:
            self.check(
                name=pidfile,
                writable=True,
                mustExist=False,
            )

    def daemonSetup(self):

        if not os.path.exists(self._defaults):
            raise RuntimeError(
                _(
                    "The configuration defaults file '{file}' "
                    "required but missing"
                ).format(
                    file=self._defaults,
                )
            )

        self._config = configfile.ConfigFile(
            (
                self._defaults,
                config.ENGINE_FKLSNR_VARS,
            ),
        )

        self._engineConfig = configfile.ConfigFile(
            (
                self._engineDefaults,
                config.ENGINE_VARS,
            ),
        )

        self._checkInstallation(
            pidfile=self.pidfile,
        )

    def daemonStdHandles(self):
        consoleLog = open(os.devnull, "w+")
        return (consoleLog, consoleLog)

    def daemonContext(self):
        with db.DbManager(
                host=self._engineConfig.get('ENGINE_DB_HOST'),
                port=self._engineConfig.get('ENGINE_DB_PORT'),
                database=self._engineConfig.get('ENGINE_DB_DATABASE'),
                username=self._engineConfig.get('ENGINE_DB_USER'),
                password=self._engineConfig.get('ENGINE_DB_PASSWORD'),
                secured=self._engineConfig.getboolean('ENGINE_DB_SECURED'),
                secure_validation=self._engineConfig.getboolean(
                    'ENGINE_DB_SECURED_VALIDATION'
                ),
        ) as db_manager:

            with listener.FenceKdumpListener(
                    bind=(
                        self._config.get('LISTENER_ADDRESS'),
                        self._config.getinteger('LISTENER_PORT')
                    ),
                    db_manager=db_manager,
                    heartbeat_interval=(
                        self._config.getinteger('HEARTBEAT_INTERVAL')
                    ),
                    session_sync_interval=(
                        self._config.getinteger('SESSION_SYNC_INTERVAL')
                    ),
                    reopen_db_connection_interval=(
                        self._config.getinteger(
                            'REOPEN_DB_CONNECTION_INTERVAL'
                        )
                    ),
                    session_expiration_time=(
                        self._config.getinteger('KDUMP_FINISHED_TIMEOUT')
                    ),
            ) as server:
                server.run()

if __name__ == "__main__":
    service.setupLogger()
    d = Daemon()
    d.run()

# vim: expandtab tabstop=4 shiftwidth=4